@angelyeye/dsh-cost-tracker 1.9.4 → 1.9.6

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,135 @@
2
2
 
3
3
  本文件用中文记录 dsh-cost-tracker 的版本变更。
4
4
 
5
+ ## v1.9.6(2026-10-17)
6
+
7
+ **新增:余额查询兼容 DSH「DeepSeek 账号登录」——账号态改走宿主 `deepseekAccount.getBalance()`,读取 Platform 钱包(充值 / 赠金);API Key 路径原样保留**
8
+
9
+ ### 一、问题:账号登录用户查不到余额
10
+
11
+ DSH 的浏览器 PKCE 账号登录(`@deepseek-ai/dsh-deepseek-account` + `dsh-deepseek-account-platform`,0.1.7-alpha.1 起引入)把授权写进 credentials 的 **record** `deepseek-account-platform/default`(`{version, token, issuer}`),**从不写 ref**。而 `credentials.resolve()` 只查 refs 半区 —— 所以:
12
+
13
+ - 账号 token 没有 ref 名,`resolve('DEEPSEEK_API_KEY')` 取不到它;
14
+ - 账号态推理用 `x-dsh-auth-token` 走 Platform 网关,运行时 `dsh-llm-deepseek-account` 与 `dsh-llm-deepseek` 的 README 都写明「**不会回退到 API key**」,两条路由互斥;
15
+ - 全 asar 扫描中 `api.deepseek.com/user/balance`、`total_balance`、`granted_balance`、`topped_up_balance` 命中数均为 0 —— 说明「登录后拿 key 去查 api.deepseek.com」这条路在 0.2.x 里根本不存在。
16
+
17
+ 结论:只认 `DEEPSEEK_API_KEY` 的旧实现,在纯账号态下必然报「未找到 DeepSeek API Key」,不是配置问题。
18
+
19
+ ### 二、改法:新增账号余额来源,优先级三级
20
+
21
+ ```
22
+ 面板手填 API Key > 账号登录态(宿主服务) > 配置/环境里的 API Key
23
+ ```
24
+
25
+ - **账号登录态**:`ctx.get('deepseekAccount').getBalance(client)`,数据源为 Platform 的 `GET /api/v0/users/get_user_summary`,返回 `null`(未登录/凭据失效换代)| `{status:'failed'}`(网络/超时/协议)| `{status:'ready', value:[充值钱包], bonusWallets:[赠金钱包]}`。
26
+ - **client 元数据三字段必填**:`version` / `locale` / `timezoneOffsetSeconds` 会被运行时直接拼进 `x-client-*` 请求头,缺一个就抛 `TypeError`(实测:无参 → `reading 'version'`,`{}` → `reading 'toLowerCase'`)。宿主侧一律补齐,浏览器半端再把 `navigator.language` 与本机时区传上来覆盖。
27
+ - **手填 Key 仍最高优先**:那是用户显式动作,意图最强。
28
+ - **账号态失败不回退 API Key**:账号已登录时回退会显示**另一个账户**的数字,比报错更误导;失败信息里直接给出出路(手动填 Key)。
29
+ - **旧宿主零影响**:没有 `deepseekAccount` 服务的 DSH 自动走原路径,文案与 v1.9.5 逐字一致,不做版本号判断。
30
+
31
+ ### 三、口径与字段
32
+
33
+ - 账号态「总余额」= 同币种充值钱包合计 + 同币种赠金合计,用 **BigInt 精确十进制加法**(不经 `Number`,`0.1+0.2` 不出现 `0.30000000000000004`;Platform 返回的 `0E-16` 这类零值统一显示为 `0`)。
34
+ - 账号态 `available` 返回 **null**(Platform 摘要没有 `is_available`,不把「未知」渲染成「不可用」);API Key 态仍为布尔。
35
+ - 多币种:卡片按 `CNY > USD > 其它` 选主币种,符号与标题跟随币种(USD 不再一律显示 `¥`),完整钱包列表放在 `wallets` / `currencies` 里。
36
+ - **展示精度**:Platform 钱包金额实测是 **16 位小数**(形如 `1234.5600000000000000`)。界面按 DSH 官方「账号与余额」页口径**截断到分**(不四舍五入)、正的不足一分显示 `<0.01`、零显示 `0.00`、负数保留符号;同时兼容 `0E-16` 这类指数写法(指数 > 30 时不硬展开)。**接口返回值保持原始精度不截断**,展示与数据分离。
37
+ - 响应新增 `source: 'account' | 'apikey' | 'none'`;`total` / `granted` / `toppedUp` / `currency` / `keySource` 等旧字段全部保留(`keySource` 账号态为 `account`)。
38
+
39
+ ### 四、顺带修复(同一轮 0.2.x 兼容审计发现)
40
+
41
+ - **历史导入对 v4 会话静默失效**:0.2.x 起宿主把新会话写成 `session.v4.jsonl.zstd`,而 `import.js` 只枚举 `session.v3.jsonl.zstd` / `session.v3.jsonl` / `session.jsonl.zstd` / `session.jsonl` 四个硬编码名字 —— v4 及以后的新会话被**静默跳过**(导入清单里 0 个 v4、无任何报错,只表现为「历史导入不再补录新会话」)。本机实测:`.dsh\sessions` 下 68 个 v4 + 20 个 v3 + 10 个 legacy,修复前 `listSessionLogs()` 只返回 29 个。**内容层本来是兼容的**(抽样实测 v4 日志能正常回放出调用(Lead 样本 1160 事件 → 132 调用;verifier 另证与同目录 v3 的调用集合一致),`usage` / `message.source` 形状未变),断点只在文件名。现改为按 `session[.vN].jsonl[.zstd]` 正则识别,**版本号高者优先、同版本 zstd 优先**,宿主将来升 v5/v6 不需要再改枚举;新增 `test/session-log-v4.test.js`(含 v5 前瞻与真实目录交叉核对)。
42
+ - **账号态 provider 的兜底价**:账号登录的推理 provider 名是 `deepseek-account`,原先不在 `PROVIDER_RATES` 里。现役模型能命中 provider 无关的精确价表(实测 100% 命中、`estimated:false`),但**表外的新模型**会落到 `GENERIC_RATES`(缓存价 0.5 而非 0.04、且无峰谷半价)→ 费用被静默高估。现把 `deepseek-account` 登记为与 `deepseek` 共用同一份兜底价(`pricing.js`)。
43
+ - **`settings` 读取迁移到 0.2.x 的 `describe()`(原为静默降级)**:0.2.x 的 `SettingsForms` 已无 `get()`(只剩 `configure/describe/update/replace/mutate/write/prepareDocument`),插件原来的 `deepseekKeyEnv()` / `kimiKeyEnv()` / 火山 AK 候选链会抛 TypeError 并被各自 try/catch 吞掉 → **恒走硬编码默认名**。默认名与官方一致,标准部署看不出问题;但**自定义 `apiKeyEnv`** 的部署会去查一个不存在的 Key 名(表现为「明明配了 Key 却报未找到」)。0.2.x 的正确读法是 `settings.describe()` —— 它返回全部条目的表单描述,`row.value` 即该条目 volatile 字段的**生效值**(`apiKeyEnv` 正是 `.volatile()` 字段)。新增 `settings.js` 做「describe() 优先、get() 兜底」的双 API 兼容读,并按 settings 实例做 10s 短缓存(describe 是全量投影,余额/Kimi/火山三个入口一次刷新会各调一次)。旧宿主行为完全不变;新增 `test/settings-compat.test.js`(两套 API、优先级、缓存、边界,以及「0.2.x 自定义 ref 真的被用来查 Key」的端到端断言)。
44
+ - **修掉既有测试腐化**:`test/import.test.js` 的「看板读到导入记录的总花费」用 `dashboard {days:30}`(相对当前时间)去断言固定日期 fixture(2026-09-15 起),2026-10-15 之后必然假失败 —— 它断言的是**口径**(导入记录要进看板)而非时间窗口,改为足够宽的窗口覆盖 fixture。这是 `npm test` 在 CI 上变红、进而挡住发布的根因。
45
+
46
+ ### 五、新增测试
47
+
48
+ `test/balance-account.test.js`:用真实文件 + 真实 HTTP 处理器跑,不打模块内桩:账号 ready 投影、未登录回退 Key、手填 Key 优先(且不调用账号服务)、账号失败不静默回退、`getBalance` 返回 `undefined` 按契约外失败处理(**不**当作未登录回退,否则会显示另一个账户的余额)、旧宿主文案不变、`client` 三字段必填、精确十进制加法、客户端来源判定与币种显示、展示格式化(从 bundle 源码取函数在 VM 里求值)、账号态 provider 兜底价、settings 双 API 端到端。
49
+
50
+ `test/session-log-v4.test.js`:`session[.vN].jsonl[.zstd]` 全版本枚举(v3/v4/v5/无版本/plain/zstd/空目录/非会话文件),并对照本机真实 `.dsh\sessions` 校验「磁盘上的 v4 全部被枚举到」。
51
+
52
+ `test/settings-compat.test.js`:`readSettingsSection()` 的双 API 兼容读(旧宿主 `get()` / 0.2.x `describe()` / 两者都在时 describe 优先 / 都不可用 / 抛错 / 非数组 / 非对象 / ns 非法)、10s 缓存与显式失效、不同 settings 实例互不串味。
53
+
54
+ > 测试口径:全仓 **22 个测试文件逐文件运行全绿**,`npm test`(CI 用的 `&&` 链)同样全绿 —— 发布工作流的 "Run tests" 关卡因此恢复可用。
55
+
56
+ > 说明:账号登录**不会**下发 API Key,因此「用账号登录直接请求 api.deepseek.com/user/balance」不可行;能查的是 **Platform 钱包**(与 DSH 官方「设置 → 账号与余额」同源),两者是同一 DeepSeek 账号的不同接口口径。
57
+
58
+ ## v1.9.5(2026-10-07)
59
+
60
+ **修复「桌面端(Electron 外壳)花费统计整块看板变成无样式原生控件」—— 自建 `<style>` 缺 `data-plugin` 归属标记,被 DSH 客户端模块系统认领给别的模块后在 HMR 清理时连带删除**
61
+
62
+ ### 一、根因(已复现并逐帧比对)
63
+
64
+ DSH 0.2 的客户端模块系统 `@deepseek-ai/dsh-client-modules/lib/client.js` 用两个函数管理插件样式表:
65
+
66
+ ```js
67
+ // 物化(materialize)一个模块的 factory 之后立刻盘点样式
68
+ const claimStyles = (id) => {
69
+ for (const el of document.querySelectorAll("style:not([data-plugin])")) el.setAttribute("data-plugin", id); // ← 无主的全认领
70
+ ...
71
+ };
72
+ // 某个模块被 HMR 失效 / 重载 / 剪枝时清理它的样式
73
+ function removeOwnedStyles(id) {
74
+ for (const el of document.querySelectorAll("style[data-plugin]")) if (el.getAttribute("data-plugin") === id) el.remove();
75
+ }
76
+ ```
77
+
78
+ **没打 `data-plugin` 的 `<style>` 会被「当时正在物化的那个模块」认领走。** 插件旧实现只打了
79
+ `data-plugin-css`,于是自己的样式表被登记在别的模块名下(本机实测被
80
+ `@deepseek-ai/dsh-api-remotes` 认领)。该模块一旦走到 `removeOwnedStyles(id)`
81
+ (HMR 清单里 `rev` 变化 → `updateManifest` 的 invalidate 分支、`reload()` 的非托管分支、
82
+ entry 重载、`prune()` 剪枝、factory 抛错的 catch),**连带把整块花费统计看板的 170 条
83
+ CSS 规则一起删掉**,界面退化成浏览器默认的 `<select>`/`<button>`/复选框排版:卡片边框、
84
+ 38 处自定义控件皮肤、图表网格与图例全部消失。
85
+
86
+ 为什么只在桌面端出现:Electron 外壳把 `apps/web` 的**原始 vite dist** 从
87
+ `dsh-app://app/` 提供(`resources/app.asar/dsh/node_modules/@deepseek-ai/dsh-web-frontend/dist`),
88
+ 启动图(`__ModuleLoader__` 队列引导、插件 `<link rel=preload>`、`__DSH_CONTACT_CONFIG__`)
89
+ 改由 IPC 取回 `ctx.webServer.collectIndexInjections()` 后**在运行期注入**;`dsh-client-hmr`
90
+ 随后推送的清单会让若干非托管行的 `rev` 与初始值不一致,触发上面那条清理路径。
91
+ 浏览器里的 `dsh web` 是宿主直接把启动图内联进 index.html,物化顺序不同、清单 rev 与本次启动一致,
92
+ 所以看不到 —— 这也解释了「同一个插件、同一份 client.js,网页版正常、桌面端无样式」。
93
+
94
+ **归属标记在插入前就要写好**:`claimStyles` 只认「当前是否已带 `data-plugin`」,
95
+ 插入后再补标会留下一个未被认领的窗口。
96
+
97
+ ### 二、修法(`client.js`)
98
+
99
+ 1. 新增模块 id 单一事实源 `var DSH_BUNDLE_ID = "@angelyeye/dsh-cost-tracker"`,
100
+ `__ModuleLoader__.load({ id })` 与样式归属标记共用它;
101
+ 2. `applyStyles()` 改为**先打标再插入**:
102
+ ```js
103
+ tag.setAttribute("data-plugin", DSH_BUNDLE_ID);
104
+ tag.setAttribute("data-plugin-css", DSH_STYLE_TAG_ID);
105
+ ```
106
+ 与宿主自带包的写法(`tag.dataset.plugin = "<包名>"`)逐字对齐;
107
+ 3. 顺带加上宿主同款去重护栏(`style[data-plugin-css="cost-tracker-plugin"]` 已存在就不再插第二张);
108
+ 4. 文件末尾注册名护栏保留它**刻意独立**的字面量副本(若与 `DSH_BUNDLE_ID` 同源,
109
+ 故障注入测试就永远测不出「注册名 ≠ 包名」了)。
110
+
111
+ ### 三、验证
112
+
113
+ - 真机复现(桌面端 profile 的等价宿主 + 无头 Edge/CDP,1280×820,与用户截图同视口):
114
+ - 修复前:插件样式表 `data-plugin = "@deepseek-ai/dsh-api-remotes"`(被误认领),
115
+ 模拟该模块的 `removeOwnedStyles` → 样式标签 1 张被删、看板立刻变成无样式原生控件,
116
+ 与用户截图逐项一致;
117
+ - 修复后:`data-plugin = "@angelyeye/dsh-cost-tracker"`,同样触发
118
+ `@deepseek-ai/dsh-api-remotes` 的清理 → 标签存活、`sheet.cssRules.length = 170`、
119
+ 6 张卡片仍在(`border-radius: 10px`、数值 `font-size: 24px`),截图正常。
120
+ - 极端对照:把 47 个无关模块的 168 张样式全删,本插件看板依然保持有样式。
121
+ - `test/client-render.test.js` 新增 [11](7 条断言):恰好注入一张样式表、
122
+ `data-plugin` 等于 bundle 注册名、`data-plugin-css` 保留、正文含关键规则、
123
+ 打标早于 `head.appendChild`、注册 id 与归属标记同源;
124
+ - `test/client-registration.test.js` 新增 [3b](5 条断言)钉住单一事实源与独立护栏副本,
125
+ 故障注入改为改写 `DSH_BUNDLE_ID`(同时覆盖注册与归属标记两个消费点);
126
+ - 全量 19 个测试文件通过。
127
+
128
+ ### 四、说明
129
+
130
+ - 只改客户端半端 `client.js`:不动任何计费/同步口径,HTTP 面、配置键、落盘路径、云端契约零改动;
131
+ - 客户端半端换版后**浏览器硬刷新**即可生效;另需确认宿主半端也已是新版(`index.js`/`PLUGIN_VERSION`);
132
+ - 同生态插件若自建 `<style>` 且只打 `data-plugin-css`,会踩同一个坑(本仓库的 `dshmarket` 已按约定打标)。
133
+
5
134
  ## v1.9.4(2026-09-24)
6
135
 
7
136
  **修复「配额查询不可用:火山方舟配额响应不是合法 JSON(GetCodingPlanUsage)」—— 宿主全局 fetch 被 undici 包污染后不解压 gzip,插件改为自带解压兜底**
package/README.en.md CHANGED
@@ -37,7 +37,7 @@
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
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 |
39
39
  | 📈 | **Subscription quota** | Kimi Coding Plan and **Volcengine Ark Coding Plan**: quota progress bars, reset countdowns and pay-as-you-go-equivalent cost for reference. Volcengine is queried through the Ark **control-plane OpenAPI** (HMAC-signed), requiring an AccessKeyID + SecretAccessKey pair |
40
- | 💳 | **Balance lookup** | One-click DeepSeek account balance (total / topped-up / granted / status) |
40
+ | 💳 | **Balance lookup** | One-click DeepSeek account balance (total / topped-up / granted / status); **signed in to a DSH account it reads the Platform wallets (top-up / bonus) directly — no API key needed (v1.9.6)** |
41
41
  | 🤖 | **Agent tools** | Ask in any chat: "how much have I spent today?" — the agent answers via `cost_stats` / `cost_prices` |
42
42
  | 🔻 | **Status line** | A live line under the chat input: **session cost** (segmented pills: session / subscription plan / per-model), split by the models actually used in the session; multi-model collapses to top2 by default, click to expand. Subscription shows the plan name; no quota or call-count clutter |
43
43
  | 🔥 | **Usage heatmap** | A "Token Usage" panel in Settings: a Codex-style **26-week daily-usage grid**, colored per-day by input / cache / output / cost with hover details and a today outline; all-time totals shown on top |
@@ -278,7 +278,7 @@ Only the three interface switches apply instantly; every other group is "edit dr
278
278
 
279
279
  ### History import (v1.9.0)
280
280
 
281
- Conversations from **before you installed the plugin** can be backfilled: the plugin replays the host session logs (`$DSH_HOME/sessions/<project>/<session>/session.v3.jsonl.zstd`, decompressed frame by frame — the host appends one zstd frame per batch) and books each model call at the price era of **its own timestamp**.
281
+ Conversations from **before you installed the plugin** can be backfilled: the plugin replays the host session logs (`$DSH_HOME/sessions/<project>/<session>/session[.vN].jsonl[.zstd]`, decompressed frame by frame — the host appends one zstd frame per batch; since v1.9.6 the `vN` version is detected automatically, so v4/v5 need no code change) and books each model call at the price era of **its own timestamp**.
282
282
 
283
283
  - **Auto-import on startup** by default (8 s delay, never blocks the boot), with an "Import now" button and an `autoImport` switch;
284
284
  - **Only calls the plugin could not have recorded**: earlier than this machine's first live record, or on a day with no live coverage at all (downtime gaps);
@@ -300,6 +300,27 @@ Conversations from **before you installed the plugin** can be backfilled: the pl
300
300
  - **No response ever echoes a secret**: status endpoints return only booleans plus the storage location (credential store / process memory). `AccessKeyID` is a non-sensitive identifier and is echoed so the form can be pre-filled;
301
301
  - **Egress protection**: any request carrying credentials must match the host allowlist (DeepSeek / Kimi / Volcengine control plane / your configured cloud URL / the pricing page host), non-loopback hosts must use https, and `redirect: 'manual'` is forced — any 3xx is treated as a failure so a redirect can never carry the `Authorization` header elsewhere.
302
302
 
303
+ ### Balance sources & account login (v1.9.6)
304
+
305
+ The lookup picks a source in this priority order — **account login neither needs nor accepts an API key**:
306
+
307
+ 1. **API key typed into the panel** (highest priority, explicit user action) → `https://api.deepseek.com/user/balance`;
308
+ 2. **DSH account login** → the host service `deepseekAccount.getBalance()`, which reads the Platform
309
+ wallets (`normal_wallets` = topped-up, `bonus_wallets` = granted; CNY / USD) — the same data source
310
+ as the official Settings → Account page;
311
+ 3. **API key from settings / environment** (`DEEPSEEK_API_KEY`) → same as 1.
312
+
313
+ Why two sources: DSH's account login stores its PKCE grant as a credentials **record**
314
+ (`deepseek-account-platform/default`) and **never issues an API key**; account inference uses
315
+ `x-dsh-auth-token` against the Platform gateway while API-key inference uses `x-api-key`, and the
316
+ runtime documents that the two routes **never fall back to each other**. "Log in, then query
317
+ api.deepseek.com with the token" is simply not a thing on 0.2.x.
318
+
319
+ Semantics: the account path reports **Platform wallets** (top-up and bonus listed separately,
320
+ total = the same-currency sum, added with exact decimal arithmetic); the API-key path keeps
321
+ `total_balance` / `granted_balance` / `topped_up_balance` and `is_available`. Hosts without a
322
+ `deepseekAccount` service fall back to the old path with v1.9.5 behaviour.
323
+
303
324
  ### HTTP API (for other tools)
304
325
 
305
326
  All endpoints are `POST` + JSON and listen on the loopback address:
@@ -319,7 +340,7 @@ POST /api/cost-tracker/cloud Read-only cloud aggregation (route/days/excl
319
340
  POST /api/cost-tracker/kimi-usage Kimi subscription quota
320
341
  POST /api/cost-tracker/volcengine-usage Volcengine Ark Coding Plan quota (5-hour / weekly / monthly windows)
321
342
  POST /api/cost-tracker/volcengine-config Save Volcengine AK/SK (reports only whether keys are configured, never the keys)
322
- POST /api/cost-tracker/balance Account balance
343
+ POST /api/cost-tracker/balance Account balance (account login first; pass {"apiKey":"sk-..."} to override)
323
344
  POST /api/cost-tracker/prices Price table (by pricing era + synced eras + multi-vendor catalog + overrides)
324
345
  POST /api/cost-tracker/recompute Re-price stored records by era (dry-run unless {"apply":true})
325
346
  POST /api/cost-tracker/billing-config Billing basis & catalog config (amount basis / plan overrides / match & fx / price overrides)
@@ -340,6 +361,66 @@ Example: `curl -X POST http://127.0.0.1:3080/api/cost-tracker/summary -d '{}'`
340
361
 
341
362
  > Highlights only — the full version-by-version history lives in [`CHANGELOG.md`](./CHANGELOG.md) (Chinese).
342
363
 
364
+ ### v1.9.6 (2026-10-17)
365
+
366
+ **Balance lookup now works with DSH "DeepSeek account login": under an account the plugin calls the host service `deepseekAccount.getBalance()` and reads the Platform wallets (top-up / bonus); the API-key path is unchanged**
367
+
368
+ - **Why it used to fail**: since 0.1.7 DSH supports browser PKCE account login, whose grant is stored
369
+ as a credentials **record** (`deepseek-account-platform/default` — `{version, token, issuer}`) and
370
+ **never as a ref**, while `credentials.resolve()` only reads the refs half. Account inference also
371
+ uses `x-dsh-auth-token` versus `x-api-key` for API keys, the runtime documents that the two routes
372
+ **never fall back to each other**, and `api.deepseek.com/user/balance` appears nowhere in the
373
+ runtime. An implementation that only knew `DEEPSEEK_API_KEY` therefore always reported
374
+ "DeepSeek API key not found" under a pure account login;
375
+ - **New priority**: API key typed in the panel > account login > configured/environment API key.
376
+ A failed account read does **not** fall back to an API key (that would show a different account's
377
+ numbers); the error tells the user to type a key instead;
378
+ - **Required contract**: the `client` argument's three fields (`version` / `locale` /
379
+ `timezoneOffsetSeconds`) are spliced into `x-client-*` headers by the runtime and a missing field
380
+ throws `TypeError`; the host always fills them in and the browser half overrides locale/time zone;
381
+ - **Semantics**: account "total" = same-currency top-up + bonus, added with exact decimal arithmetic;
382
+ `available` is `null` under an account (the Platform summary has no `is_available`, so "unknown" is
383
+ never rendered as "unavailable"); multi-currency picks CNY > USD and the symbol/title follow it;
384
+ - **No regression**: hosts without a `deepseekAccount` service take the old path with v1.9.5 wording;
385
+ - **Also fixed (same compatibility audit)**: (1) history import now recognises `session[.vN].jsonl[.zstd]`
386
+ — 0.2.x writes `session.v4.jsonl.zstd`, while the old code only enumerated v3/legacy names, so new
387
+ sessions were silently skipped (68 v4 sessions on this machine were missed; the content itself is
388
+ compatible); (2) the account provider `deepseek-account` now has a DeepSeek fallback price, so models
389
+ outside the exact table no longer fall to generic cache pricing (0.5 → 0.04) and keep peak/off-peak;
390
+ (3) settings reads migrated to 0.2.x's `settings.describe()` (`get()` was removed): the new
391
+ `settings.js` does "describe first, get as fallback", so **deployments with a custom `apiKeyEnv` no
392
+ longer resolve the wrong key name**;
393
+ - **Tests**: new `test/balance-account.test.js`, `test/session-log-v4.test.js` and
394
+ `test/settings-compat.test.js`; all **22 test files pass**, and `npm test` (the `&&` chain CI runs) is
395
+ green as well — this also fixes the pre-existing fake failure in `test/import.test.js` (fixed-date
396
+ fixture vs a relative `days` window), which was the reason CI's test gate went red.
397
+
398
+ ### v1.9.5 (2026-10-07)
399
+
400
+ **Fix "the whole Cost dashboard renders as unstyled native controls in the Desktop (Electron) app": the plugin's own `<style>` lacked a `data-plugin` ownership tag, so another module claimed it and HMR cleanup deleted it along with its own styles**
401
+
402
+ - **Root cause (reproduced)**: DSH 0.2's `@deepseek-ai/dsh-client-modules` calls `claimStyles(ownerId)`,
403
+ which claims **every `<style>` that has no `data-plugin`** for whichever module is materializing at that
404
+ moment, and `removeOwnedStyles(id)` deletes all tags tagged `id` when that module is invalidated,
405
+ reloaded or pruned. The plugin only set `data-plugin-css`, so its stylesheet was claimed by
406
+ `@deepseek-ai/dsh-api-remotes` — and when that module's styles were torn down, all 170 dashboard CSS
407
+ rules went with it: card borders, control skins and chart grid vanished, leaving raw
408
+ `<select>`/`<button>` chrome;
409
+ - **Why Desktop only**: the Electron shell serves the raw `apps/web` vite dist from `dsh-app://app/` and
410
+ applies the boot graph (ModuleLoader bootstrap, plugin preloads, contact config) **at runtime** over IPC;
411
+ the manifest `dsh-client-hmr` then pushes gives non-managed rows a different `rev`, which is exactly what
412
+ triggers that teardown path. `dsh web` inlines the boot graph into index.html, so materialization order
413
+ and revisions differ and the bug never fires there;
414
+ - **Fix**: `client.js` now has a single source of truth `DSH_BUNDLE_ID`, and `applyStyles()` sets
415
+ `data-plugin` **before** appending the tag (byte-for-byte the convention the host's own packages use),
416
+ plus the host's duplicate-tag guard;
417
+ - **Verification**: desktop-equivalent host + headless Edge/CDP at the same viewport as the report — before
418
+ the fix the emulated teardown removed the stylesheet and the dashboard became native controls; after the
419
+ fix the tag survives, `cssRules.length = 170` and all 6 cards keep their styling. 12 new assertions in
420
+ `client-render` [11] and `client-registration` [3b]; all 19 test files pass;
421
+ - **How it takes effect**: client half only — a **hard refresh** is enough; the host half's version is
422
+ bumped to 1.9.5 as well.
423
+
343
424
  ### v1.9.4 (2026-09-24)
344
425
 
345
426
  **Fix "Volcengine Ark quota response is not valid JSON": the host's global fetch stops decompressing gzip once the `undici` package is loaded, so the plugin now decodes bodies itself**
package/README.md CHANGED
@@ -38,7 +38,7 @@
38
38
  | 🧭 | **多机汇总(云端同步)** | 可对接**自建云端服务**(独立仓库 `dsh-cost-cloud`,零运行时依赖):多台电脑的用量汇总到一处,看板顶部出现 **本机 / 本机+云端 / 仅云端** 三态开关,并支持**设备 × Agent 矩阵**(行合计 = 列合计 = 总计);上报内容仅 token 数、费用、时间戳与标识符,可选会话脱敏 |
39
39
  | 🔥 | **用量热力图** | 设置页新增「Token 用量统计」:类 Codex 的 **26 周日用量方格热图**,按天着色(输入 / 缓存 / 输出 / 费用),悬停看当日明细、今天高亮描边,顶部显示全时段累计;**跟随三态视图**——「本机+云端 / 仅云端」下自动并入云端按天用量(卡片标题右侧标注当前口径) |
40
40
  | 📈 | **订阅配额监控** | Kimi Coding Plan、**火山方舟 Coding Plan** 等订阅套餐:配额进度条、重置倒计时、等效按量费用参考。火山方舟走管控面 OpenAPI(HMAC 签名),需 AccessKeyID + SecretAccessKey |
41
- | 💳 | **余额查询** | 一键查询 DeepSeek 官方账户余额(总余额 / 充值 / 赠送 / 状态) |
41
+ | 💳 | **余额查询** | 一键查询 DeepSeek 官方账户余额(总余额 / 充值 / 赠送 / 状态);**已登录 DSH 账号时直接读 Platform 钱包(充值 / 赠金),不再需要 API Key(v1.9.6)** |
42
42
  | 🤖 | **Agent 工具** | 直接在对话里问:"我现在花了多少钱?"——Agent 会调用 `cost_stats` / `cost_prices` 等工具回答 |
43
43
  | 🔻 | **状态栏** | 聊天输入框下方实时显示:**本会话花费**(胶囊分段:本会话 / 订阅套餐 / 分模型),按会话实际用到的模型与订阅拆分,**多模型默认折叠只显示 top2,点击展开全部明细**;订阅显示具体套餐名,不再展示配额与调用次数 |
44
44
  | 👁️ | **界面显示开关** | 输入框上方的花费胶囊、侧边栏峰谷时段条、设置页「花费统计」看板**三个落点各自可关**(设置 → 花费统计 → 右上角齿轮 → 数据与界面 → 界面显示),勾选即刻生效;**只影响显示**,记账、云端同步与 Agent 工具照常,配置入口(齿轮页)本身不受开关控制 |
@@ -279,7 +279,7 @@ docker compose up -d # 打开 http://<服务器>:8787 ,在「设置」页
279
279
 
280
280
  ### 历史导入(v1.9.0)
281
281
 
282
- 装上插件之前的对话也能补进账本:插件回放宿主会话日志(`$DSH_HOME/sessions/<项目>/<会话>/session.v3.jsonl.zstd`,多 zstd frame 逐帧解压、逐帧切片),把其中的模型调用按**当时时间戳**的计费口径入账。
282
+ 装上插件之前的对话也能补进账本:插件回放宿主会话日志(`$DSH_HOME/sessions/<项目>/<会话>/session[.vN].jsonl[.zstd]`,多 zstd frame 逐帧解压、逐帧切片;v1.9.6 起按 `vN` 自动识别版本,v4/v5 无需改代码),把其中的模型调用按**当时时间戳**的计费口径入账。
283
283
 
284
284
  - 默认**开机自动导入**(延迟 8 秒,不阻塞启动),也可在配置页点「立即导入」或关掉自动(`autoImport`);
285
285
  - **只补「插件不可能记到」的调用**:早于本机最早一条实时记录,或所在日完全没有实时覆盖(停机缺口);
@@ -301,6 +301,26 @@ docker compose up -d # 打开 http://<服务器>:8787 ,在「设置」页
301
301
  - **任何响应都不回显密钥**:状态接口只给布尔与「存储位置」(凭据库 / 进程内存),`AccessKeyID` 属非敏感标识才会回显以便预填;
302
302
  - **出站防护**:携带凭据的请求必须命中主机白名单(DeepSeek / Kimi / 火山管控面 / 配置的云端地址 / 定价页主机),非本机地址强制 https,`redirect: 'manual'` —— 3xx 一律按失败处理,防止重定向把 `Authorization` 头带去别处。
303
303
 
304
+ ### 余额来源与账号登录(v1.9.6)
305
+
306
+ 余额查询按以下优先级选来源,**账号登录不需要也不接受 API Key**:
307
+
308
+ 1. **面板手填 API Key**(最高优先,用户显式动作)→ 请求 `https://api.deepseek.com/user/balance`;
309
+ 2. **DSH 账号登录态** → 调宿主服务 `deepseekAccount.getBalance()`,读 Platform 钱包
310
+ (`normal_wallets` = 充值钱包、`bonus_wallets` = 赠金钱包,币种 CNY / USD),
311
+ 与官方「设置 → 账号与余额」同源;
312
+ 3. **配置 / 环境里的 API Key**(`DEEPSEEK_API_KEY`)→ 同 1。
313
+
314
+ 为什么必须分两条:DSH 的账号登录用 PKCE 授权把 token 写进凭据库的 **record**
315
+ (`deepseek-account-platform/default`),**不会下发 API Key**;账号态推理用
316
+ `x-dsh-auth-token` 走 Platform 网关、API Key 态用 `x-api-key`,运行时文档明确两条路由
317
+ **互不回退**。因此「登录后拿 key 去查 api.deepseek.com」这条路在 0.2.x 里不存在。
318
+
319
+ 口径差异:账号态展示的是 **Platform 钱包**(充值 / 赠金分开列示,总额 = 同币种两者之和,
320
+ 精确十进制相加);API Key 态沿用 `total_balance` / `granted_balance` /
321
+ `topped_up_balance` 与 `is_available`。没有 `deepseekAccount` 服务的旧宿主自动走原路径,
322
+ 行为与 v1.9.5 一致。
323
+
304
324
  ### HTTP API(供其他工具调用)
305
325
 
306
326
  全部为 `POST` + JSON,监听本机地址:
@@ -320,7 +340,7 @@ POST /api/cost-tracker/cloud 云端只读聚合(route/days/excludeSelf/de
320
340
  POST /api/cost-tracker/kimi-usage Kimi 订阅配额
321
341
  POST /api/cost-tracker/volcengine-usage 火山方舟 Coding Plan 配额(5 小时/周/月窗口)
322
342
  POST /api/cost-tracker/volcengine-config 保存火山方舟 AK/SK(只回显「是否已配置」,不回显密钥)
323
- POST /api/cost-tracker/balance 账户余额
343
+ POST /api/cost-tracker/balance 账户余额(账号登录态优先;传 {"apiKey":"sk-…"} 可手填覆盖)
324
344
  POST /api/cost-tracker/prices 单价表(按计费时代分版 + 同步时代 + 多厂商目录 + 覆盖价)
325
345
  POST /api/cost-tracker/recompute 按计费时代重算已入库记录(默认只试算,传 {"apply":true} 落盘)
326
346
  POST /api/cost-tracker/billing-config 双轨计费与目录配置(金额口径/订阅归类/匹配与汇率/覆盖价)
@@ -341,6 +361,58 @@ POST /api/cost-tracker/export 导出 CSV
341
361
 
342
362
  > 这里只列重要版本;逐版完整记录见 [`CHANGELOG.md`](./CHANGELOG.md)。
343
363
 
364
+ ### v1.9.6(2026-10-17)
365
+
366
+ **新增:余额查询兼容 DSH「DeepSeek 账号登录」—— 账号态改走宿主 `deepseekAccount.getBalance()` 读 Platform 钱包(充值 / 赠金),API Key 路径原样保留**
367
+
368
+ - **为什么之前查不到**:0.1.7 起 DSH 支持浏览器 PKCE 账号登录,授权只写进凭据库的 **record**
369
+ `deepseek-account-platform/default`(`{version, token, issuer}`),**从不写 ref**,而
370
+ `credentials.resolve()` 只查 refs 半区 —— 账号 token 没有 ref 名;同时账号态推理用
371
+ `x-dsh-auth-token`、API Key 态用 `x-api-key`,运行时文档明确两者「互不回退」,且整个运行时里
372
+ `api.deepseek.com/user/balance` 零命中。于是只认 `DEEPSEEK_API_KEY` 的旧实现,在纯账号态下
373
+ 必然报「未找到 DeepSeek API Key」;
374
+ - **新优先级**:面板手填 Key > 账号登录态 > 配置/环境 API Key。账号态**失败不回退** API Key
375
+ (回退会显示另一个账户的数字),错误信息直接给出「手动填 Key」的出路;
376
+ - **必填契约**:`getBalance(client)` 的 `client` 三字段(`version` / `locale` /
377
+ `timezoneOffsetSeconds`)会被运行时直接拼进 `x-client-*` 头,缺一个就抛 `TypeError`;
378
+ 宿主侧一律补齐,浏览器半端再用 `navigator.language` 与本机时区覆盖;
379
+ - **口径**:账号钱包「总余额 = 同币种充值 + 同币种赠金」,用 BigInt 精确十进制相加;
380
+ 账号态 `available` 为 `null`(Platform 摘要没有 `is_available`,不把未知渲染成不可用);
381
+ 多币种按 CNY > USD 选主币种,符号与标题跟随币种;
382
+ - **零影响**:没有 `deepseekAccount` 服务的旧宿主自动走原路径,文案与 v1.9.5 逐字一致;
383
+ - **顺带修复(同一轮 0.2.x 兼容审计)**:① 历史导入现在识别 `session[.vN].jsonl[.zstd]` ——
384
+ 0.2.x 起新会话写成 `session.v4.jsonl.zstd`,旧实现只认 v3/legacy 名字,导致新会话被**静默跳过**
385
+ (本机 68 个 v4 会话全部漏掉;内容层其实兼容);② 账号态 provider `deepseek-account` 补上
386
+ DeepSeek 兜底价,精确价表之外的新模型不再落到 generic 缓存价(0.5 → 0.04)且保留峰谷半价;
387
+ ③ 设置读取迁移到 0.2.x 的 `settings.describe()`(`get()` 已被移除):新增 `settings.js` 做
388
+ 「describe 优先、get 兜底」的兼容读,**自定义 `apiKeyEnv` 的部署不再取错 Key 名**;
389
+ - **测试**:新增 `test/balance-account.test.js`、`test/session-log-v4.test.js`、
390
+ `test/settings-compat.test.js`;全仓 **22 个测试文件逐文件运行全绿**,`npm test`(CI 用的 `&&` 链)
391
+ 同样全绿(同时修掉了 `test/import.test.js` 里因固定日期 fixture 造成的既有假失败 —— 它正是
392
+ `npm test` 变红、挡住发布的根因)。
393
+
394
+ ### v1.9.5(2026-10-07)
395
+
396
+ **修复「桌面端(Electron 外壳)花费统计整块看板变成无样式原生控件」:自建 `<style>` 缺 `data-plugin` 归属标记,被别的模块认领后在 HMR 清理时连带删除**
397
+
398
+ - **根因(已复现)**:DSH 0.2 的 `@deepseek-ai/dsh-client-modules` 用
399
+ `claimStyles(ownerId)` 把**所有没带 `data-plugin` 的 `<style>` 认领给当时正在物化的模块**,
400
+ 再用 `removeOwnedStyles(id)` 在该模块 HMR 失效 / 重载 / 剪枝时整片删除。
401
+ 插件旧实现只打了 `data-plugin-css`,实测样式表被 `@deepseek-ai/dsh-api-remotes` 认领,
402
+ 该模块一被清理就带走看板的 170 条 CSS 规则 —— 卡片边框、控件皮肤、图表网格全部消失,
403
+ 界面退化成浏览器默认的 `<select>`/`<button>` 排版;
404
+ - **为什么只在桌面端**:Electron 外壳把 `apps/web` 的原始 vite dist 从 `dsh-app://app/` 提供,
405
+ 启动图(ModuleLoader 引导、插件 preload、contact config)改由 IPC 取回后在**运行期注入**,
406
+ 随后 `dsh-client-hmr` 推送的清单让非托管行的 `rev` 与初始值不一致,正好命中那条清理路径;
407
+ 浏览器里的 `dsh web` 把启动图内联在 index.html 里,物化顺序与 rev 都不同,所以看不到;
408
+ - **修法**:`client.js` 新增模块 id 单一事实源 `DSH_BUNDLE_ID`,`applyStyles()` 改为
409
+ **先 `setAttribute("data-plugin", DSH_BUNDLE_ID)` 再插入**(与宿主自带包 `tag.dataset.plugin = "<包名>"`
410
+ 的约定逐字对齐),并补上宿主同款去重护栏;
411
+ - **验证**:桌面端等价宿主 + 无头 Edge/CDP(与用户截图同视口)—— 修复前模拟该模块清理后样式表被删、
412
+ 看板变原生控件;修复后同样清理,标签存活、`cssRules.length = 170`、6 张卡片样式完好。
413
+ 新增 `client-render` [11] 与 `client-registration` [3b] 共 12 条断言,全量 19 个测试文件通过;
414
+ - **生效条件**:只改客户端半端,**浏览器硬刷新**即可;宿主半端版本号同步升到 1.9.5。
415
+
344
416
  ### v1.9.4(2026-09-24)
345
417
 
346
418
  **修复「火山方舟配额响应不是合法 JSON」:宿主全局 fetch 被 undici 包污染后不解压 gzip,插件改为自带解压兜底**
package/account.js ADDED
@@ -0,0 +1,222 @@
1
+ // ============================================================
2
+ // DSH 0.2.1-rc.2+「DeepSeek 账号登录」余额适配 —— 纯投影层
3
+ //
4
+ // 为什么需要这一层(背景,来自 0.2.1-rc.2 运行时源码,见 README 的「账号登录」节):
5
+ // · 0.2.1-rc.2 起 DSH 支持浏览器 PKCE 账号登录。账号态推理用
6
+ // `x-dsh-auth-token` 走 Platform 网关(@deepseek-ai/dsh-llm-deepseek-account),
7
+ // README 原文:「不会回退到 API key」——**登录不会下发 API Key**。
8
+ // · 插件旧版余额只认 `DEEPSEEK_API_KEY` 去请求
9
+ // https://api.deepseek.com/user/balance,于是账号态下永远「未找到 DeepSeek API Key」。
10
+ // · 账号余额的正规取法:宿主服务 `deepseekAccount.getBalance(client)`,
11
+ // 内部请求 Platform Web 的 GET /api/v0/users/get_user_summary。
12
+ //
13
+ // 契约(逐字核对过 0.2.1-rc.2 的 lib/types/*.js):
14
+ // getBalance(client) → null
15
+ // | { status: 'failed' }
16
+ // | { status: 'ready', value: Wallet[], bonusWallets: Wallet[] }
17
+ // Wallet = { currency: 'CNY' | 'USD', balance: '<十进制字符串>' }
18
+ // · value = 充值钱包(normal_wallets)
19
+ // · bonusWallets = 赠金钱包(bonus_wallets)
20
+ // · null = 没有已存授权(未登录),或查询期间凭据被清除
21
+ // · 'failed' = 网络/超时/协议类失败(**不会**被伪造成 0 余额)
22
+ // client 参数**必填**:platformClientHeaders 直接读
23
+ // client.version / client.locale / client.timezoneOffsetSeconds,
24
+ // 少一个就抛 TypeError —— 所以本模块必须把三个字段补齐再调用。
25
+ //
26
+ // 本模块只做「纯投影」:不碰 ctx、不发网络请求,便于在无 DSH 运行时的环境下
27
+ // 直接单测(见 test/balance-account.test.js)。宿主侧调用见 index.js 的 balance()。
28
+ // ============================================================
29
+
30
+ /** 余额/钱包金额的十进制文法:与 0.2.1-rc.2 运行时 zod 校验器逐字一致。 */
31
+ const DECIMAL_RE = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/
32
+
33
+ /** 币种偏好:与旧版 API Key 路径「优先取 CNY」保持一致。 */
34
+ const CURRENCY_PREFERENCE = ['CNY', 'USD']
35
+
36
+ /** 数字字面量的符号(视图层用)。 */
37
+ export function currencySymbol(currency) {
38
+ return String(currency || '').toUpperCase() === 'USD' ? '$' : '¥'
39
+ }
40
+
41
+ /**
42
+ * 解析十进制字符串为「BigInt 系数 + 小数位数」。
43
+ * @param {string} value - 形如 "12.34" / "-0.5" / "0E-16" / "1e+3"
44
+ * @returns {{coef:bigint, scale:number}|null} 不合法返回 null
45
+ */
46
+ function decParse(value) {
47
+ const text = String(value === null || value === undefined ? '' : value).trim()
48
+ const m = DECIMAL_RE.exec(text)
49
+ if (!m) return null
50
+ const intPart = m[2] || ''
51
+ const fracPart = m[3] || ''
52
+ // "1." / ".5" / "0" 都合法;"." 单独一个不合法
53
+ if (!intPart && !fracPart) return null
54
+ const exp = m[4] ? parseInt(m[4], 10) : 0
55
+ if (!Number.isFinite(exp) || Math.abs(exp) > 200) return null
56
+ const sign = m[1] === '-' ? -1n : 1n
57
+ const digits = (intPart + fracPart).replace(/^0+(?=\d)/, '') || '0'
58
+ let coef = BigInt(digits) * sign
59
+ let scale = fracPart.length - exp
60
+ if (scale < 0) {
61
+ coef *= 10n ** BigInt(-scale)
62
+ scale = 0
63
+ }
64
+ return { coef, scale }
65
+ }
66
+
67
+ /** 把「系数 + 小数位数」格式化成十进制字符串(不丢精度、不做四舍五入)。 */
68
+ function decFormat(coef, scale) {
69
+ // 零统一输出 "0":Platform 会返回 0E-16 这类「零但带巨大尾数」的值,
70
+ // 若原样展开会变成 0.0000000000000000,界面上毫无意义。
71
+ if (coef === 0n) return '0'
72
+ const negative = coef < 0n
73
+ let abs = negative ? -coef : coef
74
+ let text = abs.toString()
75
+ if (scale > 0) {
76
+ while (text.length <= scale) text = '0' + text
77
+ text = text.slice(0, text.length - scale) + '.' + text.slice(text.length - scale)
78
+ }
79
+ return (negative ? '-' : '') + text
80
+ }
81
+
82
+ /**
83
+ * 精确十进制加法(字符串进、字符串出,不经过 Number,避免 0.1+0.2 类误差)。
84
+ * 非法输入按 0 处理 —— 钱包原始字符串另存在结果里,不会丢证据。
85
+ * @param {string} a
86
+ * @param {string} b
87
+ * @returns {string}
88
+ */
89
+ export function decAdd(a, b) {
90
+ const x = decParse(a)
91
+ const y = decParse(b)
92
+ const left = x || { coef: 0n, scale: 0 }
93
+ const right = y || { coef: 0n, scale: 0 }
94
+ const scale = Math.max(left.scale, right.scale)
95
+ const lc = left.coef * 10n ** BigInt(scale - left.scale)
96
+ const rc = right.coef * 10n ** BigInt(scale - right.scale)
97
+ return decFormat(lc + rc, scale)
98
+ }
99
+
100
+ /** 多个十进制字符串求和。 */
101
+ export function decSum(list) {
102
+ let total = '0'
103
+ for (const v of list || []) total = decAdd(total, v)
104
+ return total
105
+ }
106
+
107
+ /**
108
+ * 构造 getBalance(client) 的 client 元数据。
109
+ *
110
+ * 三个字段都必填:缺 version 时用插件自身版本,缺 locale 时按宿主运行环境的
111
+ * 默认语言(Node 自带完整 ICU),缺时区偏移时用本机时区。浏览器半端会把
112
+ * navigator.language 与本机时区一起传上来(见 client.js 的 balanceClientMeta)。
113
+ *
114
+ * @param {object} [input] - 来自 HTTP 参数 { version, locale, timezoneOffsetSeconds }
115
+ * @param {string} [fallbackVersion] - 缺省版本号(插件版本)
116
+ * @returns {{version:string, locale:string, timezoneOffsetSeconds:number}}
117
+ */
118
+ export function accountClientMeta(input, fallbackVersion) {
119
+ const src = input && typeof input === 'object' ? input : {}
120
+ let version = typeof src.version === 'string' && src.version.trim() ? src.version.trim() : ''
121
+ if (!version) version = typeof fallbackVersion === 'string' && fallbackVersion.trim() ? fallbackVersion.trim() : '0.0.0'
122
+ let locale = typeof src.locale === 'string' && src.locale.trim() ? src.locale.trim() : ''
123
+ if (!locale) {
124
+ try { locale = String(Intl.DateTimeFormat().resolvedOptions().locale || '') } catch (e) { locale = '' }
125
+ }
126
+ if (!locale) locale = 'zh-CN'
127
+ let tz = Number(src.timezoneOffsetSeconds)
128
+ if (!Number.isFinite(tz)) tz = -new Date().getTimezoneOffset() * 60
129
+ return { version, locale, timezoneOffsetSeconds: Math.round(tz) }
130
+ }
131
+
132
+ /** 钱包数组归一化:只留币种与金额都合法的项,保留原始金额字符串。 */
133
+ function normalizeWallets(list, kind) {
134
+ const out = []
135
+ if (!Array.isArray(list)) return out
136
+ for (const w of list) {
137
+ if (!w || typeof w !== 'object') continue
138
+ const currency = typeof w.currency === 'string' ? w.currency.toUpperCase() : ''
139
+ if (!currency) continue
140
+ const balance = w.balance === null || w.balance === undefined ? '' : String(w.balance)
141
+ if (!decParse(balance)) continue
142
+ out.push({ currency, balance, kind })
143
+ }
144
+ return out
145
+ }
146
+
147
+ /** 取某币种的合计(无该币种钱包时返回 '0')。 */
148
+ function sumCurrency(wallets, currency) {
149
+ const amounts = []
150
+ for (const w of wallets) if (w.currency === currency) amounts.push(w.balance)
151
+ return amounts.length ? decSum(amounts) : '0'
152
+ }
153
+
154
+ /**
155
+ * 把 `deepseekAccount.getBalance()` 的 ready 结果投影成本插件既有的 balance 形状。
156
+ *
157
+ * 兼容性:`total` / `granted` / `toppedUp` / `currency` / `keySource` 全部沿用旧字段,
158
+ * 新增 `source: 'account'`、`available: null`(账号态无法判断官方 is_available)与
159
+ * `wallets` / `currencies`(多币种时视图层可逐个展示)。
160
+ *
161
+ * 口径说明:Platform 的充值钱包与赠金钱包是**两个**钱包,
162
+ * 「总余额」= 同币种充值合计 + 同币种赠金合计(官方 Web 也是分开列示)。
163
+ *
164
+ * @param {object} details - getBalance 的返回值
165
+ * @returns {object|null} ready 时返回插件形状;非 ready(含 null)返回 null
166
+ */
167
+ export function mapAccountBalance(details) {
168
+ if (!details || typeof details !== 'object' || details.status !== 'ready') return null
169
+ // 运行时契约里两个数组永远存在;缺失说明服务形状变了 —— 这时宁可失败,
170
+ // 也不能把「不知道」渲染成「0 余额」(0.2.1-rc.2 自己的实现同样坚持这一点)。
171
+ if (!Array.isArray(details.value) || !Array.isArray(details.bonusWallets)) return null
172
+ const recharge = normalizeWallets(details.value, 'recharge')
173
+ const bonus = normalizeWallets(details.bonusWallets, 'bonus')
174
+ // 有元素但全被校验挡掉 = 载荷损坏 → 失败,而不是静默归零
175
+ if ((details.value.length && !recharge.length) || (details.bonusWallets.length && !bonus.length)) return null
176
+ const currencies = []
177
+ for (const w of recharge) if (currencies.indexOf(w.currency) < 0) currencies.push(w.currency)
178
+ for (const w of bonus) if (currencies.indexOf(w.currency) < 0) currencies.push(w.currency)
179
+ let currency = ''
180
+ for (const c of CURRENCY_PREFERENCE) {
181
+ if (currencies.indexOf(c) >= 0) { currency = c; break }
182
+ }
183
+ if (!currency) currency = currencies[0] || 'CNY'
184
+ const toppedUp = sumCurrency(recharge, currency)
185
+ const granted = sumCurrency(bonus, currency)
186
+ return {
187
+ ok: true,
188
+ error: '',
189
+ // 账号态没有 is_available 这一说(余额不足是请求失败时由宿主提示);
190
+ // 用 null 而不是 false,避免把「未知」显示成「不可用」。
191
+ available: null,
192
+ source: 'account',
193
+ keySource: 'account',
194
+ currency,
195
+ total: decAdd(toppedUp, granted),
196
+ toppedUp,
197
+ granted,
198
+ currencies,
199
+ wallets: recharge.concat(bonus),
200
+ }
201
+ }
202
+
203
+ /**
204
+ * 账号余额查询失败的统一形状(保持旧字段齐全,视图层无需特判空值)。
205
+ * @param {string} error - 面向用户的中文错误说明
206
+ * @returns {object}
207
+ */
208
+ export function accountBalanceFailure(error) {
209
+ return {
210
+ ok: false,
211
+ error: String(error || '账号余额查询失败'),
212
+ available: null,
213
+ source: 'account',
214
+ keySource: 'account',
215
+ currency: 'CNY',
216
+ total: '',
217
+ toppedUp: '',
218
+ granted: '',
219
+ currencies: [],
220
+ wallets: [],
221
+ }
222
+ }
package/client.js CHANGED
@@ -6,8 +6,28 @@
6
6
  // React → require('react')
7
7
  // 输出为浏览器 ModuleLoader bundle:exports.apply / exports.inject
8
8
  // ============================================================
9
+ /**
10
+ * 单一事实源:本 bundle 的模块 id(= package.json 的 name)。
11
+ * 两处消费它:
12
+ * 1. `__ModuleLoader__.load({ id })` —— 加载器按模块图里的 row.id 取 bundle,
13
+ * 注册名必须逐字一致(见文件末尾的注册名护栏)。
14
+ * 2. 运行时注入的 <style> 上的 `data-plugin` 归属标记(见 applyStyles)。
15
+ * DSH 0.2 的客户端模块系统(@deepseek-ai/dsh-client-modules)用
16
+ * `claimStyles(ownerId)` 认领样式:「已带 data-plugin 的按标注归属,
17
+ * 没带的一律算到当前正在物化的那个插件头上(HMR 记账)」,随后
18
+ * `removeOwnedStyles(id)` 会把这些标记为 id 的 <style> 整片删除。
19
+ * 所以自建 <style> 必须**先**打上自己的 data-plugin 再插入,否则会被
20
+ * 别的模块认领,并在该模块 HMR/失效时连同我们自己的样式一起被删掉
21
+ * (桌面端 Electron 外壳就是这条路径:启动期内核注入 + HMR 清单同步,
22
+ * 导致样式被连带清除 —— 整块看板退化为无样式的原生控件)。
23
+ * 注:文件末尾的注册名护栏另有一份**刻意独立**的字面量副本,见那里的说明。
24
+ */
25
+ var DSH_BUNDLE_ID = "@angelyeye/dsh-cost-tracker";
26
+ /** 本插件样式表的稳定标识(data-plugin-css 值,用于去重与盘点)。 */
27
+ var DSH_STYLE_TAG_ID = "cost-tracker-plugin";
28
+
9
29
  window.__ModuleLoader__.load({
10
- id: "@angelyeye/dsh-cost-tracker",
30
+ id: DSH_BUNDLE_ID,
11
31
  factory: (require) => {
12
32
  var module = { exports: {} };
13
33
  var exports = module.exports;
@@ -283,8 +303,13 @@ window.__ModuleLoader__.load({
283
303
  .cost-subblock { border-top: .5px dashed var(--dsw-alias-border-l2, #e5e7eb); margin-top: 10px; padding-top: 10px; }
284
304
  .cost-list { font-size: 12px; color: var(--dsw-alias-label-secondary, #5b6472); line-height: 1.7; }
285
305
  `;
306
+ // 先打归属标记再插入:宿主在 style[data-plugin] 上做归属记账,
307
+ // 未标注的标签会被下一个物化的模块用 claimStyles() 认领走
308
+ // (随后 removeOwnedStyles() 会在该模块失效时连带删除)。
309
+ if (document.querySelector('style[data-plugin-css="' + DSH_STYLE_TAG_ID + '"]') !== null) return;
286
310
  const tag = document.createElement("style");
287
- tag.setAttribute("data-plugin-css", "cost-tracker-plugin");
311
+ tag.setAttribute("data-plugin", DSH_BUNDLE_ID);
312
+ tag.setAttribute("data-plugin-css", DSH_STYLE_TAG_ID);
288
313
  tag.textContent = css;
289
314
  document.head.appendChild(tag);
290
315
  ctx.effect(() => () => { tag.remove(); }, "cost-tracker: styles");
@@ -902,6 +927,45 @@ window.__ModuleLoader__.load({
902
927
  : e("span", { className: "cost-hint" }, "峰谷时段(北京时间):" + peakWindows + " · 闲时半价"));
903
928
  }
904
929
 
930
+ // 余额金额的展示格式化。
931
+ // 账号登录态的钱包金额是 Platform 原样返回的十进制字符串,实测**16 位小数**
932
+ // (例如 "1234.5600000000000000")—— 直接拼进界面会显示成 16 位有效数字,
933
+ // 既难读也会让人误以为精度有意义。这里按 DSH 官方「账号与余额」页的口径:
934
+ // 正金额**截断**到分(不四舍五入,官方就是截断),不足一分的正金额显示 <0.01;
935
+ // 负数保留符号。API Key 态本来就是两位小数,走同一函数不改变结果。
936
+ function fmtBalanceAmount(v) {
937
+ let s = String(v === null || v === undefined ? "" : v).trim();
938
+ // 与运行时一致,接受省略整数/小数部分与十进制指数(Platform 会返回 "0E-16" 这类值)
939
+ const m = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(s);
940
+ if (!m || (!m[2] && !m[3])) return s || "0";
941
+ const neg = m[1] === "-";
942
+ let intPart = m[2] || "";
943
+ let frac = m[3] || "";
944
+ const exp = m[4] ? parseInt(m[4], 10) : 0;
945
+ if (exp) {
946
+ // 展示用:把指数并进小数点位置;指数过大时不硬撑(返回原串,避免生成巨长字符串)
947
+ if (Math.abs(exp) > 30) return s;
948
+ const digits = intPart + frac;
949
+ const point = intPart.length + exp;
950
+ if (point <= 0) {
951
+ intPart = "0";
952
+ frac = "0".repeat(-point) + digits;
953
+ } else if (point >= digits.length) {
954
+ intPart = digits + "0".repeat(point - digits.length);
955
+ frac = "";
956
+ } else {
957
+ intPart = digits.slice(0, point);
958
+ frac = digits.slice(point);
959
+ }
960
+ }
961
+ intPart = intPart.replace(/^0+(?=\d)/, "") || "0";
962
+ const cents = (frac + "00").slice(0, 2);
963
+ const out = intPart + "." + cents;
964
+ // 正的不足一分:官方口径显示 <0.01(不能显示 0.00,那会被读成没余额)
965
+ if (!neg && out === "0.00" && /[1-9]/.test(frac)) return "<0.01";
966
+ return (neg ? "-" : "") + out;
967
+ }
968
+
905
969
  function statCards(dash, balance, viewCtl, planTotal) {
906
970
  const today = dash.today || { real: 0, calls: 0, tokens: 0, sub: 0, subCalls: 0, subTokens: 0 };
907
971
  const month = dash.month || { real: 0, calls: 0, tokens: 0, sub: 0, subCalls: 0, subTokens: 0 };
@@ -918,11 +982,19 @@ window.__ModuleLoader__.load({
918
982
  return base + (t.sub > 0 ? " · 订阅 ¥" + fmtMoney(t.sub) : "");
919
983
  };
920
984
  const planBadge = planTotal ? "(含 Plan)" : "";
921
- // 余额卡
922
- let balValue = "—", balSub = "查询中…";
985
+ // 余额卡:两种口径(v1.9.6)
986
+ // · 账号登录态(DSH 0.2.1-rc.2+,source="account"):Platform 钱包,
987
+ // 充值 / 赠金分离,没有官方的 is_available 标志(宿主 getBalance 不返回);
988
+ // · API Key 态(source="apikey"):api.deepseek.com/user/balance,带 is_available。
989
+ let balValue = "—", balSub = "查询中…", balTitle = "总余额(CNY)";
923
990
  if (balance && balance.ok) {
924
- balValue = "¥" + (balance.total || "0");
925
- balSub = (balance.available ? "可用" : "不可用") + " · 充值 ¥" + (balance.toppedUp || "0") + " · 赠送 ¥" + (balance.granted || "0") + " · " + (balance.keySource || "");
991
+ const isAccount = balance.source === "account";
992
+ const sym = balance.currency === "USD" ? "$" : "¥";
993
+ if (balance.currency) balTitle = "总余额(" + balance.currency + ")";
994
+ balValue = sym + fmtBalanceAmount(balance.total || "0");
995
+ balSub = isAccount
996
+ ? "账号登录 · 充值 " + sym + fmtBalanceAmount(balance.toppedUp || "0") + " · 赠金 " + sym + fmtBalanceAmount(balance.granted || "0")
997
+ : (balance.available ? "可用" : "不可用") + " · 充值 " + sym + fmtBalanceAmount(balance.toppedUp || "0") + " · 赠送 " + sym + fmtBalanceAmount(balance.granted || "0") + " · " + (balance.keySource || "");
926
998
  } else if (balance && balance.error) {
927
999
  balSub = balance.error;
928
1000
  }
@@ -944,7 +1016,7 @@ window.__ModuleLoader__.load({
944
1016
  "按量 " + fmtInt(all.calls) + " · 订阅 " + fmtInt(all.subCalls)),
945
1017
  statCard("Tokens", fmtInt(all.tokens + all.subTokens),
946
1018
  "按量 " + fmtCompact(all.tokens) + " · 订阅 " + fmtCompact(all.subTokens)),
947
- statCard("总余额(CNY)", balValue, balSub));
1019
+ statCard(balTitle, balValue, balSub));
948
1020
  }
949
1021
 
950
1022
  function mainPanel(dash, tab, setTab, scheme, setScheme, planTotal) {
@@ -1143,16 +1215,21 @@ window.__ModuleLoader__.load({
1143
1215
  } else if (!balance.ok) {
1144
1216
  body = e("div", { className: "cost-err" }, "余额查询失败:" + (balance.error || "未知错误"));
1145
1217
  } else {
1218
+ // 账号登录态:Platform 钱包(充值 / 赠金分开列示,与 DSH 官方「账号与余额」页口径一致)
1219
+ const isAccount = balance.source === "account";
1220
+ const sym = balance.currency === "USD" ? "$" : "¥";
1146
1221
  body = e("div", { className: "cost-row", style: { gap: "4px" } },
1147
- kv("总余额", "¥" + balance.total),
1148
- kv("充值余额", "¥" + balance.toppedUp),
1149
- kv("赠送余额", "¥" + balance.granted),
1150
- kv("状态", balance.available ? "可用" : "不可用"),
1151
- e("span", { className: "cost-hint" }, "Key 来源:" + balance.keySource));
1222
+ kv(isAccount ? "账号总余额" : "总余额", sym + fmtBalanceAmount(balance.total)),
1223
+ kv("充值余额", sym + fmtBalanceAmount(balance.toppedUp)),
1224
+ kv(isAccount ? "赠金余额" : "赠送余额", sym + fmtBalanceAmount(balance.granted)),
1225
+ kv("状态", isAccount ? "账号登录" : (balance.available ? "可用" : "不可用")),
1226
+ e("span", { className: "cost-hint" }, isAccount ? "来源:DeepSeek 账号登录(Platform 钱包)" : "Key 来源:" + balance.keySource));
1152
1227
  }
1153
1228
  return e("div", { className: "cost-panel" },
1154
1229
  e("div", { className: "cost-row" }, e("span", { className: "cost-panel-title" }, "账户余额 · DeepSeek")),
1155
1230
  e("div", { style: { marginTop: "8px" } }, body),
1231
+ e("div", { className: "cost-hint", style: { marginTop: "6px" } },
1232
+ "已登录 DeepSeek 账号时显示 Platform 钱包(充值 / 赠金);手动填入 API Key 则按 api.deepseek.com 的账户余额查询。"),
1156
1233
  e("div", { className: "cost-row", style: { marginTop: "10px" } },
1157
1234
  e("input", { className: "cost-input", placeholder: "手动输入 DeepSeek API Key(sk-…)", value: manualKey, onChange: ev => setManualKey(ev.target.value) }),
1158
1235
  e("button", { className: "cost-btn", onClick: () => onQuery(manualKey) }, "查询")));
@@ -2644,8 +2721,16 @@ window.__ModuleLoader__.load({
2644
2721
  else setUsageErr(v && v.error ? String(v.error) : "数据加载失败");
2645
2722
  }).catch(err => setUsageErr(String(err && err.message ? err.message : err)));
2646
2723
  }
2724
+ // 账号余额查询的 client 元数据:DSH 0.2.1-rc.2 的 deepseekAccount.getBalance(client)
2725
+ // 把这三个字段直接拼进 x-client-* 请求头,缺一个就抛 TypeError。
2726
+ // locale 用浏览器语言、时区偏移用浏览器时区(宿主侧也有兜底,这里给更准的值)。
2727
+ function balanceClientMeta() {
2728
+ let locale = "";
2729
+ try { locale = (window.navigator && window.navigator.language) || ""; } catch (e) {}
2730
+ return { locale: locale, timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60 };
2731
+ }
2647
2732
  function loadBalance(key) {
2648
- apiCall("balance", key ? { apiKey: key } : {}).then(v => setBalance(v)).catch(() => {});
2733
+ apiCall("balance", Object.assign(balanceClientMeta(), key ? { apiKey: key } : {})).then(v => setBalance(v)).catch(() => {});
2649
2734
  }
2650
2735
  function onExport() {
2651
2736
  setBusy(true); setMsg("导出中…");
@@ -2664,7 +2749,7 @@ window.__ModuleLoader__.load({
2664
2749
  apiCall("kimi-usage", { force: false }).then(v => setKimi(v)).catch(() => {});
2665
2750
  apiCall("volcengine-usage", { force: false }).then(v => setVolc(v)).catch(() => {});
2666
2751
  loadCloudUsage(view);
2667
- apiCall("balance", {}).then(v => { setBalance(v); setBusy(false); }).catch(() => setBusy(false));
2752
+ apiCall("balance", balanceClientMeta()).then(v => { setBalance(v); setBusy(false); }).catch(() => setBusy(false));
2668
2753
  }
2669
2754
 
2670
2755
  useEffect(() => { loadDash(days); }, [days]);
@@ -2955,7 +3040,15 @@ window.__ModuleLoader__.load({
2955
3040
  // 同时若宿主将来改变约定,也能在控制台给出明确指引,而不是只留一句加载器报错。
2956
3041
  // ------------------------------------------------------------
2957
3042
  (function () {
2958
- /** 单一事实源:必须与 package.json 的 name 完全一致。 */
3043
+ /**
3044
+ * 护栏自己的**独立**期望值:刻意不从 DSH_BUNDLE_ID 派生。
3045
+ *
3046
+ * 这里必须是第二份字面量:护栏的职责正是「注册名 ≠ 包名」时报警,
3047
+ * 若两个值来自同一个变量,注入故障后两者一起变错,护栏永远不会响
3048
+ * (test/client-registration.test.js 的 [4]/[5] 就是靠改写 DSH_BUNDLE_ID
3049
+ * 来注入故障,没有这份独立副本就测不出来)。
3050
+ * 三处必须逐字一致:本行、DSH_BUNDLE_ID、package.json 的 name。
3051
+ */
2959
3052
  var _DSH_BUNDLE_ID = "@angelyeye/dsh-cost-tracker";
2960
3053
  /** v1.7.0 发布时用过的旧裸名,仅用于给出针对性提示。 */
2961
3054
  var _DSH_LEGACY_BARE_ID = "dsh-cost-tracker";
package/import.js CHANGED
@@ -114,6 +114,45 @@ export function readSessionRecords(path) {
114
114
  return records
115
115
  }
116
116
 
117
+ /**
118
+ * 会话日志文件名:`session[.vN].jsonl[.zstd]`。
119
+ *
120
+ * **不写死版本号**(v1.9.6 修):0.2.x 起宿主把新会话写成
121
+ * `session.v4.jsonl.zstd`,而旧实现只枚举
122
+ * `['session.v3.jsonl.zstd','session.v3.jsonl','session.jsonl.zstd','session.jsonl']`
123
+ * —— 于是 v4 及以后的新会话被**静默跳过**(导入清单里 0 个 v4、也没有任何报错,
124
+ * 表现为「历史导入突然不再补录新会话」)。内容层其实兼容(实测 v4 日志的事件与
125
+ * usage/source 形状未变,回放能正常重建调用),断点只在文件名。
126
+ */
127
+ const SESSION_LOG_NAME_RE = /^session(?:\.v(\d+))?\.jsonl(\.zstd)?$/
128
+
129
+ /**
130
+ * 从一个会话目录里挑一份日志:版本号高者优先(v5 > v4 > v3 > 无版本号),
131
+ * 同版本 zstd 优先。这样宿主再升 v5/v6 时不需要再改枚举。
132
+ * @param {string} dir - 单个会话目录
133
+ * @returns {string} 命中的文件名;没有则返回空串
134
+ */
135
+ function pickSessionLogName(dir) {
136
+ let entries
137
+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch (e) { return '' }
138
+ let best = ''
139
+ let bestVersion = -1
140
+ let bestZstd = -1
141
+ for (const entry of entries) {
142
+ if (!entry.isFile()) continue
143
+ const m = SESSION_LOG_NAME_RE.exec(entry.name)
144
+ if (!m) continue
145
+ const version = m[1] ? Number(m[1]) : 0
146
+ const zstd = m[2] ? 1 : 0
147
+ if (version > bestVersion || (version === bestVersion && zstd > bestZstd)) {
148
+ best = entry.name
149
+ bestVersion = version
150
+ bestZstd = zstd
151
+ }
152
+ }
153
+ return best
154
+ }
155
+
117
156
  /**
118
157
  * 枚举会话根目录下全部会话日志(<root>/<项目>/<会话>/session*.jsonl[.zstd])。
119
158
  * @param {string} root - 会话根目录($DSH_HOME/sessions)
@@ -128,12 +167,9 @@ export function listSessionLogs(root) {
128
167
  try { sessions = readdirSync(join(root, project.name), { withFileTypes: true }) } catch (e) { continue }
129
168
  for (const session of sessions) {
130
169
  if (!session.isDirectory()) continue
131
- for (const name of ['session.v3.jsonl.zstd', 'session.v3.jsonl', 'session.jsonl.zstd', 'session.jsonl']) {
132
- const path = join(root, project.name, session.name, name)
133
- try {
134
- if (statSync(path).isFile()) { paths.push(path); break } // 同一会话多种编码互斥,取先命中者
135
- } catch (e) { /* 继续尝试另一后缀 */ }
136
- }
170
+ const dir = join(root, project.name, session.name)
171
+ const name = pickSessionLogName(dir)
172
+ if (name) paths.push(join(dir, name)) // 同一会话多种编码互斥,只取最优的一份
137
173
  }
138
174
  }
139
175
  return paths
package/index.js CHANGED
@@ -30,10 +30,14 @@ import { Schema } from './schema.js'
30
30
  import { catalogEntryFor, CATALOG_META, catalogProviders, catalogFingerprint, CATALOG_FX_DEFAULT } from './vendor-catalog.js'
31
31
  import { fetchOfficialPrices, buildSyncedEra, diffAgainstEra } from './price-sync.js'
32
32
  import { createCredSeam, migrateLegacySecrets, safeFetch, CRED_REFS, hostnameOf } from './credstore.js'
33
+ // 账号登录态(DSH 0.2.1-rc.2+)余额投影:纯函数,单独成文件便于单测
34
+ import { accountClientMeta, mapAccountBalance, accountBalanceFailure } from './account.js'
35
+ // 跨版本读取 settings(0.2.x 的 SettingsForms 已无 get(),改走 describe())
36
+ import { readSettingsSection } from './settings.js'
33
37
  import { listSessionLogs, planAndBuildImports, loadManifest, IMPORT_SOURCE } from './import.js'
34
38
 
35
39
  /** 插件版本(写入上报信封,便于云端排查版本差异) */
36
- const PLUGIN_VERSION = '1.9.4'
40
+ const PLUGIN_VERSION = '1.9.6'
37
41
  setPluginVersion(PLUGIN_VERSION)
38
42
 
39
43
  /** 配置面板可写的字段(与 settings 命名空间一致)。
@@ -728,16 +732,14 @@ export default {
728
732
  function kimiKeyEnv() {
729
733
  const settings = ctx.get('settings')
730
734
  if (settings) {
731
- try {
732
- const v = settings.get('llm-pi-ai')
733
- const providers = v && v.providers
734
- if (providers) {
735
- const kc = providers['kimi-coding']
736
- if (kc && kc.apiKeyEnv) return String(kc.apiKeyEnv)
737
- const k = providers['kimi']
738
- if (k && k.apiKeyEnv) return String(k.apiKeyEnv)
739
- }
740
- } catch (e) {}
735
+ const v = readSettingsSection(settings, 'llm-pi-ai')
736
+ const providers = v && v.providers
737
+ if (providers) {
738
+ const kc = providers['kimi-coding']
739
+ if (kc && kc.apiKeyEnv) return String(kc.apiKeyEnv)
740
+ const k = providers['kimi']
741
+ if (k && k.apiKeyEnv) return String(k.apiKeyEnv)
742
+ }
741
743
  }
742
744
  return 'KIMI_CODING_API_KEY'
743
745
  }
@@ -745,15 +747,11 @@ export default {
745
747
  function deepseekKeyEnv() {
746
748
  const settings = ctx.get('settings')
747
749
  if (settings) {
748
- try {
749
- const v = settings.get('llm-deepseek')
750
- if (v && v.apiKeyEnv) return String(v.apiKeyEnv)
751
- } catch (e) {}
752
- try {
753
- const v = settings.get('llm-pi-ai')
754
- const p = v && v.providers && v.providers['deepseek']
755
- if (p && p.apiKeyEnv) return String(p.apiKeyEnv)
756
- } catch (e) {}
750
+ const v = readSettingsSection(settings, 'llm-deepseek')
751
+ if (v && v.apiKeyEnv) return String(v.apiKeyEnv)
752
+ const p = readSettingsSection(settings, 'llm-pi-ai')
753
+ const deepseek = p && p.providers && p.providers['deepseek']
754
+ if (deepseek && deepseek.apiKeyEnv) return String(deepseek.apiKeyEnv)
757
755
  }
758
756
  return 'DEEPSEEK_API_KEY'
759
757
  }
@@ -865,22 +863,20 @@ export default {
865
863
  const inference = []
866
864
  const settings = ctx.get('settings')
867
865
  if (settings) {
868
- try {
869
- const v = settings.get('llm-pi-ai')
870
- const providers = (v && v.providers) || {}
871
- for (const [id, p] of Object.entries(providers)) {
872
- if (!p) continue
873
- const base = String(p.baseURL || '')
874
- const looksArkCoding = /ark\.cn-beijing\.volces\.com\/api\/coding/i.test(base)
875
- const looksVolc = /volcengine/i.test(id) || /volces\.com/i.test(base)
876
- if (!looksArkCoding && !looksVolc) continue
877
- const env = p.apiKeyEnv ? String(p.apiKeyEnv) : ''
878
- if (!env) continue
879
- // 推理 Key 只登记到 inference(用于给出「你配的是推理 Key」这种有价值的提示)
880
- if (looksLikeInferenceKeyEnv(env)) inference.push(env)
881
- else keys.push(env)
882
- }
883
- } catch (e) {}
866
+ const v = readSettingsSection(settings, 'llm-pi-ai')
867
+ const providers = (v && v.providers) || {}
868
+ for (const [id, p] of Object.entries(providers)) {
869
+ if (!p) continue
870
+ const base = String(p.baseURL || '')
871
+ const looksArkCoding = /ark\.cn-beijing\.volces\.com\/api\/coding/i.test(base)
872
+ const looksVolc = /volcengine/i.test(id) || /volces\.com/i.test(base)
873
+ if (!looksArkCoding && !looksVolc) continue
874
+ const env = p.apiKeyEnv ? String(p.apiKeyEnv) : ''
875
+ if (!env) continue
876
+ // 推理 Key 只登记到 inference(用于给出「你配的是推理 Key」这种有价值的提示)
877
+ if (looksLikeInferenceKeyEnv(env)) inference.push(env)
878
+ else keys.push(env)
879
+ }
884
880
  }
885
881
  return { keys, inference }
886
882
  }
@@ -1040,22 +1036,111 @@ export default {
1040
1036
  }
1041
1037
 
1042
1038
  // ---------- deepseek balance ----------
1043
- async function balance(args) {
1044
- const manual = args && typeof args.apiKey === 'string' ? args.apiKey.trim() : ''
1045
- const key = manual ? { value: manual, source: 'manual' } : await resolveApiKey(deepseekKeyEnv())
1046
- if (!key.value) return { ok: false, error: '未找到 DeepSeek API Key', available: false, total: '', granted: '', toppedUp: '', currency: 'CNY', keySource: 'none' }
1039
+ // 两种余额来源(v1.9.6 起):
1040
+ // ① 账号登录态(DSH 0.2.1-rc.2+):走宿主服务 deepseekAccount.getBalance(),
1041
+ // 拿的是 **Platform 钱包**(充值钱包 normal_wallets 与赠金钱包 bonus_wallets 分离)。
1042
+ // 账号态推理用 x-dsh-auth-token 走 Platform 网关,运行时
1043
+ // @deepseek-ai/dsh-llm-deepseek-account 的 README 明确「不会回退到 API key」——
1044
+ // 也就是说登录**不会下发 API Key**,旧版只认 DEEPSEEK_API_KEY 的实现
1045
+ // 在纯账号态下必然报「未找到 DeepSeek API Key」。
1046
+ // ② API Key 态:沿用 https://api.deepseek.com/user/balance(token 口径不变)。
1047
+ // 优先级:面板手填 Key > 账号登录态 > 配置/环境里的 API Key。
1048
+ // · 手填是用户显式动作,意图最强;
1049
+ // · 账号态优先于 API Key:账号态下真正被扣的是 Platform 钱包,且「登录了账号」
1050
+ // 本身就是用户的选择;此时回退到 API Key 会显示**另一个账户**的数字,更误导。
1051
+ // 旧 DSH(没有 deepseekAccount 服务)自动走原路径,不需要版本号判断。
1052
+
1053
+ /** 取账号服务;不存在(旧宿主)返回 null。 */
1054
+ function accountService() {
1055
+ try {
1056
+ const svc = ctx.get('deepseekAccount')
1057
+ return svc && typeof svc.getBalance === 'function' ? svc : null
1058
+ } catch (e) {
1059
+ return null
1060
+ }
1061
+ }
1062
+
1063
+ /**
1064
+ * 尝试账号登录态余额。
1065
+ * @param {object} [args] - HTTP 参数(可带 locale / timezoneOffsetSeconds,由浏览器半端提供)
1066
+ * @returns {{handled:boolean, service:boolean, result?:object}}
1067
+ * handled=true → result 即最终结果,不再回退 API Key;
1068
+ * handled=false → 没有可用的账号登录态(未登录/无该服务),由调用方回退;
1069
+ * service 表示宿主是否提供账号服务,用于区分「未找到 Key」的文案。
1070
+ */
1071
+ async function tryAccountBalance(args) {
1072
+ const svc = accountService()
1073
+ if (!svc) return { handled: false, service: false }
1074
+ let details
1075
+ try {
1076
+ // client 元数据**必填**:运行时 platformClientHeaders 直接读
1077
+ // version / locale / timezoneOffsetSeconds,缺字段会抛 TypeError。
1078
+ details = await svc.getBalance(accountClientMeta(args, PLUGIN_VERSION))
1079
+ } catch (e) {
1080
+ return {
1081
+ handled: true,
1082
+ service: true,
1083
+ result: accountBalanceFailure('账号余额查询失败:' + toStr(e && e.message ? e.message : e)
1084
+ + '(若是 DSH 升级导致的服务形状变化,请反馈;期间可在下方手动填入 API Key 查询)'),
1085
+ }
1086
+ }
1087
+ // 契约里只有 null 表示「没有已存授权 / 查询期间凭据被清除」,此时才回退 API Key;
1088
+ // undefined 属于契约外(服务没实现好或 RPC 出错)—— 回退可能显示**另一个账户**的数字,
1089
+ // 所以按失败处理并留证,不装作「未登录」。
1090
+ if (details === null) return { handled: false, service: true }
1091
+ if (details === undefined) {
1092
+ return {
1093
+ handled: true,
1094
+ service: true,
1095
+ result: accountBalanceFailure('账号余额查询失败:宿主服务未返回结果(服务未就绪或版本不匹配),可稍后重试或手动填入 API Key'),
1096
+ }
1097
+ }
1098
+ if (details.status !== 'ready') {
1099
+ return {
1100
+ handled: true,
1101
+ service: true,
1102
+ result: accountBalanceFailure('账号余额查询失败:Platform 未返回可用数据(网络超时或接口异常,可稍后重试)'),
1103
+ }
1104
+ }
1105
+ const mapped = mapAccountBalance(details)
1106
+ if (!mapped) {
1107
+ return { handled: true, service: true, result: accountBalanceFailure('账号余额查询失败:返回的钱包数据无法解析') }
1108
+ }
1109
+ return { handled: true, service: true, result: mapped }
1110
+ }
1111
+
1112
+ /** API Key 路径(与 v1.9.5 完全一致,仅新增 source 字段用于视图区分来源)。 */
1113
+ async function balanceWithApiKey(key) {
1047
1114
  try {
1048
1115
  const r = await httpJson('https://api.deepseek.com/user/balance', { Authorization: 'Bearer ' + key.value }, 15000, allowHostsFor('deepseek'))
1049
- if (r.status !== 200 || !r.body) return { ok: false, error: 'HTTP ' + (r.status || 0) + (r.error ? ' · ' + r.error : ''), available: false, total: '', granted: '', toppedUp: '', currency: 'CNY', keySource: key.source }
1116
+ if (r.status !== 200 || !r.body) return { ok: false, error: 'HTTP ' + (r.status || 0) + (r.error ? ' · ' + r.error : ''), available: false, total: '', granted: '', toppedUp: '', currency: 'CNY', source: 'apikey', keySource: key.source }
1050
1117
  const j = JSON.parse(r.body)
1051
1118
  const infos = Array.isArray(j.balance_infos) ? j.balance_infos : []
1052
1119
  let info = null
1053
1120
  for (const b of infos) { if (b && b.currency === 'CNY') { info = b; break } }
1054
1121
  if (!info) info = infos[0] || {}
1055
- return { ok: true, error: '', available: !!j.is_available, total: toStr(info.total_balance), granted: toStr(info.granted_balance), toppedUp: toStr(info.topped_up_balance), currency: toStr(info.currency) || 'CNY', keySource: key.source }
1122
+ return { ok: true, error: '', available: !!j.is_available, total: toStr(info.total_balance), granted: toStr(info.granted_balance), toppedUp: toStr(info.topped_up_balance), currency: toStr(info.currency) || 'CNY', source: 'apikey', keySource: key.source }
1056
1123
  } catch (e) {
1057
- return { ok: false, error: toStr(e && e.message ? e.message : e), available: false, total: '', granted: '', toppedUp: '', currency: 'CNY', keySource: key.source }
1124
+ return { ok: false, error: toStr(e && e.message ? e.message : e), available: false, total: '', granted: '', toppedUp: '', currency: 'CNY', source: 'apikey', keySource: key.source }
1125
+ }
1126
+ }
1127
+
1128
+ async function balance(args) {
1129
+ const manual = args && typeof args.apiKey === 'string' ? args.apiKey.trim() : ''
1130
+ if (manual) return balanceWithApiKey({ value: manual, source: 'manual' })
1131
+ const acct = await tryAccountBalance(args)
1132
+ if (acct.handled) return acct.result
1133
+ const key = await resolveApiKey(deepseekKeyEnv())
1134
+ if (!key.value) {
1135
+ return {
1136
+ ok: false,
1137
+ error: acct.service
1138
+ ? '未找到 DeepSeek API Key,也没有已登录的 DeepSeek 账号(DSH 0.2.1+ 可在「设置 → 账号与余额」登录后查询账号余额)'
1139
+ : '未找到 DeepSeek API Key',
1140
+ available: false, total: '', granted: '', toppedUp: '', currency: 'CNY', source: 'none', keySource: 'none',
1141
+ }
1058
1142
  }
1143
+ return balanceWithApiKey(key)
1059
1144
  }
1060
1145
 
1061
1146
  // ---------- csv export ----------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@angelyeye/dsh-cost-tracker",
3
- "version": "1.9.4",
3
+ "version": "1.9.6",
4
4
  "description": "DeepSeek Harness (DSH) plugin: LLM token usage & cost tracking with a settings dashboard, agent tools, HTTP API, persistent storage, multi-device cloud sync, session-log history import, official price sync and a multi-vendor price catalog.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -18,6 +18,8 @@
18
18
  "price-sync.js",
19
19
  "credstore.js",
20
20
  "import.js",
21
+ "account.js",
22
+ "settings.js",
21
23
  "docs/provider-pricing.json",
22
24
  "docs/THIRD-PARTY-NOTICES.md",
23
25
  "cordis.patch.yml",
@@ -33,7 +35,7 @@
33
35
  "./package.json": "./package.json"
34
36
  },
35
37
  "scripts": {
36
- "test": "node test/storage.test.js && node test/pricing.test.js && node test/peak-holidays.test.js && node test/volcengine-plan.test.js && node test/volcengine-host.test.js && node test/config.test.js && node test/recompute.test.js && node test/credstore.test.js && node test/vendor-catalog.test.js && node test/price-sync.test.js && node test/import.test.js && node test/client-registration.test.js && node test/ui-display.test.js && node test/client-render.test.js && node test/cloud-read.test.js && node --no-warnings test/cloud-view-e2e.test.js && node test/sync.test.js && node test/view.test.js"
38
+ "test": "node test/storage.test.js && node test/pricing.test.js && node test/peak-holidays.test.js && node test/volcengine-plan.test.js && node test/volcengine-host.test.js && node test/config.test.js && node test/recompute.test.js && node test/credstore.test.js && node test/vendor-catalog.test.js && node test/price-sync.test.js && node test/import.test.js && node test/balance-account.test.js && node test/session-log-v4.test.js && node test/settings-compat.test.js && node test/client-registration.test.js && node test/ui-display.test.js && node test/client-render.test.js && node test/cloud-read.test.js && node --no-warnings test/cloud-view-e2e.test.js && node test/sync.test.js && node test/view.test.js && node test/release-notes.test.js"
37
39
  },
38
40
  "keywords": [
39
41
  "dsh-plugin",
package/pricing.js CHANGED
@@ -373,10 +373,18 @@ export function subscriptionPlanFor(np, model) {
373
373
  return null
374
374
  }
375
375
 
376
- /** Provider 兜底单价(估算);缓存写入按缓存命中价计。
377
- * deepseek 兜底已同步至 V4.1 Flash 档(2.0/8.0/0.04),未知模型不再按旧价高估。 */
376
+ /** DeepSeek 官方渠道的兜底单价(含峰谷 tiered)。
377
+ * 兜底已同步至 V4.1 Flash 档(2.0/8.0/0.04),未知模型不再按旧价高估。 */
378
+ const DEEPSEEK_PROVIDER_RATES = { rates: { input: 2.0, output: 8.0, cacheRead: 0.04, cacheWrite: 0.04 }, tiered: true }
379
+
380
+ /** Provider 兜底单价(估算);缓存写入按缓存命中价计。 */
378
381
  export const PROVIDER_RATES = {
379
- deepseek: { rates: { input: 2.0, output: 8.0, cacheRead: 0.04, cacheWrite: 0.04 }, tiered: true },
382
+ deepseek: DEEPSEEK_PROVIDER_RATES,
383
+ // DSH 0.2.x「DeepSeek 账号登录」的推理 provider 名是 `deepseek-account`
384
+ // (鉴权走 x-dsh-auth-token,模型与官方单价仍是同一套)。不登记它的话,
385
+ // 精确价表之外的模型会落到 GENERIC_RATES(缓存价 0.5 而非 0.04、且无峰谷半价),
386
+ // 账号态的新模型会被静默高估 —— 所以这里与 deepseek 共用同一份兜底价。
387
+ 'deepseek-account': DEEPSEEK_PROVIDER_RATES,
380
388
  openai: { rates: { input: 10.0, output: 30.0, cacheRead: 5.0, cacheWrite: 5.0 }, tiered: false },
381
389
  anthropic: { rates: { input: 15.0, output: 75.0, cacheRead: 1.5, cacheWrite: 1.5 }, tiered: false },
382
390
  gemini: { rates: { input: 2.5, output: 10.0, cacheRead: 0.625, cacheWrite: 0.625 }, tiered: false },
package/settings.js ADDED
@@ -0,0 +1,95 @@
1
+ // ============================================================
2
+ // 跨版本读取 profile 条目的「生效配置」(DSH settings 服务)
3
+ //
4
+ // 背景:插件有几处「按用户配置决定用哪个 Key 名」的逻辑(DeepSeek / Kimi /
5
+ // 火山方舟),旧实现直接 `ctx.get('settings').get('llm-deepseek')`。
6
+ // 但 0.2.x 的 SettingsForms 已经**没有 `get()`**(只剩 configure / describe /
7
+ // update / replace / mutate / write / prepareDocument),那段代码抛 TypeError
8
+ // 被各自的 try/catch 吞掉 → **静默**退化成永远使用硬编码默认名。
9
+ // 标准部署(默认名与官方一致)看不出问题;自定义 `apiKeyEnv` 的部署会去查
10
+ // 一个不存在的 Key 名,表现为「明明配了 Key 却报未找到」。
11
+ //
12
+ // 0.2.x 的正确读法:`settings.describe()` 返回所有条目的表单描述,
13
+ // 其中 `value` 是该条目 **volatile 字段的生效值** —— `apiKeyEnv` 正是
14
+ // `.volatile()` 字段(见 dsh-llm-deepseek-api-key 的 Config)。旧宿主(0.1.x)
15
+ // 则保留 `get(namespace)`。因此这里做一次「双 API 兼容读」:
16
+ //
17
+ // 1) settings.describe() 命中 ns → 用 row.value(0.2.x)
18
+ // 2) 否则 settings.get(ns)(旧版)
19
+ // 3) 都没有 / 都失败 → null,由调用方回落各自默认名
20
+ //
21
+ // describe() 要遍历全部 profile 条目并逐条做 schema 投影,比一次 `get` 重得多,
22
+ // 而余额 / Kimi / 火山三个入口在一次面板刷新里会各调一次 —— 所以按 settings
23
+ // 实例做 10s 短缓存,避免重复做全量投影。
24
+ // ============================================================
25
+
26
+ /** describe() 结果的缓存时长(毫秒)。配置变更在设置页写入后最迟 10s 生效。 */
27
+ const CACHE_TTL_MS = 10000
28
+
29
+ /** settings 实例 → { rows: Array|null, at: number } */
30
+ const rowsCache = new WeakMap()
31
+
32
+ /**
33
+ * 取 describe() 的行数组(带短缓存)。
34
+ * @param {object} settings - settings 服务
35
+ * @param {number} now - 当前时刻(毫秒)
36
+ * @returns {Array|null} 行数组;describe 不可用或抛错时为 null
37
+ */
38
+ function describedRows(settings, now) {
39
+ const hit = rowsCache.get(settings)
40
+ if (hit && now - hit.at < CACHE_TTL_MS) return hit.rows
41
+ let rows = null
42
+ try {
43
+ const out = settings.describe()
44
+ if (Array.isArray(out)) rows = out
45
+ } catch (e) {
46
+ rows = null
47
+ }
48
+ rowsCache.set(settings, { rows, at: now })
49
+ return rows
50
+ }
51
+
52
+ /**
53
+ * 读取某个 profile 条目(ns)的生效配置对象。
54
+ *
55
+ * @param {object|undefined} settings - `ctx.get('settings')`
56
+ * @param {string} ns - profile 条目 id(如 `llm-deepseek` / `llm-pi-ai`)
57
+ * @param {number} [now] - 仅测试用:注入当前时刻
58
+ * @returns {object|null} 配置对象;不可得时 null
59
+ */
60
+ export function readSettingsSection(settings, ns, now) {
61
+ if (!settings || typeof ns !== 'string' || !ns) return null
62
+ const at = typeof now === 'number' ? now : Date.now()
63
+ // ---- 0.2.x:describe() 的 value 是 volatile 字段的生效值 ----
64
+ if (typeof settings.describe === 'function') {
65
+ const rows = describedRows(settings, at)
66
+ if (rows) {
67
+ for (const row of rows) {
68
+ if (!row || row.ns !== ns) continue
69
+ const value = row.value
70
+ return value && typeof value === 'object' ? value : null
71
+ }
72
+ // describe() 正常返回但没有该条目:不要再回退 get()(0.2.x 上它一定抛错,
73
+ // 而且在「条目确实不存在」时也更该返回 null)
74
+ return null
75
+ }
76
+ }
77
+ // ---- 旧宿主:get(namespace) ----
78
+ if (typeof settings.get === 'function') {
79
+ try {
80
+ const value = settings.get(ns)
81
+ return value && typeof value === 'object' ? value : null
82
+ } catch (e) {
83
+ return null
84
+ }
85
+ }
86
+ return null
87
+ }
88
+
89
+ /**
90
+ * 清掉某个 settings 实例的缓存(仅测试/显式失效用)。
91
+ * @param {object} settings
92
+ */
93
+ export function resetSettingsCache(settings) {
94
+ if (settings && typeof settings === 'object') rowsCache.delete(settings)
95
+ }