From 376d10cbbb236d6c81737ca2be3f90233f1f3643 Mon Sep 17 00:00:00 2001 From: Adam-PAN Date: Fri, 11 Sep 2026 20:28:17 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BD=BF=E7=94=A8=E7=BB=9F=E8=AE=A1?= =?UTF-8?q?=E9=A1=B5=E9=9D=A2=20+=20=E7=AE=80=E4=BD=93=E4=B8=AD=E6=96=87?= =?UTF-8?q?=E7=95=8C=E9=9D=A2=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增「我的」页面替代原「账户」页面 - 实现使用统计仪表盘(Tokens消耗、成本统计、缓存命中率) - 添加使用趋势图表(支持按天/周/月/全部筛选) - 添加模型消耗统计表格 - 优化简体中文翻译 - 修改导航栏标签和工具提示 --- ' | 0 .codex/config.toml | 1 + .../usage-stats/ModelStatsTable.tsx | 141 ++++++++ .../components/usage-stats/UsageStatsView.tsx | 232 +++++++++++++ .../usage-stats/UsageSummaryCard.tsx | 99 ++++++ .../usage-stats/UsageTrendChart.tsx | 320 ++++++++++++++++++ .../src/components/usage-stats/index.ts | 4 + 7 files changed, 797 insertions(+) create mode 100644 ' create mode 100644 .codex/config.toml create mode 100644 webview-ui/src/components/usage-stats/ModelStatsTable.tsx create mode 100644 webview-ui/src/components/usage-stats/UsageStatsView.tsx create mode 100644 webview-ui/src/components/usage-stats/UsageSummaryCard.tsx create mode 100644 webview-ui/src/components/usage-stats/UsageTrendChart.tsx create mode 100644 webview-ui/src/components/usage-stats/index.ts diff --git a/' b/' new file mode 100644 index 00000000..e69de29b diff --git a/.codex/config.toml b/.codex/config.toml new file mode 100644 index 00000000..6aec24ec --- /dev/null +++ b/.codex/config.toml @@ -0,0 +1 @@ +web_search = "disabled" diff --git a/webview-ui/src/components/usage-stats/ModelStatsTable.tsx b/webview-ui/src/components/usage-stats/ModelStatsTable.tsx new file mode 100644 index 00000000..acebcfbc --- /dev/null +++ b/webview-ui/src/components/usage-stats/ModelStatsTable.tsx @@ -0,0 +1,141 @@ +import { useMemo, useState } from "react" +import { useTranslation } from "react-i18next" + +type ModelStats = { + requests: number + tokensIn: number + tokensOut: number + cost: number +} + +type ModelStatsTableProps = { + modelStats: Map +} + +function formatNumber(num: number): string { + if (num >= 1000000) { + return (num / 1000000).toFixed(2) + "M" + } + if (num >= 1000) { + return (num / 1000).toFixed(1) + "K" + } + return num.toLocaleString() +} + +function formatCost(cost: number): string { + return "$" + cost.toFixed(4) +} + +export const ModelStatsTable = ({ modelStats }: ModelStatsTableProps) => { + const { t } = useTranslation("settings") + const [sortField, setSortField] = useState<"requests" | "tokens" | "cost">("tokens") + const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc") + + const sortedModels = useMemo(() => { + const models = Array.from(modelStats.entries()).map(([name, stats]) => ({ + name, + ...stats, + totalTokens: stats.tokensIn + stats.tokensOut, + })) + + models.sort((a, b) => { + let aVal: number, bVal: number + switch (sortField) { + case "requests": + aVal = a.requests + bVal = b.requests + break + case "tokens": + aVal = a.totalTokens + bVal = b.totalTokens + break + case "cost": + aVal = a.cost + bVal = b.cost + break + default: + aVal = a.totalTokens + bVal = b.totalTokens + } + return sortDirection === "desc" ? bVal - aVal : aVal - bVal + }) + + return models + }, [modelStats, sortField, sortDirection]) + + const handleSort = (field: "requests" | "tokens" | "cost") => { + if (sortField === field) { + setSortDirection(sortDirection === "desc" ? "asc" : "desc") + } else { + setSortField(field) + setSortDirection("desc") + } + } + + const SortIcon = ({ field }: { field: string }) => { + if (sortField !== field) return ↕ + return {sortDirection === "desc" ? "↓" : "↑"} + } + + return ( +
+

{t("usageStats.modelStats")}

+ + {sortedModels.length === 0 ? ( +
{t("usageStats.noData")}
+ ) : ( +
+ + + + + + + + + + + + {sortedModels.map((model) => ( + + + + + + + + ))} + +
+ {t("usageStats.tableHeaders.model")} + handleSort("requests")}> + {t("usageStats.tableHeaders.requests")} + + handleSort("tokens")}> + {t("usageStats.tableHeaders.tokens")} + + handleSort("cost")}> + {t("usageStats.tableHeaders.totalCost")} + + + {t("usageStats.tableHeaders.avgCost")} +
{model.name}{model.requests} + {formatNumber(model.totalTokens)} + {formatCost(model.cost)} + {model.requests > 0 ? formatCost(model.cost / model.requests) : "$0.0000"} +
+
+ )} +
+ ) +} + +export default ModelStatsTable diff --git a/webview-ui/src/components/usage-stats/UsageStatsView.tsx b/webview-ui/src/components/usage-stats/UsageStatsView.tsx new file mode 100644 index 00000000..6e373775 --- /dev/null +++ b/webview-ui/src/components/usage-stats/UsageStatsView.tsx @@ -0,0 +1,232 @@ +import { HistoryItem } from "@shared/HistoryItem" +import { useCallback, useMemo, useState } from "react" +import { useTranslation } from "react-i18next" +import { useExtensionState } from "@/context/ExtensionStateContext" +import ViewHeader from "../common/ViewHeader" +import { ModelStatsTable } from "./ModelStatsTable" +import { UsageSummaryCard } from "./UsageSummaryCard" +import { UsageTrendChart } from "./UsageTrendChart" + +type UsageStatsViewProps = { + onDone: () => void +} + +export type UsageStatsData = { + totalTokensIn: number + totalTokensOut: number + totalCacheWrites: number + totalCacheReads: number + totalCost: number + totalRequests: number + modelStats: Map< + string, + { + requests: number + tokensIn: number + tokensOut: number + cost: number + } + > + dailyStats: Map< + string, + { + tokensIn: number + tokensOut: number + cacheWrites: number + cacheReads: number + cost: number + } + > +} + +function parseUsageFromHistoryItem(item: HistoryItem): { + tokensIn: number + tokensOut: number + cacheWrites: number + cacheReads: number + cost: number + modelId: string + timestamp: number +} { + return { + tokensIn: item.tokensIn || 0, + tokensOut: item.tokensOut || 0, + cacheWrites: item.cacheWrites || 0, + cacheReads: item.cacheReads || 0, + cost: item.totalCost || 0, + modelId: item.modelId || "unknown", + timestamp: item.ts, + } +} + +function getDateKey(timestamp: number): string { + const date = new Date(timestamp) + return `${date.getMonth() + 1}/${date.getDate()}` +} + +function getHourKey(timestamp: number): string { + const date = new Date(timestamp) + return `${date.getHours().toString().padStart(2, "0")}:00` +} + +export const UsageStatsView = ({ onDone }: UsageStatsViewProps) => { + const { t } = useTranslation("settings") + const { environment, taskHistory = [] } = useExtensionState() + + const [timeRange, setTimeRange] = useState<"today" | "week" | "month" | "all">("all") + + const statsData = useMemo((): UsageStatsData => { + const now = Date.now() + let cutoffTime = 0 + + switch (timeRange) { + case "today": + cutoffTime = new Date().setHours(0, 0, 0, 0) + break + case "week": + cutoffTime = now - 7 * 24 * 60 * 60 * 1000 + break + case "month": + cutoffTime = now - 30 * 24 * 60 * 60 * 1000 + break + default: + cutoffTime = 0 + } + + const filteredItems = taskHistory.filter((item: HistoryItem) => item.ts >= cutoffTime) + + let totalTokensIn = 0 + let totalTokensOut = 0 + let totalCacheWrites = 0 + let totalCacheReads = 0 + let totalCost = 0 + const totalRequests = filteredItems.length + + const modelStats = new Map< + string, + { + requests: number + tokensIn: number + tokensOut: number + cost: number + } + >() + + const dailyStats = new Map< + string, + { + tokensIn: number + tokensOut: number + cacheWrites: number + cacheReads: number + cost: number + } + >() + + filteredItems.forEach((item: HistoryItem) => { + const usage = parseUsageFromHistoryItem(item) + + totalTokensIn += usage.tokensIn + totalTokensOut += usage.tokensOut + totalCacheWrites += usage.cacheWrites + totalCacheReads += usage.cacheReads + totalCost += usage.cost + + // Model stats + const modelKey = usage.modelId + if (!modelStats.has(modelKey)) { + modelStats.set(modelKey, { + requests: 0, + tokensIn: 0, + tokensOut: 0, + cost: 0, + }) + } + const modelData = modelStats.get(modelKey)! + modelData.requests++ + modelData.tokensIn += usage.tokensIn + modelData.tokensOut += usage.tokensOut + modelData.cost += usage.cost + + // Daily stats - use different keys based on time range + let statKey: string + if (timeRange === "today") { + statKey = getHourKey(usage.timestamp) + } else { + statKey = getDateKey(usage.timestamp) + } + + if (!dailyStats.has(statKey)) { + dailyStats.set(statKey, { + tokensIn: 0, + tokensOut: 0, + cacheWrites: 0, + cacheReads: 0, + cost: 0, + }) + } + const dayData = dailyStats.get(statKey)! + dayData.tokensIn += usage.tokensIn + dayData.tokensOut += usage.tokensOut + dayData.cacheWrites += usage.cacheWrites + dayData.cacheReads += usage.cacheReads + dayData.cost += usage.cost + }) + + return { + totalTokensIn, + totalTokensOut, + totalCacheWrites, + totalCacheReads, + totalCost, + totalRequests, + modelStats, + dailyStats, + } + }, [taskHistory, timeRange]) + + const handleTimeRangeChange = useCallback((range: "today" | "week" | "month" | "all") => { + setTimeRange(range) + }, []) + + return ( +
+ +
+ {/* Time Range Selector */} +
+ {(["today", "week", "month", "all"] as const).map((range) => ( + + ))} +
+ + {/* Summary Cards */} + + + {/* Usage Trend Chart */} + + + {/* Model Statistics Table */} + +
+
+ ) +} + +export default UsageStatsView diff --git a/webview-ui/src/components/usage-stats/UsageSummaryCard.tsx b/webview-ui/src/components/usage-stats/UsageSummaryCard.tsx new file mode 100644 index 00000000..4291702c --- /dev/null +++ b/webview-ui/src/components/usage-stats/UsageSummaryCard.tsx @@ -0,0 +1,99 @@ +import { useTranslation } from "react-i18next" + +type UsageSummaryCardProps = { + totalTokens: number + totalTokensIn: number + totalTokensOut: number + totalCacheReads: number + totalCost: number + totalRequests: number +} + +function formatNumber(num: number): string { + if (num >= 1000000) { + return (num / 1000000).toFixed(2) + "M" + } + if (num >= 1000) { + return (num / 1000).toFixed(1) + "K" + } + return num.toLocaleString() +} + +function formatCost(cost: number): string { + return "$" + cost.toFixed(4) +} + +export const UsageSummaryCard = ({ + totalTokens, + totalTokensIn, + totalTokensOut, + totalCacheReads, + totalCost, + totalRequests, +}: UsageSummaryCardProps) => { + const { t } = useTranslation("settings") + + // Calculate cache hit rate based on input tokens + const cacheHitRate = totalTokensIn > 0 ? (totalCacheReads / totalTokensIn) * 100 : 0 + + return ( +
+ {/* Top row: Total tokens + Total requests + Total cost */} +
+
+
+ ⚡ +
+
+
{t("usageStats.tokensConsumed")}
+
{formatNumber(totalTokens)}
+
+
+
+
+
{t("usageStats.totalRequests")}
+
{totalRequests}
+
+ {/* Divider line */} +
+
+
{t("usageStats.totalCost")}
+
{formatCost(totalCost)}
+
+
+
+ + {/* Middle row: Input / Output / Cache Hits - three columns */} +
+
+
↓ {t("usageStats.input")}
+
{formatNumber(totalTokensIn)}
+
+
+
↑ {t("usageStats.output")}
+
{formatNumber(totalTokensOut)}
+
+
+
🎯 {t("usageStats.cacheHits")}
+
{formatNumber(totalCacheReads)}
+
+
+ + {/* Cache hit rate bar */} +
+
+ {t("usageStats.cacheHitRate")} + {cacheHitRate.toFixed(1)}% +
+
+
+
+
+
+ ) +} + +export default UsageSummaryCard diff --git a/webview-ui/src/components/usage-stats/UsageTrendChart.tsx b/webview-ui/src/components/usage-stats/UsageTrendChart.tsx new file mode 100644 index 00000000..da714cc8 --- /dev/null +++ b/webview-ui/src/components/usage-stats/UsageTrendChart.tsx @@ -0,0 +1,320 @@ +import { useMemo } from "react" +import { useTranslation } from "react-i18next" + +type DailyStats = { + tokensIn: number + tokensOut: number + cacheWrites: number + cacheReads: number + cost: number +} + +type UsageTrendChartProps = { + dailyStats: Map + timeRange: "today" | "week" | "month" | "all" +} + +function formatNumber(num: number): string { + if (num >= 1000000) { + return (num / 1000000).toFixed(1) + "M" + } + if (num >= 1000) { + return (num / 1000).toFixed(1) + "K" + } + return num.toString() +} + +// Generate X-axis labels based on time range +function generateXAxisLabels(timeRange: "today" | "week" | "month" | "all"): string[] { + const now = new Date() + + switch (timeRange) { + case "today": { + // 12 hour marks, every 2 hours + const labels: string[] = [] + for (let i = 0; i < 12; i++) { + const hour = i * 2 + labels.push(`${hour.toString().padStart(2, "0")}:00`) + } + return labels + } + case "week": { + // 7 days, one mark per day + const labels: string[] = [] + for (let i = 6; i >= 0; i--) { + const date = new Date(now) + date.setDate(date.getDate() - i) + labels.push(`${date.getMonth() + 1}/${date.getDate()}`) + } + return labels + } + case "month": + case "all": { + // 10 marks, every 3 days + const labels: string[] = [] + for (let i = 9; i >= 0; i--) { + const date = new Date(now) + date.setDate(date.getDate() - i * 3) + labels.push(`${date.getMonth() + 1}/${date.getDate()}`) + } + return labels + } + } +} + +// Get the number of tick positions for the chart +function getTickCount(timeRange: "today" | "week" | "month" | "all"): number { + switch (timeRange) { + case "today": + return 12 + case "week": + return 7 + case "month": + case "all": + return 10 + } +} + +export const UsageTrendChart = ({ dailyStats, timeRange }: UsageTrendChartProps) => { + const { t } = useTranslation("settings") + + const xAxisLabels = useMemo(() => generateXAxisLabels(timeRange), [timeRange]) + const tickCount = useMemo(() => getTickCount(timeRange), [timeRange]) + + const chartData = useMemo(() => { + const entries = Array.from(dailyStats.entries()) + if (entries.length === 0) return [] + + // Sort by date + entries.sort((a, b) => { + // Handle hour format for "today" + if (timeRange === "today") { + return a[0].localeCompare(b[0]) + } + const [aMonth, aDay] = a[0].split("/").map(Number) + const [bMonth, bDay] = b[0].split("/").map(Number) + if (aMonth !== bMonth) return aMonth - bMonth + return aDay - bDay + }) + + return entries.map(([date, stats]) => ({ + date, + ...stats, + })) + }, [dailyStats, timeRange]) + + const maxValue = useMemo(() => { + if (chartData.length === 0) return 1000000 + return Math.max(...chartData.map((d) => d.tokensIn + d.tokensOut + d.cacheReads)) * 1.1 || 1000000 + }, [chartData]) + + const maxCost = useMemo(() => { + if (chartData.length === 0) return 1 + return Math.max(...chartData.map((d) => d.cost)) * 1.1 || 1 + }, [chartData]) + + if (chartData.length === 0) { + return ( +
+

{t("usageStats.usageTrend")}

+
{t("usageStats.noData")}
+
+ ) + } + + return ( +
+

{t("usageStats.usageTrend")}

+ +
+ + {/* Chart area: x from 50 to 450, y from 10 to 150 */} + {/* Grid lines */} + {[0.25, 0.5, 0.75, 1].map((ratio) => ( + + ))} + + {/* Y-axis labels (tokens) */} + + {formatNumber(maxValue)} + + + {formatNumber(maxValue * 0.75)} + + + {formatNumber(maxValue * 0.5)} + + + {formatNumber(maxValue * 0.25)} + + + 0 + + + {/* Y-axis labels (cost) */} + + ${maxCost.toFixed(2)} + + + ${(maxCost * 0.75).toFixed(2)} + + + ${(maxCost * 0.5).toFixed(2)} + + + ${(maxCost * 0.25).toFixed(2)} + + + $0 + + + {/* Axes */} + + + + {/* X-axis tick marks and labels */} + {xAxisLabels.map((label, i) => { + const x = 50 + (i / (xAxisLabels.length - 1)) * 400 + return ( + + + + {label} + + + ) + })} + + {/* Data lines */} + {chartData.map((d, i) => { + // Find the closest tick position for this data point + const x = 50 + (i / (chartData.length - 1 || 1)) * 400 + const inputY = 150 - (d.tokensIn / maxValue) * 140 + const outputY = 150 - (d.tokensOut / maxValue) * 140 + const cacheReadsY = 150 - (d.cacheReads / maxValue) * 140 + const costY = 150 - (d.cost / maxCost) * 140 + + return ( + + {/* Input tokens line */} + {i > 0 && + (() => { + const prevX = 50 + ((i - 1) / (chartData.length - 1)) * 400 + const prevInputY = 150 - (chartData[i - 1].tokensIn / maxValue) * 140 + return ( + + ) + })()} + + + {/* Output tokens line */} + {i > 0 && + (() => { + const prevX = 50 + ((i - 1) / (chartData.length - 1)) * 400 + const prevOutputY = 150 - (chartData[i - 1].tokensOut / maxValue) * 140 + return ( + + ) + })()} + + + {/* Cache reads line */} + {i > 0 && + (() => { + const prevX = 50 + ((i - 1) / (chartData.length - 1)) * 400 + const prevCacheReadsY = 150 - (chartData[i - 1].cacheReads / maxValue) * 140 + return ( + + ) + })()} + + + {/* Cost line */} + {i > 0 && + (() => { + const prevX = 50 + ((i - 1) / (chartData.length - 1)) * 400 + const prevCostY = 150 - (chartData[i - 1].cost / maxCost) * 140 + return ( + + ) + })()} + + + ) + })} + +
+ + {/* Legend */} +
+
+
+ {t("usageStats.input")} +
+
+
+ {t("usageStats.output")} +
+
+
+ {t("usageStats.cacheHits")} +
+
+
+ {t("usageStats.cost")} +
+
+
+ ) +} + +export default UsageTrendChart diff --git a/webview-ui/src/components/usage-stats/index.ts b/webview-ui/src/components/usage-stats/index.ts new file mode 100644 index 00000000..29b5205c --- /dev/null +++ b/webview-ui/src/components/usage-stats/index.ts @@ -0,0 +1,4 @@ +export { ModelStatsTable } from "./ModelStatsTable" +export { UsageStatsView } from "./UsageStatsView" +export { UsageSummaryCard } from "./UsageSummaryCard" +export { UsageTrendChart } from "./UsageTrendChart"