dsh-usage-peak 1.2.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.1
4
+
5
+ - 修复余额充足时头部胶囊仍显示「余额仅够 X 天」的文案:改为「可撑 X 天」,只有低于 7 天警戒线才显示「余额仅够」。
6
+
7
+ ## 1.3.0
8
+
9
+ - 新增「按项目」统计:从会话头读取绝对 `cwd`,按项目聚合窗口内的请求、tokens、花费与占比;没有会话头时回落到 workspace slug 解码。
10
+ - 新增「余额可撑」:余额 ÷ 近 7 天日均花费;侧栏胶囊 <7 天转琥珀、<3 天转红,详情页新增 KPI 与余额胶囊提示。
11
+ - 新增 CSV 导出:`/plugin/dsh-usage-peak/export.csv?days=&scope=days|projects`,UTF-8 BOM + 公式注入防护;页面提供「导出 CSV」与「项目 CSV」。
12
+ - 补齐 README 里承诺、界面却缺失的「按模型」表(Flash / Pro 请求数、tokens、花费)。
13
+ - 节假日日历新增 2027 年(国务院办公厅 2027 年通知,与 holiday-cn 交叉核对);覆盖 2026–2027。
14
+ - 聚合时先按统计窗口过滤,窗口外请求不再影响项目占比或未识别模型提示。
15
+ - 新增纯函数 `parseSessionMeta` / `projectInfo` / `walletSummary` / `buildCsv`,测试从 14 条增至 21 条。
16
+
3
17
  ## 1.2.0
4
18
 
5
19
  - 峰谷判断接入中国大陆节假日/调休日历:法定节假日全天谷时,调休上班日(含周末)按工作日峰谷计算。
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),来源为[国务院办公厅 2026 年放假安排通知](https://www.gov.cn/zhengce/zhengceku/202511/content_7047091.htm),并与 [holiday-cn](https://github.com/NateScarlet/holiday-cn) 交叉核对。新一年安排公布后,补一组日期并把年份加进 `CALENDAR_YEARS` 即可。
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
  ![Sidebar pill: valley ¥17.10 · 170.3M tok · switching to peak in 13:56](assets/sidebar-pill.webp)
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 calendar shipped; missing years fall back to Mon-Fri with a visible warning);
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,30 @@ 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.runway': '可撑',
85
+ 'wallet.warn': '余额偏低',
86
+ 'wallet.low': '余额紧张',
87
+
88
+ 'projects.title': '按项目',
89
+ 'projects.hint': '按花费排序',
90
+ 'projects.name': '项目',
91
+ 'projects.calls': '请求',
92
+ 'projects.tokens': 'tokens',
93
+ 'projects.cost': '花费',
94
+ 'projects.share': '占比',
95
+ 'projects.empty': '这个窗口内还没有项目数据',
96
+ 'models.title': '按模型',
97
+ 'models.hint': '窗口内',
98
+ 'models.empty': '暂无请求',
99
+ 'export.csv': '导出 CSV',
100
+ 'export.projects': '项目 CSV',
101
+ 'export.daysTitle': '导出每日数据 CSV',
102
+ 'export.projectsTitle': '导出项目数据 CSV',
78
103
 
79
104
  'chart.hours': '今日每小时花费',
80
105
  'chart.hoursHint': '橙 峰时 · 绿 谷时',
@@ -149,6 +174,30 @@ window.__ModuleLoader__.load({
149
174
  'kpi.saving': 'Valley saving',
150
175
  'kpi.savingHint': 'peak tokens at valley price',
151
176
  'kpi.windowSaving': '7d saving',
177
+ 'kpi.runway': 'Runway',
178
+ 'kpi.runwayHint': 'balance ÷ 7-day average',
179
+ 'unit.day': 'd',
180
+ 'wallet.avg': 'avg',
181
+ 'wallet.alert': 'Balance covers',
182
+ 'wallet.runway': 'covers',
183
+ 'wallet.warn': 'Low balance',
184
+ 'wallet.low': 'Balance critical',
185
+
186
+ 'projects.title': 'By project',
187
+ 'projects.hint': 'sorted by spend',
188
+ 'projects.name': 'Project',
189
+ 'projects.calls': 'req',
190
+ 'projects.tokens': 'tokens',
191
+ 'projects.cost': 'Spend',
192
+ 'projects.share': 'Share',
193
+ 'projects.empty': 'No project data in this window',
194
+ 'models.title': 'By model',
195
+ 'models.hint': 'in window',
196
+ 'models.empty': 'No requests yet',
197
+ 'export.csv': 'Export CSV',
198
+ 'export.projects': 'Projects CSV',
199
+ 'export.daysTitle': 'Export daily CSV',
200
+ 'export.projectsTitle': 'Export project CSV',
152
201
 
153
202
  'chart.hours': 'Cost per hour today',
154
203
  'chart.hoursHint': 'orange peak · green valley',
@@ -183,6 +232,7 @@ window.__ModuleLoader__.load({
183
232
  cache: 'var(--dsw-alias-state-business-primary)',
184
233
  miss: 'var(--dsw-alias-state-warn-primary)',
185
234
  out: 'var(--dsw-alias-brand-primary)',
235
+ error: 'var(--dsw-alias-state-error-primary)',
186
236
  };
187
237
 
188
238
  /* ------------------------------ formatting ------------------------------ */
@@ -235,6 +285,13 @@ window.__ModuleLoader__.load({
235
285
  return `${minutes}${typeof t === 'function' ? t('unit.minute') : '分'}`;
236
286
  }
237
287
 
288
+ /** Runway in days: 2.9 / 7 / <1 / 120. */
289
+ function runway(value, t) {
290
+ if (value === null || value === undefined || Number.isNaN(value)) return '—';
291
+ const days = value <= 0 ? '0' : value < 1 ? '<1' : value >= 100 ? String(Math.round(value)) : value.toFixed(1).replace(/\.0$/, '');
292
+ return `${days} ${t('unit.day')}`;
293
+ }
294
+
238
295
  /* --------------------------------- data --------------------------------- */
239
296
 
240
297
  function useFeed(days) {
@@ -287,6 +344,7 @@ window.__ModuleLoader__.load({
287
344
  return h(
288
345
  'span',
289
346
  {
347
+ title: props.title,
290
348
  style: {
291
349
  display: 'inline-flex',
292
350
  alignItems: 'center',
@@ -344,14 +402,23 @@ window.__ModuleLoader__.load({
344
402
  const tone = loading ? C.text3 : peak ? C.peak : C.valley;
345
403
  const word = loading ? t('widget.loading') : peak ? t('widget.peak') : t('widget.valley');
346
404
  const short = word.slice(0, 1) === '峰' ? '峰' : word.slice(0, 1) === '谷' ? '谷' : word;
405
+ const wallet = data && data.wallet ? data.wallet : null;
406
+ const walletLevel = wallet ? wallet.level : 'unknown';
407
+ const walletAlert = walletLevel === 'low' || walletLevel === 'warn';
408
+ const walletTone = walletLevel === 'low' ? C.error : walletLevel === 'warn' ? C.peak : C.text3;
409
+ const walletText = walletAlert ? `${t('wallet.alert')} ${runway(wallet.runwayDays, t)}` : '';
347
410
  const remain = data ? Math.max(0, data.now.nextAt - Date.now()) : 0;
348
411
  const switchText =
349
412
  data && remain > 30_000
350
413
  ? `${countdown(remain, t)} ${peak ? t('widget.toValley') : t('widget.toPeak')}`
351
414
  : t('widget.soon');
352
415
  const today = data && data.today ? data.today.cost : null;
416
+ const walletTip =
417
+ wallet && wallet.balance !== null
418
+ ? `${t('kpi.balance')} ${yuan(wallet.balance)}${walletText ? ` · ${walletText}` : ''}`
419
+ : '';
353
420
  const tip = data
354
- ? `${word} · ${t('widget.today')} ${yuan(today)} · ${tokens(data.today ? data.today.tokens : 0, t)} tokens · ${t('status.switchIn')} ${switchText}`
421
+ ? `${word} · ${t('widget.today')} ${yuan(today)} · ${tokens(data.today ? data.today.tokens : 0, t)} tokens · ${t('status.switchIn')} ${switchText}${walletTip ? ` · ${walletTip}` : ''}`
355
422
  : word;
356
423
 
357
424
  // The seat is the shell's own flex row: the root takes a whole line (see
@@ -366,7 +433,8 @@ window.__ModuleLoader__.load({
366
433
  height: 21,
367
434
  padding: '0 8px',
368
435
  borderRadius: 999,
369
- border: `1px solid ${C.border}`,
436
+ border: `1px solid ${walletAlert ? walletTone : C.border}`,
437
+ background: walletAlert ? `${walletTone}14` : 'transparent',
370
438
  fontSize: 10.5,
371
439
  lineHeight: '19px',
372
440
  color: C.text2,
@@ -392,7 +460,19 @@ window.__ModuleLoader__.load({
392
460
  h('span', { style: { color: C.text3, marginLeft: 2 } }, 'tok'),
393
461
  ),
394
462
  h(Sep),
395
- h('span', { style: { color: C.text3, fontVariantNumeric: 'tabular-nums', overflow: 'hidden', textOverflow: 'ellipsis' } }, data ? switchText : ''),
463
+ h(
464
+ 'span',
465
+ {
466
+ style: {
467
+ color: walletAlert ? walletTone : C.text3,
468
+ fontWeight: walletAlert ? 600 : 400,
469
+ fontVariantNumeric: 'tabular-nums',
470
+ overflow: 'hidden',
471
+ textOverflow: 'ellipsis',
472
+ },
473
+ },
474
+ data ? (walletAlert ? `⚠ ${runway(wallet.runwayDays, t)}` : switchText) : '',
475
+ ),
396
476
  );
397
477
 
398
478
  return h('div', { ...rootProps, title: tip, onClick: open || undefined, style: rootStyle }, pill);
@@ -425,7 +505,14 @@ window.__ModuleLoader__.load({
425
505
  'header',
426
506
  { style: { display: 'flex', alignItems: 'baseline', gap: 8, justifyContent: 'space-between' } },
427
507
  h('h3', { style: { margin: 0, fontSize: 12.5, fontWeight: 600, color: C.text } }, props.title),
428
- props.hint ? h('span', { style: { fontSize: 10.5, color: C.text3 } }, props.hint) : null,
508
+ props.hint || props.action
509
+ ? h(
510
+ 'span',
511
+ { style: { display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 10.5, color: C.text3 } },
512
+ props.hint ? h('span', null, props.hint) : null,
513
+ props.action || null,
514
+ )
515
+ : null,
429
516
  );
430
517
  }
431
518
 
@@ -631,6 +718,118 @@ window.__ModuleLoader__.load({
631
718
  );
632
719
  }
633
720
 
721
+ const cellHead = (align) => ({
722
+ padding: '3px 8px',
723
+ textAlign: align,
724
+ fontWeight: 500,
725
+ color: C.text3,
726
+ borderBottom: `1px solid ${C.border}`,
727
+ whiteSpace: 'nowrap',
728
+ position: 'sticky',
729
+ top: 0,
730
+ background: C.layer1,
731
+ zIndex: 1,
732
+ });
733
+
734
+ const cellBody = {
735
+ padding: '4px 8px',
736
+ color: C.text2,
737
+ whiteSpace: 'nowrap',
738
+ fontVariantNumeric: 'tabular-nums',
739
+ };
740
+
741
+ function ProjectTable(props) {
742
+ const { projects, t } = props;
743
+ if (!projects || !projects.length) {
744
+ return h('span', { style: { fontSize: 11.5, color: C.text3 } }, t('projects.empty'));
745
+ }
746
+ const head = [t('projects.name'), t('projects.calls'), t('projects.tokens'), t('projects.cost'), t('projects.share')];
747
+ return h(
748
+ 'div',
749
+ { style: { maxHeight: 214, overflowY: 'auto', margin: '0 -2px' } },
750
+ h(
751
+ 'table',
752
+ { style: { width: '100%', borderCollapse: 'collapse', fontSize: 11.5 } },
753
+ h(
754
+ 'thead',
755
+ null,
756
+ h(
757
+ 'tr',
758
+ null,
759
+ head.map((label, index) =>
760
+ h('th', { key: label, style: cellHead(index === 0 ? 'left' : 'right') }, label),
761
+ ),
762
+ ),
763
+ ),
764
+ h(
765
+ 'tbody',
766
+ null,
767
+ projects.map((project) =>
768
+ h(
769
+ 'tr',
770
+ { key: project.key, title: project.path || project.name },
771
+ h(
772
+ 'td',
773
+ {
774
+ style: {
775
+ ...cellBody,
776
+ color: C.text,
777
+ maxWidth: 220,
778
+ overflow: 'hidden',
779
+ textOverflow: 'ellipsis',
780
+ },
781
+ },
782
+ project.name,
783
+ ),
784
+ h('td', { style: { ...cellBody, textAlign: 'right' } }, project.calls),
785
+ h('td', { style: { ...cellBody, textAlign: 'right' } }, tokens(project.tokens, t)),
786
+ h('td', { style: { ...cellBody, textAlign: 'right' } }, yuan(project.cost)),
787
+ h('td', { style: { ...cellBody, textAlign: 'right', color: C.text3 } }, percent(project.share, 0)),
788
+ ),
789
+ ),
790
+ ),
791
+ ),
792
+ );
793
+ }
794
+
795
+ function ModelTable(props) {
796
+ const { models, t } = props;
797
+ const rows = (models || []).filter((model) => model.calls > 0);
798
+ if (!rows.length) {
799
+ return h('span', { style: { fontSize: 11.5, color: C.text3 } }, t('models.empty'));
800
+ }
801
+ const head = [t('price.model'), t('projects.calls'), t('projects.tokens'), t('projects.cost')];
802
+ return h(
803
+ 'table',
804
+ { style: { width: '100%', borderCollapse: 'collapse', fontSize: 11.5 } },
805
+ h(
806
+ 'thead',
807
+ null,
808
+ h(
809
+ 'tr',
810
+ null,
811
+ head.map((label, index) =>
812
+ h('th', { key: label, style: cellHead(index === 0 ? 'left' : 'right') }, label),
813
+ ),
814
+ ),
815
+ ),
816
+ h(
817
+ 'tbody',
818
+ null,
819
+ rows.map((model) =>
820
+ h(
821
+ 'tr',
822
+ { key: model.id },
823
+ h('td', { style: { ...cellBody, color: C.text } }, model.label),
824
+ h('td', { style: { ...cellBody, textAlign: 'right' } }, model.calls),
825
+ h('td', { style: { ...cellBody, textAlign: 'right' } }, tokens(model.tokens, t)),
826
+ h('td', { style: { ...cellBody, textAlign: 'right' } }, yuan(model.cost)),
827
+ ),
828
+ ),
829
+ ),
830
+ );
831
+ }
832
+
634
833
  /* -------------------------------- settings ------------------------------- */
635
834
 
636
835
  function Dashboard(props) {
@@ -640,6 +839,11 @@ window.__ModuleLoader__.load({
640
839
  const data = feed.data;
641
840
  const windowDays = (data && data.windowDays) || days;
642
841
  const peakNow = data ? data.now.peak : false;
842
+ const wallet = data && data.wallet ? data.wallet : null;
843
+ const walletLevel = wallet ? wallet.level : 'unknown';
844
+ const walletAlert = walletLevel === 'low' || walletLevel === 'warn';
845
+ const walletTone = walletLevel === 'low' ? C.error : walletLevel === 'warn' ? C.peak : C.text3;
846
+ const runwayLabel = walletAlert ? t('wallet.alert') : t('wallet.runway');
643
847
  const remain = data ? Math.max(0, data.now.nextAt - Date.now()) : 0;
644
848
  const switchText =
645
849
  data && remain > 30_000
@@ -702,13 +906,26 @@ window.__ModuleLoader__.load({
702
906
  ),
703
907
  h(
704
908
  Pill,
705
- null,
909
+ {
910
+ style: walletAlert ? { borderColor: walletTone, background: `${walletTone}1a` } : null,
911
+ title:
912
+ wallet && wallet.avgPerDay
913
+ ? `${t('wallet.avg')} ${yuan(wallet.avgPerDay)} · ${t('kpi.runwayHint')}`
914
+ : undefined,
915
+ },
706
916
  `${t('kpi.balance')} `,
707
917
  h(
708
918
  'span',
709
919
  { style: { color: C.text } },
710
920
  data.ledger && typeof data.ledger.balance === 'number' ? yuan(data.ledger.balance) : '—',
711
921
  ),
922
+ wallet && wallet.runwayDays !== null
923
+ ? h(
924
+ 'span',
925
+ { style: { color: walletTone, fontWeight: 600 } },
926
+ ` · ${runwayLabel} ${runway(wallet.runwayDays, t)}`,
927
+ )
928
+ : null,
712
929
  ),
713
930
  h(Pill, null, `${today.calls || 0} ${t('unit.calls')} · ${tokens(today.tokens, t)} tokens`),
714
931
  ),
@@ -740,6 +957,15 @@ window.__ModuleLoader__.load({
740
957
  h(
741
958
  'div',
742
959
  { key: 'kpi', style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 10 } },
960
+ h(Kpi, {
961
+ label: t('kpi.runway'),
962
+ value: wallet && wallet.runwayDays !== null ? runway(wallet.runwayDays, t) : '—',
963
+ tone: walletAlert ? walletTone : C.text,
964
+ hint:
965
+ wallet && wallet.balance !== null
966
+ ? `${t('kpi.balance')} ${yuan(wallet.balance)} · ${t('wallet.avg')} ${yuan(wallet.avgPerDay)}`
967
+ : t('kpi.runwayHint'),
968
+ }),
743
969
  h(Kpi, {
744
970
  label: t('kpi.calls'),
745
971
  value: today.calls || 0,
@@ -809,6 +1035,38 @@ window.__ModuleLoader__.load({
809
1035
  ),
810
1036
  );
811
1037
 
1038
+ body.push(
1039
+ h(
1040
+ 'div',
1041
+ { key: 'breakdown', style: { display: 'grid', gridTemplateColumns: 'minmax(0, 1.5fr) minmax(0, 1fr)', gap: 10 } },
1042
+ h(
1043
+ Card,
1044
+ null,
1045
+ h(CardTitle, {
1046
+ title: t('projects.title'),
1047
+ hint: t('projects.hint'),
1048
+ action: h(
1049
+ 'a',
1050
+ {
1051
+ href: `${EXPORT_URL}?days=${windowDays}&scope=projects`,
1052
+ download: '',
1053
+ title: t('export.projectsTitle'),
1054
+ style: { color: C.cache, textDecoration: 'none', fontWeight: 500 },
1055
+ },
1056
+ t('export.projects'),
1057
+ ),
1058
+ }),
1059
+ h(ProjectTable, { projects: data.projects, t }),
1060
+ ),
1061
+ h(
1062
+ Card,
1063
+ null,
1064
+ h(CardTitle, { title: t('models.title'), hint: t('models.hint') }),
1065
+ h(ModelTable, { models: data.models, t }),
1066
+ ),
1067
+ ),
1068
+ );
1069
+
812
1070
  body.push(
813
1071
  h(
814
1072
  Card,
@@ -886,6 +1144,24 @@ window.__ModuleLoader__.load({
886
1144
  },
887
1145
  t('page.refresh'),
888
1146
  ),
1147
+ h(
1148
+ 'a',
1149
+ {
1150
+ href: `${EXPORT_URL}?days=${windowDays}`,
1151
+ download: '',
1152
+ title: t('export.daysTitle'),
1153
+ style: {
1154
+ padding: '4px 12px',
1155
+ borderRadius: 8,
1156
+ border: `1px solid ${C.border}`,
1157
+ background: C.layer1,
1158
+ color: C.text,
1159
+ textDecoration: 'none',
1160
+ fontSize: 11.5,
1161
+ },
1162
+ },
1163
+ t('export.csv'),
1164
+ ),
889
1165
  ),
890
1166
  body,
891
1167
  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 notice
9
- * https://www.gov.cn/zhengce/zhengceku/202511/content_7047091.htm
10
- * Cross-checked against NateScarlet/holiday-cn (2026.json), which cites the
11
- * same notice.
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
- turns.push({
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
- parsed = parseSessionTurns(decodeSessionFile(file));
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.2.0",
3
+ "version": "1.3.1",
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",
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(2027, 1, 5, 12, 0);
80
- // 2027-10-01 is a Friday; without data the weekday rule marks it peak.
81
- assert.equal(isPeakAt(bj(2027, 10, 1, 10, 0)), true);
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: [2027] }]);
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
+ });