feat: 新增Token实时监控仪表盘

This commit is contained in:
thzxx
2026-04-23 16:00:13 +08:00
parent 684b2f773b
commit e96b2a840e
4 changed files with 466 additions and 0 deletions
+182
View File
@@ -0,0 +1,182 @@
/**
* TokenDashboard - Token 实时监控仪表盘
* 显示当前会话的 Token 消耗统计、趋势图和明细表
*/
import { state, KEYS } from '../state/state.js';
import { formatTime } from '../utils/utils.js';
import type { ChatSession, ChatMessage } from '../types.js';
let dashboardModalEl: HTMLElement;
let refreshTimer: ReturnType<typeof setInterval> | null = null;
/** 打开仪表盘 */
export function openTokenDashboard(): void {
if (!dashboardModalEl) return;
dashboardModalEl.style.display = '';
renderDashboard();
startAutoRefresh();
}
/** 关闭仪表盘 */
export function closeTokenDashboard(): void {
if (!dashboardModalEl) return;
dashboardModalEl.style.display = 'none';
stopAutoRefresh();
}
/** 初始化 */
export function initTokenDashboard(): void {
dashboardModalEl = document.querySelector('#tokenDashboardModal')!;
document.querySelector('#btnTokenDashboard')!.addEventListener('click', openTokenDashboard);
document.querySelector('#btnCloseTokenDashboard')!.addEventListener('click', closeTokenDashboard);
dashboardModalEl.addEventListener('click', (e) => {
if (e.target === dashboardModalEl) closeTokenDashboard();
});
}
function startAutoRefresh(): void {
stopAutoRefresh();
refreshTimer = setInterval(() => renderDashboard(), 2000);
}
function stopAutoRefresh(): void {
if (refreshTimer) {
clearInterval(refreshTimer);
refreshTimer = null;
}
}
interface RoundData {
round: number;
role: string;
eval_count: number;
total_duration: number;
timestamp: number;
model?: string;
}
function collectRoundData(messages: ChatMessage[]): RoundData[] {
const rounds: RoundData[] = [];
let roundNum = 0;
for (const msg of messages) {
if (msg.role === 'assistant' && (msg.eval_count || msg.total_duration)) {
roundNum++;
rounds.push({
round: roundNum,
role: msg.role,
eval_count: msg.eval_count || 0,
total_duration: msg.total_duration || 0,
timestamp: msg.timestamp,
model: msg.model,
});
}
}
return rounds;
}
function formatDuration(ns: number): string {
if (!ns) return '-';
const ms = ns / 1_000_000;
if (ms < 1000) return `${Math.round(ms)}ms`;
const s = ms / 1000;
if (s < 60) return `${s.toFixed(1)}s`;
const m = Math.floor(s / 60);
const rem = (s % 60).toFixed(0);
return `${m}m${rem}s`;
}
function formatTokenCount(n: number): string {
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
return String(n);
}
function renderDashboard(): void {
const session = state.get<ChatSession | null>(KEYS.CURRENT_SESSION);
const messages = session?.messages || [];
const userMsgs = messages.filter(m => m.role === 'user');
const aiMsgs = messages.filter(m => m.role === 'assistant');
const rounds = collectRoundData(messages);
const totalTokens = rounds.reduce((sum, r) => sum + r.eval_count, 0);
const totalDurationNs = rounds.reduce((sum, r) => sum + r.total_duration, 0);
const avgTokens = rounds.length > 0 ? Math.round(totalTokens / rounds.length) : 0;
// A. 概览区域
const overviewEl = dashboardModalEl.querySelector('#tdOverview')!;
overviewEl.innerHTML = `
<div class="td-stat-card">
<div class="td-stat-icon">🔥</div>
<div class="td-stat-value">${formatTokenCount(totalTokens)}</div>
<div class="td-stat-label">总 Token 消耗</div>
</div>
<div class="td-stat-card">
<div class="td-stat-icon">💬</div>
<div class="td-stat-value">${userMsgs.length} / ${aiMsgs.length}</div>
<div class="td-stat-label">用户 / AI 消息</div>
</div>
<div class="td-stat-card">
<div class="td-stat-icon">📊</div>
<div class="td-stat-value">${formatTokenCount(avgTokens)}</div>
<div class="td-stat-label">平均 Token/轮</div>
</div>
<div class="td-stat-card">
<div class="td-stat-icon">⏱️</div>
<div class="td-stat-value">${formatDuration(totalDurationNs)}</div>
<div class="td-stat-label">总推理耗时</div>
</div>
`;
// B. 柱状图
const chartEl = dashboardModalEl.querySelector('#tdChart')!;
if (rounds.length === 0) {
chartEl.innerHTML = '<div class="td-empty">暂无数据,发送消息后开始统计</div>';
} else {
const maxTokens = Math.max(...rounds.map(r => r.eval_count), 1);
const barsHtml = rounds.map(r => {
const heightPct = Math.max((r.eval_count / maxTokens) * 100, 2);
const tooltip = `${r.round}轮 · ${formatTokenCount(r.eval_count)} tokens · ${formatDuration(r.total_duration)}`;
return `
<div class="td-bar-col" title="${tooltip}">
<div class="td-bar-value">${formatTokenCount(r.eval_count)}</div>
<div class="td-bar" style="height:${heightPct}%;">
<div class="td-bar-fill"></div>
</div>
<div class="td-bar-label">R${r.round}</div>
</div>
`;
}).join('');
chartEl.innerHTML = `
<div class="td-chart-container">
<div class="td-chart-y-axis">
<span>${formatTokenCount(maxTokens)}</span>
<span>${formatTokenCount(Math.round(maxTokens / 2))}</span>
<span>0</span>
</div>
<div class="td-chart-bars">${barsHtml}</div>
</div>
`;
}
// C. 明细表格
const tableEl = dashboardModalEl.querySelector('#tdTableBody')!;
if (rounds.length === 0) {
tableEl.innerHTML = '<tr><td colspan="5" class="td-empty-row">暂无数据</td></tr>';
} else {
// 按时间倒序
const sorted = [...rounds].reverse();
tableEl.innerHTML = sorted.map(r => `
<tr>
<td>R${r.round}</td>
<td><span class="td-role-badge">🤖 AI</span>${r.model ? ` <span class="td-model-tag">${r.model}</span>` : ''}</td>
<td class="td-num">${formatTokenCount(r.eval_count)}</td>
<td class="td-num">${formatDuration(r.total_duration)}</td>
<td class="td-time">${r.timestamp ? formatTime(r.timestamp) : '-'}</td>
</tr>
`).join('');
}
}
+43
View File
@@ -57,6 +57,11 @@
<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>
</svg>
</button>
<button class="icon-btn" id="btnTokenDashboard" title="Token 监控">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="3" y="3" width="18" height="18" rx="2"/><line x1="7" y1="13" x2="7" y2="17"/><line x1="11" y1="9" x2="11" y2="17"/><line x1="15" y1="5" x2="15" y2="17"/>
</svg>
</button>
<button class="icon-btn" id="btnHistory" title="历史记录">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
@@ -638,6 +643,44 @@
</div>
</div>
<!-- ═══════════════ Token 监控仪表盘 ═══════════════ -->
<div class="modal-overlay" id="tokenDashboardModal" style="display:none;">
<div class="modal" style="max-width:860px;width:860px;">
<div class="modal-header">
<h3>📊 Token 实时监控</h3>
<button class="icon-btn" id="btnCloseTokenDashboard">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
</svg>
</button>
</div>
<div class="modal-body" style="max-height:75vh;overflow-y:auto;">
<div class="td-overview" id="tdOverview"></div>
<div class="td-section">
<div class="td-section-title">📈 Token 消耗趋势</div>
<div class="td-chart" id="tdChart"></div>
</div>
<div class="td-section">
<div class="td-section-title">📋 明细(按时间倒序)</div>
<div class="td-table-wrap">
<table class="td-table">
<thead>
<tr>
<th>轮次</th>
<th>角色</th>
<th>Token 数</th>
<th>耗时</th>
<th>时间</th>
</tr>
</thead>
<tbody id="tdTableBody"></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- ═══════════════ 图片预览 Lightbox ═══════════════ -->
<div class="lightbox-overlay" id="lightbox" style="display:none;">
<button class="lightbox-close" id="lightboxClose"></button>
+4
View File
@@ -21,6 +21,7 @@ import { initSettingsModal, closeSettingsModal } from './components/settings-mod
import { initHistoryModal, closeHistoryModal } from './components/history-modal.js';
import { initMemoryModal } from './components/memory-modal.js';
import { initToolsModal, closeToolsModal } from './components/tools-modal.js';
import { initTokenDashboard, closeTokenDashboard } from './components/token-dashboard.js';
import { initMemoryManager } from './services/memory-manager.js';
import { restoreHeartbeat } from './components/settings-modal.js';
import { restoreCronTasks } from './services/cron-manager.js';
@@ -331,6 +332,7 @@ async function init(): Promise<void> {
initToolConfirmModal();
initMemoryModal();
initToolsModal();
initTokenDashboard();
initWorkspacePanel();
setupDesktopIntegration();
@@ -433,6 +435,7 @@ async function init(): Promise<void> {
initToolConfirmModal();
initMemoryModal();
initToolsModal();
initTokenDashboard();
initWorkspacePanel();
setupDesktopIntegration();
checkConnection().then(loadModels);
@@ -450,6 +453,7 @@ function bindGlobalEvents(): void {
closeHistoryModal();
closeLightbox();
closeToolsModal();
closeTokenDashboard();
(document.querySelector('#helpModal') as HTMLElement).style.display = 'none';
(document.querySelector('#memoryModal') as HTMLElement).style.display = 'none';
}
+237
View File
@@ -3468,3 +3468,240 @@ html, body {
margin-bottom: 6px;
font-size: 12px;
}
/* ═══════════════════════════════════════════════════════
Token 监控仪表盘
═══════════════════════════════════════════════════════ */
/* 概览卡片组 */
.td-overview {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
margin-bottom: 20px;
}
.td-stat-card {
background: var(--bg-card);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-md);
padding: 16px 14px;
text-align: center;
box-shadow: var(--shadow-card);
transition: var(--transition);
}
.td-stat-card:hover {
box-shadow: var(--shadow-flyout);
transform: translateY(-1px);
}
.td-stat-icon {
font-size: 22px;
margin-bottom: 6px;
}
.td-stat-value {
font-size: 24px;
font-weight: 700;
color: var(--accent);
font-family: var(--font-mono);
line-height: 1.2;
}
.td-stat-label {
font-size: 11px;
color: var(--text-secondary);
margin-top: 4px;
font-weight: 500;
}
/* 区块标题 */
.td-section {
margin-bottom: 20px;
}
.td-section-title {
font-size: 13px;
font-weight: 600;
color: var(--text-primary);
margin-bottom: 10px;
padding-bottom: 6px;
border-bottom: 1px solid var(--border-subtle);
}
/* 柱状图 */
.td-chart {
background: var(--bg-card);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-md);
padding: 16px;
box-shadow: var(--shadow-card);
min-height: 180px;
}
.td-chart-container {
display: flex;
gap: 8px;
height: 180px;
}
.td-chart-y-axis {
display: flex;
flex-direction: column;
justify-content: space-between;
font-size: 10px;
color: var(--text-tertiary);
font-family: var(--font-mono);
padding: 2px 0;
min-width: 36px;
text-align: right;
}
.td-chart-bars {
flex: 1;
display: flex;
align-items: flex-end;
gap: 6px;
border-left: 1px solid var(--border-subtle);
border-bottom: 1px solid var(--border-subtle);
padding: 0 8px 0 4px;
overflow-x: auto;
}
.td-bar-col {
display: flex;
flex-direction: column;
align-items: center;
flex: 1;
min-width: 36px;
max-width: 60px;
cursor: default;
}
.td-bar-value {
font-size: 9px;
font-family: var(--font-mono);
color: var(--text-secondary);
margin-bottom: 2px;
white-space: nowrap;
}
.td-bar {
width: 100%;
border-radius: 4px 4px 0 0;
overflow: hidden;
position: relative;
min-height: 2px;
}
.td-bar-fill {
width: 100%;
height: 100%;
background: linear-gradient(180deg, #E8734A 0%, #F0976E 100%);
border-radius: 4px 4px 0 0;
transition: height 0.3s ease;
}
.td-bar-label {
font-size: 10px;
color: var(--text-tertiary);
margin-top: 4px;
font-family: var(--font-mono);
}
.td-bar-col:hover .td-bar-fill {
background: linear-gradient(180deg, #D4623A 0%, #E8734A 100%);
}
/* 空状态 */
.td-empty {
text-align: center;
padding: 40px 20px;
color: var(--text-tertiary);
font-size: 13px;
}
/* 明细表格 */
.td-table-wrap {
background: var(--bg-card);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-md);
box-shadow: var(--shadow-card);
max-height: 260px;
overflow-y: auto;
}
.td-table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
.td-table thead {
position: sticky;
top: 0;
z-index: 1;
}
.td-table th {
background: var(--bg-layer);
color: var(--text-secondary);
font-weight: 600;
text-align: left;
padding: 8px 12px;
border-bottom: 1px solid var(--border-subtle);
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.3px;
}
.td-table td {
padding: 7px 12px;
border-bottom: 1px solid var(--border-subtle);
color: var(--text-primary);
}
.td-table tr:last-child td {
border-bottom: none;
}
.td-table tr:hover td {
background: var(--bg-card-hover);
}
.td-num {
font-family: var(--font-mono);
font-weight: 500;
text-align: right;
}
.td-time {
font-size: 11px;
color: var(--text-secondary);
}
.td-role-badge {
font-size: 11px;
}
.td-model-tag {
font-size: 10px;
color: var(--text-tertiary);
background: var(--bg-layer);
padding: 1px 5px;
border-radius: 4px;
}
.td-empty-row {
text-align: center;
color: var(--text-tertiary);
padding: 24px !important;
}
/* 响应式 */
@media (max-width: 900px) {
.td-overview {
grid-template-columns: repeat(2, 1fr);
}
}