Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(settings): 新增「用量历史」tab,统计 Cindy 内的 token 消耗 (#3252)
AwakeyDonkey83af0fc89e4b
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsxindex ce6145e836..c9eb7b9eb8 100644--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx@@ -66,6 +66,7 @@ import { useApiKey } from '@/hooks/useApiKey';import { useConnectedSource } from '@/hooks/useConnectedSource';import { useGatewayModelPricing, useReferenceModelPricing } from '@/hooks/useModelPricing';import { useProviders } from '@/hooks/useProviders';+import { providerDisplayName as sharedProviderDisplayName } from '@/lib/providerDisplayName';import {evictDeviceProviders,prefetchDeviceProviders,@@ -173,14 +174,6 @@ export interface ModelMemoryAccessors {clearFast?: (agent: AgentKind, providerId: string, modelId: string) => void;}-// 供应商完整展示名:三个内置 id 复用设置页 i18n 标题(settings.providers.<id>.title),-// 自定义供应商回退目录里的 provider.name。用于模型信息面板的来源说明。-const PROVIDER_TITLE_KEY: Record<string, string> = {- anthropic: 'settings.providers.anthropic.title',- openai: 'settings.providers.openai.title',- xd: 'settings.providers.xd.title',-};-// 配置面板锚在主菜单内缩 8px 的模型行上;补偿这段内缩,让两块面板贴边但不重叠。const MODEL_OPTIONS_SIDE_OFFSET = 8;const MODEL_OPTIONS_COLLISION_PADDING = 8;@@ -318,8 +311,7 @@ function ModelOptionsFloatingPanel({}function providerDisplayName(p: ProviderView, t: (key: string) => string): string {- const key = PROVIDER_TITLE_KEY[p.id];- return key ? t(key) : p.name;+ return sharedProviderDisplayName(p, t);}// 来源供应商 → 单色官方 mark(fill=currentColor)。trigger 默认右间距 + trigger 文字色;diff --git a/apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx b/apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsxindex 957d27512e..ced17bc05b 100644--- a/apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx+++ b/apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx@@ -4,6 +4,9 @@* 数据: useUsageHistory 的 days (稀疏, 无消费日无行) + todayKey 锚点。* 日期推算一律从 todayKey 出发 (renderer 不自己取系统日期, 与 main 同口径)。*+ * 强度口径由 `metric` 决定: 'money' (默认, 首页仪表盘) 或 'tokens' (设置 → 用量历史,+ * 那个页面不出现任何金额, 见 issue #2785)。两种口径共用同一套分位分桶与色阶。+ ** 视觉: 7 行 (周日起) × ~20 列周网格, 单色阶 — 非零值按 4 分位分桶,* 用 color-mix 在 --accent-emphasis 上做透明度阶梯 (黑白反色设计, 不引入彩色)。* 140 个格子用原生 title 做 tooltip (Radix per-cell 实例太重)。@@ -59,17 +62,22 @@ export function UsageHeatmap({days,todayKey,windowDays,+ metric = 'money',}: {days: Array<{ day: string; money: RegionalMoney; tokens?: number }>;todayKey: string;windowDays: number;+ /** 格子深浅按哪一维分桶。'tokens' 下 tooltip 也只显示 token, 不出现金额。 */+ metric?: 'money' | 'tokens';}): React.JSX.Element {const { t, i18n } = useTranslation();const { columns, monthLabels } = useMemo(() => {const spendByDay = new Map(days.map((d) => [d.day, d.money]));const tokensByDay = new Map(days.map((d) => [d.day, d.tokens ?? 0]));- const nonZero = days.map((d) => d.money.amount).filter((v) => v > 0).sort((a, b) => a - b);+ const intensityOf = (row: { money: RegionalMoney; tokens?: number }): number =>+ metric === 'tokens' ? (row.tokens ?? 0) : row.money.amount;+ const nonZero = days.map(intensityOf).filter((v) => v > 0).sort((a, b) => a - b);const q = (p: number): number => (nonZero.length ? nonZero[Math.min(nonZero.length - 1, Math.floor(p * nonZero.length))] : 0);const thresholds: [number, number, number] = [q(0.25), q(0.5), q(0.75)];@@ -92,7 +100,7 @@ export function UsageHeatmap({day: key,money,tokens: tokensByDay.get(key) ?? 0,- level: levelFor(money.amount, thresholds),+ level: levelFor(intensityOf({ money, tokens: tokensByDay.get(key) ?? 0 }), thresholds),placeholder: false,});cursor.setDate(cursor.getDate() + 1);@@ -127,7 +135,7 @@ export function UsageHeatmap({});return { columns: cols, monthLabels: labels };- }, [days, todayKey, windowDays, i18n.language]);+ }, [days, todayKey, windowDays, i18n.language, metric]);const colPitch = CELL_PX + GAP_PX;@@ -155,11 +163,21 @@ export function UsageHeatmap({) : (<divkey={ri}- title={`${cell.day} · ${formatMoney(cell.money)}${- cell.tokens > 0- ? ` · ${t('usageDashboard.tokensOnly', { tokens: formatCompactTokens(cell.tokens) })}`- : ''- }`}+ title={+ metric === 'tokens'+ ? `${cell.day} · ${+ cell.tokens > 0+ ? t('usageDashboard.tokensOnly', {+ tokens: formatCompactTokens(cell.tokens),+ })+ : t('usageHistory.heatmap.emptyCell')+ }`+ : `${cell.day} · ${formatMoney(cell.money)}${+ cell.tokens > 0+ ? ` · ${t('usageDashboard.tokensOnly', { tokens: formatCompactTokens(cell.tokens) })}`+ : ''+ }`+ }className="rounded-[3px]"style={{width: CELL_PX,diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/usageHeatmapMetric.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/usageHeatmapMetric.test.tsxnew file mode 100644index 0000000000..5101e71e39--- /dev/null+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/usageHeatmapMetric.test.tsx@@ -0,0 +1,73 @@+// @vitest-environment jsdom+import { render } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { UsageHeatmap } from '../UsageHeatmap';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, vars?: Record<string, unknown>) =>+ key === 'usageDashboard.tokensOnly' ? `${String(vars?.tokens)} tokens` : key,+ i18n: { language: 'en' },+ }),+}));++const money = (amount: number) => ({+ amount,+ currency: 'USD' as const,+ approximate: false,+ kind: 'actual-cost' as const,+});++/** 金额与 token 故意反向: 金额最大的那天 token 最少, 两种 metric 必须给出不同的深浅。 */+const days = [+ { day: '2026-08-20', money: money(100), tokens: 1_000 },+ { day: '2026-08-21', money: money(10), tokens: 100_000 },+ { day: '2026-08-22', money: money(1), tokens: 900_000 },+];++function cellStyles(container: HTMLElement): string[] {+ return [...container.querySelectorAll<HTMLElement>('div.rounded-\\[3px\\]')].map(+ (cell) => cell.style.backgroundColor,+ );+}++function cellTitles(container: HTMLElement): string[] {+ return [...container.querySelectorAll<HTMLElement>('div.rounded-\\[3px\\]')]+ .map((cell) => cell.title)+ .filter(Boolean);+}++describe('UsageHeatmap metric', () => {+ it('分桶取值随 metric 切换 (金额口径与 token 口径给出不同深浅)', () => {+ const asMoney = render(+ <UsageHeatmap days={days} todayKey="2026-08-22" windowDays={7} />,+ );+ const moneyStyles = cellStyles(asMoney.container);+ asMoney.unmount();++ const asTokens = render(+ <UsageHeatmap days={days} todayKey="2026-08-22" windowDays={7} metric="tokens" />,+ );+ const tokenStyles = cellStyles(asTokens.container);++ expect(moneyStyles.length).toBe(tokenStyles.length);+ expect(moneyStyles).not.toEqual(tokenStyles);+ });++ it('token 口径的 tooltip 不出现金额', () => {+ const { container } = render(+ <UsageHeatmap days={days} todayKey="2026-08-22" windowDays={7} metric="tokens" />,+ );+ const titles = cellTitles(container);+ expect(titles.some((title) => title.includes('tokens'))).toBe(true);+ expect(titles.some((title) => title.includes('$'))).toBe(false);+ });++ it('默认仍是金额口径 (首页仪表盘行为不变)', () => {+ const { container } = render(+ <UsageHeatmap days={days} todayKey="2026-08-22" windowDays={7} />,+ );+ expect(cellTitles(container).some((title) => title.includes('$'))).toBe(true);+ });+});diff --git a/apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx b/apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsxindex 81f568ee4a..6ef149dc5e 100644--- a/apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx+++ b/apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';import type { LucideProps } from 'lucide-react';import {Boxes,+ ChartColumn,CircleDollarSign,CircleHelp,FileUp,@@ -59,6 +60,7 @@ type SettingsNavIcon = ComponentType<LucideProps>;const TAB_ICON: Record<VisibleSettingsTab, SettingsNavIcon> = {general: Settings2,billing: CircleDollarSign,+ usage: ChartColumn,personalization: Sparkles,providers: Boxes,'voice-input': Mic,diff --git a/apps/desktop/src/renderer/components/settings/SettingsView.tsx b/apps/desktop/src/renderer/components/settings/SettingsView.tsxindex fbab243940..8592e45738 100644--- a/apps/desktop/src/renderer/components/settings/SettingsView.tsx+++ b/apps/desktop/src/renderer/components/settings/SettingsView.tsx@@ -49,6 +49,8 @@ import { SettingsCatalogPanel } from './SettingsCatalogPanel';import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkingDir';import { BillingSettingsSection } from '@/features/billing/BillingPage';import { canAccessBillingSettings } from './billingVisibility';+import { canAccessUsageSettings } from './usageVisibility';+import { UsageHistorySection } from './usage/UsageHistorySection';const DEFAULT_SETTINGS_MENU_WIDTH = 260;@@ -76,6 +78,9 @@ export function SettingsView() {membershipKind: user?.membershipKind ?? null,});const shouldRedirectLegacyPluginTabs = rawTab === 'api-keys' || rawTab === 'connections';+ // 用量历史对所有**已登录**身份开放 (local / cloud personal / cloud org),+ // 与 billing 的 canAccessBillingSettings 无关 —— #2785 维护者裁决。+ const canAccessUsage = canAccessUsageSettings({ mode });const activeTab = useMemo<SettingsTab>(() => {const raw = rawTab;@@ -86,9 +91,10 @@ export function SettingsView() {// legacy 别名:旧独立「Tina」(tina) 已并入「IM 机器人」(im-bot)。if (raw === 'tina') return 'im-bot';if (raw === 'billing' && !canAccessBilling) return 'general';+ if (raw === 'usage' && !canAccessUsage) return 'general';if (raw === 'agent-island' && !isMac) return 'general';return isSettingsTab(raw) ? raw : 'general';- }, [canAccessBilling, isMac, rawTab]);+ }, [canAccessBilling, canAccessUsage, isMac, rawTab]);const piExtensionsPanelOpen =activeTab === 'general' &&(rawTab === 'pi-extensions' || searchParams.get('openPanel') === 'pi-extensions');@@ -174,9 +180,12 @@ export function SettingsView() {const visibleTabIds = useMemo(() =>TAB_IDS.filter(- (tabId) => (isMac || tabId !== 'agent-island') && (canAccessBilling || tabId !== 'billing'),+ (tabId) =>+ (isMac || tabId !== 'agent-island') &&+ (canAccessBilling || tabId !== 'billing') &&+ (canAccessUsage || tabId !== 'usage'),),- [canAccessBilling, isMac],+ [canAccessBilling, canAccessUsage, isMac],);// deep-link: ?section=... → scroll to a section inside the active tab.@@ -406,6 +415,14 @@ export function SettingsView() {</div>)}+ {activeTab === 'usage' && (+ <div role="tabpanel" id="settings-panel-usage" aria-labelledby="settings-tab-usage">+ <section aria-label={t('settings.tabs.usage')}>+ <UsageHistorySection />+ </section>+ </div>+ )}+{activeTab === 'personalization' && (<divrole="tabpanel"diff --git a/apps/desktop/src/renderer/components/settings/__tests__/usageVisibility.test.ts b/apps/desktop/src/renderer/components/settings/__tests__/usageVisibility.test.tsnew file mode 100644index 0000000000..c25325f571--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/__tests__/usageVisibility.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';++import { canAccessUsageSettings } from '../usageVisibility';+import { canAccessBillingSettings } from '../billingVisibility';++describe('usageVisibility', () => {+ it('allows every signed-in identity, unlike billing', () => {+ expect(canAccessUsageSettings({ mode: 'local' })).toBe(true);+ expect(canAccessUsageSettings({ mode: 'cloud' })).toBe(true);+ expect(canAccessUsageSettings({ mode: 'signed-out' })).toBe(false);+ });++ it('does not inherit the billing tab identity gate', () => {+ // cloud + org 看不到计费页, 但必须能看到用量历史 —— 它读的是本机用量, 与账单无关。+ expect(canAccessBillingSettings({ mode: 'cloud', membershipKind: 'org' })).toBe(false);+ expect(canAccessUsageSettings({ mode: 'cloud' })).toBe(true);++ // local 同理。+ expect(canAccessBillingSettings({ mode: 'local', membershipKind: null })).toBe(false);+ expect(canAccessUsageSettings({ mode: 'local' })).toBe(true);+ });+});diff --git a/apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx b/apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsxnew file mode 100644index 0000000000..583abc597e--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx@@ -0,0 +1,171 @@+/**+ * UsageBreakdownTables — 用量历史页的两张明细表: 按 agent / harness 与按模型。+ *+ * 两张表共用同一套表格样式与 rank 配色 (usagePalette), 因此放在同一个文件里,+ * 避免为了共享 5 行 class 再拆一层。+ *+ * 缓存命中率与 shared/turnUsageDetails.ts 的逐轮口径一致 (见 usageHistoryStats.cacheHitRate),+ * 但**不着色**: DESIGN.md §2 的 --warning-accent 是 sanctioned-consumers-only, 用量页的+ * 效率指标不在名单内。要给"偏低"一个视觉信号, 得先在规范里登记这个消费者。+ */++import React from 'react';+import { useTranslation } from 'react-i18next';++import { cn } from '@/lib/utils';+import { formatCompactTokens, formatModelShort } from '@/lib/usageFormat';+import { usageRankColor } from '@/components/new-chat/usagePalette';+import {+ type AgentTokenRow,+ type ModelTokenRow,+ type UsageAgentKind,+} from './usageHistoryStats';+import { formatUsagePercent } from './formatUsagePercent';++const UNKNOWN_VALUE = '—';+/** 与 usagePalette 的 rank 阶梯对齐: 让同一 agent 在两张表与柱图里颜色一致。 */+const AGENT_RANK: Record<UsageAgentKind, number> = {+ 'claude-code': 0,+ codex: 1,+ pi: 2,+};++const TH_CLASS =+ 'whitespace-nowrap border-b border-[var(--border-default)] pb-2 text-right text-11 font-medium text-[var(--text-tertiary)]';+const TD_CLASS =+ 'whitespace-nowrap border-b border-[var(--border-default)] py-2 text-right text-12 tabular-nums';++function Swatch({ rank }: { rank: number }): React.JSX.Element {+ return (+ <span+ className="size-2 shrink-0 rounded-[2px]"+ style={{ backgroundColor: usageRankColor(rank) }}+ />+ );+}++function HitRateCell({ value }: { value: number | null }): React.JSX.Element {+ return (+ <td className={TD_CLASS}>{value === null ? UNKNOWN_VALUE : formatUsagePercent(value)}</td>+ );+}++function ShareCell({ share, rank }: { share: number; rank: number }): React.JSX.Element {+ return (+ <td className={cn(TD_CLASS, 'text-[var(--text-tertiary)]')}>+ <span+ className="mr-1.5 inline-block h-1 rounded-[2px] align-[2px]"+ style={{ width: `${Math.max(2, share * 46)}px`, backgroundColor: usageRankColor(rank) }}+ />+ {formatUsagePercent(share)}+ </td>+ );+}++export function UsageAgentTable({ rows }: { rows: AgentTokenRow[] }): React.JSX.Element {+ const { t } = useTranslation();+ const total = rows.reduce((sum, row) => sum + row.tokens, 0);++ return (+ <div>+ {/* 占比条: 让"谁占大头"在读表之前就成立。+ 8px + 2px 圆角 = DESIGN.md §5 登记的「非交互 ≤8px 状态微格」豁免档。 */}+ <div className="mb-3 flex h-2 overflow-hidden rounded-[2px]">+ {rows.map((row) => (+ <div+ key={row.agentKind}+ title={`${row.agentKind} · ${t('usageDashboard.tokensOnly', {+ tokens: formatCompactTokens(row.tokens),+ })}`}+ style={{+ width: `${total > 0 ? (row.tokens / total) * 100 : 0}%`,+ backgroundColor: usageRankColor(AGENT_RANK[row.agentKind] ?? 3),+ }}+ />+ ))}+ </div>+ <table className="w-full border-collapse">+ <thead>+ <tr>+ <th className={cn(TH_CLASS, 'text-left')}>{t('usageHistory.byAgent.col.agent')}</th>+ <th className={TH_CLASS}>{t('usageHistory.byAgent.col.total')}</th>+ <th className={TH_CLASS}>{t('usageHistory.byAgent.col.share')}</th>+ <th className={TH_CLASS}>{t('usageHistory.byAgent.col.today')}</th>+ <th className={TH_CLASS} title={t('usageHistory.cacheHitTooltip')}>+ {t('usageHistory.byAgent.col.hitRate')}+ </th>+ <th className={TH_CLASS}>{t('usageHistory.byAgent.col.models')}</th>+ </tr>+ </thead>+ <tbody>+ {rows.map((row) => {+ const rank = AGENT_RANK[row.agentKind] ?? 3;+ return (+ <tr key={row.agentKind}>+ <td className={cn(TD_CLASS, 'text-left')}>+ <span className="flex min-w-0 items-center gap-2">+ <Swatch rank={rank} />+ <span className="truncate">{row.agentKind}</span>+ </span>+ </td>+ <td className={TD_CLASS}>{formatCompactTokens(row.tokens)}</td>+ <ShareCell share={row.share} rank={rank} />+ <td className={cn(TD_CLASS, 'text-[var(--text-tertiary)]')}>+ {row.todayTokens > 0 ? formatCompactTokens(row.todayTokens) : UNKNOWN_VALUE}+ </td>+ <HitRateCell value={row.cacheHitRate} />+ <td className={cn(TD_CLASS, 'text-[var(--text-tertiary)]')}>{row.modelCount}</td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+}++export function UsageModelTable({ rows }: { rows: ModelTokenRow[] }): React.JSX.Element {+ const { t } = useTranslation();++ return (+ <table className="w-full border-collapse">+ <thead>+ <tr>+ <th className={cn(TH_CLASS, 'text-left')}>{t('usageHistory.byModel.col.model')}</th>+ <th className={TH_CLASS}>{t('usageHistory.byModel.col.total')}</th>+ <th className={TH_CLASS}>{t('usageHistory.byModel.col.share')}</th>+ <th className={TH_CLASS}>{t('usageHistory.byModel.col.input')}</th>+ <th className={TH_CLASS}>{t('usageHistory.byModel.col.output')}</th>+ <th className={TH_CLASS}>{t('usageHistory.byModel.col.cacheRead')}</th>+ <th className={TH_CLASS}>{t('usageHistory.byModel.col.cacheCreate')}</th>+ <th className={TH_CLASS} title={t('usageHistory.cacheHitTooltip')}>+ {t('usageHistory.byModel.col.hitRate')}+ </th>+ </tr>+ </thead>+ <tbody>+ {rows.map((row, index) => (+ <tr key={row.key}>+ <td className={cn(TD_CLASS, 'text-left')}>+ <span className="flex min-w-0 items-center gap-2">+ <Swatch rank={index} />+ <span className="truncate">{formatModelShort(row.model)}</span>+ {/* 同一模型 id 可能跨 agent 撞名, 标签让两行区分得开 */}+ <span className="shrink-0 rounded border border-[var(--border-default)] px-1 py-px text-10 leading-none text-[var(--text-tertiary)]">+ {row.agentKind}+ </span>+ </span>+ </td>+ <td className={TD_CLASS}>{formatCompactTokens(row.tokens)}</td>+ <ShareCell share={row.share} rank={index} />+ <td className={TD_CLASS}>{formatCompactTokens(row.inputTokens)}</td>+ <td className={TD_CLASS}>{formatCompactTokens(row.outputTokens)}</td>+ <td className={TD_CLASS}>{formatCompactTokens(row.cacheReadTokens)}</td>+ <td className={TD_CLASS}>{formatCompactTokens(row.cacheCreateTokens)}</td>+ <HitRateCell value={row.cacheHitRate} />+ </tr>+ ))}+ </tbody>+ </table>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx b/apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsxnew file mode 100644index 0000000000..264ca19a82--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx@@ -0,0 +1,166 @@+/**+ * UsageHistorySection — 设置 → 用量历史 (issue #2785)。+ *+ * 职责边界 (维护者裁决): Billing 管 Cindy AI 的账单与账户信息; 本页只统计+ * **本机 Cindy App 内产生的 token 消耗**, 不出现金额、账户额度、预算或限额窗口,+ * 也不纳入外部 Claude Code / Codex CLI / 网页版的用量 (那是 #2618)。+ *+ * 因此页面上每个数字都来自 useUsageHistory → maker:usage:history → 本地库,+ * 不读任何账号快照 —— local / cloud personal / cloud org 三种身份看到的是同一个页面。+ *+ * 两个窗口不同, 标题里分别写明:+ * - 热力图与连续活跃天数走 days[] (140 天 = 20 周)+ * - 按模型 / 按 agent / 每日柱图走 models[] 与 modelDaily (30 天)+ *+ * 首页的 HomeUsageDashboard 是金额口径的姊妹实现, 本页不复用它的外壳组件+ * (见 UsageTokenBars 的注释), 但共享同一条聚合链路与配色。+ */++import React, { useMemo } from 'react';+import { useTranslation } from 'react-i18next';+import { RefreshCw } from 'lucide-react';++import { Spinner } from '@/components/ui/spinner';+import { useAuth } from '@/contexts/AuthContext';+import { useUsageHistory } from '@/hooks/useUsageHistory';+import { UsageHeatmap } from '@/components/new-chat/UsageHeatmap';+import { USAGE_TOP_MODELS, usageModelKey } from '@/components/new-chat/usagePalette';+import { UsageStatRow } from './UsageStatRow';+import { UsageTokenBars } from './UsageTokenBars';+import { UsageAgentTable, UsageModelTable } from './UsageBreakdownTables';+import { UsageTaskTable, useTopTokenSessions } from './UsageTaskTable';+import {+ buildAgentRows,+ buildModelRows,+ buildSummary,+ isUsageHistoryEmpty,+} from './usageHistoryStats';++/** 与 useUsageHistory 的拉取窗口一致 (20 周)。 */+const HEATMAP_WINDOW_DAYS = 140;++function Card({+ title,+ subtitle,+ refreshing,+ children,+}: {+ title: string;+ subtitle?: string;+ refreshing?: boolean;+ children: React.ReactNode;+}): React.JSX.Element {+ const { t } = useTranslation();+ return (+ <div className="mb-3.5 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-4">+ <div className="mb-3 flex items-baseline gap-2">+ <span className="text-12 font-medium text-[var(--text-secondary)]">{title}</span>+ {subtitle ? (+ <span className="text-11 text-[var(--text-tertiary)]">{subtitle}</span>+ ) : null}+ {refreshing ? (+ <span className="ml-auto inline-flex items-center gap-1 text-10 font-normal leading-none text-[var(--text-tertiary)]">+ <Spinner icon={RefreshCw} size={10} className="opacity-70" />+ {t('usageDashboard.updating')}+ </span>+ ) : null}+ </div>+ {children}+ </div>+ );+}++export function UsageHistorySection(): React.JSX.Element {+ const { t } = useTranslation();+ const { user } = useAuth();+ const { history, refreshing } = useUsageHistory({ userId: user?.id });++ const summary = useMemo(() => buildSummary(history), [history]);+ const modelRows = useMemo(() => buildModelRows(history), [history]);+ const agentRows = useMemo(() => buildAgentRows(history), [history]);+ // 配色顺序必须来自 modelRows 而不是 history.models: 后者由 main 按**可比金额**降序排+ // (usageHistory.ts 的 comparable), 本页只讲 token —— 直接用它会让同一个模型在柱图与+ // 模型表里配到不同颜色, 还会让"金额高但 token 很少"的模型挤掉真正的 token 前 N 名。+ const colorOrder = useMemo(+ () => modelRows.slice(0, USAGE_TOP_MODELS).map((m) => usageModelKey(m.agentKind, m.model)),+ [modelRows],+ );++ // 任务行与用量聚合是两条数据源: 聚合里有 token, 本地任务却可能一条都没有+ // (用户删光了会话, 或列表还没加载完)。空时整张卡片不渲染, 不留空壳。+ const taskRows = useTopTokenSessions();+ const empty = isUsageHistoryEmpty(history);++ return (+ <div className="pb-2">+ <h2 className="mb-1.5 text-15 font-semibold text-[var(--text-primary)]">+ {t('settings.tabs.usage')}+ </h2>+ <p className="mb-4 max-w-[640px] text-12 leading-[1.7] text-[var(--text-tertiary)]">+ {t('usageHistory.description')}+ </p>++ {empty ? (+ <div className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-8 text-center text-12 text-[var(--text-tertiary)]">+ {t('usageHistory.empty')}+ </div>+ ) : (+ <>+ <Card title={t('usageHistory.summary.title')} refreshing={refreshing}>+ <UsageStatRow summary={summary} />+ </Card>++ <Card+ title={t('usageHistory.heatmap.title')}+ subtitle={t('usageHistory.heatmap.subtitle')}+ >+ <UsageHeatmap+ days={history?.days ?? []}+ todayKey={history?.todayKey ?? ''}+ windowDays={HEATMAP_WINDOW_DAYS}+ metric="tokens"+ />+ </Card>++ <Card+ title={t('usageHistory.daily.title')}+ subtitle={t('usageHistory.daily.subtitle')}+ >+ <UsageTokenBars+ modelDaily={history?.modelDaily ?? []}+ colorOrder={colorOrder}+ todayKey={history?.todayKey ?? ''}+ />+ </Card>++ {agentRows.length > 0 && (+ <Card+ title={t('usageHistory.byAgent.title')}+ subtitle={t('usageHistory.byAgent.subtitle')}+ >+ <UsageAgentTable rows={agentRows} />+ </Card>+ )}++ {modelRows.length > 0 && (+ <Card+ title={t('usageHistory.byModel.title')}+ subtitle={t('usageHistory.byModel.subtitle')}+ >+ <UsageModelTable rows={modelRows} />+ </Card>+ )}++ {taskRows.length > 0 && (+ <Card+ title={t('usageHistory.tasks.title')}+ subtitle={t('usageHistory.tasks.subtitle')}+ >+ <UsageTaskTable rows={taskRows} />+ </Card>+ )}+ </>+ )}+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx b/apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsxnew file mode 100644index 0000000000..2538ddfd03--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx@@ -0,0 +1,82 @@+/**+ * UsageStatRow — 用量历史页顶部统计条 (五格)。+ *+ * 未知值统一用 "—" 占位, 不显示误导性的 0 —— 与首页仪表盘同一处理。+ *+ * 缓存命中率**不着色**: DESIGN.md §2 把 --warning-accent 限定给已登记的消费者+ * (运行状态栏、呼吸图标、权限高亮等), 用量页的效率指标不在名单内, 新增消费者要先改规范。+ * 口径说明放表头 tooltip, 数值本身保持中性。+ */++import React from 'react';+import { useTranslation } from 'react-i18next';++import { Tip } from '@/components/ui/tooltip';+import { formatCompactTokens } from '@/lib/usageFormat';+import { type UsageSummary } from './usageHistoryStats';+import { formatUsagePercent } from './formatUsagePercent';++const UNKNOWN_VALUE = '—';++function StatCell({+ value,+ label,+ tip,+}: {+ value: string;+ label: string;+ tip?: string | null;+}): React.JSX.Element {+ const cell = (+ <div className="flex min-w-0 flex-1 flex-col gap-0.5 rounded-lg bg-[var(--surface-chip)] px-3 py-2">+ <span className="truncate text-14 font-semibold leading-[1.429] tabular-nums text-[var(--text-primary)]">+ {value}+ </span>+ <span className="truncate text-11 leading-[1.273] text-[var(--text-tertiary)]">{label}</span>+ </div>+ );+ return tip ? <Tip text={tip}>{cell}</Tip> : cell;+}++export function UsageStatRow({ summary }: { summary: UsageSummary }): React.JSX.Element {+ const { t } = useTranslation();++ return (+ <div className="flex gap-2">+ <StatCell+ value={+ summary.todayTokens > 0 ? formatCompactTokens(summary.todayTokens) : UNKNOWN_VALUE+ }+ label={t('usageHistory.stats.todayTokens')}+ />+ <StatCell+ value={+ summary.last30DaysTokens > 0+ ? formatCompactTokens(summary.last30DaysTokens)+ : UNKNOWN_VALUE+ }+ label={t('usageHistory.stats.totalTokens')}+ />+ <StatCell+ value={t('usageDashboard.streakValue', {+ current: summary.streak.current,+ longest: summary.streak.longest,+ })}+ label={t('usageHistory.stats.streak')}+ />+ <StatCell+ value={+ summary.cacheHitRate === null+ ? UNKNOWN_VALUE+ : formatUsagePercent(summary.cacheHitRate)+ }+ label={t('usageHistory.stats.cacheHitRate')}+ tip={t('usageHistory.cacheHitTooltip')}+ />+ <StatCell+ value={String(summary.modelCount)}+ label={t('usageHistory.stats.models')}+ />+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx b/apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsxnew file mode 100644index 0000000000..362281411b--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx@@ -0,0 +1,144 @@+/**+ * UsageTaskTable — 「最耗 token 的任务」。+ *+ * 数据来自会话列表 (useCCSessions → sessionsStore), 不新增 IPC:+ * - tokens: Session.totalTokenUsage+ * - 上下文: contextTokens / contextWindow+ * - 供应商: Session.providerId, 经 providerDisplayNameById 映射成展示名+ * (内置 id 走设置页 i18n 标题, 自定义供应商回退目录里的 name)+ * - 最后活跃: userSendAt / updatedAt 中较新者 (与 SessionItem 同一条时间轴 ——+ * 旧版 DB 行只写 userSendAt), 走 sidebar 同一套 formatSidebarTime+ *+ * 两处口径必须在 UI 上讲清楚, 否则会被误读:+ * 1. totalTokenUsage 是该任务的**生命周期累计**, 不是窗口内增量。本表筛的是+ * "近 30 天内活跃过的任务", 所以一个三个月前开始、昨天还在跑的任务会带着+ * 它的全部累计出现 —— 表头 tooltip 写明这一点。+ * 2. providerId 是会话**当前值**而非每轮事实, 且可为 null (跟随默认路由)。+ * null 留空 (照 SessionInfoMeta 既有的"无数据不显示"), 不臆造默认供应商;+ * 任务若中途切换过供应商, 早先的 token 也会归到当前这个上 —— 表头 tooltip+ * 写明"取当前选定的供应商", 不额外标记 (没有可靠的切换记录可依据)。+ *+ * 远程会话 (device-link) 的 token 字段可能缺失或为 0 —— 同样按"无数据不显示"过滤掉。+ *+ * 已知取舍: 候选集来自 sessionsStore 的列表桶 (DEFAULT_LIMIT = 1000, 按 updatedAt 降序),+ * 因此"近 30 天内更新过的会话超过 1000 条"时, 被截断的高用量会话进不了 Top N。+ * 修它需要一次按 total_token_usage 排序的专用查询 —— 那是新增 IPC, 不进本版。+ */++import React, { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { cn } from '@/lib/utils';+import { formatCompactTokens, formatModelShort } from '@/lib/usageFormat';+import { useCCSessions } from '@/hooks/useCCSessions';+import type { Session } from '@/lib/ccAgent.types';+import { formatSidebarTime } from '@/features/cc-agent/lib/formatSidebarTime';+import { useProviders } from '@/hooks/useProviders';+import { usageRankColor } from '@/components/new-chat/usagePalette';+import { providerDisplayNameById } from '@/lib/providerDisplayName';+import { formatUsagePercent } from './formatUsagePercent';++/** 展示条数 —— 与"最耗"的语义匹配, 不做成完整列表 (那是任务侧栏的事)。 */+const TOP_TASKS = 8;+/** 与本页其它区块一致的窗口。 */+const WINDOW_DAYS = 30;+const UNKNOWN_VALUE = '—';++const TH_CLASS =+ 'whitespace-nowrap border-b border-[var(--border-default)] pb-2 text-right text-11 font-medium text-[var(--text-tertiary)]';+const TD_CLASS =+ 'whitespace-nowrap border-b border-[var(--border-default)] py-2 text-right text-12 tabular-nums';++/** 与 SessionItem 一致: 取两者中较新的值, 兼容只写 userSendAt 的存量行。 */+function lastActiveIso(session: { updatedAt: string; userSendAt: string | null }): string {+ return session.userSendAt && session.userSendAt > session.updatedAt+ ? session.userSendAt+ : session.updatedAt;+}++function activeWithinWindow(iso: string | null | undefined, cutoffMs: number): boolean {+ if (!iso) return false;+ const ts = Date.parse(iso);+ return Number.isFinite(ts) && ts >= cutoffMs;+}++/**+ * 候选行 —— 单独暴露成 hook, 让调用方能在**渲染卡片之前**知道有没有行。+ * 组件内部返回 null 会留下一张只有标题、正文全空的卡片 (会话被删光 / 列表首次加载中)。+ */+export function useTopTokenSessions(): Session[] {+ // 归档的任务同样消耗过 token, 统计口径不该因为用户归档而变。+ const { sessions } = useCCSessions({ includeArchived: 'all' });++ return useMemo(() => {+ const cutoff = Date.now() - WINDOW_DAYS * 24 * 60 * 60 * 1000;+ return sessions+ .filter(+ (session) =>+ session.totalTokenUsage > 0 &&+ (activeWithinWindow(session.updatedAt, cutoff) ||+ activeWithinWindow(session.userSendAt, cutoff)),+ )+ .sort((a, b) => b.totalTokenUsage - a.totalTokenUsage)+ .slice(0, TOP_TASKS);+ }, [sessions]);+}++export function UsageTaskTable({ rows }: { rows: Session[] }): React.JSX.Element {+ const { t } = useTranslation();+ const { providers } = useProviders();++ return (+ <table className="w-full border-collapse">+ <thead>+ <tr>+ <th className={cn(TH_CLASS, 'text-left')}>{t('usageHistory.tasks.col.task')}</th>+ <th className={TH_CLASS}>{t('usageHistory.tasks.col.model')}</th>+ <th className={TH_CLASS} title={t('usageHistory.tasks.providerTooltip')}>+ {t('usageHistory.tasks.col.provider')}+ </th>+ <th className={TH_CLASS} title={t('usageHistory.tasks.tokensTooltip')}>+ {t('usageHistory.tasks.col.tokens')}+ </th>+ <th className={TH_CLASS}>{t('usageHistory.tasks.col.context')}</th>+ <th className={TH_CLASS}>{t('usageHistory.tasks.col.lastActive')}</th>+ </tr>+ </thead>+ <tbody>+ {rows.map((session, index) => {+ const providerName = session.providerId+ ? providerDisplayNameById(session.providerId, providers, t)+ : null;+ const contextRatio =+ session.contextWindow > 0 ? session.contextTokens / session.contextWindow : null;+ return (+ <tr key={session.id}>+ <td className={cn(TD_CLASS, 'text-left')}>+ <span className="flex min-w-0 items-center gap-2">+ <span+ className="size-2 shrink-0 rounded-[2px]"+ style={{ backgroundColor: usageRankColor(index) }}+ />+ <span className="truncate">{session.title}</span>+ </span>+ </td>+ <td className={cn(TD_CLASS, 'text-[var(--text-tertiary)]')}>+ {formatModelShort(session.model)}+ </td>+ <td className={cn(TD_CLASS, 'text-[var(--text-tertiary)]')}>+ {providerName ?? UNKNOWN_VALUE}+ </td>+ <td className={TD_CLASS}>{formatCompactTokens(session.totalTokenUsage)}</td>+ <td className={cn(TD_CLASS, 'text-[var(--text-tertiary)]')}>+ {contextRatio === null ? UNKNOWN_VALUE : formatUsagePercent(contextRatio)}+ </td>+ <td className={cn(TD_CLASS, 'text-[var(--text-tertiary)]')}>+ {formatSidebarTime(lastActiveIso(session), t) || UNKNOWN_VALUE}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx b/apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsxnew file mode 100644index 0000000000..9fb3d0d681--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx@@ -0,0 +1,180 @@+/**+ * UsageTokenBars — 近 30 天每日 token 堆叠柱状图 (设置 → 用量历史)。+ *+ * 与首页的 UsageDailyBars 是姊妹组件, 但**不是它的 token 分支**: 那个组件的币种选取、+ * api / 订阅估算分段、金额 tooltip 都是围绕金额长出来的, 塞进 metric 分支等于让一个+ * 组件同时维护两套逻辑。本页只统计 token (issue #2785), 分段规则简化成"按天 × rank 求和"。+ *+ * 从 UsageDailyBars 照搬的两处视觉规则 (不搬会比首页看板简陋):+ * - niceTicks(): max/4 取整到 1 / 2 / 2.5 / 5 / 10 档, 最多 3 条; Y 轴列固定 30px 宽,+ * 避免数字位数变化引起布局抖动+ * - 柱高 max(3, round(ratio × H)); 零值日固定 2px, 保留"那天有格子但没用量"的视觉+ *+ * 日期推算一律以 main 返回的 todayKey 为锚, renderer 不自己取系统日期。+ * 30 根柱子用原生 title 做 tooltip (Radix per-cell 实例太重, 同热力图取舍)。+ */++import React, { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { formatCompactTokens } from '@/lib/usageFormat';+import type { UsageHistoryModelDay } from '@/hooks/useUsageHistory';+import { usageModelKey, usageRankColor, usageRankOf } from '@/components/new-chat/usagePalette';++const WINDOW_DAYS = 30;+const CHART_HEIGHT_PX = 96;++interface DaySegment {+ rank: number;+ label: string;+ tokens: number;+}++interface DayBar {+ day: string;+ tokens: number;+ /** rank 升序 (rank 0 = 最大头模型, 渲染在柱子底部)。 */+ segments: DaySegment[];+}++function shiftDayKeyLocal(dayKey: string, deltaDays: number): string {+ const [y, m, d] = dayKey.split('-').map(Number);+ const date = new Date(y, (m ?? 1) - 1, (d ?? 1) + deltaDays);+ const mm = String(date.getMonth() + 1).padStart(2, '0');+ const dd = String(date.getDate()).padStart(2, '0');+ return `${date.getFullYear()}-${mm}-${dd}`;+}++/** 与 UsageDailyBars 同一套刻度算法, 保证两张图的刻度密度一致。 */+function niceTicks(max: number): number[] {+ if (!(max > 0)) return [];+ const rawStep = max / 4;+ const pow = Math.pow(10, Math.floor(Math.log10(rawStep)));+ const step = [1, 2, 2.5, 5, 10].map((m) => m * pow).find((s) => s >= rawStep) ?? 10 * pow;+ const ticks: number[] = [];+ for (let v = step; v <= max * 0.95 && ticks.length < 3; v += step) ticks.push(v);+ return ticks;+}++export function UsageTokenBars({+ modelDaily,+ colorOrder,+ todayKey,+}: {+ modelDaily: UsageHistoryModelDay[];+ /** 前 N 名模型 key (payload.models 排序), 决定分段与图例配色。 */+ colorOrder: string[];+ todayKey: string;+}): React.JSX.Element {+ const { t } = useTranslation();++ const bars = useMemo(() => {+ const segsByDay = new Map<string, Map<number, DaySegment>>();+ for (const row of modelDaily) {+ if (row.tokens <= 0) continue;+ const rank = usageRankOf(colorOrder, usageModelKey(row.agentKind, row.model));+ let daySegs = segsByDay.get(row.day);+ if (!daySegs) {+ daySegs = new Map();+ segsByDay.set(row.day, daySegs);+ }+ const seg = daySegs.get(rank);+ if (seg) {+ seg.tokens += row.tokens;+ // 尾部档 (rank === colorOrder.length) 会把所有非前 N 名模型并进同一分段,+ // 保留首个模型名会把合计错误地挂到它头上 —— 改标「其它」, 与图例同义。+ if (rank >= colorOrder.length) seg.label = t('usageDashboard.othersLegend');+ } else {+ daySegs.set(rank, {+ rank,+ label: rank >= colorOrder.length ? t('usageDashboard.othersLegend') : row.model,+ tokens: row.tokens,+ });+ }+ }++ const list: DayBar[] = [];+ for (let i = WINDOW_DAYS - 1; i >= 0; i--) {+ const day = shiftDayKeyLocal(todayKey, -i);+ const segments = [...(segsByDay.get(day)?.values() ?? [])].sort((a, b) => a.rank - b.rank);+ list.push({+ day,+ tokens: segments.reduce((sum, s) => sum + s.tokens, 0),+ segments,+ });+ }+ return { list, max: Math.max(...list.map((b) => b.tokens), 0) };+ }, [modelDaily, colorOrder, todayKey, t]);++ const ticks = niceTicks(bars.max);++ return (+ <div className="flex gap-1.5" style={{ height: CHART_HEIGHT_PX }}>+ {/* Y 轴 token 刻度 (有数据才显示; 宽度固定避免数字位数变化引起布局抖动) */}+ {ticks.length > 0 && (+ <div className="relative w-[30px] shrink-0">+ {ticks.map((v) => (+ <span+ key={v}+ className="absolute right-0 translate-y-1/2 text-10 leading-none tabular-nums text-[var(--text-tertiary)]"+ style={{ bottom: (v / bars.max) * CHART_HEIGHT_PX }}+ >+ {formatCompactTokens(v)}+ </span>+ ))}+ </div>+ )}+ <div className="relative min-w-0 flex-1">+ {/* 横向参考线 (柱子后面, 半透明) */}+ {ticks.map((v) => (+ <div+ key={v}+ className="absolute left-0 right-0 border-t border-[var(--border-default)] opacity-50"+ style={{ bottom: (v / bars.max) * CHART_HEIGHT_PX }}+ />+ ))}+ <div className="absolute inset-0 flex items-end gap-[3px]">+ {bars.list.map((b) => {+ const ratio = bars.max > 0 ? b.tokens / bars.max : 0;+ const height = b.tokens > 0 ? Math.max(3, Math.round(ratio * CHART_HEIGHT_PX)) : 2;+ const titleLines = [+ `${b.day} · ${+ b.tokens > 0+ ? t('usageDashboard.tokensOnly', { tokens: formatCompactTokens(b.tokens) })+ : t('usageHistory.heatmap.emptyCell')+ }`,+ ...b.segments.map(+ (s) =>+ `${s.label}: ${t('usageDashboard.tokensOnly', {+ tokens: formatCompactTokens(s.tokens),+ })}`,+ ),+ ];+ return (+ <div+ key={b.day}+ title={titleLines.join('\n')}+ // 列容器只负责高度与圆角裁切; 分段自上而下 = rank 降序 ("其它"在顶, 大头在底)+ className="flex min-w-0 flex-1 flex-col justify-end overflow-hidden rounded-[2px]"+ style={{+ height,+ backgroundColor: b.segments.length === 0 ? 'var(--surface-chip)' : undefined,+ }}+ >+ {[...b.segments].reverse().map((s) => (+ <div+ key={s.rank}+ style={{+ height: `${(s.tokens / b.tokens) * 100}%`,+ backgroundColor: usageRankColor(s.rank),+ }}+ />+ ))}+ </div>+ );+ })}+ </div>+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryStats.test.ts b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryStats.test.tsnew file mode 100644index 0000000000..bb136dd7d5--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/usage/__tests__/usageHistoryStats.test.ts@@ -0,0 +1,274 @@+import { describe, expect, it } from 'vitest';++import type { UsageHistoryPayload } from '@/hooks/useUsageHistory';+import {+ buildAgentRows,+ buildModelRows,+ buildSummary,+ cacheHitRate,+ computeTokenStreak,+ isUsageHistoryEmpty,+ toUsageDays,+} from '../usageHistoryStats';++const zeroMoney = {+ amount: 0,+ currency: 'USD' as const,+ approximate: false,+ kind: 'actual-cost' as const,+};++function model(over: Partial<UsageHistoryPayload['models'][number]>) {+ return {+ agentKind: 'claude-code' as const,+ model: 'claude-opus-4-8',+ money: zeroMoney,+ estimatedMoney: null,+ inputTokens: 0,+ outputTokens: 0,+ cacheReadTokens: 0,+ cacheCreateTokens: 0,+ ...over,+ };+}++function payload(over: Partial<UsageHistoryPayload> = {}): UsageHistoryPayload {+ return {+ generatedAt: 0,+ todayKey: '2026-08-22',+ days: [],+ modelDaily: [],+ models: [],+ streak: { current: 0, longest: 0 },+ totals: {+ today: zeroMoney,+ last30Days: zeroMoney,+ last30DaysWithEstimatedValue: zeroMoney,+ last30DaysEstimatedValue: zeroMoney,+ todayTokens: 0,+ last30DaysTokens: 0,+ },+ anomaly: { isAnomalous: false, trailing7DayAvg: null },+ ...over,+ };+}++describe('cacheHitRate', () => {+ it('输出 token 不进分母 (与逐轮卡片同一公式)', () => {+ expect(+ cacheHitRate({ inputTokens: 100, cacheReadTokens: 300, cacheCreateTokens: 100 }),+ ).toBeCloseTo(0.6);+ });++ it('分母为 0 时返回 null 而不是 0 —— 没有上下文可复用与命中率为零是两回事', () => {+ expect(+ cacheHitRate({ inputTokens: 0, cacheReadTokens: 0, cacheCreateTokens: 0 }),+ ).toBeNull();+ });+});++describe('computeTokenStreak', () => {+ const days = (...keys: string[]) => keys.map((day) => ({ day, tokens: 1000 }));++ it('今日有记录时从今日起算', () => {+ const streak = computeTokenStreak(+ days('2026-08-20', '2026-08-21', '2026-08-22'),+ '2026-08-22',+ );+ expect(streak.current).toBe(3);+ });++ it('今日还没跑过时从昨天起算, 不把昨天的连续清零', () => {+ const streak = computeTokenStreak(days('2026-08-20', '2026-08-21'), '2026-08-22');+ expect(streak.current).toBe(2);+ });++ it('昨天与今天都没有记录时 current 归零, longest 仍保留历史最长', () => {+ const streak = computeTokenStreak(+ days('2026-08-01', '2026-08-02', '2026-08-03', '2026-08-10'),+ '2026-08-22',+ );+ expect(streak.current).toBe(0);+ expect(streak.longest).toBe(3);+ });++ it('跨月连续不断档', () => {+ const streak = computeTokenStreak(+ days('2026-07-30', '2026-07-31', '2026-08-01'),+ '2026-08-01',+ );+ expect(streak).toEqual({ current: 3, longest: 3 });+ });++ it('无任何活跃日时返回 0/0', () => {+ expect(computeTokenStreak([], '2026-08-22')).toEqual({ current: 0, longest: 0 });+ });+});++describe('toUsageDays', () => {+ it('丢掉没有 token 的日子 (只有金额没有 token 的历史日不算活跃)', () => {+ const rows = toUsageDays(+ payload({+ days: [+ { day: '2026-08-21', money: zeroMoney, tokens: 0 },+ { day: '2026-08-22', money: zeroMoney, tokens: 500 },+ ],+ }),+ );+ expect(rows).toEqual([{ day: '2026-08-22', tokens: 500 }]);+ });++ it('旧快照缺 tokens 字段时按 0 兜底, 不会 NaN', () => {+ const rows = toUsageDays(+ payload({ days: [{ day: '2026-08-22', money: zeroMoney }] }),+ );+ expect(rows).toEqual([]);+ });+});++describe('buildModelRows', () => {+ it('按 token 降序并给出占比', () => {+ const rows = buildModelRows(+ payload({+ models: [+ model({ model: 'haiku', inputTokens: 100 }),+ model({ model: 'opus', inputTokens: 900 }),+ ],+ }),+ );+ expect(rows.map((r) => r.model)).toEqual(['opus', 'haiku']);+ expect(rows[0].share).toBeCloseTo(0.9);+ });++ it('同一模型的 api / subscription 两个计费维度合并成一行', () => {+ // main 侧按带 #billing= 后缀的原始 model 聚合, 到 payload 时后缀已被剥掉 ——+ // 不合并会渲染出两行同名模型 + 重复 React key, 并让模型数多算。+ const rows = buildModelRows(+ payload({+ models: [+ model({ model: 'claude-opus-4-8', inputTokens: 100, cacheReadTokens: 300 }),+ model({ model: 'claude-opus-4-8', inputTokens: 50, outputTokens: 20 }),+ ],+ }),+ );+ expect(rows).toHaveLength(1);+ expect(rows[0].tokens).toBe(470);+ expect(rows[0].inputTokens).toBe(150);+ expect(rows[0].share).toBe(1);+ // 命中率按合并后的分子分母算: 300 / (150 + 300 + 0)+ expect(rows[0].cacheHitRate).toBeCloseTo(300 / 450);+ });++ it('同名模型跨 agent 分成两行 (网关模型 id 可能撞名)', () => {+ const rows = buildModelRows(+ payload({+ models: [+ model({ agentKind: 'claude-code', model: 'gpt-5.5', inputTokens: 10 }),+ model({ agentKind: 'codex', model: 'gpt-5.5', inputTokens: 20 }),+ ],+ }),+ );+ expect(rows).toHaveLength(2);+ expect(new Set(rows.map((r) => r.key)).size).toBe(2);+ });+});++describe('buildAgentRows', () => {+ const sample = payload({+ todayKey: '2026-08-22',+ models: [+ model({ agentKind: 'claude-code', model: 'opus', inputTokens: 100, cacheReadTokens: 900 }),+ model({ agentKind: 'claude-code', model: 'haiku', inputTokens: 100, cacheReadTokens: 100 }),+ model({ agentKind: 'codex', model: 'gpt-5.5', inputTokens: 800, cacheReadTokens: 200 }),+ ],+ modelDaily: [+ {+ day: '2026-08-22',+ agentKind: 'claude-code',+ model: 'opus',+ money: zeroMoney,+ apiMoney: zeroMoney,+ subscriptionEstimateMoney: zeroMoney,+ tokens: 320,+ },+ {+ day: '2026-08-21',+ agentKind: 'codex',+ model: 'gpt-5.5',+ money: zeroMoney,+ apiMoney: zeroMoney,+ subscriptionEstimateMoney: zeroMoney,+ tokens: 999,+ },+ ],+ });++ it('modelCount 不把同一模型的两个计费维度数成两个', () => {+ const rows = buildAgentRows(+ payload({+ models: [+ model({ agentKind: 'codex', model: 'gpt-5.5', inputTokens: 100 }),+ model({ agentKind: 'codex', model: 'gpt-5.5', inputTokens: 200 }),+ ],+ }),+ );+ expect(rows).toHaveLength(1);+ expect(rows[0].modelCount).toBe(1);+ expect(rows[0].tokens).toBe(300);+ });++ it('按 agent 合并模型并数出模型个数', () => {+ const rows = buildAgentRows(sample);+ const claude = rows.find((r) => r.agentKind === 'claude-code');+ expect(claude?.modelCount).toBe(2);+ expect(claude?.tokens).toBe(1200);+ });++ it('命中率分子分母各自加总, 不是对各模型命中率取平均', () => {+ const claude = buildAgentRows(sample).find((r) => r.agentKind === 'claude-code');+ // (900 + 100) / (200 + 1000) = 0.8333…;按模型平均会得到 (0.9 + 0.5) / 2 = 0.7+ expect(claude?.cacheHitRate).toBeCloseTo(1000 / 1200);+ });++ it('today 只统计 todayKey 当天的行', () => {+ const rows = buildAgentRows(sample);+ expect(rows.find((r) => r.agentKind === 'claude-code')?.todayTokens).toBe(320);+ expect(rows.find((r) => r.agentKind === 'codex')?.todayTokens).toBe(0);+ });+});++describe('buildSummary / isUsageHistoryEmpty', () => {+ it('token 总量直接取 payload.totals', () => {+ const summary = buildSummary(+ payload({+ totals: {+ today: zeroMoney,+ last30Days: zeroMoney,+ last30DaysWithEstimatedValue: zeroMoney,+ last30DaysEstimatedValue: zeroMoney,+ todayTokens: 1234,+ last30DaysTokens: 56789,+ },+ }),+ );+ expect(summary.todayTokens).toBe(1234);+ expect(summary.last30DaysTokens).toBe(56789);+ });++ it('payload 为 null 时给出全零快照而不是抛错', () => {+ expect(buildSummary(null)).toEqual({+ todayTokens: 0,+ last30DaysTokens: 0,+ streak: { current: 0, longest: 0 },+ cacheHitRate: null,+ modelCount: 0,+ });+ expect(isUsageHistoryEmpty(null)).toBe(true);+ });++ it('有 token 记录时不算空', () => {+ expect(+ isUsageHistoryEmpty(payload({ models: [model({ inputTokens: 10 })] })),+ ).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts b/apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.tsnew file mode 100644index 0000000000..3ca45eec2f--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts@@ -0,0 +1,9 @@+/**+ * formatUsagePercent — 百分比展示, 与 TodaySpendChip 的 formatTurnUsagePercent 同一形态:+ * 接近整数时不带小数, 否则保留一位并去掉末尾的 .0。+ */+export function formatUsagePercent(value: number): string {+ const percent = Math.min(100, Math.max(0, value * 100));+ if (Math.abs(percent - Math.round(percent)) < 0.05) return `${Math.round(percent)}%`;+ return `${percent.toFixed(1).replace(/\.0$/, '')}%`;+}diff --git a/apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts b/apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.tsnew file mode 100644index 0000000000..5e4534b7d5--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts@@ -0,0 +1,255 @@+/**+ * usageHistoryStats — 用量历史页的纯聚合函数 (无 DOM / 无 IPC 依赖, 便于单测)。+ *+ * 口径约定 (与 issue #2785 的裁决一致): 本页只统计 token, 不出现任何金额、账户额度或预算。+ * 因此这里的「活跃日」按**当日有 token 记录**判定, 而不是 payload 自带的 `streak`+ * —— 那个字段用 `ACTIVE_DAY_MIN_USD` 打在 `daily_spend` 上, 订阅用户恒为 0。+ *+ * 两个窗口不同, 调用方不要混用:+ * - `days[]` 覆盖 140 天 (main 侧 usageRowsSince 已按热力图窗口取行) → 热力图、连续活跃天数+ * - `models[]` / `modelDaily` 是 30 天 → 按模型、按 agent、每日柱图+ */++import type {+ UsageHistoryModel,+ UsageHistoryPayload,+} from '@/hooks/useUsageHistory';++export type UsageAgentKind = UsageHistoryModel['agentKind'];++export interface UsageDay {+ day: string;+ tokens: number;+}++export interface ModelTokenRow {+ key: string;+ agentKind: UsageAgentKind;+ model: string;+ tokens: number;+ inputTokens: number;+ outputTokens: number;+ cacheReadTokens: number;+ cacheCreateTokens: number;+ /** 占近 30 天总量的比例 (0..1); 总量为 0 时为 0。 */+ share: number;+ /** cacheRead / (input + cacheRead + cacheCreate); 分母为 0 时为 null。 */+ cacheHitRate: number | null;+}++export interface AgentTokenRow {+ agentKind: UsageAgentKind;+ tokens: number;+ todayTokens: number;+ share: number;+ cacheHitRate: number | null;+ modelCount: number;+}++/**+ * 缓存命中率 —— 与 `shared/turnUsageDetails.ts` 的 `buildTurnUsageDetails` 同一公式,+ * 只是把窗口从一轮扩到统计区间。聚合时必须分子分母各自加总后再除,+ * 不能对各模型的命中率取平均 (那会让小用量模型获得与大用量模型相同的权重)。+ */+export function cacheHitRate(input: {+ inputTokens: number;+ cacheReadTokens: number;+ cacheCreateTokens: number;+}): number | null {+ const denominator = input.inputTokens + input.cacheReadTokens + input.cacheCreateTokens;+ if (denominator <= 0) return null;+ return input.cacheReadTokens / denominator;+}++export function modelTokenTotal(model: {+ inputTokens: number;+ outputTokens: number;+ cacheReadTokens: number;+ cacheCreateTokens: number;+}): number {+ return model.inputTokens + model.outputTokens + model.cacheReadTokens + model.cacheCreateTokens;+}++function shiftDayKey(dayKey: string, deltaDays: number): string {+ const [y, m, d] = dayKey.split('-').map(Number);+ const date = new Date(y, (m ?? 1) - 1, (d ?? 1) + deltaDays);+ const mm = String(date.getMonth() + 1).padStart(2, '0');+ const dd = String(date.getDate()).padStart(2, '0');+ return `${date.getFullYear()}-${mm}-${dd}`;+}++/** payload.days → 只保留 token 维度 (热力图与 streak 的共同输入)。 */+export function toUsageDays(payload: UsageHistoryPayload | null): UsageDay[] {+ if (!payload) return [];+ return payload.days+ .map((row) => ({ day: row.day, tokens: row.tokens ?? 0 }))+ .filter((row) => row.tokens > 0)+ .sort((a, b) => (a.day < b.day ? -1 : 1));+}++/**+ * token 口径的连续活跃天数。+ *+ * 今日还没有记录时从昨天起算 (当天刚开机不该把昨天的连续记录清零, 与 main 侧+ * `computeStreaks` 同一处理)。`longest` 只在传入窗口内计算 —— days 覆盖 140 天,+ * 因此首版最长连续以 140 天为上限。+ */+export function computeTokenStreak(+ days: UsageDay[],+ todayKey: string,+): { current: number; longest: number } {+ const active = new Set(days.filter((d) => d.tokens > 0).map((d) => d.day));+ if (active.size === 0 || !todayKey) return { current: 0, longest: 0 };++ let current = 0;+ let cursor = active.has(todayKey) ? todayKey : shiftDayKey(todayKey, -1);+ while (active.has(cursor)) {+ current += 1;+ cursor = shiftDayKey(cursor, -1);+ }++ let longest = 0;+ let run = 0;+ let previous: string | null = null;+ for (const day of [...active].sort()) {+ run = previous !== null && shiftDayKey(previous, 1) === day ? run + 1 : 1;+ if (run > longest) longest = run;+ previous = day;+ }++ return { current, longest };+}++/**+ * 近 30 天按模型, 按 token 降序。+ *+ * **必须按 (agentKind, 展示模型名) 再合并一次**: main 侧按原始 model 聚合, 而同一个模型的+ * API 与订阅两个计费维度带着 `#billing=api` / `#billing=subscription` 后缀分行+ * (`main/usage/usageHistory.ts` 的 byKey), 暴露到 payload 时后缀已被 displayModelName 剥掉。+ * 直接用展示名建 key 会渲染出两行看不出区别的同名模型、产生重复 React key,+ * 并让「用到的模型」数与 Agent 表的模型数多算。本页只统计 token, 不区分计费维度, 合并即可。+ */+export function buildModelRows(payload: UsageHistoryPayload | null): ModelTokenRow[] {+ if (!payload) return [];+ const merged = new Map<string, ModelTokenRow>();+ for (const model of payload.models) {+ const tokens = modelTokenTotal(model);+ if (tokens <= 0) continue;+ const key = `${model.agentKind} ${model.model}`;+ const existing = merged.get(key);+ if (existing) {+ existing.tokens += tokens;+ existing.inputTokens += model.inputTokens;+ existing.outputTokens += model.outputTokens;+ existing.cacheReadTokens += model.cacheReadTokens;+ existing.cacheCreateTokens += model.cacheCreateTokens;+ continue;+ }+ merged.set(key, {+ key,+ agentKind: model.agentKind,+ model: model.model,+ tokens,+ inputTokens: model.inputTokens,+ outputTokens: model.outputTokens,+ cacheReadTokens: model.cacheReadTokens,+ cacheCreateTokens: model.cacheCreateTokens,+ share: 0,+ cacheHitRate: null,+ });+ }+ const rows = [...merged.values()].sort((a, b) => b.tokens - a.tokens);++ const total = rows.reduce((sum, row) => sum + row.tokens, 0);+ return rows.map((row) => ({+ ...row,+ share: total > 0 ? row.tokens / total : 0,+ cacheHitRate: cacheHitRate(row),+ }));+}++/** 近 30 天按 agent / harness。today 取自 modelDaily 的今日行, 缺失时为 0。 */+export function buildAgentRows(payload: UsageHistoryPayload | null): AgentTokenRow[] {+ if (!payload) return [];++ const todayByAgent = new Map<UsageAgentKind, number>();+ for (const row of payload.modelDaily) {+ if (row.day !== payload.todayKey || row.tokens <= 0) continue;+ todayByAgent.set(row.agentKind, (todayByAgent.get(row.agentKind) ?? 0) + row.tokens);+ }++ interface AgentAcc extends AgentTokenRow {+ inputTokens: number;+ cacheReadTokens: number;+ cacheCreateTokens: number;+ }+ const byAgent = new Map<UsageAgentKind, AgentAcc>();+ // 走合并后的模型行 —— 同一模型的 api / subscription 两个计费维度已并成一行,+ // 否则 modelCount 会把同一个模型数成两个 (见 buildModelRows 的注释)。+ for (const model of buildModelRows(payload)) {+ const tokens = model.tokens;+ if (tokens <= 0) continue;+ const acc = byAgent.get(model.agentKind) ?? {+ agentKind: model.agentKind,+ tokens: 0,+ todayTokens: todayByAgent.get(model.agentKind) ?? 0,+ share: 0,+ cacheHitRate: null,+ modelCount: 0,+ inputTokens: 0,+ cacheReadTokens: 0,+ cacheCreateTokens: 0,+ };+ acc.tokens += tokens;+ acc.modelCount += 1;+ acc.inputTokens += model.inputTokens;+ acc.cacheReadTokens += model.cacheReadTokens;+ acc.cacheCreateTokens += model.cacheCreateTokens;+ byAgent.set(model.agentKind, acc);+ }++ const rows = [...byAgent.values()].sort((a, b) => b.tokens - a.tokens);+ const total = rows.reduce((sum, row) => sum + row.tokens, 0);+ return rows.map((row) => ({+ agentKind: row.agentKind,+ tokens: row.tokens,+ todayTokens: row.todayTokens,+ share: total > 0 ? row.tokens / total : 0,+ cacheHitRate: cacheHitRate(row),+ modelCount: row.modelCount,+ }));+}++export interface UsageSummary {+ todayTokens: number;+ last30DaysTokens: number;+ streak: { current: number; longest: number };+ cacheHitRate: number | null;+ modelCount: number;+}++/** 页面顶部统计条。token 总量直接用 payload.totals, 不自己二次求和。 */+export function buildSummary(payload: UsageHistoryPayload | null): UsageSummary {+ const models = buildModelRows(payload);+ return {+ todayTokens: payload?.totals.todayTokens ?? 0,+ last30DaysTokens: payload?.totals.last30DaysTokens ?? 0,+ streak: computeTokenStreak(toUsageDays(payload), payload?.todayKey ?? ''),+ cacheHitRate: cacheHitRate({+ inputTokens: models.reduce((sum, m) => sum + m.inputTokens, 0),+ cacheReadTokens: models.reduce((sum, m) => sum + m.cacheReadTokens, 0),+ cacheCreateTokens: models.reduce((sum, m) => sum + m.cacheCreateTokens, 0),+ }),+ modelCount: models.length,+ };+}++/** 页面是否完全没有数据可展示 (决定渲染空态还是正文)。 */+export function isUsageHistoryEmpty(payload: UsageHistoryPayload | null): boolean {+ if (!payload) return true;+ return (+ (payload.totals.last30DaysTokens ?? 0) <= 0 &&+ toUsageDays(payload).length === 0 &&+ buildModelRows(payload).length === 0+ );+}diff --git a/apps/desktop/src/renderer/components/settings/usageVisibility.ts b/apps/desktop/src/renderer/components/settings/usageVisibility.tsnew file mode 100644index 0000000000..9de4b99f50--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/usageVisibility.ts@@ -0,0 +1,15 @@+/**+ * 用量历史 tab 的可见性。+ *+ * 与 billingVisibility 刻意不同: 计费页只对个人云账号开放, 而用量历史对**所有已登录身份**+ * 开放 (local / cloud personal / cloud org) —— 它读的是本机 daily_model_usage,+ * 不涉及账户与账单, 因此不该继承计费页的身份门 (issue #2785 维护者裁决)。+ */++export interface UsageSettingsIdentity {+ mode: 'signed-out' | 'local' | 'cloud';+}++export function canAccessUsageSettings(identity: UsageSettingsIdentity): boolean {+ return identity.mode !== 'signed-out';+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ddef484057..d8ba2aa13f 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -94,6 +94,7 @@"tabs": {"general": "General","billing": "Usage and billing",+ "usage": "Usage history","personalization": "Personalization","apiKeys": "Tool Keys","voiceInput": "Voice Input",@@ -5145,6 +5146,70 @@"lowCache": "Cache hit rate is low; more context was billed again this turn"}},+ "usageHistory": {+ "description": "Token usage produced inside Cindy on this device. Records start accumulating when the feature ships; earlier history is not backfilled.",+ "empty": "No usage recorded yet. This fills in once you start a chat.",+ "cacheHitTooltip": "Cache read / (input + cache read + cache write) — the same formula as the message card.",+ "summary": {+ "title": "Overview"+ },+ "stats": {+ "todayTokens": "Tokens today",+ "totalTokens": "Tokens (30d)",+ "streak": "Active streak",+ "cacheHitRate": "Cache hit rate (30d)",+ "models": "Models used"+ },+ "heatmap": {+ "title": "Activity heatmap",+ "subtitle": "Last 20 weeks",+ "emptyCell": "No usage recorded"+ },+ "daily": {+ "title": "Daily tokens (30d)",+ "subtitle": "Stacked by model"+ },+ "byAgent": {+ "title": "By Agent / harness",+ "subtitle": "Last 30 days",+ "col": {+ "agent": "Agent / harness",+ "total": "Tokens (30d)",+ "share": "Share",+ "today": "Today",+ "hitRate": "Cache hit rate",+ "models": "Models"+ }+ },+ "byModel": {+ "title": "By model",+ "subtitle": "Last 30 days",+ "col": {+ "model": "Model",+ "total": "Total tokens",+ "share": "Share",+ "input": "Input",+ "output": "Output",+ "cacheRead": "Cache read",+ "cacheCreate": "Cache write",+ "hitRate": "Cache hit rate"+ }+ },+ "tasks": {+ "title": "Top sessions by tokens",+ "subtitle": "Sessions active in the last 30 days, ranked by lifetime tokens",+ "col": {+ "task": "Session",+ "model": "Model",+ "provider": "Provider",+ "tokens": "Total tokens",+ "context": "Context used",+ "lastActive": "Last active"+ },+ "providerTooltip": "The provider currently selected for the session; blank when none is pinned.",+ "tokensTooltip": "The session's lifetime total, not the tokens spent within the last 30 days."+ }+ },"usageDashboard": {"title": "Usage & Spend","updating": "Updating",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex f3d4b5d19b..0d82e5e570 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -94,6 +94,7 @@"tabs": {"general": "一般","billing": "使用量と請求",+ "usage": "使用履歴","personalization": "パーソナライズ","apiKeys": "ツールキー","voiceInput": "音声入力",@@ -5143,6 +5144,70 @@"lowCache": "キャッシュヒット率が低く、このターンでは多くのコンテキストが再課金されています"}},+ "usageHistory": {+ "description": "このデバイスの Cindy 内で発生したトークン使用量です。記録は機能の提供開始時から蓄積され、それ以前の履歴は補完されません。",+ "empty": "まだ使用記録がありません。会話を実行すると蓄積が始まります。",+ "cacheHitTooltip": "キャッシュ読取 ÷(入力 + キャッシュ読取 + キャッシュ書込)。メッセージカードと同じ基準です。",+ "summary": {+ "title": "概要"+ },+ "stats": {+ "todayTokens": "今日のトークン",+ "totalTokens": "直近 30 日のトークン",+ "streak": "連続稼働日数",+ "cacheHitRate": "キャッシュヒット率(30 日)",+ "models": "使用モデル数"+ },+ "heatmap": {+ "title": "アクティビティヒートマップ",+ "subtitle": "直近 20 週",+ "emptyCell": "この日は使用記録なし"+ },+ "daily": {+ "title": "直近 30 日の日次トークン",+ "subtitle": "モデル別の積み上げ"+ },+ "byAgent": {+ "title": "Agent / harness 別",+ "subtitle": "直近 30 日",+ "col": {+ "agent": "Agent / harness",+ "total": "直近 30 日のトークン",+ "share": "割合",+ "today": "今日",+ "hitRate": "キャッシュヒット率",+ "models": "モデル数"+ }+ },+ "byModel": {+ "title": "モデル別",+ "subtitle": "直近 30 日",+ "col": {+ "model": "モデル",+ "total": "合計トークン",+ "share": "割合",+ "input": "入力",+ "output": "出力",+ "cacheRead": "キャッシュ読取",+ "cacheCreate": "キャッシュ書込",+ "hitRate": "キャッシュヒット率"+ }+ },+ "tasks": {+ "title": "トークン消費の多いセッション",+ "subtitle": "直近 30 日に稼働したセッションを累計トークン順に表示",+ "col": {+ "task": "セッション",+ "model": "モデル",+ "provider": "プロバイダー",+ "tokens": "累計トークン",+ "context": "コンテキスト使用率",+ "lastActive": "最終アクティブ"+ },+ "providerTooltip": "セッションで現在選択されているプロバイダー。未指定の場合は空欄です。",+ "tokensTooltip": "セッションの累計値であり、直近 30 日の増分ではありません。"+ }+ },"usageDashboard": {"title": "使用量とコスト","updating": "更新中",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 75f3bbc307..27d8db365c 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -94,6 +94,7 @@"tabs": {"general": "일반","billing": "사용량 및 결제",+ "usage": "사용 기록","personalization": "개인화","apiKeys": "도구 키","voiceInput": "음성 입력",@@ -5143,6 +5144,70 @@"lowCache": "캐시 적중률이 낮아 이번 턴에서 더 많은 컨텍스트가 다시 과금되었습니다"}},+ "usageHistory": {+ "description": "이 기기의 Cindy 내부에서 발생한 토큰 사용량입니다. 기능 출시 시점부터 기록이 쌓이며 이전 기록은 채워지지 않습니다.",+ "empty": "아직 사용 기록이 없습니다. 대화를 실행하면 쌓이기 시작합니다.",+ "cacheHitTooltip": "캐시 읽기 ÷ (입력 + 캐시 읽기 + 캐시 쓰기) — 메시지 카드와 동일한 기준입니다.",+ "summary": {+ "title": "개요"+ },+ "stats": {+ "todayTokens": "오늘 토큰",+ "totalTokens": "최근 30일 토큰",+ "streak": "연속 활동일",+ "cacheHitRate": "캐시 적중률(30일)",+ "models": "사용한 모델"+ },+ "heatmap": {+ "title": "활동 히트맵",+ "subtitle": "최근 20주",+ "emptyCell": "해당 날짜에 사용 기록 없음"+ },+ "daily": {+ "title": "최근 30일 일별 토큰",+ "subtitle": "모델별 누적"+ },+ "byAgent": {+ "title": "Agent / harness별",+ "subtitle": "최근 30일",+ "col": {+ "agent": "Agent / harness",+ "total": "최근 30일 토큰",+ "share": "비중",+ "today": "오늘",+ "hitRate": "캐시 적중률",+ "models": "모델 수"+ }+ },+ "byModel": {+ "title": "모델별",+ "subtitle": "최근 30일",+ "col": {+ "model": "모델",+ "total": "총 토큰",+ "share": "비중",+ "input": "입력",+ "output": "출력",+ "cacheRead": "캐시 읽기",+ "cacheCreate": "캐시 쓰기",+ "hitRate": "캐시 적중률"+ }+ },+ "tasks": {+ "title": "토큰 사용이 많은 세션",+ "subtitle": "최근 30일 동안 활동한 세션을 누적 토큰 순으로 정렬",+ "col": {+ "task": "세션",+ "model": "모델",+ "provider": "제공자",+ "tokens": "누적 토큰",+ "context": "컨텍스트 사용률",+ "lastActive": "마지막 활동"+ },+ "providerTooltip": "세션에 현재 선택된 제공자입니다. 지정하지 않은 경우 비워 둡니다.",+ "tokensTooltip": "해당 세션의 누적 값이며 최근 30일 증가분이 아닙니다."+ }+ },"usageDashboard": {"title": "사용량 및 비용","updating": "업데이트 중",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 3b57ee25cc..3ed278eae1 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -94,6 +94,7 @@"tabs": {"general": "通用","billing": "用量和计费",+ "usage": "用量历史","personalization": "个性化","apiKeys": "工具密钥","voiceInput": "语音输入",@@ -5143,6 +5144,70 @@"lowCache": "缓存命中率偏低,本轮较多上下文重新计费"}},+ "usageHistory": {+ "description": "这台设备上 Cindy 内部产生的 token 用量。记录从该功能上线起积累,不回填更早的历史。",+ "empty": "还没有用量记录。跑过对话之后,这里会开始积累。",+ "cacheHitTooltip": "缓存读取 ÷(输入 + 缓存读取 + 缓存写入),与消息卡片同口径。",+ "summary": {+ "title": "概览"+ },+ "stats": {+ "todayTokens": "今日 token",+ "totalTokens": "近 30 天 token",+ "streak": "连续活跃天数",+ "cacheHitRate": "缓存命中率(近 30 天)",+ "models": "用到的模型"+ },+ "heatmap": {+ "title": "活跃热力图",+ "subtitle": "近 20 周",+ "emptyCell": "当天没有用量记录"+ },+ "daily": {+ "title": "近 30 天每日 token",+ "subtitle": "按模型堆叠"+ },+ "byAgent": {+ "title": "按 Agent / harness",+ "subtitle": "近 30 天",+ "col": {+ "agent": "Agent / harness",+ "total": "近 30 天 token",+ "share": "占比",+ "today": "今日",+ "hitRate": "缓存命中率",+ "models": "用到的模型"+ }+ },+ "byModel": {+ "title": "按模型",+ "subtitle": "近 30 天",+ "col": {+ "model": "模型",+ "total": "总 token",+ "share": "占比",+ "input": "输入",+ "output": "输出",+ "cacheRead": "缓存读取",+ "cacheCreate": "缓存写入",+ "hitRate": "缓存命中率"+ }+ },+ "tasks": {+ "title": "最耗 token 的任务",+ "subtitle": "近 30 天内活跃过的任务,按累计 token 排序",+ "col": {+ "task": "任务",+ "model": "模型",+ "provider": "供应商",+ "tokens": "累计 token",+ "context": "上下文占用",+ "lastActive": "最后活跃"+ },+ "providerTooltip": "取该任务当前选定的供应商;未指定时留空。",+ "tokensTooltip": "该任务的生命周期累计,不是近 30 天内的增量。"+ }+ },"usageDashboard": {"title": "用量与开销","updating": "更新中",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 49628668fe..12a719ff4e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -94,6 +94,7 @@"tabs": {"general": "通用","billing": "用量和計費",+ "usage": "用量歷史","personalization": "個性化","apiKeys": "工具金鑰","voiceInput": "語音輸入",@@ -5143,6 +5144,70 @@"lowCache": "快取命中率偏低,本輪較多上下文重新計費"}},+ "usageHistory": {+ "description": "這台裝置上 Cindy 內部產生的 token 用量。紀錄從該功能上線起累積,不回填更早的歷史。",+ "empty": "還沒有用量紀錄。跑過對話之後,這裡會開始累積。",+ "cacheHitTooltip": "快取讀取 ÷(輸入 + 快取讀取 + 快取寫入),與訊息卡片同口徑。",+ "summary": {+ "title": "概覽"+ },+ "stats": {+ "todayTokens": "今日 token",+ "totalTokens": "近 30 天 token",+ "streak": "連續活躍天數",+ "cacheHitRate": "快取命中率(近 30 天)",+ "models": "用到的模型"+ },+ "heatmap": {+ "title": "活躍熱力圖",+ "subtitle": "近 20 週",+ "emptyCell": "當天沒有用量紀錄"+ },+ "daily": {+ "title": "近 30 天每日 token",+ "subtitle": "按模型堆疊"+ },+ "byAgent": {+ "title": "按 Agent / harness",+ "subtitle": "近 30 天",+ "col": {+ "agent": "Agent / harness",+ "total": "近 30 天 token",+ "share": "佔比",+ "today": "今日",+ "hitRate": "快取命中率",+ "models": "用到的模型"+ }+ },+ "byModel": {+ "title": "按模型",+ "subtitle": "近 30 天",+ "col": {+ "model": "模型",+ "total": "總 token",+ "share": "佔比",+ "input": "輸入",+ "output": "輸出",+ "cacheRead": "快取讀取",+ "cacheCreate": "快取寫入",+ "hitRate": "快取命中率"+ }+ },+ "tasks": {+ "title": "最耗 token 的任務",+ "subtitle": "近 30 天內活躍過的任務,按累計 token 排序",+ "col": {+ "task": "任務",+ "model": "模型",+ "provider": "供應商",+ "tokens": "累計 token",+ "context": "上下文佔用",+ "lastActive": "最後活躍"+ },+ "providerTooltip": "取該任務目前選定的供應商;未指定時留空。",+ "tokensTooltip": "該任務的生命週期累計,不是近 30 天內的增量。"+ }+ },"usageDashboard": {"title": "用量與開銷","updating": "更新中",diff --git a/apps/desktop/src/renderer/lib/__tests__/providerDisplayName.test.ts b/apps/desktop/src/renderer/lib/__tests__/providerDisplayName.test.tsnew file mode 100644index 0000000000..1785655e10--- /dev/null+++ b/apps/desktop/src/renderer/lib/__tests__/providerDisplayName.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';++import type { ProviderView } from '@cindy/model-providers';+import { providerDisplayNameById } from '../providerDisplayName';++const t = (key: string) =>+ ({+ 'settings.providers.xd.title': 'Cindy AI',+ 'settings.providers.anthropic.title': 'Anthropic',+ })[key] ?? key;++const catalog = [+ { id: 'my-proxy', name: '公司自建网关' },+] as unknown as ProviderView[];++describe('providerDisplayNameById', () => {+ it('内置供应商用设置页标题,而不是裸 id', () => {+ expect(providerDisplayNameById('xd', [], t)).toBe('Cindy AI');+ expect(providerDisplayNameById('anthropic', catalog, t)).toBe('Anthropic');+ });++ it('自定义供应商回退目录里的展示名', () => {+ expect(providerDisplayNameById('my-proxy', catalog, t)).toBe('公司自建网关');+ });++ it('目录里查不到时才回退裸 id(用户删过该供应商 / 目录未加载)', () => {+ expect(providerDisplayNameById('gone', catalog, t)).toBe('gone');+ });+});diff --git a/apps/desktop/src/renderer/lib/__tests__/tabLabels.test.ts b/apps/desktop/src/renderer/lib/__tests__/tabLabels.test.tsindex fabe43c1a7..267fac8d05 100644--- a/apps/desktop/src/renderer/lib/__tests__/tabLabels.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/tabLabels.test.ts@@ -9,6 +9,12 @@ describe('Settings tab order', () => {expect(TAB_IDS.slice(providersIndex, providersIndex + 2)).toEqual(['providers', 'billing']);});+ it('places usage history immediately after billing', () => {+ const billingIndex = TAB_IDS.indexOf('billing');++ expect(TAB_IDS.slice(billingIndex, billingIndex + 2)).toEqual(['billing', 'usage']);+ });+it('keeps Pi extensions inside General instead of exposing a top-level tab', () => {expect(TAB_IDS).not.toContain('pi-extensions');expect(isSettingsTab('pi-extensions')).toBe(false);diff --git a/apps/desktop/src/renderer/lib/providerDisplayName.ts b/apps/desktop/src/renderer/lib/providerDisplayName.tsnew file mode 100644index 0000000000..8c02f3b09a--- /dev/null+++ b/apps/desktop/src/renderer/lib/providerDisplayName.ts@@ -0,0 +1,36 @@+/**+ * 供应商展示名 —— 三个内置 id 复用设置页 i18n 标题 (settings.providers.<id>.title),+ * 自定义供应商回退目录里的 provider.name, 都拿不到时才回退裸 id。+ *+ * 从 ModelSelector 提取到这里: 用量历史的任务表也要把 Session.providerId 渲染成人话,+ * 两处必须同源, 否则同一个 'xd' 在模型选择器里是「Cindy AI」、在用量页却是「xd」。+ */++import type { ProviderView } from '@cindy/model-providers';++export const PROVIDER_TITLE_KEY: Record<string, string> = {+ anthropic: 'settings.providers.anthropic.title',+ openai: 'settings.providers.openai.title',+ xd: 'settings.providers.xd.title',+};++type TFunc = (key: string) => string;++export function providerDisplayName(provider: ProviderView, t: TFunc): string {+ const key = PROVIDER_TITLE_KEY[provider.id];+ return key ? t(key) : provider.name;+}++/**+ * 只有 id 时的展示名 (会话行记的是 providerId, 目录未必包含它 —— 例如未登录时+ * 网关供应商不在目录里, 或用户删掉了那个自定义供应商)。+ */+export function providerDisplayNameById(+ providerId: string,+ providers: readonly ProviderView[],+ t: TFunc,+): string {+ const key = PROVIDER_TITLE_KEY[providerId];+ if (key) return t(key);+ return providers.find((provider) => provider.id === providerId)?.name ?? providerId;+}diff --git a/apps/desktop/src/renderer/lib/tabLabels.ts b/apps/desktop/src/renderer/lib/tabLabels.tsindex 4e996dc6b6..e99a247176 100644--- a/apps/desktop/src/renderer/lib/tabLabels.ts+++ b/apps/desktop/src/renderer/lib/tabLabels.ts@@ -10,6 +10,7 @@export type SettingsTab =| 'general'| 'billing'+ | 'usage'| 'personalization'| 'providers'| 'api-keys'@@ -33,6 +34,9 @@ export const TAB_IDS = ['personalization','providers','billing',+ // 「用量历史」紧随计费:两者都回答"我用了多少",但分工明确 —— billing 管账单与账户+ // 信息,usage 只统计本机 Cindy 内产生的 token 消耗(#2785 维护者裁决)。+ 'usage',// 「工具密钥」(api-keys)已于 2026-07-13 下架:面板里最后一把 mivo key 随// XD Mivo 意识化改由意识设置页收单(官方别名映射同一存储键)。id 仍留在// SettingsTab 类型与 TAB_LABEL_KEY 保留,供旧深链重定向到插件分区。@@ -58,6 +62,7 @@ export type VisibleSettingsTab = (typeof TAB_IDS)[number];export const TAB_LABEL_KEY: Record<SettingsTab, string> = {general: 'settings.tabs.general',billing: 'settings.tabs.billing',+ usage: 'settings.tabs.usage',personalization: 'settings.tabs.personalization','api-keys': 'settings.tabs.apiKeys','voice-input': 'settings.tabs.voiceInput',