dsh-usage-peak 1.1.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 CHANGED
@@ -1,5 +1,23 @@
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
+
13
+ ## 1.2.0
14
+
15
+ - 峰谷判断接入中国大陆节假日/调休日历:法定节假日全天谷时,调休上班日(含周末)按工作日峰谷计算。
16
+ - 新增 `holidays.js`(2026 年国务院办公厅安排,与 holiday-cn 交叉核对);缺失年份回落到周一至周五,并在面板给出 `calendar-missing` 提示。
17
+ - 趋势图 tooltip 标注节假日名称。
18
+ - 面板新增页脚:GitHub 仓库超链接(引导 Star)、当前版本号、日历覆盖年份。
19
+ - 快照新增 `version` / `repo` / `calendar` 字段,版本号由 `package.json` 单一来源读取。
20
+
3
21
  ## 1.1.0
4
22
 
5
23
  - 新增 7 / 14 / 30 天统计窗口切换,接口支持 `?days=`(白名单校验,快照按窗口分别缓存)。
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,14 +12,18 @@
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
  - **价目表**:当前时段那一行高亮,方便解释账单。
25
+ - **节假日与调休**:按国务院办公厅公布的安排判断——法定节假日全天谷时,调休上班的周末按工作日峰谷计算;当前覆盖 2026–2027 年,缺失年份会在面板给出提示并回落到周一至周五规则。
26
+ - **页脚**:GitHub 仓库链接(可顺手点个 Star)、当前版本号与日历覆盖年份。
23
27
 
24
28
  设置页里的入口是「用量仪表盘」,侧栏胶囊就是同一份数据的浓缩版。
25
29
 
@@ -32,16 +36,19 @@
32
36
  | DeepSeek Flash | 0.02 / 0.04 | 1 / 2 | 4 / 8 |
33
37
  | DeepSeek Pro | 0.15 / 0.30 | 4.5 / 9 | 13.5 / 27 |
34
38
 
35
- 峰时 = 周一至周五 09:00–12:00、14:00–18:00(北京时间);其余时间、周末与节假日为谷时,单价减半。
39
+ 峰时 = 工作日 09:00–12:00、14:00–18:00(北京时间);其余时间、周末与法定节假日为谷时,单价减半。调休上班日(包括周末)按工作日的峰谷窗口计算。
40
+
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` 即可。
36
42
 
37
43
  ## 数据来源
38
44
 
39
- - `~/.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。
40
46
  - `~/.dsh/.dshw-usage.json`:鲸鱼记账本的余额与当日花费,用作交叉校验。
41
47
 
42
48
  日志是**多帧 zstd**,Node 自带的 `zlib.zstdDecompressSync` 只解第一帧,所以插件内部按 zstd magic 切帧、逐帧解压再拼接(不需要 `zstd` 命令行)。
43
49
 
44
- 数据接口支持 `?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。
45
52
 
46
53
  峰时单价恰为谷时 2 倍,所以「谷时更省」= 峰时花费 ÷ 2:它衡量的是这些峰时用量如果改在谷时发生能省多少,而不是已经省下的钱。
47
54
 
@@ -68,6 +75,7 @@ dsh plugin add dsh-usage-peak
68
75
 
69
76
  - 依赖 DSH 会话日志的**内部格式**(`session.v4.jsonl.zstd` 与 `assistant/message.data.usage`)。DSH 改格式时需要跟进;读不到数据时面板会显示为空态而不是报错。
70
77
  - 只统计本机会话日志覆盖到的历史,鲸鱼记账本从 2026-11-02 才开始记账。
78
+ - 项目归属依赖会话头中的 `cwd`;极少数没有会话头的旧日志会回落到 workspace slug,slug 会转义部分字节,显示名可能不如真实路径精确。
71
79
 
72
80
  ## 许可
73
81
 
@@ -81,8 +89,10 @@ A usage and cost dashboard for DeepSeek Harness. It reads the local session logs
81
89
 
82
90
  ![Sidebar pill: valley ¥17.10 · 170.3M tok · switching to peak in 13:56](assets/sidebar-pill.webp)
83
91
 
84
- - a persistent sidebar pill with peak/valley state, today's spend, tokens and the countdown to the next price switch;
85
- - 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 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);
94
+ - a footer with the GitHub repository link, the running version and the covered calendar years;
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;
86
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.
87
97
 
88
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
 
@@ -52,6 +53,9 @@ window.__ModuleLoader__.load({
52
53
  'unit.calls': '次',
53
54
  'unit.minute': '分',
54
55
  'warn.unknownModel': '未识别的模型按 Flash 价计算',
56
+ 'warn.calendarMissing': '以下年份还没有节假日数据,峰谷按周一至周五计算:',
57
+ 'footer.calendar': '峰谷已计入节假日与调休:',
58
+ 'footer.star': '给个 Star',
55
59
  'range.7': '近 7 天',
56
60
  'range.14': '近 14 天',
57
61
  'range.30': '近 30 天',
@@ -72,6 +76,29 @@ window.__ModuleLoader__.load({
72
76
  'kpi.saving': '谷时更省',
73
77
  'kpi.savingHint': '峰时按谷价计',
74
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',
75
102
 
76
103
  'chart.hours': '今日每小时花费',
77
104
  'chart.hoursHint': '橙 峰时 · 绿 谷时',
@@ -123,6 +150,9 @@ window.__ModuleLoader__.load({
123
150
  'unit.calls': 'req',
124
151
  'unit.minute': 'm',
125
152
  'warn.unknownModel': 'Unknown models are priced as Flash',
153
+ 'warn.calendarMissing': 'No holiday data for these years, peak hours fall back to Mon-Fri:',
154
+ 'footer.calendar': 'Peak hours include holidays and makeup workdays:',
155
+ 'footer.star': 'Star it',
126
156
  'range.7': 'Last 7 days',
127
157
  'range.14': 'Last 14 days',
128
158
  'range.30': 'Last 30 days',
@@ -143,6 +173,29 @@ window.__ModuleLoader__.load({
143
173
  'kpi.saving': 'Valley saving',
144
174
  'kpi.savingHint': 'peak tokens at valley price',
145
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',
146
199
 
147
200
  'chart.hours': 'Cost per hour today',
148
201
  'chart.hoursHint': 'orange peak · green valley',
@@ -177,6 +230,7 @@ window.__ModuleLoader__.load({
177
230
  cache: 'var(--dsw-alias-state-business-primary)',
178
231
  miss: 'var(--dsw-alias-state-warn-primary)',
179
232
  out: 'var(--dsw-alias-brand-primary)',
233
+ error: 'var(--dsw-alias-state-error-primary)',
180
234
  };
181
235
 
182
236
  /* ------------------------------ formatting ------------------------------ */
@@ -229,6 +283,13 @@ window.__ModuleLoader__.load({
229
283
  return `${minutes}${typeof t === 'function' ? t('unit.minute') : '分'}`;
230
284
  }
231
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
+
232
293
  /* --------------------------------- data --------------------------------- */
233
294
 
234
295
  function useFeed(days) {
@@ -281,6 +342,7 @@ window.__ModuleLoader__.load({
281
342
  return h(
282
343
  'span',
283
344
  {
345
+ title: props.title,
284
346
  style: {
285
347
  display: 'inline-flex',
286
348
  alignItems: 'center',
@@ -338,14 +400,23 @@ window.__ModuleLoader__.load({
338
400
  const tone = loading ? C.text3 : peak ? C.peak : C.valley;
339
401
  const word = loading ? t('widget.loading') : peak ? t('widget.peak') : t('widget.valley');
340
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)}` : '';
341
408
  const remain = data ? Math.max(0, data.now.nextAt - Date.now()) : 0;
342
409
  const switchText =
343
410
  data && remain > 30_000
344
411
  ? `${countdown(remain, t)} ${peak ? t('widget.toValley') : t('widget.toPeak')}`
345
412
  : t('widget.soon');
346
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
+ : '';
347
418
  const tip = data
348
- ? `${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}` : ''}`
349
420
  : word;
350
421
 
351
422
  // The seat is the shell's own flex row: the root takes a whole line (see
@@ -360,7 +431,8 @@ window.__ModuleLoader__.load({
360
431
  height: 21,
361
432
  padding: '0 8px',
362
433
  borderRadius: 999,
363
- border: `1px solid ${C.border}`,
434
+ border: `1px solid ${walletAlert ? walletTone : C.border}`,
435
+ background: walletAlert ? `${walletTone}14` : 'transparent',
364
436
  fontSize: 10.5,
365
437
  lineHeight: '19px',
366
438
  color: C.text2,
@@ -386,7 +458,19 @@ window.__ModuleLoader__.load({
386
458
  h('span', { style: { color: C.text3, marginLeft: 2 } }, 'tok'),
387
459
  ),
388
460
  h(Sep),
389
- h('span', { style: { color: C.text3, fontVariantNumeric: 'tabular-nums', overflow: 'hidden', textOverflow: 'ellipsis' } }, data ? switchText : ''),
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
+ ),
390
474
  );
391
475
 
392
476
  return h('div', { ...rootProps, title: tip, onClick: open || undefined, style: rootStyle }, pill);
@@ -419,7 +503,14 @@ window.__ModuleLoader__.load({
419
503
  'header',
420
504
  { style: { display: 'flex', alignItems: 'baseline', gap: 8, justifyContent: 'space-between' } },
421
505
  h('h3', { style: { margin: 0, fontSize: 12.5, fontWeight: 600, color: C.text } }, props.title),
422
- props.hint ? h('span', { style: { fontSize: 10.5, color: C.text3 } }, props.hint) : null,
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,
423
514
  );
424
515
  }
425
516
 
@@ -514,7 +605,7 @@ window.__ModuleLoader__.load({
514
605
  h(
515
606
  'div',
516
607
  {
517
- title: `${entry.day} · ${yuan(entry.cost)} · ${entry.calls} ${props.t('unit.calls')}`,
608
+ title: `${entry.day}${entry.holiday ? ` · ${entry.holiday}` : ''} · ${yuan(entry.cost)} · ${entry.calls} ${props.t('unit.calls')}`,
518
609
  style: {
519
610
  flex: 1,
520
611
  width: '100%',
@@ -625,6 +716,118 @@ window.__ModuleLoader__.load({
625
716
  );
626
717
  }
627
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
+
628
831
  /* -------------------------------- settings ------------------------------- */
629
832
 
630
833
  function Dashboard(props) {
@@ -634,6 +837,10 @@ window.__ModuleLoader__.load({
634
837
  const data = feed.data;
635
838
  const windowDays = (data && data.windowDays) || days;
636
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;
637
844
  const remain = data ? Math.max(0, data.now.nextAt - Date.now()) : 0;
638
845
  const switchText =
639
846
  data && remain > 30_000
@@ -696,13 +903,26 @@ window.__ModuleLoader__.load({
696
903
  ),
697
904
  h(
698
905
  Pill,
699
- null,
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
+ },
700
913
  `${t('kpi.balance')} `,
701
914
  h(
702
915
  'span',
703
916
  { style: { color: C.text } },
704
917
  data.ledger && typeof data.ledger.balance === 'number' ? yuan(data.ledger.balance) : '—',
705
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,
706
926
  ),
707
927
  h(Pill, null, `${today.calls || 0} ${t('unit.calls')} · ${tokens(today.tokens, t)} tokens`),
708
928
  ),
@@ -721,7 +941,9 @@ window.__ModuleLoader__.load({
721
941
  ? warning
722
942
  : warning.code === 'unknown-model'
723
943
  ? `${t('warn.unknownModel')}: ${(warning.models || []).join(', ')}`
724
- : String(warning.code || warning),
944
+ : warning.code === 'calendar-missing'
945
+ ? `${t('warn.calendarMissing')} ${(warning.years || []).join(' / ')}`
946
+ : String(warning.code || warning),
725
947
  ),
726
948
  ),
727
949
  ),
@@ -732,6 +954,15 @@ window.__ModuleLoader__.load({
732
954
  h(
733
955
  'div',
734
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
+ }),
735
966
  h(Kpi, {
736
967
  label: t('kpi.calls'),
737
968
  value: today.calls || 0,
@@ -801,6 +1032,38 @@ window.__ModuleLoader__.load({
801
1032
  ),
802
1033
  );
803
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
+
804
1067
  body.push(
805
1068
  h(
806
1069
  Card,
@@ -878,8 +1141,90 @@ window.__ModuleLoader__.load({
878
1141
  },
879
1142
  t('page.refresh'),
880
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
+ ),
881
1162
  ),
882
1163
  body,
1164
+ h(
1165
+ 'footer',
1166
+ {
1167
+ style: {
1168
+ marginTop: 2,
1169
+ paddingTop: 10,
1170
+ borderTop: `1px solid ${C.border}`,
1171
+ display: 'flex',
1172
+ alignItems: 'center',
1173
+ justifyContent: 'space-between',
1174
+ gap: 10,
1175
+ flexWrap: 'wrap',
1176
+ fontSize: 10.5,
1177
+ color: C.text3,
1178
+ },
1179
+ },
1180
+ h(
1181
+ 'span',
1182
+ null,
1183
+ data && data.calendar && data.calendar.years && data.calendar.years.length
1184
+ ? `${t('footer.calendar')} ${data.calendar.years.join(' / ')}`
1185
+ : '',
1186
+ ),
1187
+ h(
1188
+ 'div',
1189
+ { style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' } },
1190
+ h(
1191
+ 'a',
1192
+ {
1193
+ href: (data && data.repo) || 'https://github.com/hhse/dsh-usage-peak',
1194
+ target: '_blank',
1195
+ rel: 'noopener noreferrer',
1196
+ title: 'https://github.com/hhse/dsh-usage-peak',
1197
+ style: {
1198
+ color: C.text2,
1199
+ textDecoration: 'none',
1200
+ fontWeight: 500,
1201
+ display: 'inline-flex',
1202
+ alignItems: 'center',
1203
+ gap: 5,
1204
+ },
1205
+ },
1206
+ '⭐',
1207
+ 'github.com/hhse/dsh-usage-peak',
1208
+ h('span', { style: { color: C.peak, fontWeight: 600 } }, `· ${t('footer.star')}`),
1209
+ ),
1210
+ data && data.version
1211
+ ? h(
1212
+ 'span',
1213
+ {
1214
+ style: {
1215
+ padding: '1px 6px',
1216
+ borderRadius: 6,
1217
+ border: `1px solid ${C.border}`,
1218
+ background: C.layer2,
1219
+ color: C.text2,
1220
+ fontVariantNumeric: 'tabular-nums',
1221
+ },
1222
+ },
1223
+ `v${data.version}`,
1224
+ )
1225
+ : null,
1226
+ ),
1227
+ ),
883
1228
  );
884
1229
  }
885
1230
 
package/holidays.js ADDED
@@ -0,0 +1,110 @@
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 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.
13
+ *
14
+ * To support a new year, append its dates here and add the year to
15
+ * CALENDAR_YEARS. Years without data fall back to the weekday rule and raise a
16
+ * `calendar-missing` warning in the snapshot.
17
+ */
18
+
19
+ /** Years covered by the data below. */
20
+ export const CALENDAR_YEARS = [2026, 2027];
21
+
22
+ /** Public holidays: date -> name. Billed at the valley tariff all day. */
23
+ export const OFF_DAYS = new Map([
24
+ ['2026-01-01', '元旦'],
25
+ ['2026-01-02', '元旦'],
26
+ ['2026-01-03', '元旦'],
27
+ ['2026-02-15', '春节'],
28
+ ['2026-02-16', '春节'],
29
+ ['2026-02-17', '春节'],
30
+ ['2026-02-18', '春节'],
31
+ ['2026-02-19', '春节'],
32
+ ['2026-02-20', '春节'],
33
+ ['2026-02-21', '春节'],
34
+ ['2026-02-22', '春节'],
35
+ ['2026-02-23', '春节'],
36
+ ['2026-04-04', '清明节'],
37
+ ['2026-04-05', '清明节'],
38
+ ['2026-04-06', '清明节'],
39
+ ['2026-05-01', '劳动节'],
40
+ ['2026-05-02', '劳动节'],
41
+ ['2026-05-03', '劳动节'],
42
+ ['2026-05-04', '劳动节'],
43
+ ['2026-05-05', '劳动节'],
44
+ ['2026-06-19', '端午节'],
45
+ ['2026-06-20', '端午节'],
46
+ ['2026-06-21', '端午节'],
47
+ ['2026-09-25', '中秋节'],
48
+ ['2026-09-26', '中秋节'],
49
+ ['2026-09-27', '中秋节'],
50
+ ['2026-10-01', '国庆节'],
51
+ ['2026-10-02', '国庆节'],
52
+ ['2026-10-03', '国庆节'],
53
+ ['2026-10-04', '国庆节'],
54
+ ['2026-10-05', '国庆节'],
55
+ ['2026-10-06', '国庆节'],
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', '国庆节'],
86
+ ]);
87
+
88
+ /** Makeup workdays: date -> the holiday they belong to. */
89
+ export const WORKDAYS = new Map([
90
+ ['2026-01-04', '元旦'],
91
+ ['2026-02-14', '春节'],
92
+ ['2026-02-28', '春节'],
93
+ ['2026-05-09', '劳动节'],
94
+ ['2026-09-20', '国庆节'],
95
+ ['2026-10-10', '国庆节'],
96
+ ['2027-01-31', '春节'],
97
+ ['2027-02-14', '春节'],
98
+ ['2027-05-08', '劳动节'],
99
+ ['2027-09-26', '国庆节'],
100
+ ['2027-10-09', '国庆节'],
101
+ ]);
102
+
103
+ /** Calendar year of a `YYYY-MM-DD` day key, as a number. */
104
+ export function yearOf(dayKey) {
105
+ return Number(String(dayKey).slice(0, 4));
106
+ }
107
+
108
+ export function hasCalendar(year) {
109
+ return CALENDAR_YEARS.includes(Number(year));
110
+ }
package/index.js CHANGED
@@ -14,7 +14,11 @@ 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;
@@ -43,11 +47,18 @@ export function dayKey(ts) {
43
47
  return bjDate(ts).toISOString().slice(0, 10);
44
48
  }
45
49
 
46
- /** Peak = Beijing Mon-Fri 09:00-12:00 and 14:00-18:00; everything else is valley (half price). */
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
+ */
47
55
  export function isPeakAt(ts) {
56
+ const key = dayKey(ts);
57
+ if (OFF_DAYS.has(key)) return false;
48
58
  const d = bjDate(ts);
49
59
  const dow = d.getUTCDay();
50
- if (dow === 0 || dow === 6) return false;
60
+ const weekend = dow === 0 || dow === 6;
61
+ if (weekend && !WORKDAYS.has(key)) return false;
51
62
  const minutes = d.getUTCHours() * 60 + d.getUTCMinutes();
52
63
  return (minutes >= 540 && minutes < 720) || (minutes >= 840 && minutes < 1080);
53
64
  }
@@ -60,8 +71,10 @@ export function nextSwitch(ts) {
60
71
  const da = d.getUTCDate();
61
72
  for (let k = 0; k < 9; k += 1) {
62
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;
63
76
  const dow = probe.getUTCDay();
64
- if (dow === 0 || dow === 6) continue;
77
+ if ((dow === 0 || dow === 6) && !WORKDAYS.has(key)) continue;
65
78
  for (const hour of [9, 12, 14, 18]) {
66
79
  const at = Date.UTC(probe.getUTCFullYear(), probe.getUTCMonth(), probe.getUTCDate(), hour, 0, 0) - BJ_OFFSET;
67
80
  if (at > ts) return { at, status: hour === 9 || hour === 14 ? 'peak' : 'valley' };
@@ -112,8 +125,52 @@ export function decodeSessionFile(file) {
112
125
  return Buffer.concat(chunks).toString('utf8');
113
126
  }
114
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
+
115
172
  /** One turn per billed model request: { t, model, input, cache, output }. */
116
- export function parseSessionTurns(text) {
173
+ export function parseSessionTurns(text, project) {
117
174
  const turns = [];
118
175
  for (const line of text.split('\n')) {
119
176
  if (line.length < 2) continue;
@@ -127,13 +184,15 @@ export function parseSessionTurns(text) {
127
184
  const usage = record.data && record.data.usage;
128
185
  if (!usage) continue;
129
186
  const model = (record.data.message && record.data.message.source && record.data.message.source.model) || 'unknown';
130
- turns.push({
187
+ const turn = {
131
188
  t: record.time,
132
189
  model,
133
190
  input: usage.inputTokens || 0,
134
191
  cache: usage.cacheReadTokens || 0,
135
192
  output: usage.outputTokens || 0,
136
- });
193
+ };
194
+ if (project) turn.project = project;
195
+ turns.push(turn);
137
196
  }
138
197
  return turns;
139
198
  }
@@ -182,7 +241,8 @@ export function collectTurns() {
182
241
  if (!entry || entry.mtimeMs !== stat.mtimeMs || entry.size !== stat.size) {
183
242
  let parsed = [];
184
243
  try {
185
- parsed = parseSessionTurns(decodeSessionFile(file));
244
+ const text = decodeSessionFile(file);
245
+ parsed = parseSessionTurns(text, projectInfo(parseSessionMeta(text).cwd, workspace.name));
186
246
  } catch {
187
247
  parsed = [];
188
248
  }
@@ -249,6 +309,8 @@ export function addTurn(day, turn) {
249
309
  slot.calls += 1;
250
310
  slot.cost += cost;
251
311
  slot.tokens += turn.input + turn.cache + turn.output;
312
+
313
+ return { cost, peak, tokens: turn.input + turn.cache + turn.output };
252
314
  }
253
315
 
254
316
  export function readLedger() {
@@ -289,6 +351,7 @@ export function shapeDay(day) {
289
351
  // Peak is exactly 2x valley, so moving these peak tokens to valley saves half.
290
352
  savingIfValley: round(day.peakCost / 2),
291
353
  peakShare: day.cost > 0 ? day.peakCost / day.cost : 0,
354
+ holiday: OFF_DAYS.get(day.day) || null,
292
355
  hitRate: billable > 0 ? day.cacheTokens / billable : 0,
293
356
  avgTokens: day.calls > 0 ? Math.round(tokens / day.calls) : 0,
294
357
  firstAt: day.firstAt,
@@ -311,6 +374,34 @@ export function hoursOf(day) {
311
374
  }));
312
375
  }
313
376
 
377
+ /** Calendar years touched by the window that have no holiday data yet. */
378
+ function missingCalendarYears(window) {
379
+ const years = new Set();
380
+ for (const entry of window) {
381
+ const year = yearOf(entry.day);
382
+ if (!hasCalendar(year)) years.add(year);
383
+ }
384
+ return years.size > 0 ? [{ code: 'calendar-missing', years: [...years] }] : [];
385
+ }
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
+
314
405
  /**
315
406
  * Pure aggregation over decoded turns.
316
407
  *
@@ -322,18 +413,43 @@ export function aggregateTurns(turns, options = {}) {
322
413
  const now = Number.isFinite(options.now) ? options.now : Date.now();
323
414
  const days = normalizeDays(options.days);
324
415
  const byDay = new Map();
416
+ const byProject = new Map();
325
417
  const unknownModels = new Set();
418
+ const firstKey = dayKey(now - (days - 1) * DAY_MS);
419
+ const todayKey = dayKey(now);
420
+ let attributedCost = 0;
326
421
 
327
422
  for (const turn of turns || []) {
328
423
  if (!turn || !Number.isFinite(turn.t)) continue;
329
424
  const key = dayKey(turn.t);
425
+ if (key < firstKey || key > todayKey) continue;
330
426
  let day = byDay.get(key);
331
427
  if (!day) {
332
428
  day = emptyDay(key);
333
429
  byDay.set(key, day);
334
430
  }
335
- addTurn(day, turn);
431
+ const priced = addTurn(day, turn);
336
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
+ }
337
453
  }
338
454
 
339
455
  const window = [];
@@ -375,11 +491,21 @@ export function aggregateTurns(turns, options = {}) {
375
491
  return { id: price.id, label: price.label, calls, cost: round(cost), tokens };
376
492
  });
377
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
+
378
503
  return {
379
504
  windowDays: days,
380
505
  today,
381
506
  hours: today ? today.hours : [],
382
507
  window,
508
+ projects,
383
509
  week: {
384
510
  cost: round(week.cost),
385
511
  calls: week.calls,
@@ -394,7 +520,10 @@ export function aggregateTurns(turns, options = {}) {
394
520
  avgTokensPerCall: week.calls > 0 ? Math.round(week.tokens / week.calls) : 0,
395
521
  },
396
522
  models,
397
- warnings: unknownModels.size > 0 ? [{ code: 'unknown-model', models: [...unknownModels] }] : [],
523
+ warnings: [
524
+ ...(unknownModels.size > 0 ? [{ code: 'unknown-model', models: [...unknownModels] }] : []),
525
+ ...missingCalendarYears(window),
526
+ ],
398
527
  };
399
528
  }
400
529
 
@@ -421,6 +550,9 @@ export function buildSnapshot(options = {}) {
421
550
  ok: true,
422
551
  generatedAt: now,
423
552
  tz: 'Asia/Shanghai',
553
+ version: VERSION,
554
+ repo: REPO_URL,
555
+ calendar: { years: CALENDAR_YEARS, holidays: OFF_DAYS.size, workdays: WORKDAYS.size },
424
556
  windowDays: days,
425
557
  now: {
426
558
  ts: now,
@@ -439,7 +571,9 @@ export function buildSnapshot(options = {}) {
439
571
  today: agg.today,
440
572
  hours: agg.hours,
441
573
  days: agg.window,
574
+ projects: agg.projects,
442
575
  week: agg.week,
576
+ wallet: walletSummary(ledger.ok ? ledger.balance : null, agg.week.avgPerDay),
443
577
  models: agg.models,
444
578
  pricing: PRICING.map((price) => ({
445
579
  id: price.id,
@@ -456,6 +590,68 @@ export function buildSnapshot(options = {}) {
456
590
  return payload;
457
591
  }
458
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
+
459
655
  /* ------------------------------------------------------------------ */
460
656
  /* HTTP surface */
461
657
  /* ------------------------------------------------------------------ */
@@ -533,7 +729,36 @@ export function apply(ctx) {
533
729
  },
534
730
  });
535
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
+
536
760
  ctx.effect(() => () => {
537
761
  dispose();
762
+ disposeExport();
538
763
  }, `${NS}: dashboard route`);
539
764
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-usage-peak",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
- "description": "DeepSeek Harness 用量峰谷仪表盘:峰/谷时段、今日花费与 tokens、7/14/30 天窗口、缓存命中、谷时更省与花费构成,侧栏常驻胶囊 + 设置页详情。",
5
+ "description": "DeepSeek Harness 用量峰谷仪表盘:峰/谷时段(含节假日与调休)、今日花费与 tokens、按项目/模型统计、余额可撑天数、CSV 导出、7/14/30 天窗口、缓存命中、谷时更省,侧栏常驻胶囊 + 设置页详情。",
6
6
  "exports": {
7
7
  ".": "./index.js",
8
8
  "./client": "./client.js",
@@ -12,6 +12,7 @@
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",
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. */
@@ -41,6 +46,63 @@ test('isPeakAt covers the four weekday windows and nothing else', () => {
41
46
  assert.equal(isPeakAt(bj(2026, 11, 8, 15, 0)), false);
42
47
  });
43
48
 
49
+ test('public holidays are valley all day, makeup workdays follow weekday hours', () => {
50
+ // 2026 National Day: Oct 1 (Thu) is a public holiday.
51
+ assert.equal(isPeakAt(bj(2026, 10, 1, 10, 0)), false);
52
+ assert.equal(isPeakAt(bj(2026, 10, 7, 15, 0)), false);
53
+ // Spring Festival makeup: Feb 14 is a Saturday but a working day.
54
+ assert.equal(isPeakAt(bj(2026, 2, 14, 10, 0)), true);
55
+ assert.equal(isPeakAt(bj(2026, 2, 14, 13, 0)), false);
56
+ // New Year makeup: Jan 4 is a Sunday but a working day.
57
+ assert.equal(isPeakAt(bj(2026, 1, 4, 10, 0)), true);
58
+ // A plain weekend stays valley.
59
+ assert.equal(isPeakAt(bj(2026, 11, 7, 10, 0)), false);
60
+ });
61
+
62
+ test('nextSwitch skips holiday blocks and honors makeup workdays', () => {
63
+ // Wednesday Sep 30 2026 evening: Oct 1-7 are holidays, next peak is Oct 8.
64
+ const afterNationalDay = nextSwitch(bj(2026, 9, 30, 19, 0));
65
+ assert.equal(afterNationalDay.at, bj(2026, 10, 8, 9, 0));
66
+ assert.equal(afterNationalDay.status, 'peak');
67
+
68
+ // Saturday Sep 19: Sunday Sep 20 is a makeup workday, so it is the next peak.
69
+ const makeup = nextSwitch(bj(2026, 9, 19, 10, 0));
70
+ assert.equal(makeup.at, bj(2026, 9, 20, 9, 0));
71
+ assert.equal(makeup.status, 'peak');
72
+ });
73
+
74
+ test('aggregateTurns tags holiday days in the window', () => {
75
+ const now = bj(2026, 10, 7, 12, 0);
76
+ const agg = aggregateTurns([], { now, days: 7 });
77
+ assert.equal(agg.window[0].day, '2026-10-01');
78
+ assert.equal(agg.window[0].holiday, '国庆节');
79
+ assert.equal(agg.window[6].holiday, '国庆节');
80
+ assert.deepEqual(agg.warnings, []);
81
+ });
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
+
98
+ test('years without calendar data fall back to weekdays and warn', () => {
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);
102
+ const agg = aggregateTurns([], { now, days: 7 });
103
+ assert.deepEqual(agg.warnings, [{ code: 'calendar-missing', years: [2028] }]);
104
+ });
105
+
44
106
  test('nextSwitch walks to the next boundary and reports the target status', () => {
45
107
  const lunch = nextSwitch(bj(2026, 11, 9, 12, 30));
46
108
  assert.equal(lunch.status, 'peak');
@@ -182,3 +244,118 @@ test('window edges stay stable across a day boundary', () => {
182
244
  assert.equal(agg.window.length, 7);
183
245
  assert.equal(now - bj(2026, 11, 10, 0, 0), 1);
184
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
+ });