dsh-usage-peak 1.0.1 → 1.2.0
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 +18 -0
- package/README.md +14 -5
- package/client.js +183 -22
- package/holidays.js +75 -0
- package/index.js +149 -81
- package/package.json +9 -3
- package/test/core.test.js +226 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.2.0
|
|
4
|
+
|
|
5
|
+
- 峰谷判断接入中国大陆节假日/调休日历:法定节假日全天谷时,调休上班日(含周末)按工作日峰谷计算。
|
|
6
|
+
- 新增 `holidays.js`(2026 年国务院办公厅安排,与 holiday-cn 交叉核对);缺失年份回落到周一至周五,并在面板给出 `calendar-missing` 提示。
|
|
7
|
+
- 趋势图 tooltip 标注节假日名称。
|
|
8
|
+
- 面板新增页脚:GitHub 仓库超链接(引导 Star)、当前版本号、日历覆盖年份。
|
|
9
|
+
- 快照新增 `version` / `repo` / `calendar` 字段,版本号由 `package.json` 单一来源读取。
|
|
10
|
+
|
|
11
|
+
## 1.1.0
|
|
12
|
+
|
|
13
|
+
- 新增 7 / 14 / 30 天统计窗口切换,接口支持 `?days=`(白名单校验,快照按窗口分别缓存)。
|
|
14
|
+
- 趋势图改为连续日期窗口,没有请求的日期补零,列数不再随数据缺失缩水。
|
|
15
|
+
- 新增「谷时更省」指标:峰时单价为谷时 2 倍,展示峰时用量改到谷时能省下的金额(今日 + 近 7 天)。
|
|
16
|
+
- 修复近 7 天卡片把 tokens 当金额显示(「平均每次 ¥102485.00」),改为日均花费 + 平均每次 tokens。
|
|
17
|
+
- 英文界面本地化补齐:图表 tooltip、命中价说明、万/亿改为 K/M/B、倒计时分钟后缀。
|
|
18
|
+
- 未识别模型的提示改为结构化 warning,由客户端按语言渲染。
|
|
19
|
+
- 宿主拆出可测试的纯函数(`aggregateTurns` / `parseSessionTurns` / `dayKey` 等),新增 `node:test` 测试与 `npm test` / `npm run check` 脚本。
|
|
20
|
+
|
|
3
21
|
## 1.0.1
|
|
4
22
|
|
|
5
23
|
- 修复冷启动后数据路由不存在的 404(宿主半声明 `inject = ['webServer']`,等 HTTP 载体就绪再注册路由)。
|
package/README.md
CHANGED
|
@@ -14,12 +14,14 @@
|
|
|
14
14
|
|
|
15
15
|
- **侧栏常驻胶囊**:`● 峰 ¥14.70 · 12.8M tok · 2:43 后转谷`,点一下打开完整面板。侧栏折叠时收成一个小圆点。
|
|
16
16
|
- **峰谷状态**:当前时段、距离下次切换的倒计时、当前时段单价(缓存命中 / 全价输入 / 输出)。
|
|
17
|
-
- **今日概况**:花费、请求数、tokens
|
|
17
|
+
- **今日概况**:花费、请求数、tokens、缓存命中率、峰时花费占比、**谷时更省**(把这些峰时用量挪到谷时能省下的钱)、余额。
|
|
18
18
|
- **今日 24 小时分布**:每小时花费柱状,峰时与谷时用不同颜色,当前小时高亮。
|
|
19
19
|
- **花费构成**:缓存命中 / 全价输入 / 输出 三段占比,直接看出钱花在哪。
|
|
20
|
-
- **近 14
|
|
20
|
+
- **近 7 / 14 / 30 天趋势**:右上角切换窗口,按天堆叠柱状,缺数据的日期补零,列数恒定;可对照峰时占比判断"贵在哪天"。
|
|
21
21
|
- **按模型**:Flash / Pro 各自的请求数、tokens、花费。
|
|
22
22
|
- **价目表**:当前时段那一行高亮,方便解释账单。
|
|
23
|
+
- **节假日与调休**:按国务院办公厅公布的安排判断——法定节假日全天谷时,调休上班的周末按工作日峰谷计算;当前覆盖 2026 年,缺失年份会在面板给出提示并回落到周一至周五规则。
|
|
24
|
+
- **页脚**:GitHub 仓库链接(可顺手点个 Star)、当前版本号与日历覆盖年份。
|
|
23
25
|
|
|
24
26
|
设置页里的入口是「用量仪表盘」,侧栏胶囊就是同一份数据的浓缩版。
|
|
25
27
|
|
|
@@ -32,7 +34,9 @@
|
|
|
32
34
|
| DeepSeek Flash | 0.02 / 0.04 | 1 / 2 | 4 / 8 |
|
|
33
35
|
| DeepSeek Pro | 0.15 / 0.30 | 4.5 / 9 | 13.5 / 27 |
|
|
34
36
|
|
|
35
|
-
峰时 =
|
|
37
|
+
峰时 = 工作日 09:00–12:00、14:00–18:00(北京时间);其余时间、周末与法定节假日为谷时,单价减半。调休上班日(包括周末)按工作日的峰谷窗口计算。
|
|
38
|
+
|
|
39
|
+
节假日数据在 [`holidays.js`](holidays.js),来源为[国务院办公厅 2026 年放假安排通知](https://www.gov.cn/zhengce/zhengceku/202511/content_7047091.htm),并与 [holiday-cn](https://github.com/NateScarlet/holiday-cn) 交叉核对。新一年安排公布后,补一组日期并把年份加进 `CALENDAR_YEARS` 即可。
|
|
36
40
|
|
|
37
41
|
## 数据来源
|
|
38
42
|
|
|
@@ -41,7 +45,9 @@
|
|
|
41
45
|
|
|
42
46
|
日志是**多帧 zstd**,Node 自带的 `zlib.zstdDecompressSync` 只解第一帧,所以插件内部按 zstd magic 切帧、逐帧解压再拼接(不需要 `zstd` 命令行)。
|
|
43
47
|
|
|
44
|
-
|
|
48
|
+
数据接口支持 `?days=7|14|30` 选择统计窗口(默认 14,白名单之外的取值回落到 14);快照按窗口分别缓存 15 秒,面板上的「刷新」按钮会带 `?fresh=1` 强制重算。
|
|
49
|
+
|
|
50
|
+
峰时单价恰为谷时 2 倍,所以「谷时更省」= 峰时花费 ÷ 2:它衡量的是这些峰时用量如果改在谷时发生能省多少,而不是已经省下的钱。
|
|
45
51
|
|
|
46
52
|
## 安装
|
|
47
53
|
|
|
@@ -80,7 +86,10 @@ A usage and cost dashboard for DeepSeek Harness. It reads the local session logs
|
|
|
80
86
|

|
|
81
87
|
|
|
82
88
|
- a persistent sidebar pill with peak/valley state, today's spend, tokens and the countdown to the next price switch;
|
|
83
|
-
-
|
|
89
|
+
- China public holidays and makeup workdays: holidays are valley all day, makeup weekend workdays follow the weekday windows (2026 calendar shipped; missing years fall back to Mon-Fri with a visible warning);
|
|
90
|
+
- a footer with the GitHub repository link, the running version and the covered calendar years;
|
|
91
|
+
- a details page (Settings → Usage dashboard) with KPIs, an hourly breakdown, cost composition, a 7/14/30-day trend switch, a per-model table and the price list;
|
|
92
|
+
- 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.
|
|
84
93
|
|
|
85
94
|
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).
|
|
86
95
|
|
package/client.js
CHANGED
|
@@ -17,6 +17,8 @@ window.__ModuleLoader__.load({
|
|
|
17
17
|
|
|
18
18
|
const NS = 'dsh-usage-peak';
|
|
19
19
|
const DATA_URL = '/plugin/dsh-usage-peak/data';
|
|
20
|
+
const DEFAULT_DAYS = 14;
|
|
21
|
+
const WINDOW_DAYS = [7, 14, 30];
|
|
20
22
|
|
|
21
23
|
const dicts = {
|
|
22
24
|
zh: {
|
|
@@ -46,21 +48,37 @@ window.__ModuleLoader__.load({
|
|
|
46
48
|
'status.valley': '谷时',
|
|
47
49
|
'status.switchIn': '距转',
|
|
48
50
|
|
|
51
|
+
'fmt.lang': 'zh',
|
|
52
|
+
'unit.calls': '次',
|
|
53
|
+
'unit.minute': '分',
|
|
54
|
+
'warn.unknownModel': '未识别的模型按 Flash 价计算',
|
|
55
|
+
'warn.calendarMissing': '以下年份还没有节假日数据,峰谷按周一至周五计算:',
|
|
56
|
+
'footer.calendar': '峰谷已计入节假日与调休:',
|
|
57
|
+
'footer.star': '给个 Star',
|
|
58
|
+
'range.7': '近 7 天',
|
|
59
|
+
'range.14': '近 14 天',
|
|
60
|
+
'range.30': '近 30 天',
|
|
61
|
+
|
|
49
62
|
'kpi.calls': '今日请求',
|
|
50
63
|
'kpi.tokens': 'tokens',
|
|
51
64
|
'kpi.hit': '缓存命中',
|
|
65
|
+
'kpi.hitHint': '命中价为未命中的 1/50',
|
|
52
66
|
'kpi.peakShare': '峰时占比',
|
|
53
67
|
'kpi.perCall': '平均每次',
|
|
68
|
+
'kpi.perDay': '日均',
|
|
54
69
|
'kpi.balance': '余额',
|
|
55
70
|
'kpi.today': '今日',
|
|
56
71
|
'kpi.cache': '缓存',
|
|
57
72
|
'kpi.out': '输出',
|
|
58
73
|
'kpi.peakCost': '峰',
|
|
59
74
|
'kpi.valleyCost': '谷',
|
|
75
|
+
'kpi.saving': '谷时更省',
|
|
76
|
+
'kpi.savingHint': '峰时按谷价计',
|
|
77
|
+
'kpi.windowSaving': '近 7 天可省',
|
|
60
78
|
|
|
61
79
|
'chart.hours': '今日每小时花费',
|
|
62
80
|
'chart.hoursHint': '橙 峰时 · 绿 谷时',
|
|
63
|
-
'chart.days': '
|
|
81
|
+
'chart.days': '每天花费',
|
|
64
82
|
'chart.daysHint': '橙 峰时 · 绿 谷时',
|
|
65
83
|
|
|
66
84
|
'cost.title': '今日花费构成',
|
|
@@ -104,21 +122,37 @@ window.__ModuleLoader__.load({
|
|
|
104
122
|
'status.valley': 'Valley',
|
|
105
123
|
'status.switchIn': 'in',
|
|
106
124
|
|
|
125
|
+
'fmt.lang': 'en',
|
|
126
|
+
'unit.calls': 'req',
|
|
127
|
+
'unit.minute': 'm',
|
|
128
|
+
'warn.unknownModel': 'Unknown models are priced as Flash',
|
|
129
|
+
'warn.calendarMissing': 'No holiday data for these years, peak hours fall back to Mon-Fri:',
|
|
130
|
+
'footer.calendar': 'Peak hours include holidays and makeup workdays:',
|
|
131
|
+
'footer.star': 'Star it',
|
|
132
|
+
'range.7': 'Last 7 days',
|
|
133
|
+
'range.14': 'Last 14 days',
|
|
134
|
+
'range.30': 'Last 30 days',
|
|
135
|
+
|
|
107
136
|
'kpi.calls': 'Requests',
|
|
108
137
|
'kpi.tokens': 'tokens',
|
|
109
138
|
'kpi.hit': 'Cache hit',
|
|
139
|
+
'kpi.hitHint': 'hit costs 1/50 of miss',
|
|
110
140
|
'kpi.peakShare': 'Peak share',
|
|
111
141
|
'kpi.perCall': 'per request',
|
|
142
|
+
'kpi.perDay': 'per day',
|
|
112
143
|
'kpi.balance': 'Balance',
|
|
113
144
|
'kpi.today': 'today',
|
|
114
145
|
'kpi.cache': 'cache',
|
|
115
146
|
'kpi.out': 'output',
|
|
116
147
|
'kpi.peakCost': 'peak',
|
|
117
148
|
'kpi.valleyCost': 'valley',
|
|
149
|
+
'kpi.saving': 'Valley saving',
|
|
150
|
+
'kpi.savingHint': 'peak tokens at valley price',
|
|
151
|
+
'kpi.windowSaving': '7d saving',
|
|
118
152
|
|
|
119
153
|
'chart.hours': 'Cost per hour today',
|
|
120
154
|
'chart.hoursHint': 'orange peak · green valley',
|
|
121
|
-
'chart.days': '
|
|
155
|
+
'chart.days': 'Spend by day',
|
|
122
156
|
'chart.daysHint': 'orange peak · green valley',
|
|
123
157
|
|
|
124
158
|
'cost.title': 'Today by token type',
|
|
@@ -158,8 +192,16 @@ window.__ModuleLoader__.load({
|
|
|
158
192
|
? '—'
|
|
159
193
|
: `¥${Number(value).toFixed(digits === undefined ? 2 : digits)}`;
|
|
160
194
|
|
|
161
|
-
|
|
195
|
+
/** Token count with the locale's own magnitude words: 1.2 万 / 1.2K. */
|
|
196
|
+
function tokens(value, t) {
|
|
162
197
|
if (!value) return '0';
|
|
198
|
+
const english = typeof t === 'function' && t('fmt.lang') === 'en';
|
|
199
|
+
if (english) {
|
|
200
|
+
if (value >= 1e9) return `${(value / 1e9).toFixed(2)}B`;
|
|
201
|
+
if (value >= 1e6) return `${(value / 1e6).toFixed(1)}M`;
|
|
202
|
+
if (value >= 1e3) return `${Math.round(value / 1e3)}K`;
|
|
203
|
+
return String(Math.round(value));
|
|
204
|
+
}
|
|
163
205
|
if (value >= 1e8) return `${(value / 1e8).toFixed(2)} 亿`;
|
|
164
206
|
if (value >= 1e4) return `${(value / 1e4).toFixed(1)} 万`;
|
|
165
207
|
return String(Math.round(value));
|
|
@@ -185,21 +227,23 @@ window.__ModuleLoader__.load({
|
|
|
185
227
|
}
|
|
186
228
|
|
|
187
229
|
/** Short numeric countdown: 27分 / 1:27 / 3:19. */
|
|
188
|
-
function countdown(ms) {
|
|
230
|
+
function countdown(ms, t) {
|
|
189
231
|
const total = Math.max(0, Math.round(ms / 60000));
|
|
190
232
|
const hours = Math.floor(total / 60);
|
|
191
233
|
const minutes = total % 60;
|
|
192
|
-
|
|
234
|
+
if (hours > 0) return `${hours}:${String(minutes).padStart(2, '0')}`;
|
|
235
|
+
return `${minutes}${typeof t === 'function' ? t('unit.minute') : '分'}`;
|
|
193
236
|
}
|
|
194
237
|
|
|
195
238
|
/* --------------------------------- data --------------------------------- */
|
|
196
239
|
|
|
197
|
-
function useFeed() {
|
|
240
|
+
function useFeed(days) {
|
|
241
|
+
const windowDays = days || 14;
|
|
198
242
|
const [state, setState] = useState({ loading: true, error: null, data: null });
|
|
199
243
|
const [tick, setTick] = useState(0);
|
|
200
244
|
|
|
201
245
|
const load = useCallback((fresh) => {
|
|
202
|
-
const url =
|
|
246
|
+
const url = `${DATA_URL}?days=${windowDays}${fresh ? '&fresh=1' : ''}`;
|
|
203
247
|
fetch(url, { headers: { accept: 'application/json' } })
|
|
204
248
|
.then((response) => {
|
|
205
249
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
@@ -212,7 +256,7 @@ window.__ModuleLoader__.load({
|
|
|
212
256
|
.catch((error) =>
|
|
213
257
|
setState((previous) => ({ loading: false, error: String(error && error.message), data: previous.data })),
|
|
214
258
|
);
|
|
215
|
-
}, []);
|
|
259
|
+
}, [windowDays]);
|
|
216
260
|
|
|
217
261
|
useEffect(() => {
|
|
218
262
|
load(false);
|
|
@@ -303,11 +347,11 @@ window.__ModuleLoader__.load({
|
|
|
303
347
|
const remain = data ? Math.max(0, data.now.nextAt - Date.now()) : 0;
|
|
304
348
|
const switchText =
|
|
305
349
|
data && remain > 30_000
|
|
306
|
-
? `${countdown(remain)} ${peak ? t('widget.toValley') : t('widget.toPeak')}`
|
|
350
|
+
? `${countdown(remain, t)} ${peak ? t('widget.toValley') : t('widget.toPeak')}`
|
|
307
351
|
: t('widget.soon');
|
|
308
352
|
const today = data && data.today ? data.today.cost : null;
|
|
309
353
|
const tip = data
|
|
310
|
-
? `${word} · ${t('widget.today')} ${yuan(today)} · ${tokens(data.today ? data.today.tokens : 0)} tokens · ${t('status.switchIn')} ${switchText}`
|
|
354
|
+
? `${word} · ${t('widget.today')} ${yuan(today)} · ${tokens(data.today ? data.today.tokens : 0, t)} tokens · ${t('status.switchIn')} ${switchText}`
|
|
311
355
|
: word;
|
|
312
356
|
|
|
313
357
|
// The seat is the shell's own flex row: the root takes a whole line (see
|
|
@@ -429,7 +473,7 @@ window.__ModuleLoader__.load({
|
|
|
429
473
|
'div',
|
|
430
474
|
{
|
|
431
475
|
key: entry.hour,
|
|
432
|
-
title: `${String(entry.hour).padStart(2, '0')}:00 · ${yuan(entry.cost)} · ${entry.calls}
|
|
476
|
+
title: `${String(entry.hour).padStart(2, '0')}:00 · ${yuan(entry.cost)} · ${entry.calls} ${props.t('unit.calls')}`,
|
|
433
477
|
style: {
|
|
434
478
|
flex: 1,
|
|
435
479
|
display: 'flex',
|
|
@@ -476,7 +520,7 @@ window.__ModuleLoader__.load({
|
|
|
476
520
|
h(
|
|
477
521
|
'div',
|
|
478
522
|
{
|
|
479
|
-
title: `${entry.day} · ${yuan(entry.cost)} · ${entry.calls}
|
|
523
|
+
title: `${entry.day}${entry.holiday ? ` · ${entry.holiday}` : ''} · ${yuan(entry.cost)} · ${entry.calls} ${props.t('unit.calls')}`,
|
|
480
524
|
style: {
|
|
481
525
|
flex: 1,
|
|
482
526
|
width: '100%',
|
|
@@ -591,13 +635,15 @@ window.__ModuleLoader__.load({
|
|
|
591
635
|
|
|
592
636
|
function Dashboard(props) {
|
|
593
637
|
const t = props.t;
|
|
594
|
-
const
|
|
638
|
+
const [days, setDays] = useState(props.days || 14);
|
|
639
|
+
const feed = useFeed(days);
|
|
595
640
|
const data = feed.data;
|
|
641
|
+
const windowDays = (data && data.windowDays) || days;
|
|
596
642
|
const peakNow = data ? data.now.peak : false;
|
|
597
643
|
const remain = data ? Math.max(0, data.now.nextAt - Date.now()) : 0;
|
|
598
644
|
const switchText =
|
|
599
645
|
data && remain > 30_000
|
|
600
|
-
? `${countdown(remain)} ${t(data.now.nextStatus === 'peak' ? 'widget.toPeak' : 'widget.toValley')}`
|
|
646
|
+
? `${countdown(remain, t)} ${t(data.now.nextStatus === 'peak' ? 'widget.toPeak' : 'widget.toValley')}`
|
|
601
647
|
: t('widget.soon');
|
|
602
648
|
|
|
603
649
|
const body = [];
|
|
@@ -664,10 +710,32 @@ window.__ModuleLoader__.load({
|
|
|
664
710
|
data.ledger && typeof data.ledger.balance === 'number' ? yuan(data.ledger.balance) : '—',
|
|
665
711
|
),
|
|
666
712
|
),
|
|
667
|
-
h(Pill, null, `${today.calls || 0}
|
|
713
|
+
h(Pill, null, `${today.calls || 0} ${t('unit.calls')} · ${tokens(today.tokens, t)} tokens`),
|
|
668
714
|
),
|
|
669
715
|
);
|
|
670
716
|
|
|
717
|
+
if (data.warnings && data.warnings.length) {
|
|
718
|
+
body.push(
|
|
719
|
+
h(
|
|
720
|
+
Card,
|
|
721
|
+
{ key: 'warnings', style: { borderColor: C.peak, gap: 4 } },
|
|
722
|
+
data.warnings.map((warning, index) =>
|
|
723
|
+
h(
|
|
724
|
+
'span',
|
|
725
|
+
{ key: index, style: { fontSize: 11.5, color: C.text2 } },
|
|
726
|
+
typeof warning === 'string'
|
|
727
|
+
? warning
|
|
728
|
+
: warning.code === 'unknown-model'
|
|
729
|
+
? `${t('warn.unknownModel')}: ${(warning.models || []).join(', ')}`
|
|
730
|
+
: warning.code === 'calendar-missing'
|
|
731
|
+
? `${t('warn.calendarMissing')} ${(warning.years || []).join(' / ')}`
|
|
732
|
+
: String(warning.code || warning),
|
|
733
|
+
),
|
|
734
|
+
),
|
|
735
|
+
),
|
|
736
|
+
);
|
|
737
|
+
}
|
|
738
|
+
|
|
671
739
|
body.push(
|
|
672
740
|
h(
|
|
673
741
|
'div',
|
|
@@ -675,20 +743,26 @@ window.__ModuleLoader__.load({
|
|
|
675
743
|
h(Kpi, {
|
|
676
744
|
label: t('kpi.calls'),
|
|
677
745
|
value: today.calls || 0,
|
|
678
|
-
hint: `${t('kpi.perCall')} ${tokens(today.avgTokens)}`,
|
|
746
|
+
hint: `${t('kpi.perCall')} ${tokens(today.avgTokens, t)}`,
|
|
679
747
|
}),
|
|
680
748
|
h(Kpi, {
|
|
681
749
|
label: t('kpi.tokens'),
|
|
682
|
-
value: tokens(today.tokens),
|
|
683
|
-
hint: `${t('kpi.cache')} ${tokens(today.cacheTokens)} · ${t('kpi.out')} ${tokens(today.outputTokens)}`,
|
|
750
|
+
value: tokens(today.tokens, t),
|
|
751
|
+
hint: `${t('kpi.cache')} ${tokens(today.cacheTokens, t)} · ${t('kpi.out')} ${tokens(today.outputTokens, t)}`,
|
|
684
752
|
}),
|
|
685
|
-
h(Kpi, { label: t('kpi.hit'), value: percent(today.hitRate), hint: '
|
|
753
|
+
h(Kpi, { label: t('kpi.hit'), value: percent(today.hitRate), hint: t('kpi.hitHint') }),
|
|
686
754
|
h(Kpi, {
|
|
687
755
|
label: t('kpi.peakShare'),
|
|
688
756
|
value: percent(today.peakShare, 0),
|
|
689
757
|
tone: (today.peakShare || 0) > 0.5 ? C.peak : C.valley,
|
|
690
758
|
hint: `${t('kpi.peakCost')} ${yuan(today.peakCost)} · ${t('kpi.valleyCost')} ${yuan(today.valleyCost)}`,
|
|
691
759
|
}),
|
|
760
|
+
h(Kpi, {
|
|
761
|
+
label: t('kpi.saving'),
|
|
762
|
+
value: yuan(today.savingIfValley),
|
|
763
|
+
tone: C.valley,
|
|
764
|
+
hint: `${t('kpi.windowSaving')} ${yuan(data.week.savingIfValley)}`,
|
|
765
|
+
}),
|
|
692
766
|
),
|
|
693
767
|
);
|
|
694
768
|
|
|
@@ -700,7 +774,7 @@ window.__ModuleLoader__.load({
|
|
|
700
774
|
Card,
|
|
701
775
|
null,
|
|
702
776
|
h(CardTitle, { title: t('chart.hours'), hint: t('chart.hoursHint') }),
|
|
703
|
-
h(HourChart, { hours: data.hours, nowHour: data.now.hour }),
|
|
777
|
+
h(HourChart, { hours: data.hours, nowHour: data.now.hour, t }),
|
|
704
778
|
h(
|
|
705
779
|
'div',
|
|
706
780
|
{ style: { display: 'flex', justifyContent: 'space-between', fontSize: 9.5, color: C.text3 } },
|
|
@@ -728,9 +802,9 @@ window.__ModuleLoader__.load({
|
|
|
728
802
|
{ key: 'days' },
|
|
729
803
|
h(CardTitle, {
|
|
730
804
|
title: t('chart.days'),
|
|
731
|
-
hint: `${t('kpi.
|
|
805
|
+
hint: `${t(`range.${windowDays}`)} · ${t('kpi.perDay')} ${yuan(data.week.avgPerDay)} · ${t('kpi.perCall')} ${tokens(data.week.avgTokensPerCall, t)}`,
|
|
732
806
|
}),
|
|
733
|
-
h(DayChart, { days: data.days }),
|
|
807
|
+
h(DayChart, { days: data.days, t }),
|
|
734
808
|
h('span', { style: { fontSize: 9.5, color: C.text3 } }, t('chart.daysHint')),
|
|
735
809
|
),
|
|
736
810
|
);
|
|
@@ -768,6 +842,29 @@ window.__ModuleLoader__.load({
|
|
|
768
842
|
h('h2', { style: { margin: 0, fontSize: 16, fontWeight: 600 } }, t('page.title')),
|
|
769
843
|
h('span', { style: { fontSize: 11.5, color: C.text2 } }, t('page.subtitle')),
|
|
770
844
|
),
|
|
845
|
+
h(
|
|
846
|
+
'div',
|
|
847
|
+
{ style: { display: 'flex', gap: 2, padding: 2, borderRadius: 9, background: C.layer2, border: `1px solid ${C.border}` } },
|
|
848
|
+
[7, 14, 30].map((value) =>
|
|
849
|
+
h(
|
|
850
|
+
'button',
|
|
851
|
+
{
|
|
852
|
+
key: value,
|
|
853
|
+
onClick: () => setDays(value),
|
|
854
|
+
style: {
|
|
855
|
+
padding: '3px 10px',
|
|
856
|
+
borderRadius: 7,
|
|
857
|
+
border: 'none',
|
|
858
|
+
background: windowDays === value ? C.layer1 : 'transparent',
|
|
859
|
+
color: windowDays === value ? C.text : C.text3,
|
|
860
|
+
cursor: 'pointer',
|
|
861
|
+
fontSize: 11,
|
|
862
|
+
},
|
|
863
|
+
},
|
|
864
|
+
t(`range.${value}`),
|
|
865
|
+
),
|
|
866
|
+
),
|
|
867
|
+
),
|
|
771
868
|
h(
|
|
772
869
|
'span',
|
|
773
870
|
{ style: { fontSize: 10.5, color: C.text3 } },
|
|
@@ -791,6 +888,70 @@ window.__ModuleLoader__.load({
|
|
|
791
888
|
),
|
|
792
889
|
),
|
|
793
890
|
body,
|
|
891
|
+
h(
|
|
892
|
+
'footer',
|
|
893
|
+
{
|
|
894
|
+
style: {
|
|
895
|
+
marginTop: 2,
|
|
896
|
+
paddingTop: 10,
|
|
897
|
+
borderTop: `1px solid ${C.border}`,
|
|
898
|
+
display: 'flex',
|
|
899
|
+
alignItems: 'center',
|
|
900
|
+
justifyContent: 'space-between',
|
|
901
|
+
gap: 10,
|
|
902
|
+
flexWrap: 'wrap',
|
|
903
|
+
fontSize: 10.5,
|
|
904
|
+
color: C.text3,
|
|
905
|
+
},
|
|
906
|
+
},
|
|
907
|
+
h(
|
|
908
|
+
'span',
|
|
909
|
+
null,
|
|
910
|
+
data && data.calendar && data.calendar.years && data.calendar.years.length
|
|
911
|
+
? `${t('footer.calendar')} ${data.calendar.years.join(' / ')}`
|
|
912
|
+
: '',
|
|
913
|
+
),
|
|
914
|
+
h(
|
|
915
|
+
'div',
|
|
916
|
+
{ style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' } },
|
|
917
|
+
h(
|
|
918
|
+
'a',
|
|
919
|
+
{
|
|
920
|
+
href: (data && data.repo) || 'https://github.com/hhse/dsh-usage-peak',
|
|
921
|
+
target: '_blank',
|
|
922
|
+
rel: 'noopener noreferrer',
|
|
923
|
+
title: 'https://github.com/hhse/dsh-usage-peak',
|
|
924
|
+
style: {
|
|
925
|
+
color: C.text2,
|
|
926
|
+
textDecoration: 'none',
|
|
927
|
+
fontWeight: 500,
|
|
928
|
+
display: 'inline-flex',
|
|
929
|
+
alignItems: 'center',
|
|
930
|
+
gap: 5,
|
|
931
|
+
},
|
|
932
|
+
},
|
|
933
|
+
'⭐',
|
|
934
|
+
'github.com/hhse/dsh-usage-peak',
|
|
935
|
+
h('span', { style: { color: C.peak, fontWeight: 600 } }, `· ${t('footer.star')}`),
|
|
936
|
+
),
|
|
937
|
+
data && data.version
|
|
938
|
+
? h(
|
|
939
|
+
'span',
|
|
940
|
+
{
|
|
941
|
+
style: {
|
|
942
|
+
padding: '1px 6px',
|
|
943
|
+
borderRadius: 6,
|
|
944
|
+
border: `1px solid ${C.border}`,
|
|
945
|
+
background: C.layer2,
|
|
946
|
+
color: C.text2,
|
|
947
|
+
fontVariantNumeric: 'tabular-nums',
|
|
948
|
+
},
|
|
949
|
+
},
|
|
950
|
+
`v${data.version}`,
|
|
951
|
+
)
|
|
952
|
+
: null,
|
|
953
|
+
),
|
|
954
|
+
),
|
|
794
955
|
);
|
|
795
956
|
}
|
|
796
957
|
|
package/holidays.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mainland China public holidays and makeup workdays.
|
|
3
|
+
*
|
|
4
|
+
* Peak pricing only applies on working days; a public holiday is billed at the
|
|
5
|
+
* valley tariff all day, while a makeup workday ("调休上班", including a
|
|
6
|
+
* weekend) follows the normal weekday peak windows.
|
|
7
|
+
*
|
|
8
|
+
* Source: State Council notice
|
|
9
|
+
* https://www.gov.cn/zhengce/zhengceku/202511/content_7047091.htm
|
|
10
|
+
* Cross-checked against NateScarlet/holiday-cn (2026.json), which cites the
|
|
11
|
+
* same notice.
|
|
12
|
+
*
|
|
13
|
+
* To support a new year, append its dates here and add the year to
|
|
14
|
+
* CALENDAR_YEARS. Years without data fall back to the weekday rule and raise a
|
|
15
|
+
* `calendar-missing` warning in the snapshot.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Years covered by the data below. */
|
|
19
|
+
export const CALENDAR_YEARS = [2026];
|
|
20
|
+
|
|
21
|
+
/** Public holidays: date -> name. Billed at the valley tariff all day. */
|
|
22
|
+
export const OFF_DAYS = new Map([
|
|
23
|
+
['2026-01-01', '元旦'],
|
|
24
|
+
['2026-01-02', '元旦'],
|
|
25
|
+
['2026-01-03', '元旦'],
|
|
26
|
+
['2026-02-15', '春节'],
|
|
27
|
+
['2026-02-16', '春节'],
|
|
28
|
+
['2026-02-17', '春节'],
|
|
29
|
+
['2026-02-18', '春节'],
|
|
30
|
+
['2026-02-19', '春节'],
|
|
31
|
+
['2026-02-20', '春节'],
|
|
32
|
+
['2026-02-21', '春节'],
|
|
33
|
+
['2026-02-22', '春节'],
|
|
34
|
+
['2026-02-23', '春节'],
|
|
35
|
+
['2026-04-04', '清明节'],
|
|
36
|
+
['2026-04-05', '清明节'],
|
|
37
|
+
['2026-04-06', '清明节'],
|
|
38
|
+
['2026-05-01', '劳动节'],
|
|
39
|
+
['2026-05-02', '劳动节'],
|
|
40
|
+
['2026-05-03', '劳动节'],
|
|
41
|
+
['2026-05-04', '劳动节'],
|
|
42
|
+
['2026-05-05', '劳动节'],
|
|
43
|
+
['2026-06-19', '端午节'],
|
|
44
|
+
['2026-06-20', '端午节'],
|
|
45
|
+
['2026-06-21', '端午节'],
|
|
46
|
+
['2026-09-25', '中秋节'],
|
|
47
|
+
['2026-09-26', '中秋节'],
|
|
48
|
+
['2026-09-27', '中秋节'],
|
|
49
|
+
['2026-10-01', '国庆节'],
|
|
50
|
+
['2026-10-02', '国庆节'],
|
|
51
|
+
['2026-10-03', '国庆节'],
|
|
52
|
+
['2026-10-04', '国庆节'],
|
|
53
|
+
['2026-10-05', '国庆节'],
|
|
54
|
+
['2026-10-06', '国庆节'],
|
|
55
|
+
['2026-10-07', '国庆节'],
|
|
56
|
+
]);
|
|
57
|
+
|
|
58
|
+
/** Makeup workdays: date -> the holiday they belong to. */
|
|
59
|
+
export const WORKDAYS = new Map([
|
|
60
|
+
['2026-01-04', '元旦'],
|
|
61
|
+
['2026-02-14', '春节'],
|
|
62
|
+
['2026-02-28', '春节'],
|
|
63
|
+
['2026-05-09', '劳动节'],
|
|
64
|
+
['2026-09-20', '国庆节'],
|
|
65
|
+
['2026-10-10', '国庆节'],
|
|
66
|
+
]);
|
|
67
|
+
|
|
68
|
+
/** Calendar year of a `YYYY-MM-DD` day key, as a number. */
|
|
69
|
+
export function yearOf(dayKey) {
|
|
70
|
+
return Number(String(dayKey).slice(0, 4));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function hasCalendar(year) {
|
|
74
|
+
return CALENDAR_YEARS.includes(Number(year));
|
|
75
|
+
}
|
package/index.js
CHANGED
|
@@ -14,11 +14,17 @@ import os from 'node:os';
|
|
|
14
14
|
import path from 'node:path';
|
|
15
15
|
import zlib from 'node:zlib';
|
|
16
16
|
|
|
17
|
+
import { CALENDAR_YEARS, OFF_DAYS, WORKDAYS, hasCalendar, yearOf } from './holidays.js';
|
|
18
|
+
|
|
17
19
|
const NS = 'dsh-usage-peak';
|
|
20
|
+
const REPO_URL = 'https://github.com/hhse/dsh-usage-peak';
|
|
21
|
+
const VERSION = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version;
|
|
18
22
|
const ROUTE_BASE = '/plugin/dsh-usage-peak';
|
|
19
23
|
const SNAPSHOT_TTL_MS = 15_000;
|
|
20
24
|
const BJ_OFFSET = 8 * 60 * 60 * 1000;
|
|
21
|
-
const
|
|
25
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
26
|
+
const DEFAULT_DAYS = 14;
|
|
27
|
+
const WINDOW_DAYS = [7, 14, 30];
|
|
22
28
|
const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]); // zstd frame magic, little endian
|
|
23
29
|
|
|
24
30
|
/** CNY per million tokens, [valley, peak]. */
|
|
@@ -27,39 +33,48 @@ const PRICING = [
|
|
|
27
33
|
{ id: 'pro', label: 'DeepSeek Pro', match: 'pro', hit: [0.15, 0.3], miss: [4.5, 9], out: [13.5, 27] },
|
|
28
34
|
];
|
|
29
35
|
|
|
30
|
-
function priceFor(model) {
|
|
36
|
+
export function priceFor(model) {
|
|
31
37
|
const name = String(model || '').toLowerCase();
|
|
32
38
|
if (name.includes('pro')) return PRICING[1];
|
|
33
39
|
return PRICING[0];
|
|
34
40
|
}
|
|
35
41
|
|
|
36
|
-
function bjDate(ts) {
|
|
42
|
+
export function bjDate(ts) {
|
|
37
43
|
return new Date(ts + BJ_OFFSET);
|
|
38
44
|
}
|
|
39
45
|
|
|
40
|
-
function dayKey(ts) {
|
|
46
|
+
export function dayKey(ts) {
|
|
41
47
|
return bjDate(ts).toISOString().slice(0, 10);
|
|
42
48
|
}
|
|
43
49
|
|
|
44
|
-
/**
|
|
45
|
-
|
|
50
|
+
/**
|
|
51
|
+
* Peak = Beijing Mon-Fri 09:00-12:00 and 14:00-18:00; everything else is valley
|
|
52
|
+
* (half price). Public holidays are valley all day, makeup workdays (including
|
|
53
|
+
* a Saturday/Sunday) follow the weekday windows.
|
|
54
|
+
*/
|
|
55
|
+
export function isPeakAt(ts) {
|
|
56
|
+
const key = dayKey(ts);
|
|
57
|
+
if (OFF_DAYS.has(key)) return false;
|
|
46
58
|
const d = bjDate(ts);
|
|
47
59
|
const dow = d.getUTCDay();
|
|
48
|
-
|
|
60
|
+
const weekend = dow === 0 || dow === 6;
|
|
61
|
+
if (weekend && !WORKDAYS.has(key)) return false;
|
|
49
62
|
const minutes = d.getUTCHours() * 60 + d.getUTCMinutes();
|
|
50
63
|
return (minutes >= 540 && minutes < 720) || (minutes >= 840 && minutes < 1080);
|
|
51
64
|
}
|
|
52
65
|
|
|
53
66
|
/** Next tariff switch after `ts`, with the status it switches into. */
|
|
54
|
-
function nextSwitch(ts) {
|
|
67
|
+
export function nextSwitch(ts) {
|
|
55
68
|
const d = bjDate(ts);
|
|
56
69
|
const y = d.getUTCFullYear();
|
|
57
70
|
const mo = d.getUTCMonth();
|
|
58
71
|
const da = d.getUTCDate();
|
|
59
72
|
for (let k = 0; k < 9; k += 1) {
|
|
60
73
|
const probe = new Date(Date.UTC(y, mo, da + k));
|
|
74
|
+
const key = probe.toISOString().slice(0, 10);
|
|
75
|
+
if (OFF_DAYS.has(key)) continue;
|
|
61
76
|
const dow = probe.getUTCDay();
|
|
62
|
-
if (dow === 0 || dow === 6) continue;
|
|
77
|
+
if ((dow === 0 || dow === 6) && !WORKDAYS.has(key)) continue;
|
|
63
78
|
for (const hour of [9, 12, 14, 18]) {
|
|
64
79
|
const at = Date.UTC(probe.getUTCFullYear(), probe.getUTCMonth(), probe.getUTCDate(), hour, 0, 0) - BJ_OFFSET;
|
|
65
80
|
if (at > ts) return { at, status: hour === 9 || hour === 14 ? 'peak' : 'valley' };
|
|
@@ -76,7 +91,7 @@ function nextSwitch(ts) {
|
|
|
76
91
|
* Session logs are concatenated zstd frames; Node's zstd entry points stop after
|
|
77
92
|
* the first frame. Split on the frame magic and stitch the frames back together.
|
|
78
93
|
*/
|
|
79
|
-
function decodeSessionFile(file) {
|
|
94
|
+
export function decodeSessionFile(file) {
|
|
80
95
|
const buf = fs.readFileSync(file);
|
|
81
96
|
const starts = [];
|
|
82
97
|
let cursor = 0;
|
|
@@ -111,7 +126,7 @@ function decodeSessionFile(file) {
|
|
|
111
126
|
}
|
|
112
127
|
|
|
113
128
|
/** One turn per billed model request: { t, model, input, cache, output }. */
|
|
114
|
-
function parseSessionTurns(text) {
|
|
129
|
+
export function parseSessionTurns(text) {
|
|
115
130
|
const turns = [];
|
|
116
131
|
for (const line of text.split('\n')) {
|
|
117
132
|
if (line.length < 2) continue;
|
|
@@ -141,9 +156,14 @@ function parseSessionTurns(text) {
|
|
|
141
156
|
/* ------------------------------------------------------------------ */
|
|
142
157
|
|
|
143
158
|
const fileCache = new Map(); // file -> { mtimeMs, size, turns }
|
|
144
|
-
|
|
159
|
+
const snapshotCache = new Map(); // window days -> { builtAt, payload }
|
|
160
|
+
|
|
161
|
+
export function normalizeDays(value) {
|
|
162
|
+
const days = Number(value);
|
|
163
|
+
return WINDOW_DAYS.includes(days) ? days : DEFAULT_DAYS;
|
|
164
|
+
}
|
|
145
165
|
|
|
146
|
-
function collectTurns() {
|
|
166
|
+
export function collectTurns() {
|
|
147
167
|
const root = path.join(os.homedir(), '.dsh', 'sessions');
|
|
148
168
|
const turns = [];
|
|
149
169
|
let workspaceDirs;
|
|
@@ -188,7 +208,7 @@ function collectTurns() {
|
|
|
188
208
|
return turns;
|
|
189
209
|
}
|
|
190
210
|
|
|
191
|
-
function emptyDay(day) {
|
|
211
|
+
export function emptyDay(day) {
|
|
192
212
|
const hours = [];
|
|
193
213
|
for (let hour = 0; hour < 24; hour += 1) hours.push({ hour, cost: 0, calls: 0 });
|
|
194
214
|
return {
|
|
@@ -210,7 +230,7 @@ function emptyDay(day) {
|
|
|
210
230
|
};
|
|
211
231
|
}
|
|
212
232
|
|
|
213
|
-
function addTurn(day, turn) {
|
|
233
|
+
export function addTurn(day, turn) {
|
|
214
234
|
const price = priceFor(turn.model);
|
|
215
235
|
const peak = isPeakAt(turn.t);
|
|
216
236
|
const offset = peak ? 1 : 0;
|
|
@@ -244,7 +264,7 @@ function addTurn(day, turn) {
|
|
|
244
264
|
slot.tokens += turn.input + turn.cache + turn.output;
|
|
245
265
|
}
|
|
246
266
|
|
|
247
|
-
function readLedger() {
|
|
267
|
+
export function readLedger() {
|
|
248
268
|
const file = path.join(os.homedir(), '.dsh', '.dshw-usage.json');
|
|
249
269
|
try {
|
|
250
270
|
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
@@ -263,9 +283,9 @@ function readLedger() {
|
|
|
263
283
|
}
|
|
264
284
|
}
|
|
265
285
|
|
|
266
|
-
function shapeDay(day) {
|
|
286
|
+
export function shapeDay(day) {
|
|
267
287
|
const tokens = day.inputTokens + day.cacheTokens + day.outputTokens;
|
|
268
|
-
const billable =
|
|
288
|
+
const billable = day.cacheTokens + day.inputTokens;
|
|
269
289
|
return {
|
|
270
290
|
day: day.day,
|
|
271
291
|
calls: day.calls,
|
|
@@ -279,8 +299,11 @@ function shapeDay(day) {
|
|
|
279
299
|
costOut: round(day.costOut),
|
|
280
300
|
peakCost: round(day.peakCost),
|
|
281
301
|
valleyCost: round(day.valleyCost),
|
|
302
|
+
// Peak is exactly 2x valley, so moving these peak tokens to valley saves half.
|
|
303
|
+
savingIfValley: round(day.peakCost / 2),
|
|
282
304
|
peakShare: day.cost > 0 ? day.peakCost / day.cost : 0,
|
|
283
|
-
|
|
305
|
+
holiday: OFF_DAYS.get(day.day) || null,
|
|
306
|
+
hitRate: billable > 0 ? day.cacheTokens / billable : 0,
|
|
284
307
|
avgTokens: day.calls > 0 ? Math.round(tokens / day.calls) : 0,
|
|
285
308
|
firstAt: day.firstAt,
|
|
286
309
|
lastAt: day.lastAt,
|
|
@@ -288,57 +311,66 @@ function shapeDay(day) {
|
|
|
288
311
|
};
|
|
289
312
|
}
|
|
290
313
|
|
|
291
|
-
function round(value) {
|
|
314
|
+
export function round(value) {
|
|
292
315
|
return Math.round(value * 10000) / 10000;
|
|
293
316
|
}
|
|
294
317
|
|
|
295
|
-
function
|
|
296
|
-
const
|
|
297
|
-
|
|
318
|
+
export function hoursOf(day) {
|
|
319
|
+
const midnight = Date.parse(`${day.day}T00:00:00Z`) - BJ_OFFSET;
|
|
320
|
+
return day.hours.map((bucket) => ({
|
|
321
|
+
hour: bucket.hour,
|
|
322
|
+
cost: round(bucket.cost),
|
|
323
|
+
calls: bucket.calls,
|
|
324
|
+
peak: isPeakAt(midnight + bucket.hour * 3600_000),
|
|
325
|
+
}));
|
|
326
|
+
}
|
|
298
327
|
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
328
|
+
/** Calendar years touched by the window that have no holiday data yet. */
|
|
329
|
+
function missingCalendarYears(window) {
|
|
330
|
+
const years = new Set();
|
|
331
|
+
for (const entry of window) {
|
|
332
|
+
const year = yearOf(entry.day);
|
|
333
|
+
if (!hasCalendar(year)) years.add(year);
|
|
334
|
+
}
|
|
335
|
+
return years.size > 0 ? [{ code: 'calendar-missing', years: [...years] }] : [];
|
|
336
|
+
}
|
|
302
337
|
|
|
303
|
-
|
|
304
|
-
|
|
338
|
+
/**
|
|
339
|
+
* Pure aggregation over decoded turns.
|
|
340
|
+
*
|
|
341
|
+
* The window is a contiguous calendar range ending today (Beijing): days
|
|
342
|
+
* without any request are zero-filled so the chart keeps all its columns and
|
|
343
|
+
* "last N days" means the same thing everywhere.
|
|
344
|
+
*/
|
|
345
|
+
export function aggregateTurns(turns, options = {}) {
|
|
346
|
+
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
347
|
+
const days = normalizeDays(options.days);
|
|
348
|
+
const byDay = new Map();
|
|
349
|
+
const unknownModels = new Set();
|
|
350
|
+
|
|
351
|
+
for (const turn of turns || []) {
|
|
352
|
+
if (!turn || !Number.isFinite(turn.t)) continue;
|
|
305
353
|
const key = dayKey(turn.t);
|
|
306
|
-
let day =
|
|
354
|
+
let day = byDay.get(key);
|
|
307
355
|
if (!day) {
|
|
308
356
|
day = emptyDay(key);
|
|
309
|
-
|
|
357
|
+
byDay.set(key, day);
|
|
310
358
|
}
|
|
311
359
|
addTurn(day, turn);
|
|
312
360
|
if (!/flash|pro/i.test(turn.model)) unknownModels.add(turn.model);
|
|
313
361
|
}
|
|
314
362
|
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
363
|
+
const window = [];
|
|
364
|
+
for (let offset = days - 1; offset >= 0; offset -= 1) {
|
|
365
|
+
const key = dayKey(now - offset * DAY_MS);
|
|
366
|
+
const day = byDay.get(key) || emptyDay(key);
|
|
319
367
|
const shaped = shapeDay(day);
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
hour: bucket.hour,
|
|
324
|
-
cost: round(bucket.cost),
|
|
325
|
-
calls: bucket.calls,
|
|
326
|
-
peak: isPeakAt(Date.parse(`${day.day}T00:00:00Z`) - BJ_OFFSET + bucket.hour * 3600_000),
|
|
327
|
-
}));
|
|
328
|
-
return shaped;
|
|
329
|
-
});
|
|
330
|
-
|
|
331
|
-
const todayKey = dayKey(now);
|
|
332
|
-
const today = window.find((entry) => entry.day === todayKey) || null;
|
|
333
|
-
const todayHours = today ? today.hours : emptyDay(todayKey).hours.map((bucket) => ({
|
|
334
|
-
hour: bucket.hour,
|
|
335
|
-
cost: 0,
|
|
336
|
-
calls: 0,
|
|
337
|
-
peak: isPeakAt(Date.parse(`${todayKey}T00:00:00Z`) - BJ_OFFSET + bucket.hour * 3600_000),
|
|
338
|
-
}));
|
|
368
|
+
shaped.hours = hoursOf(day);
|
|
369
|
+
window.push(shaped);
|
|
370
|
+
}
|
|
339
371
|
|
|
340
|
-
const
|
|
341
|
-
const week =
|
|
372
|
+
const today = window[window.length - 1];
|
|
373
|
+
const week = window.slice(-7).reduce(
|
|
342
374
|
(acc, entry) => ({
|
|
343
375
|
cost: acc.cost + entry.cost,
|
|
344
376
|
calls: acc.calls + entry.calls,
|
|
@@ -347,15 +379,12 @@ function buildSnapshot() {
|
|
|
347
379
|
costCache: acc.costCache + entry.costCache,
|
|
348
380
|
costMiss: acc.costMiss + entry.costMiss,
|
|
349
381
|
costOut: acc.costOut + entry.costOut,
|
|
382
|
+
savingIfValley: acc.savingIfValley + entry.savingIfValley,
|
|
350
383
|
days: acc.days + 1,
|
|
351
384
|
}),
|
|
352
|
-
{ cost: 0, calls: 0, tokens: 0, peakCost: 0, costCache: 0, costMiss: 0, costOut: 0, days: 0 },
|
|
385
|
+
{ cost: 0, calls: 0, tokens: 0, peakCost: 0, costCache: 0, costMiss: 0, costOut: 0, savingIfValley: 0, days: 0 },
|
|
353
386
|
);
|
|
354
387
|
|
|
355
|
-
const switchPoint = nextSwitch(now);
|
|
356
|
-
const peakNow = isPeakAt(now);
|
|
357
|
-
const currentPrice = PRICING[0];
|
|
358
|
-
|
|
359
388
|
const models = PRICING.map((price) => {
|
|
360
389
|
let calls = 0;
|
|
361
390
|
let cost = 0;
|
|
@@ -370,13 +399,62 @@ function buildSnapshot() {
|
|
|
370
399
|
return { id: price.id, label: price.label, calls, cost: round(cost), tokens };
|
|
371
400
|
});
|
|
372
401
|
|
|
402
|
+
return {
|
|
403
|
+
windowDays: days,
|
|
404
|
+
today,
|
|
405
|
+
hours: today ? today.hours : [],
|
|
406
|
+
window,
|
|
407
|
+
week: {
|
|
408
|
+
cost: round(week.cost),
|
|
409
|
+
calls: week.calls,
|
|
410
|
+
tokens: week.tokens,
|
|
411
|
+
peakCost: round(week.peakCost),
|
|
412
|
+
costCache: round(week.costCache),
|
|
413
|
+
costMiss: round(week.costMiss),
|
|
414
|
+
costOut: round(week.costOut),
|
|
415
|
+
savingIfValley: round(week.savingIfValley),
|
|
416
|
+
peakShare: week.cost > 0 ? week.peakCost / week.cost : 0,
|
|
417
|
+
avgPerDay: week.days > 0 ? round(week.cost / week.days) : 0,
|
|
418
|
+
avgTokensPerCall: week.calls > 0 ? Math.round(week.tokens / week.calls) : 0,
|
|
419
|
+
},
|
|
420
|
+
models,
|
|
421
|
+
warnings: [
|
|
422
|
+
...(unknownModels.size > 0 ? [{ code: 'unknown-model', models: [...unknownModels] }] : []),
|
|
423
|
+
...missingCalendarYears(window),
|
|
424
|
+
],
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
export function buildSnapshot(options = {}) {
|
|
429
|
+
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
430
|
+
const days = normalizeDays(options.days);
|
|
431
|
+
const cached = snapshotCache.get(days);
|
|
432
|
+
if (cached && !options.fresh && now - cached.builtAt < SNAPSHOT_TTL_MS) return cached.payload;
|
|
433
|
+
|
|
434
|
+
const agg = aggregateTurns(collectTurns(), { now, days });
|
|
435
|
+
const ledger = readLedger();
|
|
436
|
+
if (ledger.ok) {
|
|
437
|
+
for (const entry of agg.window) {
|
|
438
|
+
const booked = ledger.history && ledger.history[entry.day];
|
|
439
|
+
entry.ledger = typeof booked === 'number' ? round(booked) : null;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const switchPoint = nextSwitch(now);
|
|
444
|
+
const peakNow = isPeakAt(now);
|
|
445
|
+
const currentPrice = PRICING[0];
|
|
446
|
+
|
|
373
447
|
const payload = {
|
|
374
448
|
ok: true,
|
|
375
449
|
generatedAt: now,
|
|
376
450
|
tz: 'Asia/Shanghai',
|
|
451
|
+
version: VERSION,
|
|
452
|
+
repo: REPO_URL,
|
|
453
|
+
calendar: { years: CALENDAR_YEARS, holidays: OFF_DAYS.size, workdays: WORKDAYS.size },
|
|
454
|
+
windowDays: days,
|
|
377
455
|
now: {
|
|
378
456
|
ts: now,
|
|
379
|
-
day:
|
|
457
|
+
day: dayKey(now),
|
|
380
458
|
peak: peakNow,
|
|
381
459
|
hour: bjDate(now).getUTCHours(),
|
|
382
460
|
minutesIntoHour: bjDate(now).getUTCMinutes(),
|
|
@@ -388,22 +466,11 @@ function buildSnapshot() {
|
|
|
388
466
|
out: currentPrice.out[peakNow ? 1 : 0],
|
|
389
467
|
},
|
|
390
468
|
},
|
|
391
|
-
today,
|
|
392
|
-
hours:
|
|
393
|
-
days: window,
|
|
394
|
-
week:
|
|
395
|
-
|
|
396
|
-
calls: week.calls,
|
|
397
|
-
tokens: week.tokens,
|
|
398
|
-
peakCost: round(week.peakCost),
|
|
399
|
-
costCache: round(week.costCache),
|
|
400
|
-
costMiss: round(week.costMiss),
|
|
401
|
-
costOut: round(week.costOut),
|
|
402
|
-
peakShare: week.cost > 0 ? week.peakCost / week.cost : 0,
|
|
403
|
-
avgPerDay: week.days > 0 ? round(week.cost / week.days) : 0,
|
|
404
|
-
avgPerCall: week.calls > 0 ? Math.round(week.tokens / week.calls) : 0,
|
|
405
|
-
},
|
|
406
|
-
models,
|
|
469
|
+
today: agg.today,
|
|
470
|
+
hours: agg.hours,
|
|
471
|
+
days: agg.window,
|
|
472
|
+
week: agg.week,
|
|
473
|
+
models: agg.models,
|
|
407
474
|
pricing: PRICING.map((price) => ({
|
|
408
475
|
id: price.id,
|
|
409
476
|
label: price.label,
|
|
@@ -412,10 +479,10 @@ function buildSnapshot() {
|
|
|
412
479
|
out: price.out,
|
|
413
480
|
})),
|
|
414
481
|
ledger,
|
|
415
|
-
warnings:
|
|
482
|
+
warnings: agg.warnings,
|
|
416
483
|
};
|
|
417
484
|
|
|
418
|
-
snapshotCache
|
|
485
|
+
snapshotCache.set(days, { builtAt: now, payload });
|
|
419
486
|
return payload;
|
|
420
487
|
}
|
|
421
488
|
|
|
@@ -486,9 +553,10 @@ export function apply(ctx) {
|
|
|
486
553
|
return;
|
|
487
554
|
}
|
|
488
555
|
const url = new URL(req.url || '/', 'http://127.0.0.1');
|
|
489
|
-
|
|
556
|
+
const fresh = url.searchParams.get('fresh') === '1' || url.searchParams.get('fresh') === 'true';
|
|
557
|
+
const days = normalizeDays(url.searchParams.get('days'));
|
|
490
558
|
try {
|
|
491
|
-
sendJson(res, 200, buildSnapshot());
|
|
559
|
+
sendJson(res, 200, buildSnapshot({ days, fresh }));
|
|
492
560
|
} catch (error) {
|
|
493
561
|
sendJson(res, 500, { ok: false, error: String((error && error.stack) || error) });
|
|
494
562
|
}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-usage-peak",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "DeepSeek Harness
|
|
5
|
+
"description": "DeepSeek Harness 用量峰谷仪表盘:峰/谷时段(含节假日与调休)、今日花费与 tokens、7/14/30 天窗口、缓存命中、谷时更省,侧栏常驻胶囊 + 设置页详情。",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": "./index.js",
|
|
8
8
|
"./client": "./client.js",
|
|
@@ -12,13 +12,15 @@
|
|
|
12
12
|
"files": [
|
|
13
13
|
"index.js",
|
|
14
14
|
"client.js",
|
|
15
|
+
"holidays.js",
|
|
15
16
|
"cordis.patch.yml",
|
|
16
17
|
"locale/*.json",
|
|
17
18
|
"icon.svg",
|
|
18
19
|
"README.md",
|
|
19
20
|
"LICENSE",
|
|
20
21
|
"CHANGELOG.md",
|
|
21
|
-
"assets/*.webp"
|
|
22
|
+
"assets/*.webp",
|
|
23
|
+
"test/*.js"
|
|
22
24
|
],
|
|
23
25
|
"dsh": {
|
|
24
26
|
"bundle": {
|
|
@@ -63,5 +65,9 @@
|
|
|
63
65
|
},
|
|
64
66
|
"publishConfig": {
|
|
65
67
|
"access": "public"
|
|
68
|
+
},
|
|
69
|
+
"scripts": {
|
|
70
|
+
"test": "node --test test/core.test.js",
|
|
71
|
+
"check": "node --check index.js && node --check client.js && npm test"
|
|
66
72
|
}
|
|
67
73
|
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import test from 'node:test';
|
|
6
|
+
import zlib from 'node:zlib';
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
aggregateTurns,
|
|
10
|
+
decodeSessionFile,
|
|
11
|
+
emptyDay,
|
|
12
|
+
isPeakAt,
|
|
13
|
+
nextSwitch,
|
|
14
|
+
normalizeDays,
|
|
15
|
+
parseSessionTurns,
|
|
16
|
+
priceFor,
|
|
17
|
+
} from '../index.js';
|
|
18
|
+
|
|
19
|
+
/** Beijing wall clock -> epoch ms. */
|
|
20
|
+
const bj = (y, mo, d, h, mi = 0) => Date.UTC(y, mo - 1, d, h, mi) - 8 * 3600_000;
|
|
21
|
+
|
|
22
|
+
test('priceFor picks the pro table only for pro models', () => {
|
|
23
|
+
assert.equal(priceFor('deepseek-flash').id, 'flash');
|
|
24
|
+
assert.equal(priceFor('deepseek-pro').id, 'pro');
|
|
25
|
+
assert.equal(priceFor('some-unknown-model').id, 'flash');
|
|
26
|
+
assert.equal(priceFor(undefined).id, 'flash');
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('isPeakAt covers the four weekday windows and nothing else', () => {
|
|
30
|
+
// 2026-11-09 is a Monday.
|
|
31
|
+
assert.equal(isPeakAt(bj(2026, 11, 9, 8, 59)), false);
|
|
32
|
+
assert.equal(isPeakAt(bj(2026, 11, 9, 9, 0)), true);
|
|
33
|
+
assert.equal(isPeakAt(bj(2026, 11, 9, 11, 59)), true);
|
|
34
|
+
assert.equal(isPeakAt(bj(2026, 11, 9, 12, 0)), false);
|
|
35
|
+
assert.equal(isPeakAt(bj(2026, 11, 9, 14, 0)), true);
|
|
36
|
+
assert.equal(isPeakAt(bj(2026, 11, 9, 17, 59)), true);
|
|
37
|
+
assert.equal(isPeakAt(bj(2026, 11, 9, 18, 0)), false);
|
|
38
|
+
assert.equal(isPeakAt(bj(2026, 11, 9, 23, 30)), false);
|
|
39
|
+
// Saturday / Sunday are always valley.
|
|
40
|
+
assert.equal(isPeakAt(bj(2026, 11, 7, 10, 0)), false);
|
|
41
|
+
assert.equal(isPeakAt(bj(2026, 11, 8, 15, 0)), false);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
test('public holidays are valley all day, makeup workdays follow weekday hours', () => {
|
|
45
|
+
// 2026 National Day: Oct 1 (Thu) is a public holiday.
|
|
46
|
+
assert.equal(isPeakAt(bj(2026, 10, 1, 10, 0)), false);
|
|
47
|
+
assert.equal(isPeakAt(bj(2026, 10, 7, 15, 0)), false);
|
|
48
|
+
// Spring Festival makeup: Feb 14 is a Saturday but a working day.
|
|
49
|
+
assert.equal(isPeakAt(bj(2026, 2, 14, 10, 0)), true);
|
|
50
|
+
assert.equal(isPeakAt(bj(2026, 2, 14, 13, 0)), false);
|
|
51
|
+
// New Year makeup: Jan 4 is a Sunday but a working day.
|
|
52
|
+
assert.equal(isPeakAt(bj(2026, 1, 4, 10, 0)), true);
|
|
53
|
+
// A plain weekend stays valley.
|
|
54
|
+
assert.equal(isPeakAt(bj(2026, 11, 7, 10, 0)), false);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('nextSwitch skips holiday blocks and honors makeup workdays', () => {
|
|
58
|
+
// Wednesday Sep 30 2026 evening: Oct 1-7 are holidays, next peak is Oct 8.
|
|
59
|
+
const afterNationalDay = nextSwitch(bj(2026, 9, 30, 19, 0));
|
|
60
|
+
assert.equal(afterNationalDay.at, bj(2026, 10, 8, 9, 0));
|
|
61
|
+
assert.equal(afterNationalDay.status, 'peak');
|
|
62
|
+
|
|
63
|
+
// Saturday Sep 19: Sunday Sep 20 is a makeup workday, so it is the next peak.
|
|
64
|
+
const makeup = nextSwitch(bj(2026, 9, 19, 10, 0));
|
|
65
|
+
assert.equal(makeup.at, bj(2026, 9, 20, 9, 0));
|
|
66
|
+
assert.equal(makeup.status, 'peak');
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('aggregateTurns tags holiday days in the window', () => {
|
|
70
|
+
const now = bj(2026, 10, 7, 12, 0);
|
|
71
|
+
const agg = aggregateTurns([], { now, days: 7 });
|
|
72
|
+
assert.equal(agg.window[0].day, '2026-10-01');
|
|
73
|
+
assert.equal(agg.window[0].holiday, '国庆节');
|
|
74
|
+
assert.equal(agg.window[6].holiday, '国庆节');
|
|
75
|
+
assert.deepEqual(agg.warnings, []);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('years without calendar data fall back to weekdays and warn', () => {
|
|
79
|
+
const now = bj(2027, 1, 5, 12, 0);
|
|
80
|
+
// 2027-10-01 is a Friday; without data the weekday rule marks it peak.
|
|
81
|
+
assert.equal(isPeakAt(bj(2027, 10, 1, 10, 0)), true);
|
|
82
|
+
const agg = aggregateTurns([], { now, days: 7 });
|
|
83
|
+
assert.deepEqual(agg.warnings, [{ code: 'calendar-missing', years: [2027] }]);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test('nextSwitch walks to the next boundary and reports the target status', () => {
|
|
87
|
+
const lunch = nextSwitch(bj(2026, 11, 9, 12, 30));
|
|
88
|
+
assert.equal(lunch.status, 'peak');
|
|
89
|
+
assert.equal(lunch.at, bj(2026, 11, 9, 14, 0));
|
|
90
|
+
|
|
91
|
+
const evening = nextSwitch(bj(2026, 11, 9, 18, 0));
|
|
92
|
+
assert.equal(evening.status, 'peak');
|
|
93
|
+
assert.equal(evening.at, bj(2026, 11, 10, 9, 0));
|
|
94
|
+
|
|
95
|
+
const morning = nextSwitch(bj(2026, 11, 9, 7, 15));
|
|
96
|
+
assert.equal(morning.status, 'peak');
|
|
97
|
+
assert.equal(morning.at, bj(2026, 11, 9, 9, 0));
|
|
98
|
+
|
|
99
|
+
// Friday after close: the next switch is Monday morning, not Saturday.
|
|
100
|
+
const weekend = nextSwitch(bj(2026, 11, 13, 19, 0));
|
|
101
|
+
assert.equal(weekend.status, 'peak');
|
|
102
|
+
assert.equal(weekend.at, bj(2026, 11, 16, 9, 0));
|
|
103
|
+
|
|
104
|
+
// Inside a peak window the next switch is back to valley.
|
|
105
|
+
const insidePeak = nextSwitch(bj(2026, 11, 9, 10, 0));
|
|
106
|
+
assert.equal(insidePeak.status, 'valley');
|
|
107
|
+
assert.equal(insidePeak.at, bj(2026, 11, 9, 12, 0));
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('decodeSessionFile stitches concatenated zstd frames', () => {
|
|
111
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'usage-peak-'));
|
|
112
|
+
const file = path.join(dir, 'session.v4.jsonl.zstd');
|
|
113
|
+
const one = Buffer.from('{"type":"assistant/message","time":1}\n');
|
|
114
|
+
const two = Buffer.from('{"type":"assistant/message","time":2}\n');
|
|
115
|
+
fs.writeFileSync(file, Buffer.concat([zlib.zstdCompressSync(one), zlib.zstdCompressSync(two)]));
|
|
116
|
+
try {
|
|
117
|
+
const text = decodeSessionFile(file);
|
|
118
|
+
assert.equal(text, one.toString('utf8') + two.toString('utf8'));
|
|
119
|
+
} finally {
|
|
120
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test('parseSessionTurns keeps only billed assistant messages', () => {
|
|
125
|
+
const text = [
|
|
126
|
+
'{"type":"user/message","time":100}',
|
|
127
|
+
'{"type":"assistant/message","time":200,"data":{"usage":{"inputTokens":10,"cacheReadTokens":20,"outputTokens":30},"message":{"source":{"model":"deepseek-flash"}}}}',
|
|
128
|
+
'{"type":"assistant/message","time":300,"data":{}}',
|
|
129
|
+
'not json',
|
|
130
|
+
'',
|
|
131
|
+
'{"type":"assistant/message","time":400,"data":{"usage":{"inputTokens":1},"message":{"source":{"model":"deepseek-pro"}}}}',
|
|
132
|
+
].join('\n');
|
|
133
|
+
|
|
134
|
+
assert.deepEqual(parseSessionTurns(text), [
|
|
135
|
+
{ t: 200, model: 'deepseek-flash', input: 10, cache: 20, output: 30 },
|
|
136
|
+
{ t: 400, model: 'deepseek-pro', input: 1, cache: 0, output: 0 },
|
|
137
|
+
]);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test('normalizeDays accepts only the offered windows', () => {
|
|
141
|
+
assert.equal(normalizeDays('7'), 7);
|
|
142
|
+
assert.equal(normalizeDays(30), 30);
|
|
143
|
+
assert.equal(normalizeDays('14'), 14);
|
|
144
|
+
assert.equal(normalizeDays('90'), 14);
|
|
145
|
+
assert.equal(normalizeDays(null), 14);
|
|
146
|
+
assert.equal(normalizeDays(undefined), 14);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test('aggregateTurns zero-fills a contiguous window and prices peak at 2x', () => {
|
|
150
|
+
const now = bj(2026, 11, 10, 12, 0);
|
|
151
|
+
const turns = [
|
|
152
|
+
// Peak Monday: 1M miss + 1M hit + 1M out at double price -> 10.04.
|
|
153
|
+
{ t: bj(2026, 11, 9, 10, 0), model: 'deepseek-flash', input: 1e6, cache: 1e6, output: 1e6 },
|
|
154
|
+
// Valley Tuesday: same tokens -> 5.02.
|
|
155
|
+
{ t: bj(2026, 11, 10, 8, 0), model: 'deepseek-flash', input: 1e6, cache: 1e6, output: 1e6 },
|
|
156
|
+
];
|
|
157
|
+
|
|
158
|
+
const agg = aggregateTurns(turns, { now, days: 7 });
|
|
159
|
+
|
|
160
|
+
assert.equal(agg.windowDays, 7);
|
|
161
|
+
assert.equal(agg.window.length, 7);
|
|
162
|
+
assert.deepEqual(
|
|
163
|
+
agg.window.map((day) => day.day),
|
|
164
|
+
['2026-11-04', '2026-11-05', '2026-11-06', '2026-11-07', '2026-11-08', '2026-11-09', '2026-11-10'],
|
|
165
|
+
);
|
|
166
|
+
assert.equal(agg.window[0].calls, 0);
|
|
167
|
+
assert.equal(agg.window[0].cost, 0);
|
|
168
|
+
|
|
169
|
+
assert.equal(agg.window[5].cost, 10.04);
|
|
170
|
+
assert.equal(agg.window[5].peakCost, 10.04);
|
|
171
|
+
assert.equal(agg.window[5].savingIfValley, 5.02);
|
|
172
|
+
assert.equal(agg.window[6].cost, 5.02);
|
|
173
|
+
assert.equal(agg.window[6].valleyCost, 5.02);
|
|
174
|
+
assert.equal(agg.today.day, '2026-11-10');
|
|
175
|
+
|
|
176
|
+
assert.equal(agg.week.cost, 15.06);
|
|
177
|
+
assert.equal(agg.week.calls, 2);
|
|
178
|
+
assert.equal(agg.week.savingIfValley, 5.02);
|
|
179
|
+
assert.equal(agg.week.avgTokensPerCall, 3_000_000);
|
|
180
|
+
assert.equal(agg.week.avgPerDay, 2.1514);
|
|
181
|
+
|
|
182
|
+
assert.deepEqual(agg.models.map((model) => [model.id, model.calls]), [
|
|
183
|
+
['flash', 2],
|
|
184
|
+
['pro', 0],
|
|
185
|
+
]);
|
|
186
|
+
assert.deepEqual(agg.warnings, []);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test('aggregateTurns sums per-window models and flags unknown models once', () => {
|
|
190
|
+
const now = bj(2026, 11, 10, 12, 0);
|
|
191
|
+
const turns = [
|
|
192
|
+
{ t: bj(2026, 11, 10, 9, 0), model: 'deepseek-flash', input: 1e6, cache: 0, output: 0 },
|
|
193
|
+
{ t: bj(2026, 11, 10, 9, 5), model: 'deepseek-pro', input: 1e6, cache: 0, output: 0 },
|
|
194
|
+
{ t: bj(2026, 11, 10, 9, 6), model: 'mystery-model', input: 0, cache: 0, output: 1e6 },
|
|
195
|
+
];
|
|
196
|
+
|
|
197
|
+
const agg = aggregateTurns(turns, { now, days: 7 });
|
|
198
|
+
assert.deepEqual(agg.models.map((model) => [model.id, model.calls]), [
|
|
199
|
+
['flash', 2],
|
|
200
|
+
['pro', 1],
|
|
201
|
+
]);
|
|
202
|
+
assert.deepEqual(agg.warnings, [{ code: 'unknown-model', models: ['mystery-model'] }]);
|
|
203
|
+
|
|
204
|
+
// Windows that end before the turns contain only zero days.
|
|
205
|
+
const old = aggregateTurns(turns, { now, days: 30 });
|
|
206
|
+
assert.equal(old.window.length, 30);
|
|
207
|
+
assert.equal(old.window[0].calls, 0);
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
test('emptyDay starts with 24 empty hour buckets', () => {
|
|
211
|
+
const day = emptyDay('2026-11-10');
|
|
212
|
+
assert.equal(day.hours.length, 24);
|
|
213
|
+
assert.equal(day.hours[0].hour, 0);
|
|
214
|
+
assert.equal(day.hours[23].hour, 23);
|
|
215
|
+
assert.equal(day.calls, 0);
|
|
216
|
+
assert.equal(day.lastAt, 0);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
test('window edges stay stable across a day boundary', () => {
|
|
220
|
+
const now = bj(2026, 11, 10, 0, 0) + 1; // one ms past midnight
|
|
221
|
+
const agg = aggregateTurns([], { now, days: 7 });
|
|
222
|
+
assert.equal(agg.window[6].day, '2026-11-10');
|
|
223
|
+
assert.equal(agg.window[0].day, '2026-11-04');
|
|
224
|
+
assert.equal(agg.window.length, 7);
|
|
225
|
+
assert.equal(now - bj(2026, 11, 10, 0, 0), 1);
|
|
226
|
+
});
|