dsh-continue-cost 1.2.0 → 1.4.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # dsh-continue-cost · 对话轮数与续聊差价
2
2
 
3
- > DeepSeek Harness(DSH)插件:在输入框右侧显示**已完成的对话轮数**,或者——**继续这次对话比新开一次要多花多少钱**。
3
+ > DeepSeek Harness(DSH)插件:在输入框右侧显示**已完成的对话轮数**、**继续这次对话比新开一次要多花多少钱**,以及**这条对话到现在为止因为带着上下文一共多花了多少钱**。
4
4
 
5
5
  大多数费用插件回答的是“已经花了多少”。这个插件回答的是“**下一步该不该开新对话**”:续聊会把历史上下文再传一遍,这笔钱是可以省下来的,省多少取决于历史 token、缓存命中率和当前峰谷价。
6
6
 
@@ -10,13 +10,38 @@
10
10
  |---|---|---|
11
11
  | 口径 | 已经发生的花费 | 下一轮**继续 vs 新开**的差额 |
12
12
  | 用途 | 看账单 | 做决定(要不要开新对话) |
13
- | 展示 | 金额、明细、余额 | 一个胶囊 + 三色阈值(轮数或金额) |
13
+ | 展示 | 金额、明细、余额 | 一个胶囊 + 三色阈值(轮数、下一轮差额或累计多花) |
14
14
 
15
15
  差额是纯增量信息,和已有的费用统计插件共存不冲突。
16
16
 
17
- ## 两个数字到底是什么
17
+ ## 先统一口径:这两个数字是「下一轮」,不是「总共」
18
18
 
19
- 胶囊显示二选一,点开面板顶部可以切换。
19
+ 最常见的误解是把它读成“每轮都要多花这么多钱,所以很贵”。准确的说法是:
20
+
21
+ | 做法 | 历史消息 | 这笔钱付几次 |
22
+ |---|---|---|
23
+ | **继续当前对话** | 全部带上 | **每一轮都付一次**,历史越长越贵 |
24
+ | **新开对话(同一轮上下文)** | 不带 | 不用再付;新对话从“系统提示 + 工具 + 这一轮”的底价重新开始 |
25
+
26
+ 所以胶囊上的差额 = **续聊比新开,下一轮(以及之后每一轮)为历史多付的钱**:
27
+
28
+ ```text
29
+ 胶囊金额 ≈ 历史上下文 token × 平均 token 单价
30
+ ```
31
+
32
+ 它不是一次性的“切换成本”,而是**待在这条对话里的每轮门票**:只要还在这条对话里发消息,每轮都要再交一次。
33
+
34
+ 三点补充,免得把估算当账单:
35
+
36
+ 1. 面板里的两行是**同一轮对话**在两种做法下的**输入**费;回答本身的费用两边一样,因此既不计入,也不影响差额。
37
+ 2. 续聊的历史绝大多数命中缓存,命中价比未命中便宜一个数量级,再叠上谷时半价,真实差价常常只有几厘钱(示例:6 万 token、97% 命中、谷时 `deepseek-flash` ≈ ¥0.0014)。峰时或缓存命中率下降时会明显变大。
38
+ 3. 全部按“历史 token × 本会话平均单价”估算,实际以账户扣费为准。
39
+
40
+ 结论:把胶囊当成“留在这条对话里的每轮成本”。超过你觉得值的阈值(默认 ¥0.05 黄 / ¥0.15 红)就写个交接摘要、新开对话;没超过就继续聊,更省事。
41
+
42
+ ## 三个数字到底是什么
43
+
44
+ 胶囊三选一,点开面板顶部可以切换。
20
45
 
21
46
  **对话轮数**
22
47
 
@@ -26,6 +51,21 @@
26
51
 
27
52
  `≈ ¥0.0076` —— **继续当前对话**,比**新开一个对话**,下一轮请求要多花多少钱。
28
53
 
54
+ **累计多花**
55
+
56
+ `≈ ¥0.0545` —— 这条对话**从开始到现在**,因为每轮都带着历史上下文,一共比“每轮都新开一个对话”多花了多少钱。它是过去时,回答“这条对话已经贵到什么程度了”,而不是“下一轮要不要开新对话”。
57
+
58
+ ```text
59
+ 累计多花 ≈ 本会话实测输入 token − 每轮都新开所需的输入
60
+ 每轮都新开所需的输入 ≈ 轮数 × (系统提示 + 工具) + 当前历史
61
+ ```
62
+
63
+ 实测输入 token 取 `tokenUsage`(缓存命中 + 未命中 + 缓存写入,累计值),所以你不用相信启发式的历史占比,累计这一栏是拿真实用量算的。工具多步(一次提问里跑了好多轮工具)在两边同等处理,差额仍然归给上下文。
64
+
65
+ **按当时的价算,不取平均价。** 累计这一栏不会拿“当前这一刻的单价”去称整段会话:插件在本地持续采样用量,每段用量按采样时刻(至少每 30 秒一次,峰谷切换点立刻采样)当时的峰价或谷价分别计价,所以 11:58 花的和 12:02 花的各按各的价,跨时段的会话不会被摊成一个平均价。面板里「累计用量时段」一行会显示峰、谷各计入多少 token。
66
+
67
+ 累加全部发生在浏览器里:不新增网络请求,不上传任何对话内容,只读本机已有投影 + 本地价格表。刷新或重开页面后从当下重新累计,已有用量记入当时时段(所以刚刷新时峰/谷的拆分是近似的,金额随后续轮次继续精确累加)。
68
+
29
69
  ### 为什么会有差价
30
70
 
31
71
  每次对话,模型都要重新读一遍上下文:系统提示、工具 schema、以及之前所有对话消息。开新对话时系统提示和工具还在,**历史消息不再携带**;续聊则要为这些历史消息再付一次输入费(命中缓存的部分便宜很多)。
@@ -44,13 +84,32 @@
44
84
  悬停胶囊:
45
85
 
46
86
  - 已完成轮数、差额(继续 − 新开)
87
+ - 本会话累计三行:**已付输入费**、**若每轮都新开**、**累计因上下文多花**(附覆盖轮数与峰/谷用量分布)
47
88
  - 继续当前对话(下一轮上下文)费用、新开对话(同一轮上下文)费用
48
89
  - 历史上下文、下一轮上下文预计、本会话平均 token 单价、计价模型(含峰/谷标注)
90
+ - **当前时段:峰时 / 谷时 + 计算所用的北京时间**,下面一行写明官方峰谷规则
49
91
  - 价格表来源、节假日表来源(官方在线 / 本地缓存 / 内置)
50
92
 
51
- 点击胶囊固定面板:顶部切换「对话轮数 / 多花金额」,下方设置绿色上限、黄色上限;「恢复默认」回到 5 / 10 轮、¥0.05 / ¥0.15。阈值存在 `localStorage`。
93
+ 点击胶囊固定面板:顶部切换「对话轮数 / 多花金额 / 累计多花」,下方设置绿色上限、黄色上限;「恢复默认」回到 5 / 10 轮、¥0.05 / ¥0.15、¥0.5 / ¥2。三个口径各有自己的两档阈值,都存 `localStorage`,互不影响。
94
+
95
+ 圆点在数值前面,按当前显示值着色:不超过绿色上限为绿,不超过黄色上限为黄,超过为红。峰谷切换不再依赖“正好赶上一次轮询”:跨过 09:00 / 12:00 / 14:00 / 18:00 或零点时会立即重算,最多 30 秒兜底;窗口从睡眠、最小化或后台恢复时也会马上重算。
52
96
 
53
- 圆点在数值前面,按当前显示值着色:不超过绿色上限为绿,不超过黄色上限为黄,超过为红。每 30 秒重算一次,跨过峰谷边界会自动变色。
97
+ ## 峰谷自动切换
98
+
99
+ 官方口径(价格页原文):**北京时间周一至周五(不含中国法定节假日)09:00–12:00、14:00–18:00 为高峰时段,其余时段——包括 12:00–14:00 午间、周末和法定节假日全天——都是空闲时段**;空闲时段价格是高峰时段的一半。
100
+
101
+ 插件按这个规则自动切换:
102
+
103
+ | 时间(北京时间) | 时段 | 胶囊上的标记 |
104
+ |---|---|---|
105
+ | 周一至周五 09:00–12:00、14:00–18:00 | 峰时(价格 ×2) | 峰 |
106
+ | 周一至周五 12:00–14:00 | 谷时 | 谷 |
107
+ | 周末、调休上班周末、法定节假日全天 | 谷时 | 谷 |
108
+
109
+ - **胶囊上直接标「峰/谷」**,不用悬停也能看出当前按哪档计价。
110
+ - 面板「当前时段」一行同时给出北京时间(如 `峰时 · 北京时间 14:23`),方便核对是不是时钟/时区问题。
111
+ - 切换是精确到边界的:09:00、12:00、14:00、18:00 和零点都会重算;`focus` / `visibilitychange` / `pageshow` 也会触发一次,所以睡眠唤醒、最小化恢复后不会沿用旧价。
112
+ - 判断用的是「当前时刻换算成 UTC+8 后读时钟」,与浏览器/系统时区无关;系统时间本身错了才会算错。
54
113
 
55
114
  ## 估算口径
56
115
 
@@ -61,13 +120,20 @@
61
120
  继续费用 ≈ 下一轮上下文 token / 1,000,000 × 平均 token 单价
62
121
  新开费用 ≈ (下一轮上下文 token − 历史 token) / 1,000,000 × 平均 token 单价
63
122
  差额 ≈ 历史 token / 1,000,000 × 平均 token 单价
123
+
124
+ 累计多花 ≈ max(0, Σ峰(已付) − Σ峰(新开基准) + Σ谷(已付) − Σ谷(新开基准))
125
+ 已付(时段) = 该时段的命中 token × 命中价 + 未命中 token × 未命中价
126
+ 新开基准(时段) = (该时段新增轮数 × (系统提示 + 工具) + 当时历史) × 该时段平均单价
64
127
  ```
65
128
 
66
- - 平均 token 单价按本会话累计 `tokenUsage` 的缓存命中/未命中比例,套用当前时段官方单价。
129
+ - 每个时段用**自己的**价格行计价:峰时用量按峰价、谷时用量按谷价,不做跨时段平均。分桶发生在本地采样时刻(每 ≤30 秒一次 + 峰谷边界),因此一段跨过 12:00 的会话会被拆成两段计价。
130
+ - 平均 token 单价按对应时段桶里的缓存命中/未命中比例;新开基准也用同一时段的单价,保证两边可比。
131
+ - 累计多花用**实测**的累计输入 token 减基准,因此不依赖历史占比的启发式;但“每轮都新开”的基准仍按当前系统提示/工具与当时历史推算,轮数多了以后它只是一个近似。中途换模型时两边都按当前模型的价格表重算。
132
+ - 页面隐藏或机器休眠期间没有采样,恢复后那一段会按恢复时刻的时段计价;刷新或重开页面后从当下重新累计。
67
133
  - 回答本身在两种做法下费用相同,不计入差额;只比较输入侧。
68
- - 峰时:北京时间周一至周五(不含法定节假日)09:00–12:00、14:00–18:00;其余时段、周末、调休上班周末、法定节假日全天为谷时。
134
+ - 峰时:北京时间周一至周五(不含法定节假日)09:00–12:00、14:00–18:00;其余时段、周末、调休上班周末、法定节假日全天为谷时(见上一节)。
69
135
  - 下一轮上下文取 `contextPressure.projectedTokens`(缺失时退回 `pressureTokens`),历史消息占比取 `contextBreakdown`;两者都没有时显示「上下文数据还没准备好」,而不是硬猜。
70
- - 每 30 秒重算一次,跨过峰谷边界会自动更新。
136
+ - 跨过峰谷边界会在半秒内自动更新,另有 30 秒轮询兜底。
71
137
 
72
138
  ## 安装
73
139
 
@@ -75,13 +141,13 @@
75
141
 
76
142
  **1. 本地文件夹(推荐给朋友之间分享)**
77
143
 
78
- 1. 下载 `dsh-continue-cost-1.2.0.zip` 并解压,得到 `dsh-continue-cost` 文件夹,放到固定位置。
144
+ 1. 下载 `dsh-continue-cost-1.4.0.zip` 并解压,得到 `dsh-continue-cost` 文件夹,放到固定位置。
79
145
  2. DSH:**设置 → 插件 → 添加插件**,选择这个包含 `package.json` 的文件夹。
80
146
  3. **完全退出 DSH 再打开**(Host 端的价格/节假日路由要重启才挂载)。
81
147
 
82
148
  **2. npm(发布后可用)**
83
149
 
84
- 在 DSH 里用插件管理器安装:`plugin_manager` 的 `install_bundle`,target 填 `dsh-continue-cost@1.2.0`;如果这台 DSH 自带 `dsh` 命令,也可以 `dsh plugin add dsh-continue-cost`(profile 名按你的安装,桌面版一般是 `desktop`)。
150
+ 在 DSH 里用插件管理器安装:`plugin_manager` 的 `install_bundle`,target 填 `dsh-continue-cost@1.4.0`;如果这台 DSH 自带 `dsh` 命令,也可以 `dsh plugin add dsh-continue-cost`(profile 名按你的安装,桌面版一般是 `desktop`)。
85
151
 
86
152
  **3. GitHub Release**:从 Releases 下载 zip,按方式 1 安装。
87
153
 
@@ -109,21 +175,26 @@
109
175
  ## 限制
110
176
 
111
177
  - 历史 token 占比是按 `contextBreakdown` 缩放到 provider 锚定总量的启发式,不是精确分桶。
178
+ - 累计口径假设“每轮都新开”的系统提示与工具 schema 大小一直等于当前值;DSH 升级或工具增减会让基准偏移。
112
179
  - 平均单价按整个会话累计缓存比例,下一轮缓存状态变化会让实际值偏离。
180
+ - 累计的峰/谷拆分靠本地采样(≤30 秒一次):页面隐藏、机器休眠或长时间不刷新时,那一段会整体记到恢复时刻的时段;刷新后从当下重新累计,已有用量记入当时时段。
113
181
  - 中途切换模型时累计用量按当前模型价格折算。
114
182
  - 节假日解析依赖 gov.cn 通知的固定文本结构;结构变化时回退缓存/内置。
115
183
  - 已内置 2026 年表;2027 年表来自官方通知;更久远年份依赖自动发现。
184
+ - 峰谷按系统时钟换算成北京时间;系统时间本身错误时判断也会错,面板「当前时段」会显示所用的北京时间,便于核对。
116
185
 
117
186
  ## 开发
118
187
 
119
188
  - `client.js` 是浏览器端(module factory,无构建),`host-1.2.0.js` 是 Host 端。
120
189
  - DSH 会缓存 Host 模块:改 Host 时复制成新版本文件(如 `host-1.3.0.js`),改 `package.json` 的 `main`/`exports`/`files`,重启 DSH。
121
190
  - 改包名时要同步:`client.js` 的 `NAME`/`NS` 与两个路由常量、`host-1.2.0.js` 的 `BASE_PATH`、`cordis.patch.yml` 的 `id`/`name`。
122
- - 自检:`node --check client.js`、`node -e "import('./host-1.2.0.js')"`、重启后两个路由返回 `ok:true`。
191
+ - 自检:`npm test`(19 个用例:峰谷边界、周末/节假日、跨边界自动切换、唤醒重算、alias 解析、累计口径、峰谷分桶计价、Host 解析器)、`node --check client.js`、`node -e "import('./host-1.2.0.js')"`、重启后两个路由返回 `ok:true`。
123
192
 
124
193
  ## English
125
194
 
126
- **dsh-continue-cost** is a DeepSeek Harness plugin that shows the completed turn count and, more importantly, the extra context cost of **continuing this conversation instead of starting a fresh one** — priced from the official peak/off-peak CNY table and the session's cache-hit mix. Most cost plugins report money already spent; this one helps you decide whether to start over. Badge thresholds (green/yellow/red) apply to turns or to the delta.
195
+ **dsh-continue-cost** is a DeepSeek Harness plugin that shows the completed turn count, the extra context cost of **continuing this conversation instead of starting a fresh one**, and — since 1.4.0 — the **cumulative amount this session has already overpaid for carrying its history**, measured from real cumulative input tokens minus the "every turn started fresh" baseline. Most cost plugins report money already spent; this one helps you decide whether to start over. Badge thresholds (green/yellow/red) apply to turns, to the next-turn delta, or to the session total.
196
+
197
+ The chip carries a small **peak / off** badge that flips by itself at the official boundaries (09:00 / 12:00 / 14:00 / 18:00 Beijing on weekdays, and midnight for weekends and statutory holidays), and refreshes immediately when the window is restored after sleep or minimisation. The panel spells out the tariff in force together with the Beijing time it was derived from. The session total is accumulated locally: each sample is priced at the peak or off-peak rate in force at that moment (at least every 30 s, plus every boundary), never at one session-wide average, and the panel shows how many tokens landed in each tariff.
127
198
 
128
199
  Install: unzip into a folder and add it from **Settings → Plugins → Add plugin**, then fully restart DSH.
129
200
 
package/client.js CHANGED
@@ -235,6 +235,8 @@
235
235
  turnsYellow: 10,
236
236
  costGreen: 0.05,
237
237
  costYellow: 0.15,
238
+ totalGreen: 0.5,
239
+ totalYellow: 2,
238
240
  }
239
241
 
240
242
  const ZH = {
@@ -246,6 +248,12 @@
246
248
  'panel.title': '续聊差价估算',
247
249
  'panel.turns': '已完成轮数',
248
250
  'panel.extra': '差额(继续 − 新开)',
251
+ 'panel.totalPaid': '本会话已付输入费',
252
+ 'panel.totalFresh': '若每轮都新开(同一轮内容)',
253
+ 'panel.total': '累计因上下文多花',
254
+ 'panel.totalSpan': '覆盖轮数',
255
+ 'panel.totalSplit': '累计用量时段',
256
+ 'panel.totalNote': '累计 = 本会话实测输入 token − 每轮都新开所需的输入(系统提示 + 工具 × 轮数 + 一次历史)。用量按采样时刻(至少每 30 秒一次,峰谷切换点也会立刻采样)当时的峰价或谷价计入,不做全程平均;窗口隐藏或休眠的那一段会在恢复时按当时的时段计入。累加全在本机完成;刷新或重开页面后从当前时刻重新累计,已有用量记入当时时段。实际以账户扣费为准。',
249
257
  'panel.continue': '继续当前对话(下一轮上下文)',
250
258
  'panel.fresh': '新开对话(同一轮上下文)',
251
259
  'panel.history': '历史上下文',
@@ -264,6 +272,9 @@
264
272
  'panel.holidayCache': '本地缓存',
265
273
  'panel.holidayBuiltin': '内置',
266
274
  'panel.perMillion': '/ 百万 tokens',
275
+ 'panel.tariff': '当前时段',
276
+ 'panel.tariffRule': '工作日北京时间 9:00–12:00、14:00–18:00 为峰时;午间、周末与法定节假日全天为谷时。跨过边界后这里与胶囊上的「峰/谷」会自动切换。',
277
+ 'panel.beijingTime': '北京时间',
267
278
  'panel.noPrice': '未收录该模型价格',
268
279
  'panel.noContext': '上下文数据还没准备好,暂时无法估算历史占比。',
269
280
  'panel.waiting': '还没有可用的 token 用量,先按未命中缓存的单价估算。',
@@ -278,9 +289,12 @@
278
289
  'tone.idle': '等待数据',
279
290
  'tariff.peak': '峰时',
280
291
  'tariff.off': '谷时',
292
+ 'tariff.peakShort': '峰',
293
+ 'tariff.offShort': '谷',
281
294
  'settings.title': '阈值设置',
282
295
  'settings.turns': '对话轮数',
283
296
  'settings.cost': '多花金额',
297
+ 'settings.total': '累计多花',
284
298
  'settings.green': '绿色上限',
285
299
  'settings.yellow': '黄色上限',
286
300
  'settings.unitTurns': '轮',
@@ -300,6 +314,12 @@
300
314
  'panel.title': 'Carry-over delta estimate',
301
315
  'panel.turns': 'Completed turns',
302
316
  'panel.extra': 'Delta (continue − fresh)',
317
+ 'panel.totalPaid': 'Input paid this session',
318
+ 'panel.totalFresh': 'If every turn started fresh',
319
+ 'panel.total': 'Extra paid for carry-over',
320
+ 'panel.totalSpan': 'Turns covered',
321
+ 'panel.totalSplit': 'Usage by tariff',
322
+ 'panel.totalNote': 'Total = measured session input tokens − what starting every turn fresh would need (system prompt + tools × turns + one history). Usage is stamped with the peak or off-peak rate in force at each sample (at least every 30 s, and right at each tariff boundary) rather than one session-wide average; a stretch spent while the window was hidden or the machine slept is stamped when it resumes. The accumulation is local: reloading restarts it from that moment, attributing the existing usage to the tariff then. Actual billing may differ.',
303
323
  'panel.continue': 'Continue this chat (next-turn context)',
304
324
  'panel.fresh': 'Fresh chat (same-turn context)',
305
325
  'panel.history': 'History context',
@@ -318,6 +338,9 @@
318
338
  'panel.holidayCache': 'Local cache',
319
339
  'panel.holidayBuiltin': 'Built-in',
320
340
  'panel.perMillion': '/ 1M tokens',
341
+ 'panel.tariff': 'Current tariff',
342
+ 'panel.tariffRule': 'Peak is 09:00–12:00 and 14:00–18:00 Beijing weekdays; the midday break, weekends and public holidays are off-peak. The chip badge and this row follow the clock automatically.',
343
+ 'panel.beijingTime': 'Beijing',
321
344
  'panel.noPrice': 'No listed price for this model',
322
345
  'panel.noContext': 'Context data is not ready yet; the history share is unknown for now.',
323
346
  'panel.waiting': 'No token usage yet; pricing the history at the cache-miss rate.',
@@ -332,9 +355,12 @@
332
355
  'tone.idle': 'waiting for data',
333
356
  'tariff.peak': 'peak',
334
357
  'tariff.off': 'off-peak',
358
+ 'tariff.peakShort': 'peak',
359
+ 'tariff.offShort': 'off',
335
360
  'settings.title': 'Thresholds',
336
361
  'settings.turns': 'Turns',
337
362
  'settings.cost': 'Extra cost',
363
+ 'settings.total': 'Session total',
338
364
  'settings.green': 'Green up to',
339
365
  'settings.yellow': 'Yellow up to',
340
366
  'settings.unitTurns': 'turns',
@@ -359,7 +385,8 @@
359
385
  */
360
386
  function normalizeSettings(raw) {
361
387
  const source = raw !== null && typeof raw === 'object' ? raw : {}
362
- const metric = source.metric === 'cost' ? 'cost' : 'turns'
388
+ const metric =
389
+ source.metric === 'cost' || source.metric === 'total' ? source.metric : 'turns'
363
390
  const turnsGreen = Math.round(nonNegative(source.turnsGreen, DEFAULT_SETTINGS.turnsGreen))
364
391
  const turnsYellow = Math.max(
365
392
  turnsGreen,
@@ -367,7 +394,9 @@
367
394
  )
368
395
  const costGreen = nonNegative(source.costGreen, DEFAULT_SETTINGS.costGreen)
369
396
  const costYellow = Math.max(costGreen, nonNegative(source.costYellow, DEFAULT_SETTINGS.costYellow))
370
- return { metric, turnsGreen, turnsYellow, costGreen, costYellow }
397
+ const totalGreen = nonNegative(source.totalGreen, DEFAULT_SETTINGS.totalGreen)
398
+ const totalYellow = Math.max(totalGreen, nonNegative(source.totalYellow, DEFAULT_SETTINGS.totalYellow))
399
+ return { metric, turnsGreen, turnsYellow, costGreen, costYellow, totalGreen, totalYellow }
371
400
  }
372
401
 
373
402
  /** @returns settings remembered by this browser, or the defaults. */
@@ -405,6 +434,8 @@
405
434
  const fullKey = raw.toLowerCase()
406
435
  const id = PRICING[bareKey] === undefined ? fullKey : bareKey
407
436
  const alias = PRICING_ALIASES[id]
437
+ ?? PRICING_ALIASES[bareKey]
438
+ ?? PRICING_ALIASES[fullKey]
408
439
  return PRICING[id] ?? (alias === undefined ? undefined : PRICING[alias])
409
440
  }
410
441
 
@@ -416,6 +447,53 @@
416
447
  return slash === -1 ? raw : raw.slice(slash + 1)
417
448
  }
418
449
 
450
+ /**
451
+ * Peak windows as Beijing wall-clock `[start, end)` hour pairs, straight from
452
+ * the official pricing page: "北京时间周一至周五(不含中国法定节假日)
453
+ * 9:00 - 12:00、14:00 - 18:00 为高峰时段". Everything else — including the
454
+ * 12:00-14:00 midday break, weekends and statutory holidays — is off-peak.
455
+ */
456
+ const PEAK_WINDOWS = [
457
+ [9, 12],
458
+ [14, 18],
459
+ ]
460
+
461
+ /** Hours at which the tariff can change: window edges plus midnight. */
462
+ const TARIFF_BOUNDARY_HOURS = [0, ...PEAK_WINDOWS.flat()]
463
+
464
+ /** How far ahead the boundary search looks (a weekend plus a holiday run). */
465
+ const BOUNDARY_LOOKAHEAD_DAYS = 12
466
+
467
+ /**
468
+ * Read an instant as Beijing wall-clock fields. Shifting the epoch by eight
469
+ * hours and reading the UTC fields makes the answer independent of the
470
+ * browser's own time zone.
471
+ * @param now - instant to read.
472
+ * @returns `{ day, hour, minute, timeKey, dateKey }` in Beijing time.
473
+ */
474
+ function beijingClock(now = new Date()) {
475
+ const shifted = new Date(now.getTime() + 8 * 60 * 60 * 1000)
476
+ const hour = shifted.getUTCHours()
477
+ const minute = shifted.getUTCMinutes()
478
+ return {
479
+ day: shifted.getUTCDay(),
480
+ hour,
481
+ minute,
482
+ dateKey: shifted.toISOString().slice(0, 10),
483
+ timeKey: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`,
484
+ }
485
+ }
486
+
487
+ /**
488
+ * @param clock - Beijing wall-clock fields from {@link beijingClock}.
489
+ * @returns true when the provider charges the peak tariff then.
490
+ */
491
+ function isPeakAtClock(clock) {
492
+ if (clock.day === 0 || clock.day === 6) return false
493
+ if (isChineseHoliday(clock.dateKey)) return false
494
+ return PEAK_WINDOWS.some(([start, end]) => clock.hour >= start && clock.hour < end)
495
+ }
496
+
419
497
  /**
420
498
  * Which provider tariff is in force now: peak 09:00-12:00 and 14:00-18:00
421
499
  * Beijing time on weekdays, off-peak on weekends, make-up working weekends,
@@ -426,18 +504,42 @@
426
504
  */
427
505
  function isPeakTariff(now = new Date()) {
428
506
  try {
429
- const beijing = new Date(now.getTime() + 8 * 60 * 60 * 1000)
430
- const day = beijing.getUTCDay()
431
- if (day === 0 || day === 6) return false
432
- const dateKey = beijing.toISOString().slice(0, 10)
433
- if (isChineseHoliday(dateKey)) return false
434
- const hour = beijing.getUTCHours()
435
- return (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18)
507
+ return isPeakAtClock(beijingClock(now))
436
508
  } catch {
437
509
  return true
438
510
  }
439
511
  }
440
512
 
513
+ /**
514
+ * Milliseconds until the tariff next changes, so the chip can switch exactly
515
+ * at 09:00 / 12:00 / 14:00 / 18:00 and at midnight (weekend or holiday
516
+ * starts) instead of waiting for the next poll. Returns the poll interval
517
+ * when the search fails.
518
+ * @param now - instant to measure from.
519
+ * @returns a positive delay in milliseconds.
520
+ */
521
+ function msUntilNextTariffChange(now = new Date()) {
522
+ try {
523
+ const base = now.getTime()
524
+ const shifted = new Date(base + 8 * 60 * 60 * 1000)
525
+ const year = shifted.getUTCFullYear()
526
+ const month = shifted.getUTCMonth()
527
+ const date = shifted.getUTCDate()
528
+ let next = Number.POSITIVE_INFINITY
529
+ for (let offset = 0; offset <= BOUNDARY_LOOKAHEAD_DAYS; offset += 1) {
530
+ const day = new Date(Date.UTC(year, month, date + offset))
531
+ for (const hour of TARIFF_BOUNDARY_HOURS) {
532
+ const at = Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate(), hour)
533
+ - 8 * 60 * 60 * 1000
534
+ if (at > base + 1_000 && at < next) next = at
535
+ }
536
+ }
537
+ return Number.isFinite(next) ? next - base : 30_000
538
+ } catch {
539
+ return 30_000
540
+ }
541
+ }
542
+
441
543
  /**
442
544
  * Estimate the next turn's input side and the extra part caused by carrying
443
545
  * the current history into it.
@@ -455,41 +557,72 @@
455
557
  * @param params - live projections and the current tariff.
456
558
  * @returns the estimate and the figures behind it.
457
559
  */
458
- function estimateNextTurn(params) {
459
- const { usage, breakdown, pressure, selection, peak } = params
460
- const tariffs = pricingOf(selection)
461
- const tariff = tariffs === undefined ? undefined : tariffs[peak ? 'peak' : 'off']
462
- const systemTokens = countOf(breakdown?.systemTokens)
463
- const toolsTokens = countOf(breakdown?.toolsTokens)
464
- const baseTokens = systemTokens + toolsTokens
465
- const hit = countOf(usage?.cacheReadTokens)
466
- const miss = countOf(usage?.uncachedInputTokens) + countOf(usage?.cacheWriteTokens)
467
- const inputTokens = hit + miss
560
+ /**
561
+ * Split the next request into its fixed part (system prompt + tool schemas)
562
+ * and the message history carried into it.
563
+ *
564
+ * `projectedTokens`/`pressureTokens` are provider-anchored while the
565
+ * composition is heuristic. When both exist, scale the message share to the
566
+ * anchored total so a systematic CJK/JSON undercount does not shrink the
567
+ * history.
568
+ *
569
+ * @param breakdown - `contextBreakdown` projection, if any.
570
+ * @param pressure - `contextPressure` projection, if any.
571
+ * @returns the fixed part, the history and the whole next request.
572
+ */
573
+ function historyTokensOf(breakdown, pressure) {
574
+ const baseTokens = countOf(breakdown?.systemTokens) + countOf(breakdown?.toolsTokens)
468
575
  const projected = countOf(pressure?.projectedTokens)
469
576
  const lastPressure = countOf(pressure?.pressureTokens)
470
577
  const anchor = projected > 0 ? projected : lastPressure
471
578
  const heuristicHistory = countOf(breakdown?.messageTokens)
472
579
  const heuristicTotal = baseTokens + heuristicHistory
473
580
  const inferredHistory = anchor > baseTokens ? anchor - baseTokens : 0
474
- const hasContext = anchor > 0 || breakdown !== undefined
475
- // `projectedTokens`/`pressureTokens` are provider-anchored while the
476
- // composition is heuristic. When both exist, scale the message share to
477
- // the anchored total so a systematic CJK/JSON undercount does not shrink
478
- // the history.
479
581
  const historyTokens =
480
582
  anchor > 0 && heuristicHistory > 0 && heuristicTotal > 0
481
583
  ? anchor * (heuristicHistory / heuristicTotal)
482
584
  : heuristicHistory > 0
483
585
  ? heuristicHistory
484
586
  : inferredHistory
485
- const promptTokens = anchor > 0 ? anchor : historyTokens + baseTokens
587
+ const hasContext = anchor > 0 || breakdown !== undefined
588
+ return {
589
+ baseTokens,
590
+ historyTokens,
591
+ promptTokens: anchor > 0 ? anchor : historyTokens + baseTokens,
592
+ hasContext,
593
+ }
594
+ }
486
595
 
596
+ /**
597
+ * Session-average input rate: the observed cache-hit/cache-miss mix at the
598
+ * current tariff, falling back to the cache-miss rate before any usage.
599
+ *
600
+ * @param usage - `tokenUsage` projection, if any.
601
+ * @param tariff - resolved price row, or undefined for an unknown model.
602
+ * @returns the rate per token, the measured input tokens and the split.
603
+ */
604
+ function rateOf(usage, tariff) {
605
+ const hit = countOf(usage?.cacheReadTokens)
606
+ const miss = countOf(usage?.uncachedInputTokens) + countOf(usage?.cacheWriteTokens)
607
+ const inputTokens = hit + miss
487
608
  const ratePerMillion =
488
609
  tariff === undefined
489
610
  ? undefined
490
611
  : inputTokens > 0
491
612
  ? (hit * tariff.cacheHit + miss * tariff.cacheMiss) / inputTokens
492
613
  : tariff.cacheMiss
614
+ return { ratePerMillion, inputTokens, hit, miss }
615
+ }
616
+
617
+ function estimateNextTurn(params) {
618
+ const { usage, breakdown, pressure, selection, peak } = params
619
+ const tariffs = pricingOf(selection)
620
+ const tariff = tariffs === undefined ? undefined : tariffs[peak ? 'peak' : 'off']
621
+ const { baseTokens, historyTokens, promptTokens, hasContext } = historyTokensOf(
622
+ breakdown,
623
+ pressure,
624
+ )
625
+ const { ratePerMillion, inputTokens } = rateOf(usage, tariff)
493
626
 
494
627
  const priced = tariff !== undefined && ratePerMillion !== undefined
495
628
  const extraCny = priced && hasContext ? (historyTokens / 1e6) * ratePerMillion : undefined
@@ -513,15 +646,151 @@
513
646
  }
514
647
  }
515
648
 
649
+ /**
650
+ * One empty per-tariff bucket. The session ledger keeps two of these (peak and
651
+ * off-peak) so each measured token is priced at the tariff that was in force
652
+ * when it was spent, instead of one rate for the whole session.
653
+ * @returns a zeroed ledger.
654
+ */
655
+ function createLedger() {
656
+ return {
657
+ peak: { hit: 0, miss: 0, fresh: 0, turns: 0 },
658
+ off: { hit: 0, miss: 0, fresh: 0, turns: 0 },
659
+ seen: { hit: 0, miss: 0, turns: 0 },
660
+ }
661
+ }
662
+
663
+ /**
664
+ * @param ledger - a ledger to copy. @returns a detached copy.
665
+ */
666
+ function cloneLedger(ledger) {
667
+ const copy = createLedger()
668
+ for (const name of ['peak', 'off']) {
669
+ copy[name].hit = ledger[name].hit
670
+ copy[name].miss = ledger[name].miss
671
+ copy[name].fresh = ledger[name].fresh
672
+ copy[name].turns = ledger[name].turns
673
+ }
674
+ copy.seen.hit = ledger.seen.hit
675
+ copy.seen.miss = ledger.seen.miss
676
+ copy.seen.turns = ledger.seen.turns
677
+ return copy
678
+ }
679
+
680
+ /**
681
+ * Fold one observation into the session ledger, attributing everything spent
682
+ * since the previous observation to the tariff in force right now.
683
+ *
684
+ * The projections only expose cumulative usage and no per-turn timestamps, so
685
+ * this module samples them and stamps each delta with the clock it reads.
686
+ * Sampling happens on every re-render and at each tariff boundary, so a delta
687
+ * spanning a boundary is split at the boundary instead of being priced at one
688
+ * flat rate. The fresh-chat baseline is accumulated the same way: the turns
689
+ * completed since the last sample plus the history that was carried at that
690
+ * moment, so both sides of the comparison use the same time's prices.
691
+ *
692
+ * A shrinking cumulative counter means a different conversation took over
693
+ * this view, so the ledger restarts from that observation.
694
+ *
695
+ * @param state - the previous ledger, or undefined on the first observation.
696
+ * @param sample - cumulative usage, completed turns, the fixed baseline, the
697
+ * carried history and the tariff in force.
698
+ * @returns the next ledger (a new object).
699
+ */
700
+ function ledgerStep(state, sample) {
701
+ const { hit, miss, turns, baseTokens, historyTokens, peak } = sample
702
+ const previous = state === undefined || state === null ? undefined : state
703
+ const shrank = previous !== undefined
704
+ && (hit + miss < previous.seen.hit + previous.seen.miss || turns < previous.seen.turns)
705
+ const next = previous === undefined || shrank ? createLedger() : cloneLedger(previous)
706
+ const from = previous === undefined || shrank ? createLedger().seen : previous.seen
707
+ const deltaHit = Math.max(0, hit - from.hit)
708
+ const deltaMiss = Math.max(0, miss - from.miss)
709
+ const deltaTurns = Math.max(0, turns - from.turns)
710
+ const bucket = next[peak ? 'peak' : 'off']
711
+ bucket.hit += deltaHit
712
+ bucket.miss += deltaMiss
713
+ bucket.turns += deltaTurns
714
+ if (deltaTurns > 0) bucket.fresh += deltaTurns * baseTokens + historyTokens
715
+ next.seen = { hit, miss, turns }
716
+ return next
717
+ }
718
+
719
+ /**
720
+ * Price both halves of the ledger with each bucket's own tariff.
721
+ *
722
+ * The baseline is valued at its bucket's observed cache-hit mix, so a token
723
+ * spent in peak hours is compared against a fresh-chat token in peak hours.
724
+ *
725
+ * @param ledger - the accumulated session ledger.
726
+ * @param tariffs - the priced model's `{ off, peak }` rows, or undefined.
727
+ * @returns the paid / fresh / extra figures and the per-tariff split.
728
+ */
729
+ function ledgerTotals(ledger, tariffs) {
730
+ if (ledger === undefined || ledger === null || tariffs === undefined) return undefined
731
+ const totals = {
732
+ paidCny: 0,
733
+ freshCny: 0,
734
+ paidTokens: 0,
735
+ freshTokens: 0,
736
+ peakTokens: 0,
737
+ offTokens: 0,
738
+ completed: 0,
739
+ peakTurns: 0,
740
+ offTurns: 0,
741
+ }
742
+ for (const name of ['peak', 'off']) {
743
+ const bucket = ledger[name]
744
+ const price = tariffs[name]
745
+ const tokens = bucket.hit + bucket.miss
746
+ const ratePerMillion = tokens > 0
747
+ ? (bucket.hit * price.cacheHit + bucket.miss * price.cacheMiss) / tokens
748
+ : price.cacheMiss
749
+ const paid = (bucket.hit * price.cacheHit + bucket.miss * price.cacheMiss) / 1e6
750
+ const fresh = (bucket.fresh / 1e6) * ratePerMillion
751
+ totals.paidCny += paid
752
+ totals.freshCny += fresh
753
+ totals.paidTokens += tokens
754
+ totals.freshTokens += bucket.fresh
755
+ totals.completed += bucket.turns
756
+ if (name === 'peak') {
757
+ totals.peakTokens = tokens
758
+ totals.peakTurns = bucket.turns
759
+ } else {
760
+ totals.offTokens = tokens
761
+ totals.offTurns = bucket.turns
762
+ }
763
+ }
764
+ const measured = totals.paidTokens > 0
765
+ const extraCny = Math.max(0, totals.paidCny - totals.freshCny)
766
+ const extraTokens = Math.max(0, totals.paidTokens - totals.freshTokens)
767
+ return {
768
+ priced: true,
769
+ measured,
770
+ completed: totals.completed,
771
+ peakTokens: totals.peakTokens,
772
+ offTokens: totals.offTokens,
773
+ peakTurns: totals.peakTurns,
774
+ offTurns: totals.offTurns,
775
+ paidTokens: measured ? totals.paidTokens : undefined,
776
+ freshTokens: measured ? totals.freshTokens : undefined,
777
+ extraTokens: measured ? extraTokens : undefined,
778
+ paidCny: measured ? totals.paidCny : undefined,
779
+ freshCny: measured ? totals.freshCny : undefined,
780
+ extraCny: measured ? extraCny : undefined,
781
+ }
782
+ }
783
+
516
784
  /**
517
785
  * Pick the dot tone from the configured metric and thresholds.
518
786
  * @param settings - normalized settings.
519
787
  * @param turns - completed turns.
520
- * @param estimate - the current estimate.
788
+ * @param estimate - the current next-turn estimate.
521
789
  * @param loaded - whether the turn projection has arrived.
790
+ * @param session - the cumulative session estimate.
522
791
  * @returns `green`, `yellow`, `red`, or `idle`.
523
792
  */
524
- function toneOf(settings, turns, estimate, loaded) {
793
+ function toneOf(settings, turns, estimate, loaded, session) {
525
794
  let value
526
795
  let green
527
796
  let yellow
@@ -530,6 +799,11 @@
530
799
  value = estimate.extraCny
531
800
  green = settings.costGreen
532
801
  yellow = settings.costYellow
802
+ } else if (settings.metric === 'total') {
803
+ if (session === undefined || !session.priced || session.extraCny === undefined) return 'idle'
804
+ value = session.extraCny
805
+ green = settings.totalGreen
806
+ yellow = settings.totalYellow
533
807
  } else {
534
808
  if (!loaded) return 'idle'
535
809
  value = turns
@@ -690,7 +964,7 @@
690
964
  display: inline-flex;
691
965
  align-items: stretch;
692
966
  height: 28px;
693
- max-width: 180px;
967
+ max-width: 200px;
694
968
  padding: 0;
695
969
  border: 1px solid var(--dsw-alias-border-l1);
696
970
  border-radius: var(--dsw-radius-sm);
@@ -732,6 +1006,18 @@
732
1006
  .dshTurnCost_chip[data-tone="yellow"] .dshTurnCost_dot { background: var(--dsw-alias-state-warn-primary); }
733
1007
  .dshTurnCost_chip[data-tone="red"] .dshTurnCost_dot { background: var(--dsw-alias-state-error-primary); }
734
1008
  .dshTurnCost_amount { font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
1009
+ .dshTurnCost_tariff {
1010
+ flex: none;
1011
+ align-self: center;
1012
+ padding: 1px 3px;
1013
+ border-radius: 3px;
1014
+ background: var(--dsw-alias-bg-layer-2);
1015
+ color: var(--dsw-alias-label-secondary);
1016
+ font-size: 10px;
1017
+ line-height: 12px;
1018
+ letter-spacing: .02em;
1019
+ }
1020
+ .dshTurnCost_tariff[data-tariff="peak"] { color: var(--dsw-alias-label-primary); }
735
1021
  .dshTurnCost_panel {
736
1022
  position: absolute;
737
1023
  bottom: calc(100% + 8px);
@@ -918,18 +1204,19 @@
918
1204
  }
919
1205
  }
920
1206
 
921
- /** @param amount - non-negative CNY. @returns a cost value with a stable four decimals. */
1207
+ /** @param amount - non-negative CNY. @returns a cost value with four decimals (five below ¥0.0001). */
922
1208
  function formatCost(amount) {
923
1209
  if (typeof amount !== 'number' || !Number.isFinite(amount)) return '—'
1210
+ const digits = amount > 0 && amount < 0.0001 ? 5 : 4
924
1211
  try {
925
1212
  return new Intl.NumberFormat(undefined, {
926
1213
  style: 'currency',
927
1214
  currency: 'CNY',
928
- minimumFractionDigits: 4,
929
- maximumFractionDigits: 4,
1215
+ minimumFractionDigits: digits,
1216
+ maximumFractionDigits: digits,
930
1217
  }).format(amount)
931
1218
  } catch {
932
- return `¥${amount.toFixed(4)}`
1219
+ return `¥${amount.toFixed(digits)}`
933
1220
  }
934
1221
  }
935
1222
 
@@ -950,7 +1237,7 @@
950
1237
 
951
1238
  /** @param value - threshold number. @returns a plain editable string. */
952
1239
  function formatInput(value, metric) {
953
- return metric === 'cost' ? String(value) : String(Math.round(value))
1240
+ return metric === 'turns' ? String(Math.round(value)) : String(value)
954
1241
  }
955
1242
 
956
1243
  /** The bundle's stylesheet as one React element, removed with the surface. */
@@ -1007,7 +1294,7 @@
1007
1294
  className: 'dshTurnCost_input',
1008
1295
  type: 'number',
1009
1296
  min: '0',
1010
- step: metric === 'cost' ? '0.01' : '1',
1297
+ step: metric === 'turns' ? '1' : '0.01',
1011
1298
  inputMode: 'decimal',
1012
1299
  value: draft,
1013
1300
  onChange: (event) => {
@@ -1055,10 +1342,12 @@
1055
1342
  */
1056
1343
  function Panel({
1057
1344
  estimate,
1345
+ session,
1058
1346
  turnsLabel,
1059
1347
  settings,
1060
1348
  priceSource,
1061
1349
  holidaySource,
1350
+ tariffTime,
1062
1351
  t,
1063
1352
  pinned,
1064
1353
  onUnpin,
@@ -1068,23 +1357,37 @@
1068
1357
  onMouseEnter,
1069
1358
  onMouseLeave,
1070
1359
  }) {
1071
- const metricLabel = settings.metric === 'cost' ? t('settings.cost') : t('settings.turns')
1072
- const green = settings.metric === 'cost' ? settings.costGreen : settings.turnsGreen
1073
- const yellow = settings.metric === 'cost' ? settings.costYellow : settings.turnsYellow
1074
- const greenText =
1360
+ const moneyMetric = settings.metric !== 'turns'
1361
+ const metricLabel =
1075
1362
  settings.metric === 'cost'
1076
- ? formatCny(green)
1077
- : `${Math.round(green)} ${t('settings.unitTurns')}`
1078
- const yellowText =
1363
+ ? t('settings.cost')
1364
+ : settings.metric === 'total'
1365
+ ? t('settings.total')
1366
+ : t('settings.turns')
1367
+ const green =
1079
1368
  settings.metric === 'cost'
1080
- ? formatCny(yellow)
1081
- : `${Math.round(yellow)} ${t('settings.unitTurns')}`
1369
+ ? settings.costGreen
1370
+ : settings.metric === 'total'
1371
+ ? settings.totalGreen
1372
+ : settings.turnsGreen
1373
+ const yellow =
1374
+ settings.metric === 'cost'
1375
+ ? settings.costYellow
1376
+ : settings.metric === 'total'
1377
+ ? settings.totalYellow
1378
+ : settings.turnsYellow
1379
+ const greenText = moneyMetric ? formatCny(green) : `${Math.round(green)} ${t('settings.unitTurns')}`
1380
+ const yellowText = moneyMetric ? formatCny(yellow) : `${Math.round(yellow)} ${t('settings.unitTurns')}`
1082
1381
  const current =
1083
1382
  settings.metric === 'cost'
1084
1383
  ? estimate.priced && estimate.extraCny !== undefined
1085
1384
  ? `≈ ${formatCost(estimate.extraCny)}`
1086
1385
  : '—'
1087
- : turnsLabel
1386
+ : settings.metric === 'total'
1387
+ ? session !== undefined && session.extraCny !== undefined
1388
+ ? `≈ ${formatCost(session.extraCny)}`
1389
+ : '—'
1390
+ : turnsLabel
1088
1391
  const tariff = estimate.peak ? t('tariff.peak') : t('tariff.off')
1089
1392
  const modelText =
1090
1393
  estimate.model === undefined
@@ -1104,6 +1407,48 @@
1104
1407
  : '—',
1105
1408
  emphasis: true,
1106
1409
  }),
1410
+ h('div', { key: 'sessionDivider', className: 'dshTurnCost_divider' }),
1411
+ h(Line, {
1412
+ key: 'totalPaid',
1413
+ label: t('panel.totalPaid'),
1414
+ value:
1415
+ session !== undefined && session.paidCny !== undefined
1416
+ ? `≈ ${formatCost(session.paidCny)}`
1417
+ : '—',
1418
+ }),
1419
+ h(Line, {
1420
+ key: 'totalFresh',
1421
+ label: t('panel.totalFresh'),
1422
+ value:
1423
+ session !== undefined && session.freshCny !== undefined
1424
+ ? `≈ ${formatCost(session.freshCny)}`
1425
+ : '—',
1426
+ }),
1427
+ h(Line, {
1428
+ key: 'total',
1429
+ label: t('panel.total'),
1430
+ value:
1431
+ session !== undefined && session.extraCny !== undefined
1432
+ ? `≈ ${formatCost(session.extraCny)}`
1433
+ : '—',
1434
+ emphasis: true,
1435
+ }),
1436
+ session !== undefined && session.measured
1437
+ ? h(Line, {
1438
+ key: 'totalSplit',
1439
+ label: t('panel.totalSplit'),
1440
+ value: `${t('tariff.peakShort')} ${formatTokens(session.peakTokens)} · ${t(
1441
+ 'tariff.offShort',
1442
+ )} ${formatTokens(session.offTokens)} ${t('panel.tokens')}`,
1443
+ })
1444
+ : null,
1445
+ session !== undefined && session.measured
1446
+ ? h(
1447
+ 'div',
1448
+ { key: 'totalSpan', className: 'dshTurnCost_note' },
1449
+ `${t('panel.totalSpan')}: ${session.completed}`,
1450
+ )
1451
+ : null,
1107
1452
  h('div', { key: 'split', className: 'dshTurnCost_divider' }),
1108
1453
  h(Line, {
1109
1454
  key: 'continue',
@@ -1132,6 +1477,12 @@
1132
1477
  value: estimate.rate === undefined ? '—' : `${formatRate(estimate.rate)} ${t('panel.perMillion')}`,
1133
1478
  }),
1134
1479
  h(Line, { key: 'model', label: t('panel.model'), value: modelText }),
1480
+ h(Line, {
1481
+ key: 'tariff',
1482
+ label: t('panel.tariff'),
1483
+ value: `${tariff} · ${t('panel.beijingTime')} ${tariffTime}`,
1484
+ }),
1485
+ h('div', { key: 'tariffRule', className: 'dshTurnCost_note' }, t('panel.tariffRule')),
1135
1486
  h(Line, {
1136
1487
  key: 'priceSource',
1137
1488
  label: t('panel.priceTable'),
@@ -1182,6 +1533,16 @@
1182
1533
  },
1183
1534
  t('settings.cost'),
1184
1535
  ),
1536
+ h(
1537
+ MetricButton,
1538
+ {
1539
+ active: settings.metric === 'total',
1540
+ onClick: () => {
1541
+ onMetric('total')
1542
+ },
1543
+ },
1544
+ t('settings.total'),
1545
+ ),
1185
1546
  ),
1186
1547
  )
1187
1548
  : null
@@ -1195,7 +1556,7 @@
1195
1556
  key: `green-${settings.metric}`,
1196
1557
  label: t('settings.green'),
1197
1558
  value: green,
1198
- unit: settings.metric === 'cost' ? t('settings.unitCost') : t('settings.unitTurns'),
1559
+ unit: settings.metric === 'turns' ? t('settings.unitTurns') : t('settings.unitCost'),
1199
1560
  metric: settings.metric,
1200
1561
  onCommit: (value) => {
1201
1562
  onThreshold('green', value)
@@ -1205,7 +1566,7 @@
1205
1566
  key: `yellow-${settings.metric}`,
1206
1567
  label: t('settings.yellow'),
1207
1568
  value: yellow,
1208
- unit: settings.metric === 'cost' ? t('settings.unitCost') : t('settings.unitTurns'),
1569
+ unit: settings.metric === 'turns' ? t('settings.unitTurns') : t('settings.unitCost'),
1209
1570
  metric: settings.metric,
1210
1571
  onCommit: (value) => {
1211
1572
  onThreshold('yellow', value)
@@ -1253,6 +1614,7 @@
1253
1614
  ),
1254
1615
  displaySwitch,
1255
1616
  ...rows,
1617
+ h('div', { className: 'dshTurnCost_note' }, t('panel.totalNote')),
1256
1618
  estimate.hasContext
1257
1619
  ? !estimate.priced && estimate.model !== undefined
1258
1620
  ? h('div', { className: 'dshTurnCost_note dshTurnCost_alert' }, t('panel.noPrice'))
@@ -1365,16 +1727,88 @@
1365
1727
 
1366
1728
  const rawTurns = stats?.turns
1367
1729
  const turns = typeof rawTurns === 'number' && Number.isFinite(rawTurns) && rawTurns >= 0 ? Math.floor(rawTurns) : 0
1368
- const peak = isPeakTariff()
1730
+ const now = new Date()
1731
+ const peak = isPeakTariff(now)
1732
+ let tariffTime = ''
1733
+ try {
1734
+ tariffTime = beijingClock(now).timeKey
1735
+ } catch {
1736
+ tariffTime = ''
1737
+ }
1369
1738
  const estimate = estimateNextTurn({ usage, breakdown, pressure, selection, peak })
1370
- const tone = toneOf(settings, turns, estimate, stats !== undefined)
1739
+ /**
1740
+ * The session ledger lives in a ref, one per conversation view, so two
1741
+ * chats open side by side never share a running total. Every re-render
1742
+ * (and every tariff-boundary wake-up) folds the usage measured since the
1743
+ * last sample into the bucket of the clock reading at that moment, which
1744
+ * is what keeps peak tokens at peak prices and off-peak tokens at
1745
+ * off-peak prices instead of one session-wide average.
1746
+ */
1747
+ const ledgerRef = useRef(undefined)
1748
+ const [session, setSession] = useState(undefined)
1749
+ const sampleHit = countOf(usage?.cacheReadTokens)
1750
+ const sampleMiss = countOf(usage?.uncachedInputTokens) + countOf(usage?.cacheWriteTokens)
1751
+ const sampleContext = historyTokensOf(breakdown, pressure)
1752
+ const modelKey = `${selection?.next?.model ?? ''}|${selection?.lastUsed?.model ?? ''}`
1753
+ useEffect(() => {
1754
+ const next = ledgerStep(ledgerRef.current, {
1755
+ hit: sampleHit,
1756
+ miss: sampleMiss,
1757
+ turns,
1758
+ baseTokens: sampleContext.baseTokens,
1759
+ historyTokens: sampleContext.historyTokens,
1760
+ peak,
1761
+ })
1762
+ ledgerRef.current = next
1763
+ setSession(ledgerTotals(next, pricingOf(selection)))
1764
+ }, [
1765
+ sampleHit,
1766
+ sampleMiss,
1767
+ turns,
1768
+ peak,
1769
+ sampleContext.baseTokens,
1770
+ sampleContext.historyTokens,
1771
+ modelKey,
1772
+ ])
1773
+ const tone = toneOf(settings, turns, estimate, stats !== undefined, session)
1371
1774
  const open = hovered || pinned || focusWithin
1775
+ /**
1776
+ * Keep the displayed tariff honest without polling blindly: wake up at
1777
+ * the exact next change (window edge or midnight, so weekends and
1778
+ * holidays flip too), fall back to a 30 s poll, and recompute as soon
1779
+ * as the window is visible again after sleep, minimise or a background
1780
+ * tab — the case where a stale "谷价" used to survive into peak hours.
1781
+ */
1372
1782
  useEffect(() => {
1373
- const timer = window.setInterval(() => {
1783
+ let timer = 0
1784
+ let disposed = false
1785
+ const schedule = () => {
1786
+ if (disposed) return
1787
+ if (timer !== 0) window.clearTimeout(timer)
1788
+ const delay = Math.min(30_000, Math.max(500, msUntilNextTariffChange() + 400))
1789
+ timer = window.setTimeout(() => {
1790
+ if (disposed) return
1791
+ setClock((value) => value + 1)
1792
+ schedule()
1793
+ }, delay)
1794
+ }
1795
+ const refreshNow = () => {
1374
1796
  setClock((value) => value + 1)
1375
- }, 30_000)
1797
+ schedule()
1798
+ }
1799
+ const onVisibility = () => {
1800
+ if (document.visibilityState === 'visible') refreshNow()
1801
+ }
1802
+ document.addEventListener('visibilitychange', onVisibility)
1803
+ window.addEventListener('focus', refreshNow)
1804
+ window.addEventListener('pageshow', refreshNow)
1805
+ schedule()
1376
1806
  return () => {
1377
- window.clearInterval(timer)
1807
+ disposed = true
1808
+ if (timer !== 0) window.clearTimeout(timer)
1809
+ document.removeEventListener('visibilitychange', onVisibility)
1810
+ window.removeEventListener('focus', refreshNow)
1811
+ window.removeEventListener('pageshow', refreshNow)
1378
1812
  }
1379
1813
  }, [])
1380
1814
  const turnsLabel = stats === undefined ? t('chip.turnsLoading') : `${turns} ${t('chip.unit')}`
@@ -1382,7 +1816,16 @@
1382
1816
  estimate.hasContext && estimate.priced && estimate.extraCny !== undefined
1383
1817
  ? `≈ ${formatCost(estimate.extraCny)}`
1384
1818
  : t('chip.costUnknown')
1385
- const valueLabel = settings.metric === 'cost' ? costLabel : turnsLabel
1819
+ const totalLabel =
1820
+ session !== undefined && session.priced && session.extraCny !== undefined
1821
+ ? `≈ ${formatCost(session.extraCny)}`
1822
+ : t('chip.costUnknown')
1823
+ const valueLabel =
1824
+ settings.metric === 'cost'
1825
+ ? costLabel
1826
+ : settings.metric === 'total'
1827
+ ? totalLabel
1828
+ : turnsLabel
1386
1829
  const toneText =
1387
1830
  tone === 'green'
1388
1831
  ? t('tone.green')
@@ -1391,8 +1834,15 @@
1391
1834
  : tone === 'red'
1392
1835
  ? t('tone.red')
1393
1836
  : t('tone.idle')
1394
- const basisLabel = settings.metric === 'cost' ? t('settings.cost') : t('settings.turns')
1395
- const summary = `${t('chip.title')} · ${valueLabel} · ${t('panel.colorBy')}: ${basisLabel} (${toneText}) · ${t('chip.pinHint')}`
1837
+ const basisLabel =
1838
+ settings.metric === 'cost'
1839
+ ? t('settings.cost')
1840
+ : settings.metric === 'total'
1841
+ ? t('settings.total')
1842
+ : t('settings.turns')
1843
+ const tariffLabel = peak ? t('tariff.peak') : t('tariff.off')
1844
+ const tariffBadge = peak ? t('tariff.peakShort') : t('tariff.offShort')
1845
+ const summary = `${t('chip.title')} · ${valueLabel} · ${tariffLabel} · ${t('panel.colorBy')}: ${basisLabel} (${toneText}) · ${t('chip.pinHint')}`
1396
1846
 
1397
1847
  const updateMetric = (metric) => {
1398
1848
  publishSettings({ ...settings, metric })
@@ -1411,6 +1861,19 @@
1411
1861
  costYellow: Math.max(settings.costGreen, value),
1412
1862
  })
1413
1863
  }
1864
+ } else if (settings.metric === 'total') {
1865
+ if (field === 'green') {
1866
+ publishSettings({
1867
+ ...settings,
1868
+ totalGreen: value,
1869
+ totalYellow: Math.max(settings.totalYellow, value),
1870
+ })
1871
+ } else {
1872
+ publishSettings({
1873
+ ...settings,
1874
+ totalYellow: Math.max(settings.totalGreen, value),
1875
+ })
1876
+ }
1414
1877
  } else if (field === 'green') {
1415
1878
  publishSettings({
1416
1879
  ...settings,
@@ -1480,16 +1943,27 @@
1480
1943
  },
1481
1944
  h('span', { className: 'dshTurnCost_dot', 'aria-hidden': true }),
1482
1945
  h('span', { className: 'dshTurnCost_amount' }, valueLabel),
1946
+ h(
1947
+ 'span',
1948
+ {
1949
+ className: 'dshTurnCost_tariff',
1950
+ 'data-tariff': peak ? 'peak' : 'off',
1951
+ 'aria-hidden': true,
1952
+ },
1953
+ tariffBadge,
1954
+ ),
1483
1955
  ),
1484
1956
  ),
1485
1957
  open
1486
1958
  ? h(Panel, {
1487
1959
  key: 'panel',
1488
1960
  estimate,
1961
+ session,
1489
1962
  turnsLabel,
1490
1963
  settings,
1491
1964
  priceSource: priceInfo.source,
1492
1965
  holidaySource: holidayInfo.source,
1966
+ tariffTime,
1493
1967
  t,
1494
1968
  pinned,
1495
1969
  onUnpin: dismiss,
@@ -1511,6 +1985,28 @@
1511
1985
  ctx.effect(() => ctx.locale.register(NS, 'en', EN), 'dsh-continue-cost: en dictionary')
1512
1986
  const t = ctx.locale.bind(NS)
1513
1987
 
1988
+ /* Thresholds are shared through localStorage, so a second window or tab
1989
+ * picks up a change without a reload. Echo suppression comes from
1990
+ * comparing the normalized value before writing again. */
1991
+ ctx.effect(() => {
1992
+ const onStorage = (event) => {
1993
+ if (event.key !== STORAGE_KEY) return
1994
+ let parsed
1995
+ try {
1996
+ parsed = event.newValue === null ? undefined : JSON.parse(event.newValue)
1997
+ } catch {
1998
+ return
1999
+ }
2000
+ const next = normalizeSettings(parsed)
2001
+ if (JSON.stringify(next) === JSON.stringify(getSettings())) return
2002
+ publishSettings(next)
2003
+ }
2004
+ window.addEventListener('storage', onStorage)
2005
+ return () => {
2006
+ window.removeEventListener('storage', onStorage)
2007
+ }
2008
+ }, 'dsh-continue-cost: threshold sync')
2009
+
1514
2010
  ctx.effect(() => {
1515
2011
  void refreshPrices()
1516
2012
  void refreshHolidays()
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Turn count & carry-over delta",
4
- "description": "Shows the completed turn count at the right of the composer, or switches to the extra cost of continuing this conversation instead of starting a fresh one. Hover for the estimate; click the chip to pin the panel, switch the display, and set green, yellow, and red thresholds for turns or cost. Price and Chinese holiday tables update daily from public DeepSeek and gov.cn pages, falling back to a local cache or built-in table; no conversation content is sent and no API key is read."
4
+ "description": "Shows the completed turn count at the right of the composer, or switches to the extra cost of continuing this conversation instead of starting a fresh one, or to the cumulative amount this session has overpaid for carrying its history. A small badge on the chip names the tariff in force and flips automatically across the official peak boundaries (09:00–12:00 and 14:00–18:00 Beijing time on workdays); the cumulative total is summed locally, each sample at the peak or off-peak rate in force at that moment, never at one session-wide average. Hover for the estimate; click the chip to pin the panel, switch the display, and set green, yellow, and red thresholds for turns or cost. Price and Chinese holiday tables update daily from public DeepSeek and gov.cn pages, falling back to a local cache or built-in table; no conversation content is sent and no API key is read."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "对话轮数与续聊差价",
4
- "description": "在输入框右侧显示已完成的对话轮数,也可切换为显示继续当前对话比新开对话多花的金额;悬停查看估算明细,点击胶囊固定面板后切换显示并设置轮数或金额的绿、黄、红阈值。价格表和法定节假日表每天从 DeepSeek 与中国政府网的公开页面自动更新,失败时使用本地缓存或内置表;不发送会话内容,不读取 API Key。"
4
+ "description": "在输入框右侧显示已完成的对话轮数,也可切换为显示继续当前对话比新开对话多花的金额,或这条对话已经因上下文累计多花多少钱;胶囊上直接标出当前是峰时还是谷时,跨过官方峰谷边界(工作日北京时间 9:00–12:00、14:00–18:00 为峰时)会自动切换。累计金额在本机按采样时刻当时的峰/谷价分别累加,不做全程平均。悬停查看估算明细,点击胶囊固定面板后切换显示并设置轮数或金额的绿、黄、红阈值。价格表和法定节假日表每天从 DeepSeek 与中国政府网的公开页面自动更新,失败时使用本地缓存或内置表;不发送会话内容,不读取 API Key。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "dsh-continue-cost",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
- "description": "DSH 插件:显示对话轮数与续聊差价 —— 继续当前对话比新开一次多花多少钱。Turn count and the extra context cost of continuing this chat instead of starting fresh.",
6
+ "description": "DSH 插件:显示对话轮数、续聊差价与累计多花 —— 续聊比新开多花多少钱、这条对话为止因上下文一共多花了多少,按官方峰谷时段自动切换。Turn count, next-turn carry-over delta and the cumulative overpay of this session, switching between peak and off-peak tariffs automatically.",
7
7
  "author": {
8
8
  "name": "0345-0433",
9
9
  "url": "https://github.com/0345-0433"
@@ -30,6 +30,9 @@
30
30
  "type": "module",
31
31
  "icon": "./icon.svg",
32
32
  "main": "./host-1.2.0.js",
33
+ "scripts": {
34
+ "test": "node test/client.test.mjs"
35
+ },
33
36
  "exports": {
34
37
  ".": "./host-1.2.0.js",
35
38
  "./host": "./host-1.2.0.js",