// ==UserScript==
// @name DeepSeek 开放平台 - 缓存命中率统计面板 (多Key版 v4)
// @namespace https://platform.deepseek.com
// @version 4.0.0
// @description 通过拦截/api/v0/usage/by_api_key/amount与/cost接口自动识别所有API Key并获取平台真实费用;支持近7天/近30天/本月/上月/自定义时间范围查看缓存命中率、Token数量及预估费用;支持全部Key合计;含汇总表格与CSV导出(可一键清除旧版default残留数据)
// @author You
// @match https://platform.deepseek.com/*
// @icon https://platform.deepseek.com/favicon.ico
// @grant none
// @run-at document-idle
// @license MIT
// ==/UserScript==
(function () {
'use strict';
// ==================== 全局防重复执行锁 ====================
if (window.__DS_CACHE_STATS_INITIALIZED__) {
console.log('[DS-Cache-Stats] 脚本已初始化,跳过重复执行');
return;
}
window.__DS_CACHE_STATS_INITIALIZED__ = true;
// ==================== 配置 ====================
const CONFIG = {
STORAGE_PREFIX: 'ds_cache_stats_v3_',
KEY_META_STORAGE_KEY: 'ds_cache_stats_v4_key_meta',
PERIOD_STORAGE_KEY: 'ds_cache_stats_v4_period',
CUSTOM_PERIOD_STORAGE_KEY: 'ds_cache_stats_v4_custom_period',
USAGE_ENDPOINT_MATCH: '/api/v0/usage/amount',
API_KEYS_ENDPOINT: '/api/v0/users/get_api_keys',
DATA_RETENTION_DAYS: 90,
REFRESH_INTERVAL: 5000,
DEBUG: false,
PANEL_DEFAULT_TOP: 120,
PANEL_DEFAULT_RIGHT: 20,
// DeepSeek V4 Pro 定价 (元/百万tokens)
PRICING: {
inputCacheHit: 0.025,
inputCacheMiss: 3,
output: 6
}
};
// ==================== v4.2 新增:时间段定义 ====================
const PERIODS = {
'7d': '近7天',
'30d': '近30天',
'month': '本月',
'lastMonth': '上月',
'custom': '自定义'
};
const PERIOD_ORDER = ['7d', '30d', 'month', 'lastMonth', 'custom'];
// v5.1:下拉框「全部 Key 合计」的特殊 groupId
const ALL_KEYS_ID = '__all__';
// ==================== 工具函数 ====================
const logger = {
log: (...args) => CONFIG.DEBUG && console.log('[DS-Cache-Stats]', ...args),
warn: (...args) => console.warn('[DS-Cache-Stats]', ...args),
error: (...args) => console.error('[DS-Cache-Stats]', ...args),
};
function formatDateStr(d) {
return d.getFullYear() + '-' +
String(d.getMonth() + 1).padStart(2, '0') + '-' +
String(d.getDate()).padStart(2, '0');
}
function getTodayStr() {
return formatDateStr(new Date());
}
function addDays(d, days) {
const r = new Date(d);
r.setDate(r.getDate() + days);
return r;
}
function formatNumber(num) {
if (num == null || isNaN(num)) return '0';
return Number(num).toLocaleString('en-US');
}
function formatPercent(rate) {
if (rate == null || isNaN(rate)) return '0.00%';
return rate.toFixed(2) + '%';
}
function formatCurrency(num) {
if (num == null || isNaN(num)) return '¥0.00';
return '¥' + num.toFixed(2);
}
function escapeHtml(str) {
return String(str).replace(/[&<>"']/g, c => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
}[c]));
}
function truncateKey(id, len = 16) {
if (!id) return '';
return id.length > len ? id.substring(0, len) + '…' : id;
}
function safeGet(obj, path, defaultValue = null) {
const keys = path.split('.');
let current = obj;
for (const key of keys) {
if (current == null || typeof current !== 'object') return defaultValue;
current = current[key];
}
return current != null ? current : defaultValue;
}
function calcHitRate(hit, miss) {
const total = hit + miss;
if (total <= 0) return 0;
return (hit / total) * 100;
}
function calcCost(hit, miss, output) {
return (hit / 1e6 * CONFIG.PRICING.inputCacheHit) +
(miss / 1e6 * CONFIG.PRICING.inputCacheMiss) +
(output / 1e6 * CONFIG.PRICING.output);
}
// ==================== v4.2 新增:时间段状态(localStorage 持久化) ====================
function getCurrentPeriod() {
const p = localStorage.getItem(CONFIG.PERIOD_STORAGE_KEY);
return PERIODS[p] ? p : '7d';
}
function setCurrentPeriod(period) {
if (PERIODS[period]) localStorage.setItem(CONFIG.PERIOD_STORAGE_KEY, period);
}
function getCustomPeriod() {
try {
return JSON.parse(localStorage.getItem(CONFIG.CUSTOM_PERIOD_STORAGE_KEY) || 'null');
} catch (e) {
return null;
}
}
function setCustomPeriod(start, end) {
if (!start || !end) return;
if (start > end) [start, end] = [end, start];
try {
localStorage.setItem(CONFIG.CUSTOM_PERIOD_STORAGE_KEY, JSON.stringify({ start, end }));
} catch (e) {}
}
// 计算某时间段对应的起止日期(Date 对象)
function getPeriodRange(period) {
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
switch (period) {
case '7d':
return { start: addDays(today, -6), end: today };
case '30d':
return { start: addDays(today, -29), end: today };
case 'month':
return { start: new Date(now.getFullYear(), now.getMonth(), 1), end: today };
case 'lastMonth':
return {
start: new Date(now.getFullYear(), now.getMonth() - 1, 1),
end: new Date(now.getFullYear(), now.getMonth(), 0)
};
case 'custom': {
const c = getCustomPeriod();
if (c && c.start && c.end) {
return { start: new Date(c.start), end: new Date(c.end) };
}
// 未设置过自定义范围时,默认近30天
return { start: addDays(today, -29), end: today };
}
default:
return { start: addDays(today, -6), end: today };
}
}
// 返回起止日期字符串
function getPeriodRangeStr(period) {
const r = getPeriodRange(period);
return { start: formatDateStr(r.start), end: formatDateStr(r.end) };
}
// ==================== 数据存储(按 groupId 分组) ====================
const Storage = {
_makeKey(groupId, dateStr) {
return CONFIG.STORAGE_PREFIX + groupId + '_' + dateStr;
},
getAllData() {
try {
const data = {};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith(CONFIG.STORAGE_PREFIX)) {
const rest = key.substring(CONFIG.STORAGE_PREFIX.length);
const lastUnderscoreIndex = rest.lastIndexOf('_');
if (lastUnderscoreIndex > 0) {
const dateStr = rest.substring(lastUnderscoreIndex + 1);
const groupId = rest.substring(0, lastUnderscoreIndex);
if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
const value = localStorage.getItem(key);
if (value) {
try {
if (!data[groupId]) data[groupId] = {};
data[groupId][dateStr] = JSON.parse(value);
} catch (e) {}
}
}
}
}
}
return data;
} catch (e) {
logger.error('读取localStorage失败:', e);
return {};
}
},
saveDayData(groupId, dateStr, newData) {
if (!groupId || !dateStr || !/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) return;
try {
const key = this._makeKey(groupId, dateStr);
const existing = localStorage.getItem(key);
let merged = newData;
if (existing) {
try {
const existingData = JSON.parse(existing);
merged = {
inputCacheHit: Math.max(safeGet(existingData, 'inputCacheHit', 0), safeGet(newData, 'inputCacheHit', 0)),
inputCacheMiss: Math.max(safeGet(existingData, 'inputCacheMiss', 0), safeGet(newData, 'inputCacheMiss', 0)),
outputTokens: Math.max(safeGet(existingData, 'outputTokens', 0), safeGet(newData, 'outputTokens', 0)),
// v5.2:保留已写入的真实费用(cost 接口单独写入)
cost: Math.max(safeGet(existingData, 'cost', 0), safeGet(newData, 'cost', 0)),
lastUpdated: newData.lastUpdated || Date.now(),
};
} catch (e) { merged = newData; }
}
localStorage.setItem(key, JSON.stringify(merged));
logger.log(`保存数据 [${groupId}] ${dateStr}:`, merged);
} catch (e) {
logger.error('保存数据失败:', e);
}
},
// v5.2:保存平台真实费用(元),cost 接口返回累计值,取最大防回退
saveDayCost(groupId, dateStr, cost) {
if (!groupId || !dateStr || !/^\d{4}-\d{2}-\d{2}$/.test(dateStr) || !(cost > 0)) return;
try {
const key = this._makeKey(groupId, dateStr);
const existing = localStorage.getItem(key);
if (!existing) {
localStorage.setItem(key, JSON.stringify({
inputCacheHit: 0, inputCacheMiss: 0, outputTokens: 0,
cost, lastUpdated: Date.now()
}));
return;
}
const d = JSON.parse(existing);
d.cost = Math.max(Number(safeGet(d, 'cost', 0)), cost);
d.lastUpdated = Date.now();
localStorage.setItem(key, JSON.stringify(d));
} catch (e) {
logger.error('保存费用失败:', e);
}
},
getAllGroupIds() {
return Object.keys(this.getAllData());
},
// v4.2:按起止日期统计任意时间段(含首尾);v5.2:费用优先真实 cost,无则估算
getPeriodSummary(groupId, startDateStr, endDateStr) {
const allData = this.getAllData();
const groupData = allData[groupId] || {};
let inputCacheHit = 0, inputCacheMiss = 0, outputTokens = 0, cost = 0, hasCost = false;
for (const [dateStr, dayData] of Object.entries(groupData)) {
if (dateStr >= startDateStr && dateStr <= endDateStr) {
inputCacheHit += safeGet(dayData, 'inputCacheHit', 0);
inputCacheMiss += safeGet(dayData, 'inputCacheMiss', 0);
outputTokens += safeGet(dayData, 'outputTokens', 0);
const c = safeGet(dayData, 'cost', null);
if (c != null) {
cost += Number(c);
hasCost = true;
}
}
}
return {
inputCacheHit,
inputCacheMiss,
outputTokens,
totalInput: inputCacheHit + inputCacheMiss,
cacheHitRate: calcHitRate(inputCacheHit, inputCacheMiss),
estimatedCost: hasCost ? cost : calcCost(inputCacheHit, inputCacheMiss, outputTokens)
};
},
cleanup() {
try {
const cutoff = new Date();
cutoff.setDate(cutoff.getDate() - CONFIG.DATA_RETENTION_DAYS);
const cutoffStr = cutoff.toISOString().split('T')[0];
const keysToRemove = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith(CONFIG.STORAGE_PREFIX)) {
const rest = key.substring(CONFIG.STORAGE_PREFIX.length);
const lastUnderscoreIndex = rest.lastIndexOf('_');
if (lastUnderscoreIndex > 0) {
const dateStr = rest.substring(lastUnderscoreIndex + 1);
if (dateStr < cutoffStr) keysToRemove.push(key);
}
}
}
keysToRemove.forEach(k => localStorage.removeItem(k));
if (keysToRemove.length > 0) logger.log('清理过期数据:', keysToRemove.length);
} catch (e) { logger.error('清理数据失败:', e); }
},
};
// ==================== v5.1:全部 Key 合计 ====================
// 汇总所有具体 Key 在所选时间段的数据(排除 default 历史兜底数据)
function getTotalSummary(startDateStr, endDateStr) {
const groupIds = getAllDisplayGroupIds().filter(id => id !== 'default' && id !== ALL_KEYS_ID);
let hit = 0, miss = 0, output = 0, costSum = 0;
groupIds.forEach(id => {
const s = Storage.getPeriodSummary(id, startDateStr, endDateStr);
hit += s.inputCacheHit;
miss += s.inputCacheMiss;
output += s.outputTokens;
// v5.2:费用直接累加各 Key 的(真实 cost 或估算),保持口径一致
costSum += s.estimatedCost;
});
return {
inputCacheHit: hit,
inputCacheMiss: miss,
outputTokens: output,
totalInput: hit + miss,
cacheHitRate: calcHitRate(hit, miss),
estimatedCost: costSum
};
}
// ==================== v4.1:API Key 元数据(从 get_api_keys 接口获取) ====================
const KeyMeta = {
getAll() {
try {
return JSON.parse(localStorage.getItem(CONFIG.KEY_META_STORAGE_KEY) || '{}');
} catch (e) {
return {};
}
},
save(keys) {
if (!Array.isArray(keys) || keys.length === 0) return {};
const meta = this.getAll();
let changed = false;
keys.forEach(k => {
if (!k.tracking_id) return;
const existing = meta[k.tracking_id];
const next = {
name: k.name || k.tracking_id,
sensitive_id: k.sensitive_id || '',
created_at: k.created_at || null,
last_use: k.last_use || null,
};
if (!existing ||
existing.name !== next.name ||
existing.sensitive_id !== next.sensitive_id ||
existing.last_use !== next.last_use) {
meta[k.tracking_id] = next;
changed = true;
}
});
if (changed) {
try { localStorage.setItem(CONFIG.KEY_META_STORAGE_KEY, JSON.stringify(meta)); } catch (e) {}
}
return meta;
},
// 显示名称:优先用 Key 名称,找不到则用 tracking_id 前 8 位
displayName(groupId) {
if (!groupId || groupId === 'default') return 'default';
const m = this.getAll()[groupId];
if (m && m.name) return m.name;
return groupId.length > 8 ? groupId.substring(0, 8) + '…' : groupId;
},
};
// ==================== API 拦截 ====================
// v5.0:匹配 usage/by_api_key/amount(新)与 usage/amount(旧)
function isUsageUrl(url) {
return typeof url === 'string' && /\/usage\/(?:by_api_key\/)?amount/.test(url);
}
// v5.2:匹配费用接口 usage/by_api_key/cost
function isCostUrl(url) {
return typeof url === 'string' && /\/usage\/(?:by_api_key\/)?cost/.test(url);
}
function isApiKeysUrl(url) {
return typeof url === 'string' && url.includes('users/get_api_keys');
}
// 从 usage 接口 URL 中解析 groupId(v4.2.1:扩展参数名并返回来源,便于调试)
function resolveGroupId(url) {
let groupId = 'default';
let source = 'none';
try {
const urlObj = new URL(url, location.origin);
const candidates = ['group_id', 'api_key_id', 'api_key', 'key_id', 'apikey_id', 'tracking_id', 'id'];
for (const name of candidates) {
const v = urlObj.searchParams.get(name);
if (v) {
groupId = v;
source = name;
break;
}
}
} catch (e) {}
return { groupId, source };
}
// v4.2.1:最近一次用量接口解析结果(用于面板调试显示)
let lastDebug = null;
function updateDebugInfo() {
const el = document.getElementById('ds-stats-debug');
if (!el) return;
if (!lastDebug) {
el.textContent = '';
el.title = '';
return;
}
let text, title;
if (lastDebug.costUpdated) {
text = `已更新真实费用:${lastDebug.costUpdated} 天`;
title = `最近一次费用请求:\n${lastDebug.url}\n已写入平台真实费用(元)\n解析时间: ${lastDebug.time}`;
} else if (lastDebug.seriesCount > 0) {
text = `已解析 by_api_key 数据(${lastDebug.seriesCount} 个序列)`;
title = `最近一次用量请求:\n${lastDebug.url}\n数据自带 Key 信息,按 tracking_id 分组存储\n解析时间: ${lastDebug.time}`;
} else {
const name = KeyMeta.displayName(lastDebug.groupId);
const hint = lastDebug.hasDays
? '已解析 days 结构数据'
: (lastDebug.groupId === 'default' && lastDebug.source === 'none'
? '未识别到用量数据'
: `来自参数 ${lastDebug.source}`);
text = `解析: ${name} · ${hint}`;
title = `最近一次用量请求:\n${lastDebug.url}\n解析出的 Key: ${name}\n${hint}\n解析时间: ${lastDebug.time}`;
}
el.textContent = text;
el.title = title;
}
function parseApiResponse(responseData, groupId = 'default', groupSource = 'none', requestUrl = '') {
const biz = safeGet(responseData, 'data.biz_data', {}) || {};
const series = Array.isArray(biz.series) ? biz.series : [];
const days = Array.isArray(biz.days) ? biz.days : [];
// 无论解析是否成功都记录调试信息,便于定位关联失败
lastDebug = {
groupId,
source: groupSource,
url: requestUrl || '',
time: new Date().toLocaleTimeString('zh-CN'),
seriesCount: series.length,
hasDays: days.length > 0,
};
updateDebugInfo();
// v5.0:新结构 usage/by_api_key/amount(series 数据自带 Key 信息)
if (series.length > 0) {
parseSeriesData(series);
return;
}
// 旧结构兼容(usage/amount → days)
if (days.length === 0) return;
days.forEach(day => {
const dateStr = day.date;
let hit = 0, miss = 0, output = 0;
if (Array.isArray(day.data)) {
day.data.forEach(modelUsage => {
if (Array.isArray(modelUsage.usage)) {
modelUsage.usage.forEach(u => {
const amount = Number(u.amount || 0);
switch (u.type) {
case 'PROMPT_CACHE_HIT_TOKEN':
hit += amount;
break;
case 'PROMPT_CACHE_MISS_TOKEN':
miss += amount;
break;
case 'RESPONSE_TOKEN':
output += amount;
break;
}
});
}
});
}
if (hit > 0 || miss > 0 || output > 0) {
Storage.saveDayData(groupId, dateStr, {
inputCacheHit: hit,
inputCacheMiss: miss,
outputTokens: output,
lastUpdated: Date.now(),
});
}
});
logger.log(`API 数据已解析 [${groupId}],共 ${days.length} 天`);
updatePanel();
}
// v5.0:解析 usage/by_api_key/amount 新结构
// series[] 每项 = { api_key: {tracking_id, name, sensitive_id, valid}, model, buckets: [{time, usage: {RESPONSE_TOKEN, REQUEST, PROMPT_CACHE_HIT_TOKEN, PROMPT_CACHE_MISS_TOKEN}}] }
function parseSeriesData(series) {
const keyMetaMap = {};
// 同一 Key 会按模型拆成多条 series,先按 (trackingId, dateStr) 在本次响应内聚合求和
const agg = {};
series.forEach(item => {
const apiKey = item.api_key || {};
const trackingId = apiKey.tracking_id;
if (!trackingId) return;
// 同步 Key 名称/脱敏ID(series 自带,无需单独请求 get_api_keys)
keyMetaMap[trackingId] = {
name: apiKey.name || trackingId,
sensitive_id: apiKey.sensitive_id || '',
};
const buckets = Array.isArray(item.buckets) ? item.buckets : [];
buckets.forEach(b => {
// time 为 UTC 0 点的时间戳(秒),桶按天切分
const dateStr = new Date(b.time * 1000).toISOString().slice(0, 10);
const usage = b.usage || {};
const hit = Number(usage.PROMPT_CACHE_HIT_TOKEN || 0);
const miss = Number(usage.PROMPT_CACHE_MISS_TOKEN || 0);
const output = Number(usage.RESPONSE_TOKEN || 0);
if (hit > 0 || miss > 0 || output > 0) {
const key = trackingId + '|' + dateStr;
if (!agg[key]) agg[key] = { hit: 0, miss: 0, output: 0 };
agg[key].hit += hit;
agg[key].miss += miss;
agg[key].output += output;
}
});
});
// 落库(跨请求仍由 saveDayData 的 Math.max 保证只增不减)
const dayKeys = Object.keys(agg);
dayKeys.forEach(k => {
const sep = k.indexOf('|');
const trackingId = k.substring(0, sep);
const dateStr = k.substring(sep + 1);
const v = agg[k];
Storage.saveDayData(trackingId, dateStr, {
inputCacheHit: v.hit,
inputCacheMiss: v.miss,
outputTokens: v.output,
lastUpdated: Date.now(),
});
});
// 保存 Key 元数据(名称映射)
KeyMeta.save(Object.entries(keyMetaMap).map(([tid, m]) => ({
tracking_id: tid,
name: m.name,
sensitive_id: m.sensitive_id,
})));
logger.log(`by_api_key 数据已解析:${Object.keys(keyMetaMap).length} 个 Key,${dayKeys.length} 个 Key×天记录`);
updatePanel();
}
// v5.2:解析 usage/by_api_key/cost 真实费用
// data.biz_data.data[] = [{currency, series: [{api_key, model, buckets: [{time, cost: "0.0185..."}]}]}]
function parseCostResponse(responseData, requestUrl = '') {
const data = safeGet(responseData, 'data.biz_data.data', []);
if (!Array.isArray(data) || data.length === 0) return;
let savedCount = 0;
data.forEach(currencyGroup => {
const series = Array.isArray(currencyGroup.series) ? currencyGroup.series : [];
series.forEach(item => {
const apiKey = item.api_key || {};
const trackingId = apiKey.tracking_id;
if (!trackingId) return;
(Array.isArray(item.buckets) ? item.buckets : []).forEach(b => {
const cost = Number(b.cost);
if (!(cost > 0)) return;
const dateStr = new Date(b.time * 1000).toISOString().slice(0, 10);
Storage.saveDayCost(trackingId, dateStr, cost);
savedCount++;
});
});
});
if (savedCount > 0) {
// v5.2.1:更新调试行,便于确认费用接口已拦截
lastDebug = {
groupId: 'default',
source: 'none',
url: requestUrl || '',
time: new Date().toLocaleTimeString('zh-CN'),
seriesCount: 0,
hasDays: false,
costUpdated: savedCount,
};
updateDebugInfo();
logger.log(`cost 数据已解析,更新 ${savedCount} 个有费用的天`);
updatePanel();
}
}
// v4.1:解析 get_api_keys 接口返回的 Key 列表
function parseApiKeysResponse(data) {
const keys = safeGet(data, 'data.biz_data.api_keys', []);
if (!Array.isArray(keys) || keys.length === 0) {
logger.warn('get_api_keys 返回空列表');
return;
}
KeyMeta.save(keys);
logger.log(`已识别 ${keys.length} 个 API Key`);
updatePanel();
}
// v4.1:初始化时主动拉取一次 Key 列表(失败静默,靠被动拦截兜底)
function fetchApiKeysOnce() {
try {
fetch(CONFIG.API_KEYS_ENDPOINT, {
method: 'GET',
credentials: 'include',
headers: { 'Accept': 'application/json' }
})
.then(r => r.json())
.then(parseApiKeysResponse)
.catch(() => {});
} catch (e) {}
}
function interceptFetch() {
const originalFetch = window.fetch;
window.fetch = async function (...args) {
const response = await originalFetch.apply(this, args);
try {
const url = args[0] instanceof Request ? args[0].url : args[0];
if (isUsageUrl(url)) {
const resolved = resolveGroupId(url);
const cloned = response.clone();
cloned.json().then(data => {
parseApiResponse(data, resolved.groupId, resolved.source, url);
}).catch(() => {});
} else if (isCostUrl(url)) {
const cloned = response.clone();
cloned.json().then(data => {
parseCostResponse(data, url);
}).catch(() => {});
} else if (isApiKeysUrl(url)) {
const cloned = response.clone();
cloned.json().then(data => {
parseApiKeysResponse(data);
}).catch(() => {});
}
} catch (e) {}
return response;
};
}
function interceptXHR() {
const OriginalXHR = window.XMLHttpRequest;
window.XMLHttpRequest = function () {
const xhr = new OriginalXHR();
let requestURL = '';
const originalOpen = xhr.open;
xhr.open = function (method, url, ...rest) {
requestURL = url;
return originalOpen.apply(this, [method, url, ...rest]);
};
const originalSend = xhr.send;
xhr.send = function (...args) {
xhr.addEventListener('load', function () {
if (!xhr.responseText) return;
try {
if (isUsageUrl(requestURL)) {
const resolved = resolveGroupId(requestURL);
parseApiResponse(JSON.parse(xhr.responseText), resolved.groupId, resolved.source, requestURL);
} else if (isCostUrl(requestURL)) {
parseCostResponse(JSON.parse(xhr.responseText), requestURL);
} else if (isApiKeysUrl(requestURL)) {
parseApiKeysResponse(JSON.parse(xhr.responseText));
}
} catch (e) {}
});
return originalSend.apply(this, args);
};
return xhr;
};
window.XMLHttpRequest.prototype = OriginalXHR.prototype;
for (const key in OriginalXHR) {
if (OriginalXHR.hasOwnProperty(key)) {
window.XMLHttpRequest[key] = OriginalXHR[key];
}
}
}
// ==================== UI 面板 ====================
let panelElement = null;
let panelMinimized = false;
let isDragging = false;
let dragStartX, dragStartY, panelStartRight, panelStartTop;
let panelCreationLock = false; // 面板创建互斥锁
function createPanel() {
if (panelCreationLock) {
logger.log('面板正在创建中,跳过重复请求');
return;
}
panelCreationLock = true;
try {
// 更彻底的旧面板清理
const existingPanels = document.querySelectorAll('#ds-cache-stats-panel');
if (existingPanels.length > 0) {
existingPanels.forEach(panel => {
const header = panel.querySelector('#ds-stats-header');
if (header) {
header.removeEventListener('mousedown', onDragStart);
header.removeEventListener('touchstart', onDragStart);
}
panel.remove();
});
logger.log(`已清理 ${existingPanels.length} 个旧面板`);
}
const periodBtns = PERIOD_ORDER.map(p =>
``
).join('');
const panel = document.createElement('div');
panel.id = 'ds-cache-stats-panel';
panel.dataset.version = '5.2.3';
panel.innerHTML = `
📊 近7天统计
✅ 缓存命中--tokens
❌ 缓存未命中--tokens
📤 输出--tokens
💰 预估费用--
🎯 命中率--
`;
panel.style.top = CONFIG.PANEL_DEFAULT_TOP + 'px';
panel.style.right = CONFIG.PANEL_DEFAULT_RIGHT + 'px';
document.body.appendChild(panel);
panelElement = panel;
bindPanelEvents();
populateGroupSelect();
logger.log('新面板创建成功');
} finally {
panelCreationLock = false;
}
}
// v4.1:下拉框选项 = 有数据的 groupId ∪ 已知 API Key 的 tracking_id
function getAllDisplayGroupIds() {
const dataIds = Storage.getAllGroupIds();
const keyIds = Object.keys(KeyMeta.getAll());
let ids = Array.from(new Set([...dataIds, ...keyIds]));
// 已识别具体 Key 且 default 无实际数据时,隐藏 default
if (keyIds.length > 0 && !dataIds.includes('default')) {
ids = ids.filter(id => id !== 'default');
}
if (ids.length === 0) ids = ['default'];
return ids;
}
function populateGroupSelect() {
const select = document.getElementById('ds-group-select');
if (!select) return;
const hasAnyData = Storage.getAllGroupIds().length > 0 || Object.keys(KeyMeta.getAll()).length > 0;
const groupIds = getAllDisplayGroupIds();
const currentVal = select.value;
select.innerHTML = '';
if (!hasAnyData) {
select.innerHTML = '';
return;
}
// v5.1:首选项 = 全部 Key 合计
const allOption = document.createElement('option');
allOption.value = ALL_KEYS_ID;
allOption.textContent = '全部 Key(合计)';
select.appendChild(allOption);
groupIds.forEach(id => {
const option = document.createElement('option');
option.value = id;
let label = KeyMeta.displayName(id);
// v5.2.2:default 有数据且已识别具体 Key 时,标记为历史残留
if (id === 'default' && Object.keys(KeyMeta.getAll()).length > 0) {
label = 'default(历史数据)';
}
option.textContent = label;
select.appendChild(option);
});
// v5.2.3 修复:currentVal 需包含「全部 Key(合计)」的 __all__,
// 否则每 5 秒 updatePanel 重建下拉框时,选中「全部 Key」会被重置为第一个具体 Key
const allIds = groupIds.concat(ALL_KEYS_ID);
if (allIds.includes(currentVal)) {
select.value = currentVal;
} else {
select.value = ALL_KEYS_ID; // 默认「全部 Key(合计)」
}
}
function bindPanelEvents() {
if (!panelElement) return;
const header = panelElement.querySelector('#ds-stats-header');
const minBtn = panelElement.querySelector('#ds-stats-min-btn');
const closeBtn = panelElement.querySelector('#ds-stats-close-btn');
const refreshBtn = panelElement.querySelector('#ds-stats-refresh-btn');
const exportBtn = panelElement.querySelector('#ds-stats-export-btn');
const cleanBtn = panelElement.querySelector('#ds-stats-clean-btn');
const body = panelElement.querySelector('#ds-stats-body');
const groupSelect = panelElement.querySelector('#ds-group-select');
const periodTabs = panelElement.querySelector('#ds-period-tabs');
const customStart = panelElement.querySelector('#ds-custom-start');
const customEnd = panelElement.querySelector('#ds-custom-end');
// 先移除可能存在的旧事件监听器
header?.removeEventListener('mousedown', onDragStart);
header?.removeEventListener('touchstart', onDragStart);
minBtn?.removeEventListener('click', onMinBtnClick);
closeBtn?.removeEventListener('click', onCloseBtnClick);
refreshBtn?.removeEventListener('click', onRefreshBtnClick);
exportBtn?.removeEventListener('click', exportCSV);
cleanBtn?.removeEventListener('click', clearDefaultData);
groupSelect?.removeEventListener('change', updatePanel);
periodTabs?.removeEventListener('click', onPeriodTabClick);
customStart?.removeEventListener('change', onCustomDateChange);
customEnd?.removeEventListener('change', onCustomDateChange);
// 添加新的事件监听器
header?.addEventListener('mousedown', onDragStart);
header?.addEventListener('touchstart', onDragStart, { passive: false });
minBtn?.addEventListener('click', onMinBtnClick);
closeBtn?.addEventListener('click', onCloseBtnClick);
refreshBtn?.addEventListener('click', onRefreshBtnClick);
exportBtn?.addEventListener('click', exportCSV);
cleanBtn?.addEventListener('click', clearDefaultData);
groupSelect?.addEventListener('change', updatePanel);
periodTabs?.addEventListener('click', onPeriodTabClick);
customStart?.addEventListener('change', onCustomDateChange);
customEnd?.addEventListener('change', onCustomDateChange);
}
// v5.2.2:清除旧版本遗留的 default 分组历史数据
function clearDefaultData() {
const keys = [];
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
if (k && k.startsWith(CONFIG.STORAGE_PREFIX + 'default_')) keys.push(k);
}
if (keys.length === 0) {
alert('没有需要清除的 default 历史数据');
return;
}
if (!confirm(`确认清除 ${keys.length} 条 default 历史数据?\n(这是旧版本拦截旧接口时遗留的数据,新接口按 Key 分组,不产生 default)`)) return;
keys.forEach(k => localStorage.removeItem(k));
alert(`已清除 ${keys.length} 条 default 历史数据`);
// 若当前选中 default,自动切回「全部 Key(合计)」
const select = document.getElementById('ds-group-select');
if (select && select.value === 'default') {
select.value = ALL_KEYS_ID;
}
updatePanel();
}
// v4.2:时间段 Tab 切换
function onPeriodTabClick(e) {
const btn = e.target.closest('.ds-period-btn');
if (!btn) return;
setCurrentPeriod(btn.dataset.period);
syncPeriodTabs();
updatePanel();
}
// v4.2:同步时间段 Tab 激活态与自定义日期输入框
function syncPeriodTabs() {
const period = getCurrentPeriod();
panelElement?.querySelectorAll('.ds-period-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.period === period);
});
const customRange = document.getElementById('ds-custom-range');
if (customRange) customRange.style.display = period === 'custom' ? 'flex' : 'none';
if (period === 'custom') {
const startInput = document.getElementById('ds-custom-start');
const endInput = document.getElementById('ds-custom-end');
const c = getCustomPeriod();
if (c && c.start && c.end) {
if (startInput) startInput.value = c.start;
if (endInput) endInput.value = c.end;
} else {
const r = getPeriodRangeStr('custom');
if (startInput) startInput.value = r.start;
if (endInput) endInput.value = r.end;
}
}
}
// v4.2:自定义日期变更
function onCustomDateChange() {
const startInput = document.getElementById('ds-custom-start');
const endInput = document.getElementById('ds-custom-end');
if (!startInput || !endInput) return;
if (startInput.value && endInput.value) {
setCustomPeriod(startInput.value, endInput.value);
updatePanel();
}
}
function onMinBtnClick(e) {
e.stopPropagation();
panelMinimized = !panelMinimized;
const body = panelElement.querySelector('#ds-stats-body');
const minBtn = panelElement.querySelector('#ds-stats-min-btn');
if (body) body.style.display = panelMinimized ? 'none' : 'block';
minBtn.textContent = panelMinimized ? '□' : '─';
if (panelMinimized) panelElement.style.height = 'auto';
else panelElement.style.height = '';
}
function onCloseBtnClick(e) {
e.stopPropagation();
panelElement.style.display = 'none';
setTimeout(() => {
if (panelElement && document.body.contains(panelElement)) {
panelElement.style.display = '';
}
}, 180000);
}
function onRefreshBtnClick() {
updatePanel();
const refreshBtn = panelElement.querySelector('#ds-stats-refresh-btn');
refreshBtn.style.transition = 'transform 0.4s ease';
refreshBtn.style.transform = 'rotate(360deg)';
setTimeout(() => {
refreshBtn.style.transform = '';
refreshBtn.style.transition = '';
}, 400);
}
function onDragStart(e) {
if (e.target.closest('button') || e.target.closest('select')) return;
isDragging = true;
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
dragStartX = clientX;
dragStartY = clientY;
const rect = panelElement.getBoundingClientRect();
panelStartRight = window.innerWidth - rect.right;
panelStartTop = rect.top;
panelElement.style.transition = 'none';
panelElement.style.cursor = 'grabbing';
e.preventDefault();
}
function onDragMove(e) {
if (!isDragging) return;
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
const dx = clientX - dragStartX;
const dy = clientY - dragStartY;
let newRight = panelStartRight - dx;
let newTop = panelStartTop + dy;
const maxRight = window.innerWidth - 100;
const minRight = -panelElement.offsetWidth + 40;
newRight = Math.max(minRight, Math.min(newRight, maxRight));
newTop = Math.max(0, Math.min(newTop, window.innerHeight - 60));
panelElement.style.right = newRight + 'px';
panelElement.style.top = newTop + 'px';
panelElement.style.left = 'auto';
e.preventDefault();
}
function onDragEnd() {
if (isDragging) {
isDragging = false;
if (panelElement) {
panelElement.style.transition = '';
panelElement.style.cursor = '';
}
}
}
// 全局拖拽事件只注册一次
document.addEventListener('mousemove', onDragMove);
document.addEventListener('mouseup', onDragEnd);
document.addEventListener('touchmove', onDragMove, { passive: false });
document.addEventListener('touchend', onDragEnd);
function updatePanel() {
if (!panelElement || !document.body.contains(panelElement)) {
logger.log('检测到面板丢失,重新创建');
createPanel();
}
populateGroupSelect();
const select = document.getElementById('ds-group-select');
const groupId = select?.value;
if (!groupId) {
setEmptyValues();
renderSummaryTable();
return;
}
syncPeriodTabs();
const period = getCurrentPeriod();
const range = getPeriodRangeStr(period);
// v5.1:选中「全部 Key(合计)」时汇总所有 Key
const summary = groupId === ALL_KEYS_ID
? getTotalSummary(range.start, range.end)
: Storage.getPeriodSummary(groupId, range.start, range.end);
const updateEl = (id, text) => {
const el = panelElement?.querySelector('#' + id);
if (el) el.textContent = text;
};
updateEl('ds-period-label', PERIODS[period]);
updateEl('ds-period-range', `(${range.start} ~ ${range.end})`);
updateEl('ds-period-hit', formatNumber(summary.inputCacheHit));
updateEl('ds-period-miss', formatNumber(summary.inputCacheMiss));
updateEl('ds-period-output', formatNumber(summary.outputTokens));
updateEl('ds-period-cost', formatCurrency(summary.estimatedCost));
updateEl('ds-period-rate', formatPercent(summary.cacheHitRate));
updateRateColor('ds-period-rate', summary.cacheHitRate);
renderSummaryTable(period, range);
const updatedEl = panelElement.querySelector('#ds-stats-updated');
if (updatedEl) updatedEl.textContent = '更新于 ' + new Date().toLocaleTimeString('zh-CN');
}
function setEmptyValues() {
const ids = ['ds-period-hit', 'ds-period-miss', 'ds-period-output', 'ds-period-cost', 'ds-period-rate'];
ids.forEach(id => {
const el = panelElement?.querySelector('#' + id);
if (el) el.textContent = '--';
});
const updatedEl = panelElement?.querySelector('#ds-stats-updated');
if (updatedEl) updatedEl.textContent = '暂无数据';
}
function updateRateColor(id, rate) {
const el = panelElement?.querySelector('#' + id);
if (!el) return;
if (rate >= 70) el.style.color = '#10b981';
else if (rate >= 30) el.style.color = '#f59e0b';
else if (rate > 0) el.style.color = '#ef4444';
else el.style.color = '#94a3b8';
}
function rateColor(rate) {
if (rate >= 70) return '#10b981';
if (rate >= 30) return '#f59e0b';
if (rate > 0) return '#ef4444';
return '#94a3b8';
}
// ==================== v4.2:全部 Key 汇总表格(跟随所选时间段) ====================
function renderSummaryTable(period = getCurrentPeriod(), range = getPeriodRangeStr(period)) {
const tableBody = document.getElementById('ds-summary-tbody');
if (!tableBody) return;
const summaryPeriodEl = document.getElementById('ds-summary-period');
if (summaryPeriodEl) summaryPeriodEl.textContent = PERIODS[period] || '统计';
const groupIds = getAllDisplayGroupIds();
const hasAnyData = Storage.getAllGroupIds().length > 0 || Object.keys(KeyMeta.getAll()).length > 0;
if (!hasAnyData) {
tableBody.innerHTML = '| 暂无数据,请先访问用量页面或 Key 管理页面 |
';
return;
}
// 按所选时间段费用降序排列
const rows = groupIds
.map(id => ({ id, summary: Storage.getPeriodSummary(id, range.start, range.end) }))
.sort((a, b) => b.summary.estimatedCost - a.summary.estimatedCost)
.map(item => `
| ${escapeHtml(truncateKey(KeyMeta.displayName(item.id), 18))} |
${formatPercent(item.summary.cacheHitRate)} |
${formatCurrency(item.summary.estimatedCost)} |
`)
.join('');
// v5.1:合计行(排除 default 历史兜底数据;v5.2:费用用真实 cost 合计)
const totalGroups = groupIds.filter(id => id !== 'default' && id !== ALL_KEYS_ID);
const totalHit = totalGroups.reduce((acc, id) => acc + Storage.getPeriodSummary(id, range.start, range.end).inputCacheHit, 0);
const totalMiss = totalGroups.reduce((acc, id) => acc + Storage.getPeriodSummary(id, range.start, range.end).inputCacheMiss, 0);
const totalRate = calcHitRate(totalHit, totalMiss);
const totalCost = getTotalSummary(range.start, range.end).estimatedCost;
const totalRow = `
| 🧮 合计 |
${formatPercent(totalRate)} |
${formatCurrency(totalCost)} |
`;
tableBody.innerHTML = rows + totalRow;
}
// ==================== v4.0:导出 CSV(UTF-8 BOM,兼容 Excel) ====================
function exportCSV() {
const allData = Storage.getAllData();
const groupIds = Object.keys(allData);
if (groupIds.length === 0) {
alert('暂无数据可导出,请先访问用量页面');
return;
}
const rows = [
['Key', 'KeyID', '日期', '缓存命中Token', '缓存未命中Token', '输出Token', '命中率(%)', '预估费用(¥)']
];
groupIds.forEach(id => {
const dates = Object.keys(allData[id]).sort();
dates.forEach(dateStr => {
const d = allData[id][dateStr];
const hit = safeGet(d, 'inputCacheHit', 0);
const miss = safeGet(d, 'inputCacheMiss', 0);
const output = safeGet(d, 'outputTokens', 0);
const c = safeGet(d, 'cost', null);
// v5.2:优先真实费用,无则估算
const cost = c != null ? Number(c) : calcCost(hit, miss, output);
rows.push([
KeyMeta.displayName(id), id, dateStr, hit, miss, output,
calcHitRate(hit, miss).toFixed(2),
cost.toFixed(4)
]);
});
});
const csv = '\uFEFF' + rows
.map(r => r.map(v => '"' + String(v).replace(/"/g, '""') + '"').join(','))
.join('\r\n');
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'deepseek_cache_stats_' + getTodayStr() + '.csv';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 1000);
logger.log(`CSV 已导出,共 ${rows.length - 1} 行数据`);
}
// ==================== 样式注入 ====================
function injectStyles() {
if (document.getElementById('ds-cache-stats-styles')) return;
const style = document.createElement('style');
style.id = 'ds-cache-stats-styles';
style.textContent = `
#ds-cache-stats-panel {
position: fixed;
z-index: 99999;
width: 360px;
background: #ffffff;
border-radius: 12px;
box-shadow: 0 8px 32px rgba(0,0,0,0.15), 0 2px 8px rgba(0,0,0,0.08);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
font-size: 13px;
color: #1e293b;
border: 1px solid #e2e8f0;
transition: box-shadow 0.3s ease;
user-select: none;
overflow: hidden;
animation: ds-panel-fade-in 0.3s ease;
}
@keyframes ds-panel-fade-in {
from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); }
}
#ds-cache-stats-panel:hover { box-shadow: 0 12px 40px rgba(0,0,0,0.2), 0 4px 12px rgba(0,0,0,0.1); }
.ds-stats-header {
display: flex; justify-content: space-between; align-items: center;
padding: 10px 14px; background: linear-gradient(135deg, #4F6EF7 0%, #3b5de7 100%);
color: #ffffff; cursor: move; border-radius: 12px 12px 0 0;
font-weight: 600; font-size: 14px; letter-spacing: 0.3px;
gap: 8px;
}
.ds-stats-title { white-space: nowrap; }
.ds-group-select {
padding: 2px 8px;
border: 1px solid rgba(255,255,255,0.3);
border-radius: 4px;
background: rgba(255,255,255,0.15);
color: #fff;
font-size: 12px;
max-width: 140px;
cursor: pointer;
outline: none;
}
.ds-group-select option {
background: #fff;
color: #1e293b;
}
.ds-stats-header-btns { display: flex; gap: 4px; }
.ds-stats-btn {
background: rgba(255,255,255,0.2); border: none; color: #fff;
cursor: pointer; padding: 3px 8px; border-radius: 4px; font-size: 14px;
line-height: 1; transition: background 0.2s;
}
.ds-stats-btn:hover { background: rgba(255,255,255,0.35); }
.ds-stats-close-btn:hover { background: rgba(255,80,80,0.5); }
.ds-stats-body { padding: 10px 14px; max-height: 560px; overflow-y: auto; }
.ds-stats-section { margin-bottom: 4px; }
.ds-stats-section-title {
font-weight: 600; font-size: 13px; color: #475569;
margin-bottom: 8px; padding-bottom: 4px; border-bottom: 2px solid #e2e8f0;
}
.ds-stats-section-title span { font-weight: 400; font-size: 11px; color: #94a3b8; }
.ds-stats-row { display: flex; align-items: center; padding: 5px 0; justify-content: space-between; }
.ds-stats-highlight { background: #f8fafc; border-radius: 6px; padding: 7px 8px; margin-top: 4px; font-weight: 600; }
.ds-stats-label { flex: 1; font-size: 12px; color: #64748b; }
.ds-label-hit { color: #10b981; } .ds-label-miss { color: #f59e0b; } .ds-label-output { color: #6366f1; }
.ds-stats-value { flex: 0 0 auto; text-align: right; font-weight: 600; font-size: 13px; color: #1e293b; min-width: 80px; padding-right: 4px; }
.ds-stats-rate { font-size: 16px; font-weight: 700; }
.ds-stats-unit { flex: 0 0 auto; font-size: 10px; color: #94a3b8; width: 36px; text-align: left; }
.ds-stats-divider { height: 1px; background: #e2e8f0; margin: 8px 0; }
.ds-stats-footer { display: flex; justify-content: space-between; align-items: center; margin-top: 8px; padding-top: 6px; border-top: 1px solid #f1f5f9; gap: 8px; }
.ds-stats-footer-left { display: flex; flex-direction: column; gap: 3px; min-width: 0; flex: 1; }
.ds-stats-updated { font-size: 10px; color: #94a3b8; }
.ds-stats-debug { font-size: 9px; color: #cbd5e1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 220px; cursor: help; }
.ds-stats-cleanbar { display: flex; justify-content: flex-end; margin-top: 6px; }
.ds-stats-clean-btn {
background: transparent; border: 1px dashed #e2e8f0; color: #94a3b8;
padding: 3px 8px; border-radius: 6px; cursor: pointer; font-size: 10px;
transition: all 0.2s ease; white-space: nowrap;
}
.ds-stats-clean-btn:hover { background: #fef2f2; border-color: #fca5a5; color: #ef4444; }
.ds-stats-refresh-btn {
background: #f1f5f9; border: 1px solid #e2e8f0; padding: 4px 10px;
border-radius: 6px; cursor: pointer; font-size: 11px; color: #475569;
transition: all 0.3s ease;
}
.ds-stats-refresh-btn:hover { background: #e2e8f0; border-color: #cbd5e1; }
.ds-stats-footer-btns { display: flex; gap: 6px; align-items: center; }
.ds-stats-export-btn {
background: #4F6EF7; border: none; padding: 4px 10px;
border-radius: 6px; cursor: pointer; font-size: 11px; color: #ffffff;
transition: all 0.3s ease; white-space: nowrap;
}
.ds-stats-export-btn:hover { background: #3b5de7; }
/* v4.2:时间段选择器 */
.ds-period-tabs { display: flex; flex-wrap: nowrap; gap: 4px; margin-bottom: 8px; }
.ds-period-btn {
flex: 1; padding: 5px 0; font-size: 11px; white-space: nowrap;
border: 1px solid #e2e8f0; background: #f8fafc; color: #475569;
border-radius: 6px; cursor: pointer; transition: all 0.2s ease;
}
.ds-period-btn:hover { background: #e2e8f0; border-color: #cbd5e1; }
.ds-period-btn.active {
background: #4F6EF7; border-color: #4F6EF7; color: #ffffff; font-weight: 600;
}
.ds-custom-range { display: flex; align-items: center; gap: 6px; margin-bottom: 8px; }
.ds-date-sep { font-size: 11px; color: #94a3b8; }
.ds-date-input {
flex: 1; min-width: 0; font-size: 11px; padding: 4px 6px;
border: 1px solid #e2e8f0; border-radius: 4px; color: #1e293b; background: #fff;
}
.ds-date-input:focus { outline: none; border-color: #4F6EF7; }
.ds-summary-table { width: 100%; border-collapse: collapse; font-size: 11px; table-layout: fixed; }
.ds-summary-table th {
text-align: left; font-weight: 600; color: #64748b;
padding: 4px 6px; border-bottom: 1px solid #e2e8f0; white-space: nowrap;
}
.ds-summary-table td { padding: 4px 6px; border-bottom: 1px solid #f1f5f9; color: #1e293b; }
.ds-summary-table tr:last-child td { border-bottom: none; }
.ds-summary-key { max-width: 110px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #475569; }
.ds-summary-rate { font-weight: 600; white-space: nowrap; }
.ds-summary-cost { text-align: right; color: #475569; font-weight: 600; white-space: nowrap; }
.ds-summary-empty { text-align: center; color: #94a3b8; padding: 10px 0 !important; }
.ds-summary-total td { border-top: 2px solid #e2e8f0; font-weight: 700; color: #1e293b; background: #f8fafc; }
@media (max-width: 480px) {
#ds-cache-stats-panel { width: 300px; right: 4px !important; font-size: 11px; }
.ds-stats-value { font-size: 11px; min-width: 60px; }
.ds-stats-rate { font-size: 14px; }
.ds-stats-header { padding: 8px 10px; font-size: 12px; }
.ds-stats-body { padding: 8px 10px; }
.ds-group-select { max-width: 90px; font-size: 10px; }
.ds-period-btn { font-size: 10px; padding: 4px 0; }
}
`;
document.head.appendChild(style);
}
// ==================== 初始化 ====================
function init() {
logger.log('启动多 Key 缓存命中率统计 v5.2.3 (下拉框选择修复版)');
injectStyles();
Storage.cleanup();
createPanel();
interceptFetch();
interceptXHR();
fetchApiKeysOnce();
updatePanel();
setInterval(updatePanel, CONFIG.REFRESH_INTERVAL);
setInterval(Storage.cleanup, 3600000);
// 面板丢失时自动重建
const observer = new MutationObserver((mutations) => {
if (!document.getElementById('ds-cache-stats-panel')) {
logger.log('检测到面板从DOM中移除,重新创建');
createPanel();
updatePanel();
}
});
observer.observe(document.body, { childList: true });
}
// 确保只执行一次初始化
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => setTimeout(init, 500));
} else {
setTimeout(init, 500);
}
})();