dsh-continue-cost 1.3.1 → 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,7 +10,7 @@
10
10
  |---|---|---|
11
11
  | 口径 | 已经发生的花费 | 下一轮**继续 vs 新开**的差额 |
12
12
  | 用途 | 看账单 | 做决定(要不要开新对话) |
13
- | 展示 | 金额、明细、余额 | 一个胶囊 + 三色阈值(轮数或金额) |
13
+ | 展示 | 金额、明细、余额 | 一个胶囊 + 三色阈值(轮数、下一轮差额或累计多花) |
14
14
 
15
15
  差额是纯增量信息,和已有的费用统计插件共存不冲突。
16
16
 
@@ -39,9 +39,9 @@
39
39
 
40
40
  结论:把胶囊当成“留在这条对话里的每轮成本”。超过你觉得值的阈值(默认 ¥0.05 黄 / ¥0.15 红)就写个交接摘要、新开对话;没超过就继续聊,更省事。
41
41
 
42
- ## 两个数字到底是什么
42
+ ## 三个数字到底是什么
43
43
 
44
- 胶囊显示二选一,点开面板顶部可以切换。
44
+ 胶囊三选一,点开面板顶部可以切换。
45
45
 
46
46
  **对话轮数**
47
47
 
@@ -51,6 +51,21 @@
51
51
 
52
52
  `≈ ¥0.0076` —— **继续当前对话**,比**新开一个对话**,下一轮请求要多花多少钱。
53
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
+
54
69
  ### 为什么会有差价
55
70
 
56
71
  每次对话,模型都要重新读一遍上下文:系统提示、工具 schema、以及之前所有对话消息。开新对话时系统提示和工具还在,**历史消息不再携带**;续聊则要为这些历史消息再付一次输入费(命中缓存的部分便宜很多)。
@@ -69,12 +84,13 @@
69
84
  悬停胶囊:
70
85
 
71
86
  - 已完成轮数、差额(继续 − 新开)
87
+ - 本会话累计三行:**已付输入费**、**若每轮都新开**、**累计因上下文多花**(附覆盖轮数与峰/谷用量分布)
72
88
  - 继续当前对话(下一轮上下文)费用、新开对话(同一轮上下文)费用
73
89
  - 历史上下文、下一轮上下文预计、本会话平均 token 单价、计价模型(含峰/谷标注)
74
90
  - **当前时段:峰时 / 谷时 + 计算所用的北京时间**,下面一行写明官方峰谷规则
75
91
  - 价格表来源、节假日表来源(官方在线 / 本地缓存 / 内置)
76
92
 
77
- 点击胶囊固定面板:顶部切换「对话轮数 / 多花金额」,下方设置绿色上限、黄色上限;「恢复默认」回到 5 / 10 轮、¥0.05 / ¥0.15。阈值存在 `localStorage`。
93
+ 点击胶囊固定面板:顶部切换「对话轮数 / 多花金额 / 累计多花」,下方设置绿色上限、黄色上限;「恢复默认」回到 5 / 10 轮、¥0.05 / ¥0.15、¥0.5 / ¥2。三个口径各有自己的两档阈值,都存 `localStorage`,互不影响。
78
94
 
79
95
  圆点在数值前面,按当前显示值着色:不超过绿色上限为绿,不超过黄色上限为黄,超过为红。峰谷切换不再依赖“正好赶上一次轮询”:跨过 09:00 / 12:00 / 14:00 / 18:00 或零点时会立即重算,最多 30 秒兜底;窗口从睡眠、最小化或后台恢复时也会马上重算。
80
96
 
@@ -104,9 +120,16 @@
104
120
  继续费用 ≈ 下一轮上下文 token / 1,000,000 × 平均 token 单价
105
121
  新开费用 ≈ (下一轮上下文 token − 历史 token) / 1,000,000 × 平均 token 单价
106
122
  差额 ≈ 历史 token / 1,000,000 × 平均 token 单价
123
+
124
+ 累计多花 ≈ max(0, Σ峰(已付) − Σ峰(新开基准) + Σ谷(已付) − Σ谷(新开基准))
125
+ 已付(时段) = 该时段的命中 token × 命中价 + 未命中 token × 未命中价
126
+ 新开基准(时段) = (该时段新增轮数 × (系统提示 + 工具) + 当时历史) × 该时段平均单价
107
127
  ```
108
128
 
109
- - 平均 token 单价按本会话累计 `tokenUsage` 的缓存命中/未命中比例,套用当前时段官方单价。
129
+ - 每个时段用**自己的**价格行计价:峰时用量按峰价、谷时用量按谷价,不做跨时段平均。分桶发生在本地采样时刻(每 ≤30 秒一次 + 峰谷边界),因此一段跨过 12:00 的会话会被拆成两段计价。
130
+ - 平均 token 单价按对应时段桶里的缓存命中/未命中比例;新开基准也用同一时段的单价,保证两边可比。
131
+ - 累计多花用**实测**的累计输入 token 减基准,因此不依赖历史占比的启发式;但“每轮都新开”的基准仍按当前系统提示/工具与当时历史推算,轮数多了以后它只是一个近似。中途换模型时两边都按当前模型的价格表重算。
132
+ - 页面隐藏或机器休眠期间没有采样,恢复后那一段会按恢复时刻的时段计价;刷新或重开页面后从当下重新累计。
110
133
  - 回答本身在两种做法下费用相同,不计入差额;只比较输入侧。
111
134
  - 峰时:北京时间周一至周五(不含法定节假日)09:00–12:00、14:00–18:00;其余时段、周末、调休上班周末、法定节假日全天为谷时(见上一节)。
112
135
  - 下一轮上下文取 `contextPressure.projectedTokens`(缺失时退回 `pressureTokens`),历史消息占比取 `contextBreakdown`;两者都没有时显示「上下文数据还没准备好」,而不是硬猜。
@@ -118,13 +141,13 @@
118
141
 
119
142
  **1. 本地文件夹(推荐给朋友之间分享)**
120
143
 
121
- 1. 下载 `dsh-continue-cost-1.3.1.zip` 并解压,得到 `dsh-continue-cost` 文件夹,放到固定位置。
144
+ 1. 下载 `dsh-continue-cost-1.4.0.zip` 并解压,得到 `dsh-continue-cost` 文件夹,放到固定位置。
122
145
  2. DSH:**设置 → 插件 → 添加插件**,选择这个包含 `package.json` 的文件夹。
123
146
  3. **完全退出 DSH 再打开**(Host 端的价格/节假日路由要重启才挂载)。
124
147
 
125
148
  **2. npm(发布后可用)**
126
149
 
127
- 在 DSH 里用插件管理器安装:`plugin_manager` 的 `install_bundle`,target 填 `dsh-continue-cost@1.3.1`;如果这台 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`)。
128
151
 
129
152
  **3. GitHub Release**:从 Releases 下载 zip,按方式 1 安装。
130
153
 
@@ -152,7 +175,9 @@
152
175
  ## 限制
153
176
 
154
177
  - 历史 token 占比是按 `contextBreakdown` 缩放到 provider 锚定总量的启发式,不是精确分桶。
178
+ - 累计口径假设“每轮都新开”的系统提示与工具 schema 大小一直等于当前值;DSH 升级或工具增减会让基准偏移。
155
179
  - 平均单价按整个会话累计缓存比例,下一轮缓存状态变化会让实际值偏离。
180
+ - 累计的峰/谷拆分靠本地采样(≤30 秒一次):页面隐藏、机器休眠或长时间不刷新时,那一段会整体记到恢复时刻的时段;刷新后从当下重新累计,已有用量记入当时时段。
156
181
  - 中途切换模型时累计用量按当前模型价格折算。
157
182
  - 节假日解析依赖 gov.cn 通知的固定文本结构;结构变化时回退缓存/内置。
158
183
  - 已内置 2026 年表;2027 年表来自官方通知;更久远年份依赖自动发现。
@@ -163,13 +188,13 @@
163
188
  - `client.js` 是浏览器端(module factory,无构建),`host-1.2.0.js` 是 Host 端。
164
189
  - DSH 会缓存 Host 模块:改 Host 时复制成新版本文件(如 `host-1.3.0.js`),改 `package.json` 的 `main`/`exports`/`files`,重启 DSH。
165
190
  - 改包名时要同步:`client.js` 的 `NAME`/`NS` 与两个路由常量、`host-1.2.0.js` 的 `BASE_PATH`、`cordis.patch.yml` 的 `id`/`name`。
166
- - 自检:`npm test`(12 个用例:峰谷边界、周末/节假日、跨边界自动切换、唤醒重算、alias 解析、Host 解析器)、`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`。
167
192
 
168
193
  ## English
169
194
 
170
- **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.
171
196
 
172
- 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.
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.
173
198
 
174
199
  Install: unzip into a folder and add it from **Settings → Plugins → Add plugin**, then fully restart DSH.
175
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': '历史上下文',
@@ -286,6 +294,7 @@
286
294
  'settings.title': '阈值设置',
287
295
  'settings.turns': '对话轮数',
288
296
  'settings.cost': '多花金额',
297
+ 'settings.total': '累计多花',
289
298
  'settings.green': '绿色上限',
290
299
  'settings.yellow': '黄色上限',
291
300
  'settings.unitTurns': '轮',
@@ -305,6 +314,12 @@
305
314
  'panel.title': 'Carry-over delta estimate',
306
315
  'panel.turns': 'Completed turns',
307
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.',
308
323
  'panel.continue': 'Continue this chat (next-turn context)',
309
324
  'panel.fresh': 'Fresh chat (same-turn context)',
310
325
  'panel.history': 'History context',
@@ -345,6 +360,7 @@
345
360
  'settings.title': 'Thresholds',
346
361
  'settings.turns': 'Turns',
347
362
  'settings.cost': 'Extra cost',
363
+ 'settings.total': 'Session total',
348
364
  'settings.green': 'Green up to',
349
365
  'settings.yellow': 'Yellow up to',
350
366
  'settings.unitTurns': 'turns',
@@ -369,7 +385,8 @@
369
385
  */
370
386
  function normalizeSettings(raw) {
371
387
  const source = raw !== null && typeof raw === 'object' ? raw : {}
372
- const metric = source.metric === 'cost' ? 'cost' : 'turns'
388
+ const metric =
389
+ source.metric === 'cost' || source.metric === 'total' ? source.metric : 'turns'
373
390
  const turnsGreen = Math.round(nonNegative(source.turnsGreen, DEFAULT_SETTINGS.turnsGreen))
374
391
  const turnsYellow = Math.max(
375
392
  turnsGreen,
@@ -377,7 +394,9 @@
377
394
  )
378
395
  const costGreen = nonNegative(source.costGreen, DEFAULT_SETTINGS.costGreen)
379
396
  const costYellow = Math.max(costGreen, nonNegative(source.costYellow, DEFAULT_SETTINGS.costYellow))
380
- 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 }
381
400
  }
382
401
 
383
402
  /** @returns settings remembered by this browser, or the defaults. */
@@ -538,41 +557,72 @@
538
557
  * @param params - live projections and the current tariff.
539
558
  * @returns the estimate and the figures behind it.
540
559
  */
541
- function estimateNextTurn(params) {
542
- const { usage, breakdown, pressure, selection, peak } = params
543
- const tariffs = pricingOf(selection)
544
- const tariff = tariffs === undefined ? undefined : tariffs[peak ? 'peak' : 'off']
545
- const systemTokens = countOf(breakdown?.systemTokens)
546
- const toolsTokens = countOf(breakdown?.toolsTokens)
547
- const baseTokens = systemTokens + toolsTokens
548
- const hit = countOf(usage?.cacheReadTokens)
549
- const miss = countOf(usage?.uncachedInputTokens) + countOf(usage?.cacheWriteTokens)
550
- 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)
551
575
  const projected = countOf(pressure?.projectedTokens)
552
576
  const lastPressure = countOf(pressure?.pressureTokens)
553
577
  const anchor = projected > 0 ? projected : lastPressure
554
578
  const heuristicHistory = countOf(breakdown?.messageTokens)
555
579
  const heuristicTotal = baseTokens + heuristicHistory
556
580
  const inferredHistory = anchor > baseTokens ? anchor - baseTokens : 0
557
- const hasContext = anchor > 0 || breakdown !== undefined
558
- // `projectedTokens`/`pressureTokens` are provider-anchored while the
559
- // composition is heuristic. When both exist, scale the message share to
560
- // the anchored total so a systematic CJK/JSON undercount does not shrink
561
- // the history.
562
581
  const historyTokens =
563
582
  anchor > 0 && heuristicHistory > 0 && heuristicTotal > 0
564
583
  ? anchor * (heuristicHistory / heuristicTotal)
565
584
  : heuristicHistory > 0
566
585
  ? heuristicHistory
567
586
  : inferredHistory
568
- 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
+ }
569
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
570
608
  const ratePerMillion =
571
609
  tariff === undefined
572
610
  ? undefined
573
611
  : inputTokens > 0
574
612
  ? (hit * tariff.cacheHit + miss * tariff.cacheMiss) / inputTokens
575
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)
576
626
 
577
627
  const priced = tariff !== undefined && ratePerMillion !== undefined
578
628
  const extraCny = priced && hasContext ? (historyTokens / 1e6) * ratePerMillion : undefined
@@ -596,15 +646,151 @@
596
646
  }
597
647
  }
598
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
+
599
784
  /**
600
785
  * Pick the dot tone from the configured metric and thresholds.
601
786
  * @param settings - normalized settings.
602
787
  * @param turns - completed turns.
603
- * @param estimate - the current estimate.
788
+ * @param estimate - the current next-turn estimate.
604
789
  * @param loaded - whether the turn projection has arrived.
790
+ * @param session - the cumulative session estimate.
605
791
  * @returns `green`, `yellow`, `red`, or `idle`.
606
792
  */
607
- function toneOf(settings, turns, estimate, loaded) {
793
+ function toneOf(settings, turns, estimate, loaded, session) {
608
794
  let value
609
795
  let green
610
796
  let yellow
@@ -613,6 +799,11 @@
613
799
  value = estimate.extraCny
614
800
  green = settings.costGreen
615
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
616
807
  } else {
617
808
  if (!loaded) return 'idle'
618
809
  value = turns
@@ -1046,7 +1237,7 @@
1046
1237
 
1047
1238
  /** @param value - threshold number. @returns a plain editable string. */
1048
1239
  function formatInput(value, metric) {
1049
- return metric === 'cost' ? String(value) : String(Math.round(value))
1240
+ return metric === 'turns' ? String(Math.round(value)) : String(value)
1050
1241
  }
1051
1242
 
1052
1243
  /** The bundle's stylesheet as one React element, removed with the surface. */
@@ -1103,7 +1294,7 @@
1103
1294
  className: 'dshTurnCost_input',
1104
1295
  type: 'number',
1105
1296
  min: '0',
1106
- step: metric === 'cost' ? '0.01' : '1',
1297
+ step: metric === 'turns' ? '1' : '0.01',
1107
1298
  inputMode: 'decimal',
1108
1299
  value: draft,
1109
1300
  onChange: (event) => {
@@ -1151,6 +1342,7 @@
1151
1342
  */
1152
1343
  function Panel({
1153
1344
  estimate,
1345
+ session,
1154
1346
  turnsLabel,
1155
1347
  settings,
1156
1348
  priceSource,
@@ -1165,23 +1357,37 @@
1165
1357
  onMouseEnter,
1166
1358
  onMouseLeave,
1167
1359
  }) {
1168
- const metricLabel = settings.metric === 'cost' ? t('settings.cost') : t('settings.turns')
1169
- const green = settings.metric === 'cost' ? settings.costGreen : settings.turnsGreen
1170
- const yellow = settings.metric === 'cost' ? settings.costYellow : settings.turnsYellow
1171
- const greenText =
1360
+ const moneyMetric = settings.metric !== 'turns'
1361
+ const metricLabel =
1172
1362
  settings.metric === 'cost'
1173
- ? formatCny(green)
1174
- : `${Math.round(green)} ${t('settings.unitTurns')}`
1175
- const yellowText =
1363
+ ? t('settings.cost')
1364
+ : settings.metric === 'total'
1365
+ ? t('settings.total')
1366
+ : t('settings.turns')
1367
+ const green =
1176
1368
  settings.metric === 'cost'
1177
- ? formatCny(yellow)
1178
- : `${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')}`
1179
1381
  const current =
1180
1382
  settings.metric === 'cost'
1181
1383
  ? estimate.priced && estimate.extraCny !== undefined
1182
1384
  ? `≈ ${formatCost(estimate.extraCny)}`
1183
1385
  : '—'
1184
- : turnsLabel
1386
+ : settings.metric === 'total'
1387
+ ? session !== undefined && session.extraCny !== undefined
1388
+ ? `≈ ${formatCost(session.extraCny)}`
1389
+ : '—'
1390
+ : turnsLabel
1185
1391
  const tariff = estimate.peak ? t('tariff.peak') : t('tariff.off')
1186
1392
  const modelText =
1187
1393
  estimate.model === undefined
@@ -1201,6 +1407,48 @@
1201
1407
  : '—',
1202
1408
  emphasis: true,
1203
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,
1204
1452
  h('div', { key: 'split', className: 'dshTurnCost_divider' }),
1205
1453
  h(Line, {
1206
1454
  key: 'continue',
@@ -1285,6 +1533,16 @@
1285
1533
  },
1286
1534
  t('settings.cost'),
1287
1535
  ),
1536
+ h(
1537
+ MetricButton,
1538
+ {
1539
+ active: settings.metric === 'total',
1540
+ onClick: () => {
1541
+ onMetric('total')
1542
+ },
1543
+ },
1544
+ t('settings.total'),
1545
+ ),
1288
1546
  ),
1289
1547
  )
1290
1548
  : null
@@ -1298,7 +1556,7 @@
1298
1556
  key: `green-${settings.metric}`,
1299
1557
  label: t('settings.green'),
1300
1558
  value: green,
1301
- unit: settings.metric === 'cost' ? t('settings.unitCost') : t('settings.unitTurns'),
1559
+ unit: settings.metric === 'turns' ? t('settings.unitTurns') : t('settings.unitCost'),
1302
1560
  metric: settings.metric,
1303
1561
  onCommit: (value) => {
1304
1562
  onThreshold('green', value)
@@ -1308,7 +1566,7 @@
1308
1566
  key: `yellow-${settings.metric}`,
1309
1567
  label: t('settings.yellow'),
1310
1568
  value: yellow,
1311
- unit: settings.metric === 'cost' ? t('settings.unitCost') : t('settings.unitTurns'),
1569
+ unit: settings.metric === 'turns' ? t('settings.unitTurns') : t('settings.unitCost'),
1312
1570
  metric: settings.metric,
1313
1571
  onCommit: (value) => {
1314
1572
  onThreshold('yellow', value)
@@ -1356,6 +1614,7 @@
1356
1614
  ),
1357
1615
  displaySwitch,
1358
1616
  ...rows,
1617
+ h('div', { className: 'dshTurnCost_note' }, t('panel.totalNote')),
1359
1618
  estimate.hasContext
1360
1619
  ? !estimate.priced && estimate.model !== undefined
1361
1620
  ? h('div', { className: 'dshTurnCost_note dshTurnCost_alert' }, t('panel.noPrice'))
@@ -1477,7 +1736,41 @@
1477
1736
  tariffTime = ''
1478
1737
  }
1479
1738
  const estimate = estimateNextTurn({ usage, breakdown, pressure, selection, peak })
1480
- 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)
1481
1774
  const open = hovered || pinned || focusWithin
1482
1775
  /**
1483
1776
  * Keep the displayed tariff honest without polling blindly: wake up at
@@ -1523,7 +1816,16 @@
1523
1816
  estimate.hasContext && estimate.priced && estimate.extraCny !== undefined
1524
1817
  ? `≈ ${formatCost(estimate.extraCny)}`
1525
1818
  : t('chip.costUnknown')
1526
- 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
1527
1829
  const toneText =
1528
1830
  tone === 'green'
1529
1831
  ? t('tone.green')
@@ -1532,7 +1834,12 @@
1532
1834
  : tone === 'red'
1533
1835
  ? t('tone.red')
1534
1836
  : t('tone.idle')
1535
- const basisLabel = settings.metric === 'cost' ? t('settings.cost') : t('settings.turns')
1837
+ const basisLabel =
1838
+ settings.metric === 'cost'
1839
+ ? t('settings.cost')
1840
+ : settings.metric === 'total'
1841
+ ? t('settings.total')
1842
+ : t('settings.turns')
1536
1843
  const tariffLabel = peak ? t('tariff.peak') : t('tariff.off')
1537
1844
  const tariffBadge = peak ? t('tariff.peakShort') : t('tariff.offShort')
1538
1845
  const summary = `${t('chip.title')} · ${valueLabel} · ${tariffLabel} · ${t('panel.colorBy')}: ${basisLabel} (${toneText}) · ${t('chip.pinHint')}`
@@ -1554,6 +1861,19 @@
1554
1861
  costYellow: Math.max(settings.costGreen, value),
1555
1862
  })
1556
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
+ }
1557
1877
  } else if (field === 'green') {
1558
1878
  publishSettings({
1559
1879
  ...settings,
@@ -1638,6 +1958,7 @@
1638
1958
  ? h(Panel, {
1639
1959
  key: 'panel',
1640
1960
  estimate,
1961
+ session,
1641
1962
  turnsLabel,
1642
1963
  settings,
1643
1964
  priceSource: priceInfo.source,
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. 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). 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": "在输入框右侧显示已完成的对话轮数,也可切换为显示继续当前对话比新开对话多花的金额;胶囊上直接标出当前是峰时还是谷时,跨过官方峰谷边界(工作日北京时间 9:00–12:00、14:00–18:00 为峰时)会自动切换。悬停查看估算明细,点击胶囊固定面板后切换显示并设置轮数或金额的绿、黄、红阈值。价格表和法定节假日表每天从 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.3.1",
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, switching between peak and off-peak tariffs automatically.",
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"