dsh-cost-meter 1.8.36 → 1.9.2

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.
@@ -0,0 +1,58 @@
1
+ # 2026-10-18 性能与透明度验证
2
+
3
+ 基线 commit:`9725581bdbd19cf6a2ad2e7c02e0557f2e045771`,版本 1.9.0。测试使用同一台 Windows 主机、Node.js 24.19.0、AMD Ryzen 7 5800H。两版均使用锁文件中的 acorn 8.15.0、zod 4.6.5 和 esbuild 0.28.2。原始数据见 [JSON 记录](performance-2026-10-18.json)。
4
+
5
+ ## 自动语言模式的费用查询
6
+
7
+ [#312](https://github.com/Han-1413141/dsh-cost-meter/issues/312) 指出的开销来自:宿主没有可用 locale 服务时,每个费用方法都通过 `settings.describe({ redactSecrets: true })` 构建全部插件设置,只为读取语言偏好。
8
+
9
+ 现在只缓存解析出的语言,设置或语言事件立即使缓存失效。没有事件的旧宿主最多每秒探测一次,在下一次费用读取时更新;明确选择中文或英文仍直接使用指定语言。缓存不保留设置描述和凭据,插件卸载时清理。另处理了 `describe()` 自身触发设置事件的重入情况,避免递归调用。
10
+
11
+ 基准调用真实的 `costMeter.getSessionCost()`,使用空账本和合成设置描述:64 个插件、每个 20 个字段,加一个语言设置条目。预热 100 次,随后执行 5 轮,每轮 2,000 次读取;两版均使用同一数据和禁网条件。
12
+
13
+ | 指标 | 修改前 | 修改后 |
14
+ | --- | ---: | ---: |
15
+ | 10,000 次读取中的全量设置描述次数 | 10,000 | 0 |
16
+ | 每轮耗时中位数 | 1,719.58 ms | 40.19 ms |
17
+ | 每轮 CPU 时间中位数 | 1,719 ms | 47 ms |
18
+ | 外部网络请求 | 0 | 0 |
19
+
20
+ 这次测量中,该调用路径的耗时降低 **97.7%**。这是隔离基准,不是整个 DSH 的 CPU 降幅,也不将报告者旧版采样中的 11.3% 当成新版实测结果。修改后全部计时轮次在缓存期限内完成;长期运行的无事件宿主仍保留每秒最多一次的检查。
21
+
22
+ 复现命令:
23
+
24
+ ```powershell
25
+ # 两个 checkout 使用相同依赖;第一个参数是被测仓库根目录。
26
+ node test/host-locale-performance.mjs <baseline-checkout> before.json
27
+ node test/host-locale-performance.mjs <updated-checkout> after.json
28
+ ```
29
+
30
+ ## OpenDesign 请求数量
31
+
32
+ 同一份合成 Control Key 场景中,旧路径请求 `coding-plan-usage` 收到 401 后,再请求 preflight,同时读取钱包,共 **3 次 GET**。新路径直接并行读取 preflight 和钱包,共 **2 次 GET**,减少一次必然失败的请求和串行等待。身份校验、大整数额度校验和单侧失败处理保留。未用真实账户测量网络延迟。
33
+
34
+ ## 客户端体积
35
+
36
+ 构建时根据实际重复次数压缩 CSS 声明、选择器与主题变量;客户端加载时解码一次。构建过程逐字节核对解码结果与 esbuild 输出一致。
37
+
38
+ 主客户端从 **261,676 字节**变为 **260,671 字节**,新增功能后仍减少 **1,005 字节**。统计和定价继续按需加载。没有通过删除界面内容满足 DSH STORE 的 262,144 字节限制。
39
+
40
+ ## 透明度
41
+
42
+ 主题背景色中含透明度时,费用设置页、统计页、价格下拉框、费用详情、上下文引导、兼容提醒、峰谷提醒和侧栏固定区域使用相同 RGB 颜色的不透明背景;不修改宿主或其它插件的主题变量。统计内容和费用弹窗使用皮肤的弹窗表面色,避免把深色壁纸遮罩当成浅色界面的正文底色。
43
+
44
+ Chromium 测试覆盖 11 类区域、3 种主题、4 档透明度,共 **132 个场景**。每个场景只切换后方页面的颜色,比较区域内部的截图像素:
45
+
46
+ - 基线有 **105 个场景**的内部像素随后方内容变化,复现透出。
47
+ - 修改后 **132 个场景全部保持相同**,浏览器无脚本错误。
48
+ - 主题包含浅色、深色、浅色宿主配深色皮肤;透明度为 0、0.2、0.65、1。
49
+
50
+ ```powershell
51
+ $env:DSH_TEST_UI_MODULES = '<含 react、react-dom、playwright-core 的 node_modules>'
52
+ node test/skin-opacity-browser.mjs 9725581
53
+ node test/skin-opacity-browser.mjs
54
+ ```
55
+
56
+ 测试使用真实客户端和按需模块的 CSS,以及真实 React 费用详情和兼容提示组件。测试范围是背景色透明度;没有把任意第三方插件直接修改父元素 `opacity` 的行为纳入已验证范围。
57
+
58
+ 贡献:@XHPAN 提供 [#312](https://github.com/Han-1413141/dsh-cost-meter/issues/312) 的 CPU profile 归因、环境和优化建议;本文的数据是本轮另行运行的隔离基准。
@@ -35,7 +35,7 @@
35
35
  ```yaml
36
36
  minimumReleaseAgeExclude:
37
37
  # 保留宿主已经写入的其他条目
38
- - dsh-cost-meter@1.8.36
38
+ - dsh-cost-meter@1.9.0
39
39
  ```
40
40
 
41
41
  只影响列出的 `名称@版本`;不要删除文件里已有的其他排除项。修改后完全退出并重新打开 DSH,再在插件页重试。
@@ -49,7 +49,7 @@ minimumReleaseAgeExclude:
49
49
  dsh plugin --profile desktop remove dsh-cost-meter --config.minimum-release-age=0
50
50
 
51
51
  # 安装 / 升级
52
- dsh plugin --profile desktop add dsh-cost-meter@1.8.36 --config.minimum-release-age=0
52
+ dsh plugin --profile desktop add dsh-cost-meter@1.9.0 --config.minimum-release-age=0
53
53
  ```
54
54
 
55
55
  如果是 lockfile 校验阶段失败(`ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION`),也可以加 `--trust-lockfile` 跳过校验并重试。以上两个参数已在本机 pnpm 11.28.5 的临时 Profile 上实测可用。
@@ -83,6 +83,6 @@ This page explains the pnpm `minimumReleaseAge` (supply-chain) policy shipped in
83
83
 
84
84
  - **Scope** — DSH 0.2.1-rc.1 / 0.2.1-rc.2 bundle pnpm **11.28.5**, which enables a built-in **24-hour** `minimumReleaseAge`. Packages published less than 24 hours ago can produce a resolution-policy violation.
85
85
  - **Symptoms** — the plugin page reports uninstall/install failure with lines such as `✓ Lockfile passes supply-chain policies (verified 28m ago)`, then `ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION` (lockfile verification) or `ERR_PNPM_RESOLUTION_POLICY_VIOLATIONS_UNHANDLED` (dependency resolution during `pnpm remove`). The unhandled-callback case is a defect of the host's bundled pnpm; the plugin cannot patch it.
86
- - **Workarounds** — (1) wait until the package/version is 24 hours old, then retry; (2) add an exact `minimumReleaseAgeExclude` entry (`- dsh-cost-meter@1.8.36`) to the profile's `pnpm-workspace.yaml` (`%USERPROFILE%\.dsh\profiles\<profile>\pnpm-workspace.yaml` on Windows, `~/.dsh/profiles/<profile>/pnpm-workspace.yaml` elsewhere), keep existing entries, restart DSH and retry; (3) forward pnpm flags for one operation via the CLI, for example `dsh plugin --profile desktop remove dsh-cost-meter --config.minimum-release-age=0` (or `--trust-lockfile` when only lockfile verification fails). Both flags were verified against pnpm 11.28.5 in a temporary profile.
86
+ - **Workarounds** — (1) wait until the package/version is 24 hours old, then retry; (2) add an exact `minimumReleaseAgeExclude` entry (`- dsh-cost-meter@1.9.0`) to the profile's `pnpm-workspace.yaml` (`%USERPROFILE%\.dsh\profiles\<profile>\pnpm-workspace.yaml` on Windows, `~/.dsh/profiles/<profile>/pnpm-workspace.yaml` elsewhere), keep existing entries, restart DSH and retry; (3) forward pnpm flags for one operation via the CLI, for example `dsh plugin --profile desktop remove dsh-cost-meter --config.minimum-release-age=0` (or `--trust-lockfile` when only lockfile verification fails). Both flags were verified against pnpm 11.28.5 in a temporary profile.
87
87
  - **Diagnostics** — read the first `ERR_PNPM_*` line in `<profile>/.plugin-manager/logs/operation-*/pnpm.log`; remove credentials before sharing. Do not delete the profile or the ledger.
88
88
  - **Upstream** — DSH's repository restricts external pull requests, so this cannot be patched from the plugin side; the workarounds above are the supported mitigation until a DSH release updates the bundled pnpm. See also issue [#250](https://github.com/Han-1413141/dsh-cost-meter/issues/250).
@@ -0,0 +1,83 @@
1
+ # v1.9.0
2
+
3
+ ## 中文
4
+
5
+ 本版新增三类外部插件/存储的兼容:Codex 订阅插件、ChatGPT 订阅插件与 better-session 的 SQLite 会话存储;为全部费用界面适配 dsh-pocket 手机端;并按 #274 的社区反馈为 OpenDesign 增加 Control Key 直连的 preflight 回退与窗口/钱包独立降级。账本格式不变;除用户主动确认的「历史 Codex 归类」外,不自动重算历史金额。
6
+
7
+ ### Codex 订阅插件兼容(dsh-codex-subscription)
8
+
9
+ - 安装 dsh-codex-subscription 后,插件启动时从 Profile 的 `node_modules` 检测它,并自动把该插件产生的 Codex 订阅调用归类为 Plan 订阅额度,不再计入 API 按量花费;新产生的用量在记账时直接按 Plan 处理。
10
+ - 升级后首次检测到该插件时,弹出一次「兼容修复」提示:是否把升级前已记录的历史 Codex 类模型计费统一归类为 Plan。选择「统一归类为 Plan」后立即重算本地账本中的历史 Codex 用量(`apiCost` 归零、Plan 等值保留),可重复执行且幂等;选择「保持现状」或关闭提示不会改动历史金额,并永久记住该选择。
11
+ - 提示可随时从「设置 → 费用 → Codex」重新操作:设置页新增「Codex 订阅兼容」面板,展示检测到的版本、当前计费方式、历史 Codex 用量(调用数 / 金额 / 天数 / 来源 Provider)与归类状态,并提供「统一归类为 Plan」按钮;未安装该插件时不显示该区块。
12
+ - 判定沿用 Plan/API 双轨与 `provider:model` 覆盖机制;用户已显式选择 plan/api 的厂商不会被覆盖。
13
+
14
+ ### ChatGPT 订阅插件兼容(@eddyskywalker/dsh-chatgpt-subscription)
15
+
16
+ - 检测该插件的 9 条订阅线路并映射到对应 Plan 家族:`codex-chatgpt` → Codex、`kimi-code` → Kimi、`command-code` → CommandCode、`claude-subscription` → Anthropic、`minimax-code` → MiniMax、`glm-coding-plan` → Z.AI、`workbuddy-subscription` → WorkBuddy(新增)、`antigravity` → Antigravity(新增)、`step-code` → StepFun(新增)。
17
+ - 启动时对计费分类仍为「自动」的上述厂商自动归为 Plan,不覆盖用户显式选择的 plan/API,使其订阅调用不再计入 API 花费。
18
+ - 该插件自身的登录、额度卡片与 Provider 功能不受影响;本插件只读取本地账本记账口径,不发起任何订阅插件的网络请求。
19
+
20
+ ### better-session SQLite 会话存储兼容
21
+
22
+ - 新增会话存储适配层:自动探测宿主后端(`session-rdb` / `sessionPersistence` / `sessionQuery` 或 `@morlay/better-session`、`@morlay/session-rdb` 安装),当 better-session 接管会话存储、不再产生 JSONL 日志时,历史回填、旧账本导入、按模型历史重定价、小时桶修复、fork 种子清洗,以及逐会话费用、轨迹、调用详情、标题与统计缓存仍可正常工作。
23
+ - JSONL 存储路径逐字节保持原有行为;RDB 模式走宿主的会话持久化/查询接口,不直接读 SQLite 文件,也不自动合并旧 JSONL 与 RDB 历史(旧日志可用「导入旧版历史」补录,[说明](better-session.md))。
24
+ - 修正 5 个一次性迁移标记在 RDB 空扫描时被误消费的问题,避免误以为旧会话已处理;首次全量回放增加单会话顺序与事件上限保护。
25
+ - 启动日志会打印当前会话存储后端(`session-rdb` / `jsonl` / `unknown`);会话修复 CLI 检测到 RDB 时明确提示不支持并返回退出码 2,不假装修复成功。
26
+
27
+ ### dsh-pocket 手机端适配
28
+
29
+ - 主设置面板、侧栏卡片、额度横条、预算框、统计页、显示设置、定价页、OpenRouter 与社区面板、Codex 兼容面板均适配窄屏(≤1023px)与 dsh-pocket 强制移动布局:卡片单列、标签横向滚动、按钮/标签 36px 触控高度、对话框不超过 90vh 并避开安全区、宽表横向滚动。
30
+ - 桌面布局不变;新增样式全部包在 `@media (max-width: 1023px)` 或 `body[data-dsh-pocket-layout="mobile"]` 下。
31
+
32
+ ### OpenDesign 额度查询:Control Key preflight 回退与独立降级(#274)
33
+
34
+ - 按 [@yunjuanhuakai 的实测](https://github.com/Han-1413141/dsh-cost-meter/issues/274#issuecomment-6236591566):同一把 Control Key 用 Bearer 调用 `/billing/coding-plan-usage` 会 401,但可正常读取 `/billing/preflight`(返回 `codingPlan.windows` 与 `balanceUsd`)。本版在主端点返回 401/403 时保守回退一次 preflight;主端点非 401/403 不触发回退,避免掩盖真实故障。
35
+ - 解析器支持解包 preflight 的 `codingPlan` 结构;preflight 的 `balanceUsd` 仅在钱包接口不可读时兜底显示,不覆盖可读钱包。
36
+ - 窗口与钱包读取完全独立并行:一方失败只降级该部分(窗口失败 → 仅显示钱包余额并标记 partial;钱包失败 → 保留窗口),只有两者都失败才报错;错误区分鉴权失败、无生效订阅、响应无效与网络失败,不再混同。
37
+ - 文档补充端点权限、Control Key 只能用于部分端点、`workspaceId` 必须取 `GET /api/v1/workspaces` 的 `items[].workspaceId`(误用用户 id 会 403 `workspace_billing_scope_forbidden`)以及 401 排查步骤,见 [OpenDesign 计费与排查](opendesign-billing.md)。
38
+ - 感谢 [@playgithub](https://github.com/Han-1413141/dsh-cost-meter/issues/274#issuecomment-6215322540) 提出 OpenDesign 支持需求并复现入口问题、[@codeforker654](https://github.com/Han-1413141/dsh-cost-meter/issues/274#issuecomment-6236228870) 复现并提交 401 报告、[@yunjuanhuakai](https://github.com/Han-1413141/dsh-cost-meter/issues/274#issuecomment-6236591566) 发现 `/billing/preflight` 可接受 Control Key 并提供回执样例。
39
+
40
+ ### 升级方式
41
+
42
+ 重跑新版 `install.ps1` 或从插件市场更新(npm 用户执行 `dsh plugin --profile web add dsh-cost-meter@latest`),升级后完全退出并重新打开 DSH。账本格式不变;除主动确认的历史 Codex 归类外不自动重算历史金额。
43
+
44
+ ## English
45
+
46
+ This release adds compatibility for three external integrations: the Codex subscription plugin, the ChatGPT subscription plugin, and better-session's SQLite session storage. Every cost UI now adapts to dsh-pocket mobile layouts. Following the #274 community feedback, OpenDesign gains a Control-Key-only `/billing/preflight` fallback plus independent window/wallet degradation. The ledger format is unchanged; historical amounts are never recalculated automatically except for the explicitly confirmed "historical Codex reclassification".
47
+
48
+ ### Codex subscription plugin compatibility (dsh-codex-subscription)
49
+
50
+ - When dsh-codex-subscription is installed, the plugin is detected from the Profile's `node_modules` at startup. Codex subscription calls it makes are classified as Plan subscription quota instead of pay-as-you-go API spend, and new usage is recorded as Plan immediately.
51
+ - On the first detection after upgrading, a one-time "Compatibility fix" prompt asks whether to reclassify historical Codex models recorded before the upgrade as Plan. Choosing "Reclassify as Plan" recomputes the local ledger immediately (`apiCost` zeroed, Plan equivalents kept); it is idempotent. Choosing "Keep as is" or closing the prompt leaves historical amounts untouched and remembers the decision permanently.
52
+ - The action is always reachable in Settings → Cost → Codex: the new "Codex subscription compatibility" panel shows the detected version, current billing class, historical Codex usage (calls / cost / days / source providers) and the reclassification state, with a "Reclassify as Plan" button. The section is hidden when the plugin is not installed.
53
+ - Classification follows the existing Plan/API dual-track and `provider:model` overrides; vendors explicitly set to plan/api are never overwritten.
54
+
55
+ ### ChatGPT subscription plugin compatibility (@eddyskywalker/dsh-chatgpt-subscription)
56
+
57
+ - Detects the plugin's nine subscription routes and maps them to Plan families: `codex-chatgpt` → Codex, `kimi-code` → Kimi, `command-code` → CommandCode, `claude-subscription` → Anthropic, `minimax-code` → MiniMax, `glm-coding-plan` → Z.AI, `workbuddy-subscription` → WorkBuddy (new), `antigravity` → Antigravity (new), `step-code` → StepFun (new).
58
+ - At startup, vendors still set to "auto" are classified as Plan without overriding explicit plan/API choices, so subscription calls no longer count as API spend.
59
+ - The plugin's own login, quota cards and providers are untouched; this plugin reads only the local ledger billing class and makes no network requests on behalf of subscription plugins.
60
+
61
+ ### better-session SQLite session storage compatibility
62
+
63
+ - New session-storage adapter: the host backend is detected automatically (`session-rdb` / `sessionPersistence` / `sessionQuery`, or installed `@morlay/better-session` / `@morlay/session-rdb`). When better-session takes over storage and no JSONL logs are produced, historical backfill, legacy-ledger import, per-model history repricing, hour-bucket repair, fork-seed cleanup, per-session cost, trajectory, call inspection, titles and statistics caches keep working.
64
+ - The JSONL path remains byte-for-byte unchanged; RDB mode goes through the host's session persistence/query APIs instead of reading SQLite files directly, and does not merge old JSONL with RDB history automatically (use "Import legacy history" for old logs; see [guide](better-session.md)).
65
+ - Five one-time migration markers are no longer consumed by an empty RDB scan (previously they could mark old sessions as processed). The first full replay now runs one session at a time with an event cap.
66
+ - Startup logs the current session storage backend (`session-rdb` / `jsonl` / `unknown`); the session repair CLI detects RDB, explains that it is unsupported and exits with code 2 instead of pretending to repair.
67
+
68
+ ### dsh-pocket mobile layout
69
+
70
+ - The main settings panel, sidebar cards, quota strip, budget box, statistics, display settings, pricing, OpenRouter and community panels, and the Codex compatibility panel now adapt to narrow screens (≤1023px) and dsh-pocket's forced mobile layout: single-column cards, horizontally scrolling tabs, 36px touch targets, dialogs capped at 90vh with safe-area padding, and horizontally scrolling wide tables.
71
+ - Desktop layout is unchanged; all new styles live under `@media (max-width: 1023px)` or `body[data-dsh-pocket-layout="mobile"]`.
72
+
73
+ ### OpenDesign quota: Control-Key preflight fallback and independent degradation (#274)
74
+
75
+ - Based on [the measurements shared by @yunjuanhuakai](https://github.com/Han-1413141/dsh-cost-meter/issues/274#issuecomment-6236591566): the same Control Key returns 401 from `/billing/coding-plan-usage` as a Bearer token, but `/billing/preflight` works and returns `codingPlan.windows` plus `balanceUsd`. This release falls back once to preflight only when the primary endpoint returns 401/403; other failures never trigger the fallback, so real outages are not masked.
76
+ - The parser unwraps preflight's `codingPlan` structure; preflight `balanceUsd` is used as a fallback display only when the wallet endpoint is unreadable, never overriding a readable wallet.
77
+ - Window and wallet reads are fully independent and parallel: a single failure degrades only that part (window failure → wallet balance only, marked partial; wallet failure → windows kept), and only two failures raise. Errors distinguish authentication failure, no active subscription, invalid responses and network failures.
78
+ - Docs now cover endpoint permissions, which endpoints accept a Control Key, why `workspaceId` must come from `items[].workspaceId` of `GET /api/v1/workspaces` (a user id yields 403 `workspace_billing_scope_forbidden`) and a 401 troubleshooting checklist: [OpenDesign billing and troubleshooting](opendesign-billing.md).
79
+ - Thanks to [@playgithub](https://github.com/Han-1413141/dsh-cost-meter/issues/274#issuecomment-6215322540) for requesting OpenDesign support and reproducing the entry problem, [@codeforker654](https://github.com/Han-1413141/dsh-cost-meter/issues/274#issuecomment-6236228870) for reproducing and reporting the 401, and [@yunjuanhuakai](https://github.com/Han-1413141/dsh-cost-meter/issues/274#issuecomment-6236591566) for discovering that `/billing/preflight` accepts the Control Key and providing sample responses.
80
+
81
+ ### Upgrade
82
+
83
+ Re-run the new `install.ps1` or update from the plugin marketplace (`dsh plugin --profile web add dsh-cost-meter@latest` for npm), then fully quit and reopen DSH. The ledger format is unchanged; historical amounts are not recalculated automatically except for the confirmed historical Codex reclassification.
@@ -0,0 +1,100 @@
1
+ # v1.9.1
2
+
3
+ ## 中文
4
+
5
+ 本版本修复皮肤类插件把主题别名(`--dsw-alias-bg-*`)调成半透明后,插件浮层与弹窗透出后方页面内容的问题;同时对记账、账本落盘合并、统计缓存与设置页自动保存路径做了可度量的性能优化。**无配置或账本格式变化,升级后无需手动迁移。**
6
+
7
+ ### 皮肤半透明时浮层与弹窗不再透出后方内容
8
+
9
+ 皮肤插件把 `--dsw-alias-bg-base` / `--dsw-alias-bg-layer-1` / `--dsw-alias-bg-layer-2` 设成 `rgba(...)` 时,插件里直接使用这些别名的容器会整体变透明,导致弹窗内部左右两栏、浮层与后方页面互相透出,文字不可读。
10
+
11
+ 本版本把「遮挡面」(必须遮住下方内容的浮层/弹窗)统一改为**本地不透明基底 + 皮肤色渐变叠层**合成:
12
+
13
+ - `background-color` 使用不透明本地基底:浅色主题 `#fff`,深色主题(`body[data-ds-dark-theme]` / `html[data-theme=dark]`)`#151517`;
14
+ - `background-image` 用皮肤别名色做一层渐变,保留皮肤的色调与明暗观感;
15
+ - 默认主题或不透明皮肤下合成结果与原视觉完全一致;半透明皮肤下不再透出后方内容。
16
+
17
+ 覆盖的遮挡面:
18
+
19
+ - 主包:统计明细弹窗(`.cm-stat-dialog`)、额度引导(`.cm-qguide`)、峰谷提醒(`.cm-peak-alert`)、精简侧栏底栏(`.cm-footer-stack.simple`);
20
+ - 统计页:费用明细弹窗(`dialog.cm-fee-dialog`)、上下文费用开关引导(`.cm-context-intro`)、billion-context 提示(`.cm-billion-notice`);
21
+ - 定价页:模型/价格组合浮层(`.cm-combo-panel`);
22
+ - Codex 兼容弹窗复用统计弹窗样式,自动获得同样的不透明合成。
23
+
24
+ 新增静态 fixture `test/skin-occlusion-static.mjs`(源码规则 + 构建产物标记双重断言),并在真实浏览器回归里模拟 Dream Skin(半透明 `--dsw-alias-bg-base` 与半透明 `--dsw-alias-bg-layer-2`),断言弹窗底色不透明且渐变里保留皮肤色。
25
+
26
+ ### 记账性能:价格历史快照改为落盘时推进
27
+
28
+ 此前每一笔用量入账都会重建整张价格历史快照(835 个模型,约 2.18ms 名称整理 + 0.66ms 哈希 + JSON 比较),占单笔记账耗时(1.3–2.3ms)的 99.8%。现在改为在落盘合并的锁内一次性推进价格历史,单笔记账不再触发重建。
29
+
30
+ - 1000 笔连续记账:1308ms → 93ms;
31
+ - 短窗口(1 / 5 / 20 / 50 笔):42.4 / 46.4 / 64.5 / 102.9ms → 36.5 / 34.5 / 36.5 / 39.1ms(约 -26% / -43% / -62%)。
32
+
33
+ 价格变更仍由配置写入路径记录,历史价格查询与重算结果不变。
34
+
35
+ ### 落盘合并与渲染缓存优化
36
+
37
+ - 账本落盘合并(`mergeLedger`)不再无条件做 3 次全账本深拷贝:本地快照是自有对象时跳过克隆、磁盘快照与基线相同时直接复用,待提交记录仍逐条重放。普通 flush 由约 40ms 降到约 30ms,合并后的内存/磁盘账本内容与语义哈希(`30f37c10373d0a50`)和原实现完全一致。
38
+ - 统计页渲染缓存键改用 `pricesRev`,不再每帧序列化整张价格表(178KB,2.55ms → 0.015ms,约 170 倍);旧宿主没有 `pricesRev` 时回退原来的整体序列化。
39
+ - 设置页自动保存的逐键差异比较增加引用短路:未变化的配置项直接跳过,不再对每个键序列化比较。
40
+
41
+ ### 验证
42
+
43
+ - `node test/verify.mjs`:全部断言通过(含新增皮肤遮挡静态断言)。
44
+ - 真实浏览器回归:`test/statistics-dialog-titlebar.mjs`(229 条断言,含皮肤与窄屏几何)、`test/session-costs-browser.mjs`(含 Dream Skin 不透明合成断言)通过。
45
+ - 全部测试使用本地账本与合成数据,不发起真实模型请求、不消耗订阅额度。
46
+
47
+ ### 升级方式
48
+
49
+ ```powershell
50
+ dsh plugin --profile desktop add dsh-cost-meter@1.9.1
51
+ ```
52
+
53
+ 重启 DSH 后生效(web Profile 把 `desktop` 换成 `web`)。或重新运行一键安装脚本:`irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.1/install.ps1 | iex`。
54
+
55
+ ## English
56
+
57
+ This release fixes translucent skin plugins leaking page content through plugin overlays and dialogs, and ships measured performance improvements for accounting, ledger flushes, statistics caching and settings auto-save. **No configuration or ledger schema changes; no manual migration is required.**
58
+
59
+ ### Overlays and dialogs stay opaque with translucent skins
60
+
61
+ When a skin plugin sets `--dsw-alias-bg-base` / `--dsw-alias-bg-layer-1` / `--dsw-alias-bg-layer-2` to `rgba(...)`, containers that use those aliases directly become translucent: dialog columns, popovers and the page behind them bleed into each other and text becomes unreadable.
62
+
63
+ All "occluding" surfaces (overlays/dialogs that must cover what is behind them) now composite an **opaque local base + a skin-tint gradient**:
64
+
65
+ - `background-color` uses an opaque local base: `#fff` in light themes, `#151517` in dark themes (`body[data-ds-dark-theme]` / `html[data-theme=dark]`);
66
+ - `background-image` keeps the skin alias colour as a gradient layer, preserving the skin's hue;
67
+ - with the default theme or opaque skins the composite is visually identical to before; with translucent skins nothing behind the surface bleeds through.
68
+
69
+ Covered surfaces: the main stat dialog, quota guide, peak alert and simple footer (main bundle); the fee dialog, context-costs intro and billion-context notice (statistics page); and the model/price combo popover (pricing page). The Codex compat dialog reuses the stat dialog rule and inherits the fix.
70
+
71
+ A new static fixture (`test/skin-occlusion-static.mjs`) asserts both source rules and built-bundle markers, and the real-browser suites simulate a Dream Skin (translucent `--dsw-alias-bg-base` and `--dsw-alias-bg-layer-2`) and assert an opaque background with the skin tint preserved in the gradient.
72
+
73
+ ### Faster accounting: price-history snapshots advanced at flush time
74
+
75
+ Every usage entry used to rebuild the whole price-history snapshot (835 models, ~2.18ms normalisation + 0.66ms hashing + JSON comparison), which was 99.8% of the per-entry cost (1.3–2.3ms). Price history is now advanced once inside the flush lock, so individual entries no longer rebuild it.
76
+
77
+ - 1000 consecutive entries: 1308ms → 93ms;
78
+ - short windows (1 / 5 / 20 / 50 entries): 42.4 / 46.4 / 64.5 / 102.9ms → 36.5 / 34.5 / 36.5 / 39.1ms (about -26% / -43% / -62%).
79
+
80
+ Price changes are still recorded on config writes, and historical pricing queries/repricing keep the same results.
81
+
82
+ ### Ledger merge and render-cache optimisations
83
+
84
+ - `mergeLedger` no longer performs three unconditional deep clones of the whole ledger: the local snapshot is cloned only when it is not owned, and the disk snapshot is reused when it equals the base; pending records are still replayed one by one. A normal flush drops from ~40ms to ~30ms, and the merged in-memory/on-disk ledger content and semantic hash (`30f37c10373d0a50`) are identical to the previous implementation.
85
+ - The statistics render cache key now uses `pricesRev` instead of serialising the whole price table on every render (178KB, 2.55ms → 0.015ms, about 170×); hosts without `pricesRev` fall back to the old serialisation.
86
+ - Settings auto-save diffing short-circuits unchanged entries by reference, avoiding serialisation comparisons for every key.
87
+
88
+ ### Verification
89
+
90
+ - `node test/verify.mjs`: all assertions pass, including the new skin-occlusion static fixture.
91
+ - Real-browser suites: `test/statistics-dialog-titlebar.mjs` (229 assertions incl. skin and narrow-viewport geometry) and `test/session-costs-browser.mjs` (incl. the Dream Skin opacity assertions) pass.
92
+ - All tests use local ledgers and synthetic data; no live model requests and no subscription quota consumption.
93
+
94
+ ### Upgrading
95
+
96
+ ```powershell
97
+ dsh plugin --profile desktop add dsh-cost-meter@1.9.1
98
+ ```
99
+
100
+ Restart DSH afterwards (use `web` instead of `desktop` for the web profile), or rerun the one-click installer: `irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.1/install.ps1 | iex`.
@@ -0,0 +1,46 @@
1
+ # v1.9.2
2
+
3
+ ## 中文
4
+
5
+ 本版包含 [PR #314](https://github.com/Han-1413141/dsh-cost-meter/pull/314) 的全部修复。v1.9.1 未单独发布到 npm,其记账、落盘合并、统计缓存和设置比较优化也一并发布。账本格式与历史金额口径不变,升级无需手动迁移。
6
+
7
+ - **OpenDesign**:直接并行查询接受 Control Key 的 `/billing/preflight` 与独立钱包接口,正常查询从 3 次 GET 减为 2 次,保留身份、大整数和单侧失败处理。仅在 DSH 中使用模型 API 计费,不需要安装 OpenDesign 应用;远端额度查询需要工作区 ID 和 Control Key。[配置说明](opendesign-billing.md)
8
+ - **自定义余额**:以 `/` 开头的相对路径跟随 DSH 实际监听端口,端口改变后缓存失效。局域网 HTTP 需显式打开 `allowInsecureHttp` 并填写准确的主机与端口白名单;凭据仍通过凭据库引用。[配置说明](custom-balance-sources.md)
9
+ - **WorkBuddy2API**:新增积分预设,读取管理接口的活跃账号池积分 `summary.available_remaining`。使用管理端 `X-Admin-Token`,不是模型 API Key;按实际服务端口填写地址。
10
+ - **皮肤透明度**:页面与弹窗保留皮肤 RGB 颜色并去除背景 alpha;统计内容使用弹窗表面色,解决深色壁纸遮罩与浅色弹窗混用时的黑底黑字。11 类区域、3 种主题、4 档透明度共 132 个浏览器场景全部通过。
11
+ - **性能**:缓存自动语言模式的宿主语言探测结果,随设置和语言事件失效;没有事件的旧宿主最多每秒检查一次。5 轮各 2,000 次费用读取的隔离基准中,中位耗时从 1,719.58 ms 降至 40.19 ms,降低 97.7%;此数值不代表整个 DSH 的 CPU 降幅。新增功能后,主客户端仍从 261,676 字节降至 260,671 字节。[原始数据与复现方法](performance-2026-10-18.md)
12
+
13
+ 本版代码已通过完整本地回归、Windows / Linux 安装、宿主兼容、浏览器交互及 CodeQL 检查。OpenDesign 与 WorkBuddy2API 的认证路径使用模拟响应验证,未查询真实用户账号。
14
+
15
+ ### 升级
16
+
17
+ 在 DSH 对应的 CLI 中执行:
18
+
19
+ ```powershell
20
+ dsh plugin --profile desktop add dsh-cost-meter@1.9.2
21
+ ```
22
+
23
+ 随后完全重启 DSH。Web 用户把 `desktop` 换成 `web`;Desktop 用户按[桌面版安装说明](install-troubleshooting.md#desktop-安装与更新)使用应用自带的 CLI。
24
+
25
+ ### 贡献
26
+
27
+ - @playgithub 提出 [#274](https://github.com/Han-1413141/dsh-cost-meter/issues/274) 接入需求、设置交互反馈及仅使用 DSH API 的配置问题。
28
+ - @codeforker654 提供 [Control Key 401 复现](https://github.com/Han-1413141/dsh-cost-meter/issues/274#issuecomment-6236228870);@yunjuanhuakai 提供 [preflight 端点定位、响应结构与验证](https://github.com/Han-1413141/dsh-cost-meter/issues/274#issuecomment-6236591566)。
29
+ - @unifilitence 提供 [#313](https://github.com/Han-1413141/dsh-cost-meter/issues/313) 独立复现、端点建议与钱包契约。
30
+ - @XHPAN 提供 [#312](https://github.com/Han-1413141/dsh-cost-meter/issues/312) CPU profile 归因和缓存失效建议。
31
+ - @Jav1es 提供 [#311](https://github.com/Han-1413141/dsh-cost-meter/issues/311) 随机端口复现与相对路径建议。
32
+ - @snhun 提出 [#309](https://github.com/Han-1413141/dsh-cost-meter/issues/309) 局域网 HTTP 和 [#310](https://github.com/Han-1413141/dsh-cost-meter/issues/310) WorkBuddy2API 接入需求。
33
+
34
+ ## English
35
+
36
+ This release includes all fixes from [PR #314](https://github.com/Han-1413141/dsh-cost-meter/pull/314), plus the accounting, ledger merge, statistics cache and settings comparison improvements recorded under v1.9.1, which was not published separately to npm. Ledger format and historical amounts remain unchanged.
37
+
38
+ - OpenDesign directly queries the Control Key-compatible preflight endpoint and the independent wallet endpoint, reducing a normal query from three GET requests to two. DSH-only model usage accounting does not require installing the OpenDesign application.
39
+ - Host-relative custom-balance URLs follow the actual DSH listening port and invalidate cached results when it changes. LAN HTTP requires an explicit opt-in and an exact host/port allowlist.
40
+ - A WorkBuddy2API preset reads active account-pool credits through its admin endpoint with an `X-Admin-Token`, separate from model API keys and monetary costs.
41
+ - Pages and dialogs retain skin RGB colours with opaque backgrounds. Statistics content uses the popup surface colour to keep text readable when wallpaper and popup colours differ. All 132 browser opacity scenarios pass.
42
+ - Automatic-language fallback results are cached with event invalidation and a one-second fallback interval. In five isolated rounds of 2,000 cost reads, median time fell from 1,719.58 ms to 40.19 ms (97.7%). This is not a claim about total DSH CPU usage. The main client is 260,671 bytes, down from 261,676 bytes despite the added features. [Method and raw data](performance-2026-10-18.md)
43
+
44
+ Full local regression, Windows/Linux installation, host compatibility, browser interaction and CodeQL checks passed for the implementation. Authenticated OpenDesign and WorkBuddy2API paths were tested with synthetic responses rather than live user accounts. Contributor roles and original reports are linked above.
45
+
46
+ Upgrade using `dsh plugin --profile desktop add dsh-cost-meter@1.9.2`, then fully restart DSH. Use `web` for a web profile and the bundled CLI for Desktop installations.
package/lib/backfill.js CHANGED
@@ -258,13 +258,31 @@ export function listSessionLogs(root, onlySessionIds = null) {
258
258
  return listSessionLogFiles(root, onlySessionIds)
259
259
  }
260
260
 
261
- /** Merge the plugin journal before replay, so UUID dedup also covers repaired v1.7.21 logs. */
262
- async function* sessionBillingRecords(ledger, sessionsRoot, onlySessionIds = null) {
261
+ /**
262
+ * Merge the plugin journal before replay, so UUID dedup also covers repaired v1.7.21 logs.
263
+ * @param sessionSource - 可选的统一会话记录源(T3):非空时用
264
+ * `listSessions(onlySessionIds)` 枚举 + `readRecords(id)` 读取(JSONL 文件或 SQLite
265
+ * 由适配器自动选择);为空时保持原有 `listSessionLogs` 文件枚举路径不变。
266
+ */
267
+ async function* sessionBillingRecords(ledger, sessionsRoot, onlySessionIds = null, sessionSource = null) {
263
268
  const seen = new Set()
264
- for (const path of listSessionLogs(sessionsRoot, onlySessionIds)) {
269
+ const hasSource = sessionSource !== null && sessionSource !== undefined
270
+ const sessions = hasSource ? await sessionSource.listSessions(onlySessionIds) : null
271
+ const paths = hasSource ? null : listSessionLogs(sessionsRoot, onlySessionIds)
272
+ for (const entry of sessions ?? paths) {
265
273
  let records
266
- try { records = await readSessionRecordsAsync(path) } catch { yield null; continue }
267
- const id = records.find(record => record.type === 'session')?.id
274
+ let id
275
+ try {
276
+ if (hasSource) {
277
+ id = typeof entry?.id === 'string' ? entry.id : ''
278
+ if (id.length === 0) continue
279
+ records = await sessionSource.readRecords(id)
280
+ } else {
281
+ records = await readSessionRecordsAsync(entry)
282
+ id = records.find(record => record.type === 'session')?.id
283
+ }
284
+ } catch { yield null; continue }
285
+ if (!Array.isArray(records)) { yield null; continue }
268
286
  if (typeof id === 'string') {
269
287
  seen.add(id)
270
288
  try { for (const record of await nativeSearchRecordsFor(ledger.path, id)) records.push(record) } catch { /* Keep the readable host prefix. */ }
@@ -291,8 +309,11 @@ async function* sessionBillingRecords(ledger, sessionsRoot, onlySessionIds = nul
291
309
  }
292
310
  }
293
311
 
294
- /** Recover only recent, fully covered days. Neither calls nor recorded costs change. */
295
- export async function repairPlanHourBuckets(ledger, sessionsRoot, { nowMs = Date.now(), isActive = () => true } = {}) {
312
+ /**
313
+ * Recover only recent, fully covered days. Neither calls nor recorded costs change.
314
+ * @param sessionSource - 可选统一会话记录源(T3);为空时走原 JSONL 文件枚举。
315
+ */
316
+ export async function repairPlanHourBuckets(ledger, sessionsRoot, { nowMs = Date.now(), isActive = () => true } = {}, sessionSource = null) {
296
317
  const config = structuredClone(ledger.config), fingerprint = planUsageFingerprint(config)
297
318
  const historyReset = structuredClone(ledger.historyReset ?? null)
298
319
  const from = nowMs - HOUR_BUCKET_RETENTION_MS
@@ -304,7 +325,7 @@ export async function repairPlanHourBuckets(ledger, sessionsRoot, { nowMs = Date
304
325
  }
305
326
  if (!sessionIds.size || !isActive() || ledger.closed) return { days: 0 }
306
327
  const byDay = new Map(), enabled = enabledPlanSetOf(config)
307
- for await (const records of sessionBillingRecords(ledger, sessionsRoot, sessionIds)) {
328
+ for await (const records of sessionBillingRecords(ledger, sessionsRoot, sessionIds, sessionSource)) {
308
329
  if (!isActive() || ledger.closed || planUsageFingerprint(ledger.config) !== fingerprint) return { days: 0 }
309
330
  if (!records) continue
310
331
  const replay = replaySessionRecords(records, config, dates, true)
@@ -598,9 +619,10 @@ export function replaySessionRecords(records, config, wantDates = null, collectS
598
619
  * 写入该会话当日的回放拆分。
599
620
  * @param ledger - 已打开的账本。
600
621
  * @param sessionsRoot - 宿主会话根目录($DSH_HOME/sessions)。
622
+ * @param sessionSource - 可选统一会话记录源(T3,better-session/RDB);为空时走原 JSONL 文件枚举。
601
623
  * @returns { days, sessions, scanned, titles } 实际填补的日期/会话数、扫描文件数与补齐的会话标题数。
602
624
  */
603
- export async function backfillLegacyLedger(ledger, sessionsRoot) {
625
+ export async function backfillLegacyLedger(ledger, sessionsRoot, sessionSource = null) {
604
626
  const result = { days: 0, sessions: 0, scanned: 0, titles: 0 }
605
627
  const needDates = new Set()
606
628
  for (const [date, day] of Object.entries(ledger.days ?? {})) {
@@ -648,7 +670,7 @@ export async function backfillLegacyLedger(ledger, sessionsRoot) {
648
670
  }
649
671
  }
650
672
  }
651
- for await (const records of sessionBillingRecords(ledger, sessionsRoot, onlySessionIds)) {
673
+ for await (const records of sessionBillingRecords(ledger, sessionsRoot, onlySessionIds, sessionSource)) {
652
674
  // 会话日志多时逐份解压会长时间占住事件循环:每 8 份让出一次,不卡宿主 UI;
653
675
  // 单文件内部亦为流式读取(v1.7.7,issue #88:解压期间周期性让出,大日志不再卡死宿主)。
654
676
  if ((scannedCount += 1) % 8 === 0) await new Promise(resolve => setImmediate(resolve))
@@ -891,13 +913,14 @@ function sessionEntryOf(sessionId, info, totals, pm) {
891
913
  * - 同一会话跨安装时刻:实时条目已存在,安装前用量不计入(无法安全拆分)。
892
914
  * @param ledger - 已打开的账本。
893
915
  * @param sessionsRoot - 宿主会话根目录($DSH_HOME/sessions)。
916
+ * @param sessionSource - 可选统一会话记录源(T3,better-session/RDB);为空时走原 JSONL 文件枚举。
894
917
  * @returns { days, sessions, scanned } 重建/追加的日期数、新增会话数与扫描文件数。
895
918
  */
896
- export async function importLegacyHistory(ledger, sessionsRoot) {
919
+ export async function importLegacyHistory(ledger, sessionsRoot, sessionSource = null) {
897
920
  const result = { days: 0, sessions: 0, scanned: 0 }
898
921
  const bySession = new Map()
899
922
  let scannedCount = 0
900
- for await (const records of sessionBillingRecords(ledger, sessionsRoot)) {
923
+ for await (const records of sessionBillingRecords(ledger, sessionsRoot, null, sessionSource)) {
901
924
  if ((scannedCount += 1) % 8 === 0) await new Promise(resolve => setImmediate(resolve))
902
925
  result.scanned += 1
903
926
  let replayed
@@ -988,9 +1011,13 @@ export async function importLegacyHistory(ledger, sessionsRoot) {
988
1011
  * @param ledger - 已打开的账本(config 已是目标币种价格表)。
989
1012
  * @param sessionsRoot - 宿主会话根目录($DSH_HOME/sessions)。
990
1013
  * @param includeBucket - 可选的 (providerModelKey, date) 过滤器,仅修复目标价格路径。
1014
+ * @param onlySessionIds - 可选:仅回放这些会话。
1015
+ * @param explicit - 是否显式重定价(设置页 RPC),会记录前后金额与历史快照。
1016
+ * @param model - 可选的单个 provider:model 键。
1017
+ * @param sessionSource - 可选统一会话记录源(T3,better-session/RDB);为空时走原 JSONL 文件枚举。
991
1018
  * @returns {{ scanned, recostedSessions, skippedSessions, recostedDays }}。
992
1019
  */
993
- export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeBucket, onlySessionIds = null, explicit = false, model = '') {
1020
+ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeBucket, onlySessionIds = null, explicit = false, model = '', sessionSource = null) {
994
1021
  const result = { scanned: 0, recostedSessions: 0, skippedSessions: 0, recostedDays: 0 }
995
1022
  const pricingConfig = explicit ? currentPricingConfig(ledger.config) : ledger.config
996
1023
  if (explicit && model) pricingConfig._repriceFxConfig = ledger.config
@@ -999,7 +1026,7 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
999
1026
  const reset = JSON.stringify(ledger.historyReset ?? null)
1000
1027
  const startedAt = Date.now()
1001
1028
  const bySession = new Map()
1002
- for await (const records of sessionBillingRecords(ledger, sessionsRoot, onlySessionIds)) {
1029
+ for await (const records of sessionBillingRecords(ledger, sessionsRoot, onlySessionIds, sessionSource)) {
1003
1030
  if ((result.scanned += 1) % 8 === 0) await new Promise(resolve => setImmediate(resolve))
1004
1031
  let replayed
1005
1032
  try {
@@ -1114,17 +1141,23 @@ function subtractBucketInto(target, source) {
1114
1141
  * 减法逐字段 clamp ≥ 0,即使账本未被污染(种子量为 0)也无副作用。
1115
1142
  * @param ledger - 已打开的账本。
1116
1143
  * @param sessionsRoot - 宿主会话根目录($DSH_HOME/sessions)。
1144
+ * @param sessionSource - 可选统一会话记录源(T3,better-session/RDB);为空时走原 JSONL 文件枚举。
1117
1145
  * @returns { sessions, days, scanned } 受影响的 fork 会话数、扣除的日期数与扫描文件数。
1118
1146
  */
1119
- export async function repairForkSeed(ledger, sessionsRoot) {
1147
+ export async function repairForkSeed(ledger, sessionsRoot, sessionSource = null) {
1120
1148
  const result = { sessions: 0, days: 0, scanned: 0 }
1121
- for (const path of listSessionLogs(sessionsRoot)) {
1149
+ const hasSource = sessionSource !== null && sessionSource !== undefined
1150
+ // 统一记录源(T3):RDB 下从数据库枚举会话;未传源时保持原 JSONL 文件枚举路径不变。
1151
+ const entries = hasSource
1152
+ ? (await sessionSource.listSessions()).map(row => (typeof row === 'string' ? row : row?.id)).filter(id => typeof id === 'string' && id.length > 0)
1153
+ : listSessionLogs(sessionsRoot)
1154
+ for (const entry of entries) {
1122
1155
  // 全量同步扫描会长时间占住事件循环:每 8 份让出一次(与回填/导入同策略);
1123
1156
  // 单文件内部亦为流式读取(v1.7.7,issue #88)。
1124
1157
  if ((result.scanned += 1) % 8 === 0) await new Promise(resolve => setImmediate(resolve))
1125
1158
  let records
1126
1159
  try {
1127
- records = await readSessionRecordsAsync(path)
1160
+ records = hasSource ? await sessionSource.readRecords(entry) : await readSessionRecordsAsync(entry)
1128
1161
  } catch {
1129
1162
  continue // 单文件损坏(含解压预算超限)不阻断整体清洗。
1130
1163
  }
@@ -2,6 +2,7 @@
2
2
  import { join } from 'node:path'
3
3
  import { resolveDshHome } from '@deepseek-ai/dsh-home-paths'
4
4
  import { listSessionLogs, iterateSessionRecords } from './backfill.js'
5
+ import { probeSessionStorage, readSessionRecords } from './session-storage-compat.js'
5
6
 
6
7
  const LIMIT = 16000
7
8
  const validSeq = n => Number.isSafeInteger(n) && n >= 0
@@ -114,6 +115,11 @@ export async function getCallInspection(ctx, query) {
114
115
  || !validSeq(query.offset ?? 0) || (query.offset ?? 0) > 1e7) throw new Error('invalid call inspection query')
115
116
  const live = ctx?.get?.('sessions')?.get?.(query.sessionId)?.snapshotEvents?.()
116
117
  if (Array.isArray(live)) return inspectCall(live, query.seq, query.offset ?? 0, query.atMs)
118
+ // RDB(会话 SQLite)宿主不再落 JSONL 文件:通过兼容层读同一份 records 事件源。
119
+ if (probeSessionStorage(ctx).mode === 'rdb') {
120
+ const stored = await readSessionRecords(ctx, query.sessionId, { maxEvents: 500_000 })
121
+ return inspectCall(stored?.records ?? [], query.seq, query.offset ?? 0, query.atMs)
122
+ }
117
123
  const paths = listSessionLogs(join(resolveDshHome(), 'sessions'), new Set([query.sessionId]))
118
124
  return inspectCall(paths.length ? iterateSessionRecords(paths[0]) : [], query.seq, query.offset ?? 0, query.atMs)
119
125
  }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @eddyskywalker/dsh-chatgpt-subscription 兼容(9 条订阅线路归 Plan)。
3
+ *
4
+ * 该插件注册 9 条走「订阅额度」的 LLM provider(codex-chatgpt / claude-subscription /
5
+ * antigravity / kimi-code / minimax-code / command-code / workbuddy-subscription /
6
+ * glm-coding-plan / step-code),用量消耗的是各订阅账户的额度,不应计入 API 真金白银。
7
+ *
8
+ * 本模块负责(均为纯本地逻辑,**绝不发起网络请求**):
9
+ * 1. 泛化检测该插件是否安装(复用 codex-subscription-compat.js 的
10
+ * detectSubscriptionPackage,支持 scoped 包名的三条路径);
11
+ * 2. 启动时把这些线路 provider 对应的 Plan 提供商 id 归类写为 'plan'
12
+ * (只影响新用量;历史 apiCost 不在此重算),用户显式选择的 plan/api 不覆盖。
13
+ */
14
+
15
+ import { detectSubscriptionPackage } from './codex-subscription-compat.js'
16
+
17
+ /** @eddyskywalker/dsh-chatgpt-subscription 的 npm 包名(检测与前端展示共用)。 */
18
+ export const CHATGPT_SUBSCRIPTION_PACKAGE = '@eddyskywalker/dsh-chatgpt-subscription'
19
+
20
+ /**
21
+ * 9 条订阅线路 provider → dsh-cost-meter 的 Plan 提供商 id。
22
+ *
23
+ * provider 名来自该插件注册的 LLM provider;planId 必须存在于
24
+ * lib/plan-billing.js 的 PLAN_PROVIDER_IDS(否则 store.js 清洗/校验会丢弃配置)。
25
+ */
26
+ export const CHATGPT_SUBSCRIPTION_PROVIDER_PLANS = Object.freeze({
27
+ 'codex-chatgpt': 'codex',
28
+ 'claude-subscription': 'anthropic',
29
+ antigravity: 'antigravity',
30
+ 'kimi-code': 'kimi',
31
+ 'minimax-code': 'minimax',
32
+ 'command-code': 'commandcode',
33
+ 'workbuddy-subscription': 'workbuddy',
34
+ 'glm-coding-plan': 'zai',
35
+ 'step-code': 'stepfun',
36
+ })
37
+
38
+ /**
39
+ * 检测 @eddyskywalker/dsh-chatgpt-subscription 是否安装(纯本地)。
40
+ *
41
+ * detectSubscriptionPackage 的薄包装;options 与 detectCodexSubscription 相同
42
+ * ({ moduleUrl, env, homeDir, profileDir, fs }),便于测试注入假 fs/env。
43
+ *
44
+ * @returns {{ installed: boolean, version: string, detection: 'package'|'profile'|'none', packagePath: string }}
45
+ */
46
+ export function detectChatgptSubscription(options = {}) {
47
+ return detectSubscriptionPackage(CHATGPT_SUBSCRIPTION_PACKAGE, options)
48
+ }
49
+
50
+ /**
51
+ * 启动时调用:检测到该插件后,把尚未显式配置的线路 provider 归类写为 'plan'。
52
+ *
53
+ * - 只覆盖 undefined / 'auto'(以及任何非法值);用户显式选择的 'plan'/'api' 不覆盖;
54
+ * - 不调用 splitLedgerApiCost:历史 apiCost 保持原样(仅影响新用量);
55
+ * - 全部写完后只调用一次 ledger.scheduleWrite()。
56
+ *
57
+ * @param ledger - 账本(至少需要 config.planBilling.providers 与 scheduleWrite)。
58
+ * @param detection - detectChatgptSubscription() 结果。
59
+ * @returns {{ changed: boolean, planIds: string[] }} planIds 为本次实际写成 'plan' 的提供商 id。
60
+ */
61
+ export function ensureChatgptSubscriptionPlan(ledger, detection) {
62
+ if (detection?.installed !== true) return { changed: false, planIds: [] }
63
+ const config = ledger?.config
64
+ if (config === null || typeof config !== 'object' || Array.isArray(config)) return { changed: false, planIds: [] }
65
+ const billing = config.planBilling
66
+ if (billing === null || typeof billing !== 'object' || Array.isArray(billing)) return { changed: false, planIds: [] }
67
+ const current = billing.providers
68
+ const providers = current !== null && typeof current === 'object' && !Array.isArray(current) ? current : (billing.providers = {})
69
+ const planIds = []
70
+ for (const planId of Object.values(CHATGPT_SUBSCRIPTION_PROVIDER_PLANS)) {
71
+ const value = providers[planId]
72
+ if (value === 'plan' || value === 'api') continue
73
+ providers[planId] = 'plan'
74
+ planIds.push(planId)
75
+ }
76
+ if (planIds.length === 0) return { changed: false, planIds }
77
+ ledger.scheduleWrite?.()
78
+ return { changed: true, planIds }
79
+ }
@@ -0,0 +1 @@
1
+ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.codex.js",factory:g=>{const f=g("react"),{createElement:e,useState:C,useEffect:h,useRef:v}=f,N="cm-stat-dialog cm-codex-compat-dialog";if(typeof document<"u"){const s=document.createElement("style");s.textContent=".cm-codex-compat-dialog{width:min(560px,94vw)}.cm-codex-compat{display:flex;flex-direction:column;gap:8px;font-size:13px}",s.textContent+='@media (max-width:1023px){.cm-codex-compat-dialog{width:calc(100vw - 32px)}.cm-codex-compat{padding:0 2px}}body[data-dsh-pocket-layout="mobile"] .cm-codex-compat-dialog{width:calc(100vw - 32px)}',document.head.appendChild(s)}function P(){const[s,u]=C(!1),[a,c]=C(null);return[s,a,o=>{s||(u(!0),c(null),o().catch(t=>c(t?.message??String(t))).finally(()=>u(!1)))}]}function y(s){const a=s.state?.codexCompat,c=s.api,i=s.locale==="en",o=(x,A)=>i?A:x,t=v(null),[l,n,p]=P(),r=a?.promptDue===!0;if(h(()=>{r&&t.current&&!t.current.open&&t.current.showModal()},[r]),!r)return null;const d=a.usage??{},m=()=>p(c.dismissCodexCompat);return e("dialog",{ref:t,className:N,"aria-label":o("兼容修复","Compatibility fix"),onCancel:x=>{x.preventDefault(),m()}},e("header",{className:"cm-stat-dialog-head"},o("兼容修复","Compatibility fix"),e("button",{type:"button",className:"cm-btn","aria-label":o("关闭","Close"),disabled:l,onClick:m},"×")),e("div",{className:"cm-stat-dialog-body"},e("p",null,o("检测到 dsh-codex-subscription {version}。Codex 订阅用量不计入 API 费用;为兼容本插件,新产生的 Codex 用量已自动归类为 Plan。是否将历史 codex 类模型的计费统一归类为 Plan(订阅额度,不计入 API 费用)?","Detected dsh-codex-subscription {version}. Codex subscription usage is not billed as API usage; for compatibility this plugin now defaults new Codex usage to Plan. Reclassify the billing of historical codex-class models as Plan (subscription quota, excluded from API usage)?").replace("{version}","v"+(a.version??""))),d.calls>0?e("p",{className:"cm-note"},o("历史 Codex 用量:{calls} 次调用 · {cost} · {days} 天","Historical Codex usage: {calls} calls · {cost} · {days} days").replace("{calls}",d.calls).replace("{cost}","$"+Number(d.cost??0).toFixed(2)).replace("{days}",d.days)):null,n?e("div",{className:"cm-msg err"},o("失败:","Failed: ")+n):null,e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn",disabled:l,onClick:m},o("保持现状","Keep status quo")),e("button",{type:"button",className:"cm-btn primary",disabled:l,onClick:()=>p(c.applyCodexCompatHistory)},o("统一归类为 Plan","Reclassify as Plan"))),e("p",{className:"cm-note"},o("之后可在 设置 → 费用 → Codex 订阅兼容 中处理。","You can change this later in Settings → Cost → Codex subscription compatibility."))))}function b(s){const a=s.state?.codexCompat;if(a?.installed!==!0)return null;const c=s.api,i=s.t,o=s.locale==="en",t=(r,d)=>o?d:r,l=a.usage??{},n=a.historyAppliedAt>0,p=a.planClass==="plan"?i("billingClassPlan"):a.planClass==="api"?i("billingClassApi"):i("billingClassAuto");return e("div",{className:"cm-codex-compat"},e("h3",null,t("Codex 订阅兼容","Codex subscription compatibility")),e("p",null,t("检测版本:{version}","Detected version: {version}").replace("{version}","v"+(a.version??""))),e("p",null,t("当前计费方式:{planClass}","Current billing class: {planClass}").replace("{planClass}",p)),e("p",null,t("历史用量:{calls} 次调用 · {cost} · {tokens} tokens · {days} 天","Historical usage: {calls} calls · {cost} · {tokens} tokens · {days} days").replace("{calls}",l.calls).replace("{cost}","$"+Number(l.cost??0).toFixed(2)).replace("{tokens}",Number(l.tokens??0).toLocaleString(o?"en-US":"zh-CN")).replace("{days}",l.days)),n?e("p",{className:"cm-note"},t("已归类于 {time}","Reclassified at {time}").replace("{time}",new Date(a.historyAppliedAt).toLocaleString())):e("p",null,t("历史用量未归类。","Historical usage is not reclassified yet.")),!n&&l.providers?.length?e("p",{className:"cm-note"},t("来源:{providers}","Sources: {providers}").replace("{providers}",l.providers.join(", "))):null,n?null:e("div",{className:"cm-buttons"},e("button",{type:"button",className:"cm-btn primary",onClick:()=>c.applyCodexCompatHistory().catch(()=>{})},t("统一归类为 Plan","Reclassify as Plan"))),!n&&a.promptDismissed===!0?e("p",{className:"cm-note"},t("此前选择保持现状,可随时统一归类。","You chose Keep status quo earlier; you can reclassify anytime.")):null)}function w(){return{CodexCompatPrompt:y,CodexCompatPanel:b}}return{mount:w,CodexCompatPrompt:y,CodexCompatPanel:b}}});
@@ -1 +1 @@
1
- window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.community.js",factory:d=>{const y=d("react"),{createElement:e,useState:p,useEffect:f}=y,a="dsh-cost-meter:community-notice-seen",r=new Set;let i=!1;function b(){if(i)return!0;try{return window.localStorage.getItem(a)==="1"}catch{return!1}}function w({locale:s,footer:t=!1}){const[m,c]=p(b),n=s==="en",h="https://github.com/Han-1413141/dsh-cost-meter/blob/master/"+(n?"README.md#community":"README.zh-CN.md#交流与反馈"),g=()=>{i=!0;try{window.localStorage.setItem(a,"1")}catch{}c(!0);for(const o of r)o(!0)};f(()=>{r.add(c);const o=u=>{if(u.key===a&&u.newValue==="1"){i=!0;for(const v of r)v(!0)}};return window.addEventListener("storage",o),()=>{r.delete(c),window.removeEventListener("storage",o)}},[]);const l={href:h,target:"_blank",rel:"noopener noreferrer"};return t?m?e("footer",{className:"cm-community-entry"},e("a",l,n?"Community & feedback ↗":"交流与反馈 ↗")):null:m?null:e("aside",{className:"cm-community-notice",role:"status"},e("span",null,n?"The plugin WeChat group is open":"插件交流群已开放"),e("a",l,n?"View QR code ↗":"查看二维码 ↗"),e("button",{type:"button",className:"cm-btn small","aria-label":n?"Dismiss community notice":"关闭交流群提示",onClick:g},"×"))}function x(s){const t=document.createElement("style");return t.textContent=".cm-community-notice{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:10px 12px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-community-notice button{margin-left:auto;flex:none;min-width:28px;min-height:28px}.cm-community-notice a,.cm-community-entry a{color:var(--dsw-alias-state-business-primary,var(--dsw-alias-brand-primary,#4d6bfe));text-decoration:none}.cm-community-notice a:hover,.cm-community-entry a:hover{text-decoration:underline}.cm-community-entry{display:flex;border-top:1px solid var(--dsw-alias-border-l1);padding-top:12px;font-size:12px}.cm-community-notice :focus-visible,.cm-community-entry a:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4d6bfe);outline-offset:3px;border-radius:4px}",document.head.appendChild(t),s.effect(()=>()=>t.remove(),"cost-meter: community styles"),w}return{mount:x}}});
1
+ window.__ModuleLoader__.load({id:"dsh-cost-meter",chunk:"client.community.js",factory:u=>{const p=u("react"),{createElement:e,useState:y,useEffect:f}=p,s="dsh-cost-meter:community-notice-seen",r=new Set;let i=!1;function b(){if(i)return!0;try{return window.localStorage.getItem(s)==="1"}catch{return!1}}function x({locale:a,footer:t=!1}){const[m,c]=y(b),n=a==="en",h="https://github.com/Han-1413141/dsh-cost-meter/blob/master/"+(n?"README.md#community":"README.zh-CN.md#交流与反馈"),g=()=>{i=!0;try{window.localStorage.setItem(s,"1")}catch{}c(!0);for(const o of r)o(!0)};f(()=>{r.add(c);const o=d=>{if(d.key===s&&d.newValue==="1"){i=!0;for(const v of r)v(!0)}};return window.addEventListener("storage",o),()=>{r.delete(c),window.removeEventListener("storage",o)}},[]);const l={href:h,target:"_blank",rel:"noopener noreferrer"};return t?m?e("footer",{className:"cm-community-entry"},e("a",l,n?"Community & feedback ↗":"交流与反馈 ↗")):null:m?null:e("aside",{className:"cm-community-notice",role:"status"},e("span",null,n?"The plugin WeChat group is open":"插件交流群已开放"),e("a",l,n?"View QR code ↗":"查看二维码 ↗"),e("button",{type:"button",className:"cm-btn small","aria-label":n?"Dismiss community notice":"关闭交流群提示",onClick:g},"×"))}function w(a){const t=document.createElement("style");return t.textContent=".cm-community-notice{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:10px 12px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);font-size:12px;color:var(--dsw-alias-label-secondary)}.cm-community-notice button{margin-left:auto;flex:none;min-width:28px;min-height:28px}.cm-community-notice a,.cm-community-entry a{color:var(--dsw-alias-state-business-primary,var(--dsw-alias-brand-primary,#4d6bfe));text-decoration:none}.cm-community-notice a:hover,.cm-community-entry a:hover{text-decoration:underline}.cm-community-entry{display:flex;border-top:1px solid var(--dsw-alias-border-l1);padding-top:12px;font-size:12px}.cm-community-notice :focus-visible,.cm-community-entry a:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4d6bfe);outline-offset:3px;border-radius:4px}",t.textContent+='@media (max-width:1023px){.cm-community-notice{padding:8px 10px;gap:8px}}body[data-dsh-pocket-layout="mobile"] .cm-community-notice{flex-wrap:wrap}',document.head.appendChild(t),a.effect(()=>()=>t.remove(),"cost-meter: community styles"),x}return{mount:w}}});