@angelyeye/dsh-cost-tracker 1.8.9 → 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,52 @@
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
+
27
+ ## v1.8.10(2026-09-17)
28
+
29
+ **修复:Windows 上落盘偶发 `EPERM`(rename 被瞬时占用),启动日志甩出吓人的堆栈**
30
+
31
+ - **现场**(v1.8.9 重启时):
32
+ ```
33
+ cost tracker persist failed Error: EPERM: operation not permitted,
34
+ rename '...cost-tracker-records.json.tmp' -> '...cost-tracker-records.json'
35
+ at renameSync (node:fs:1012:11)
36
+ at Object.persist (.../store.js:307:7)
37
+ ```
38
+ - **根因**:`persist()` 是「写临时文件 → rename 覆盖」,但**只尝试一次**。Windows 上 rename 需要**目标文件的删除权限**,以下都会瞬时失败:杀毒 / 搜索索引器刚扫过刚写完的临时文件;资源管理器预览、备份/同步工具正在读它;**上一个 dsh 实例还没退干净**(或同时跑了两个实例)。失败后数据仍在内存、下次写入会重试(本次实测 2 分钟后自动写成功、未丢数据),但用户看到的是完整堆栈,且这段时间磁盘上是旧数据。
39
+ - **修法**:
40
+ 1. 临时文件名带 **pid**(`<file>.<pid>.tmp`)——旧实现固定用 `<file>.tmp`,两个实例必然抢同一个临时文件;
41
+ 2. `renameSync` 遇 `EPERM/EACCES/EBUSY` **退避重试**(20/40/80/160ms,共 5 次 ≈ 0.35s);`ENOENT` 等代码类错误不重试;
42
+ 3. 仍失败**不做**「直接覆盖写」——那会让并发读方看到半个 JSON,而 `load()` 一旦读到半个 JSON 会把文件改名为 `.corrupt-*` 并清空,损失远大于「晚几秒落盘」;改为数据留在内存,由调用方重试;
43
+ 4. `index.js` 再排 **3 次延迟重试**(2s/4s/6s),覆盖「杀毒扫描持续数秒」这类同步重试兜不住的情况;重试链走完之前**不打日志**(quiet 模式),彻底放弃时才打印一次带「原因 + 影响」的说明;
44
+ 5. 退出前最后一次落盘给足重试(10 次 ≈ 2s),避免被瞬时占用就丢掉本次会话的记录。
45
+ - **实测**(真实 Windows 文件锁:`[System.IO.File]::Open(..., FileShare.Read)` 持锁):
46
+ - 持续占用 → 重试 5 次后放弃,**原文件字节不变**、无残留临时文件,日志变成三行可读说明;
47
+ - 持锁 120ms 后释放 → 第 3 次尝试成功落盘(`{ok:true, ms:82}`),**无需人工干预**;
48
+ - quiet 模式失败 → stderr 为空(由调用方决定何时报)。
49
+ - **测试**:`test/storage.test.js` 新增第 13 节(17 条断言):一次成功、退避重试、持续占用不覆盖目标且清理临时文件、非占用类错误只试一次、错误分类、真实落盘往返。
50
+
5
51
  ## v1.8.9(2026-09-17)
6
52
 
7
53
  **修正档位文案:「平峰」→「不分峰谷」,且为 0 时不再占图例**
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,35 @@ 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
+
260
+ ### v1.8.10(2026-09-17)
261
+
262
+ **修复:Windows 上落盘偶发 `EPERM`(rename 被瞬时占用),启动日志出现吓人的堆栈**
263
+
264
+ - **现场**:重启 `dsh web` 时打印 `cost tracker persist failed Error: EPERM: operation not permitted, rename '...cost-tracker-records.json.tmp' -> '...cost-tracker-records.json'`,附完整调用栈。**数据没丢**(内存里还在、随后自动写成功),但这段堆栈看起来像崩溃。
265
+ - **根因**:`persist()` 是「写临时文件 → rename 覆盖」,但**只尝试一次**。Windows 上 rename 需要**目标文件的删除权限**,以下情况都会瞬时失败:杀毒 / 搜索索引器刚扫过临时文件;资源管理器预览或备份/同步工具正在读它;**上一个 dsh 实例还没退干净**(或同时跑了两个实例)。旧实现还固定用 `<file>.tmp` 作临时文件名,两个实例必然抢同一个名字。
266
+ - **修法**:
267
+ - 临时文件名带 **pid**;rename 遇 `EPERM/EACCES/EBUSY` **退避重试**(20/40/80/160ms,共 5 次 ≈ 0.35s),`ENOENT` 等代码类错误不重试;
268
+ - 应用层(`index.js`)再排 **3 次延迟重试**(2s/4s/6s),覆盖「杀毒扫描持续数秒」这种同步重试兜不住的情况;**重试链走完之前不打日志**,彻底放弃时才打印一次「原因 + 影响」说明;
269
+ - 仍失败**不做**「直接覆盖写」:那会让并发读方看到半个 JSON,而 `load()` 读到半个 JSON 会把文件改名为 `.corrupt-*` 并清空,损失远大于晚几秒落盘;数据留在内存,等下一次写入自动重试;
270
+ - 退出前最后一次落盘给足重试(10 次 ≈ 2s),避免被瞬时占用就丢掉本次会话的记录。
271
+ - **实测**(真实 Windows 文件锁):持续占用 → 重试后放弃、**原文件字节不变**、无残留临时文件、日志为三行可读说明;持锁 120ms 后释放 → 第 3 次尝试成功落盘,**无需人工干预**。
272
+
241
273
  ### v1.8.9(2026-09-17)
242
274
 
243
275
  **修正档位文案:「平峰」→「不分峰谷」,且为 0 时不再占图例**
@@ -377,7 +409,8 @@ POST /api/cost-tracker/export 导出 CSV
377
409
  全部数据只存在你本机的 `~/.dsh/storages/cost-tracker-records.json`,不会上传到任何服务器。API 只监听本机回环地址,但无鉴权——**不要把 DSH 端口暴露到公网**。
378
410
 
379
411
  **Q:重启 DSH 数据会丢吗?**
380
- 不会。记录防抖写入磁盘(原子写入),重启后自动恢复;文件损坏时自动备份为 `.corrupt-<时间戳>` 并从头开始。
412
+ 不会。记录防抖写入磁盘(临时文件 + rename 原子替换),重启后自动恢复;文件损坏时自动备份为 `.corrupt-<时间戳>` 并从头开始。
413
+ 落盘遇到**瞬时占用**(Windows 上杀毒 / 索引器 / 备份工具正在读该文件,或上一个 `dsh` 实例还没退干净)时会**退避重试**;重试仍失败则数据留在内存、稍后自动重试,**不会写坏原文件**。若反复出现,请确认没有同时运行两个 DSH 实例。
381
414
 
382
415
  **Q:历史记录会保留多久?统计有上限吗?**
383
416
  明细记录保留最近 **180 天**;更早的记录自动按「天 + 模型」压缩为**永久日汇总**(只保留聚合数字:调用数 / 各段 tokens / 费用,不再保留单次调用)。因此「全部」时间的总花费、分模型统计**永远精确**,且内存、磁盘、写入量有界,跑多久都不会膨胀。按天图表日期轴最长 730 天。数据文件支持旧版格式自动迁移;可用环境变量 `DSH_COST_TRACKER_STORE` 覆盖存储路径(默认 `$DSH_HOME/storages`,未设 `DSH_HOME` 时为 `~/.dsh`)。
@@ -406,9 +439,12 @@ POST /api/cost-tracker/export 导出 CSV
406
439
 
407
440
  ```
408
441
  ├── index.js Host 半端:用量采集、聚合、HTTP API、Agent 工具
409
- ├── store.js 存储层:明细保留 + 永久日汇总 + 持久化(纯逻辑,可独立测试)
442
+ ├── store.js 存储层:明细保留 + 永久日汇总 + 原子落盘(含占用重试,纯逻辑可独立测试)
410
443
  ├── pricing.js 定价与 Token 层:单价表、峰谷计价、视觉模型、峰值相位(纯逻辑,可独立测试)
411
- ├── config.js 配置层:峰谷计价提示的默认值与规范化(纯逻辑,可独立测试)
444
+ ├── config.js 配置层:峰谷计价提示 + 云端同步的默认值与规范化(纯逻辑,可独立测试)
445
+ ├── sync.js 云端同步引擎:设备身份、增量水位、幂等批次、退避重试
446
+ ├── schema.js 宿主设置空间的 schema(插件配置卡片字段)
447
+ ├── view.js 三态视图合并:本机 / 本机+云端 / 仅云端的口径归一化(浏览器与测试共用)
412
448
  ├── client.js Client 半端:设置页仪表盘、状态栏与峰谷提示 UI
413
449
  ├── package.json 插件清单:声明 dsh.bundle(插件可被安装的关键)与 dsh.client(前端 UI)
414
450
  ├── cordis.patch.yml Bundle 补丁:把本插件注册进 DSH 的 loader,由 dsh.bundle 指向
@@ -416,7 +452,7 @@ POST /api/cost-tracker/export 导出 CSV
416
452
  ├── README.md 中文说明文档
417
453
  ├── README.en.md 英文说明文档
418
454
  ├── CHANGELOG.md 更新记录(中文)
419
- ├── test/ 单元测试(storage / pricing / config / recompute,node test/*.test.js)
455
+ ├── test/ 单元测试(storage / pricing / config / recompute / 渲染 / 云端读取,node test/*.test.js)
420
456
  └── docs/ README 截图与设计文档
421
457
  ```
422
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.9'
22
+ const PLUGIN_VERSION = '1.8.11'
23
23
  setPluginVersion(PLUGIN_VERSION)
24
24
 
25
25
  /** 「设置 → 插件 → 插件配置」里的卡片字段(与 settings 命名空间一致) */
@@ -139,7 +139,32 @@ export default {
139
139
  const records = store.details
140
140
  const rollups = store.rollups
141
141
 
142
- function writeRecords() { store.persist() }
142
+ /**
143
+ * 落盘。store.persist() 内部已对「文件被短暂占用」退避重试(约 0.3s);
144
+ * 仍失败时在这里**再排 3 次延迟重试**(2s / 4s / 6s)——
145
+ * 杀毒或备份工具一次扫描常常持续数秒,仅靠同步重试兜不住,
146
+ * 而数据一直在内存里,晚几秒落盘没有任何损失。
147
+ *
148
+ * 期间对 store 用 quiet 模式:重试链没走完之前**不打日志**,
149
+ * 避免「其实马上就好了」的情况在启动日志里甩出一段吓人的 EPERM 堆栈
150
+ * (v1.8.9 重启时的真实现场)。彻底放弃时才打印一次带原因与影响的说明。
151
+ */
152
+ let persistRetry = 0
153
+ let persistRetryTimer = null
154
+ function writeRecords() {
155
+ if (store.persist({ quiet: true })) { persistRetry = 0; return true }
156
+ if (persistRetry >= 3) {
157
+ console.error(store.persistProblem())
158
+ return false
159
+ }
160
+ persistRetry += 1
161
+ const delay = 2000 * persistRetry
162
+ const fire = () => { persistRetryTimer = null; writeRecords() }
163
+ const timer = ctx.get('timer')
164
+ if (persistRetryTimer) { try { persistRetryTimer() } catch (e) {} }
165
+ persistRetryTimer = timer ? timer.timeout(fire, delay) : setTimeout(fire, delay)
166
+ return false
167
+ }
143
168
 
144
169
  // ---------- plugin config(峰谷计价 + 云端同步) ----------
145
170
  // 与记录分开存储:$DSH_HOME/storages/cost-tracker-config.json。
@@ -260,6 +285,9 @@ export default {
260
285
  const n = store.load()
261
286
  const ru = Object.keys(rollups).length
262
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 })
263
291
  }
264
292
 
265
293
  let persistPending = false
@@ -278,6 +306,7 @@ export default {
278
306
  function persistNow() {
279
307
  persistPending = false
280
308
  if (persistTimer) { try { persistTimer() } catch (e) {} persistTimer = null }
309
+ if (persistRetryTimer) { try { persistRetryTimer() } catch (e) {} persistRetryTimer = null }
281
310
  writeRecords()
282
311
  }
283
312
 
@@ -1381,7 +1410,10 @@ export default {
1381
1410
  startSyncTimer()
1382
1411
  if (cloudConfig.cloudEnabled) scheduleSync(5000)
1383
1412
  ctx.effect(() => () => {
1384
- try { writeRecords() } catch (e) {}
1413
+ // 退出前最后一次落盘:给足重试(10 次 ≈ 2s)——否则被瞬时占用就会丢掉本次会话的记录;
1414
+ // 这里不能用 writeRecords(),它失败后只是「排个延迟重试」,而进程马上要退出。
1415
+ try { store.persist({ tries: 10 }) } catch (e) {}
1416
+ try { store.releaseLock() } catch (e) {}
1385
1417
  if (syncTimer) { try { syncTimer() } catch (e) {} }
1386
1418
  if (syncDebounce) { try { syncDebounce() } catch (e) {} }
1387
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.9",
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
@@ -16,7 +16,7 @@
16
16
  // v1(旧版裸数组)在 load() 时自动迁移;损坏文件自动备份为
17
17
  // .corrupt-<时间戳> 并从零开始,不阻断启动。
18
18
  // ============================================================
19
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
19
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
20
20
  import { dirname } from 'node:path'
21
21
  import { createHash } from 'node:crypto'
22
22
 
@@ -53,6 +53,148 @@ export function emptyEntry(provider, model, subscription, estimated) {
53
53
  /** 单条日汇总最多记录多少条被吸收明细的键(云端据此排除重复,超出部分不再追溯) */
54
54
  export const MAX_ABSORBED_KEYS = 5000
55
55
 
56
+ // ---------- 原子落盘(Windows 友好) ----------
57
+ /**
58
+ * rename 的**瞬时**失败码。Windows 上目标文件被短暂占用时 renameSync 会抛这些:
59
+ * · 杀毒 / 搜索索引器刚扫过刚写完的临时文件;
60
+ * · 资源管理器预览、备份/同步工具正在读该文件;
61
+ * · 上一个 dsh 实例还没退干净(或同时跑了两个实例)。
62
+ * 这类「等一下就好」,退避重试即可;代码类错误(ENOENT、EISDIR…)不该重试。
63
+ */
64
+ const TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EACCES', 'EBUSY'])
65
+ export function isTransientRenameError(e) {
66
+ return !!e && TRANSIENT_RENAME_CODES.has(String(e.code || ''))
67
+ }
68
+
69
+ /** 同步睡眠(Node 没有 sleepSync;Atomics.wait 不占 CPU) */
70
+ function sleepSync(ms) {
71
+ try {
72
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
73
+ } catch (e) {
74
+ const end = Date.now() + ms
75
+ while (Date.now() < end) { /* 无 SharedArrayBuffer 的极端环境下退化为忙等 */ }
76
+ }
77
+ }
78
+
79
+ /**
80
+ * 原子落盘:写临时文件 → rename 覆盖目标。
81
+ *
82
+ * · 临时文件名带 **pid**:两个实例各写各的临时文件,不会互相盖掉半个文件
83
+ * (旧实现固定用 `<file>.tmp`,两实例必然抢同一个临时文件)。
84
+ * · rename 遇瞬时占用时按 20/40/80/160ms 退避重试(默认 5 次,约 0.3s)。
85
+ * · 仍失败**不做**「直接覆盖写」:那会让并发读方看到半个 JSON,而 store.load()
86
+ * 一旦读到半个 JSON 会把文件改名为 `.corrupt-*` 并清空 —— 损失远大于「晚几秒落盘」。
87
+ * 数据留在内存里,由调用方稍后重试(见 index.js 的 writeRecords 重试链)。
88
+ *
89
+ * @returns {{ok:boolean, attempts:number, mode:'rename'|'failed', error?:Error|null, transient?:boolean}}
90
+ */
91
+ export function writeFileAtomic(filePath, data, opts) {
92
+ const o = opts || {}
93
+ const fs = Object.assign({ mkdirSync, writeFileSync, renameSync, unlinkSync }, o.fs || {})
94
+ const sleep = o.sleep || sleepSync
95
+ const tries = Math.max(1, Number(o.tries) || 5)
96
+ const tmp = filePath + '.' + process.pid + '.tmp'
97
+ const cleanup = () => { try { fs.unlinkSync(tmp) } catch (e) { /* 已被 rename 走或从未创建 */ } }
98
+ try {
99
+ fs.mkdirSync(dirname(filePath), { recursive: true })
100
+ fs.writeFileSync(tmp, data, 'utf8')
101
+ } catch (e) {
102
+ cleanup()
103
+ return { ok: false, attempts: 0, mode: 'failed', error: e, transient: isTransientRenameError(e) }
104
+ }
105
+ let attempts = 0
106
+ let last = null
107
+ for (let i = 0; i < tries; i++) {
108
+ attempts += 1
109
+ try {
110
+ fs.renameSync(tmp, filePath)
111
+ return { ok: true, attempts, mode: 'rename', error: last }
112
+ } catch (e) {
113
+ last = e
114
+ if (!isTransientRenameError(e)) break
115
+ if (i < tries - 1) sleep(20 * Math.pow(2, i))
116
+ }
117
+ }
118
+ cleanup()
119
+ return { ok: false, attempts, mode: 'failed', error: last, transient: isTransientRenameError(last) }
120
+ }
121
+
122
+ /** 给用户看的失败原因(区分「被占用」与「文件系统错误」) */
123
+ function explainPersistError(res) {
124
+ if (res.transient) {
125
+ return '记录文件被占用(杀毒/索引器/备份工具正在读它,或另有一个 dsh 实例在跑;'
126
+ + 'Windows 上 rename 需要目标文件的删除权限,被占用时会失败)'
127
+ }
128
+ return '文件系统错误(不是占用问题)'
129
+ }
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
+
197
+
56
198
  /**
57
199
  * 由插件侧统一计算明细的内容哈希键(与云端契约 §6 一致)。
58
200
  * 这里即时计算而不是在 store 里 import sync.js —— 该函数只依赖 node:crypto,
@@ -299,17 +441,45 @@ export function createStore(filePath, opts) {
299
441
  return r
300
442
  }
301
443
 
302
- function persist() {
303
- try {
304
- mkdirSync(dirname(filePath), { recursive: true })
305
- const tmp = filePath + '.tmp'
306
- writeFileSync(tmp, JSON.stringify({ v: 2, seq, resetEpoch, details, rollups }), 'utf8')
307
- renameSync(tmp, filePath)
444
+ // 落盘失败只报一次(避免每 1.5 秒刷屏);恢复后又失败会再次提示
445
+ let persistWarned = false
446
+ // 最近一次失败的原因(供调用方在重试链耗尽后打印)
447
+ let lastPersistError = null
448
+ let lastPersistTransient = false
449
+ /** 供调用方在「自己还有重试机会」时静默(quiet=1),等重试链耗尽再报一次 */
450
+ function persistProblemText(res) {
451
+ return 'cost tracker persist failed: ' + ((res.error && res.error.message) || String(res.error))
452
+ + '\n 原因:' + explainPersistError(res)
453
+ + '\n 影响:数据仍在内存中,会在下一次写入时自动重试(不会丢);'
454
+ + '若反复出现,请确认没有同时运行两个 dsh 实例'
455
+ }
456
+ function persist(opts) {
457
+ const o = opts || {}
458
+ const res = writeFileAtomic(filePath, JSON.stringify({ v: 2, seq, resetEpoch, details, rollups }), o)
459
+ if (res.ok) {
460
+ lastPersistError = null
461
+ lastPersistTransient = false
462
+ if (res.attempts > 1 && !persistWarned) {
463
+ persistWarned = true
464
+ console.error('cost tracker persist: 文件被短暂占用,重试 ' + res.attempts + ' 次后已写入('
465
+ + explainPersistError({ transient: true }) + ')')
466
+ } else if (res.attempts === 1) {
467
+ persistWarned = false
468
+ }
308
469
  return true
309
- } catch (e) {
310
- console.error('cost tracker persist failed', e)
311
- return false
312
470
  }
471
+ lastPersistError = res.error
472
+ lastPersistTransient = res.transient === true
473
+ if (!o.quiet && !persistWarned) {
474
+ persistWarned = true
475
+ console.error(persistProblemText(res))
476
+ }
477
+ return false
478
+ }
479
+ /** 重试链彻底放弃时由调用方打印(保证「只在真的没救时」才出现一次) */
480
+ function persistProblem() {
481
+ persistWarned = true
482
+ return persistProblemText({ error: lastPersistError, transient: lastPersistTransient })
313
483
  }
314
484
 
315
485
  function clear() {
@@ -328,7 +498,18 @@ export function createStore(filePath, opts) {
328
498
  }
329
499
 
330
500
  return {
331
- details, rollups, load, add, persist, clear, counts,
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),
332
513
  /** 当前最大序号(云端水位比较用) */
333
514
  maxSeq: () => seq,
334
515
  /** 清空次数(参与去重键) */