dsh-usage-peak 1.2.0 → 1.3.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 +10 -0
- package/README.md +14 -10
- package/client.js +278 -5
- package/holidays.js +40 -5
- package/index.js +200 -5
- package/package.json +2 -2
- package/test/core.test.js +139 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.3.0
|
|
4
|
+
|
|
5
|
+
- 新增「按项目」统计:从会话头读取绝对 `cwd`,按项目聚合窗口内的请求、tokens、花费与占比;没有会话头时回落到 workspace slug 解码。
|
|
6
|
+
- 新增「余额可撑」:余额 ÷ 近 7 天日均花费;侧栏胶囊 <7 天转琥珀、<3 天转红,详情页新增 KPI 与余额胶囊提示。
|
|
7
|
+
- 新增 CSV 导出:`/plugin/dsh-usage-peak/export.csv?days=&scope=days|projects`,UTF-8 BOM + 公式注入防护;页面提供「导出 CSV」与「项目 CSV」。
|
|
8
|
+
- 补齐 README 里承诺、界面却缺失的「按模型」表(Flash / Pro 请求数、tokens、花费)。
|
|
9
|
+
- 节假日日历新增 2027 年(国务院办公厅 2027 年通知,与 holiday-cn 交叉核对);覆盖 2026–2027。
|
|
10
|
+
- 聚合时先按统计窗口过滤,窗口外请求不再影响项目占比或未识别模型提示。
|
|
11
|
+
- 新增纯函数 `parseSessionMeta` / `projectInfo` / `walletSummary` / `buildCsv`,测试从 14 条增至 21 条。
|
|
12
|
+
|
|
3
13
|
## 1.2.0
|
|
4
14
|
|
|
5
15
|
- 峰谷判断接入中国大陆节假日/调休日历:法定节假日全天谷时,调休上班日(含周末)按工作日峰谷计算。
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 用量峰谷仪表盘(DSH Usage Dashboard)
|
|
2
2
|
|
|
3
|
-
给 DeepSeek Harness 用的用量/花费仪表盘:一眼看清现在是不是**峰时**、今天花了多少钱、烧了多少 tokens
|
|
3
|
+
给 DeepSeek Harness 用的用量/花费仪表盘:一眼看清现在是不是**峰时**、今天花了多少钱、烧了多少 tokens、钱花在哪个项目,以及余额还能撑几天。
|
|
4
4
|
|
|
5
5
|
全部在本地读取 DSH 自己的会话日志,不联网、不上报。
|
|
6
6
|
|
|
@@ -12,15 +12,17 @@
|
|
|
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
|
-
- **今日概况**:花费、请求数、tokens
|
|
17
|
+
- **今日概况**:花费、请求数、tokens、缓存命中率、峰时花费占比、**谷时更省**(把这些峰时用量挪到谷时能省下的钱)、余额、**余额可撑天数**(余额 ÷ 近 7 天日均花费)。
|
|
18
18
|
- **今日 24 小时分布**:每小时花费柱状,峰时与谷时用不同颜色,当前小时高亮。
|
|
19
19
|
- **花费构成**:缓存命中 / 全价输入 / 输出 三段占比,直接看出钱花在哪。
|
|
20
20
|
- **近 7 / 14 / 30 天趋势**:右上角切换窗口,按天堆叠柱状,缺数据的日期补零,列数恒定;可对照峰时占比判断"贵在哪天"。
|
|
21
|
+
- **按项目**:按会话头里的工作目录(`cwd`)聚合,倒序列出每个项目的请求数、tokens、花费与占比,直接回答「哪个项目最烧钱」。
|
|
21
22
|
- **按模型**:Flash / Pro 各自的请求数、tokens、花费。
|
|
23
|
+
- **导出 CSV**:每日数据与项目数据都能导出(UTF-8 BOM,Excel 直接打开不乱码;单元格做了公式注入防护)。
|
|
22
24
|
- **价目表**:当前时段那一行高亮,方便解释账单。
|
|
23
|
-
- **节假日与调休**:按国务院办公厅公布的安排判断——法定节假日全天谷时,调休上班的周末按工作日峰谷计算;当前覆盖 2026 年,缺失年份会在面板给出提示并回落到周一至周五规则。
|
|
25
|
+
- **节假日与调休**:按国务院办公厅公布的安排判断——法定节假日全天谷时,调休上班的周末按工作日峰谷计算;当前覆盖 2026–2027 年,缺失年份会在面板给出提示并回落到周一至周五规则。
|
|
24
26
|
- **页脚**:GitHub 仓库链接(可顺手点个 Star)、当前版本号与日历覆盖年份。
|
|
25
27
|
|
|
26
28
|
设置页里的入口是「用量仪表盘」,侧栏胶囊就是同一份数据的浓缩版。
|
|
@@ -36,16 +38,17 @@
|
|
|
36
38
|
|
|
37
39
|
峰时 = 工作日 09:00–12:00、14:00–18:00(北京时间);其余时间、周末与法定节假日为谷时,单价减半。调休上班日(包括周末)按工作日的峰谷窗口计算。
|
|
38
40
|
|
|
39
|
-
节假日数据在 [`holidays.js`](holidays.js)
|
|
41
|
+
节假日数据在 [`holidays.js`](holidays.js),来源为国务院办公厅 [2026 年](https://www.gov.cn/zhengce/zhengceku/202511/content_7047091.htm)、[2027 年](https://www.gov.cn/zhengce/zhengceku/202611/content_7085102.htm) 放假安排通知,并与 [holiday-cn](https://github.com/NateScarlet/holiday-cn) 交叉核对。新一年安排公布后,补一组日期并把年份加进 `CALENDAR_YEARS` 即可。
|
|
40
42
|
|
|
41
43
|
## 数据来源
|
|
42
44
|
|
|
43
|
-
- `~/.dsh/sessions/<项目 slug>/<会话 id>/session.v4.jsonl.zstd`:每条 `assistant/message` 的 `usage
|
|
45
|
+
- `~/.dsh/sessions/<项目 slug>/<会话 id>/session.v4.jsonl.zstd`:每条 `assistant/message` 的 `usage`(输入、缓存读取、输出)与模型,按请求发生的时刻判断峰谷;项目归属取会话头里的绝对 `cwd`,没有会话头时才回落到目录 slug。
|
|
44
46
|
- `~/.dsh/.dshw-usage.json`:鲸鱼记账本的余额与当日花费,用作交叉校验。
|
|
45
47
|
|
|
46
48
|
日志是**多帧 zstd**,Node 自带的 `zlib.zstdDecompressSync` 只解第一帧,所以插件内部按 zstd magic 切帧、逐帧解压再拼接(不需要 `zstd` 命令行)。
|
|
47
49
|
|
|
48
|
-
数据接口支持 `?days=7|14|30` 选择统计窗口(默认 14,白名单之外的取值回落到 14);快照按窗口分别缓存 15 秒,面板上的「刷新」按钮会带 `?fresh=1` 强制重算。
|
|
50
|
+
- 数据接口支持 `?days=7|14|30` 选择统计窗口(默认 14,白名单之外的取值回落到 14);快照按窗口分别缓存 15 秒,面板上的「刷新」按钮会带 `?fresh=1` 强制重算。
|
|
51
|
+
- 导出接口为 `/plugin/dsh-usage-peak/export.csv?days=7|14|30&scope=days|projects`,带 `Content-Disposition: attachment` 与 UTF-8 BOM。
|
|
49
52
|
|
|
50
53
|
峰时单价恰为谷时 2 倍,所以「谷时更省」= 峰时花费 ÷ 2:它衡量的是这些峰时用量如果改在谷时发生能省多少,而不是已经省下的钱。
|
|
51
54
|
|
|
@@ -72,6 +75,7 @@ dsh plugin add dsh-usage-peak
|
|
|
72
75
|
|
|
73
76
|
- 依赖 DSH 会话日志的**内部格式**(`session.v4.jsonl.zstd` 与 `assistant/message.data.usage`)。DSH 改格式时需要跟进;读不到数据时面板会显示为空态而不是报错。
|
|
74
77
|
- 只统计本机会话日志覆盖到的历史,鲸鱼记账本从 2026-11-02 才开始记账。
|
|
78
|
+
- 项目归属依赖会话头中的 `cwd`;极少数没有会话头的旧日志会回落到 workspace slug,slug 会转义部分字节,显示名可能不如真实路径精确。
|
|
75
79
|
|
|
76
80
|
## 许可
|
|
77
81
|
|
|
@@ -85,10 +89,10 @@ A usage and cost dashboard for DeepSeek Harness. It reads the local session logs
|
|
|
85
89
|
|
|
86
90
|

|
|
87
91
|
|
|
88
|
-
- a persistent sidebar pill with peak/valley state, today's spend, tokens and the countdown to the next price switch;
|
|
89
|
-
- China public holidays and makeup workdays: holidays are valley all day, makeup weekend workdays follow the weekday windows (2026
|
|
92
|
+
- a persistent sidebar pill with peak/valley state, today's spend, tokens and the countdown to the next price switch; the pill turns amber when the balance runway is under 7 days and red under 3 days;
|
|
93
|
+
- 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);
|
|
90
94
|
- 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;
|
|
95
|
+
- 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;
|
|
92
96
|
- 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.
|
|
93
97
|
|
|
94
98
|
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
|
@@ -17,6 +17,7 @@ window.__ModuleLoader__.load({
|
|
|
17
17
|
|
|
18
18
|
const NS = 'dsh-usage-peak';
|
|
19
19
|
const DATA_URL = '/plugin/dsh-usage-peak/data';
|
|
20
|
+
const EXPORT_URL = '/plugin/dsh-usage-peak/export.csv';
|
|
20
21
|
const DEFAULT_DAYS = 14;
|
|
21
22
|
const WINDOW_DAYS = [7, 14, 30];
|
|
22
23
|
|
|
@@ -75,6 +76,29 @@ window.__ModuleLoader__.load({
|
|
|
75
76
|
'kpi.saving': '谷时更省',
|
|
76
77
|
'kpi.savingHint': '峰时按谷价计',
|
|
77
78
|
'kpi.windowSaving': '近 7 天可省',
|
|
79
|
+
'kpi.runway': '余额可撑',
|
|
80
|
+
'kpi.runwayHint': '余额 ÷ 近 7 天日均',
|
|
81
|
+
'unit.day': '天',
|
|
82
|
+
'wallet.avg': '日均',
|
|
83
|
+
'wallet.alert': '余额仅够',
|
|
84
|
+
'wallet.warn': '余额偏低',
|
|
85
|
+
'wallet.low': '余额紧张',
|
|
86
|
+
|
|
87
|
+
'projects.title': '按项目',
|
|
88
|
+
'projects.hint': '按花费排序',
|
|
89
|
+
'projects.name': '项目',
|
|
90
|
+
'projects.calls': '请求',
|
|
91
|
+
'projects.tokens': 'tokens',
|
|
92
|
+
'projects.cost': '花费',
|
|
93
|
+
'projects.share': '占比',
|
|
94
|
+
'projects.empty': '这个窗口内还没有项目数据',
|
|
95
|
+
'models.title': '按模型',
|
|
96
|
+
'models.hint': '窗口内',
|
|
97
|
+
'models.empty': '暂无请求',
|
|
98
|
+
'export.csv': '导出 CSV',
|
|
99
|
+
'export.projects': '项目 CSV',
|
|
100
|
+
'export.daysTitle': '导出每日数据 CSV',
|
|
101
|
+
'export.projectsTitle': '导出项目数据 CSV',
|
|
78
102
|
|
|
79
103
|
'chart.hours': '今日每小时花费',
|
|
80
104
|
'chart.hoursHint': '橙 峰时 · 绿 谷时',
|
|
@@ -149,6 +173,29 @@ window.__ModuleLoader__.load({
|
|
|
149
173
|
'kpi.saving': 'Valley saving',
|
|
150
174
|
'kpi.savingHint': 'peak tokens at valley price',
|
|
151
175
|
'kpi.windowSaving': '7d saving',
|
|
176
|
+
'kpi.runway': 'Runway',
|
|
177
|
+
'kpi.runwayHint': 'balance ÷ 7-day average',
|
|
178
|
+
'unit.day': 'd',
|
|
179
|
+
'wallet.avg': 'avg',
|
|
180
|
+
'wallet.alert': 'Balance covers',
|
|
181
|
+
'wallet.warn': 'Low balance',
|
|
182
|
+
'wallet.low': 'Balance critical',
|
|
183
|
+
|
|
184
|
+
'projects.title': 'By project',
|
|
185
|
+
'projects.hint': 'sorted by spend',
|
|
186
|
+
'projects.name': 'Project',
|
|
187
|
+
'projects.calls': 'req',
|
|
188
|
+
'projects.tokens': 'tokens',
|
|
189
|
+
'projects.cost': 'Spend',
|
|
190
|
+
'projects.share': 'Share',
|
|
191
|
+
'projects.empty': 'No project data in this window',
|
|
192
|
+
'models.title': 'By model',
|
|
193
|
+
'models.hint': 'in window',
|
|
194
|
+
'models.empty': 'No requests yet',
|
|
195
|
+
'export.csv': 'Export CSV',
|
|
196
|
+
'export.projects': 'Projects CSV',
|
|
197
|
+
'export.daysTitle': 'Export daily CSV',
|
|
198
|
+
'export.projectsTitle': 'Export project CSV',
|
|
152
199
|
|
|
153
200
|
'chart.hours': 'Cost per hour today',
|
|
154
201
|
'chart.hoursHint': 'orange peak · green valley',
|
|
@@ -183,6 +230,7 @@ window.__ModuleLoader__.load({
|
|
|
183
230
|
cache: 'var(--dsw-alias-state-business-primary)',
|
|
184
231
|
miss: 'var(--dsw-alias-state-warn-primary)',
|
|
185
232
|
out: 'var(--dsw-alias-brand-primary)',
|
|
233
|
+
error: 'var(--dsw-alias-state-error-primary)',
|
|
186
234
|
};
|
|
187
235
|
|
|
188
236
|
/* ------------------------------ formatting ------------------------------ */
|
|
@@ -235,6 +283,13 @@ window.__ModuleLoader__.load({
|
|
|
235
283
|
return `${minutes}${typeof t === 'function' ? t('unit.minute') : '分'}`;
|
|
236
284
|
}
|
|
237
285
|
|
|
286
|
+
/** Runway in days: 2.9 / 7 / <1 / 120. */
|
|
287
|
+
function runway(value, t) {
|
|
288
|
+
if (value === null || value === undefined || Number.isNaN(value)) return '—';
|
|
289
|
+
const days = value <= 0 ? '0' : value < 1 ? '<1' : value >= 100 ? String(Math.round(value)) : value.toFixed(1).replace(/\.0$/, '');
|
|
290
|
+
return `${days} ${t('unit.day')}`;
|
|
291
|
+
}
|
|
292
|
+
|
|
238
293
|
/* --------------------------------- data --------------------------------- */
|
|
239
294
|
|
|
240
295
|
function useFeed(days) {
|
|
@@ -287,6 +342,7 @@ window.__ModuleLoader__.load({
|
|
|
287
342
|
return h(
|
|
288
343
|
'span',
|
|
289
344
|
{
|
|
345
|
+
title: props.title,
|
|
290
346
|
style: {
|
|
291
347
|
display: 'inline-flex',
|
|
292
348
|
alignItems: 'center',
|
|
@@ -344,14 +400,23 @@ window.__ModuleLoader__.load({
|
|
|
344
400
|
const tone = loading ? C.text3 : peak ? C.peak : C.valley;
|
|
345
401
|
const word = loading ? t('widget.loading') : peak ? t('widget.peak') : t('widget.valley');
|
|
346
402
|
const short = word.slice(0, 1) === '峰' ? '峰' : word.slice(0, 1) === '谷' ? '谷' : word;
|
|
403
|
+
const wallet = data && data.wallet ? data.wallet : null;
|
|
404
|
+
const walletLevel = wallet ? wallet.level : 'unknown';
|
|
405
|
+
const walletAlert = walletLevel === 'low' || walletLevel === 'warn';
|
|
406
|
+
const walletTone = walletLevel === 'low' ? C.error : walletLevel === 'warn' ? C.peak : C.text3;
|
|
407
|
+
const walletText = walletAlert ? `${t('wallet.alert')} ${runway(wallet.runwayDays, t)}` : '';
|
|
347
408
|
const remain = data ? Math.max(0, data.now.nextAt - Date.now()) : 0;
|
|
348
409
|
const switchText =
|
|
349
410
|
data && remain > 30_000
|
|
350
411
|
? `${countdown(remain, t)} ${peak ? t('widget.toValley') : t('widget.toPeak')}`
|
|
351
412
|
: t('widget.soon');
|
|
352
413
|
const today = data && data.today ? data.today.cost : null;
|
|
414
|
+
const walletTip =
|
|
415
|
+
wallet && wallet.balance !== null
|
|
416
|
+
? `${t('kpi.balance')} ${yuan(wallet.balance)}${walletText ? ` · ${walletText}` : ''}`
|
|
417
|
+
: '';
|
|
353
418
|
const tip = data
|
|
354
|
-
? `${word} · ${t('widget.today')} ${yuan(today)} · ${tokens(data.today ? data.today.tokens : 0, t)} tokens · ${t('status.switchIn')} ${switchText}`
|
|
419
|
+
? `${word} · ${t('widget.today')} ${yuan(today)} · ${tokens(data.today ? data.today.tokens : 0, t)} tokens · ${t('status.switchIn')} ${switchText}${walletTip ? ` · ${walletTip}` : ''}`
|
|
355
420
|
: word;
|
|
356
421
|
|
|
357
422
|
// The seat is the shell's own flex row: the root takes a whole line (see
|
|
@@ -366,7 +431,8 @@ window.__ModuleLoader__.load({
|
|
|
366
431
|
height: 21,
|
|
367
432
|
padding: '0 8px',
|
|
368
433
|
borderRadius: 999,
|
|
369
|
-
border: `1px solid ${C.border}`,
|
|
434
|
+
border: `1px solid ${walletAlert ? walletTone : C.border}`,
|
|
435
|
+
background: walletAlert ? `${walletTone}14` : 'transparent',
|
|
370
436
|
fontSize: 10.5,
|
|
371
437
|
lineHeight: '19px',
|
|
372
438
|
color: C.text2,
|
|
@@ -392,7 +458,19 @@ window.__ModuleLoader__.load({
|
|
|
392
458
|
h('span', { style: { color: C.text3, marginLeft: 2 } }, 'tok'),
|
|
393
459
|
),
|
|
394
460
|
h(Sep),
|
|
395
|
-
h(
|
|
461
|
+
h(
|
|
462
|
+
'span',
|
|
463
|
+
{
|
|
464
|
+
style: {
|
|
465
|
+
color: walletAlert ? walletTone : C.text3,
|
|
466
|
+
fontWeight: walletAlert ? 600 : 400,
|
|
467
|
+
fontVariantNumeric: 'tabular-nums',
|
|
468
|
+
overflow: 'hidden',
|
|
469
|
+
textOverflow: 'ellipsis',
|
|
470
|
+
},
|
|
471
|
+
},
|
|
472
|
+
data ? (walletAlert ? `⚠ ${runway(wallet.runwayDays, t)}` : switchText) : '',
|
|
473
|
+
),
|
|
396
474
|
);
|
|
397
475
|
|
|
398
476
|
return h('div', { ...rootProps, title: tip, onClick: open || undefined, style: rootStyle }, pill);
|
|
@@ -425,7 +503,14 @@ window.__ModuleLoader__.load({
|
|
|
425
503
|
'header',
|
|
426
504
|
{ style: { display: 'flex', alignItems: 'baseline', gap: 8, justifyContent: 'space-between' } },
|
|
427
505
|
h('h3', { style: { margin: 0, fontSize: 12.5, fontWeight: 600, color: C.text } }, props.title),
|
|
428
|
-
props.hint
|
|
506
|
+
props.hint || props.action
|
|
507
|
+
? h(
|
|
508
|
+
'span',
|
|
509
|
+
{ style: { display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 10.5, color: C.text3 } },
|
|
510
|
+
props.hint ? h('span', null, props.hint) : null,
|
|
511
|
+
props.action || null,
|
|
512
|
+
)
|
|
513
|
+
: null,
|
|
429
514
|
);
|
|
430
515
|
}
|
|
431
516
|
|
|
@@ -631,6 +716,118 @@ window.__ModuleLoader__.load({
|
|
|
631
716
|
);
|
|
632
717
|
}
|
|
633
718
|
|
|
719
|
+
const cellHead = (align) => ({
|
|
720
|
+
padding: '3px 8px',
|
|
721
|
+
textAlign: align,
|
|
722
|
+
fontWeight: 500,
|
|
723
|
+
color: C.text3,
|
|
724
|
+
borderBottom: `1px solid ${C.border}`,
|
|
725
|
+
whiteSpace: 'nowrap',
|
|
726
|
+
position: 'sticky',
|
|
727
|
+
top: 0,
|
|
728
|
+
background: C.layer1,
|
|
729
|
+
zIndex: 1,
|
|
730
|
+
});
|
|
731
|
+
|
|
732
|
+
const cellBody = {
|
|
733
|
+
padding: '4px 8px',
|
|
734
|
+
color: C.text2,
|
|
735
|
+
whiteSpace: 'nowrap',
|
|
736
|
+
fontVariantNumeric: 'tabular-nums',
|
|
737
|
+
};
|
|
738
|
+
|
|
739
|
+
function ProjectTable(props) {
|
|
740
|
+
const { projects, t } = props;
|
|
741
|
+
if (!projects || !projects.length) {
|
|
742
|
+
return h('span', { style: { fontSize: 11.5, color: C.text3 } }, t('projects.empty'));
|
|
743
|
+
}
|
|
744
|
+
const head = [t('projects.name'), t('projects.calls'), t('projects.tokens'), t('projects.cost'), t('projects.share')];
|
|
745
|
+
return h(
|
|
746
|
+
'div',
|
|
747
|
+
{ style: { maxHeight: 214, overflowY: 'auto', margin: '0 -2px' } },
|
|
748
|
+
h(
|
|
749
|
+
'table',
|
|
750
|
+
{ style: { width: '100%', borderCollapse: 'collapse', fontSize: 11.5 } },
|
|
751
|
+
h(
|
|
752
|
+
'thead',
|
|
753
|
+
null,
|
|
754
|
+
h(
|
|
755
|
+
'tr',
|
|
756
|
+
null,
|
|
757
|
+
head.map((label, index) =>
|
|
758
|
+
h('th', { key: label, style: cellHead(index === 0 ? 'left' : 'right') }, label),
|
|
759
|
+
),
|
|
760
|
+
),
|
|
761
|
+
),
|
|
762
|
+
h(
|
|
763
|
+
'tbody',
|
|
764
|
+
null,
|
|
765
|
+
projects.map((project) =>
|
|
766
|
+
h(
|
|
767
|
+
'tr',
|
|
768
|
+
{ key: project.key, title: project.path || project.name },
|
|
769
|
+
h(
|
|
770
|
+
'td',
|
|
771
|
+
{
|
|
772
|
+
style: {
|
|
773
|
+
...cellBody,
|
|
774
|
+
color: C.text,
|
|
775
|
+
maxWidth: 220,
|
|
776
|
+
overflow: 'hidden',
|
|
777
|
+
textOverflow: 'ellipsis',
|
|
778
|
+
},
|
|
779
|
+
},
|
|
780
|
+
project.name,
|
|
781
|
+
),
|
|
782
|
+
h('td', { style: { ...cellBody, textAlign: 'right' } }, project.calls),
|
|
783
|
+
h('td', { style: { ...cellBody, textAlign: 'right' } }, tokens(project.tokens, t)),
|
|
784
|
+
h('td', { style: { ...cellBody, textAlign: 'right' } }, yuan(project.cost)),
|
|
785
|
+
h('td', { style: { ...cellBody, textAlign: 'right', color: C.text3 } }, percent(project.share, 0)),
|
|
786
|
+
),
|
|
787
|
+
),
|
|
788
|
+
),
|
|
789
|
+
),
|
|
790
|
+
);
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
function ModelTable(props) {
|
|
794
|
+
const { models, t } = props;
|
|
795
|
+
const rows = (models || []).filter((model) => model.calls > 0);
|
|
796
|
+
if (!rows.length) {
|
|
797
|
+
return h('span', { style: { fontSize: 11.5, color: C.text3 } }, t('models.empty'));
|
|
798
|
+
}
|
|
799
|
+
const head = [t('price.model'), t('projects.calls'), t('projects.tokens'), t('projects.cost')];
|
|
800
|
+
return h(
|
|
801
|
+
'table',
|
|
802
|
+
{ style: { width: '100%', borderCollapse: 'collapse', fontSize: 11.5 } },
|
|
803
|
+
h(
|
|
804
|
+
'thead',
|
|
805
|
+
null,
|
|
806
|
+
h(
|
|
807
|
+
'tr',
|
|
808
|
+
null,
|
|
809
|
+
head.map((label, index) =>
|
|
810
|
+
h('th', { key: label, style: cellHead(index === 0 ? 'left' : 'right') }, label),
|
|
811
|
+
),
|
|
812
|
+
),
|
|
813
|
+
),
|
|
814
|
+
h(
|
|
815
|
+
'tbody',
|
|
816
|
+
null,
|
|
817
|
+
rows.map((model) =>
|
|
818
|
+
h(
|
|
819
|
+
'tr',
|
|
820
|
+
{ key: model.id },
|
|
821
|
+
h('td', { style: { ...cellBody, color: C.text } }, model.label),
|
|
822
|
+
h('td', { style: { ...cellBody, textAlign: 'right' } }, model.calls),
|
|
823
|
+
h('td', { style: { ...cellBody, textAlign: 'right' } }, tokens(model.tokens, t)),
|
|
824
|
+
h('td', { style: { ...cellBody, textAlign: 'right' } }, yuan(model.cost)),
|
|
825
|
+
),
|
|
826
|
+
),
|
|
827
|
+
),
|
|
828
|
+
);
|
|
829
|
+
}
|
|
830
|
+
|
|
634
831
|
/* -------------------------------- settings ------------------------------- */
|
|
635
832
|
|
|
636
833
|
function Dashboard(props) {
|
|
@@ -640,6 +837,10 @@ window.__ModuleLoader__.load({
|
|
|
640
837
|
const data = feed.data;
|
|
641
838
|
const windowDays = (data && data.windowDays) || days;
|
|
642
839
|
const peakNow = data ? data.now.peak : false;
|
|
840
|
+
const wallet = data && data.wallet ? data.wallet : null;
|
|
841
|
+
const walletLevel = wallet ? wallet.level : 'unknown';
|
|
842
|
+
const walletAlert = walletLevel === 'low' || walletLevel === 'warn';
|
|
843
|
+
const walletTone = walletLevel === 'low' ? C.error : walletLevel === 'warn' ? C.peak : C.text3;
|
|
643
844
|
const remain = data ? Math.max(0, data.now.nextAt - Date.now()) : 0;
|
|
644
845
|
const switchText =
|
|
645
846
|
data && remain > 30_000
|
|
@@ -702,13 +903,26 @@ window.__ModuleLoader__.load({
|
|
|
702
903
|
),
|
|
703
904
|
h(
|
|
704
905
|
Pill,
|
|
705
|
-
|
|
906
|
+
{
|
|
907
|
+
style: walletAlert ? { borderColor: walletTone, background: `${walletTone}1a` } : null,
|
|
908
|
+
title:
|
|
909
|
+
wallet && wallet.avgPerDay
|
|
910
|
+
? `${t('wallet.avg')} ${yuan(wallet.avgPerDay)} · ${t('kpi.runwayHint')}`
|
|
911
|
+
: undefined,
|
|
912
|
+
},
|
|
706
913
|
`${t('kpi.balance')} `,
|
|
707
914
|
h(
|
|
708
915
|
'span',
|
|
709
916
|
{ style: { color: C.text } },
|
|
710
917
|
data.ledger && typeof data.ledger.balance === 'number' ? yuan(data.ledger.balance) : '—',
|
|
711
918
|
),
|
|
919
|
+
wallet && wallet.runwayDays !== null
|
|
920
|
+
? h(
|
|
921
|
+
'span',
|
|
922
|
+
{ style: { color: walletTone, fontWeight: 600 } },
|
|
923
|
+
` · ${t('wallet.alert')} ${runway(wallet.runwayDays, t)}`,
|
|
924
|
+
)
|
|
925
|
+
: null,
|
|
712
926
|
),
|
|
713
927
|
h(Pill, null, `${today.calls || 0} ${t('unit.calls')} · ${tokens(today.tokens, t)} tokens`),
|
|
714
928
|
),
|
|
@@ -740,6 +954,15 @@ window.__ModuleLoader__.load({
|
|
|
740
954
|
h(
|
|
741
955
|
'div',
|
|
742
956
|
{ key: 'kpi', style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 10 } },
|
|
957
|
+
h(Kpi, {
|
|
958
|
+
label: t('kpi.runway'),
|
|
959
|
+
value: wallet && wallet.runwayDays !== null ? runway(wallet.runwayDays, t) : '—',
|
|
960
|
+
tone: walletAlert ? walletTone : C.text,
|
|
961
|
+
hint:
|
|
962
|
+
wallet && wallet.balance !== null
|
|
963
|
+
? `${t('kpi.balance')} ${yuan(wallet.balance)} · ${t('wallet.avg')} ${yuan(wallet.avgPerDay)}`
|
|
964
|
+
: t('kpi.runwayHint'),
|
|
965
|
+
}),
|
|
743
966
|
h(Kpi, {
|
|
744
967
|
label: t('kpi.calls'),
|
|
745
968
|
value: today.calls || 0,
|
|
@@ -809,6 +1032,38 @@ window.__ModuleLoader__.load({
|
|
|
809
1032
|
),
|
|
810
1033
|
);
|
|
811
1034
|
|
|
1035
|
+
body.push(
|
|
1036
|
+
h(
|
|
1037
|
+
'div',
|
|
1038
|
+
{ key: 'breakdown', style: { display: 'grid', gridTemplateColumns: 'minmax(0, 1.5fr) minmax(0, 1fr)', gap: 10 } },
|
|
1039
|
+
h(
|
|
1040
|
+
Card,
|
|
1041
|
+
null,
|
|
1042
|
+
h(CardTitle, {
|
|
1043
|
+
title: t('projects.title'),
|
|
1044
|
+
hint: t('projects.hint'),
|
|
1045
|
+
action: h(
|
|
1046
|
+
'a',
|
|
1047
|
+
{
|
|
1048
|
+
href: `${EXPORT_URL}?days=${windowDays}&scope=projects`,
|
|
1049
|
+
download: '',
|
|
1050
|
+
title: t('export.projectsTitle'),
|
|
1051
|
+
style: { color: C.cache, textDecoration: 'none', fontWeight: 500 },
|
|
1052
|
+
},
|
|
1053
|
+
t('export.projects'),
|
|
1054
|
+
),
|
|
1055
|
+
}),
|
|
1056
|
+
h(ProjectTable, { projects: data.projects, t }),
|
|
1057
|
+
),
|
|
1058
|
+
h(
|
|
1059
|
+
Card,
|
|
1060
|
+
null,
|
|
1061
|
+
h(CardTitle, { title: t('models.title'), hint: t('models.hint') }),
|
|
1062
|
+
h(ModelTable, { models: data.models, t }),
|
|
1063
|
+
),
|
|
1064
|
+
),
|
|
1065
|
+
);
|
|
1066
|
+
|
|
812
1067
|
body.push(
|
|
813
1068
|
h(
|
|
814
1069
|
Card,
|
|
@@ -886,6 +1141,24 @@ window.__ModuleLoader__.load({
|
|
|
886
1141
|
},
|
|
887
1142
|
t('page.refresh'),
|
|
888
1143
|
),
|
|
1144
|
+
h(
|
|
1145
|
+
'a',
|
|
1146
|
+
{
|
|
1147
|
+
href: `${EXPORT_URL}?days=${windowDays}`,
|
|
1148
|
+
download: '',
|
|
1149
|
+
title: t('export.daysTitle'),
|
|
1150
|
+
style: {
|
|
1151
|
+
padding: '4px 12px',
|
|
1152
|
+
borderRadius: 8,
|
|
1153
|
+
border: `1px solid ${C.border}`,
|
|
1154
|
+
background: C.layer1,
|
|
1155
|
+
color: C.text,
|
|
1156
|
+
textDecoration: 'none',
|
|
1157
|
+
fontSize: 11.5,
|
|
1158
|
+
},
|
|
1159
|
+
},
|
|
1160
|
+
t('export.csv'),
|
|
1161
|
+
),
|
|
889
1162
|
),
|
|
890
1163
|
body,
|
|
891
1164
|
h(
|
package/holidays.js
CHANGED
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
* valley tariff all day, while a makeup workday ("调休上班", including a
|
|
6
6
|
* weekend) follows the normal weekday peak windows.
|
|
7
7
|
*
|
|
8
|
-
* Source: State Council
|
|
9
|
-
* https://www.gov.cn/zhengce/zhengceku/202511/content_7047091.htm
|
|
10
|
-
*
|
|
11
|
-
*
|
|
8
|
+
* Source: State Council notices
|
|
9
|
+
* 2026 — https://www.gov.cn/zhengce/zhengceku/202511/content_7047091.htm
|
|
10
|
+
* 2027 — https://www.gov.cn/zhengce/zhengceku/202611/content_7085102.htm
|
|
11
|
+
* Cross-checked against NateScarlet/holiday-cn (2026.json, 2027.json), which
|
|
12
|
+
* cite the same notices.
|
|
12
13
|
*
|
|
13
14
|
* To support a new year, append its dates here and add the year to
|
|
14
15
|
* CALENDAR_YEARS. Years without data fall back to the weekday rule and raise a
|
|
@@ -16,7 +17,7 @@
|
|
|
16
17
|
*/
|
|
17
18
|
|
|
18
19
|
/** Years covered by the data below. */
|
|
19
|
-
export const CALENDAR_YEARS = [2026];
|
|
20
|
+
export const CALENDAR_YEARS = [2026, 2027];
|
|
20
21
|
|
|
21
22
|
/** Public holidays: date -> name. Billed at the valley tariff all day. */
|
|
22
23
|
export const OFF_DAYS = new Map([
|
|
@@ -53,6 +54,35 @@ export const OFF_DAYS = new Map([
|
|
|
53
54
|
['2026-10-05', '国庆节'],
|
|
54
55
|
['2026-10-06', '国庆节'],
|
|
55
56
|
['2026-10-07', '国庆节'],
|
|
57
|
+
['2027-01-01', '元旦'],
|
|
58
|
+
['2027-01-02', '元旦'],
|
|
59
|
+
['2027-01-03', '元旦'],
|
|
60
|
+
['2027-02-05', '春节'],
|
|
61
|
+
['2027-02-06', '春节'],
|
|
62
|
+
['2027-02-07', '春节'],
|
|
63
|
+
['2027-02-08', '春节'],
|
|
64
|
+
['2027-02-09', '春节'],
|
|
65
|
+
['2027-02-10', '春节'],
|
|
66
|
+
['2027-02-11', '春节'],
|
|
67
|
+
['2027-02-12', '春节'],
|
|
68
|
+
['2027-02-13', '春节'],
|
|
69
|
+
['2027-04-03', '清明节'],
|
|
70
|
+
['2027-04-04', '清明节'],
|
|
71
|
+
['2027-04-05', '清明节'],
|
|
72
|
+
['2027-05-01', '劳动节'],
|
|
73
|
+
['2027-05-02', '劳动节'],
|
|
74
|
+
['2027-05-03', '劳动节'],
|
|
75
|
+
['2027-05-04', '劳动节'],
|
|
76
|
+
['2027-05-05', '劳动节'],
|
|
77
|
+
['2027-06-09', '端午节'],
|
|
78
|
+
['2027-09-15', '中秋节'],
|
|
79
|
+
['2027-10-01', '国庆节'],
|
|
80
|
+
['2027-10-02', '国庆节'],
|
|
81
|
+
['2027-10-03', '国庆节'],
|
|
82
|
+
['2027-10-04', '国庆节'],
|
|
83
|
+
['2027-10-05', '国庆节'],
|
|
84
|
+
['2027-10-06', '国庆节'],
|
|
85
|
+
['2027-10-07', '国庆节'],
|
|
56
86
|
]);
|
|
57
87
|
|
|
58
88
|
/** Makeup workdays: date -> the holiday they belong to. */
|
|
@@ -63,6 +93,11 @@ export const WORKDAYS = new Map([
|
|
|
63
93
|
['2026-05-09', '劳动节'],
|
|
64
94
|
['2026-09-20', '国庆节'],
|
|
65
95
|
['2026-10-10', '国庆节'],
|
|
96
|
+
['2027-01-31', '春节'],
|
|
97
|
+
['2027-02-14', '春节'],
|
|
98
|
+
['2027-05-08', '劳动节'],
|
|
99
|
+
['2027-09-26', '国庆节'],
|
|
100
|
+
['2027-10-09', '国庆节'],
|
|
66
101
|
]);
|
|
67
102
|
|
|
68
103
|
/** Calendar year of a `YYYY-MM-DD` day key, as a number. */
|
package/index.js
CHANGED
|
@@ -125,8 +125,52 @@ export function decodeSessionFile(file) {
|
|
|
125
125
|
return Buffer.concat(chunks).toString('utf8');
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
+
/** Session header: reads `cwd` from the first `type:"session"` record. */
|
|
129
|
+
export function parseSessionMeta(text) {
|
|
130
|
+
const head = String(text || '').slice(0, 8192);
|
|
131
|
+
for (const line of head.split('\n')) {
|
|
132
|
+
if (!line.includes('"session"')) continue;
|
|
133
|
+
let record;
|
|
134
|
+
try {
|
|
135
|
+
record = JSON.parse(line);
|
|
136
|
+
} catch {
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (record && record.type === 'session') {
|
|
140
|
+
return { cwd: typeof record.cwd === 'string' && record.cwd.trim() ? record.cwd : null };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return { cwd: null };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Project identity for a session directory.
|
|
148
|
+
*
|
|
149
|
+
* The session log's absolute `cwd` is authoritative. Older/foreign logs without
|
|
150
|
+
* a header fall back to the workspace directory slug, which hex-escapes some
|
|
151
|
+
* bytes (`~5FAE~`); decode what we can and use the path as the display name.
|
|
152
|
+
*/
|
|
153
|
+
export function projectInfo(cwd, dirName) {
|
|
154
|
+
if (typeof cwd === 'string' && cwd.trim()) {
|
|
155
|
+
const clean = cwd.trim().replace(/[\\/]+$/, '') || cwd.trim();
|
|
156
|
+
return { key: clean, name: path.basename(clean) || clean, path: clean };
|
|
157
|
+
}
|
|
158
|
+
const body = String(dirName || '').replace(/^--|--$/g, '');
|
|
159
|
+
const decoded = body
|
|
160
|
+
.replace(/~([0-9a-fA-F]{4})~/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
|
|
161
|
+
.split('-')
|
|
162
|
+
.filter(Boolean)
|
|
163
|
+
.join('/');
|
|
164
|
+
const label = decoded || String(dirName || 'unknown');
|
|
165
|
+
return {
|
|
166
|
+
key: `slug:${dirName || 'unknown'}`,
|
|
167
|
+
name: label,
|
|
168
|
+
path: label.startsWith('/') ? label : `/${label}`,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
128
172
|
/** One turn per billed model request: { t, model, input, cache, output }. */
|
|
129
|
-
export function parseSessionTurns(text) {
|
|
173
|
+
export function parseSessionTurns(text, project) {
|
|
130
174
|
const turns = [];
|
|
131
175
|
for (const line of text.split('\n')) {
|
|
132
176
|
if (line.length < 2) continue;
|
|
@@ -140,13 +184,15 @@ export function parseSessionTurns(text) {
|
|
|
140
184
|
const usage = record.data && record.data.usage;
|
|
141
185
|
if (!usage) continue;
|
|
142
186
|
const model = (record.data.message && record.data.message.source && record.data.message.source.model) || 'unknown';
|
|
143
|
-
|
|
187
|
+
const turn = {
|
|
144
188
|
t: record.time,
|
|
145
189
|
model,
|
|
146
190
|
input: usage.inputTokens || 0,
|
|
147
191
|
cache: usage.cacheReadTokens || 0,
|
|
148
192
|
output: usage.outputTokens || 0,
|
|
149
|
-
}
|
|
193
|
+
};
|
|
194
|
+
if (project) turn.project = project;
|
|
195
|
+
turns.push(turn);
|
|
150
196
|
}
|
|
151
197
|
return turns;
|
|
152
198
|
}
|
|
@@ -195,7 +241,8 @@ export function collectTurns() {
|
|
|
195
241
|
if (!entry || entry.mtimeMs !== stat.mtimeMs || entry.size !== stat.size) {
|
|
196
242
|
let parsed = [];
|
|
197
243
|
try {
|
|
198
|
-
|
|
244
|
+
const text = decodeSessionFile(file);
|
|
245
|
+
parsed = parseSessionTurns(text, projectInfo(parseSessionMeta(text).cwd, workspace.name));
|
|
199
246
|
} catch {
|
|
200
247
|
parsed = [];
|
|
201
248
|
}
|
|
@@ -262,6 +309,8 @@ export function addTurn(day, turn) {
|
|
|
262
309
|
slot.calls += 1;
|
|
263
310
|
slot.cost += cost;
|
|
264
311
|
slot.tokens += turn.input + turn.cache + turn.output;
|
|
312
|
+
|
|
313
|
+
return { cost, peak, tokens: turn.input + turn.cache + turn.output };
|
|
265
314
|
}
|
|
266
315
|
|
|
267
316
|
export function readLedger() {
|
|
@@ -335,6 +384,24 @@ function missingCalendarYears(window) {
|
|
|
335
384
|
return years.size > 0 ? [{ code: 'calendar-missing', years: [...years] }] : [];
|
|
336
385
|
}
|
|
337
386
|
|
|
387
|
+
export const RUNWAY_WARN_DAYS = 7;
|
|
388
|
+
export const RUNWAY_LOW_DAYS = 3;
|
|
389
|
+
|
|
390
|
+
/** How many days the current balance lasts at the recent daily burn rate. */
|
|
391
|
+
export function walletSummary(balance, avgPerDay) {
|
|
392
|
+
const hasBalance = typeof balance === 'number' && Number.isFinite(balance);
|
|
393
|
+
const perDay = typeof avgPerDay === 'number' && Number.isFinite(avgPerDay) && avgPerDay > 0 ? avgPerDay : 0;
|
|
394
|
+
const runwayDays = hasBalance && perDay > 0 ? Math.max(0, balance / perDay) : null;
|
|
395
|
+
const level =
|
|
396
|
+
runwayDays === null ? 'unknown' : runwayDays < RUNWAY_LOW_DAYS ? 'low' : runwayDays < RUNWAY_WARN_DAYS ? 'warn' : 'ok';
|
|
397
|
+
return {
|
|
398
|
+
balance: hasBalance ? round(balance) : null,
|
|
399
|
+
avgPerDay: round(perDay),
|
|
400
|
+
runwayDays: runwayDays === null ? null : round(runwayDays),
|
|
401
|
+
level,
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
338
405
|
/**
|
|
339
406
|
* Pure aggregation over decoded turns.
|
|
340
407
|
*
|
|
@@ -346,18 +413,43 @@ export function aggregateTurns(turns, options = {}) {
|
|
|
346
413
|
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
347
414
|
const days = normalizeDays(options.days);
|
|
348
415
|
const byDay = new Map();
|
|
416
|
+
const byProject = new Map();
|
|
349
417
|
const unknownModels = new Set();
|
|
418
|
+
const firstKey = dayKey(now - (days - 1) * DAY_MS);
|
|
419
|
+
const todayKey = dayKey(now);
|
|
420
|
+
let attributedCost = 0;
|
|
350
421
|
|
|
351
422
|
for (const turn of turns || []) {
|
|
352
423
|
if (!turn || !Number.isFinite(turn.t)) continue;
|
|
353
424
|
const key = dayKey(turn.t);
|
|
425
|
+
if (key < firstKey || key > todayKey) continue;
|
|
354
426
|
let day = byDay.get(key);
|
|
355
427
|
if (!day) {
|
|
356
428
|
day = emptyDay(key);
|
|
357
429
|
byDay.set(key, day);
|
|
358
430
|
}
|
|
359
|
-
addTurn(day, turn);
|
|
431
|
+
const priced = addTurn(day, turn);
|
|
360
432
|
if (!/flash|pro/i.test(turn.model)) unknownModels.add(turn.model);
|
|
433
|
+
if (turn.project && turn.project.key) {
|
|
434
|
+
let project = byProject.get(turn.project.key);
|
|
435
|
+
if (!project) {
|
|
436
|
+
project = {
|
|
437
|
+
key: turn.project.key,
|
|
438
|
+
name: turn.project.name,
|
|
439
|
+
path: turn.project.path,
|
|
440
|
+
calls: 0,
|
|
441
|
+
cost: 0,
|
|
442
|
+
peakCost: 0,
|
|
443
|
+
tokens: 0,
|
|
444
|
+
};
|
|
445
|
+
byProject.set(turn.project.key, project);
|
|
446
|
+
}
|
|
447
|
+
project.calls += 1;
|
|
448
|
+
project.cost += priced.cost;
|
|
449
|
+
project.tokens += priced.tokens;
|
|
450
|
+
if (priced.peak) project.peakCost += priced.cost;
|
|
451
|
+
attributedCost += priced.cost;
|
|
452
|
+
}
|
|
361
453
|
}
|
|
362
454
|
|
|
363
455
|
const window = [];
|
|
@@ -399,11 +491,21 @@ export function aggregateTurns(turns, options = {}) {
|
|
|
399
491
|
return { id: price.id, label: price.label, calls, cost: round(cost), tokens };
|
|
400
492
|
});
|
|
401
493
|
|
|
494
|
+
const projects = [...byProject.values()]
|
|
495
|
+
.map((project) => ({
|
|
496
|
+
...project,
|
|
497
|
+
cost: round(project.cost),
|
|
498
|
+
peakCost: round(project.peakCost),
|
|
499
|
+
share: round(attributedCost > 0 ? project.cost / attributedCost : 0),
|
|
500
|
+
}))
|
|
501
|
+
.sort((a, b) => b.cost - a.cost || a.name.localeCompare(b.name));
|
|
502
|
+
|
|
402
503
|
return {
|
|
403
504
|
windowDays: days,
|
|
404
505
|
today,
|
|
405
506
|
hours: today ? today.hours : [],
|
|
406
507
|
window,
|
|
508
|
+
projects,
|
|
407
509
|
week: {
|
|
408
510
|
cost: round(week.cost),
|
|
409
511
|
calls: week.calls,
|
|
@@ -469,7 +571,9 @@ export function buildSnapshot(options = {}) {
|
|
|
469
571
|
today: agg.today,
|
|
470
572
|
hours: agg.hours,
|
|
471
573
|
days: agg.window,
|
|
574
|
+
projects: agg.projects,
|
|
472
575
|
week: agg.week,
|
|
576
|
+
wallet: walletSummary(ledger.ok ? ledger.balance : null, agg.week.avgPerDay),
|
|
473
577
|
models: agg.models,
|
|
474
578
|
pricing: PRICING.map((price) => ({
|
|
475
579
|
id: price.id,
|
|
@@ -486,6 +590,68 @@ export function buildSnapshot(options = {}) {
|
|
|
486
590
|
return payload;
|
|
487
591
|
}
|
|
488
592
|
|
|
593
|
+
/* ------------------------------------------------------------------ */
|
|
594
|
+
/* CSV export */
|
|
595
|
+
/* ------------------------------------------------------------------ */
|
|
596
|
+
|
|
597
|
+
const CSV_FORMULA = /^[=+\-@\t\r]/;
|
|
598
|
+
|
|
599
|
+
/** RFC 4180 cell, with a guard against spreadsheet formula injection. */
|
|
600
|
+
export function csvEscape(value) {
|
|
601
|
+
let text = value === null || value === undefined ? '' : String(value);
|
|
602
|
+
if (typeof value === 'string' && CSV_FORMULA.test(text)) text = `'${text}`;
|
|
603
|
+
return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function csvTable(rows) {
|
|
607
|
+
return `${rows.map((row) => row.map(csvEscape).join(',')).join('\n')}\n`;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
export function buildCsv(payload, scope = 'days') {
|
|
611
|
+
if (scope === 'projects') {
|
|
612
|
+
const rows = [['project', 'path', 'calls', 'tokens', 'cost', 'peak_cost', 'share']];
|
|
613
|
+
for (const project of (payload && payload.projects) || []) {
|
|
614
|
+
rows.push([project.name, project.path, project.calls, project.tokens, project.cost, project.peakCost, project.share]);
|
|
615
|
+
}
|
|
616
|
+
return csvTable(rows);
|
|
617
|
+
}
|
|
618
|
+
const rows = [
|
|
619
|
+
[
|
|
620
|
+
'day',
|
|
621
|
+
'calls',
|
|
622
|
+
'tokens',
|
|
623
|
+
'cost',
|
|
624
|
+
'cost_cache',
|
|
625
|
+
'cost_miss',
|
|
626
|
+
'cost_out',
|
|
627
|
+
'peak_cost',
|
|
628
|
+
'valley_cost',
|
|
629
|
+
'saving_if_valley',
|
|
630
|
+
'peak_share',
|
|
631
|
+
'hit_rate',
|
|
632
|
+
'holiday',
|
|
633
|
+
],
|
|
634
|
+
];
|
|
635
|
+
for (const day of (payload && payload.days) || []) {
|
|
636
|
+
rows.push([
|
|
637
|
+
day.day,
|
|
638
|
+
day.calls,
|
|
639
|
+
day.tokens,
|
|
640
|
+
day.cost,
|
|
641
|
+
day.costCache,
|
|
642
|
+
day.costMiss,
|
|
643
|
+
day.costOut,
|
|
644
|
+
day.peakCost,
|
|
645
|
+
day.valleyCost,
|
|
646
|
+
day.savingIfValley,
|
|
647
|
+
round(day.peakShare),
|
|
648
|
+
round(day.hitRate),
|
|
649
|
+
day.holiday || '',
|
|
650
|
+
]);
|
|
651
|
+
}
|
|
652
|
+
return csvTable(rows);
|
|
653
|
+
}
|
|
654
|
+
|
|
489
655
|
/* ------------------------------------------------------------------ */
|
|
490
656
|
/* HTTP surface */
|
|
491
657
|
/* ------------------------------------------------------------------ */
|
|
@@ -563,7 +729,36 @@ export function apply(ctx) {
|
|
|
563
729
|
},
|
|
564
730
|
});
|
|
565
731
|
|
|
732
|
+
const disposeExport = register({
|
|
733
|
+
kind: 'exact',
|
|
734
|
+
path: `${ROUTE_BASE}/export.csv`,
|
|
735
|
+
handler: async (req, res) => {
|
|
736
|
+
if (trustCheck(req, res)) return;
|
|
737
|
+
if ((req.method || 'GET').toUpperCase() !== 'GET') {
|
|
738
|
+
sendJson(res, 405, { ok: false, error: 'method not allowed' });
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1');
|
|
742
|
+
const days = normalizeDays(url.searchParams.get('days'));
|
|
743
|
+
const scope = url.searchParams.get('scope') === 'projects' ? 'projects' : 'days';
|
|
744
|
+
try {
|
|
745
|
+
const snapshot = buildSnapshot({ days, fresh: true });
|
|
746
|
+
const body = Buffer.from(`\uFEFF${buildCsv(snapshot, scope)}`, 'utf8');
|
|
747
|
+
res.writeHead(200, {
|
|
748
|
+
'Content-Type': 'text/csv; charset=utf-8',
|
|
749
|
+
'Content-Disposition': `attachment; filename="dsh-usage-${dayKey(Date.now())}-${days}d-${scope}.csv"`,
|
|
750
|
+
'Cache-Control': 'no-store',
|
|
751
|
+
'Content-Length': String(body.length),
|
|
752
|
+
});
|
|
753
|
+
res.end(body);
|
|
754
|
+
} catch (error) {
|
|
755
|
+
sendJson(res, 500, { ok: false, error: String((error && error.stack) || error) });
|
|
756
|
+
}
|
|
757
|
+
},
|
|
758
|
+
});
|
|
759
|
+
|
|
566
760
|
ctx.effect(() => () => {
|
|
567
761
|
dispose();
|
|
762
|
+
disposeExport();
|
|
568
763
|
}, `${NS}: dashboard route`);
|
|
569
764
|
}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-usage-peak",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
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",
|
package/test/core.test.js
CHANGED
|
@@ -7,13 +7,18 @@ import zlib from 'node:zlib';
|
|
|
7
7
|
|
|
8
8
|
import {
|
|
9
9
|
aggregateTurns,
|
|
10
|
+
buildCsv,
|
|
11
|
+
csvEscape,
|
|
10
12
|
decodeSessionFile,
|
|
11
13
|
emptyDay,
|
|
12
14
|
isPeakAt,
|
|
13
15
|
nextSwitch,
|
|
14
16
|
normalizeDays,
|
|
17
|
+
parseSessionMeta,
|
|
15
18
|
parseSessionTurns,
|
|
16
19
|
priceFor,
|
|
20
|
+
projectInfo,
|
|
21
|
+
walletSummary,
|
|
17
22
|
} from '../index.js';
|
|
18
23
|
|
|
19
24
|
/** Beijing wall clock -> epoch ms. */
|
|
@@ -75,12 +80,27 @@ test('aggregateTurns tags holiday days in the window', () => {
|
|
|
75
80
|
assert.deepEqual(agg.warnings, []);
|
|
76
81
|
});
|
|
77
82
|
|
|
83
|
+
test('2027 holidays and makeup workdays follow the 2027 State Council notice', () => {
|
|
84
|
+
// Spring Festival: Feb 5-13 off; Jan 31 and Feb 14 (Sundays) are workdays.
|
|
85
|
+
assert.equal(isPeakAt(bj(2027, 2, 5, 10, 0)), false);
|
|
86
|
+
assert.equal(isPeakAt(bj(2027, 2, 13, 10, 0)), false);
|
|
87
|
+
assert.equal(isPeakAt(bj(2027, 1, 31, 10, 0)), true);
|
|
88
|
+
assert.equal(isPeakAt(bj(2027, 2, 14, 10, 0)), true);
|
|
89
|
+
// National Day: Oct 1-7 off, Oct 8 is a normal Friday, Oct 9 is makeup.
|
|
90
|
+
assert.equal(isPeakAt(bj(2027, 10, 1, 10, 0)), false);
|
|
91
|
+
assert.equal(isPeakAt(bj(2027, 10, 8, 10, 0)), true);
|
|
92
|
+
assert.equal(isPeakAt(bj(2027, 10, 9, 10, 0)), true);
|
|
93
|
+
// The full 2027 calendar no longer raises the missing-calendar warning.
|
|
94
|
+
const agg = aggregateTurns([], { now: bj(2027, 10, 7, 12, 0), days: 7 });
|
|
95
|
+
assert.deepEqual(agg.warnings, []);
|
|
96
|
+
});
|
|
97
|
+
|
|
78
98
|
test('years without calendar data fall back to weekdays and warn', () => {
|
|
79
|
-
const now = bj(
|
|
80
|
-
//
|
|
81
|
-
assert.equal(isPeakAt(bj(
|
|
99
|
+
const now = bj(2028, 1, 5, 12, 0);
|
|
100
|
+
// 2028-01-05 is a Wednesday; without data the weekday rule marks it peak.
|
|
101
|
+
assert.equal(isPeakAt(bj(2028, 1, 5, 10, 0)), true);
|
|
82
102
|
const agg = aggregateTurns([], { now, days: 7 });
|
|
83
|
-
assert.deepEqual(agg.warnings, [{ code: 'calendar-missing', years: [
|
|
103
|
+
assert.deepEqual(agg.warnings, [{ code: 'calendar-missing', years: [2028] }]);
|
|
84
104
|
});
|
|
85
105
|
|
|
86
106
|
test('nextSwitch walks to the next boundary and reports the target status', () => {
|
|
@@ -224,3 +244,118 @@ test('window edges stay stable across a day boundary', () => {
|
|
|
224
244
|
assert.equal(agg.window.length, 7);
|
|
225
245
|
assert.equal(now - bj(2026, 11, 10, 0, 0), 1);
|
|
226
246
|
});
|
|
247
|
+
|
|
248
|
+
test('parseSessionMeta reads cwd from the session header only', () => {
|
|
249
|
+
const text = [
|
|
250
|
+
'{"type":"session","version":4,"id":"s1","cwd":"/Users/me/projects/alpha"}',
|
|
251
|
+
'{"type":"assistant/message","time":1}',
|
|
252
|
+
].join('\n');
|
|
253
|
+
assert.deepEqual(parseSessionMeta(text), { cwd: '/Users/me/projects/alpha' });
|
|
254
|
+
assert.deepEqual(parseSessionMeta('{"type":"assistant/message"}'), { cwd: null });
|
|
255
|
+
assert.deepEqual(parseSessionMeta('not json'), { cwd: null });
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
test('projectInfo prefers cwd and decodes the workspace slug fallback', () => {
|
|
259
|
+
assert.deepEqual(projectInfo('/Users/me/projects/alpha/', '--Users-me-projects-alpha--'), {
|
|
260
|
+
key: '/Users/me/projects/alpha',
|
|
261
|
+
name: 'alpha',
|
|
262
|
+
path: '/Users/me/projects/alpha',
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
const fallback = projectInfo(null, '--Users-me-~5FAE~~8F6F~soft-alpha--');
|
|
266
|
+
assert.equal(fallback.key, 'slug:--Users-me-~5FAE~~8F6F~soft-alpha--');
|
|
267
|
+
assert.equal(fallback.name, 'Users/me/微软soft/alpha');
|
|
268
|
+
assert.equal(fallback.path, '/Users/me/微软soft/alpha');
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
test('parseSessionTurns attaches the project when one is supplied', () => {
|
|
272
|
+
const line =
|
|
273
|
+
'{"type":"assistant/message","time":200,"data":{"usage":{"inputTokens":10,"cacheReadTokens":20,"outputTokens":30},"message":{"source":{"model":"deepseek-flash"}}}}';
|
|
274
|
+
const project = { key: '/alpha', name: 'alpha', path: '/alpha' };
|
|
275
|
+
assert.deepEqual(parseSessionTurns(line, project), [
|
|
276
|
+
{
|
|
277
|
+
t: 200,
|
|
278
|
+
model: 'deepseek-flash',
|
|
279
|
+
input: 10,
|
|
280
|
+
cache: 20,
|
|
281
|
+
output: 30,
|
|
282
|
+
project,
|
|
283
|
+
},
|
|
284
|
+
]);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
test('aggregateTurns groups window spend by project, sorted by cost', () => {
|
|
288
|
+
const now = bj(2026, 11, 10, 12, 0);
|
|
289
|
+
const alpha = { key: '/alpha', name: 'alpha', path: '/alpha' };
|
|
290
|
+
const beta = { key: '/beta', name: 'beta', path: '/beta' };
|
|
291
|
+
const turns = [
|
|
292
|
+
// Peak Monday: 1M miss at peak price = 2.
|
|
293
|
+
{ t: bj(2026, 11, 9, 10, 0), model: 'deepseek-flash', input: 1e6, cache: 0, output: 0, project: alpha },
|
|
294
|
+
// Valley Tuesday: 3M miss at valley price = 3.
|
|
295
|
+
{ t: bj(2026, 11, 10, 8, 0), model: 'deepseek-flash', input: 3e6, cache: 0, output: 0, project: beta },
|
|
296
|
+
// Outside the 7-day window: must not be grouped.
|
|
297
|
+
{ t: bj(2026, 10, 1, 8, 0), model: 'deepseek-flash', input: 9e6, cache: 0, output: 0, project: alpha },
|
|
298
|
+
// Legacy turn without a project: counted in totals, not in project shares.
|
|
299
|
+
{ t: bj(2026, 11, 10, 9, 0), model: 'deepseek-flash', input: 1e6, cache: 0, output: 0 },
|
|
300
|
+
];
|
|
301
|
+
|
|
302
|
+
const agg = aggregateTurns(turns, { now, days: 7 });
|
|
303
|
+
assert.deepEqual(
|
|
304
|
+
agg.projects.map((project) => [project.name, project.path, project.calls, project.tokens, project.cost]),
|
|
305
|
+
[
|
|
306
|
+
['beta', '/beta', 1, 3_000_000, 3],
|
|
307
|
+
['alpha', '/alpha', 1, 1_000_000, 2],
|
|
308
|
+
],
|
|
309
|
+
);
|
|
310
|
+
assert.ok(Math.abs(agg.projects[0].share - 0.6) < 1e-12);
|
|
311
|
+
assert.ok(Math.abs(agg.projects[1].share - 0.4) < 1e-12);
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
test('walletSummary levels follow the 7-day and 3-day runways', () => {
|
|
315
|
+
assert.equal(walletSummary(70, 10).level, 'ok');
|
|
316
|
+
assert.equal(walletSummary(69, 10).level, 'warn');
|
|
317
|
+
assert.equal(walletSummary(30, 10).level, 'warn');
|
|
318
|
+
assert.equal(walletSummary(29, 10).level, 'low');
|
|
319
|
+
assert.deepEqual(walletSummary(29, 10), { balance: 29, avgPerDay: 10, runwayDays: 2.9, level: 'low' });
|
|
320
|
+
assert.deepEqual(walletSummary(null, 10), { balance: null, avgPerDay: 10, runwayDays: null, level: 'unknown' });
|
|
321
|
+
assert.deepEqual(walletSummary(10, 0), { balance: 10, avgPerDay: 0, runwayDays: null, level: 'unknown' });
|
|
322
|
+
assert.equal(walletSummary(-5, 10).runwayDays, 0);
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
test('buildCsv escapes cells and guards spreadsheet formulas', () => {
|
|
326
|
+
assert.equal(csvEscape('a,b'), '"a,b"');
|
|
327
|
+
assert.equal(csvEscape('say "hi"'), '"say ""hi"""');
|
|
328
|
+
assert.equal(csvEscape('=SUM(A1)'), "'=SUM(A1)");
|
|
329
|
+
assert.equal(csvEscape(3), '3');
|
|
330
|
+
assert.equal(csvEscape(null), '');
|
|
331
|
+
|
|
332
|
+
const payload = {
|
|
333
|
+
days: [
|
|
334
|
+
{
|
|
335
|
+
day: '2026-11-10',
|
|
336
|
+
calls: 2,
|
|
337
|
+
tokens: 10,
|
|
338
|
+
cost: 0.5,
|
|
339
|
+
costCache: 0.1,
|
|
340
|
+
costMiss: 0.2,
|
|
341
|
+
costOut: 0.2,
|
|
342
|
+
peakCost: 0.3,
|
|
343
|
+
valleyCost: 0.2,
|
|
344
|
+
savingIfValley: 0.15,
|
|
345
|
+
peakShare: 0.6,
|
|
346
|
+
hitRate: 0.5,
|
|
347
|
+
holiday: '国庆节',
|
|
348
|
+
},
|
|
349
|
+
],
|
|
350
|
+
projects: [{ name: 'a,b', path: '/x', calls: 1, tokens: 2, cost: 0.1, peakCost: 0.1, share: 1 }],
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
const daily = buildCsv(payload, 'days');
|
|
354
|
+
assert.match(daily, /^day,calls,tokens,cost,cost_cache/);
|
|
355
|
+
assert.match(daily, /2026-11-10,2,10,0.5,0.1,0.2,0.2,0.3,0.2,0.15,0.6,0.5,国庆节\n$/);
|
|
356
|
+
|
|
357
|
+
const projects = buildCsv(payload, 'projects');
|
|
358
|
+
assert.match(projects, /^project,path,calls,tokens,cost,peak_cost,share\n/);
|
|
359
|
+
assert.match(projects, /"a,b",\/x,1,2,0.1,0.1,1\n$/);
|
|
360
|
+
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
|
+
});
|