@angelyeye/dsh-cost-tracker 1.8.10 → 1.8.11

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
@@ -2,6 +2,28 @@
2
2
 
3
3
  本文件用中文记录 dsh-cost-tracker 的版本变更。
4
4
 
5
+ ## v1.8.11(2026-09-17)
6
+
7
+ **新增:启动时检测「另一个 dsh 实例正在用同一份记录文件」并直接点名**
8
+
9
+ - **背景**:v1.8.10 的 EPERM 现场根因就是**上一个 dsh 实例还在跑,用户又起了一个** —— 两个实例写同一份 `cost-tracker-records.json`,互相覆盖,并在 Windows 上撞上 rename 的 EPERM(旧的临时文件名还是固定的 `<file>.tmp`,两实例必然互抢)。此前用户只能对着堆栈猜。
10
+ - **现在**:启动时在记录文件旁登记一把**仅用于提示**的实例锁(`cost-tracker-records.json.lock`,内含 pid / 版本 / 时间)。若锁的持有者**仍然存活**(`process.kill(pid, 0)`,Windows 上 EPERM 也算存活),立即打印占用者信息与处理办法:
11
+ ```
12
+ cost tracker: 检测到另一个 dsh 实例(PID 15784 · v1.8.10)正在使用同一份记录文件:
13
+ ~/.dsh/storages/cost-tracker-records.json
14
+ 两个实例会互相覆盖对方的记录,并可能在 Windows 上触发 rename EPERM(需要目标文件的删除权限)。
15
+ 请只保留一个 dsh 实例:先 Ctrl+C 停掉旧的,再启动新的。
16
+ ```
17
+ - **绝不阻断启动**:锁文件不存在 / 损坏 / 持有者已退出(陈旧锁)都静默跳过;退出时只删自己的锁,不碰别人的。
18
+ - **实测**(两个真实进程):holder 登记锁并保持存活 → 第二个实例输出 `{"lockHeldBy":15784,"warned":true}` 且 stderr 打印上面那段;holder 退出后残留的陈旧锁不影响后续启动。
19
+ - **测试**:`test/storage.test.js` 第 14 节新增 14 条断言(无锁 / 自己的锁 / 存活占用者 / 陈旧锁 / 不存在的 pid / 只删自己的锁 / 锁文件损坏不炸)。
20
+
21
+ **文档:两份 README 补齐长期漂移(无功能变更)**
22
+
23
+ - 英文 README 更新记录补齐 v1.8.7–v1.8.10(此前停在 v1.8.6)并补上缺失的 v1.3.0;「本机+云端」口径由过时的「服务端排除本机,因此不重复计数」更正为**并集**(其他整机 ∪ 本机上的非 dsh 来源);补「多机汇总(云端同步)」功能行与 `sync.js` / `view.js` / `schema.js`。
24
+ - 中文 README 设置页说明补「六组概览卡」「峰谷计价与提示」两条(此前只有英文版有);FAQ「重启会丢数据吗」补落盘遇瞬时占用的处理;同样补「多机汇总」功能行与三个源文件。
25
+ - 两份 README 的版本徽标改为 **npm 动态徽标**(不再是硬编码的 v1.6.0),以后发版自动跟随;更新记录标题下注明「只列重要版本,完整逐版记录见 `CHANGELOG.md`」。
26
+
5
27
  ## v1.8.10(2026-09-17)
6
28
 
7
29
  **修复:Windows 上落盘偶发 `EPERM`(rename 被瞬时占用),启动日志甩出吓人的堆栈**
package/README.en.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  [简体中文](./README.md) | **English**
8
8
 
9
- ![version](https://img.shields.io/badge/version-v1.6.0-blue?style=flat-square)
9
+ [![version](https://img.shields.io/npm/v/@angelyeye/dsh-cost-tracker?label=version&style=flat-square)](https://www.npmjs.com/package/@angelyeye/dsh-cost-tracker)
10
10
  ![license](https://img.shields.io/badge/license-MIT-green?style=flat-square)
11
11
  ![status](https://img.shields.io/badge/status-stable-brightgreen?style=flat-square)
12
12
  ![platform](https://img.shields.io/badge/platform-DSH%20Web-blueviolet?style=flat-square)
@@ -35,6 +35,7 @@
35
35
  | 👁️ | **Vision model** | Supports `deepseek-v4-flash-vision-exp`: priced as flash in the legacy era, billed at V4.1 Flash rates from 2026-09-10 12:00 (that legacy id is retired; requests are served by V4.1 Flash); images are converted to tokens per the official rule (≤384 tokens each, billed per API usage) |
36
36
  | 🏷️ | **Official model-name alignment** | Billing recognises the official current name **`deepseek-flash`** (price-card note (1): "use the model name `deepseek-flash`"); older spellings such as `deepseek-v4.1-flash` normalize to the same rate, so an official rename can never silently drop usage into the fallback estimate |
37
37
  | 📊 | **Visual dashboard** | A new "Cost Statistics" page in Settings: overview cards, cost bar charts (by peak period / by model), per-model request & token charts — **all with hover tooltips** |
38
+ | 🧭 | **Multi-machine aggregation (cloud sync)** | Point it at your own **self-hosted cloud service** (separate `dsh-cost-cloud` repo, zero runtime dependencies) to merge usage from several computers; the dashboard then offers a **This machine / This machine + cloud / Cloud only** switcher plus a **device × Agent matrix** (row totals = column totals = grand total). Only token counts, cost, timestamps and identifiers are uploaded, with optional session-id masking |
38
39
  | 📈 | **Subscription quota** | Kimi Coding Plan and similar subscriptions: weekly quota, 5-hour rolling window limit, pay-as-you-go-equivalent cost for reference |
39
40
  | 💳 | **Balance lookup** | One-click DeepSeek account balance (total / topped-up / granted / status) |
40
41
  | 🤖 | **Agent tools** | Ask in any chat: "how much have I spent today?" — the agent answers via `cost_stats` / `cost_prices` |
@@ -170,7 +171,7 @@ rm -rf ~/.dsh/profiles/node_modules/dsh-cost-tracker
170
171
  | `cost_prices` | Show the built-in price table & peak rules | "What does deepseek-v4-flash cost right now?" |
171
172
  | `cost_peak` | Show the current peak tier & next-switch countdown | "Is it peak hour right now?" |
172
173
  | `cost_recompute` | **Re-price stored records by pricing era (one-off backfill)**, dry-run by default | "Re-price the records from before the price change" |
173
- | `cost_sync` | **Cloud sync**: status / sync now / test connection / update config | "Sync my usage to the cloud" |
174
+ | `cost_sync` | **Cloud sync**: status / sync now / test connection / update config | "Sync my usage to the cloud" · "Is cloud sync healthy?" |
174
175
  | `cost_reset` | **Erase ALL statistics (irreversible)** | "Reset my cost statistics" |
175
176
 
176
177
  ### Multi-machine aggregation (cloud sync, v1.8.0)
@@ -199,9 +200,12 @@ Then hit `Test connection` → `Sync now`. Back in **Settings → Cost Tracker**
199
200
  | View | Meaning |
200
201
  | --- | --- |
201
202
  | **This machine** | local-only (identical to running without cloud sync) |
202
- | **This machine + cloud** | local **plus** other devices — the server excludes this machine, so nothing is double-counted |
203
+ | **This machine + cloud** | this machine + **all other devices** + **the other agents running on this machine** (server-side *union*, nothing double-counted) |
203
204
  | **Cloud only** | cloud records only (includes this machine's synced part) |
204
205
 
206
+ > The union behind "This machine + cloud" is `other devices` ∪ `non-DSH agents on this machine`.
207
+ > So with several machines and mixed agents: this machine's DSH numbers come from local storage, its ZCode/Codex (etc.) numbers come from the cloud, and every other computer comes from the cloud — the three add up to exactly the whole network, with nothing counted twice or missed.
208
+
205
209
  The dimension selector adds per-device / per-agent / per-model breakdowns and a **device × Agent matrix** (row totals = column totals = grand total).
206
210
 
207
211
  **Other agents can report too**: the ingest protocol is open. Any agent's stats plugin that implements `docs/INGEST-API.md` in the `dsh-cost-cloud` repo is aggregated with no server changes, and a new agent column shows up automatically.
@@ -237,6 +241,61 @@ Example: `curl -X POST http://127.0.0.1:3080/api/cost-tracker/summary -d '{}'`
237
241
 
238
242
  ## Changelog
239
243
 
244
+ > Highlights only — the full version-by-version history lives in [`CHANGELOG.md`](./CHANGELOG.md) (Chinese).
245
+
246
+ ### v1.8.11 (2026-09-17)
247
+
248
+ **Added: startup detection of "another dsh instance is using the same records file", reported by name**
249
+
250
+ - The root cause behind the v1.8.10 `EPERM` report was exactly this: **a previous `dsh` instance was still running when another was started**, so two instances wrote the same records file, overwrote each other, and tripped `rename`'s EPERM on Windows. Until now the only clue was a stack trace.
251
+ - On startup the plugin now registers a **advisory-only** instance lock next to the records file (`.lock`, holding pid / version). If the holder is still alive it prints the culprit and what to do (Ctrl+C the old instance first). It **never blocks startup**: a stale, corrupted or self-owned lock is ignored, and shutdown only removes its own lock.
252
+ - Verified with two real processes: the second instance printed `检测到另一个 dsh 实例(PID 15784 · v1.8.10)…` (detected another dsh instance) immediately.
253
+
254
+ **Docs: both READMEs caught up on long-standing drift (no functional change)**
255
+
256
+ - The English changelog was backfilled with v1.8.7–v1.8.10 (it had stopped at v1.8.6) plus the missing v1.3.0; the "This machine + cloud" semantics were corrected from the outdated "the server excludes this machine" to the actual **union** (other devices ∪ non-DSH agents on this machine); a "Multi-machine aggregation (cloud sync)" feature row and `sync.js` / `view.js` / `schema.js` were added (the feature table had no cloud entry at all).
257
+ - The Chinese README gained the two missing dashboard bullets (**Six overview cards**, **Peak-price notice**) and a note in the restart FAQ about transient write locks.
258
+ - Both READMEs now use a **dynamic npm version badge** (instead of a hardcoded v1.6.0), and the changelog heading points at `CHANGELOG.md` for the full history.
259
+
260
+ ### v1.8.10 (2026-09-17)
261
+
262
+ **Fixed: occasional `EPERM` on flush (a `rename` blocked by a transient lock) printing a scary stack trace**
263
+
264
+ - **Symptom**: restarting `dsh web` printed `cost tracker persist failed Error: EPERM: operation not permitted, rename '...cost-tracker-records.json.tmp' -> '...cost-tracker-records.json'` with a full stack. **No data was lost** (it was still in memory and the next flush succeeded), but it looked like a crash.
265
+ - **Root cause**: `persist()` is "write a temp file → `rename` over the target", but it **only tried once**. On Windows `rename` needs *delete* access to the target, which fails transiently when an antivirus/search indexer has just scanned the temp file, when Explorer preview or a backup/sync tool is reading it, or when a **previous `dsh` instance has not fully exited** (or two instances run at once). The temp file also used a fixed name (`<file>.tmp`), so two instances were guaranteed to collide on it.
266
+ - **Fix**: temp name now carries the **pid**; `rename` **retries with backoff** on `EPERM/EACCES/EBUSY` (20/40/80/160 ms, 5 attempts ≈ 0.35 s) while `ENOENT`-style errors are not retried; if it still fails the plugin does **not** fall back to an in-place overwrite (a concurrent reader could see half a JSON file, and `load()` treats that as corruption — renaming it to `.corrupt-*` and starting empty, which is far worse than a few seconds of delay) — the data stays in memory and is retried instead. `index.js` then schedules **3 more delayed retries** (2 s / 4 s / 6 s) and stays **silent until the retry chain is exhausted**, printing one clear "cause + impact" message instead of a stack. The final flush on shutdown gets 10 attempts (~2 s).
267
+ - **Verified** against a real Windows file lock (`[System.IO.File]::Open(..., FileShare.Read)`): a held lock → retries, then gives up with the **original file byte-identical**, no leftover temp file and a readable message; a lock released after 120 ms → the 3rd attempt succeeds with no intervention; quiet mode on failure → empty stderr.
268
+
269
+ ### v1.8.9 (2026-09-17)
270
+
271
+ **Wording fix: "平峰" → "不分峰谷" (flat / tier-independent), and the third legend item is hidden when it is zero**
272
+
273
+ - The peak/off-peak chart's third legend item was labelled 平峰 — a literal translation of the internal `period='flat'`. Official pricing has **only two tiers**: peak (Mon–Fri 9:00–12:00, 14:00–18:00 Beijing time) and off-peak (peak × 0.5, weekends fully off-peak). `flat` actually means "**this charge does not depend on the time of day**" (`price.tiered === false`: subscription plans, non-DeepSeek provider fallbacks, unknown-model generic rates). In Chinese electricity-tariff usage 平峰/平段 means a *third time-of-day tier*, so the label implied DeepSeek has three price tiers.
274
+ - It also occupied a legend slot and a colour swatch even when the whole window was 0 (the normal case when only DeepSeek pay-as-you-go calls are recorded), reinforcing the illusion.
275
+ - The legend, the "period" column of recent records and the `cost_peak` tool output now read **"不分峰谷"**, and the legend/chart only include the third series **when the window's flat total is > 0**. Billing logic and the `flat` field are unchanged.
276
+
277
+ ### v1.8.8 (2026-09-15)
278
+
279
+ **Fixed: the "Cloud only" view showed request counts but every amount as ¥0.0000 (field-name mismatch)**
280
+
281
+ - The cloud's `/api/v1/overview` returns `realCost` / `subEquivalent`, while the local dashboard and every card reads `real` / `sub`. The client-side normalization passed the fields straight through (and dropped `summary` entirely), so the amounts were all zero while `calls`/`tokens` — same names on both sides — survived. **The cloud fixture in the tests used `real/sub`, which hid the defect**; it now uses the real online shape.
282
+ - `view.js` gained `cloudSlices()` for per-field mapping (accepting `realCost/real`, `subCost/subEquivalent/sub` for backwards compatibility), with the inline fallback in `client.js` kept identical.
283
+
284
+ **Added: cloud `GET /api/v1/plugin-view` (device-token readable) so "Cloud only" can draw charts**
285
+
286
+ - The client needs `byDay / byModel / byModelDay / recent` to draw the cost chart, per-model detail and recent records; `/api/v1/overview` only returned the summary cards, so those panels were structurally empty. The new endpoint returns exactly the local `buildDashboard` shape and supports `union`.
287
+ - The plugin probes `/api/v1/health` capabilities and prefers `plugin-view`, falling back to `overview` on older cloud servers (cards work, charts stay empty) instead of failing outright.
288
+ - Fixed the same class of bug on the cloud side: `pluginView()`'s today/month/all slices were taken from an unfiltered table scan, **bypassing `excludeDevice`** (so "This machine + cloud" counted this machine twice); they now use the same filter, with `calls/tokens` holding pay-as-you-go only and subscriptions counted separately (`subCalls`/`subTokens`).
289
+
290
+ ### v1.8.7 (2026-09-15)
291
+
292
+ **Fixed: `cost_recompute` only scanned the most recent pricing era, silently skipping older stale records**
293
+
294
+ - After the v1.8.6 backfill, **750 `deepseek-flash` records were still flagged "estimated"** (timestamps 09-10 21:24 … 09-14 02:36): the default `since` was the start of the latest pricing era (`v41pro` = 09-14 12:00), so nothing before it was scanned — yet the tool reported "no records needed re-pricing".
295
+ - The default is now a **full-range scan (`since = 0`)**, and `since: 0` is correctly recognised as "all time" (the old `> 0` check fell through to the era default). In full-range mode `era` is reported as `null` instead of claiming a single era. The backfill is idempotent, so the extra scan is cheap.
296
+ - Measured locally: `scanned=1642 / changed=772 / estimatedFlips=750 / delta=0.0000`, and a second run reported `changed=0` — the "estimated" flag was cleared on 1643 `deepseek-flash` records with **amounts unchanged** (only the 5 Kimi subscription records stay estimated, which is correct).
297
+ - Hardening: `client-registration.test.js` now asserts that the `package.json` version equals `index.js`'s `PLUGIN_VERSION` (they had drifted in the v1.8.6 release).
298
+
240
299
  ### v1.8.6 (2026-09-15)
241
300
 
242
301
  **Fixed: two basis mismatches against DeepSeek's official pricing** (checked against the official [price card](https://api-docs.deepseek.com/zh-cn/quick_start/pricing) and the [V4.1 Flash announcement](https://api-docs.deepseek.com/zh-cn/news/news260910))
@@ -322,6 +381,24 @@ Example: `curl -X POST http://127.0.0.1:3080/api/cost-tracker/summary -d '{}'`
322
381
  **Fixed**
323
382
  - The preview popup was hardcoded to center; it now **follows your configured popup position** (bottom-right / center).
324
383
 
384
+ ### v1.3.0 (2026-08-23)
385
+
386
+ **New**
387
+ - **Token usage heatmap**: a "Token Usage" panel in Settings with a Codex-style **26-week daily-usage grid**, shaded into 4 levels by each day's token count relative to the maximum and stretched to the panel width; hover any cell for that day's breakdown (date / input / cache / output / cost), today outlined; all-time totals on top (`累计 X tokens · input · cache · output · N calls`). Adds `POST /api/cost-tracker/usage`. Date keys are always Beijing time (UTC+8), matching the server's bucketing.
388
+ - **Per-model split for the current session**: the status line breaks the session down by the models actually used, with subscriptions counted separately from pay-as-you-go.
389
+
390
+ **Improved**
391
+ - **Status line redesign**: a **segmented pill** layout (session / subscription plan / per-model), pipe-separated and baseline-aligned.
392
+ - **Session cost only**: no more cumulative amount or current peak/off-peak price.
393
+ - **Subscription de-duplication**: subscriptions appear once as a colored badge (plan name + total equivalent cost) instead of repeating in the model area.
394
+ - **Multi-model collapsing**: top-2 models plus a count by default; click `▸` to expand the full list.
395
+ - **Less noise**: quota leftovers and per-model call counts (`×N`) removed.
396
+ - **Visual consistency**: unified amount weight and colors.
397
+
398
+ **Fixed**
399
+ - The status line no longer depends on the "currently selected model"; it follows the models/subscriptions actually used in the session, fixing wrong figures when switching sessions and subscription sessions showing ¥0.
400
+ - The heatmap tooltip now repositions near the left/right/top edges instead of being clipped by the container.
401
+
325
402
  ---
326
403
 
327
404
  ## FAQ
@@ -330,7 +407,8 @@ Example: `curl -X POST http://127.0.0.1:3080/api/cost-tracker/summary -d '{}'`
330
407
  Everything stays on your machine in `~/.dsh/storages/cost-tracker-records.json`; nothing is uploaded. The API binds to loopback but has no authentication — **do not expose the DSH port to the public internet**.
331
408
 
332
409
  **Q: Do I lose data when DSH restarts?**
333
- No. Records are flushed to disk with debounced atomic writes and restored on startup. A corrupted file is backed up as `.corrupt-<timestamp>` and tracking restarts cleanly.
410
+ No. Records are flushed to disk with debounced atomic writes (temp file + `rename`) and restored on startup. A corrupted file is backed up as `.corrupt-<timestamp>` and tracking restarts cleanly.
411
+ If a flush hits a **transient lock** (on Windows: an antivirus/indexer/backup tool reading the file, or a previous `dsh` instance that has not exited yet) it **retries with backoff**; if the retries fail the data stays in memory and is retried later, and the existing file is **never left half-written**. If this keeps happening, make sure two DSH instances are not running at once.
334
412
 
335
413
  **Q: How long is history kept? Is there a stats cap?**
336
414
  Detail records are kept for the last **180 days**; older records are auto-compressed into **permanent daily rollups** (aggregates only: calls / token breakdown / cost — no per-call details). So all-time totals and per-model stats stay **exact forever**, while memory, disk and write volume stay bounded no matter how long you run. The daily chart axis spans up to 730 days. Old-format data files migrate automatically; set the `DSH_COST_TRACKER_STORE` env var to override the store path (default `$DSH_HOME/storages`, or `~/.dsh` when `DSH_HOME` is unset).
@@ -359,14 +437,20 @@ Either way: if only the UI (`client.js`) changed, a **hard browser refresh** (Cm
359
437
 
360
438
  ```
361
439
  ├── index.js Host half: usage capture, aggregation, HTTP API, agent tools
362
- ├── store.js Storage layer: 180-day detail retention + permanent daily rollups + persistence (pure logic, unit-testable)
440
+ ├── store.js Storage layer: 180-day detail retention + permanent daily rollups + atomic writes (with lock retries; pure logic, unit-testable)
363
441
  ├── pricing.js Pricing & tokens: price tables, peak/off-peak billing, vision model, peak-phase math (pure logic, unit-testable)
364
- ├── config.js Config layer: defaults & normalization for the peak-price notice (pure logic, unit-testable)
442
+ ├── config.js Config layer: defaults & normalization for the peak-price notice and cloud sync (pure logic, unit-testable)
443
+ ├── sync.js Cloud sync engine: device identity, incremental watermark, idempotent batches, backoff
444
+ ├── schema.js Host settings schema (the plugin-config card fields)
445
+ ├── view.js Three-state view merge: normalizes This machine / + cloud / Cloud only (shared by browser and tests)
365
446
  ├── client.js Client half: settings dashboard, status line & peak-price notice UI
366
447
  ├── package.json Plugin manifest: declares dsh.bundle (what makes it installable) and dsh.client (browser UI)
367
448
  ├── cordis.patch.yml Bundle patch: registers the plugin with DSH's loader, pointed at by dsh.bundle
368
449
  ├── screenshots.json Marketplace detail-page screenshot list (relative paths, 1-8 images)
369
- ├── test/ Unit tests (storage / pricing / config / recompute, node test/*.test.js)
450
+ ├── README.md Chinese documentation
451
+ ├── README.en.md English documentation
452
+ ├── CHANGELOG.md Changelog (Chinese)
453
+ ├── test/ Unit tests (storage / pricing / config / recompute / render / cloud read; node test/*.test.js)
370
454
  └── docs/ README screenshots and design notes
371
455
  ```
372
456
 
package/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  **简体中文** | [English](./README.en.md)
8
8
 
9
- ![version](https://img.shields.io/badge/version-v1.6.0-blue?style=flat-square)
9
+ [![version](https://img.shields.io/npm/v/@angelyeye/dsh-cost-tracker?label=version&style=flat-square)](https://www.npmjs.com/package/@angelyeye/dsh-cost-tracker)
10
10
  ![license](https://img.shields.io/badge/license-MIT-green?style=flat-square)
11
11
  ![status](https://img.shields.io/badge/status-stable-brightgreen?style=flat-square)
12
12
  ![platform](https://img.shields.io/badge/platform-DSH%20Web-blueviolet?style=flat-square)
@@ -35,6 +35,7 @@
35
35
  | 👁️ | **视觉模型** | 支持 `deepseek-v4-flash-vision-exp`:legacy 时代单价与 flash 一致,2026-09-10 12:00 起随 V4.1 Flash 新价计费(该旧名已下线,请求由 V4.1 Flash 提供);图片按官方规则换算 token(每张上限 384 个,以接口用量计费) |
36
36
  | 🏷️ | **官方模型名对齐** | 计费支持**官方现役名 `deepseek-flash`**(价格卡脚注 (1):「模型名请使用 `deepseek-flash`」),旧写法 `deepseek-v4.1-flash` 等归一化后命中同一档价,避免因官方改名而落入兜底估算 |
37
37
  | 📊 | **可视化仪表盘** | 设置页新增「花费统计」:概览卡片、消费柱状图(按峰谷/按模型)、分模型的请求次数与 Tokens 图表,**全部支持鼠标悬停查看明细** |
38
+ | 🧭 | **多机汇总(云端同步)** | 可对接**自建云端服务**(独立仓库 `dsh-cost-cloud`,零运行时依赖):多台电脑的用量汇总到一处,看板顶部出现 **本机 / 本机+云端 / 仅云端** 三态开关,并支持**设备 × Agent 矩阵**(行合计 = 列合计 = 总计);上报内容仅 token 数、费用、时间戳与标识符,可选会话脱敏 |
38
39
  | 🔥 | **用量热力图** | 设置页新增「Token 用量统计」:类 Codex 的 **26 周日用量方格热图**,按天着色(输入 / 缓存 / 输出 / 费用),悬停看当日明细、今天高亮描边,顶部显示全时段累计 |
39
40
  | 📈 | **订阅配额监控** | Kimi Coding Plan 等订阅套餐:本周配额、5 小时滚动窗口限额、等效按量费用参考 |
40
41
  | 💳 | **余额查询** | 一键查询 DeepSeek 官方账户余额(总余额 / 充值 / 赠送 / 状态) |
@@ -154,10 +155,12 @@ rm -rf ~/.dsh/profiles/node_modules/dsh-cost-tracker
154
155
  ### 设置页「花费统计」
155
156
 
156
157
  - **时间范围**:右上角可切换近 7 天 / 近 30 天 / 全部;
158
+ - **六组概览卡**:今日费用 / 本月费用 / 总花费 / API 请求次数 / Tokens / **总余额**。前三个金额卡**不含订阅会员等效费用**,订阅以附注展示;
157
159
  - **消费金额图**:支持「按峰谷」「按模型」两种分段方式,鼠标悬停查看当日明细;
158
160
  - **配色切换**:「按模型」视图下,消费金额标题旁有三套装色款条(橙→黄 / 蓝→紫 / 蓝→浅蓝)可切换;模型按总消费降序排名取色(第 1 名最深夜底、逐级变浅,不循环不撞色),选择保存在浏览器本地;
159
161
  - **分模型区块**:每个模型一张请求次数图 + 一张 Tokens 构成图(输入/缓存写入/输出/缓存命中);
160
162
  - **Token 用量统计热力图**:类 Codex 的 26 周每日用量方格,颜色深浅按当日 token 相对最大值分档;悬停任一格看该日明细(输入 / 缓存 / 输出 / 费用),今天高亮描边;
163
+ - **峰谷计价与提示**:时段条样式可选(**简洁单行·按 24h 比例**(白色实时进度线) / **环形表盘·相位色点**),简洁样式可选**双行紧凑**(条上文下 / 文上条下),可开关「显示时间」刻度(00:00–21:00),设置峰/谷切换前的弹窗提醒提前量(1–30 分钟)、提醒类型(两者 / 进入高峰 / 进入闲时)、弹窗位置(右下角 / 屏幕中心)与浏览器系统通知;全部自动保存。侧边栏底部常驻时段条显示当前档位与下次切换倒计时;
161
164
  - **导出 CSV**:导出明细记录(近 180 天)+ 日汇总行(`purpose=rollup`)。
162
165
 
163
166
  ### 对话中的 Agent 工具
@@ -238,6 +241,22 @@ POST /api/cost-tracker/export 导出 CSV
238
241
 
239
242
  ## 更新记录
240
243
 
244
+ > 这里只列重要版本;逐版完整记录见 [`CHANGELOG.md`](./CHANGELOG.md)。
245
+
246
+ ### v1.8.11(2026-09-17)
247
+
248
+ **新增:启动时检测「另一个 dsh 实例正在用同一份记录文件」并直接点名**
249
+
250
+ - v1.8.10 的 EPERM 现场根因就是**上一个 dsh 实例还在跑、又起了一个** —— 两个实例写同一份记录文件、互相覆盖,并在 Windows 上撞 rename 的 EPERM。此前只能对着堆栈猜。
251
+ - 现在启动时会在记录文件旁登记一把**仅用于提示**的实例锁(`.lock`,含 pid / 版本);若持有者仍存活,直接打印占用者与处理办法(先 Ctrl+C 停掉旧的,再启动新的)。**绝不阻断启动**:陈旧锁、损坏锁、自己的锁都静默跳过,退出时只删自己的锁。
252
+ - 实测(两个真实进程):第二个实例启动即报 `检测到另一个 dsh 实例(PID 15784 · v1.8.10)…`。
253
+
254
+ **文档:两份 README 补齐长期漂移(无功能变更)**
255
+
256
+ - 英文 README 更新记录补齐 v1.8.7–v1.8.10(此前停在 v1.8.6)并补 v1.3.0;**修正过时口径**:「本机+云端」原写作「服务端排除本机」——那是旧语义,实际是**并集**(其他整机 ∪ 本机上的非 dsh 来源);补「多机汇总(云端同步)」功能行与 `sync.js`/`view.js`/`schema.js`。
257
+ - 中文 README 补「六组概览卡」「峰谷计价与提示」两条设置页说明;FAQ 补落盘遇瞬时占用的处理。
258
+ - 两份 README 的版本徽标改为 **npm 动态徽标**(不再硬编码 v1.6.0,发版自动跟随)。
259
+
241
260
  ### v1.8.10(2026-09-17)
242
261
 
243
262
  **修复:Windows 上落盘偶发 `EPERM`(rename 被瞬时占用),启动日志出现吓人的堆栈**
@@ -390,7 +409,8 @@ POST /api/cost-tracker/export 导出 CSV
390
409
  全部数据只存在你本机的 `~/.dsh/storages/cost-tracker-records.json`,不会上传到任何服务器。API 只监听本机回环地址,但无鉴权——**不要把 DSH 端口暴露到公网**。
391
410
 
392
411
  **Q:重启 DSH 数据会丢吗?**
393
- 不会。记录防抖写入磁盘(原子写入),重启后自动恢复;文件损坏时自动备份为 `.corrupt-<时间戳>` 并从头开始。
412
+ 不会。记录防抖写入磁盘(临时文件 + rename 原子替换),重启后自动恢复;文件损坏时自动备份为 `.corrupt-<时间戳>` 并从头开始。
413
+ 落盘遇到**瞬时占用**(Windows 上杀毒 / 索引器 / 备份工具正在读该文件,或上一个 `dsh` 实例还没退干净)时会**退避重试**;重试仍失败则数据留在内存、稍后自动重试,**不会写坏原文件**。若反复出现,请确认没有同时运行两个 DSH 实例。
394
414
 
395
415
  **Q:历史记录会保留多久?统计有上限吗?**
396
416
  明细记录保留最近 **180 天**;更早的记录自动按「天 + 模型」压缩为**永久日汇总**(只保留聚合数字:调用数 / 各段 tokens / 费用,不再保留单次调用)。因此「全部」时间的总花费、分模型统计**永远精确**,且内存、磁盘、写入量有界,跑多久都不会膨胀。按天图表日期轴最长 730 天。数据文件支持旧版格式自动迁移;可用环境变量 `DSH_COST_TRACKER_STORE` 覆盖存储路径(默认 `$DSH_HOME/storages`,未设 `DSH_HOME` 时为 `~/.dsh`)。
@@ -419,9 +439,12 @@ POST /api/cost-tracker/export 导出 CSV
419
439
 
420
440
  ```
421
441
  ├── index.js Host 半端:用量采集、聚合、HTTP API、Agent 工具
422
- ├── store.js 存储层:明细保留 + 永久日汇总 + 持久化(纯逻辑,可独立测试)
442
+ ├── store.js 存储层:明细保留 + 永久日汇总 + 原子落盘(含占用重试,纯逻辑可独立测试)
423
443
  ├── pricing.js 定价与 Token 层:单价表、峰谷计价、视觉模型、峰值相位(纯逻辑,可独立测试)
424
- ├── config.js 配置层:峰谷计价提示的默认值与规范化(纯逻辑,可独立测试)
444
+ ├── config.js 配置层:峰谷计价提示 + 云端同步的默认值与规范化(纯逻辑,可独立测试)
445
+ ├── sync.js 云端同步引擎:设备身份、增量水位、幂等批次、退避重试
446
+ ├── schema.js 宿主设置空间的 schema(插件配置卡片字段)
447
+ ├── view.js 三态视图合并:本机 / 本机+云端 / 仅云端的口径归一化(浏览器与测试共用)
425
448
  ├── client.js Client 半端:设置页仪表盘、状态栏与峰谷提示 UI
426
449
  ├── package.json 插件清单:声明 dsh.bundle(插件可被安装的关键)与 dsh.client(前端 UI)
427
450
  ├── cordis.patch.yml Bundle 补丁:把本插件注册进 DSH 的 loader,由 dsh.bundle 指向
@@ -429,7 +452,7 @@ POST /api/cost-tracker/export 导出 CSV
429
452
  ├── README.md 中文说明文档
430
453
  ├── README.en.md 英文说明文档
431
454
  ├── CHANGELOG.md 更新记录(中文)
432
- ├── test/ 单元测试(storage / pricing / config / recompute,node test/*.test.js)
455
+ ├── test/ 单元测试(storage / pricing / config / recompute / 渲染 / 云端读取,node test/*.test.js)
433
456
  └── docs/ README 截图与设计文档
434
457
  ```
435
458
 
package/index.js CHANGED
@@ -19,7 +19,7 @@ import { createSyncEngine, setPluginVersion, SOURCE as SYNC_SOURCE, SYNC_VERSION
19
19
  import { Schema } from './schema.js'
20
20
 
21
21
  /** 插件版本(写入上报信封,便于云端排查版本差异) */
22
- const PLUGIN_VERSION = '1.8.10'
22
+ const PLUGIN_VERSION = '1.8.11'
23
23
  setPluginVersion(PLUGIN_VERSION)
24
24
 
25
25
  /** 「设置 → 插件 → 插件配置」里的卡片字段(与 settings 命名空间一致) */
@@ -285,6 +285,9 @@ export default {
285
285
  const n = store.load()
286
286
  const ru = Object.keys(rollups).length
287
287
  if (n > 0 || ru > 0) startupLog('cost tracker restored ' + n + ' detail records, ' + ru + ' rollup days from ' + STORE_FILE)
288
+ // 实例锁:若同一份记录文件已被另一个存活的 dsh 实例占用,明确报出来
289
+ // (多实例会互相覆盖记录,并可能在 Windows 上触发 rename EPERM —— v1.8.10 的现场根因)
290
+ store.lock({ version: PLUGIN_VERSION })
288
291
  }
289
292
 
290
293
  let persistPending = false
@@ -1410,6 +1413,7 @@ export default {
1410
1413
  // 退出前最后一次落盘:给足重试(10 次 ≈ 2s)——否则被瞬时占用就会丢掉本次会话的记录;
1411
1414
  // 这里不能用 writeRecords(),它失败后只是「排个延迟重试」,而进程马上要退出。
1412
1415
  try { store.persist({ tries: 10 }) } catch (e) {}
1416
+ try { store.releaseLock() } catch (e) {}
1413
1417
  if (syncTimer) { try { syncTimer() } catch (e) {} }
1414
1418
  if (syncDebounce) { try { syncDebounce() } catch (e) {} }
1415
1419
  }, 'cost-tracker: final flush')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@angelyeye/dsh-cost-tracker",
3
- "version": "1.8.10",
3
+ "version": "1.8.11",
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",
package/store.js CHANGED
@@ -128,6 +128,72 @@ function explainPersistError(res) {
128
128
  return '文件系统错误(不是占用问题)'
129
129
  }
130
130
 
131
+ // ---------- 实例锁(只提示,不阻断) ----------
132
+ /** 进程是否存活:Windows 上 EPERM 表示「存在但无权限」,同样算存活 */
133
+ function pidAlive(pid) {
134
+ try {
135
+ process.kill(pid, 0)
136
+ return true
137
+ } catch (e) {
138
+ return !!e && e.code === 'EPERM'
139
+ }
140
+ }
141
+
142
+ /**
143
+ * 检测同一份记录文件是否已被**另一个存活的 dsh 实例**占用。
144
+ *
145
+ * 为什么需要:两个实例同时写同一份记录会互相覆盖,并且在 Windows 上很容易撞上
146
+ * rename 的 EPERM(v1.8.10 的现场根因就是「上一个实例还在跑,又起了一个」)。
147
+ * 与其让用户对着 EPERM 堆栈猜,不如启动时直接说清楚。
148
+ * 纯提示:读不到 / 解析失败 / 陈旧锁都返回 null,绝不阻断启动。
149
+ * @returns {{heldBy:number|null, text:string|null}}
150
+ */
151
+ export function checkStoreLock(filePath, opts) {
152
+ const o = opts || {}
153
+ const isAlive = o.isAlive || pidAlive
154
+ const lockFile = filePath + '.lock'
155
+ try {
156
+ if (!existsSync(lockFile)) return { heldBy: null, text: null }
157
+ const prev = JSON.parse(readFileSync(lockFile, 'utf8'))
158
+ const pid = Number(prev && prev.pid)
159
+ if (!pid || pid === process.pid || !isAlive(pid)) return { heldBy: null, text: null }
160
+ return {
161
+ heldBy: pid,
162
+ text: 'cost tracker: 检测到另一个 dsh 实例(PID ' + pid + (prev && prev.version ? ' · v' + prev.version : '')
163
+ + ')正在使用同一份记录文件:\n ' + filePath
164
+ + '\n 两个实例会互相覆盖对方的记录,并可能在 Windows 上触发 rename EPERM(需要目标文件的删除权限)。'
165
+ + '\n 请只保留一个 dsh 实例:先 Ctrl+C 停掉旧的,再启动新的。',
166
+ }
167
+ } catch (e) {
168
+ return { heldBy: null, text: null }
169
+ }
170
+ }
171
+
172
+ /** 写下本进程的实例锁(带上版本,便于提示里说清是谁占着) */
173
+ export function writeStoreLock(filePath, opts) {
174
+ const o = opts || {}
175
+ try {
176
+ mkdirSync(dirname(filePath), { recursive: true })
177
+ writeFileSync(filePath + '.lock', JSON.stringify({ pid: process.pid, at: Date.now(), version: o.version || '' }), 'utf8')
178
+ return true
179
+ } catch (e) {
180
+ return false
181
+ }
182
+ }
183
+
184
+ /** 退出时清理实例锁(只删自己的,别删别人的) */
185
+ export function releaseStoreLock(filePath) {
186
+ const lockFile = filePath + '.lock'
187
+ try {
188
+ const prev = JSON.parse(readFileSync(lockFile, 'utf8'))
189
+ if (Number(prev && prev.pid) === process.pid) unlinkSync(lockFile)
190
+ return true
191
+ } catch (e) {
192
+ return false
193
+ }
194
+ }
195
+
196
+
131
197
 
132
198
  /**
133
199
  * 由插件侧统一计算明细的内容哈希键(与云端契约 §6 一致)。
@@ -433,6 +499,17 @@ export function createStore(filePath, opts) {
433
499
 
434
500
  return {
435
501
  details, rollups, load, add, persist, persistProblem, clear, counts,
502
+ /**
503
+ * 启动时登记实例锁:先把「另一个实例还占着」讲清楚,再写自己的锁。
504
+ * 只提示、不阻断——多实例本来就是用户的操作问题,不是插件的错误。
505
+ */
506
+ lock(opts) {
507
+ const res = checkStoreLock(filePath, opts)
508
+ if (res.text) console.error(res.text)
509
+ writeStoreLock(filePath, opts)
510
+ return res
511
+ },
512
+ releaseLock: () => releaseStoreLock(filePath),
436
513
  /** 当前最大序号(云端水位比较用) */
437
514
  maxSeq: () => seq,
438
515
  /** 清空次数(参与去重键) */