dsh-usage-peak 1.3.1 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +11 -4
- package/client.js +186 -53
- package/index.js +47 -10
- package/package.json +3 -3
- package/test/client.test.js +104 -0
- package/test/core.test.js +173 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.4.1
|
|
4
|
+
|
|
5
|
+
- 修复侧栏余额/预算预警激活后,峰谷倒计时被警告文案替换、看不到「还有多久转峰/转谷」的问题:现在倒计时始终保留,前面加 `⚠` 并在 tooltip 中补充预警原因。
|
|
6
|
+
|
|
7
|
+
## 1.4.0
|
|
8
|
+
|
|
9
|
+
- 新增项目下钻:点击项目筛选概况、小时/每日趋势、模型明细,顶部可切换或恢复全部项目;项目占比增加条形提示。
|
|
10
|
+
- `/data` 和 `/export.csv` 新增精确 `project` 参数;快照缓存按窗口与项目隔离,CSV 跟随筛选,未知项目返回空态。
|
|
11
|
+
- 新增浏览器本地预警设置:余额预警天数、紧张天数和可选每日预算;保存后侧栏与面板同步,存储不可用时在当前页面继续工作。
|
|
12
|
+
- 每日预算超过 100% 预警、达到 120% 紧张;余额和预算告警取最高等级。全局余额、余额可撑与每日预算不受项目筛选影响。
|
|
13
|
+
- 修复主题变量拼接透明度的无效 CSS,改用主题友好的混色。
|
|
14
|
+
- 新增项目筛选、缓存隔离、HTTP/CSV 和客户端预警逻辑测试。
|
|
15
|
+
|
|
3
16
|
## 1.3.1
|
|
4
17
|
|
|
5
18
|
- 修复余额充足时头部胶囊仍显示「余额仅够 X 天」的文案:改为「可撑 X 天」,只有低于 7 天警戒线才显示「余额仅够」。
|
package/README.md
CHANGED
|
@@ -12,13 +12,15 @@
|
|
|
12
12
|
|
|
13
13
|
## 功能
|
|
14
14
|
|
|
15
|
-
- **侧栏常驻胶囊**:`● 峰 ¥14.70 · 12.8M tok · 2:43
|
|
15
|
+
- **侧栏常驻胶囊**:`● 峰 ¥14.70 · 12.8M tok · 2:43 后转谷`,点一下打开完整面板。侧栏折叠时收成一个小圆点。默认可撑天数不足 7 天时胶囊转琥珀色,不足 3 天转红色;可在面板调整阈值。
|
|
16
16
|
- **峰谷状态**:当前时段、距离下次切换的倒计时、当前时段单价(缓存命中 / 全价输入 / 输出)。
|
|
17
17
|
- **今日概况**:花费、请求数、tokens、缓存命中率、峰时花费占比、**谷时更省**(把这些峰时用量挪到谷时能省下的钱)、余额、**余额可撑天数**(余额 ÷ 近 7 天日均花费)。
|
|
18
18
|
- **今日 24 小时分布**:每小时花费柱状,峰时与谷时用不同颜色,当前小时高亮。
|
|
19
19
|
- **花费构成**:缓存命中 / 全价输入 / 输出 三段占比,直接看出钱花在哪。
|
|
20
20
|
- **近 7 / 14 / 30 天趋势**:右上角切换窗口,按天堆叠柱状,缺数据的日期补零,列数恒定;可对照峰时占比判断"贵在哪天"。
|
|
21
|
-
-
|
|
21
|
+
- **按项目与下钻**:按会话头里的工作目录(`cwd`)聚合,倒序列出每个项目的请求数、tokens、花费与占比条。点击项目可只看该项目的概况、24 小时、趋势和模型明细,通过顶部「全部项目」恢复。
|
|
22
|
+
- **可配置预警**:在面板中设置余额预警天数(默认 7)、紧张天数(默认 3)和可选每日预算。每日花费超过预算时预警,达到预算 120% 时紧张;多个告警取最高级别。配置保存在当前浏览器,侧栏与面板同步。
|
|
23
|
+
- **全局钱包口径**:余额、余额可撑天数和每日预算始终按所有项目计算,不会因为筛选一个低花费项目而误判余额充足。
|
|
22
24
|
- **按模型**:Flash / Pro 各自的请求数、tokens、花费。
|
|
23
25
|
- **导出 CSV**:每日数据与项目数据都能导出(UTF-8 BOM,Excel 直接打开不乱码;单元格做了公式注入防护)。
|
|
24
26
|
- **价目表**:当前时段那一行高亮,方便解释账单。
|
|
@@ -47,8 +49,9 @@
|
|
|
47
49
|
|
|
48
50
|
日志是**多帧 zstd**,Node 自带的 `zlib.zstdDecompressSync` 只解第一帧,所以插件内部按 zstd magic 切帧、逐帧解压再拼接(不需要 `zstd` 命令行)。
|
|
49
51
|
|
|
50
|
-
- 数据接口支持 `?days=7|14|30` 选择统计窗口(默认 14,白名单之外的取值回落到 14
|
|
51
|
-
-
|
|
52
|
+
- 数据接口支持 `?days=7|14|30` 选择统计窗口(默认 14,白名单之外的取值回落到 14);快照按窗口与项目分别缓存 15 秒,面板上的「刷新」按钮会带 `?fresh=1` 强制重算。
|
|
53
|
+
- `/data` 和 `/export.csv` 均接受可选 `project` 参数(项目的精确 key,真实会话通常是绝对 `cwd`;必须 URL 编码)。不传或空字符串表示全部项目,未知 key 返回空项目数据而不是退回全量。项目列表来自全局窗口,方便切换。
|
|
54
|
+
- 导出接口为 `/plugin/dsh-usage-peak/export.csv?days=7|14|30&scope=days|projects&project=...`,带 `Content-Disposition: attachment` 与 UTF-8 BOM。页面的每日和项目 CSV 都跟随当前筛选。
|
|
52
55
|
|
|
53
56
|
峰时单价恰为谷时 2 倍,所以「谷时更省」= 峰时花费 ÷ 2:它衡量的是这些峰时用量如果改在谷时发生能省多少,而不是已经省下的钱。
|
|
54
57
|
|
|
@@ -74,6 +77,7 @@ dsh plugin add dsh-usage-peak
|
|
|
74
77
|
## 已知限制
|
|
75
78
|
|
|
76
79
|
- 依赖 DSH 会话日志的**内部格式**(`session.v4.jsonl.zstd` 与 `assistant/message.data.usage`)。DSH 改格式时需要跟进;读不到数据时面板会显示为空态而不是报错。
|
|
80
|
+
- 每日预算基于本机会话日志估算的北京时间「今日」总花费,不代表平台实时账单;预警配置只存当前浏览器,不跨设备同步。宿主功能升级后需重启 DSH,客户端重新加载后使用新界面。
|
|
77
81
|
- 只统计本机会话日志覆盖到的历史,鲸鱼记账本从 2026-11-02 才开始记账。
|
|
78
82
|
- 项目归属依赖会话头中的 `cwd`;极少数没有会话头的旧日志会回落到 workspace slug,slug 会转义部分字节,显示名可能不如真实路径精确。
|
|
79
83
|
|
|
@@ -93,6 +97,9 @@ A usage and cost dashboard for DeepSeek Harness. It reads the local session logs
|
|
|
93
97
|
- China public holidays and makeup workdays: holidays are valley all day, makeup weekend workdays follow the weekday windows (2026–2027 calendars shipped; missing years fall back to Mon-Fri with a visible warning);
|
|
94
98
|
- a footer with the GitHub repository link, the running version and the covered calendar years;
|
|
95
99
|
- a details page (Settings → Usage dashboard) with KPIs (including balance runway), an hourly breakdown, cost composition, a 7/14/30-day trend switch, spend by project, a per-model table, CSV export and the price list;
|
|
100
|
+
- project drilldown: select a project to filter KPIs, hourly/daily charts, models and both CSV exports; clear the filter to return to all projects;
|
|
101
|
+
- configurable browser-local runway thresholds (warning 7 days / critical 3 days by default) and an optional daily budget (warning above 100%, critical at 120%); settings sync between the sidebar and dashboard;
|
|
102
|
+
- balance runway and daily-budget alerts always use global spend, even while a project is selected;
|
|
96
103
|
- a "valley saving" KPI: since peak costs exactly 2x valley, moving the same peak usage to valley time would have saved half of the peak spend.
|
|
97
104
|
|
|
98
105
|
Pricing (`[valley, peak]`, CNY per million tokens): Flash cache-hit 0.02/0.04, miss 1/2, output 4/8; Pro cache-hit 0.15/0.30, miss 4.5/9, output 13.5/27. Peak hours are 09:00–12:00 and 14:00–18:00 Beijing time on weekdays; everything else is valley (half price).
|
package/client.js
CHANGED
|
@@ -13,7 +13,7 @@ window.__ModuleLoader__.load({
|
|
|
13
13
|
factory(require) {
|
|
14
14
|
const React = require('react');
|
|
15
15
|
const h = React.createElement;
|
|
16
|
-
const { useState, useEffect, useCallback } = React;
|
|
16
|
+
const { useState, useEffect, useCallback, useRef } = React;
|
|
17
17
|
|
|
18
18
|
const NS = 'dsh-usage-peak';
|
|
19
19
|
const DATA_URL = '/plugin/dsh-usage-peak/data';
|
|
@@ -85,6 +85,20 @@ window.__ModuleLoader__.load({
|
|
|
85
85
|
'wallet.warn': '余额偏低',
|
|
86
86
|
'wallet.low': '余额紧张',
|
|
87
87
|
|
|
88
|
+
'projects.all': '全部项目',
|
|
89
|
+
'projects.clear': '清除项目筛选',
|
|
90
|
+
'projects.select': '筛选项目',
|
|
91
|
+
'alerts.title': '全局预算与余额预警',
|
|
92
|
+
'alerts.warn': '预警天数',
|
|
93
|
+
'alerts.low': '紧张天数',
|
|
94
|
+
'alerts.budget': '每日预算(元,可选)',
|
|
95
|
+
'alerts.save': '保存阈值',
|
|
96
|
+
'alerts.invalid': '请输入有限正数,且紧张天数必须小于预警天数。',
|
|
97
|
+
'alerts.savedMemory': '存储不可用;仅本页生效,关闭页面后会丢失。',
|
|
98
|
+
'alerts.saved': '已保存;当前页面所有面板同步生效。',
|
|
99
|
+
'alerts.rules': '全局账户:余额可撑 <{warn} 天为琥珀、<{low} 天为红;每日花费 >预算为琥珀、≥120%预算为红。仅提示,不自动限流。',
|
|
100
|
+
'alerts.exceeded': '全局每日预算已超出',
|
|
101
|
+
'alerts.global': '全局今日',
|
|
88
102
|
'projects.title': '按项目',
|
|
89
103
|
'projects.hint': '按花费排序',
|
|
90
104
|
'projects.name': '项目',
|
|
@@ -183,6 +197,20 @@ window.__ModuleLoader__.load({
|
|
|
183
197
|
'wallet.warn': 'Low balance',
|
|
184
198
|
'wallet.low': 'Balance critical',
|
|
185
199
|
|
|
200
|
+
'projects.all': 'All projects',
|
|
201
|
+
'projects.clear': 'Clear project filter',
|
|
202
|
+
'projects.select': 'Filter project',
|
|
203
|
+
'alerts.title': 'Global budget and balance alerts',
|
|
204
|
+
'alerts.warn': 'Warning days',
|
|
205
|
+
'alerts.low': 'Critical days',
|
|
206
|
+
'alerts.budget': 'Daily budget (CNY, optional)',
|
|
207
|
+
'alerts.save': 'Save thresholds',
|
|
208
|
+
'alerts.invalid': 'Use finite positive numbers; critical days must be less than warning days.',
|
|
209
|
+
'alerts.savedMemory': 'Storage unavailable; applies only to this page until it closes.',
|
|
210
|
+
'alerts.saved': 'Saved; all panels on this page are synchronized.',
|
|
211
|
+
'alerts.rules': 'Global account: runway <{warn} days is amber, <{low} is red; daily spend >budget is amber, ≥120% is red. Alerts only, no rate limiting.',
|
|
212
|
+
'alerts.exceeded': 'Global daily budget exceeded',
|
|
213
|
+
'alerts.global': 'Global today',
|
|
186
214
|
'projects.title': 'By project',
|
|
187
215
|
'projects.hint': 'sorted by spend',
|
|
188
216
|
'projects.name': 'Project',
|
|
@@ -294,48 +322,125 @@ window.__ModuleLoader__.load({
|
|
|
294
322
|
|
|
295
323
|
/* --------------------------------- data --------------------------------- */
|
|
296
324
|
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
325
|
+
const PREFS_KEY = 'dsh-usage-peak:alerts:v1';
|
|
326
|
+
const PREFS_EVENT = 'dsh-usage-peak:alerts-change';
|
|
327
|
+
const DEFAULT_PREFS = { warnDays: 7, lowDays: 3, dailyBudget: null };
|
|
328
|
+
const tint = (color, amount = 10) => `color-mix(in srgb, ${color} ${amount}%, transparent)`;
|
|
329
|
+
|
|
330
|
+
function validatePrefs(value) {
|
|
331
|
+
if (!value || typeof value !== 'object') return null;
|
|
332
|
+
const positive = (v) => (typeof v === 'number' || typeof v === 'string') && String(v).trim() !== '' && Number.isFinite(Number(v)) && Number(v) > 0;
|
|
333
|
+
if (!positive(value.warnDays) || !positive(value.lowDays) || Number(value.lowDays) >= Number(value.warnDays)) return null;
|
|
334
|
+
const empty = value.dailyBudget === null || value.dailyBudget === undefined || value.dailyBudget === '';
|
|
335
|
+
if (!empty && !positive(value.dailyBudget)) return null;
|
|
336
|
+
return { warnDays: Number(value.warnDays), lowDays: Number(value.lowDays), dailyBudget: empty ? null : Number(value.dailyBudget) };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
let memoryPrefs = { ...DEFAULT_PREFS };
|
|
340
|
+
let storageFailed = false;
|
|
341
|
+
function readPrefs() {
|
|
342
|
+
if (storageFailed) return { ...memoryPrefs };
|
|
343
|
+
try {
|
|
344
|
+
const raw = window.localStorage.getItem(PREFS_KEY);
|
|
345
|
+
if (raw !== null) memoryPrefs = validatePrefs(JSON.parse(raw)) || { ...DEFAULT_PREFS };
|
|
346
|
+
} catch { /* Disabled storage: retain this page's last valid values. */ }
|
|
347
|
+
return { ...memoryPrefs };
|
|
348
|
+
}
|
|
349
|
+
function savePrefs(value) {
|
|
350
|
+
const next = validatePrefs(value);
|
|
351
|
+
if (!next) return false;
|
|
352
|
+
memoryPrefs = next;
|
|
353
|
+
try { window.localStorage.setItem(PREFS_KEY, JSON.stringify(next)); storageFailed = false; } catch { storageFailed = true; /* In-memory fallback even if reads still succeed. */ }
|
|
354
|
+
window.dispatchEvent(new CustomEvent(PREFS_EVENT, { detail: next }));
|
|
355
|
+
return true;
|
|
356
|
+
}
|
|
357
|
+
function usePreferences() {
|
|
358
|
+
const [prefs, setPrefs] = useState(readPrefs);
|
|
359
|
+
useEffect(() => {
|
|
360
|
+
const sync = (event) => {
|
|
361
|
+
if (event.type === 'storage' && event.key !== PREFS_KEY && event.key !== null) return;
|
|
362
|
+
if (event.type === 'storage') storageFailed = false;
|
|
363
|
+
if (event.type === 'storage' && (event.key === PREFS_KEY || event.key === null) && event.newValue === null) memoryPrefs = { ...DEFAULT_PREFS };
|
|
364
|
+
setPrefs(event.type === PREFS_EVENT ? { ...memoryPrefs } : readPrefs());
|
|
365
|
+
};
|
|
366
|
+
window.addEventListener(PREFS_EVENT, sync);
|
|
367
|
+
window.addEventListener('storage', sync);
|
|
368
|
+
return () => { window.removeEventListener(PREFS_EVENT, sync); window.removeEventListener('storage', sync); };
|
|
369
|
+
}, []);
|
|
370
|
+
return prefs;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// Account-level signals only. Never substitute the selected project's cost.
|
|
374
|
+
function alertState(data, prefs) {
|
|
375
|
+
const rules = validatePrefs(prefs) || DEFAULT_PREFS;
|
|
376
|
+
const days = data && data.wallet && data.wallet.runwayDays;
|
|
377
|
+
const walletLevel = Number.isFinite(days) ? days < rules.lowDays ? 'low' : days < rules.warnDays ? 'warn' : 'ok' : 'unknown';
|
|
378
|
+
const cost = data && data.globalTodayCost;
|
|
379
|
+
const budgetLevel = rules.dailyBudget && Number.isFinite(cost)
|
|
380
|
+
? cost >= rules.dailyBudget * 1.2 ? 'low' : cost > rules.dailyBudget ? 'warn' : 'ok' : 'unknown';
|
|
381
|
+
const rank = { unknown: 0, ok: 0, warn: 1, low: 2 };
|
|
382
|
+
const level = rank[budgetLevel] > rank[walletLevel] ? budgetLevel : walletLevel;
|
|
383
|
+
return { level, walletLevel, budgetLevel, budgetExceeded: rank[budgetLevel] > 0,
|
|
384
|
+
active: rank[level] > 0, tone: level === 'low' ? C.error : level === 'warn' ? C.peak : C.text3 };
|
|
385
|
+
}
|
|
301
386
|
|
|
387
|
+
function feedUrl(base, days, project, fresh = false) {
|
|
388
|
+
return `${base}?days=${days || DEFAULT_DAYS}${project ? `&project=${encodeURIComponent(project)}` : ''}${fresh ? '&fresh=1' : ''}`;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Keep the peak/valley countdown visible in the pill; the warning is an
|
|
392
|
+
// accent plus a prefix, never a replacement for the status text.
|
|
393
|
+
function pillStatus(alertActive, switchText) {
|
|
394
|
+
return alertActive ? `⚠ ${switchText}` : switchText;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// Generation guard rejects old filter responses and older same-filter reloads.
|
|
398
|
+
function requestGate() {
|
|
399
|
+
let key = null;
|
|
400
|
+
let serial = 0;
|
|
401
|
+
return {
|
|
402
|
+
select(next) { if (key !== next) { key = next; serial += 1; } },
|
|
403
|
+
begin(next) { key = next; serial += 1; return { key, serial }; },
|
|
404
|
+
current(ticket) { return ticket.key === key && ticket.serial === serial; },
|
|
405
|
+
invalidate() { serial += 1; },
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
function useFeed(days, project = '') {
|
|
409
|
+
const windowDays = days || DEFAULT_DAYS;
|
|
410
|
+
const queryKey = JSON.stringify([windowDays, project]);
|
|
411
|
+
const guard = useRef(null);
|
|
412
|
+
if (!guard.current) guard.current = requestGate();
|
|
413
|
+
guard.current.select(queryKey);
|
|
414
|
+
const [state, setState] = useState({ key: queryKey, loading: true, error: null, data: null });
|
|
415
|
+
const [tick, setTick] = useState(0);
|
|
302
416
|
const load = useCallback((fresh) => {
|
|
303
|
-
const
|
|
304
|
-
fetch(
|
|
305
|
-
.then((response) => {
|
|
306
|
-
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
307
|
-
return response.json();
|
|
308
|
-
})
|
|
417
|
+
const ticket = guard.current.begin(queryKey);
|
|
418
|
+
fetch(feedUrl(DATA_URL, windowDays, project, fresh), { headers: { accept: 'application/json' } })
|
|
419
|
+
.then((response) => { if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json(); })
|
|
309
420
|
.then((data) => {
|
|
310
421
|
if (!data || data.ok === false) throw new Error((data && data.error) || 'bad payload');
|
|
311
|
-
setState({ loading: false, error: null, data });
|
|
422
|
+
if (guard.current.current(ticket)) setState({ key: queryKey, loading: false, error: null, data });
|
|
312
423
|
})
|
|
313
|
-
.catch((error) =>
|
|
314
|
-
setState((previous) => ({ loading: false, error: String(error && error.message), data: previous.data }))
|
|
315
|
-
);
|
|
316
|
-
}, [windowDays]);
|
|
317
|
-
|
|
424
|
+
.catch((error) => {
|
|
425
|
+
if (guard.current.current(ticket)) setState((previous) => ({ key: queryKey, loading: false, error: String(error && error.message), data: previous.key === queryKey ? previous.data : null }));
|
|
426
|
+
});
|
|
427
|
+
}, [queryKey, windowDays, project]);
|
|
318
428
|
useEffect(() => {
|
|
319
429
|
load(false);
|
|
320
430
|
const timer = setInterval(() => load(false), 60_000);
|
|
321
|
-
return () => clearInterval(timer);
|
|
431
|
+
return () => { clearInterval(timer); guard.current.invalidate(); };
|
|
322
432
|
}, [load]);
|
|
323
|
-
|
|
324
|
-
// A failed start (the host half may register its route a moment after the
|
|
325
|
-
// page boots) should not leave the widget stuck on "读取失败" for a minute.
|
|
326
|
-
const failing = !!state.error;
|
|
433
|
+
const visible = state.key === queryKey ? state : { loading: true, error: null, data: null };
|
|
327
434
|
useEffect(() => {
|
|
328
|
-
if (!
|
|
435
|
+
if (!visible.error) return undefined;
|
|
329
436
|
const timer = setTimeout(() => load(false), 5_000);
|
|
330
437
|
return () => clearTimeout(timer);
|
|
331
|
-
}, [
|
|
332
|
-
|
|
438
|
+
}, [visible.error, load]);
|
|
333
439
|
useEffect(() => {
|
|
334
440
|
const timer = setInterval(() => setTick((value) => value + 1), 15_000);
|
|
335
441
|
return () => clearInterval(timer);
|
|
336
442
|
}, []);
|
|
337
|
-
|
|
338
|
-
return { ...state, tick, reload: load };
|
|
443
|
+
return { ...visible, tick, reload: load };
|
|
339
444
|
}
|
|
340
445
|
|
|
341
446
|
/* -------------------------------- atoms --------------------------------- */
|
|
@@ -372,7 +477,7 @@ window.__ModuleLoader__.load({
|
|
|
372
477
|
borderRadius: 4,
|
|
373
478
|
flex: 'none',
|
|
374
479
|
background: props.tone,
|
|
375
|
-
boxShadow: props.glow ? `0 0 0 3px ${props.tone}
|
|
480
|
+
boxShadow: props.glow ? `0 0 0 3px ${tint(props.tone, 14)}` : 'none',
|
|
376
481
|
},
|
|
377
482
|
});
|
|
378
483
|
}
|
|
@@ -403,10 +508,11 @@ window.__ModuleLoader__.load({
|
|
|
403
508
|
const word = loading ? t('widget.loading') : peak ? t('widget.peak') : t('widget.valley');
|
|
404
509
|
const short = word.slice(0, 1) === '峰' ? '峰' : word.slice(0, 1) === '谷' ? '谷' : word;
|
|
405
510
|
const wallet = data && data.wallet ? data.wallet : null;
|
|
406
|
-
const
|
|
407
|
-
const
|
|
408
|
-
const
|
|
409
|
-
const
|
|
511
|
+
const prefs = usePreferences();
|
|
512
|
+
const alert = alertState(data, prefs);
|
|
513
|
+
const walletAlert = alert.active;
|
|
514
|
+
const walletTone = alert.tone;
|
|
515
|
+
const walletText = walletAlert ? (alert.budgetExceeded ? t('alerts.exceeded') : `${t('wallet.alert')} ${runway(wallet && wallet.runwayDays, t)}`) : '';
|
|
410
516
|
const remain = data ? Math.max(0, data.now.nextAt - Date.now()) : 0;
|
|
411
517
|
const switchText =
|
|
412
518
|
data && remain > 30_000
|
|
@@ -416,7 +522,7 @@ window.__ModuleLoader__.load({
|
|
|
416
522
|
const walletTip =
|
|
417
523
|
wallet && wallet.balance !== null
|
|
418
524
|
? `${t('kpi.balance')} ${yuan(wallet.balance)}${walletText ? ` · ${walletText}` : ''}`
|
|
419
|
-
:
|
|
525
|
+
: walletText;
|
|
420
526
|
const tip = data
|
|
421
527
|
? `${word} · ${t('widget.today')} ${yuan(today)} · ${tokens(data.today ? data.today.tokens : 0, t)} tokens · ${t('status.switchIn')} ${switchText}${walletTip ? ` · ${walletTip}` : ''}`
|
|
422
528
|
: word;
|
|
@@ -434,7 +540,7 @@ window.__ModuleLoader__.load({
|
|
|
434
540
|
padding: '0 8px',
|
|
435
541
|
borderRadius: 999,
|
|
436
542
|
border: `1px solid ${walletAlert ? walletTone : C.border}`,
|
|
437
|
-
background: walletAlert ?
|
|
543
|
+
background: walletAlert ? tint(walletTone, 8) : 'transparent',
|
|
438
544
|
fontSize: 10.5,
|
|
439
545
|
lineHeight: '19px',
|
|
440
546
|
color: C.text2,
|
|
@@ -445,7 +551,7 @@ window.__ModuleLoader__.load({
|
|
|
445
551
|
};
|
|
446
552
|
|
|
447
553
|
const pill = rail
|
|
448
|
-
? h(Dot, { tone })
|
|
554
|
+
? h(Dot, { tone: walletAlert ? walletTone : tone })
|
|
449
555
|
: h(
|
|
450
556
|
'span',
|
|
451
557
|
{ style: pillStyle },
|
|
@@ -471,7 +577,7 @@ window.__ModuleLoader__.load({
|
|
|
471
577
|
textOverflow: 'ellipsis',
|
|
472
578
|
},
|
|
473
579
|
},
|
|
474
|
-
data ? (walletAlert
|
|
580
|
+
data ? pillStatus(walletAlert, switchText) : '',
|
|
475
581
|
),
|
|
476
582
|
);
|
|
477
583
|
|
|
@@ -739,14 +845,14 @@ window.__ModuleLoader__.load({
|
|
|
739
845
|
};
|
|
740
846
|
|
|
741
847
|
function ProjectTable(props) {
|
|
742
|
-
const { projects, t } = props;
|
|
848
|
+
const { projects, t, onSelect } = props;
|
|
743
849
|
if (!projects || !projects.length) {
|
|
744
850
|
return h('span', { style: { fontSize: 11.5, color: C.text3 } }, t('projects.empty'));
|
|
745
851
|
}
|
|
746
852
|
const head = [t('projects.name'), t('projects.calls'), t('projects.tokens'), t('projects.cost'), t('projects.share')];
|
|
747
853
|
return h(
|
|
748
854
|
'div',
|
|
749
|
-
{ style: { maxHeight: 214,
|
|
855
|
+
{ style: { maxHeight: 214, overflow: 'auto', margin: '0 -2px' } },
|
|
750
856
|
h(
|
|
751
857
|
'table',
|
|
752
858
|
{ style: { width: '100%', borderCollapse: 'collapse', fontSize: 11.5 } },
|
|
@@ -779,12 +885,12 @@ window.__ModuleLoader__.load({
|
|
|
779
885
|
textOverflow: 'ellipsis',
|
|
780
886
|
},
|
|
781
887
|
},
|
|
782
|
-
project.name,
|
|
888
|
+
h('button', { type: 'button', onClick: () => onSelect(project.key), title: project.path, style: { border: 0, background: 'transparent', padding: 0, color: C.cache, cursor: 'pointer', font: 'inherit', textAlign: 'left' } }, project.name),
|
|
783
889
|
),
|
|
784
890
|
h('td', { style: { ...cellBody, textAlign: 'right' } }, project.calls),
|
|
785
891
|
h('td', { style: { ...cellBody, textAlign: 'right' } }, tokens(project.tokens, t)),
|
|
786
892
|
h('td', { style: { ...cellBody, textAlign: 'right' } }, yuan(project.cost)),
|
|
787
|
-
h('td', { style: { ...cellBody, textAlign: 'right', color: C.text3 } }, percent(project.share, 0)),
|
|
893
|
+
h('td', { style: { ...cellBody, textAlign: 'right', color: C.text3 } }, percent(project.share, 0), h('div', { style: { height: 3, minWidth: 38, background: C.layer2, borderRadius: 2 } }, h('div', { style: { height: '100%', width: `${Math.max(0, Math.min(100, (project.share || 0) * 100))}%`, background: C.cache, borderRadius: 2 } }))),
|
|
788
894
|
),
|
|
789
895
|
),
|
|
790
896
|
),
|
|
@@ -830,20 +936,37 @@ window.__ModuleLoader__.load({
|
|
|
830
936
|
);
|
|
831
937
|
}
|
|
832
938
|
|
|
939
|
+
function AlertSettings({ prefs, t }) {
|
|
940
|
+
const [draft, setDraft] = useState(prefs);
|
|
941
|
+
const [message, setMessage] = useState('');
|
|
942
|
+
useEffect(() => { setDraft(prefs); }, [prefs.warnDays, prefs.lowDays, prefs.dailyBudget]);
|
|
943
|
+
const rules = t('alerts.rules').replace('{warn}', prefs.warnDays).replace('{low}', prefs.lowDays);
|
|
944
|
+
return h(Card, null, h(CardTitle, { title: t('alerts.title') }),
|
|
945
|
+
h('form', { onSubmit: (event) => { event.preventDefault(); setMessage(savePrefs(draft) ? (storageFailed ? 'alerts.savedMemory' : 'alerts.saved') : 'alerts.invalid'); }, style: { display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'end' } },
|
|
946
|
+
['warnDays', 'lowDays', 'dailyBudget'].map((key) => h('label', { key, style: { fontSize: 11, color: C.text2, display: 'flex', flexDirection: 'column', gap: 3 } },
|
|
947
|
+
t(key === 'warnDays' ? 'alerts.warn' : key === 'lowDays' ? 'alerts.low' : 'alerts.budget'),
|
|
948
|
+
h('input', { type: 'number', min: 0, step: 'any', required: key !== 'dailyBudget', value: draft[key] ?? '', onChange: (event) => { setDraft({ ...draft, [key]: event.target.value }); setMessage(''); }, style: { width: key === 'dailyBudget' ? 155 : 85, padding: 5, borderRadius: 5, border: `1px solid ${C.border}`, color: C.text, background: C.layer2 } }))),
|
|
949
|
+
h('button', { type: 'submit', style: { color: C.text, background: C.layer2, border: `1px solid ${C.border}`, padding: 5, borderRadius: 5, cursor: 'pointer' } }, t('alerts.save'))),
|
|
950
|
+
h('span', { style: { color: C.text3, fontSize: 11 } }, rules),
|
|
951
|
+
message ? h('span', { role: 'status', style: { color: message === 'alerts.invalid' ? C.error : C.valley, fontSize: 11 } }, t(message)) : null);
|
|
952
|
+
}
|
|
953
|
+
|
|
833
954
|
/* -------------------------------- settings ------------------------------- */
|
|
834
955
|
|
|
835
956
|
function Dashboard(props) {
|
|
836
957
|
const t = props.t;
|
|
837
958
|
const [days, setDays] = useState(props.days || 14);
|
|
838
|
-
const
|
|
959
|
+
const [project, setProject] = useState('');
|
|
960
|
+
const feed = useFeed(days, project);
|
|
839
961
|
const data = feed.data;
|
|
840
962
|
const windowDays = (data && data.windowDays) || days;
|
|
841
963
|
const peakNow = data ? data.now.peak : false;
|
|
842
964
|
const wallet = data && data.wallet ? data.wallet : null;
|
|
843
|
-
const
|
|
844
|
-
const
|
|
845
|
-
const
|
|
846
|
-
const
|
|
965
|
+
const prefs = usePreferences();
|
|
966
|
+
const alert = alertState(data, prefs);
|
|
967
|
+
const walletAlert = alert.active;
|
|
968
|
+
const walletTone = alert.tone;
|
|
969
|
+
const runwayLabel = alert.walletLevel === 'low' || alert.walletLevel === 'warn' ? t('wallet.alert') : t('wallet.runway');
|
|
847
970
|
const remain = data ? Math.max(0, data.now.nextAt - Date.now()) : 0;
|
|
848
971
|
const switchText =
|
|
849
972
|
data && remain > 30_000
|
|
@@ -892,7 +1015,7 @@ window.__ModuleLoader__.load({
|
|
|
892
1015
|
{ key: 'pills', style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
|
|
893
1016
|
h(
|
|
894
1017
|
Pill,
|
|
895
|
-
{ style: { background: peakNow ?
|
|
1018
|
+
{ style: { background: peakNow ? tint(C.peak) : tint(C.valley), borderColor: 'transparent' } },
|
|
896
1019
|
h(Dot, { tone: peakNow ? C.peak : C.valley, glow: true }),
|
|
897
1020
|
h(
|
|
898
1021
|
'span',
|
|
@@ -907,7 +1030,7 @@ window.__ModuleLoader__.load({
|
|
|
907
1030
|
h(
|
|
908
1031
|
Pill,
|
|
909
1032
|
{
|
|
910
|
-
style: walletAlert ? { borderColor: walletTone, background:
|
|
1033
|
+
style: walletAlert ? { borderColor: walletTone, background: tint(walletTone) } : null,
|
|
911
1034
|
title:
|
|
912
1035
|
wallet && wallet.avgPerDay
|
|
913
1036
|
? `${t('wallet.avg')} ${yuan(wallet.avgPerDay)} · ${t('kpi.runwayHint')}`
|
|
@@ -923,7 +1046,7 @@ window.__ModuleLoader__.load({
|
|
|
923
1046
|
? h(
|
|
924
1047
|
'span',
|
|
925
1048
|
{ style: { color: walletTone, fontWeight: 600 } },
|
|
926
|
-
` · ${runwayLabel} ${runway(wallet.runwayDays, t)}`,
|
|
1049
|
+
` · ${runwayLabel} ${runway(wallet.runwayDays, t)}${alert.budgetExceeded ? ` · ${t('alerts.exceeded')}` : ''}`,
|
|
927
1050
|
)
|
|
928
1051
|
: null,
|
|
929
1052
|
),
|
|
@@ -963,7 +1086,7 @@ window.__ModuleLoader__.load({
|
|
|
963
1086
|
tone: walletAlert ? walletTone : C.text,
|
|
964
1087
|
hint:
|
|
965
1088
|
wallet && wallet.balance !== null
|
|
966
|
-
? `${t('kpi.balance')} ${yuan(wallet.balance)} · ${t('wallet.avg')} ${yuan(wallet.avgPerDay)}`
|
|
1089
|
+
? `${t('kpi.balance')} ${yuan(wallet.balance)} · ${t('wallet.avg')} ${yuan(wallet.avgPerDay)}${alert.budgetExceeded ? ` · ${t('alerts.exceeded')}` : ''}`
|
|
967
1090
|
: t('kpi.runwayHint'),
|
|
968
1091
|
}),
|
|
969
1092
|
h(Kpi, {
|
|
@@ -1038,7 +1161,7 @@ window.__ModuleLoader__.load({
|
|
|
1038
1161
|
body.push(
|
|
1039
1162
|
h(
|
|
1040
1163
|
'div',
|
|
1041
|
-
{ key: 'breakdown', style: { display: 'grid', gridTemplateColumns: '
|
|
1164
|
+
{ key: 'breakdown', style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 330px), 1fr))', gap: 10 } },
|
|
1042
1165
|
h(
|
|
1043
1166
|
Card,
|
|
1044
1167
|
null,
|
|
@@ -1048,7 +1171,7 @@ window.__ModuleLoader__.load({
|
|
|
1048
1171
|
action: h(
|
|
1049
1172
|
'a',
|
|
1050
1173
|
{
|
|
1051
|
-
href: `${EXPORT_URL
|
|
1174
|
+
href: `${feedUrl(EXPORT_URL, windowDays, project)}&scope=projects`,
|
|
1052
1175
|
download: '',
|
|
1053
1176
|
title: t('export.projectsTitle'),
|
|
1054
1177
|
style: { color: C.cache, textDecoration: 'none', fontWeight: 500 },
|
|
@@ -1056,7 +1179,7 @@ window.__ModuleLoader__.load({
|
|
|
1056
1179
|
t('export.projects'),
|
|
1057
1180
|
),
|
|
1058
1181
|
}),
|
|
1059
|
-
h(ProjectTable, { projects: data.projects, t }),
|
|
1182
|
+
h(ProjectTable, { projects: data.projects, t, onSelect: setProject }),
|
|
1060
1183
|
),
|
|
1061
1184
|
h(
|
|
1062
1185
|
Card,
|
|
@@ -1147,7 +1270,7 @@ window.__ModuleLoader__.load({
|
|
|
1147
1270
|
h(
|
|
1148
1271
|
'a',
|
|
1149
1272
|
{
|
|
1150
|
-
href:
|
|
1273
|
+
href: feedUrl(EXPORT_URL, windowDays, project),
|
|
1151
1274
|
download: '',
|
|
1152
1275
|
title: t('export.daysTitle'),
|
|
1153
1276
|
style: {
|
|
@@ -1163,6 +1286,16 @@ window.__ModuleLoader__.load({
|
|
|
1163
1286
|
t('export.csv'),
|
|
1164
1287
|
),
|
|
1165
1288
|
),
|
|
1289
|
+
h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' } },
|
|
1290
|
+
h('label', { style: { minWidth: 0, maxWidth: '100%' } }, t('projects.select'), ' ', h('select', { value: project, onChange: (event) => setProject(event.target.value), style: { color: C.text, background: C.layer1, border: `1px solid ${C.border}`, padding: 5, borderRadius: 6, maxWidth: '100%', minWidth: 0 } },
|
|
1291
|
+
h('option', { value: '' }, t('projects.all')),
|
|
1292
|
+
project && !(data && data.projectOptions || []).some((entry) => entry.key === project) ? h('option', { value: project }, project) : null,
|
|
1293
|
+
((data && data.projectOptions) || []).map((entry) => h('option', { key: entry.key, value: entry.key }, entry.name)))) ,
|
|
1294
|
+
project ? h(Pill, { title: data && data.selectedProject ? data.selectedProject.path : project }, data && data.selectedProject ? data.selectedProject.name : project,
|
|
1295
|
+
h('button', { type: 'button', onClick: () => setProject(''), 'aria-label': t('projects.clear'), style: { border: 0, background: 'transparent', color: C.text, cursor: 'pointer' } }, '×')) : null),
|
|
1296
|
+
h(AlertSettings, { prefs, t }),
|
|
1297
|
+
feed.error && data ? h('div', { role: 'status', style: { color: C.peak, fontSize: 12 } }, t('page.error'), ': ', feed.error, ' ', h('button', { type: 'button', onClick: () => feed.reload(true) }, t('page.retry'))) : null,
|
|
1298
|
+
alert.budgetExceeded ? h(Pill, { style: { color: alert.tone, borderColor: alert.tone } }, t('alerts.exceeded'), ' · ', t('alerts.global'), ' ', yuan(data && data.globalTodayCost)) : null,
|
|
1166
1299
|
body,
|
|
1167
1300
|
h(
|
|
1168
1301
|
'footer',
|
package/index.js
CHANGED
|
@@ -21,6 +21,7 @@ const REPO_URL = 'https://github.com/hhse/dsh-usage-peak';
|
|
|
21
21
|
const VERSION = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version;
|
|
22
22
|
const ROUTE_BASE = '/plugin/dsh-usage-peak';
|
|
23
23
|
const SNAPSHOT_TTL_MS = 15_000;
|
|
24
|
+
const MAX_SNAPSHOTS = 64;
|
|
24
25
|
const BJ_OFFSET = 8 * 60 * 60 * 1000;
|
|
25
26
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
26
27
|
const DEFAULT_DAYS = 14;
|
|
@@ -202,7 +203,7 @@ export function parseSessionTurns(text, project) {
|
|
|
202
203
|
/* ------------------------------------------------------------------ */
|
|
203
204
|
|
|
204
205
|
const fileCache = new Map(); // file -> { mtimeMs, size, turns }
|
|
205
|
-
const snapshotCache = new Map(); // window days -> { builtAt, payload }
|
|
206
|
+
const snapshotCache = new Map(); // [window days, exact project key] -> { builtAt, payload }
|
|
206
207
|
|
|
207
208
|
export function normalizeDays(value) {
|
|
208
209
|
const days = Number(value);
|
|
@@ -412,6 +413,18 @@ export function walletSummary(balance, avgPerDay) {
|
|
|
412
413
|
export function aggregateTurns(turns, options = {}) {
|
|
413
414
|
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
414
415
|
const days = normalizeDays(options.days);
|
|
416
|
+
// Keys are opaque identities: do not trim, prefix-match, or URL-decode here.
|
|
417
|
+
// URLSearchParams already performs the single required HTTP decoding pass.
|
|
418
|
+
const projectKey = typeof options.project === 'string' && options.project !== '' ? options.project : null;
|
|
419
|
+
if (projectKey !== null) {
|
|
420
|
+
const global = aggregateTurns(turns, { now, days });
|
|
421
|
+
const filtered = aggregateTurns((turns || []).filter((turn) => turn?.project?.key === projectKey), { now, days });
|
|
422
|
+
const known = global.projects.find((project) => project.key === projectKey);
|
|
423
|
+
const selectedProject = known
|
|
424
|
+
? { key: known.key, name: known.name, path: known.path }
|
|
425
|
+
: { key: projectKey, name: path.basename(projectKey) || projectKey, path: projectKey };
|
|
426
|
+
return { ...filtered, selectedProject, projectOptions: global.projects };
|
|
427
|
+
}
|
|
415
428
|
const byDay = new Map();
|
|
416
429
|
const byProject = new Map();
|
|
417
430
|
const unknownModels = new Set();
|
|
@@ -506,6 +519,8 @@ export function aggregateTurns(turns, options = {}) {
|
|
|
506
519
|
hours: today ? today.hours : [],
|
|
507
520
|
window,
|
|
508
521
|
projects,
|
|
522
|
+
selectedProject: null,
|
|
523
|
+
projectOptions: projects,
|
|
509
524
|
week: {
|
|
510
525
|
cost: round(week.cost),
|
|
511
526
|
calls: week.calls,
|
|
@@ -530,12 +545,22 @@ export function aggregateTurns(turns, options = {}) {
|
|
|
530
545
|
export function buildSnapshot(options = {}) {
|
|
531
546
|
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
532
547
|
const days = normalizeDays(options.days);
|
|
533
|
-
const
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
548
|
+
const project = typeof options.project === 'string' && options.project !== '' ? options.project : null;
|
|
549
|
+
const cacheKey = JSON.stringify([days, project]);
|
|
550
|
+
const cached = snapshotCache.get(cacheKey);
|
|
551
|
+
if (cached && !options.fresh && now >= cached.builtAt && now - cached.builtAt < SNAPSHOT_TTL_MS) return cached.payload;
|
|
552
|
+
|
|
553
|
+
const turns = collectTurns();
|
|
554
|
+
const global = aggregateTurns(turns, { now, days });
|
|
555
|
+
// Reuse the already-built directory rather than aggregating all projects twice.
|
|
556
|
+
const selected = project === null ? null : global.projects.find((entry) => entry.key === project);
|
|
557
|
+
const selectedProject = project === null ? null : selected
|
|
558
|
+
? { key: selected.key, name: selected.name, path: selected.path }
|
|
559
|
+
: { key: project, name: path.basename(project) || project, path: project };
|
|
560
|
+
const agg = project === null ? global : aggregateTurns(turns.filter((turn) => turn.project?.key === project), { now, days });
|
|
537
561
|
const ledger = readLedger();
|
|
538
|
-
|
|
562
|
+
// Ledger values are account-level, not attributable to an individual project.
|
|
563
|
+
if (ledger.ok && project === null) {
|
|
539
564
|
for (const entry of agg.window) {
|
|
540
565
|
const booked = ledger.history && ledger.history[entry.day];
|
|
541
566
|
entry.ledger = typeof booked === 'number' ? round(booked) : null;
|
|
@@ -572,8 +597,11 @@ export function buildSnapshot(options = {}) {
|
|
|
572
597
|
hours: agg.hours,
|
|
573
598
|
days: agg.window,
|
|
574
599
|
projects: agg.projects,
|
|
600
|
+
selectedProject,
|
|
601
|
+
projectOptions: global.projects,
|
|
602
|
+
globalTodayCost: global.today.cost,
|
|
575
603
|
week: agg.week,
|
|
576
|
-
wallet: walletSummary(ledger.ok ? ledger.balance : null,
|
|
604
|
+
wallet: walletSummary(ledger.ok ? ledger.balance : null, global.week.avgPerDay),
|
|
577
605
|
models: agg.models,
|
|
578
606
|
pricing: PRICING.map((price) => ({
|
|
579
607
|
id: price.id,
|
|
@@ -586,7 +614,14 @@ export function buildSnapshot(options = {}) {
|
|
|
586
614
|
warnings: agg.warnings,
|
|
587
615
|
};
|
|
588
616
|
|
|
589
|
-
|
|
617
|
+
// Project is user-controlled, so avoid retaining one snapshot for every
|
|
618
|
+
// arbitrary key forever. Drop expired entries and bound live snapshots FIFO.
|
|
619
|
+
for (const [key, entry] of snapshotCache) {
|
|
620
|
+
if (now < entry.builtAt || now - entry.builtAt >= SNAPSHOT_TTL_MS) snapshotCache.delete(key);
|
|
621
|
+
}
|
|
622
|
+
snapshotCache.delete(cacheKey);
|
|
623
|
+
while (snapshotCache.size >= MAX_SNAPSHOTS) snapshotCache.delete(snapshotCache.keys().next().value);
|
|
624
|
+
snapshotCache.set(cacheKey, { builtAt: now, payload });
|
|
590
625
|
return payload;
|
|
591
626
|
}
|
|
592
627
|
|
|
@@ -721,8 +756,9 @@ export function apply(ctx) {
|
|
|
721
756
|
const url = new URL(req.url || '/', 'http://127.0.0.1');
|
|
722
757
|
const fresh = url.searchParams.get('fresh') === '1' || url.searchParams.get('fresh') === 'true';
|
|
723
758
|
const days = normalizeDays(url.searchParams.get('days'));
|
|
759
|
+
const project = url.searchParams.get('project');
|
|
724
760
|
try {
|
|
725
|
-
sendJson(res, 200, buildSnapshot({ days, fresh }));
|
|
761
|
+
sendJson(res, 200, buildSnapshot({ days, fresh, project }));
|
|
726
762
|
} catch (error) {
|
|
727
763
|
sendJson(res, 500, { ok: false, error: String((error && error.stack) || error) });
|
|
728
764
|
}
|
|
@@ -741,8 +777,9 @@ export function apply(ctx) {
|
|
|
741
777
|
const url = new URL(req.url || '/', 'http://127.0.0.1');
|
|
742
778
|
const days = normalizeDays(url.searchParams.get('days'));
|
|
743
779
|
const scope = url.searchParams.get('scope') === 'projects' ? 'projects' : 'days';
|
|
780
|
+
const project = url.searchParams.get('project');
|
|
744
781
|
try {
|
|
745
|
-
const snapshot = buildSnapshot({ days, fresh: true });
|
|
782
|
+
const snapshot = buildSnapshot({ days, fresh: true, project });
|
|
746
783
|
const body = Buffer.from(`\uFEFF${buildCsv(snapshot, scope)}`, 'utf8');
|
|
747
784
|
res.writeHead(200, {
|
|
748
785
|
'Content-Type': 'text/csv; charset=utf-8',
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-usage-peak",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.1",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "DeepSeek Harness 用量峰谷仪表盘:峰/谷时段(含节假日与调休)、今日花费与 tokens
|
|
5
|
+
"description": "DeepSeek Harness 用量峰谷仪表盘:峰/谷时段(含节假日与调休)、今日花费与 tokens、项目下钻/模型统计、可配置预算预警、余额可撑天数、CSV 导出、7/14/30 天窗口、缓存命中、谷时更省,侧栏常驻胶囊 + 设置页详情。",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": "./index.js",
|
|
8
8
|
"./client": "./client.js",
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
"access": "public"
|
|
68
68
|
},
|
|
69
69
|
"scripts": {
|
|
70
|
-
"test": "node --test test
|
|
70
|
+
"test": "node --test test/*.test.js",
|
|
71
71
|
"check": "node --check index.js && node --check client.js && npm test"
|
|
72
72
|
}
|
|
73
73
|
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import vm from 'node:vm';
|
|
4
|
+
import test from 'node:test';
|
|
5
|
+
|
|
6
|
+
// Evaluate only the production pure/storage helpers; no React/DOM rendering.
|
|
7
|
+
const source = fs.readFileSync(new URL('../client.js', import.meta.url), 'utf8');
|
|
8
|
+
function helpers(storage = {}) {
|
|
9
|
+
const events = [];
|
|
10
|
+
const context = { window: { localStorage: storage, dispatchEvent: (event) => events.push(event) }, CustomEvent: class { constructor(type, options) { this.type = type; this.detail = options.detail; } }, C: { error: 'red', peak: 'amber', text3: 'gray' }, DATA_URL: '/data', DEFAULT_DAYS: 14 };
|
|
11
|
+
const start = source.indexOf(" const PREFS_KEY =");
|
|
12
|
+
const stop = source.indexOf(' function useFeed(', start);
|
|
13
|
+
vm.runInNewContext(source.slice(start, stop) + '\nthis.api = { validatePrefs, readPrefs, savePrefs, alertState, feedUrl, requestGate, tint, pillStatus };', context);
|
|
14
|
+
return { ...context.api, events };
|
|
15
|
+
}
|
|
16
|
+
const plain = (value) => JSON.parse(JSON.stringify(value));
|
|
17
|
+
|
|
18
|
+
test('client validates finite positive thresholds and ordered runway limits', () => {
|
|
19
|
+
const api = helpers();
|
|
20
|
+
assert.deepEqual(plain(api.validatePrefs({ warnDays: '8', lowDays: '2', dailyBudget: '' })), { warnDays: 8, lowDays: 2, dailyBudget: null });
|
|
21
|
+
for (const value of [0, -1, Infinity, NaN, 'abc', true, ' ']) {
|
|
22
|
+
assert.equal(api.validatePrefs({ warnDays: value, lowDays: 1 }), null);
|
|
23
|
+
}
|
|
24
|
+
assert.equal(api.validatePrefs({ warnDays: 3, lowDays: 3 }), null);
|
|
25
|
+
assert.equal(api.validatePrefs({ warnDays: 7, lowDays: 3, dailyBudget: -1 }), null);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('client storage exceptions retain valid in-memory preferences and dispatch sync event', () => {
|
|
29
|
+
const api = helpers({ getItem() { throw Error('blocked'); }, setItem() { throw Error('quota'); } });
|
|
30
|
+
assert.equal(api.readPrefs().warnDays, 7);
|
|
31
|
+
assert.equal(api.savePrefs({ warnDays: 10, lowDays: 4, dailyBudget: 20 }), true);
|
|
32
|
+
assert.equal(api.readPrefs().warnDays, 10);
|
|
33
|
+
assert.equal(api.events.length, 1);
|
|
34
|
+
assert.equal(api.events[0].type, 'dsh-usage-peak:alerts-change');
|
|
35
|
+
assert.equal(api.savePrefs({ warnDays: 1, lowDays: 2 }), false);
|
|
36
|
+
assert.equal(api.events.length, 1);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test('client quota errors do not restore stale readable storage over unsaved preferences', () => {
|
|
40
|
+
const api = helpers({ getItem: () => JSON.stringify({ warnDays: 7, lowDays: 3, dailyBudget: null }), setItem() { throw Error('quota'); } });
|
|
41
|
+
assert.equal(api.readPrefs().warnDays, 7);
|
|
42
|
+
api.savePrefs({ warnDays: 10, lowDays: 4, dailyBudget: 20 });
|
|
43
|
+
assert.equal(api.readPrefs().warnDays, 10);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test('client corrupt storage falls back and valid storage restores', () => {
|
|
47
|
+
let raw = '{broken';
|
|
48
|
+
const api = helpers({ getItem: () => raw });
|
|
49
|
+
assert.equal(api.readPrefs().lowDays, 3);
|
|
50
|
+
raw = JSON.stringify({ warnDays: 9, lowDays: 2, dailyBudget: 30 });
|
|
51
|
+
assert.equal(api.readPrefs().dailyBudget, 30);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('client global budget and runway boundary levels use highest alert, never selected cost', () => {
|
|
55
|
+
const api = helpers();
|
|
56
|
+
const prefs = { warnDays: 7, lowDays: 3, dailyBudget: 100 };
|
|
57
|
+
const check = (days, cost) => api.alertState({ wallet: { runwayDays: days }, globalTodayCost: cost, today: { cost: 0 } }, prefs);
|
|
58
|
+
assert.equal(check(7, 100).level, 'ok');
|
|
59
|
+
assert.equal(check(6.99, 100).level, 'warn');
|
|
60
|
+
assert.equal(check(3, 100).level, 'warn');
|
|
61
|
+
assert.equal(check(2.99, 0).level, 'low');
|
|
62
|
+
assert.equal(check(20, 100.01).level, 'warn');
|
|
63
|
+
assert.equal(check(20, 120).level, 'low');
|
|
64
|
+
assert.equal(check(3, 120).level, 'low');
|
|
65
|
+
assert.equal(check(null, 0).walletLevel, 'unknown');
|
|
66
|
+
assert.equal(api.alertState({ wallet: { runwayDays: 20 }, today: { cost: 999 } }, prefs).budgetLevel, 'unknown');
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('client data and CSV URLs encode project identity and preserve scope', () => {
|
|
70
|
+
const api = helpers();
|
|
71
|
+
const project = '/项目/a b?x=1&foo=#';
|
|
72
|
+
assert.equal(api.feedUrl('/data', 7, project, true), `/data?days=7&project=${encodeURIComponent(project)}&fresh=1`);
|
|
73
|
+
assert.equal(`${api.feedUrl('/export.csv', 30, project)}&scope=projects`, `/export.csv?days=30&project=${encodeURIComponent(project)}&scope=projects`);
|
|
74
|
+
assert.equal(api.feedUrl('/data', 14, ''), '/data?days=14');
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test('client alert prefix keeps the peak/valley countdown visible', () => {
|
|
78
|
+
const api = helpers();
|
|
79
|
+
assert.equal(api.pillStatus(true, '2:43 后转谷'), '⚠ 2:43 后转谷');
|
|
80
|
+
assert.equal(api.pillStatus(false, '2:43 后转谷'), '2:43 后转谷');
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('client request generation guard rejects old filters, refreshes, and unmount results', () => {
|
|
84
|
+
const gate = helpers().requestGate();
|
|
85
|
+
gate.select('alpha');
|
|
86
|
+
const first = gate.begin('alpha');
|
|
87
|
+
gate.select('beta');
|
|
88
|
+
assert.equal(gate.current(first), false);
|
|
89
|
+
const second = gate.begin('beta');
|
|
90
|
+
assert.equal(gate.current(second), true);
|
|
91
|
+
const refresh = gate.begin('beta');
|
|
92
|
+
assert.equal(gate.current(second), false);
|
|
93
|
+
assert.equal(gate.current(refresh), true);
|
|
94
|
+
gate.invalidate();
|
|
95
|
+
assert.equal(gate.current(refresh), false);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('client uses valid CSS color mixing and native keyboard buttons', () => {
|
|
99
|
+
assert.equal(helpers().tint('var(--color)', 14), 'color-mix(in srgb, var(--color) 14%, transparent)');
|
|
100
|
+
assert.doesNotMatch(source, /\$\{(?:C\.\w+|walletTone|props\.tone)\}(?:14|1a|22)/);
|
|
101
|
+
assert.match(source, /onClick: \(\) => onSelect\(project.key\)/);
|
|
102
|
+
assert.match(source, /'aria-label': t\('projects.clear'\)/);
|
|
103
|
+
assert.match(source, /window.addEventListener\('storage', sync\)/);
|
|
104
|
+
});
|
package/test/core.test.js
CHANGED
|
@@ -7,6 +7,8 @@ import zlib from 'node:zlib';
|
|
|
7
7
|
|
|
8
8
|
import {
|
|
9
9
|
aggregateTurns,
|
|
10
|
+
apply,
|
|
11
|
+
buildSnapshot,
|
|
10
12
|
buildCsv,
|
|
11
13
|
csvEscape,
|
|
12
14
|
decodeSessionFile,
|
|
@@ -359,3 +361,174 @@ test('buildCsv escapes cells and guards spreadsheet formulas', () => {
|
|
|
359
361
|
assert.match(projects, /"a,b",\/x,1,2,0.1,0.1,1\n$/);
|
|
360
362
|
assert.equal(buildCsv({ days: [] }, 'bogus'), 'day,calls,tokens,cost,cost_cache,cost_miss,cost_out,peak_cost,valley_cost,saving_if_valley,peak_share,hit_rate,holiday\n');
|
|
361
363
|
});
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
const filterAlpha = { key: '/项目/alpha + 100% & #', name: 'alpha + 100% & #', path: '/项目/alpha + 100% & #' };
|
|
367
|
+
const filterBeta = { key: '/项目/alpha + 100% & #-child', name: 'beta', path: '/项目/beta' };
|
|
368
|
+
function filterTurns(now) {
|
|
369
|
+
return [
|
|
370
|
+
{ t: now, model: 'deepseek-flash', input: 1e6, cache: 0, output: 0, project: filterAlpha },
|
|
371
|
+
{ t: now, model: 'deepseek-pro', input: 2e6, cache: 0, output: 0, project: filterBeta },
|
|
372
|
+
{ t: now, model: 'mystery', input: 1e6, cache: 0, output: 0 },
|
|
373
|
+
];
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
test('project drilldown uses exact opaque keys and preserves the full project directory', () => {
|
|
377
|
+
const now = bj(2026, 11, 10, 10);
|
|
378
|
+
const turns = filterTurns(now);
|
|
379
|
+
const global = aggregateTurns(turns, { now, days: 7 });
|
|
380
|
+
const alpha = aggregateTurns(turns, { now, days: 7, project: filterAlpha.key });
|
|
381
|
+
assert.deepEqual(alpha.selectedProject, filterAlpha);
|
|
382
|
+
assert.deepEqual(alpha.projectOptions, global.projects);
|
|
383
|
+
assert.equal(alpha.today.calls, 1);
|
|
384
|
+
assert.equal(alpha.today.cost, 2);
|
|
385
|
+
assert.equal(alpha.week.cost, 2);
|
|
386
|
+
assert.equal(alpha.hours[10].calls, 1);
|
|
387
|
+
assert.deepEqual(alpha.models.map((m) => m.calls), [1, 0]);
|
|
388
|
+
assert.deepEqual(alpha.warnings, []);
|
|
389
|
+
assert.equal(alpha.projects.length, 1);
|
|
390
|
+
assert.equal(alpha.projects[0].share, 1);
|
|
391
|
+
assert.equal(global.selectedProject, null);
|
|
392
|
+
assert.deepEqual(aggregateTurns(turns, { now, project: '' }).selectedProject, null);
|
|
393
|
+
const unknown = aggregateTurns(turns, { now, days: 7, project: '/missing' });
|
|
394
|
+
assert.deepEqual(unknown.selectedProject, { key: '/missing', name: 'missing', path: '/missing' });
|
|
395
|
+
assert.equal(unknown.today.calls, 0);
|
|
396
|
+
assert.equal(unknown.window.length, 7);
|
|
397
|
+
assert.deepEqual(unknown.projects, []);
|
|
398
|
+
assert.deepEqual(unknown.projectOptions, global.projects);
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
function snapshotFixture(t) {
|
|
402
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'usage-filter-'));
|
|
403
|
+
const now = bj(2036, 11, 10, 10);
|
|
404
|
+
const turns = filterTurns(now);
|
|
405
|
+
for (const [i, turn] of turns.entries()) {
|
|
406
|
+
const session = path.join(dir, '.dsh/sessions', `workspace-${i}`, 'session');
|
|
407
|
+
fs.mkdirSync(session, { recursive: true });
|
|
408
|
+
const text = [
|
|
409
|
+
JSON.stringify({ type: 'session', cwd: turn.project?.key || '/legacy' }),
|
|
410
|
+
JSON.stringify({
|
|
411
|
+
type: 'assistant/message',
|
|
412
|
+
time: turn.t,
|
|
413
|
+
data: { usage: { inputTokens: turn.input }, message: { source: { model: turn.model } } },
|
|
414
|
+
}),
|
|
415
|
+
].join('\n');
|
|
416
|
+
fs.writeFileSync(path.join(session, 'session.v4.jsonl.zstd'), zlib.zstdCompressSync(Buffer.from(text)));
|
|
417
|
+
}
|
|
418
|
+
fs.writeFileSync(
|
|
419
|
+
path.join(dir, '.dsh/.dshw-usage.json'),
|
|
420
|
+
JSON.stringify({ lastBalance: 70, history: { '2036-11-10': 99 } }),
|
|
421
|
+
);
|
|
422
|
+
t.mock.method(os, 'homedir', () => dir);
|
|
423
|
+
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
|
424
|
+
return { now };
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
test('snapshot caches isolate project and window while wallet and global spend stay global', (t) => {
|
|
428
|
+
const { now } = snapshotFixture(t);
|
|
429
|
+
const global = buildSnapshot({ now, days: 7, fresh: true });
|
|
430
|
+
const alpha = buildSnapshot({ now, days: 7, project: filterAlpha.key, fresh: true });
|
|
431
|
+
const beta = buildSnapshot({ now, days: 7, project: filterBeta.key, fresh: true });
|
|
432
|
+
assert.equal(alpha.today.calls, 1);
|
|
433
|
+
assert.equal(beta.today.calls, 1);
|
|
434
|
+
assert.notEqual(alpha.today.cost, beta.today.cost);
|
|
435
|
+
assert.deepEqual(alpha.wallet, global.wallet);
|
|
436
|
+
assert.deepEqual(beta.wallet, global.wallet);
|
|
437
|
+
assert.equal(alpha.globalTodayCost, global.today.cost);
|
|
438
|
+
assert.equal(global.today.ledger, 99);
|
|
439
|
+
assert.equal(alpha.today.ledger, undefined);
|
|
440
|
+
assert.deepEqual(alpha.projectOptions, global.projects);
|
|
441
|
+
assert.strictEqual(buildSnapshot({ now: now + 1, days: 7, project: filterAlpha.key }), alpha);
|
|
442
|
+
assert.strictEqual(buildSnapshot({ now: now + 1, days: 7, project: filterBeta.key }), beta);
|
|
443
|
+
assert.strictEqual(buildSnapshot({ now: now + 1, days: 7 }), global);
|
|
444
|
+
assert.equal(buildSnapshot({ now, days: 14, project: filterAlpha.key, fresh: true }).days.length, 14);
|
|
445
|
+
const unknown = buildSnapshot({ now, days: 7, project: '/missing', fresh: true });
|
|
446
|
+
assert.equal(unknown.today.cost, 0);
|
|
447
|
+
assert.deepEqual(unknown.wallet, global.wallet);
|
|
448
|
+
assert.equal(unknown.globalTodayCost, global.today.cost);
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
function routeHarness(rejection) {
|
|
452
|
+
const routes = new Map();
|
|
453
|
+
const disposed = [];
|
|
454
|
+
let cleanup;
|
|
455
|
+
apply({
|
|
456
|
+
webServer: {
|
|
457
|
+
register(route) {
|
|
458
|
+
routes.set(route.path, route);
|
|
459
|
+
return () => disposed.push(route.path);
|
|
460
|
+
},
|
|
461
|
+
},
|
|
462
|
+
connection: { requestRejection() { return rejection; } },
|
|
463
|
+
effect(factory) { cleanup = factory(); },
|
|
464
|
+
});
|
|
465
|
+
return {
|
|
466
|
+
disposed,
|
|
467
|
+
cleanup: () => cleanup(),
|
|
468
|
+
async request(route, url, method = 'GET') {
|
|
469
|
+
const res = {
|
|
470
|
+
statusCode: 200,
|
|
471
|
+
headers: {},
|
|
472
|
+
body: Buffer.alloc(0),
|
|
473
|
+
writeHead(status, headers) {
|
|
474
|
+
this.statusCode = status;
|
|
475
|
+
this.headers = headers;
|
|
476
|
+
},
|
|
477
|
+
end(body) { this.body = Buffer.from(body || ''); },
|
|
478
|
+
};
|
|
479
|
+
await routes.get(`/plugin/dsh-usage-peak/${route}`).handler({ url, method }, res);
|
|
480
|
+
return res;
|
|
481
|
+
},
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
test('HTTP data and CSV routes decode project once, filter exports, and preserve BOM', async (t) => {
|
|
486
|
+
const { now } = snapshotFixture(t);
|
|
487
|
+
t.mock.method(Date, 'now', () => now);
|
|
488
|
+
const app = routeHarness();
|
|
489
|
+
const project = encodeURIComponent(filterAlpha.key);
|
|
490
|
+
const res = await app.request('data', `/plugin/dsh-usage-peak/data?days=7&fresh=1&project=${project}`);
|
|
491
|
+
assert.equal(res.statusCode, 200);
|
|
492
|
+
const payload = JSON.parse(res.body);
|
|
493
|
+
assert.deepEqual(payload.selectedProject, filterAlpha);
|
|
494
|
+
assert.equal(payload.today.calls, 1);
|
|
495
|
+
assert.equal(payload.projectOptions.length, 3);
|
|
496
|
+
const csv = await app.request('export.csv', `/plugin/dsh-usage-peak/export.csv?days=7&scope=projects&project=${project}`);
|
|
497
|
+
assert.equal(csv.statusCode, 200);
|
|
498
|
+
assert.deepEqual([...csv.body.subarray(0, 3)], [0xef, 0xbb, 0xbf]);
|
|
499
|
+
assert.match(csv.headers['Content-Type'], /^text\/csv/);
|
|
500
|
+
assert.match(csv.headers['Content-Disposition'], /^attachment;/);
|
|
501
|
+
assert.equal(Number(csv.headers['Content-Length']), csv.body.length);
|
|
502
|
+
assert.equal(csv.headers['Cache-Control'], 'no-store');
|
|
503
|
+
const text = csv.body.toString('utf8');
|
|
504
|
+
assert.ok(text.includes(filterAlpha.key));
|
|
505
|
+
assert.ok(!text.includes(filterBeta.key));
|
|
506
|
+
assert.equal(text.trim().split('\n').length, 2);
|
|
507
|
+
const daily = await app.request('export.csv', `/?days=7&project=${project}`);
|
|
508
|
+
assert.ok(daily.body.toString('utf8').includes(buildCsv(payload, 'days')));
|
|
509
|
+
const unknown = await app.request('data', '/?project=%2Fmissing&fresh=1');
|
|
510
|
+
assert.equal(JSON.parse(unknown.body).today.calls, 0);
|
|
511
|
+
for (const route of ['data', 'export.csv']) {
|
|
512
|
+
assert.equal((await app.request(route, '/', 'POST')).statusCode, 405);
|
|
513
|
+
const rejected = routeHarness(401);
|
|
514
|
+
const denied = await rejected.request(route, '/');
|
|
515
|
+
assert.equal(denied.statusCode, 401);
|
|
516
|
+
assert.equal(denied.body.length, 0);
|
|
517
|
+
assert.equal((await routeHarness(true).request(route, '/')).statusCode, 403);
|
|
518
|
+
}
|
|
519
|
+
app.cleanup();
|
|
520
|
+
assert.deepEqual(app.disposed, ['/plugin/dsh-usage-peak/data', '/plugin/dsh-usage-peak/export.csv']);
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
test('snapshot cache bounds arbitrary keys and evicts expired entries', (t) => {
|
|
524
|
+
const { now } = snapshotFixture(t);
|
|
525
|
+
const oldest = buildSnapshot({ now, days: 7, project: '/cache-0', fresh: true });
|
|
526
|
+
for (let index = 1; index <= 64; index += 1) {
|
|
527
|
+
buildSnapshot({ now, days: 7, project: `/cache-${index}`, fresh: true });
|
|
528
|
+
}
|
|
529
|
+
assert.notStrictEqual(buildSnapshot({ now, days: 7, project: '/cache-0' }), oldest);
|
|
530
|
+
const current = buildSnapshot({ now, days: 7, project: '/cache-64' });
|
|
531
|
+
assert.strictEqual(buildSnapshot({ now: now + 1, days: 7, project: '/cache-64' }), current);
|
|
532
|
+
buildSnapshot({ now: now + 15000, days: 7, project: '/new-after-expiry' });
|
|
533
|
+
assert.notStrictEqual(buildSnapshot({ now: now + 15000, days: 7, project: '/cache-64' }), current);
|
|
534
|
+
});
|