@feiyang666/dsh-usage-plugin 1.9.2 → 1.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -8,10 +8,40 @@
8
8
 
9
9
  ---
10
10
 
11
+ ## 开源贡献基础:合并 PR #6(@Martin-soaring-dev,2026-08-20)
12
+
13
+ > 本期(以及后续 v1.9.2 / v1.9.3)建立在社区贡献分支 **`Martin-soaring-dev/prepare_for_contribution`** 之上。该分支由用户上传、经你合并(GitHub Pull Request #6,合并 commit `12a52be`),是插件转向对外开源贡献的形态基础。
14
+
15
+ ### 该分支带来的主要改动
16
+ - **多服务商余额查询**(`lib/balance.js` 新增 +205 行,新增余额适配器 `BalanceProviderAdapter`):将原先仅 DeepSeek 的 `/user/balance` 查询扩展为可对接多个服务商的余额查询框架,新增 DeepSeek / SiliconFlow / DigitalOcean / AMD GPU Cloud 等 Provider 适配器。
17
+ - **按服务商展示余额与价格**(`lib/client.js` +258 行):客户端新增「剩余余额查询」Tab 的多服务商 UI,可分别展示各服务商的「总余额 / 充值 / 赠送」并切换查看。
18
+ - **Provider 化计费**(`lib/index.js` +399 行重构):注入 `settings` 服务用于服务商查找,调用计费改为 provider-aware,支持按不同服务商分别统计与计价。
19
+ - **插件装配与测试**:新增余额适配器单测(`test/balance.test.js`,+130 行)、`scripts/wire.js` 手动装配兜底、`cordis.patch.yml` 插件注册条目。
20
+
21
+ ### 致谢
22
+ - **[@Martin-soaring-dev](https://github.com/Martin-soaring-dev)**:提交并筹备了上述开源贡献分支(PR #6),是后续公开发布版本的功能与结构基础。
23
+
24
+ ---
25
+
26
+ ## v1.9.4 (2026-08-20)
27
+
28
+ - **持久化不再落到工作目录(修复「数据又进了工作区」的反馈)**:之前插件的落盘走的是模型侧沙箱化的 `fs` 服务,在 `workspace-write` 模式下会被限制只能写工作区;当系统/用户目录因沙箱不可写时,数据会兜底写进 `<工作区>/dsh-usage`,于是切换工作区又出现「数据没了」的现象(即 issue #4 的本质)。
29
+ - **改动**:持久化改为由插件**宿主进程自身的 `node:fs`** 直接完成,完全绕过 `workspace-write` 沙箱约束。数据根解析优先级变为 `DSH_USAGE_DATA_DIR` > `%LOCALAPPDATA%\dsh-usage-plugin`(或 `%APPDATA%`)> `~/dsh-usage-data`,**工作区降级为绝对最后的兜底**,正常桌面环境下数据稳定落在 AppData / 用户主目录,与当前工作区无关,切换工作区不再丢失历史。导出、价格表、`.keep` 等写操作同样改为宿主进程 `node:fs`,不再依赖受沙箱子进程。
30
+ - **数据迁移**:原有 4558 条历史记录位于 `<工作区>/dsh-usage/usage-records.json`,首次以新版本启动时会被自动去重合并进新的固定数据根(`%LOCALAPPDATA%\dsh-usage-plugin\dsh-usage\usage-records.json`),无需手动处理。
31
+
32
+ ## v1.9.3 (2026-08-20)
33
+
34
+ - **概览支持日期筛选**:概览 Tab 顶部新增筛选栏,可按「今天 / 近 7 天 / 近 30 天 / 全部」快速切换,或自定义起止日期区间;所有聚合统计(按模型表、服务商 × 模型明细、总计)均按所选范围实时计算,并展示当前范围的记录数与总消耗。
35
+ - **文档**:新增「如何更新插件」章节——桌面端 / 命令行 / 手动三种更新方式、版本锁定、已装版本校验,并提示**勿手改 `node_modules` 下文件**(每次更新会被 npm 覆盖)。
36
+
11
37
  ## v1.9.2 (2026-08-20)
12
38
 
13
39
  > 修复 issue #4:持久化路径随会话工作区漂移,导致历史用量数据"消失/统计为 0",且 UI 显示路径与实际落盘路径不一致。
14
40
 
41
+ ### 背景(症状与根因)
42
+ - **症状**:切换会话工作区、或用不同工作区重开桌面端后,统计页的「历史用量 / 总消耗」变成 0、仿佛数据丢失;同时统计页顶部显示的「数据持久化」路径,与磁盘上真实写入的文件路径对不上。
43
+ - **根因**:旧版持久化根按 `agent.session.cwd` / `sandboxPolicy.workspaceRoot` 推导——无会话启动时常解析到用户主目录,插件激活后又切到当前工作区,且不同根之间不会互相合并,于是历史被「切走」到另一个目录而读不到;写盘还会受工作区沙箱策略约束。
44
+
15
45
  ### 修复
16
46
  - **固定专用数据目录**:持久化根不再跟随 `agent.session.cwd` / `sandboxPolicy.workspaceRoot` 漂移。解析顺序为:环境变量 `DSH_USAGE_DATA_DIR` > 系统应用数据目录 `%LOCALAPPDATA%\dsh-usage-plugin`(仅 Windows;macOS/Linux 下该分支不生效,因 `LOCALAPPDATA`/`APPDATA` 未定义)> 用户主目录下专用文件夹 `~/dsh-usage-data`(Windows 为 `%USERPROFILE%\dsh-usage-data`,macOS/Linux 为 `~/dsh-usage-data`)。该目录独立于桌面端安装目录、`~/.dsh` 主目录与任何会话工作区,删除工作区或卸载 APP 都不会丢失数据。
17
47
  - **启动时合并去重**:首次初始化与会话激活时,自动把散落在用户主目录、`.dsh`、各工作区旧路径里的 `usage-records.json` 按 `time` 去重合并进固定根(复用现有 `normalizeRecord`),不再只读当前根的那一份。
package/README.md CHANGED
@@ -32,7 +32,7 @@ dsh-usage-plugin is a **usage & cost tracker** plugin in the DeepSeek Harness ec
32
32
 
33
33
  > Supports **Windows / macOS / Linux**: paths are handled per platform (`node:path`), and the folder picker / "reveal in file manager" use each OS's native mechanism (macOS: `osascript` / `open`; Linux: `zenity` / `xdg-open`). Balance query and export do not depend on Windows-only commands.
34
34
 
35
- - **Usage & Cost**: records each model call's token usage and cache hits (input miss / cache hit / cache write / output / reasoning / finish reason), and computes cost using DeepSeek's peak/valley or base pricing (peak hours are automatically priced by Beijing time 09:00–12:00 and 14:00–18:00). Model names come from the actual request parameters, so non-DeepSeek models are shown truthfully instead of "unknown model"; models without an official price are counted as 0. The overview shows a by-model table plus a by-API-provider × model drill-down (each provider grouped with every model's calls and peak/off-peak cost split) and a grand total row.
35
+ - **Usage & Cost**: records each model call's token usage and cache hits (input miss / cache hit / cache write / output / reasoning / finish reason), and computes cost using DeepSeek's peak/valley or base pricing (peak hours are automatically priced by Beijing time 09:00–12:00 and 14:00–18:00). Model names come from the actual request parameters, so non-DeepSeek models are shown truthfully instead of "unknown model"; models without an official price are counted as 0. The overview shows a by-model table plus a by-API-provider × model drill-down (each provider grouped with every model's calls and peak/off-peak cost split) and a grand total row. The overview also supports **date filtering** (Today / Last 7 days / Last 30 days / All, plus a custom start–end range), so the aggregate stats can be scoped to any single day or date range.
36
36
  - **Usage Calendar**: a monthly daily-usage heatmap (colored by cost or call count), hover for details including the peak/off-peak cost split, click a day for its call list and peak/off-peak totals, plus a per-day statistics table with peak cost / off-peak cost / total columns and monthly rollups.
37
37
  - **Cache Hit List**: newest-first, fully scrollable, with quick filters (Today / 7 days / 30 days / All) and custom date ranges; the summary line and footer total split peak vs off-peak consumption with a grand cost total. The list is paginated (100 rows per page), so it stays smooth even with large data volumes.
38
38
  - **Price Table**: the official DeepSeek API price table — base and peak/valley unit prices shown side by side (peak vs off-peak), editable in-panel and persisted to `pricing.json`, with a reset-to-default option.
@@ -193,15 +193,55 @@ For manual installs (Method B), do it in reverse: remove the `usage-plugin` row
193
193
 
194
194
  ---
195
195
 
196
+ ## How to update
197
+
198
+ Releasing happens on npm, so updating just means pulling the latest published package. Your usage history is **safe** — since v1.9.2 it lives in a fixed dedicated directory (not in any profile / workspace), so an update never wipes it.
199
+
200
+ ### Desktop app
201
+ Open **"Install Plugins"** → find **Usage & Cost Tracker** → click **Update** (or **Re-install**) → **"Restart Service Now"**. If there is no Update button, just remove then re-add it.
202
+
203
+ ### Command line (Method A)
204
+ Re-running `add` is idempotent and pulls the newest version:
205
+
206
+ ```bash
207
+ dsh plugin --profile web add @feiyang666/dsh-usage-plugin
208
+ dsh web # restart
209
+ ```
210
+
211
+ Pin a specific version:
212
+
213
+ ```bash
214
+ dsh plugin --profile web add @feiyang666/dsh-usage-plugin@1.9.3
215
+ ```
216
+
217
+ ### Manual install (Method B)
218
+ In the profile dir:
219
+
220
+ ```bash
221
+ cd ~/.dsh/profiles/web
222
+ pnpm update @feiyang666/dsh-usage-plugin # or: npm update @feiyang666/dsh-usage-plugin
223
+ ```
224
+
225
+ ### Verify the installed version
226
+ ```bash
227
+ npm ls @feiyang666/dsh-usage-plugin --prefix ~/.dsh/profiles/web
228
+ ```
229
+
230
+ > ⚠️ **Do not hand-edit files under `~/.dsh/profiles/web/node_modules/@feiyang666/dsh-usage-plugin/`** (e.g. `lib/index.js` / `lib/client.js`). Every update re-extracts the package from npm and overwrites those files, so local edits are silently lost. To change behavior, fork the repo and publish your own version, or contribute upstream.
231
+
232
+ ---
233
+
196
234
  ## Data & locations
197
235
 
198
236
  > **Since v1.9.2**, records are stored in a **fixed, dedicated data directory** (fixes [#4](https://github.com/feiyang-dev/dsh-usage-plugin/issues/4)). The path no longer follows the session workspace / `~/.dsh` / desktop-app install dir, so your history never "disappears" (counted as 0) when the workspace changes, and the path shown in the UI equals the on-disk path.
199
237
 
200
238
  - **Records**: `<data root>/dsh-usage/usage-records.json`
201
- - Resolution order for the **data root**:
239
+ - Resolution order for the **data root** (data always lands in the **first writable** dir of this list, **never in the workspace** unless all of the below are unwritable):
202
240
  1. env var `DSH_USAGE_DATA_DIR` (if set) — overrides everything;
203
241
  2. Windows: `%LOCALAPPDATA%\dsh-usage-plugin` (falls back to `%APPDATA%` if `LOCALAPPDATA` is unset);
204
- 3. user home dir: `~/dsh-usage-data` (Windows `%USERPROFILE%\dsh-usage-data`, macOS/Linux `~/dsh-usage-data`).
242
+ 3. user home dir: `~/dsh-usage-data` (Windows `%USERPROFILE%\dsh-usage-data`, macOS/Linux `~/dsh-usage-data`);
243
+ 4. **fallback (rare)**: current workspace `<workspace>/dsh-usage` — only used when all system/user dirs above are unwritable, and the panel will show a "persistence disabled" warning.
244
+ - **Writes bypass the model sandbox**: persistence is done by the host plugin process's own filesystem, not subject to the `workspace-write` sandbox, so the fixed directory is always writable and data is not lost when switching workspaces.
205
245
  - Default on Windows: `%LOCALAPPDATA%\dsh-usage-plugin\dsh-usage\usage-records.json`
206
246
  - **Legacy data auto-merge**: on first start, records previously scattered in `%USERPROFILE%\dsh-usage`, `~/.dsh/dsh-usage`, and each workspace's `dsh-usage` (or `.dsh-usage-records.json`) are merged into the fixed root, deduplicated by `time` — no manual migration needed.
207
247
  - Price config (edited & saved in the panel): `<data root>/dsh-usage/pricing.json`
@@ -259,6 +299,7 @@ pnpm dsh web
259
299
 
260
300
  ## Acknowledgements
261
301
 
302
+ - **[@Martin-soaring-dev](https://github.com/Martin-soaring-dev)**: prepared the plugin for public contribution (packaging, plugin-contract checks, docs & CI) and submitted the contribution branch that became the basis for the open-source releases ([#6](https://github.com/feiyang-dev/dsh-usage-plugin/pull/6)).
262
303
  - **[@mumuer1024](https://github.com/mumuer1024)**: reported and diagnosed the persistence-path drift across workspaces (history "disappearing" / counted as 0) and proposed storing data in a fixed, dedicated directory ([#4](https://github.com/feiyang-dev/dsh-usage-plugin/issues/4)).
263
304
  - **[@liu3734](https://github.com/liu3734)**: reported and diagnosed the Windows-only path handling / spawn issues on macOS (POSIX) and proposed the cross-platform fix ([#1](https://github.com/feiyang-dev/dsh-usage-plugin/issues/1)).
264
305
 
package/README.zh.md CHANGED
@@ -32,14 +32,14 @@ dsh-usage-plugin 是 DeepSeek Harness 生态的**用量与消耗统计插件**
32
32
 
33
33
  > 支持 **Windows / macOS / Linux**:路径按当前平台处理(`node:path`),目录选择与「打开所在目录」均调用系统原生方式(macOS 用 `osascript` / `open`,Linux 用 `zenity` / `xdg-open`),余额查询与导出不依赖 Windows 专用命令。
34
34
 
35
- - **用量与消耗**:记录每次模型调用的 token 用量与缓存命中(输入·未命中 / 缓存命中 / 缓存写入 / 输出 / 推理 / 结束原因),按 DeepSeek 峰谷/基础价格计算消耗(高峰时段自动按北京时间 9:00–12:00、14:00–18:00 计价)。模型名以请求参数为准如实显示(非 DeepSeek 模型不再显示为「未知模型」,无官方价格的模型消耗按 0 统计)。概览含「按模型」表与「按 API 服务商 × 模型」明细表(每个服务商一组,组内列出各模型的调用与高峰/空闲分列消耗),底部有总费用合计。
35
+ - **用量与消耗**:记录每次模型调用的 token 用量与缓存命中(输入·未命中 / 缓存命中 / 缓存写入 / 输出 / 推理 / 结束原因),按 DeepSeek 峰谷/基础价格计算消耗(高峰时段自动按北京时间 9:00–12:00、14:00–18:00 计价)。模型名以请求参数为准如实显示(非 DeepSeek 模型不再显示为「未知模型」,无官方价格的模型消耗按 0 统计)。概览含「按模型」表与「按 API 服务商 × 模型」明细表(每个服务商一组,组内列出各模型的调用与高峰/空闲分列消耗),底部有总费用合计。概览还支持**日期筛选**(今天 / 近 7 天 / 近 30 天 / 全部,外加自定义起止区间),可将聚合统计限定到任意一天或日期范围。
36
36
  - **用量日历**:按月查看每日用量热力图(按消耗或调用数着色),悬停查看详情(含高峰 / 空闲消耗拆分)、点击某天查看当日调用明细与高峰/空闲消耗统计,附本月每日统计表(高峰消耗 / 空闲消耗 / 总消耗分列)与月度汇总。
37
37
  - **缓存命中列表**:最新记录排在最前,支持 今天 / 近7天 / 近30天 / 全部 快捷筛选与自定义起止日期区间,汇总行与表尾合计区分高峰消耗 / 空闲消耗 / 总费用合计;列表分页渲染(每页 100 条),记录量大也不卡顿。
38
38
  - **价格表**:**DeepSeek 官方 API 价格表**,展示基础价与峰谷价(高峰/空闲)单价表,高峰价与空闲价分列展示,支持在面板内直接编辑价格并持久化(数据目录 `pricing.json`),也可一键恢复默认。
39
39
  - **剩余余额查询**:用当前配置的 `DEEPSEEK_API_KEY` 查询 DeepSeek 账户余额。
40
40
  - **导出**:CSV / JSON / **PNG 长图**(按最新在前展示,最多含最近 2000 条,超出会提示;PNG 报告含高峰 / 空闲消耗分列统计),可导出到任意目录(原生目录选择器),导出后自动打开所在目录。
41
41
  - **导入**:选择文件(JSON / CSV)合并导入,按时间去重。
42
- - **持久化**:记录实时落盘到 `<会话工作区>/dsh-usage/usage-records.json`,重启自动恢复(上限 100000 条,尽量多存)。
42
+ - **持久化**:记录实时落盘到**固定专用数据目录**(如 `%LOCALAPPDATA%\dsh-usage-plugin\dsh-usage\usage-records.json`,详见下文「数据目录」),与当前工作区无关,重启自动恢复(上限 100000 条,尽量多存)。
43
43
  - **界面适配**:面板字号跟随应用「显示大小」设置自动缩放(em 相对字号),面板宽度以视口封顶、宽表格在容器内横向滑动(max-content + overflow-x),任何窗口大小下所有列与合计都完整可见,不会裁掉右侧内容。
44
44
 
45
45
  ---
@@ -193,15 +193,55 @@ dsh plugin --profile web remove @feiyang666/dsh-usage-plugin
193
193
 
194
194
  ---
195
195
 
196
+ ## 如何更新插件
197
+
198
+ 发布在 npm 上,因此更新本质就是把已发布的包拉到最新——你的用量历史**不会丢**(自 v1.9.2 起数据存放在固定的专用目录,不位于任何 profile / 工作区,更新不会清掉它)。
199
+
200
+ ### 桌面端
201
+ 打开 **「安装插件」** → 找到 **Usage & Cost Tracker** → 点 **更新**(或 **重新安装**)→ **「立即重启服务」**。若没有更新按钮,先卸载再重新安装即可。
202
+
203
+ ### 命令行(方式 A)
204
+ 重新执行 `add` 是幂等的,会拉取最新版本:
205
+
206
+ ```bash
207
+ dsh plugin --profile web add @feiyang666/dsh-usage-plugin
208
+ dsh web # 重启
209
+ ```
210
+
211
+ 锁定某个版本:
212
+
213
+ ```bash
214
+ dsh plugin --profile web add @feiyang666/dsh-usage-plugin@1.9.3
215
+ ```
216
+
217
+ ### 手动安装(方式 B)
218
+ 在 profile 目录下:
219
+
220
+ ```bash
221
+ cd ~/.dsh/profiles/web
222
+ pnpm update @feiyang666/dsh-usage-plugin # 或:npm update @feiyang666/dsh-usage-plugin
223
+ ```
224
+
225
+ ### 查看已装版本
226
+ ```bash
227
+ npm ls @feiyang666/dsh-usage-plugin --prefix ~/.dsh/profiles/web
228
+ ```
229
+
230
+ > ⚠️ **不要手动修改 `~/.dsh/profiles/web/node_modules/@feiyang666/dsh-usage-plugin/` 下的文件**(如 `lib/index.js` / `lib/client.js`)。每次更新都会从 npm 重新解包并覆盖这些文件,本地改动会被静默丢弃。如需改行为,请 fork 仓库自行发布版本或向上游提贡献。
231
+
232
+ ---
233
+
196
234
  ## 数据与位置
197
235
 
198
236
  > **自 v1.9.2 起**,记录存储在**固定专用数据目录**中(修复 [#4](https://github.com/feiyang-dev/dsh-usage-plugin/issues/4))。路径不再跟随会话工作区 / `~/.dsh` / 桌面端安装目录漂移,因此切换工作区时历史数据不会再"消失"(被统计为 0),且 UI 中显示的路径与真实落盘路径始终一致。
199
237
 
200
238
  - 数据文件:`<数据根>/dsh-usage/usage-records.json`
201
- - **数据根**的解析顺序:
239
+ - **数据根**的解析顺序(数据始终落在该顺序里**第一个可写**的目录,**不会放进工作区**,除非以下全部不可写):
202
240
  1. 环境变量 `DSH_USAGE_DATA_DIR`(若已设置)——优先级最高,覆盖其它;
203
241
  2. Windows:`%LOCALAPPDATA%\dsh-usage-plugin`(若 `LOCALAPPDATA` 未设置则回退到 `%APPDATA%`);
204
- 3. 用户主目录:`~/dsh-usage-data`(Windows 为 `%USERPROFILE%\dsh-usage-data`,macOS/Linux 为 `~/dsh-usage-data`)。
242
+ 3. 用户主目录:`~/dsh-usage-data`(Windows 为 `%USERPROFILE%\dsh-usage-data`,macOS/Linux 为 `~/dsh-usage-data`);
243
+ 4. **兜底(极少见)**:当前工作区 `<工作区>/dsh-usage` —— 仅当上述系统/用户目录都不可写时才使用,并会在面板顶部提示「持久化未启用」。
244
+ - **写入不经过模型沙箱**:持久化由插件宿主进程自身的文件系统直接完成,不受 `workspace-write` 沙箱约束,因此固定目录一定能正常写入,数据也不因工作区切换而丢失。
205
245
  - Windows 下默认位置:`%LOCALAPPDATA%\dsh-usage-plugin\dsh-usage\usage-records.json`
206
246
  - 旧数据自动合并:首次启动时,落在 `%USERPROFILE%\dsh-usage`、`~/.dsh/dsh-usage` 以及各工作区 `dsh-usage`(或 `.dsh-usage-records.json`)下的旧记录会按 `time` 去重合并进固定数据根,无需手动迁移。
207
247
  - 价格配置(面板内编辑后保存):`<数据根>/dsh-usage/pricing.json`
@@ -259,6 +299,7 @@ pnpm dsh web
259
299
 
260
300
  ## 致谢
261
301
 
302
+ - **[@Martin-soaring-dev](https://github.com/Martin-soaring-dev)**:筹备了插件开源贡献(打包、插件契约校验、文档与 CI),并提交贡献分支,成为后续开源版本的基础([#6](https://github.com/feiyang-dev/dsh-usage-plugin/pull/6))。
262
303
  - **[@mumuer1024](https://github.com/mumuer1024)**:报告并定位了持久化路径随会话工作区漂移导致历史数据"消失/统计为 0"的问题,提出把数据写到固定专用目录的方案([#4](https://github.com/feiyang-dev/dsh-usage-plugin/issues/4))。
263
304
  - **[@liu3734](https://github.com/liu3734)**:报告并定位 macOS(POSIX)下路径处理与 spawn 的 Windows 专用问题,提出跨平台修复方案([#1](https://github.com/feiyang-dev/dsh-usage-plugin/issues/1))。
264
305
 
package/lib/client.js CHANGED
@@ -409,7 +409,30 @@ window.__ModuleLoader__.load({
409
409
 
410
410
  // ── Overview view ──
411
411
  function OverviewView(props) {
412
- var records = props.records, regime = props.regime;
412
+ var allRecords = props.records, regime = props.regime;
413
+ var presetState = React.useState("all");
414
+ var preset = presetState[0], setPreset = presetState[1];
415
+ var fromState = React.useState("");
416
+ var fromDate = fromState[0], setFromDate = fromState[1];
417
+ var toState = React.useState("");
418
+ var toDate = toState[0], setToDate = toState[1];
419
+
420
+ var nowKey = bjKey(Date.now());
421
+ var fromMs = null, toMs = null;
422
+ if (preset === "today") { fromMs = bjStartMs(nowKey); toMs = Date.now(); }
423
+ else if (preset === "7d") { fromMs = bjStartMs(nowKey) - 6 * 86400000; toMs = Date.now(); }
424
+ else if (preset === "30d") { fromMs = bjStartMs(nowKey) - 29 * 86400000; toMs = Date.now(); }
425
+ else if (preset === "custom") {
426
+ if (fromDate) fromMs = bjStartMs(fromDate);
427
+ if (toDate) toMs = bjStartMs(toDate) + 86400000 - 1;
428
+ }
429
+ var records = [];
430
+ for (var fi = 0; fi < allRecords.length; fi++) {
431
+ var fr = allRecords[fi];
432
+ if (fromMs != null && fr.time < fromMs) continue;
433
+ if (toMs != null && fr.time > toMs) continue;
434
+ records.push(fr);
435
+ }
413
436
  var totalCalls = records.length;
414
437
  var totalHit = 0, totalMiss = 0, totalWrite = 0, totalOut = 0, totalReason = 0, totalCost = 0, peakTotal = 0, offTotal = 0, peakCalls = 0, offCalls = 0;
415
438
  var byModel = {}, byProvider = {}, byProviderModel = {};
@@ -519,7 +542,26 @@ window.__ModuleLoader__.load({
519
542
  el("td", { style: st.tdTotal }, fmtMoney(totalCost))
520
543
  ));
521
544
 
545
+ function presetBtn(k, label) {
546
+ return el("button", { style: preset === k ? st.segBtnOn : st.segBtn, onClick: function () { setPreset(k); } }, label);
547
+ }
548
+ function setCustomFrom(v) { setFromDate(v); setPreset("custom"); }
549
+ function setCustomTo(v) { setToDate(v); setPreset("custom"); }
550
+
522
551
  return el("div", null,
552
+ el("div", { style: st.calBar },
553
+ el("div", { style: st.seg },
554
+ presetBtn("today", "今天"), presetBtn("7d", "近7天"), presetBtn("30d", "近30天"), presetBtn("all", "全部")
555
+ ),
556
+ el("span", { style: st.note }, "自定义区间:"),
557
+ el("input", { type: "date", style: st.dateInput, value: fromDate, onChange: function (e) { setCustomFrom(e.target.value); } }),
558
+ el("span", { style: st.note }, "至"),
559
+ el("input", { type: "date", style: st.dateInput, value: toDate, onChange: function (e) { setCustomTo(e.target.value); } }),
560
+ (fromDate || toDate || preset !== "all") ? el("button", { style: st.btn, onClick: function () { setFromDate(""); setToDate(""); setPreset("all"); } }, "清除筛选") : null
561
+ ),
562
+ el("div", { style: st.note, marginTop: 8 },
563
+ "当前范围:共 " + fmtInt(records.length) + " 条" + (preset === "all" && !fromDate && !toDate ? "(全部记录)" : "") + " · 总消耗 " + fmtMoney(totalCost) + "(" + costHint(regime) + ")"
564
+ ),
523
565
  el("div", { style: st.cards },
524
566
  el(Card, { label: "调用次数", value: fmtInt(totalCalls), hint: "高峰 " + fmtInt(peakCalls) + " · 空闲 " + fmtInt(offCalls) }),
525
567
  el(Card, { label: "输入 · 未命中", value: fmtInt(totalMiss), hint: "token" }),
package/lib/index.js CHANGED
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import path from 'node:path'
18
18
  import os from 'node:os'
19
+ import { promises as fsp, existsSync } from 'node:fs'
19
20
  import {
20
21
  getBalanceProvider,
21
22
  matchesModelProvider,
@@ -167,6 +168,14 @@ export default {
167
168
  return IS_WIN ? s.replace(/\//g, '\\') : s
168
169
  }
169
170
  const joinPath = (...parts) => path.join(...parts.map((p) => String(p == null ? '' : p)))
171
+ // 插件自身持久化统一走宿主进程的 node:fs(不经 ctx.fs 沙箱),
172
+ // 因此可稳定写入工作区之外的系统目录,切换工作区也不会丢失历史。
173
+ const nfsWriteText = async (filePath, content) => {
174
+ await fsp.mkdir(path.dirname(filePath), { recursive: true })
175
+ await fsp.writeFile(filePath, content, 'utf8')
176
+ }
177
+ const nfsReadText = async (filePath) => fsp.readFile(filePath, 'utf8')
178
+ const nfsExists = (filePath) => { try { return existsSync(filePath) } catch (e) { return false } }
170
179
  const stamp = () => {
171
180
  const d = new Date()
172
181
  return `${d.getFullYear()}${pad2(d.getMonth() + 1)}${pad2(d.getDate())}-${pad2(d.getHours())}${pad2(d.getMinutes())}${pad2(d.getSeconds())}`
@@ -265,31 +274,21 @@ export default {
265
274
  }
266
275
 
267
276
  function persistNow() {
268
- if (!fs || !dataPath || !persistOk) return Promise.resolve()
277
+ if (!dataPath || !persistOk) return Promise.resolve()
269
278
  const text = JSON.stringify(records)
270
- const policy = undefined
271
- writeChain = writeChain.then(() =>
272
- fs.resolve(dataPath).then((target) =>
273
- fs.writeText(target, text, undefined, undefined, policy || undefined)
274
- )
275
- ).catch(() => {})
279
+ writeChain = writeChain.then(() => nfsWriteText(dataPath, text)).catch(() => {})
276
280
  return writeChain
277
281
  }
278
282
 
279
283
  function persistPricing() {
280
- if (!fs || !pricingPath || !persistOk) return Promise.resolve()
281
- const text = JSON.stringify(PRICING)
282
- const policy = undefined
283
- return fs.resolve(pricingPath)
284
- .then((target) => fs.writeText(target, text, undefined, undefined, policy || undefined))
285
- .catch(() => {})
284
+ if (!pricingPath || !persistOk) return Promise.resolve()
285
+ return nfsWriteText(pricingPath, JSON.stringify(PRICING)).catch(() => {})
286
286
  }
287
287
 
288
- async function loadPricing(policy) {
289
- if (!fs || !pricingPath) return
288
+ async function loadPricing() {
289
+ if (!pricingPath) return
290
290
  try {
291
- const target = await fs.resolve(pricingPath)
292
- const data = JSON.parse(await fs.readText(target))
291
+ const data = JSON.parse(await nfsReadText(pricingPath))
293
292
  if (!data || typeof data !== 'object') return
294
293
  for (const regime of ['base', 'peakValley']) {
295
294
  const src = data[regime]
@@ -328,31 +327,33 @@ export default {
328
327
  }
329
328
  }
330
329
 
331
- async function tryInitWithRoot(candidate, policy) {
330
+ async function tryInitWithRoot(candidate) {
332
331
  const tryPath = joinPath(normPath(candidate), 'dsh-usage', 'usage-records.json')
333
332
  try {
334
- const target = await fs.resolve(tryPath)
335
- const arr = JSON.parse(await fs.readText(target))
336
- if (Array.isArray(arr) && arr.length > 0) {
337
- const existing = {}
338
- for (let i = 0; i < records.length; i++) existing[records[i].time] = true
339
- for (let i = 0; i < arr.length; i++) {
340
- const rec = normalizeRecord(arr[i])
341
- if (!rec || existing[rec.time]) continue
342
- existing[rec.time] = true
343
- records.push(rec)
333
+ if (nfsExists(tryPath)) {
334
+ const arr = JSON.parse(await nfsReadText(tryPath))
335
+ if (Array.isArray(arr) && arr.length > 0) {
336
+ const existing = {}
337
+ for (let i = 0; i < records.length; i++) existing[records[i].time] = true
338
+ for (let i = 0; i < arr.length; i++) {
339
+ const rec = normalizeRecord(arr[i])
340
+ if (!rec || existing[rec.time]) continue
341
+ existing[rec.time] = true
342
+ records.push(rec)
343
+ }
344
+ if (records.length > MAX_RECORDS) records.splice(0, records.length - MAX_RECORDS)
345
+ records.sort((a, b) => a.time - b.time)
344
346
  }
345
- if (records.length > MAX_RECORDS) records.splice(0, records.length - MAX_RECORDS)
346
- records.sort((a, b) => a.time - b.time)
347
347
  }
348
348
  } catch (e) {}
349
349
  try {
350
- const target = await fs.resolve(tryPath)
351
- await fs.writeText(target, JSON.stringify(records), undefined, undefined, policy || undefined)
350
+ // 真实试写以确认该目录可写;用宿主进程的 node:fs,不受 workspace-write
351
+ // 沙箱约束,因此活动数据根会落在工作区之外的系统/用户目录。
352
+ await nfsWriteText(tryPath, JSON.stringify(records))
352
353
  root = normPath(candidate)
353
354
  dataPath = tryPath
354
355
  pricingPath = joinPath(path.dirname(dataPath), 'pricing.json')
355
- await loadPricing(policy)
356
+ await loadPricing()
356
357
  persistOk = true
357
358
  persistError = ''
358
359
  return { ok: true }
@@ -362,7 +363,6 @@ export default {
362
363
  }
363
364
 
364
365
  async function migrateLegacy(candidates) {
365
- if (!fs) return
366
366
  const paths = []
367
367
  for (const c of candidates) {
368
368
  paths.push(joinPath(normPath(c), '.dsh-usage-records.json'))
@@ -370,7 +370,8 @@ export default {
370
370
  }
371
371
  for (const p of paths) {
372
372
  try {
373
- const arr = JSON.parse(await fs.readText(await fs.resolve(p)))
373
+ if (!nfsExists(p)) continue
374
+ const arr = JSON.parse(await nfsReadText(p))
374
375
  if (Array.isArray(arr)) {
375
376
  const existing = {}
376
377
  for (let j = 0; j < records.length; j++) existing[records[j].time] = true
@@ -387,17 +388,27 @@ export default {
387
388
  }
388
389
  }
389
390
 
390
- // 固定、专用的数据目录:不随工作区漂移,也不放在 DSH 主目录(~/.dsh)或
391
- // 桌面端安装目录。优先级:环境变量 DSH_USAGE_DATA_DIR >
392
- // 系统应用数据目录(AppData/Local~/Library/Application Support) >
391
+ // 固定、专用的数据目录:不随工作区漂移,也绝不放进工作目录。
392
+ // 优先级:环境变量 DSH_USAGE_DATA_DIR >
393
+ // 系统应用数据目录(LOCALAPPDATAAPPDATA 下的 dsh-usage-plugin) >
393
394
  // 用户主目录下的专用文件夹 dsh-usage-data。
395
+ // 这些目录由宿主进程 node:fs 直接写入,不受 workspace-write 沙箱约束,
396
+ // 因此数据稳定地落在工作区之外——切换工作区也不会丢失历史。
397
+ // 仅在以上目录全部不可写时,才兜底写到工作区(极少见,且会提示用户)。
394
398
  function resolveDataRoot() {
395
399
  const out = []
396
400
  const env = ((typeof process !== 'undefined' && process.env && process.env.DSH_USAGE_DATA_DIR) || '').trim()
397
401
  if (env) out.push(normPath(env))
398
- const appData = (typeof process !== 'undefined' && process.env) ? (process.env.LOCALAPPDATA || process.env.APPDATA) : ''
399
- if (appData) out.push(joinPath(normPath(appData), 'dsh-usage-plugin'))
402
+ const localApp = (typeof process !== 'undefined' && process.env) ? (process.env.LOCALAPPDATA || '') : ''
403
+ if (localApp) out.push(joinPath(normPath(localApp), 'dsh-usage-plugin'))
404
+ const roamingApp = (typeof process !== 'undefined' && process.env) ? (process.env.APPDATA || '') : ''
405
+ if (roamingApp) out.push(joinPath(normPath(roamingApp), 'dsh-usage-plugin'))
400
406
  out.push(joinPath(normPath(os.homedir()), 'dsh-usage-data'))
407
+ // 兜底(极少见):以上均不可写时落到工作区,保证不丢数据并提示用户。
408
+ try {
409
+ const sp = ctx.get('sandboxPolicy')
410
+ if (sp && sp.workspaceRoot) out.push(joinPath(normPath(String(sp.workspaceRoot)), 'dsh-usage'))
411
+ } catch (e) {}
401
412
  return out
402
413
  }
403
414
 
@@ -419,17 +430,16 @@ export default {
419
430
  // 会话激活后不再切换根目录(避免路径漂移/历史被拆散);仅把工作区里
420
431
  // 可能遗留的旧记录并入固定的数据根。
421
432
  async function ensureSessionRoot() {
422
- if (!fs || !persistOk) return
433
+ if (!persistOk) return
423
434
  await migrateLegacy(knownLegacyRoots())
424
435
  persistNow()
425
436
  }
426
437
 
427
438
  async function initPersistence() {
428
- if (!fs) { persistError = '文件服务不可用'; return }
429
439
  const candidates = resolveDataRoot()
430
440
  let lastError = ''
431
441
  for (const c of candidates) {
432
- const r = await tryInitWithRoot(c, undefined)
442
+ const r = await tryInitWithRoot(c)
433
443
  if (r.ok) {
434
444
  // 首次初始化时把散落在 主目录/.dsh/各工作区 的历史记录合并进来
435
445
  await migrateLegacy(knownLegacyRoots())
@@ -511,11 +521,10 @@ export default {
511
521
 
512
522
  // ── balance / network helpers ──────────────────────────────────────────
513
523
  async function safeCwd() {
514
- if (root && fs) {
524
+ if (root) {
515
525
  try {
516
- const t = await fs.resolve(root)
517
- const info = await fs.stat(t)
518
- if (info) return root
526
+ await fsp.stat(root)
527
+ return root
519
528
  } catch (e) {}
520
529
  }
521
530
  return (typeof process !== 'undefined' && typeof process.cwd === 'function' && process.cwd()) || '.'
@@ -861,41 +870,23 @@ export default {
861
870
  }
862
871
 
863
872
  async function writePngFile(base64, outPath) {
864
- const script = [
865
- 'const fs=require("fs");',
866
- 'let d="";',
867
- 'process.stdin.on("data",function(c){d+=c});',
868
- 'process.stdin.on("end",function(){',
869
- ' const buf=Buffer.from(d,"base64");',
870
- ' fs.mkdirSync(require("path").dirname(process.env.PNG_PATH),{recursive:true});',
871
- ' fs.writeFileSync(process.env.PNG_PATH,buf);',
872
- ' process.stdout.write(JSON.stringify({ok:true,bytes:buf.length}));',
873
- '});'
874
- ].join('\n')
875
- return spawnNode(script, base64, { PNG_PATH: outPath })
873
+ try {
874
+ await fsp.mkdir(path.dirname(outPath), { recursive: true })
875
+ await fsp.writeFile(outPath, Buffer.from(base64, 'base64'))
876
+ return { ok: true }
877
+ } catch (e) { return { ok: false, error: msg(e) } }
876
878
  }
877
879
 
878
880
  async function writeTextFileViaNode(content, outPath) {
879
- const script = [
880
- 'const fs=require("fs");',
881
- 'let d="";',
882
- 'process.stdin.on("data",function(c){d+=c});',
883
- 'process.stdin.on("end",function(){',
884
- ' fs.mkdirSync(require("path").dirname(process.env.OUT_PATH),{recursive:true});',
885
- ' fs.writeFileSync(process.env.OUT_PATH, Buffer.from(d,"utf8"));',
886
- ' process.stdout.write(JSON.stringify({ok:true}));',
887
- '});'
888
- ].join('\n')
889
- return spawnNode(script, content, { OUT_PATH: outPath })
881
+ try {
882
+ await fsp.mkdir(path.dirname(outPath), { recursive: true })
883
+ await fsp.writeFile(outPath, Buffer.from(content, 'utf8'))
884
+ return { ok: true }
885
+ } catch (e) { return { ok: false, error: msg(e) } }
890
886
  }
891
887
 
892
888
  async function mkdirViaNode(dir) {
893
- const script = [
894
- 'const fs=require("fs");',
895
- 'fs.mkdirSync(process.env.MKDIR_PATH,{recursive:true});',
896
- 'process.stdout.write(JSON.stringify({ok:true}));'
897
- ].join('\n')
898
- return spawnNode(script, null, { MKDIR_PATH: dir })
889
+ try { await fsp.mkdir(dir, { recursive: true }); return { ok: true } } catch (e) { return { ok: false, error: msg(e) } }
899
890
  }
900
891
 
901
892
  async function pickDirectory() {
@@ -949,10 +940,8 @@ export default {
949
940
  const d = dirs()
950
941
  target = dirArg === 'csv' ? d.csv : dirArg === 'json' ? d.json : dirArg === 'images' ? d.images : d.data
951
942
  target = normPath(target)
952
- const policy = sessionPolicy()
953
943
  try {
954
- const t = await fs.resolve(joinPath(target, '.keep'))
955
- await fs.writeText(t, '', undefined, undefined, policy || undefined)
944
+ await nfsWriteText(joinPath(target, '.keep'), '')
956
945
  } catch (e) {}
957
946
  } else {
958
947
  target = normPath(dirArg)
@@ -1044,7 +1033,7 @@ export default {
1044
1033
  case 'pickDir':
1045
1034
  return pickDirectory()
1046
1035
  case 'export': {
1047
- if (!root) return fail('未找到工作区路径')
1036
+ if (!root) return fail('未找到数据根目录')
1048
1037
  const kind = (body && body.kind) === 'json' ? 'json' : 'csv'
1049
1038
  const name = 'dsh-usage-' + stamp() + (kind === 'json' ? '.json' : '.csv')
1050
1039
  const content = kind === 'json'
@@ -1059,9 +1048,8 @@ export default {
1059
1048
  }
1060
1049
  const outPath = joinPath(kind === 'json' ? dirs().json : dirs().csv, name)
1061
1050
  try {
1062
- const target = await fs.resolve(outPath)
1063
- await fs.writeText(target, content, undefined, undefined, sessionPolicy() || undefined)
1064
- return { ok: true, path: normPath(fs.processPath ? fs.processPath(target) : outPath), name, dir: kind === 'json' ? 'json' : 'csv' }
1051
+ await nfsWriteText(outPath, content)
1052
+ return { ok: true, path: normPath(outPath), name, dir: kind === 'json' ? 'json' : 'csv' }
1065
1053
  } catch (e) { return fail(msg(e)) }
1066
1054
  }
1067
1055
  case 'exportPng': {
@@ -1069,7 +1057,7 @@ export default {
1069
1057
  if (!dataUrl) return fail('缺少图片数据')
1070
1058
  const idx = dataUrl.indexOf('base64,')
1071
1059
  const b64 = idx >= 0 ? dataUrl.slice(idx + 7) : dataUrl
1072
- if (!root) return fail('未找到工作区路径')
1060
+ if (!root) return fail('未找到数据根目录')
1073
1061
  const name = 'dsh-usage-report-' + stamp() + '.png'
1074
1062
  const dirArg = body && body.dir ? normPath(String(body.dir)) : ''
1075
1063
  const outPath = normPath(joinPath(dirArg || dirs().images, name))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feiyang666/dsh-usage-plugin",
3
- "version": "1.9.2",
3
+ "version": "1.9.4",
4
4
  "description": "DeepSeek Harness usage & cost tracker plugin: per-call token/cache-hit stats, peak/off-peak billing, DeepSeek balance query, CSV/JSON/PNG export with custom destination, and persistent local storage. Ships a host half plus a web client half in one npm package; installs into a DSH profile as a dsh.bundle with one command (dsh plugin --profile web add @feiyang666/dsh-usage-plugin).",
5
5
  "keywords": [
6
6
  "deepseek",
@@ -21,6 +21,10 @@
21
21
  "url": "git+https://github.com/feiyang-dev/dsh-usage-plugin.git"
22
22
  },
23
23
  "contributors": [
24
+ {
25
+ "name": "Martin-soaring-dev",
26
+ "url": "https://github.com/Martin-soaring-dev"
27
+ },
24
28
  {
25
29
  "name": "liu3734",
26
30
  "url": "https://github.com/liu3734"