@angelyeye/dsh-cost-tracker 1.8.11 → 1.8.13
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 +54 -0
- package/README.en.md +35 -3
- package/README.md +37 -4
- package/client.js +222 -10
- package/config.js +63 -4
- package/index.js +117 -21
- package/package.json +2 -2
- package/view.js +56 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,60 @@
|
|
|
2
2
|
|
|
3
3
|
本文件用中文记录 dsh-cost-tracker 的版本变更。
|
|
4
4
|
|
|
5
|
+
## v1.8.13(2026-09-25)
|
|
6
|
+
|
|
7
|
+
**新增:可以关掉插件在前端的显示(三个落点各自独立)**
|
|
8
|
+
|
|
9
|
+
- **背景**:插件的几个前端落点此前都是常驻的、没有开关 —— 输入框上方的「本会话花费」胶囊、侧边栏底部的峰谷时段条、设置页的「花费统计」看板。不想看的人只能忍,或者干脆卸载插件(连带失去记账与云端同步)。
|
|
10
|
+
- **现在**:设置 → 插件 → 插件配置 → 花费统计 → **界面显示**,三个开关**各自独立**、**勾选即刻生效**(不需要点上面的「保存」,也不需要重启 dsh):
|
|
11
|
+
| 开关 | 配置键 | 落点 |
|
|
12
|
+
| --- | --- | --- |
|
|
13
|
+
| 输入框上方的花费胶囊 | `uiDockEnabled` | `conversation.composer.dock` |
|
|
14
|
+
| 侧边栏峰谷时段条 | `uiPeakEnabled` | `sidebar.footer.action` |
|
|
15
|
+
| 设置页「花费统计」看板 | `uiDashboardEnabled` | `settings.section` |
|
|
16
|
+
另有一键「全部显示」恢复默认。
|
|
17
|
+
- **只影响渲染**:关掉之后记账、落盘、云端同步与 Agent 工具(`cost_stats` 等)全部照常工作;关掉看板时,设置项仍在,页面里给出一句「如何重新打开」的提示,而不是留一个点不开的空白导航项。
|
|
18
|
+
- **插件配置卡片本身不受这三个开关控制** —— 否则关掉看板之后就再没有入口能打开了。
|
|
19
|
+
- **安全默认**:显隐的真值与 `peakEnabled` 相反,**只有显式 `false` 才隐藏**,缺省/非布尔一律按「可见」处理。老配置文件里没有这几个键,升级后界面与升级前逐像素一致。
|
|
20
|
+
- **实现要点**:
|
|
21
|
+
- 显隐在**渲染期**判定(`uiOn(ui, key)` = `ui[key] !== false`),不是注册期 —— 宿主不会重启插件、插槽注册也无法撤销,只有在渲染期判定才能做到「改完立刻生效」。
|
|
22
|
+
- 配置卡片保存后广播 `dsh-cost-tracker-ui` 事件,已挂载的胶囊 / 时段条 / 看板立刻跟手;另有 30 秒轮询兜底。
|
|
23
|
+
- 新增宿主路由 `ui-config`(写)与 `peak`/`sync` 快照里的 `ui` 字段(读),三个开关与峰谷、云端字段**同存一份配置文件**(`~/.dsh/storages/cost-tracker-config.json`),互不覆盖。
|
|
24
|
+
- 侧边栏时段条关闭时,峰谷切换弹窗与系统通知一并停用(同属一个落点);只想留提醒不要时段条,用「峰谷计价与提示 → 峰时高价时段显著提示」。
|
|
25
|
+
- **测试**:新增 `test/ui-display.test.js`(23 条断言,四层:宿主 HTTP 面读写、落盘不覆盖其它字段、重启后读回、客户端三处判定);`test/client-render.test.js` 新增 [8][9] 两节(关掉即渲染为空、重新打开即恢复、卡片三个开关各自提交自己的键、client.js 与 config.js 的开关清单逐项对齐);`test/config.test.js` 新增界面开关一节(默认可见 / 老配置可见 / 非布尔回退)。全量测试通过。
|
|
26
|
+
- **顺带修掉一处假红**:`cloud-view-e2e.test.js` 的「热力图不重不漏」用例在**本地兄弟目录 dsh-cost-cloud 还是旧版**(< v1.3.2,`byDay` 无 token 类型拆分)时会硬失败 —— 那与「跨仓库依赖检测不到就跳过」的既定原则不一致。现改为探测到旧云端就明确 skip 并提示升级兄弟目录,不再把一个环境问题伪装成发布闸门红灯(线上真连旧云端时热力图本就会退回本机并在卡片标注口径,属已声明的降级)。
|
|
27
|
+
|
|
28
|
+
## v1.8.12(2026-09-19)
|
|
29
|
+
|
|
30
|
+
**修复:①「Token 用量统计」热力图不跟随三态视图(本机+云端下屏内自相矛盾)② `cost_stats scope=cloud|both` 崩溃**
|
|
31
|
+
|
|
32
|
+
- **① 热力图此前恒为本机**:它的数据源是宿主的 `usage` 路由 → `buildUsageHeat()`,只遍历本地
|
|
33
|
+
store 的 records/rollups,**没有任何云端输入**;而同一屏的卡片走 `viewDash`(本机+云端合并)。
|
|
34
|
+
于是切到「本机+云端」时,热力图说「累计 98.4M · 536 次调用」(纯本机),上方卡片说 955M ——
|
|
35
|
+
同一屏两套口径,用户第一反应就是"统计显示有问题"。
|
|
36
|
+
- 宿主新增 `route=usage` 取数:走云端 `/api/v1/plugin-view`(**只有它的 byDay 带 token 类型
|
|
37
|
+
拆分**)、固定 `range=all`(热力图是全时段累计口径,与页面区间选择无关)、
|
|
38
|
+
「本机+云端」沿用与卡片相同的 `union` 并集(其他整机 ∪ 本机其它 agent),
|
|
39
|
+
并归一成与本地 `buildUsageHeat` 同形的 `{days:[{date,input,output,cacheRead,cacheWrite,...}], total}`。
|
|
40
|
+
- 归一化时两处口径对齐:**tokens 一律按 `input+output+cacheRead+cacheWrite` 重算**(云端
|
|
41
|
+
byDay 的 tokens 含 `reasoning`,直接相加会比两侧之和大一截);**丢掉云端连续日期轴里的
|
|
42
|
+
补零日**(本地只返回有数据的日期,热力图自己会按 26 周补格)。
|
|
43
|
+
- 客户端新增 `mergeUsageHeat`(`view.js` 与 bundle 内联实现各一份,与 `mergeDash` 同款约定),
|
|
44
|
+
热力图改为消费 `viewUsage`:本机 / 本机+云端 / 仅云端;云端明细取不到时退回本机,
|
|
45
|
+
并在卡片标题右侧标注口径(「本机 + 云端(不重复计数)」/「仅云端」),避免再出现无标注的纯本机数字。
|
|
46
|
+
- **云端前置依赖**:`dsh-cost-cloud ≥ v1.3.2`(`plugin-view` 的 `byDay` 才带
|
|
47
|
+
input/output/cacheRead/cacheWrite)。旧云端下热力图自动退回本机,卡片与其它面板不受影响。
|
|
48
|
+
- **② `cost_stats scope=cloud|both` 必崩**:`Cannot read properties of undefined (reading 'realCost')`。
|
|
49
|
+
根因是云端响应形状漂移 —— `/api/v1/overview` 的金额摊在 `summary.{realCost,subEquivalent,…}`,
|
|
50
|
+
而宿主在云端支持 `devicePluginView` 时会**优先用 `/api/v1/plugin-view`**,后者**没有 `summary`**
|
|
51
|
+
(字段直接摊在顶层)。工具只读了 `c.summary`,于是 README 明确文档化的 `scope=both` 一直不可用。
|
|
52
|
+
现两种形状都兼容。
|
|
53
|
+
- **测试**:`view.test.js` 新增第 11 节(合并的相加不变量、tokens 重算、容错分支);
|
|
54
|
+
`cloud-read.test.js` 新增 4 条路径契约(usage 走 plugin-view、固定 range=all、
|
|
55
|
+
union 对 overview/usage 同时生效、cost_stats 兼容两种形状);`client-render.test.js`
|
|
56
|
+
新增第 7 节(三态下热力图的累计与按天数字,含"云端独有日期必须进入热力图");
|
|
57
|
+
`cloud-view-e2e.test.js` 新增真实云端 payload → `cloudUsageHeat` → `mergeUsageHeat` 的端到端不重不漏断言。
|
|
58
|
+
|
|
5
59
|
## v1.8.11(2026-09-17)
|
|
6
60
|
|
|
7
61
|
**新增:启动时检测「另一个 dsh 实例正在用同一份记录文件」并直接点名**
|
package/README.en.md
CHANGED
|
@@ -159,7 +159,7 @@ rm -rf ~/.dsh/profiles/node_modules/dsh-cost-tracker
|
|
|
159
159
|
- **Cost chart**: segment by peak period or by model; hover for daily breakdowns;
|
|
160
160
|
- **Color schemes**: in "by model" view, three swatches next to the title switch between 橙→黄 / 蓝→紫 / 蓝→浅蓝 palettes. Models are ranked by total spend and colored in a sequential gradient (rank 1 = darkest at the bottom, getting lighter upwards; no cycling, no collisions). The choice is remembered in the browser (localStorage);
|
|
161
161
|
- **Per-model sections**: one request-count chart and one token-composition chart (input / cache write / output / cache hit) per model;
|
|
162
|
-
- **Usage heatmap**: a Codex-style 26-week daily-usage grid; shade by the day's token count relative to the maximum; hover any cell for that day's breakdown (input / cache / output / cost), today outlined;
|
|
162
|
+
- **Usage heatmap**: a Codex-style 26-week daily-usage grid; shade by the day's token count relative to the maximum; hover any cell for that day's breakdown (input / cache / output / cost), today outlined; **the scope follows the three-state switch**: "local" counts this machine only, "local + cloud" merges the cloud's per-day usage (same union scope as the cards above, no double counting), "cloud only" shows the cloud alone, with the active scope labelled next to the title. Cloud per-day detail requires `dsh-cost-cloud ≥ v1.3.2`; on an older cloud it falls back to the local scope;
|
|
163
163
|
- **Peak/off-peak pricing & notice**: pick the tier strip style (**compact single-row — a 24h-proportional bar with a white real-time line** / **ring dial — a 24h hollow dial with a phase-colored dot**), optionally switch the compact strip to a **two-row compact** stacked layout (bar-above-text or text-above-bar), toggle the "Show time" tick labels (00:00–21:00), set the popup-alert lead time (1–30 min), alert type (both / entering peak / entering off-peak), popup position (bottom-right / center), and optional browser system notification; everything auto-saves. A persistent strip in the sidebar footer shows the current tier and countdown to the next switch;
|
|
164
164
|
- **CSV export**: exports detail records (last 180 days) plus daily rollup rows (`purpose=rollup`).
|
|
165
165
|
|
|
@@ -213,6 +213,21 @@ The dimension selector adds per-device / per-agent / per-model breakdowns and a
|
|
|
213
213
|
|
|
214
214
|
**Privacy**: only token counts, cost, timestamps and identifiers are uploaded — never prompts, responses, file paths or code. The config card offers "mask session id" (irreversible hash) and "omit purpose".
|
|
215
215
|
|
|
216
|
+
### Interface visibility (v1.8.12, optional)
|
|
217
|
+
|
|
218
|
+
Don't want the plugin in your face? **Settings → Plugins → Plugin configuration → Cost Tracker → Interface visibility** has three independent switches that apply **the moment you tick them** (no Save, no `dsh` restart):
|
|
219
|
+
|
|
220
|
+
| Switch | What turning it off does |
|
|
221
|
+
| --- | --- |
|
|
222
|
+
| Composer cost pill | the per-session cost / model breakdown above the chat input disappears |
|
|
223
|
+
| Sidebar peak bar | the phase / countdown strip at the bottom of the sidebar disappears (the peak-switch popup and web notifications go with it; if you only want the reminder without the strip, use the notice switch under "Peak/off-peak pricing & notices" instead) |
|
|
224
|
+
| Settings dashboard | the "Cost Tracker" entry disappears from the Settings nav (accounting and cloud sync keep running; the page then shows a one-line hint on how to bring it back) |
|
|
225
|
+
|
|
226
|
+
- **Display only**: accounting, persistence, cloud sync and the agent tools (`cost_stats` etc.) are unaffected;
|
|
227
|
+
- **The plugin configuration card itself is never hidden by these switches** — otherwise you would have no way to turn them back on;
|
|
228
|
+
- Truth value is "hidden only on an explicit `false`", so a missing key means visible: **an existing config file looks exactly the same after upgrading**;
|
|
229
|
+
- All three keys live in the same `~/.dsh/storages/cost-tracker-config.json` (`uiDockEnabled` / `uiPeakEnabled` / `uiDashboardEnabled`) and never overwrite the peak/cloud fields.
|
|
230
|
+
|
|
216
231
|
### HTTP API (for other tools)
|
|
217
232
|
|
|
218
233
|
All endpoints are `POST` + JSON and listen on the loopback address:
|
|
@@ -221,9 +236,10 @@ All endpoints are `POST` + JSON and listen on the loopback address:
|
|
|
221
236
|
POST /api/cost-tracker/summary Overview
|
|
222
237
|
POST /api/cost-tracker/dashboard Dashboard data
|
|
223
238
|
POST /api/cost-tracker/usage Usage heatmap (all-time totals + daily token aggregation)
|
|
224
|
-
POST /api/cost-tracker/peak Peak-phase snapshot (current tier / next switch / config)
|
|
239
|
+
POST /api/cost-tracker/peak Peak-phase snapshot (current tier / next switch / config / interface visibility)
|
|
225
240
|
POST /api/cost-tracker/peak-config Save peak-price notice config
|
|
226
|
-
POST /api/cost-tracker/
|
|
241
|
+
POST /api/cost-tracker/ui-config Save interface-visibility switches (pill / sidebar bar / dashboard; partial patches OK)
|
|
242
|
+
POST /api/cost-tracker/sync Cloud sync status (device id / watermark / pending / last error / interface visibility)
|
|
227
243
|
POST /api/cost-tracker/sync-now Sync now ({"full":true} to re-send everything)
|
|
228
244
|
POST /api/cost-tracker/sync-test Test the cloud connection
|
|
229
245
|
POST /api/cost-tracker/sync-config Save cloud sync config
|
|
@@ -243,6 +259,22 @@ Example: `curl -X POST http://127.0.0.1:3080/api/cost-tracker/summary -d '{}'`
|
|
|
243
259
|
|
|
244
260
|
> Highlights only — the full version-by-version history lives in [`CHANGELOG.md`](./CHANGELOG.md) (Chinese).
|
|
245
261
|
|
|
262
|
+
### v1.8.13 (2026-09-25)
|
|
263
|
+
|
|
264
|
+
**Added: the plugin's front-end surfaces can now be turned off (three independent switches)**
|
|
265
|
+
|
|
266
|
+
- **Settings → Plugins → Plugin configuration → Cost Tracker → Interface visibility**: the composer cost pill, the sidebar peak bar and the Settings "Cost Tracker" dashboard can each be switched off on their own, applied **immediately** (no Save, no `dsh` restart), plus a one-click "Show all".
|
|
267
|
+
- **Display only**: accounting, cloud sync and the agent tools keep working; the plugin configuration card itself is never hidden (otherwise there would be no way back).
|
|
268
|
+
- **Safe default**: hidden only on an explicit `false`, so missing keys mean visible — an existing config file looks identical after upgrading. See the "Interface visibility" section above.
|
|
269
|
+
|
|
270
|
+
### v1.8.12 (2026-09-19)
|
|
271
|
+
|
|
272
|
+
**Fixed: the heatmap ignored the three-state switch (self-contradicting screen in "local + cloud"), and `cost_stats scope=cloud|both` crashed**
|
|
273
|
+
|
|
274
|
+
- The "Token Usage" heatmap only ever read the local store, so in "local + cloud" it still showed a local-only total (field report: heatmap 98.4M / 536 calls on the same screen as cards reading 955M). It now fetches per view: the host asks the cloud's `plugin-view` for per-day detail **with the token-type breakdown** (`range=all` all-time scope; "local + cloud" reuses the same `union` as the cards), and the client merges it with `mergeUsageHeat`. When cloud detail is unavailable it falls back to local and labels the scope next to the title. **Requires `dsh-cost-cloud ≥ v1.3.2`.**
|
|
275
|
+
- Fixed the `Cannot read properties of undefined (reading 'realCost')` crash in `cost_stats scope=cloud|both`: cloud responses come in two shapes (`overview.summary` vs. `plugin-view` top level) and only the former was read.
|
|
276
|
+
- Added regression guards: `view.test.js` section 11, four path contracts in `cloud-read.test.js`, `client-render.test.js` section 7, and an end-to-end merge assertion in `cloud-view-e2e.test.js` against the real cloud.
|
|
277
|
+
|
|
246
278
|
### v1.8.11 (2026-09-17)
|
|
247
279
|
|
|
248
280
|
**Added: startup detection of "another dsh instance is using the same records file", reported by name**
|
package/README.md
CHANGED
|
@@ -36,11 +36,12 @@
|
|
|
36
36
|
| 🏷️ | **官方模型名对齐** | 计费支持**官方现役名 `deepseek-flash`**(价格卡脚注 (1):「模型名请使用 `deepseek-flash`」),旧写法 `deepseek-v4.1-flash` 等归一化后命中同一档价,避免因官方改名而落入兜底估算 |
|
|
37
37
|
| 📊 | **可视化仪表盘** | 设置页新增「花费统计」:概览卡片、消费柱状图(按峰谷/按模型)、分模型的请求次数与 Tokens 图表,**全部支持鼠标悬停查看明细** |
|
|
38
38
|
| 🧭 | **多机汇总(云端同步)** | 可对接**自建云端服务**(独立仓库 `dsh-cost-cloud`,零运行时依赖):多台电脑的用量汇总到一处,看板顶部出现 **本机 / 本机+云端 / 仅云端** 三态开关,并支持**设备 × Agent 矩阵**(行合计 = 列合计 = 总计);上报内容仅 token 数、费用、时间戳与标识符,可选会话脱敏 |
|
|
39
|
-
| 🔥 | **用量热力图** | 设置页新增「Token 用量统计」:类 Codex 的 **26 周日用量方格热图**,按天着色(输入 / 缓存 / 输出 / 费用)
|
|
39
|
+
| 🔥 | **用量热力图** | 设置页新增「Token 用量统计」:类 Codex 的 **26 周日用量方格热图**,按天着色(输入 / 缓存 / 输出 / 费用),悬停看当日明细、今天高亮描边,顶部显示全时段累计;**跟随三态视图**——「本机+云端 / 仅云端」下自动并入云端按天用量(卡片标题右侧标注当前口径) |
|
|
40
40
|
| 📈 | **订阅配额监控** | Kimi Coding Plan 等订阅套餐:本周配额、5 小时滚动窗口限额、等效按量费用参考 |
|
|
41
41
|
| 💳 | **余额查询** | 一键查询 DeepSeek 官方账户余额(总余额 / 充值 / 赠送 / 状态) |
|
|
42
42
|
| 🤖 | **Agent 工具** | 直接在对话里问:"我现在花了多少钱?"——Agent 会调用 `cost_stats` / `cost_prices` 等工具回答 |
|
|
43
43
|
| 🔻 | **状态栏** | 聊天输入框下方实时显示:**本会话花费**(胶囊分段:本会话 / 订阅套餐 / 分模型),按会话实际用到的模型与订阅拆分,**多模型默认折叠只显示 top2,点击展开全部明细**;订阅显示具体套餐名,不再展示配额与调用次数 |
|
|
44
|
+
| 👁️ | **界面显示开关** | 输入框上方的花费胶囊、侧边栏峰谷时段条、设置页「花费统计」看板**三个落点各自可关**(设置 → 插件 → 插件配置 → 花费统计 → 界面显示),勾选即刻生效;**只影响显示**,记账、云端同步与 Agent 工具照常,配置卡片本身不受开关控制 |
|
|
44
45
|
| 💾 | **本地持久化** | 数据存本机 `~/.dsh/storages/cost-tracker-records.json`,重启不丢、不上传;**明细保留最近 180 天,更早自动压缩为永久日汇总,全时段统计永远精确且内存/磁盘有界** |
|
|
45
46
|
| 📤 | **CSV 导出** | 一键导出明细 + 日汇总(purpose=rollup),方便用 Excel / Numbers 做进一步分析 |
|
|
46
47
|
|
|
@@ -159,7 +160,7 @@ rm -rf ~/.dsh/profiles/node_modules/dsh-cost-tracker
|
|
|
159
160
|
- **消费金额图**:支持「按峰谷」「按模型」两种分段方式,鼠标悬停查看当日明细;
|
|
160
161
|
- **配色切换**:「按模型」视图下,消费金额标题旁有三套装色款条(橙→黄 / 蓝→紫 / 蓝→浅蓝)可切换;模型按总消费降序排名取色(第 1 名最深夜底、逐级变浅,不循环不撞色),选择保存在浏览器本地;
|
|
161
162
|
- **分模型区块**:每个模型一张请求次数图 + 一张 Tokens 构成图(输入/缓存写入/输出/缓存命中);
|
|
162
|
-
- **Token 用量统计热力图**:类 Codex 的 26 周每日用量方格,颜色深浅按当日 token 相对最大值分档;悬停任一格看该日明细(输入 / 缓存 / 输出 / 费用)
|
|
163
|
+
- **Token 用量统计热力图**:类 Codex 的 26 周每日用量方格,颜色深浅按当日 token 相对最大值分档;悬停任一格看该日明细(输入 / 缓存 / 输出 / 费用),今天高亮描边;**口径跟随三态开关**:「本机」只统计本机,「本机+云端」把云端按天用量并入(与上方卡片同一并集口径、不重复计数),「仅云端」只看云端,标题右侧标注当前口径。云端按天明细需要 `dsh-cost-cloud ≥ v1.3.2`,旧云端下自动退回本机口径;
|
|
163
164
|
- **峰谷计价与提示**:时段条样式可选(**简洁单行·按 24h 比例**(白色实时进度线) / **环形表盘·相位色点**),简洁样式可选**双行紧凑**(条上文下 / 文上条下),可开关「显示时间」刻度(00:00–21:00),设置峰/谷切换前的弹窗提醒提前量(1–30 分钟)、提醒类型(两者 / 进入高峰 / 进入闲时)、弹窗位置(右下角 / 屏幕中心)与浏览器系统通知;全部自动保存。侧边栏底部常驻时段条显示当前档位与下次切换倒计时;
|
|
164
165
|
- **导出 CSV**:导出明细记录(近 180 天)+ 日汇总行(`purpose=rollup`)。
|
|
165
166
|
|
|
@@ -213,6 +214,21 @@ docker compose up -d # 打开 http://<服务器>:8787 ,在「设置」页
|
|
|
213
214
|
|
|
214
215
|
**隐私**:只上报 token 数量、费用、时间戳与标识符(不涉及 prompt / 回复 / 文件内容);可在配置卡开启「会话脱敏」(`sessionId` 上报前替换为不可逆哈希)与「不含 purpose」。
|
|
215
216
|
|
|
217
|
+
### 界面显示(v1.8.12,可选)
|
|
218
|
+
|
|
219
|
+
不想在界面上看到插件?**设置 → 插件 → 插件配置 → 花费统计 → 界面显示**里三个开关**各自独立**、**勾选即刻生效**(无需点「保存」,也无需重启 dsh):
|
|
220
|
+
|
|
221
|
+
| 开关 | 关掉之后 |
|
|
222
|
+
| --- | --- |
|
|
223
|
+
| 输入框上方的花费胶囊 | 会话输入区不再显示本会话花费与模型明细 |
|
|
224
|
+
| 侧边栏峰谷时段条 | 侧边栏底部的档位 / 倒计时消失(峰谷切换弹窗与系统通知一并停用;只想留提醒不想要时段条,请改用「峰谷计价与提示」里的提示开关) |
|
|
225
|
+
| 设置页「花费统计」看板 | 设置页左侧不再出现该入口(记账与云端同步照常;关掉后该页只留一句重新打开的指引) |
|
|
226
|
+
|
|
227
|
+
- **只影响显示**:记账、落盘、云端同步与 Agent 工具(`cost_stats` 等)全部照常工作;
|
|
228
|
+
- **插件配置卡片本身不受这三个开关控制** —— 否则关掉之后就没有入口能再打开了;
|
|
229
|
+
- 取值为「只有显式 `false` 才隐藏」,缺省即显示。老配置文件里没有这几个键,**升级后界面与升级前一致**;
|
|
230
|
+
- 落盘在同一份 `~/.dsh/storages/cost-tracker-config.json`(键名 `uiDockEnabled` / `uiPeakEnabled` / `uiDashboardEnabled`),与峰谷、云端字段互不覆盖。
|
|
231
|
+
|
|
216
232
|
### HTTP API(供其他工具调用)
|
|
217
233
|
|
|
218
234
|
全部为 `POST` + JSON,监听本机地址:
|
|
@@ -221,9 +237,10 @@ docker compose up -d # 打开 http://<服务器>:8787 ,在「设置」页
|
|
|
221
237
|
POST /api/cost-tracker/summary 概览(含本会话按模型拆分 / 订阅)
|
|
222
238
|
POST /api/cost-tracker/dashboard 仪表盘数据
|
|
223
239
|
POST /api/cost-tracker/usage 用量热力图(全时段累计 + 按天 token 聚合)
|
|
224
|
-
POST /api/cost-tracker/peak 峰谷相位快照(
|
|
240
|
+
POST /api/cost-tracker/peak 峰谷相位快照(当前档位/下次切换/配置/界面显示开关)
|
|
225
241
|
POST /api/cost-tracker/peak-config 保存峰谷计价提示配置
|
|
226
|
-
POST /api/cost-tracker/
|
|
242
|
+
POST /api/cost-tracker/ui-config 保存界面显示开关(胶囊/时段条/看板,可只传要改的键)
|
|
243
|
+
POST /api/cost-tracker/sync 云端同步状态(设备 ID/水位/待上报/最近错误/界面显示开关)
|
|
227
244
|
POST /api/cost-tracker/sync-now 立即同步(传 {"full":true} 全量补传)
|
|
228
245
|
POST /api/cost-tracker/sync-test 测试云端连接
|
|
229
246
|
POST /api/cost-tracker/sync-config 保存云端同步配置
|
|
@@ -243,6 +260,22 @@ POST /api/cost-tracker/export 导出 CSV
|
|
|
243
260
|
|
|
244
261
|
> 这里只列重要版本;逐版完整记录见 [`CHANGELOG.md`](./CHANGELOG.md)。
|
|
245
262
|
|
|
263
|
+
### v1.8.13(2026-09-25)
|
|
264
|
+
|
|
265
|
+
**新增:可以关掉插件在前端的显示(三个落点各自独立)**
|
|
266
|
+
|
|
267
|
+
- 设置 → 插件 → 插件配置 → 花费统计 → **界面显示**:输入框上方的花费胶囊、侧边栏峰谷时段条、设置页「花费统计」看板三个落点**各自可关**,勾选即刻生效(无需点「保存」、无需重启 dsh),另有「全部显示」一键恢复。
|
|
268
|
+
- **只影响显示**:记账、云端同步与 Agent 工具照常;配置卡片本身不受这三个开关控制(否则关掉就没入口再打开)。
|
|
269
|
+
- **安全默认**:只有显式 `false` 才隐藏,缺省即显示 —— 老配置升级后界面与升级前一致。详见上方「界面显示」一节。
|
|
270
|
+
|
|
271
|
+
### v1.8.12(2026-09-19)
|
|
272
|
+
|
|
273
|
+
**修复:热力图不跟随三态视图(本机+云端下屏内自相矛盾)+ `cost_stats scope=cloud|both` 崩溃**
|
|
274
|
+
|
|
275
|
+
- 「Token 用量统计」热力图此前只读本地 store,切到「本机+云端」时仍显示纯本机累计(现场:热力图 98.4M / 536 次调用,同屏卡片 955M)。现在按视图取数:宿主走云端 `plugin-view` 拿**带 token 类型拆分的按天明细**(`range=all` 全时段口径,「本机+云端」沿用与卡片相同的 `union` 并集),客户端 `mergeUsageHeat` 合并;云端明细不可用时退回本机并在标题右侧标注口径。**需要 `dsh-cost-cloud ≥ v1.3.2`**。
|
|
276
|
+
- 修掉 `cost_stats scope=cloud|both` 必崩的 `Cannot read properties of undefined (reading 'realCost')`:云端响应有 `overview.summary` 与 `plugin-view` 顶层两种形状,此前只读前者。
|
|
277
|
+
- 新增护栏:`view.test.js` 第 11 节、`cloud-read.test.js` 4 条契约、`client-render.test.js` 第 7 节、`cloud-view-e2e.test.js` 真实云端端到端合并断言。
|
|
278
|
+
|
|
246
279
|
### v1.8.11(2026-09-17)
|
|
247
280
|
|
|
248
281
|
**新增:启动时检测「另一个 dsh 实例正在用同一份记录文件」并直接点名**
|
package/client.js
CHANGED
|
@@ -58,6 +58,40 @@ window.__ModuleLoader__.load({
|
|
|
58
58
|
}
|
|
59
59
|
const MEMBERSHIP = { LEVEL_FREE: "免费版", LEVEL_BASIC: "基础版", LEVEL_INTERMEDIATE: "进阶版", LEVEL_ADVANCED: "高级版" };
|
|
60
60
|
|
|
61
|
+
// ---------- 前端显隐开关(服务端 ui-config,见 config.js 的 UI_SURFACES) ----------
|
|
62
|
+
// 配置改动后由配置卡片广播,已挂载的部件立刻响应,不必等下一次轮询。
|
|
63
|
+
const UI_EVENT = "dsh-cost-tracker-ui";
|
|
64
|
+
/**
|
|
65
|
+
* 取显隐标志:只有显式 false 才算关闭。
|
|
66
|
+
* snap 还没加载完 / 老服务端不返回该字段时按「可见」处理 —— 否则界面会先闪一下再出现。
|
|
67
|
+
*/
|
|
68
|
+
function uiOn(ui, key) {
|
|
69
|
+
return !(ui && ui[key] === false);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* 「界面显示」分组的开关清单。
|
|
73
|
+
* 说明书(label/desc)在浏览器里必须有本地副本:配置卡片渲染时不该为了拿一段
|
|
74
|
+
* 文案再往返一次服务端。key 与 config.js 的 UI_SURFACES 必须逐字一致 ——
|
|
75
|
+
* test/client-render.test.js 的 [8] 会把两份清单对起来,漂移即报红。
|
|
76
|
+
*/
|
|
77
|
+
const UI_SURFACES = [
|
|
78
|
+
{
|
|
79
|
+
key: "uiDockEnabled",
|
|
80
|
+
label: "输入框上方的花费胶囊",
|
|
81
|
+
desc: "本会话花费与模型明细(会话输入区上方)。关闭后输入区不再显示任何花费信息。",
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
key: "uiPeakEnabled",
|
|
85
|
+
label: "侧边栏峰谷时段条",
|
|
86
|
+
desc: "侧边栏底部的当前档位 / 倒计时。关闭后峰谷切换弹窗与系统通知一并停用;只想留提醒不想要时段条时,请改用「峰谷计价与提示」里的提示开关。",
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
key: "uiDashboardEnabled",
|
|
90
|
+
label: "设置页「花费统计」看板",
|
|
91
|
+
desc: "设置页左侧导航的花费统计入口与看板。关闭后该入口隐藏,插件仍照常记账并同步云端。",
|
|
92
|
+
},
|
|
93
|
+
];
|
|
94
|
+
|
|
61
95
|
// ---------- styles ----------
|
|
62
96
|
function applyStyles(ctx) {
|
|
63
97
|
const css = `
|
|
@@ -660,6 +694,49 @@ window.__ModuleLoader__.load({
|
|
|
660
694
|
asOf: cloud.asOf || 0,
|
|
661
695
|
});
|
|
662
696
|
}
|
|
697
|
+
// 「Token 用量统计」热力图的跨视图合并(与 view.js 的 mergeUsageHeat 逐行等价,
|
|
698
|
+
// 浏览器里 require("./view") 取不到时必须自带一份,否则云端用量永远并不进来)
|
|
699
|
+
function vR4(x) { return Math.round((Number(x) || 0) * 10000) / 10000; }
|
|
700
|
+
function vMergeUsageHeat(local, cloud) {
|
|
701
|
+
if (!cloud || !Array.isArray(cloud.days)) return local || null;
|
|
702
|
+
if (!local || !Array.isArray(local.days)) return cloud;
|
|
703
|
+
const per = new Map();
|
|
704
|
+
const add = (d) => {
|
|
705
|
+
if (!d || !d.date) return;
|
|
706
|
+
const cur = per.get(d.date) || { date: d.date, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0, cost: 0, tokens: 0 };
|
|
707
|
+
cur.input += d.input || 0;
|
|
708
|
+
cur.output += d.output || 0;
|
|
709
|
+
cur.cacheRead += d.cacheRead || 0;
|
|
710
|
+
cur.cacheWrite += d.cacheWrite || 0;
|
|
711
|
+
cur.calls += d.calls || 0;
|
|
712
|
+
cur.cost += d.cost || 0;
|
|
713
|
+
// tokens 一律按本地口径重算:云端 byDay 的 tokens 含 reasoning,直接相加会不同源
|
|
714
|
+
cur.tokens = cur.input + cur.output + cur.cacheRead + cur.cacheWrite;
|
|
715
|
+
per.set(d.date, cur);
|
|
716
|
+
};
|
|
717
|
+
for (const d of local.days) add(d);
|
|
718
|
+
for (const d of cloud.days) add(d);
|
|
719
|
+
const days = Array.from(per.values())
|
|
720
|
+
.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0))
|
|
721
|
+
.map((d) => Object.assign({}, d, { cost: vR4(d.cost) }));
|
|
722
|
+
const lt = local.total || {};
|
|
723
|
+
const ct = cloud.total || {};
|
|
724
|
+
const n = (v) => Number(v) || 0;
|
|
725
|
+
return {
|
|
726
|
+
ok: true,
|
|
727
|
+
source: "merged",
|
|
728
|
+
days,
|
|
729
|
+
total: {
|
|
730
|
+
tokens: n(lt.tokens) + n(ct.tokens),
|
|
731
|
+
input: n(lt.input) + n(ct.input),
|
|
732
|
+
cache: n(lt.cache) + n(ct.cache),
|
|
733
|
+
output: n(lt.output) + n(ct.output),
|
|
734
|
+
calls: n(lt.calls) + n(ct.calls),
|
|
735
|
+
cost: vR4(n(lt.cost) + n(ct.cost)),
|
|
736
|
+
},
|
|
737
|
+
asOf: cloud.asOf || 0,
|
|
738
|
+
};
|
|
739
|
+
}
|
|
663
740
|
const VIEW = requireLocal("./view", {
|
|
664
741
|
BOARD_VIEWS: [
|
|
665
742
|
{ id: "local", label: "本机" },
|
|
@@ -678,11 +755,13 @@ window.__ModuleLoader__.load({
|
|
|
678
755
|
r2: vR2,
|
|
679
756
|
normalizeCloudDash: vNormalizeCloudDash,
|
|
680
757
|
mergeDash: vMergeDash,
|
|
758
|
+
mergeUsageHeat: vMergeUsageHeat,
|
|
681
759
|
});
|
|
682
760
|
const BOARD_VIEWS = VIEW.BOARD_VIEWS;
|
|
683
761
|
const BOARD_DIMS = VIEW.BOARD_DIMS;
|
|
684
762
|
const normalizeCloudDash = VIEW.normalizeCloudDash;
|
|
685
763
|
const mergeDash = VIEW.mergeDash;
|
|
764
|
+
const mergeUsageHeat = VIEW.mergeUsageHeat || vMergeUsageHeat;
|
|
686
765
|
|
|
687
766
|
function filterRow(days, setDays, onExport, onRefresh, msg, busy, peakWindows, viewCtl) {
|
|
688
767
|
const views = viewCtl && viewCtl.available ? BOARD_VIEWS : [BOARD_VIEWS[0]];
|
|
@@ -1251,6 +1330,10 @@ window.__ModuleLoader__.load({
|
|
|
1251
1330
|
// 预览跟随用户配置的弹窗位置(右下角 / 屏幕中心),不强制覆盖
|
|
1252
1331
|
popup = e(PeakAlertPopup, { snap, preview, now: now + 120000, countdownText: "2 分", onDismiss: () => setPreview(null) });
|
|
1253
1332
|
}
|
|
1333
|
+
// 显隐开关(在所有 hook 之后判定,避免条件式 hook 顺序漂移):
|
|
1334
|
+
// 时段条、切换弹窗与系统通知同属这一个落点,关闭即整体停用;
|
|
1335
|
+
// 想「只留提醒、不要时段条」请关掉「峰谷计价与提示 → 峰时高价时段显著提示」。
|
|
1336
|
+
if (!uiOn(snap && snap.ui, "uiPeakEnabled")) return null;
|
|
1254
1337
|
return e("div", null,
|
|
1255
1338
|
e(PeakStrip, { snap, style: snap ? snap.style : "compact", wide, now, ringSize: 112 }),
|
|
1256
1339
|
popup);
|
|
@@ -1398,6 +1481,9 @@ window.__ModuleLoader__.load({
|
|
|
1398
1481
|
const [msg, setMsg] = useState("");
|
|
1399
1482
|
const [busy, setBusy] = useState(false);
|
|
1400
1483
|
const [testing, setTesting] = useState("");
|
|
1484
|
+
// 界面显示三开关(独立于云端同步草稿:勾选即刻生效并落盘)
|
|
1485
|
+
const [uiDraft, setUiDraft] = useState({ uiDockEnabled: true, uiPeakEnabled: true, uiDashboardEnabled: true });
|
|
1486
|
+
const [uiMsg, setUiMsg] = useState("");
|
|
1401
1487
|
// 折叠态:与宿主「插件配置」里其它卡片一致——默认收起,点标题展开
|
|
1402
1488
|
const [open, setOpen] = useState(false);
|
|
1403
1489
|
function load() {
|
|
@@ -1414,6 +1500,12 @@ window.__ModuleLoader__.load({
|
|
|
1414
1500
|
includePurpose: v.includePurpose !== false,
|
|
1415
1501
|
cloudView: v.view || "local",
|
|
1416
1502
|
});
|
|
1503
|
+
// 界面显示:缺省视为可见(与 normalizeUiConfig 同一真值语义)
|
|
1504
|
+
setUiDraft({
|
|
1505
|
+
uiDockEnabled: v.uiDockEnabled !== false,
|
|
1506
|
+
uiPeakEnabled: v.uiPeakEnabled !== false,
|
|
1507
|
+
uiDashboardEnabled: v.uiDashboardEnabled !== false,
|
|
1508
|
+
});
|
|
1417
1509
|
}).catch(() => {});
|
|
1418
1510
|
}
|
|
1419
1511
|
useEffect(() => { load(); }, []);
|
|
@@ -1449,6 +1541,32 @@ window.__ModuleLoader__.load({
|
|
|
1449
1541
|
load();
|
|
1450
1542
|
}).catch(err => { setBusy(false); setMsg("同步失败:" + String(err && err.message ? err.message : err)); });
|
|
1451
1543
|
}
|
|
1544
|
+
/**
|
|
1545
|
+
* 界面显示开关:勾选即刻提交并落盘(无需点「保存」),随后广播 UI_EVENT,
|
|
1546
|
+
* 让已经挂载的胶囊 / 时段条 / 看板立刻跟着显隐。
|
|
1547
|
+
* 关掉看板后本卡片仍在原位(它不受这三个开关控制),随时能改回来。
|
|
1548
|
+
*/
|
|
1549
|
+
function saveUi(patch) {
|
|
1550
|
+
const next = Object.assign({}, uiDraft, patch);
|
|
1551
|
+
setUiDraft(next);
|
|
1552
|
+
setUiMsg("保存中…");
|
|
1553
|
+
apiCall("ui-config", patch).then(v => {
|
|
1554
|
+
if (v && v.ok) {
|
|
1555
|
+
setUiDraft({
|
|
1556
|
+
uiDockEnabled: v.uiDockEnabled !== false,
|
|
1557
|
+
uiPeakEnabled: v.uiPeakEnabled !== false,
|
|
1558
|
+
uiDashboardEnabled: v.uiDashboardEnabled !== false,
|
|
1559
|
+
});
|
|
1560
|
+
setUiMsg("已保存,界面立即生效");
|
|
1561
|
+
try { window.dispatchEvent(new CustomEvent(UI_EVENT)); } catch (_) {}
|
|
1562
|
+
} else {
|
|
1563
|
+
setUiMsg("保存失败:" + ((v && v.error) || "未知错误"));
|
|
1564
|
+
}
|
|
1565
|
+
setTimeout(() => setUiMsg(""), 2500);
|
|
1566
|
+
}).catch(err => {
|
|
1567
|
+
setUiMsg("保存失败:" + String(err && err.message ? err.message : err));
|
|
1568
|
+
});
|
|
1569
|
+
}
|
|
1452
1570
|
// 卡片外壳对齐宿主 PluginCard:li.cost-pcard > button.cost-pcard-head(标题+副标题+箭头)> body
|
|
1453
1571
|
const head = e("button", { type: "button", className: "cost-pcard-head", "aria-expanded": open, onClick: () => setOpen(v => !v) },
|
|
1454
1572
|
e("span", { className: "cost-pcard-headtext" },
|
|
@@ -1492,12 +1610,60 @@ window.__ModuleLoader__.load({
|
|
|
1492
1610
|
"设备 ID " + (st.deviceId || "(未生成)") + " · 水位 seq=" + st.watermark + " · 待上报 " + st.pending + " 条 · 上次同步 " + (st.lastSyncAt ? timeLabel(st.lastSyncAt) : "从未")),
|
|
1493
1611
|
st.lastError ? e("div", { className: "cost-err" }, "最近错误:" + st.lastError) : null,
|
|
1494
1612
|
st.needAuth ? e("div", { className: "cost-err" }, "令牌无效:请在云端看板重新生成共享引导令牌后填入上方「共享令牌」。") : null,
|
|
1495
|
-
st.url ? e("div", { className: "cost-hint", style: { marginTop: "6px" } }, "云端看板:" + st.url) : null
|
|
1613
|
+
st.url ? e("div", { className: "cost-hint", style: { marginTop: "6px" } }, "云端看板:" + st.url) : null,
|
|
1614
|
+
// ---------- 界面显示:三个前端落点各自显隐,勾选即刻生效 ----------
|
|
1615
|
+
// 只影响渲染,不影响记账 / 云端同步 / Agent 工具;本卡片不受这三个开关控制
|
|
1616
|
+
// (否则关掉之后就再没有入口能打开了)。
|
|
1617
|
+
e("div", { className: "cost-sync-card" },
|
|
1618
|
+
e("div", { className: "cost-panel-title" }, "界面显示"),
|
|
1619
|
+
e("div", { className: "cost-hint", style: { marginTop: "6px" } },
|
|
1620
|
+
"控制插件在 DSH 界面上的落点,勾选后立即生效(无需点上面的「保存」)。关闭只影响显示:记账、云端同步与 Agent 工具照常工作。"),
|
|
1621
|
+
e("div", { style: { marginTop: "8px", display: "grid", gap: "6px" } },
|
|
1622
|
+
UI_SURFACES.map(s => e("label", { key: s.key, className: "cost-row", style: { gap: "8px", alignItems: "flex-start" } },
|
|
1623
|
+
e("input", {
|
|
1624
|
+
type: "checkbox",
|
|
1625
|
+
checked: uiDraft[s.key] !== false,
|
|
1626
|
+
onChange: ev => saveUi({ [s.key]: ev.target.checked }),
|
|
1627
|
+
}),
|
|
1628
|
+
e("span", null,
|
|
1629
|
+
e("span", null, s.label),
|
|
1630
|
+
e("div", { className: "cost-hint" }, s.desc))))),
|
|
1631
|
+
e("div", { className: "cost-row", style: { gap: "8px", marginTop: "6px" } },
|
|
1632
|
+
e("button", { className: "cost-btn", onClick: () => saveUi({ uiDockEnabled: true, uiPeakEnabled: true, uiDashboardEnabled: true }) }, "全部显示"),
|
|
1633
|
+
uiMsg ? e("span", { className: "cost-hint" }, uiMsg) : null)));
|
|
1496
1634
|
return e("li", { className: "cost-pcard" + (open ? " is-open" : "") },
|
|
1497
1635
|
head,
|
|
1498
1636
|
open ? e("div", { className: "cost-pcard-body" }, body) : null);
|
|
1499
1637
|
}
|
|
1500
1638
|
|
|
1639
|
+
/**
|
|
1640
|
+
* 「花费统计」看板的插槽门卫。
|
|
1641
|
+
* 关掉界面显示时**不能注册成空渲染**(会留下一个点不开的空白导航项),
|
|
1642
|
+
* 所以这里保留设置项但只渲染一句说明 —— 用户随时能在插件配置卡片里改回来。
|
|
1643
|
+
* 宿主不重启插件、插槽注册也无法撤销,因此显隐必须在渲染期判定。
|
|
1644
|
+
*/
|
|
1645
|
+
function DashGate() {
|
|
1646
|
+
const [ui, setUi] = useState(null);
|
|
1647
|
+
useEffect(() => {
|
|
1648
|
+
let alive = true;
|
|
1649
|
+
function load() {
|
|
1650
|
+
apiCall("peak", {}).then(v => { if (alive && v && v.ok) setUi(v.ui || {}); }).catch(() => {});
|
|
1651
|
+
}
|
|
1652
|
+
load();
|
|
1653
|
+
const id = setInterval(load, 30000);
|
|
1654
|
+
window.addEventListener(UI_EVENT, load);
|
|
1655
|
+
return () => { alive = false; clearInterval(id); window.removeEventListener(UI_EVENT, load); };
|
|
1656
|
+
}, []);
|
|
1657
|
+
if (!uiOn(ui, "uiDashboardEnabled")) {
|
|
1658
|
+
return e("div", { className: "cost-wrap" },
|
|
1659
|
+
e("div", { className: "cost-h1" }, pluginIcon(18), "花费统计"),
|
|
1660
|
+
e("div", { className: "cost-hint", style: { marginTop: "8px" } },
|
|
1661
|
+
"花费统计看板已在设置里关闭显示。记账与云端同步不受影响;要重新打开:" +
|
|
1662
|
+
"设置 → 插件 → 插件配置 → 花费统计 → 界面显示 → 打开「设置页花费统计看板」。"));
|
|
1663
|
+
}
|
|
1664
|
+
return e(Dashboard, {});
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1501
1667
|
function Dashboard() {
|
|
1502
1668
|
const [days, setDays] = useState(7);
|
|
1503
1669
|
const [dash, setDash] = useState(null);
|
|
@@ -1523,6 +1689,8 @@ window.__ModuleLoader__.load({
|
|
|
1523
1689
|
const [cloudDash, setCloudDash] = useState(null);
|
|
1524
1690
|
const [cloudErr, setCloudErr] = useState("");
|
|
1525
1691
|
const [cloudMatrix, setCloudMatrix] = useState(null);
|
|
1692
|
+
const [cloudUsage, setCloudUsage] = useState(null);
|
|
1693
|
+
const [cloudUsageErr, setCloudUsageErr] = useState("");
|
|
1526
1694
|
const [view, setViewState] = useState(() => {
|
|
1527
1695
|
try { return localStorage.getItem("dsh-cost-tracker-view") || "local" } catch (e) { return "local" }
|
|
1528
1696
|
});
|
|
@@ -1577,6 +1745,20 @@ window.__ModuleLoader__.load({
|
|
|
1577
1745
|
if (v && v.ok !== false) setCloudMatrix(v); else setCloudMatrix(null);
|
|
1578
1746
|
}).catch(() => setCloudMatrix(null));
|
|
1579
1747
|
}
|
|
1748
|
+
/**
|
|
1749
|
+
* 云端「按天用量明细」(热力图数据源)。
|
|
1750
|
+
* · view=local+cloud → cloud-rest:其他整机 ∪ 本机其它 agent(与卡片同一并集口径)
|
|
1751
|
+
* · view=cloud → 全网
|
|
1752
|
+
* 宿主把它归一成与本地 buildUsageHeat 同形的 {days:[{date,input,output,cacheRead,cacheWrite,...}], total},
|
|
1753
|
+
* 客户端再按视图合并,热力图与上方卡片口径才能一致(此前热力图恒为本机,屏内自相矛盾)。
|
|
1754
|
+
*/
|
|
1755
|
+
function loadCloudUsage(mode) {
|
|
1756
|
+
if (!mode || mode === "local") { setCloudUsage(null); setCloudUsageErr(""); return; }
|
|
1757
|
+
apiCall("cloud", { route: "usage", view: mode === "local+cloud" ? "cloud-rest" : "cloud" }).then(v => {
|
|
1758
|
+
if (v && v.ok !== false && Array.isArray(v.days)) { setCloudUsage(v); setCloudUsageErr(""); }
|
|
1759
|
+
else { setCloudUsage(null); setCloudUsageErr((v && v.error) || "云端用量明细不可用"); }
|
|
1760
|
+
}).catch(err => { setCloudUsage(null); setCloudUsageErr(String(err && err.message ? err.message : err)); });
|
|
1761
|
+
}
|
|
1580
1762
|
function loadKimi(force) {
|
|
1581
1763
|
apiCall("kimi-usage", { force: !!force }).then(v => setKimi(v)).catch(() => {});
|
|
1582
1764
|
}
|
|
@@ -1604,13 +1786,14 @@ window.__ModuleLoader__.load({
|
|
|
1604
1786
|
else setUsageErr(v && v.error ? String(v.error) : "数据加载失败");
|
|
1605
1787
|
}).catch(err => setUsageErr(String(err && err.message ? err.message : err)));
|
|
1606
1788
|
apiCall("kimi-usage", { force: false }).then(v => setKimi(v)).catch(() => {});
|
|
1789
|
+
loadCloudUsage(view);
|
|
1607
1790
|
apiCall("balance", {}).then(v => { setBalance(v); setBusy(false); }).catch(() => setBusy(false));
|
|
1608
1791
|
}
|
|
1609
1792
|
|
|
1610
1793
|
useEffect(() => { loadDash(days); }, [days]);
|
|
1611
1794
|
useEffect(() => { loadKimi(false); loadBalance(""); loadUsage(); loadSync(); }, []);
|
|
1612
|
-
// 视图切换:local+cloud
|
|
1613
|
-
useEffect(() => { loadCloud(days, view); loadCloudMatrix(days); }, [view, days]);
|
|
1795
|
+
// 视图切换:local+cloud 需要额外拉「排除本机」的云端聚合、矩阵与按天用量明细
|
|
1796
|
+
useEffect(() => { loadCloud(days, view); loadCloudMatrix(days); loadCloudUsage(view); }, [view, days]);
|
|
1614
1797
|
useEffect(() => {
|
|
1615
1798
|
const id = setInterval(() => setNow(Date.now()), 30000);
|
|
1616
1799
|
return () => clearInterval(id);
|
|
@@ -1623,6 +1806,18 @@ window.__ModuleLoader__.load({
|
|
|
1623
1806
|
: view === "cloud"
|
|
1624
1807
|
? cloudNorm
|
|
1625
1808
|
: (cloudNorm ? mergeDash(dash, cloudNorm) : dash);
|
|
1809
|
+
// 热力图同样跟随三态视图:本机 / 本机+云端 / 仅云端。
|
|
1810
|
+
// 云端明细取不到时退回本机,并在标题右侧注明口径,避免与上方卡片数字打架。
|
|
1811
|
+
const viewUsage = view === "local"
|
|
1812
|
+
? usage
|
|
1813
|
+
: view === "cloud"
|
|
1814
|
+
? cloudUsage
|
|
1815
|
+
: (usage && cloudUsage ? mergeUsageHeat(usage, cloudUsage) : (cloudUsage || usage));
|
|
1816
|
+
const usageScope = view === "local"
|
|
1817
|
+
? "本机"
|
|
1818
|
+
: view === "cloud"
|
|
1819
|
+
? ("仅云端" + (cloudUsageErr ? "(" + cloudUsageErr + ")" : ""))
|
|
1820
|
+
: (cloudUsage ? "本机 + 云端(不重复计数)" : "本机(云端明细加载中或不可用)");
|
|
1626
1821
|
const cloudAvailable = !!(sync && sync.enabled && sync.hasToken);
|
|
1627
1822
|
const viewCtl = {
|
|
1628
1823
|
view, setView, dimension, setDimension,
|
|
@@ -1646,7 +1841,7 @@ window.__ModuleLoader__.load({
|
|
|
1646
1841
|
sync && sync.enabled && sync.pending > 0 && view !== "local"
|
|
1647
1842
|
? e("div", { className: "cost-cloudnote" },
|
|
1648
1843
|
"本机还有 " + sync.pending + " 条尚未同步,云端数字会偏小 —— ",
|
|
1649
|
-
e("button", { className: "cost-btn", onClick: () => { apiCall("sync-now", {}).then(() => { loadSync(); loadCloud(days, view); loadCloudMatrix(days); }); } }, "立即同步"))
|
|
1844
|
+
e("button", { className: "cost-btn", onClick: () => { apiCall("sync-now", {}).then(() => { loadSync(); loadCloud(days, view); loadCloudMatrix(days); loadCloudUsage(view); }); } }, "立即同步"))
|
|
1650
1845
|
: null,
|
|
1651
1846
|
cloudErr && view !== "local"
|
|
1652
1847
|
? e("div", { className: "cost-err", style: { marginTop: "6px" } }, "云端数据不可用(已显示本机数据):" + cloudErr)
|
|
@@ -1660,9 +1855,12 @@ window.__ModuleLoader__.load({
|
|
|
1660
1855
|
view !== "local" && dimension !== "total" && viewDash ? dimensionPanel(viewDash, dimension, cloudMatrix, loadingCloud => loadingCloud) : null,
|
|
1661
1856
|
viewDash ? mainPanel(viewDash, tab, setTab, scheme, setScheme) : null,
|
|
1662
1857
|
e("div", { className: "cost-panel" },
|
|
1663
|
-
e("div", { className: "cost-row" },
|
|
1858
|
+
e("div", { className: "cost-row" },
|
|
1859
|
+
e("span", { className: "cost-panel-title" }, "Token 用量统计"),
|
|
1860
|
+
e("span", { className: "cost-spacer" }),
|
|
1861
|
+
e("span", { className: "cost-hint" }, usageScope)),
|
|
1664
1862
|
e("div", { style: { marginTop: "8px" } },
|
|
1665
|
-
|
|
1863
|
+
viewUsage ? e(UsageHeatmap, { data: viewUsage })
|
|
1666
1864
|
: usageErr ? e("div", { className: "cost-err" }, "加载失败:" + usageErr)
|
|
1667
1865
|
: e("div", { className: "cost-hint" }, "加载中…"))),
|
|
1668
1866
|
subPanel(kimi, viewDash, now, () => loadKimi(true)),
|
|
@@ -1725,7 +1923,12 @@ window.__ModuleLoader__.load({
|
|
|
1725
1923
|
e("span", { className: "cost-matrix-num" }, "¥" + fmtMoney((matrix.totals || {}).cost || 0))))));
|
|
1726
1924
|
}
|
|
1727
1925
|
|
|
1728
|
-
|
|
1926
|
+
/**
|
|
1927
|
+
* 输入框上方的花费胶囊(conversation.composer.dock)。
|
|
1928
|
+
* 显隐只在本部件内部判定:StatusLine 始终注册,快照说关就渲染 null ——
|
|
1929
|
+
* 用户改配置后无需重载页面(宿主不重启插件,插槽注册也无法撤销)。
|
|
1930
|
+
*/
|
|
1931
|
+
function CostDock(props) {
|
|
1729
1932
|
const sessionId = props && props.sessionId ? String(props.sessionId) : "";
|
|
1730
1933
|
const [s, setS] = useState(null);
|
|
1731
1934
|
const [expanded, setExpanded] = useState(false);
|
|
@@ -1736,9 +1939,12 @@ window.__ModuleLoader__.load({
|
|
|
1736
1939
|
}
|
|
1737
1940
|
load();
|
|
1738
1941
|
const id = setInterval(load, 30000);
|
|
1739
|
-
|
|
1942
|
+
const onUi = () => load();
|
|
1943
|
+
window.addEventListener(UI_EVENT, onUi);
|
|
1944
|
+
return () => { alive = false; clearInterval(id); window.removeEventListener(UI_EVENT, onUi); };
|
|
1740
1945
|
}, [sessionId]);
|
|
1741
1946
|
if (!s) return null;
|
|
1947
|
+
if (!uiOn(s.ui, "uiDockEnabled")) return null;
|
|
1742
1948
|
// 按会话实际内容决定显示(而不是按当前选中的模型):
|
|
1743
1949
|
// - realModels 按量模型 / subModels 订阅模型(分开)
|
|
1744
1950
|
// - 订阅只用一个着色徽标展示套餐名 + 总等效费用,订阅模型不再单独进模型区(避免重复)
|
|
@@ -1782,13 +1988,19 @@ window.__ModuleLoader__.load({
|
|
|
1782
1988
|
}
|
|
1783
1989
|
}
|
|
1784
1990
|
// 分段组装:主胶囊 | 订阅胶囊 | 模型胶囊(细竖线分隔,换行时自动分段)
|
|
1991
|
+
// hasReal 为假时(本会话还没有任何按量花费)不渲染主胶囊,避免出现 ¥0.0000 的空壳
|
|
1785
1992
|
const segs = [];
|
|
1786
|
-
segs.push(costPill);
|
|
1993
|
+
if (hasReal || !hasSub) segs.push(costPill);
|
|
1787
1994
|
if (subPill) segs.push(subPill);
|
|
1788
1995
|
if (modelPill) segs.push(modelPill);
|
|
1789
1996
|
return e("div", { className: "cost-dock" }, segs.map((seg, i) => e("span", { key: "seg" + i, className: "cost-seg" }, seg)));
|
|
1790
1997
|
}
|
|
1791
1998
|
|
|
1999
|
+
/** 插槽入口:插槽本身始终注册,显隐在 CostDock 内判定 */
|
|
2000
|
+
function StatusLine(props) {
|
|
2001
|
+
return e(CostDock, props || {});
|
|
2002
|
+
}
|
|
2003
|
+
|
|
1792
2004
|
const inject = ["slots"];
|
|
1793
2005
|
function apply(ctx) {
|
|
1794
2006
|
applyStyles(ctx);
|
|
@@ -1796,7 +2008,7 @@ window.__ModuleLoader__.load({
|
|
|
1796
2008
|
if (slots === undefined) return;
|
|
1797
2009
|
slots.inject("settings.section", () => slots.register(
|
|
1798
2010
|
{ name: "settings.section", id: "cost-dashboard", order: 30, label: "花费统计" },
|
|
1799
|
-
() => e(
|
|
2011
|
+
() => e(DashGate, {}),
|
|
1800
2012
|
));
|
|
1801
2013
|
// 插件配置卡片(设置 → 插件 → 插件配置):以 settings 命名空间为键。
|
|
1802
2014
|
// 这里必须**无条件** inject,不能拿 slots.entries(key).length 当"插槽是否存在"的探测:
|
package/config.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// ============================================================
|
|
2
2
|
// DSH 花费统计插件 —— 配置层(纯逻辑,可独立测试)
|
|
3
3
|
//
|
|
4
|
-
//
|
|
4
|
+
// 三部分配置同存于 $DSH_HOME/storages/cost-tracker-config.json:
|
|
5
5
|
// 1. 峰谷计价提示(peak*):默认值与参考项目 dsh-cost-meter 保持一致;
|
|
6
|
-
// 2. 云端同步(cloud* / sync* / boardView
|
|
6
|
+
// 2. 云端同步(cloud* / sync* / boardView):多机汇总与设备身份;
|
|
7
|
+
// 3. 界面显示(ui*):前端各落点的显隐(本文件末尾有说明)。
|
|
7
8
|
//
|
|
8
9
|
// 字段(峰谷):
|
|
9
10
|
// peakEnabled 启用 DeepSeek 峰谷时段价格(影响计费 + 提示显隐)
|
|
@@ -36,6 +37,19 @@
|
|
|
36
37
|
// 于是「本机可见数据 + 云端结果」= 本机全部 + 其他整机 + 本机其它 agent(不重不漏)
|
|
37
38
|
// cloudPanelDevices 云端视图的机器过滤(空数组 = 全部)
|
|
38
39
|
// lastSyncAt/lastSyncOk/lastSyncError 最近一次同步结果(只读回显用)
|
|
40
|
+
//
|
|
41
|
+
// 字段(界面显示,v1.8.12):
|
|
42
|
+
// uiDockEnabled 输入框上方的「本会话花费」胶囊(conversation.composer.dock)
|
|
43
|
+
// uiPeakEnabled 侧边栏底部的峰谷时段条(sidebar.footer.action)
|
|
44
|
+
// uiDashboardEnabled 设置页左侧的「花费统计」看板入口(settings.section)
|
|
45
|
+
//
|
|
46
|
+
// 三者**互相独立**,且都只影响前端渲染,不影响记账、云端同步与 Agent 工具。
|
|
47
|
+
// 插件配置卡片(settings.plugin.item)不受这三个开关控制 —— 它必须始终可点,
|
|
48
|
+
// 否则关掉之后用户就没有入口再打开了。
|
|
49
|
+
//
|
|
50
|
+
// 真值语义与 peakEnabled 相反:null/undefined → true(显隐是从 v1.8.12 才有的新
|
|
51
|
+
// 能力,老配置文件里没有这几个键,必须保持默认全部可见),只有显式 false 才隐藏。
|
|
52
|
+
// 这样两个方向上都安全:老配置升级后界面不变,新配置关掉就是关掉。
|
|
39
53
|
// ============================================================
|
|
40
54
|
|
|
41
55
|
/** 默认峰谷计价生效时间(UTC;两档方案已即时生效,门控恒通过) */
|
|
@@ -84,6 +98,39 @@ export function defaultCloudConfig() {
|
|
|
84
98
|
/** 看板三态视图取值 */
|
|
85
99
|
export const BOARD_VIEWS = ['local', 'local+cloud', 'cloud']
|
|
86
100
|
|
|
101
|
+
/**
|
|
102
|
+
* 前端显隐开关(设置 → 插件 → 插件配置 → 花费统计 → 界面显示)。
|
|
103
|
+
* 每项声明:配置键、文案、说明,以及它在 DSH 里对应的插槽(便于对照宿主与测试)。
|
|
104
|
+
* 新增可控落点时只改这张表:服务端 normalize 与前端卡片都从它派生。
|
|
105
|
+
*/
|
|
106
|
+
export const UI_SURFACES = [
|
|
107
|
+
{
|
|
108
|
+
key: 'uiDockEnabled',
|
|
109
|
+
label: '输入框上方的花费胶囊',
|
|
110
|
+
desc: '本会话花费与模型明细(会话输入区上方)。关闭后输入区不再显示任何花费信息。',
|
|
111
|
+
slot: 'conversation.composer.dock',
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
key: 'uiPeakEnabled',
|
|
115
|
+
label: '侧边栏峰谷时段条',
|
|
116
|
+
desc: '侧边栏底部的当前档位 / 倒计时。关闭后峰谷切换弹窗与系统通知一并停用;只想留提醒不想要时段条时,请改用「峰谷计价与提示」里的提示开关。',
|
|
117
|
+
slot: 'sidebar.footer.action',
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
key: 'uiDashboardEnabled',
|
|
121
|
+
label: '设置页「花费统计」看板',
|
|
122
|
+
desc: '设置页左侧导航的花费统计入口与看板。关闭后该入口隐藏,插件仍照常记账并同步云端。',
|
|
123
|
+
slot: 'settings.section',
|
|
124
|
+
},
|
|
125
|
+
]
|
|
126
|
+
|
|
127
|
+
/** 界面显示默认配置(全部可见;老配置文件里没有这几个键,读出来就是 true) */
|
|
128
|
+
export function defaultUiConfig() {
|
|
129
|
+
const out = {}
|
|
130
|
+
for (const s of UI_SURFACES) out[s.key] = true
|
|
131
|
+
return out
|
|
132
|
+
}
|
|
133
|
+
|
|
87
134
|
function bool(v, fallback) { return typeof v === 'boolean' ? v : fallback }
|
|
88
135
|
function intIn(v, lo, hi, fallback) { return typeof v === 'number' && Number.isInteger(v) && v >= lo && v <= hi ? v : fallback }
|
|
89
136
|
|
|
@@ -143,9 +190,21 @@ export function normalizeCloudConfig(raw) {
|
|
|
143
190
|
}
|
|
144
191
|
}
|
|
145
192
|
|
|
146
|
-
/**
|
|
193
|
+
/**
|
|
194
|
+
* 规范化界面显示开关(显隐真值见文件头的说明:缺省/非布尔 → 可见)。
|
|
195
|
+
* @param {object} raw - 任意输入
|
|
196
|
+
*/
|
|
197
|
+
export function normalizeUiConfig(raw) {
|
|
198
|
+
const def = defaultUiConfig()
|
|
199
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return def
|
|
200
|
+
const out = {}
|
|
201
|
+
for (const s of UI_SURFACES) out[s.key] = bool(raw[s.key], def[s.key])
|
|
202
|
+
return out
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** 合并规范化:一份配置文件同时承载峰谷、云端同步与界面显示三组字段 */
|
|
147
206
|
export function normalizePluginConfig(raw) {
|
|
148
|
-
return Object.assign(normalizePeakConfig(raw), normalizeCloudConfig(raw))
|
|
207
|
+
return Object.assign(normalizePeakConfig(raw), normalizeCloudConfig(raw), normalizeUiConfig(raw))
|
|
149
208
|
}
|
|
150
209
|
|
|
151
210
|
/**
|
package/index.js
CHANGED
|
@@ -14,12 +14,13 @@ import { PRICE_ERAS, V41_EFFECTIVE_AT, V41_PRO_ROUTE_AT, exactModelsAt, eraAt, S
|
|
|
14
14
|
import {
|
|
15
15
|
normalizePeakConfig, defaultPeakConfig, peakEffective,
|
|
16
16
|
normalizeCloudConfig, defaultCloudConfig, normalizePluginConfig,
|
|
17
|
+
normalizeUiConfig, defaultUiConfig, UI_SURFACES,
|
|
17
18
|
} from './config.js'
|
|
18
19
|
import { createSyncEngine, setPluginVersion, SOURCE as SYNC_SOURCE, SYNC_VERSION, loadIdentity } from './sync.js'
|
|
19
20
|
import { Schema } from './schema.js'
|
|
20
21
|
|
|
21
22
|
/** 插件版本(写入上报信封,便于云端排查版本差异) */
|
|
22
|
-
const PLUGIN_VERSION = '1.8.
|
|
23
|
+
const PLUGIN_VERSION = '1.8.13'
|
|
23
24
|
setPluginVersion(PLUGIN_VERSION)
|
|
24
25
|
|
|
25
26
|
/** 「设置 → 插件 → 插件配置」里的卡片字段(与 settings 命名空间一致) */
|
|
@@ -35,6 +36,10 @@ const SyncSchema = Schema.object({
|
|
|
35
36
|
syncRollups: Schema.boolean().default(undefined).description('上报历史日汇总快照'),
|
|
36
37
|
syncSinceDays: Schema.natural().default(undefined).description('补传起始窗口天数(0 = 不限)'),
|
|
37
38
|
cloudView: Schema.string().default(undefined).description('看板视图:local / local+cloud / cloud'),
|
|
39
|
+
// 界面显示(v1.8.12):三个前端落点各自显隐,缺省/非布尔 = 可见
|
|
40
|
+
uiDockEnabled: Schema.boolean().default(undefined).description('显示输入框上方的花费胶囊'),
|
|
41
|
+
uiPeakEnabled: Schema.boolean().default(undefined).description('显示侧边栏峰谷时段条'),
|
|
42
|
+
uiDashboardEnabled: Schema.boolean().default(undefined).description('显示设置页「花费统计」看板'),
|
|
38
43
|
})
|
|
39
44
|
|
|
40
45
|
// ============================================================
|
|
@@ -57,6 +62,48 @@ function startupLog(msg) {
|
|
|
57
62
|
// ============================================================
|
|
58
63
|
const NAV_ICON_BRANCH = 'if (id === "cost-dashboard") return (0, react_jsx_runtime.jsxs)("svg", { className: SettingsRoot_module_css_default.navIcon, width: 16, height: 16, viewBox: "0 0 16 16", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [(0, react_jsx_runtime.jsx)("rect", { x: 1.5, y: 8.6, width: 3.1, height: 5.9, rx: 0.9, fill: "currentColor" }), (0, react_jsx_runtime.jsx)("rect", { x: 5.9, y: 5.2, width: 3.1, height: 9.3, rx: 0.9, fill: "currentColor" }), (0, react_jsx_runtime.jsxs)("g", { fill: "none", stroke: "currentColor", strokeWidth: 1.3, strokeLinecap: "round", strokeLinejoin: "round", children: [(0, react_jsx_runtime.jsx)("path", { d: "M10.7 4.9 L12.3 7.2 L13.9 4.9" }), (0, react_jsx_runtime.jsx)("path", { d: "M12.3 7.2 L12.3 10.9" }), (0, react_jsx_runtime.jsx)("path", { d: "M10.9 7.8 L13.7 7.8" }), (0, react_jsx_runtime.jsx)("path", { d: "M10.9 9.5 L13.7 9.5" })] })] }); // cost-tracker-icon-patch\n\t\t\t'
|
|
59
64
|
|
|
65
|
+
// ============================================================
|
|
66
|
+
// 云端按天用量明细 → 「Token 用量统计」热力图形状(纯函数,跨仓库 e2e 直接单测)
|
|
67
|
+
//
|
|
68
|
+
// 形状与本地 buildUsageHeat() 一致:
|
|
69
|
+
// { ok, source, asOf, days: [{date,input,output,cacheRead,cacheWrite,calls,cost,tokens}],
|
|
70
|
+
// total: {tokens, input, cache, output, calls, cost} }
|
|
71
|
+
//
|
|
72
|
+
// tokens 一律按 input+output+cacheRead+cacheWrite **重算**:云端 byDay 的 tokens 含
|
|
73
|
+
// reasoning,而本地 buildUsageHeat 不含 —— 直接相加会让「本机+云端」比两侧之和大一截。
|
|
74
|
+
// ============================================================
|
|
75
|
+
export function cloudUsageHeat(body, mode) {
|
|
76
|
+
const n = (v) => Number(v) || 0
|
|
77
|
+
const days = ((body && body.byDay) || []).map((d) => {
|
|
78
|
+
const input = n(d.input), output = n(d.output), cacheRead = n(d.cacheRead), cacheWrite = n(d.cacheWrite)
|
|
79
|
+
return {
|
|
80
|
+
date: String(d.date), input, output, cacheRead, cacheWrite,
|
|
81
|
+
calls: n(d.calls), cost: n(d.cost),
|
|
82
|
+
tokens: input + output + cacheRead + cacheWrite,
|
|
83
|
+
}
|
|
84
|
+
// 云端 range=all 返回的是**连续日期轴**(首条记录到今天,含大量补零日),
|
|
85
|
+
// 而本地 buildUsageHeat 只返回有数据的日期。这里对齐本地语义:丢掉全零日,
|
|
86
|
+
// 否则合并后的 days 会多出几百个空格(热力图自己会按 26 周补格,不需要它们)。
|
|
87
|
+
}).filter((d) => d.tokens > 0 || d.calls > 0 || d.cost > 0)
|
|
88
|
+
const sum = (k) => days.reduce((s, d) => s + (d[k] || 0), 0)
|
|
89
|
+
const r4 = (x) => Math.round((Number(x) || 0) * 10000) / 10000
|
|
90
|
+
return {
|
|
91
|
+
ok: true,
|
|
92
|
+
source: 'cloud',
|
|
93
|
+
asOf: Date.now(),
|
|
94
|
+
cloudMode: mode,
|
|
95
|
+
days,
|
|
96
|
+
total: {
|
|
97
|
+
tokens: sum('tokens'),
|
|
98
|
+
input: sum('input'),
|
|
99
|
+
cache: sum('cacheRead') + sum('cacheWrite'),
|
|
100
|
+
output: sum('output'),
|
|
101
|
+
calls: sum('calls'),
|
|
102
|
+
cost: r4(sum('cost')),
|
|
103
|
+
},
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
60
107
|
export function ensureNavIconPatch(opts) {
|
|
61
108
|
const log = (opts && opts.log) || (() => {})
|
|
62
109
|
try {
|
|
@@ -175,6 +222,7 @@ export default {
|
|
|
175
222
|
const CONFIG_FILE = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'storages', 'cost-tracker-config.json')
|
|
176
223
|
let peakConfig = defaultPeakConfig()
|
|
177
224
|
let cloudConfig = defaultCloudConfig()
|
|
225
|
+
let uiConfig = defaultUiConfig()
|
|
178
226
|
let configLoadWarned = false
|
|
179
227
|
|
|
180
228
|
function loadConfig() {
|
|
@@ -183,6 +231,7 @@ export default {
|
|
|
183
231
|
const parsed = JSON.parse(readFileSync(CONFIG_FILE, 'utf8'))
|
|
184
232
|
peakConfig = normalizePeakConfig(parsed)
|
|
185
233
|
cloudConfig = normalizeCloudConfig(parsed)
|
|
234
|
+
uiConfig = normalizeUiConfig(parsed)
|
|
186
235
|
} catch (e) {
|
|
187
236
|
if (!configLoadWarned) { console.error('cost tracker config load failed, using defaults', e); configLoadWarned = true }
|
|
188
237
|
}
|
|
@@ -192,7 +241,7 @@ export default {
|
|
|
192
241
|
try {
|
|
193
242
|
mkdirSync(dirname(CONFIG_FILE), { recursive: true })
|
|
194
243
|
const tmp = CONFIG_FILE + '.tmp'
|
|
195
|
-
writeFileSync(tmp, JSON.stringify(Object.assign({}, peakConfig, cloudConfig)), 'utf8')
|
|
244
|
+
writeFileSync(tmp, JSON.stringify(Object.assign({}, peakConfig, cloudConfig, uiConfig)), 'utf8')
|
|
196
245
|
renameSync(tmp, CONFIG_FILE)
|
|
197
246
|
return true
|
|
198
247
|
} catch (e) {
|
|
@@ -213,6 +262,13 @@ export default {
|
|
|
213
262
|
return cloudConfig
|
|
214
263
|
}
|
|
215
264
|
|
|
265
|
+
/** 界面显示开关:显式写 false 才隐藏,缺省保持可见(老配置升级后界面不变) */
|
|
266
|
+
function setUiConfig(raw) {
|
|
267
|
+
uiConfig = normalizeUiConfig(Object.assign({}, uiConfig, raw))
|
|
268
|
+
saveConfig()
|
|
269
|
+
return uiConfig
|
|
270
|
+
}
|
|
271
|
+
|
|
216
272
|
// ---------- settings 命名空间(可选服务) ----------
|
|
217
273
|
// 字段全部 .default(undefined):只有用户在卡片里显式保存才写入用户层,
|
|
218
274
|
// 从而不覆盖我们自己配置文件里的既有值。
|
|
@@ -226,9 +282,25 @@ export default {
|
|
|
226
282
|
const patch = {}
|
|
227
283
|
for (const k of Object.keys(next)) if (next[k] !== undefined) patch[k] = next[k]
|
|
228
284
|
if (!Object.keys(patch).length) return
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
285
|
+
// 卡片里既有云端同步字段也有界面显示字段,分给各自的规范化函数(互不覆盖)
|
|
286
|
+
const cloudPatch = {}
|
|
287
|
+
const uiPatch = {}
|
|
288
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
289
|
+
if (UI_SURFACES.some((s) => s.key === k)) uiPatch[k] = v
|
|
290
|
+
else cloudPatch[k] = v
|
|
291
|
+
}
|
|
292
|
+
let changed = false
|
|
293
|
+
if (Object.keys(cloudPatch).length) {
|
|
294
|
+
const before = JSON.stringify(cloudConfig)
|
|
295
|
+
cloudConfig = normalizeCloudConfig(Object.assign({}, cloudConfig, cloudPatch))
|
|
296
|
+
if (JSON.stringify(cloudConfig) !== before) changed = true
|
|
297
|
+
}
|
|
298
|
+
if (Object.keys(uiPatch).length) {
|
|
299
|
+
const before = JSON.stringify(uiConfig)
|
|
300
|
+
uiConfig = normalizeUiConfig(Object.assign({}, uiConfig, uiPatch))
|
|
301
|
+
if (JSON.stringify(uiConfig) !== before) changed = true
|
|
302
|
+
}
|
|
303
|
+
if (changed) saveConfig()
|
|
232
304
|
}
|
|
233
305
|
|
|
234
306
|
function installSettingsSection(provider, owner) {
|
|
@@ -277,6 +349,8 @@ export default {
|
|
|
277
349
|
peakWindows: PEAK_WINDOWS,
|
|
278
350
|
peakHours: PEAK_HOUR_WINDOWS,
|
|
279
351
|
effectiveAt: peakConfig.peakEffectiveAt,
|
|
352
|
+
// 前端显隐开关(只影响渲染;与峰谷计价本身无关,因此不参与 enabled/effective 判定)
|
|
353
|
+
ui: Object.assign({}, uiConfig),
|
|
280
354
|
now,
|
|
281
355
|
}
|
|
282
356
|
}
|
|
@@ -922,7 +996,7 @@ export default {
|
|
|
922
996
|
// ---------- cloud sync ----------
|
|
923
997
|
// 同步引擎:只上报、不回写;失败只影响云端视图,绝不影响本地记账。
|
|
924
998
|
const syncEngine = createSyncEngine({
|
|
925
|
-
getConfig: () => Object.assign({}, peakConfig, cloudConfig),
|
|
999
|
+
getConfig: () => Object.assign({}, peakConfig, cloudConfig, uiConfig),
|
|
926
1000
|
getSnapshot: () => ({
|
|
927
1001
|
details: records,
|
|
928
1002
|
rollups,
|
|
@@ -1054,8 +1128,9 @@ export default {
|
|
|
1054
1128
|
}
|
|
1055
1129
|
}
|
|
1056
1130
|
}
|
|
1057
|
-
|
|
1058
|
-
|
|
1131
|
+
// union 并集:overview(卡片口径)与 plugin-view(按天/按模型图表口径)都支持;
|
|
1132
|
+
// 「本机+云端」的卡片走 overview、热力图走 plugin-view,各自取自己需要的范围。
|
|
1133
|
+
if (unionParts && (query.route === 'overview' || query.route === 'usage')) {
|
|
1059
1134
|
qs.set('union', JSON.stringify(unionParts))
|
|
1060
1135
|
} else if (mode === 'cloud-rest' && !selfKnown && selfId) {
|
|
1061
1136
|
qs.set('excludeDevice', selfId) // 拿不到本机记录时退化为「排除本机整台」
|
|
@@ -1072,7 +1147,13 @@ export default {
|
|
|
1072
1147
|
// · 带 union(「本机+云端」并集)时沿用 overview:其卡片是**全网**口径,与并集相加的
|
|
1073
1148
|
// 语义一致;plugin-view 的卡片落在并集范围内,换成它会让总额口径突变。
|
|
1074
1149
|
let endpoint = query.route
|
|
1075
|
-
if (query.route === '
|
|
1150
|
+
if (query.route === 'usage') {
|
|
1151
|
+
// 热力图要的是**按天明细 + token 类型拆分**,只有 plugin-view 有;
|
|
1152
|
+
// 且热力图是「全时段累计」口径,与页面上的区间选择无关,固定 range=all。
|
|
1153
|
+
endpoint = 'plugin-view'
|
|
1154
|
+
qs.set('range', 'all')
|
|
1155
|
+
qs.delete('days')
|
|
1156
|
+
} else if (query.route === 'overview' && !unionParts) {
|
|
1076
1157
|
const caps = await cloudCaps()
|
|
1077
1158
|
if (caps.pluginView) endpoint = 'plugin-view'
|
|
1078
1159
|
}
|
|
@@ -1089,14 +1170,16 @@ export default {
|
|
|
1089
1170
|
const out = { ok: false, error: hint || (body && body.error) || ('HTTP ' + res.status), code: (body && body.code) || (res.status === 404 ? 'CLOUD_TOO_OLD' : 'CLOUD_ERROR') }
|
|
1090
1171
|
return out
|
|
1091
1172
|
}
|
|
1092
|
-
const value =
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1173
|
+
const value = query.route === 'usage'
|
|
1174
|
+
? Object.assign(cloudUsageHeat(body, mode), { selfResolved: selfKnown, selfDeviceId: selfId, unionParts: unionParts })
|
|
1175
|
+
: Object.assign({}, body, {
|
|
1176
|
+
source: 'cloud',
|
|
1177
|
+
asOf: Date.now(),
|
|
1178
|
+
cloudMode: mode,
|
|
1179
|
+
selfResolved: selfKnown,
|
|
1180
|
+
selfDeviceId: selfId,
|
|
1181
|
+
unionParts: unionParts,
|
|
1182
|
+
})
|
|
1100
1183
|
cloudCache.set(key, { at: Date.now(), value })
|
|
1101
1184
|
return value
|
|
1102
1185
|
} catch (e) {
|
|
@@ -1118,7 +1201,10 @@ export default {
|
|
|
1118
1201
|
usage: () => buildUsageHeat(),
|
|
1119
1202
|
peak: () => peakSnapshot(),
|
|
1120
1203
|
'peak-config': (args) => setPeakConfig(args),
|
|
1121
|
-
|
|
1204
|
+
// 界面显示三开关(设置卡片的「界面显示」分组):patch 里只带这几个键,写回后原样回显
|
|
1205
|
+
'ui-config': (args) => Object.assign({ ok: true }, setUiConfig(args || {})),
|
|
1206
|
+
// 同步状态里一并带上界面显示开关:配置卡片只需一次往返就能初始化表单
|
|
1207
|
+
sync: () => Object.assign({}, syncEngine.status(), uiConfig),
|
|
1122
1208
|
'sync-now': async (args) => {
|
|
1123
1209
|
const result = await syncEngine.runOnce({ manual: true, full: !!(args && args.full) })
|
|
1124
1210
|
return Object.assign({ ok: result.ok !== false || !result.error, result }, syncEngine.status())
|
|
@@ -1320,13 +1406,23 @@ export default {
|
|
|
1320
1406
|
}
|
|
1321
1407
|
if (scope === 'cloud' || scope === 'both') {
|
|
1322
1408
|
const c = await fetchCloud({ route: 'overview', range: days === 0 ? 'all' : '7d', days })
|
|
1409
|
+
// 云端响应有两种形状,必须都认:
|
|
1410
|
+
// · /api/v1/overview → 金额摊在 c.summary.{realCost,subEquivalent,...}
|
|
1411
|
+
// · /api/v1/plugin-view → 没有 summary,字段直接摊在顶层(宿主在云端支持
|
|
1412
|
+
// devicePluginView 时会优先用它)。1.8.11 只读了 c.summary,于是
|
|
1413
|
+
// scope=cloud|both 必然抛 "Cannot read properties of undefined (reading 'realCost')"。
|
|
1414
|
+
const s = (c && c.summary) ? c.summary : (c || {})
|
|
1415
|
+
const num = (v) => Number(v) || 0
|
|
1323
1416
|
out.cloud = c.ok === false
|
|
1324
1417
|
? { ok: false, error: c.error || '云端不可用' }
|
|
1325
1418
|
: {
|
|
1326
1419
|
ok: true,
|
|
1327
|
-
realCost:
|
|
1328
|
-
|
|
1329
|
-
|
|
1420
|
+
realCost: num(s.realCost != null ? s.realCost : s.real),
|
|
1421
|
+
realCalls: num(s.realCalls != null ? s.realCalls : s.calls),
|
|
1422
|
+
realTokens: num(s.realTokens != null ? s.realTokens : s.tokens),
|
|
1423
|
+
subEquivalent: num(s.subEquivalent != null ? s.subEquivalent : s.sub),
|
|
1424
|
+
subCalls: num(s.subCalls),
|
|
1425
|
+
peakCost: num(s.peakCost), offCost: num(s.offCost), flatCost: num(s.flatCost),
|
|
1330
1426
|
devices: c.devices, sources: c.sources, asOf: c.asOf,
|
|
1331
1427
|
}
|
|
1332
1428
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@angelyeye/dsh-cost-tracker",
|
|
3
|
-
"version": "1.8.
|
|
3
|
+
"version": "1.8.13",
|
|
4
4
|
"description": "DeepSeek Harness (DSH) plugin: LLM token usage & cost tracking with a settings dashboard, agent tools, HTTP API, persistent storage and multi-device cloud sync.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"./package.json": "./package.json"
|
|
24
24
|
},
|
|
25
25
|
"scripts": {
|
|
26
|
-
"test": "node test/storage.test.js && node test/pricing.test.js && node test/config.test.js && node test/recompute.test.js && node test/client-registration.test.js && node test/client-render.test.js && node test/cloud-read.test.js && node --no-warnings test/cloud-view-e2e.test.js && node test/sync.test.js && node test/view.test.js"
|
|
26
|
+
"test": "node test/storage.test.js && node test/pricing.test.js && node test/config.test.js && node test/recompute.test.js && node test/client-registration.test.js && node test/ui-display.test.js && node test/client-render.test.js && node test/cloud-read.test.js && node --no-warnings test/cloud-view-e2e.test.js && node test/sync.test.js && node test/view.test.js"
|
|
27
27
|
},
|
|
28
28
|
"keywords": [
|
|
29
29
|
"dsh-plugin",
|
package/view.js
CHANGED
|
@@ -179,6 +179,61 @@ export function mergeDash(local, cloud) {
|
|
|
179
179
|
});
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
+
// ------------------------------------------------------------
|
|
183
|
+
// 「Token 用量统计」热力图的跨视图合并
|
|
184
|
+
//
|
|
185
|
+
// 形状与宿主 buildUsageHeat() 的返回值一致:
|
|
186
|
+
// { ok, days: [{date, input, output, cacheRead, cacheWrite, calls, cost, tokens}],
|
|
187
|
+
// total: {tokens, input, cache, output, calls, cost} }
|
|
188
|
+
//
|
|
189
|
+
// 两条口径约定(否则合并后屏内自相矛盾):
|
|
190
|
+
// · 按天 tokens 一律重算为 input+output+cacheRead+cacheWrite —— 本地 buildUsageHeat
|
|
191
|
+
// 就是这个口径;云端 byDay 的 tokens 含 reasoning,直接相加会与本地不同源。
|
|
192
|
+
// · total 用两份数据的**全时段** total 相加,而不是对 days 求和:本地 days 只保留最近
|
|
193
|
+
// 27 周,云端 days 覆盖全部历史,只有各自的 total 才是真正的「累计」。
|
|
194
|
+
// ------------------------------------------------------------
|
|
195
|
+
export function mergeUsageHeat(local, cloud) {
|
|
196
|
+
if (!cloud || !Array.isArray(cloud.days)) return local || null;
|
|
197
|
+
if (!local || !Array.isArray(local.days)) return cloud;
|
|
198
|
+
const per = new Map();
|
|
199
|
+
const add = (d) => {
|
|
200
|
+
if (!d || !d.date) return;
|
|
201
|
+
const cur = per.get(d.date) || { date: d.date, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, calls: 0, cost: 0, tokens: 0 };
|
|
202
|
+
cur.input += d.input || 0;
|
|
203
|
+
cur.output += d.output || 0;
|
|
204
|
+
cur.cacheRead += d.cacheRead || 0;
|
|
205
|
+
cur.cacheWrite += d.cacheWrite || 0;
|
|
206
|
+
cur.calls += d.calls || 0;
|
|
207
|
+
cur.cost += d.cost || 0;
|
|
208
|
+
cur.tokens = cur.input + cur.output + cur.cacheRead + cur.cacheWrite;
|
|
209
|
+
per.set(d.date, cur);
|
|
210
|
+
};
|
|
211
|
+
for (const d of local.days) add(d);
|
|
212
|
+
for (const d of cloud.days) add(d);
|
|
213
|
+
const days = Array.from(per.values())
|
|
214
|
+
.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0))
|
|
215
|
+
.map((d) => Object.assign({}, d, { cost: r4(d.cost) }));
|
|
216
|
+
const lt = local.total || {};
|
|
217
|
+
const ct = cloud.total || {};
|
|
218
|
+
const n = (v) => Number(v) || 0;
|
|
219
|
+
return {
|
|
220
|
+
ok: true,
|
|
221
|
+
source: "merged",
|
|
222
|
+
days,
|
|
223
|
+
total: {
|
|
224
|
+
tokens: n(lt.tokens) + n(ct.tokens),
|
|
225
|
+
input: n(lt.input) + n(ct.input),
|
|
226
|
+
cache: n(lt.cache) + n(ct.cache),
|
|
227
|
+
output: n(lt.output) + n(ct.output),
|
|
228
|
+
calls: n(lt.calls) + n(ct.calls),
|
|
229
|
+
cost: r4(n(lt.cost) + n(ct.cost)),
|
|
230
|
+
},
|
|
231
|
+
asOf: cloud.asOf || 0,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function r4(x) { return Math.round((Number(x) || 0) * 10000) / 10000; }
|
|
236
|
+
|
|
182
237
|
// ------------------------------------------------------------
|
|
183
238
|
// 浏览器 bundle 注册(client.js 通过 require("./view") 取用)
|
|
184
239
|
// ------------------------------------------------------------
|
|
@@ -187,7 +242,7 @@ if (typeof window !== "undefined" && window.__ModuleLoader__ && typeof window.__
|
|
|
187
242
|
window.__ModuleLoader__.load({
|
|
188
243
|
id: "@angelyeye/dsh-cost-tracker/view",
|
|
189
244
|
factory: () => ({
|
|
190
|
-
BOARD_VIEWS, BOARD_DIMS, zeroSlice, addSlice, r2, normalizeCloudDash, mergeDash, cloudSlices,
|
|
245
|
+
BOARD_VIEWS, BOARD_DIMS, zeroSlice, addSlice, r2, normalizeCloudDash, mergeDash, cloudSlices, mergeUsageHeat,
|
|
191
246
|
}),
|
|
192
247
|
});
|
|
193
248
|
}
|