dsh-notify-tray 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,18 +27,19 @@ A notification + status-bar plugin for DeepSeek Harness (DSH). Works on macOS, W
27
27
 
28
28
  The plugin is published on npm as [`dsh-notify-tray`](https://www.npmjs.com/package/dsh-notify-tray). Installing from npm needs nothing beyond DSH itself — no Git required.
29
29
 
30
+ > **⚠️ To get the latest release, include the version number**, e.g. `dsh-notify-tray@0.1.4` (the latest version is listed on [npm](https://www.npmjs.com/package/dsh-notify-tray)).
31
+ > DSH installs plugins with pnpm, whose supply-chain policy (`minimumReleaseAge`) won't auto-install a release that is still inside its waiting period. With a bare `dsh-notify-tray` you may get an older version (e.g. 0.1.0). If an older version is already installed, remove it first, then install with the version number.
32
+
30
33
  **Option 1 — from inside DSH (recommended)**
31
- Open DSH **Plugins → Add plugin**, type `dsh-notify-tray` into the input box and click **Install**.
34
+ Open DSH **Plugins → Add plugin**, type `dsh-notify-tray@0.1.4` (with the version number) into the input box and click **Install**.
32
35
 
33
36
  **Option 2 — command line**
34
37
 
35
38
  ```sh
36
- # Desktop app (the dsh command bundled with the app)
37
- dsh plugin --profile desktop add dsh-notify-tray
39
+ # Desktop app (the dsh command bundled with the app); include the version to get the latest
40
+ dsh plugin --profile desktop add dsh-notify-tray@0.1.4
38
41
  # Or the web / CLI profile
39
- dsh plugin --profile web add dsh-notify-tray
40
- # Pin a specific version
41
- dsh plugin --profile desktop add dsh-notify-tray@0.1.2
42
+ dsh plugin --profile web add dsh-notify-tray@0.1.4
42
43
  ```
43
44
 
44
45
  **Option 3 — from the Git repository** (latest unreleased code)
@@ -49,9 +50,16 @@ This route **requires Git**; without it you'll see `ERR_PNPM_GIT_RESOLVE_FAILED
49
50
 
50
51
  Restart DSH after installing. The version on the plugin page is the one installed; the latest is listed on [npm](https://www.npmjs.com/package/dsh-notify-tray).
51
52
 
52
- > **Got an older version?** When the official npm registry is unreachable, DSH falls back to the npmmirror registry, which syncs a little later, so a just-published release may not be there yet. Update again in a few minutes, or pin the version: `dsh plugin --profile desktop add dsh-notify-tray@0.1.2`.
53
+ > **Got an older version?** Most often this is pnpm's `minimumReleaseAge` described above: a new release is only auto-installed after a waiting period, and the install message says releases younger than the required age are not installed automatically. Remove the plugin, then install with the version number:
54
+ >
55
+ > ```sh
56
+ > dsh plugin --profile desktop remove dsh-notify-tray
57
+ > dsh plugin --profile desktop add dsh-notify-tray@0.1.4
58
+ > ```
59
+ >
60
+ > Also, when the official npm registry is unreachable, DSH falls back to the npmmirror registry, which syncs a little later, so a just-published release may take a few minutes to appear there.
53
61
 
54
- To update: `dsh plugin --profile desktop update dsh-notify-tray`. To uninstall: `dsh plugin --profile desktop remove dsh-notify-tray`.
62
+ To update: include the version here too — `dsh plugin --profile desktop remove dsh-notify-tray`, then `dsh plugin --profile desktop add dsh-notify-tray@<new version>`. To uninstall: `dsh plugin --profile desktop remove dsh-notify-tray`.
55
63
 
56
64
  ## Configuration
57
65
 
@@ -78,7 +86,7 @@ Every option can be changed under DSH **Plugins → Whale Notify Station → Con
78
86
  | `channel` | `auto` | `auto`: the DSH window shows the notification when one is open, otherwise the OS does |
79
87
  | `suppressWhenFocused` | `true` | Don't notify while you're looking at that session (switch to another app and you will be) |
80
88
  | `sound` | `true` | Play a sound with system notifications (macOS chime, Windows toast sound, Linux where the desktop supports it) |
81
- | `tray` | `true` | Show the status-bar icon (macOS / Linux, takes effect after a restart; ignored on Windows) |
89
+ | `tray` | `true` | Show the status-bar icon (macOS / Linux, takes effect as soon as you save; ignored on Windows). After **Hide status-bar icon** in the tray menu, **Show the status-bar icon again** on the settings page brings it back without restarting DSH |
82
90
  | `titleStyle` | `text` | What to show next to the whale in the macOS menu bar: `text` (Pending 1 / Running 2), `count` (numbers only), `icon` (whale only) |
83
91
  | `showSpendInTitle` | `false` | Append today's spend to the macOS menu-bar label |
84
92
  | `errorHoldMinutes` | `10` | How many minutes the icon stays red / shows the `×` after a task fails (macOS / Linux) |
@@ -87,7 +95,7 @@ Every option can be changed under DSH **Plugins → Whale Notify Station → Con
87
95
 
88
96
  | Option | Default | Description |
89
97
  |---|---|---|
90
- | `spendSource` | `auto` | Use the DeepSeek account balance when available, otherwise estimate from prices |
98
+ | `spendSource` | `auto` | Use the DeepSeek account balance when available, otherwise estimate from prices. In `auto`, while balance drops lag behind the DeepSeek models' estimate (the platform bills with a delay) the estimate is shown until the balance catches up; other providers' models are always added as an estimate |
91
99
  | `currency` | `CNY` | Display currency |
92
100
  | `balancePollMinutes` | `5` | How often (minutes) to refresh the DeepSeek account balance |
93
101
  | `priceSource` | `auto` | Which price to estimate with: `auto` (price table → custom price → DSH's built-in model catalog → plugin's built-in prices), `catalog`, `custom` |
@@ -96,7 +104,7 @@ Every option can be changed under DSH **Plugins → Whale Notify Station → Con
96
104
  | `exchangeRate` | `7.2` | 1 USD = ? CNY; catalog prices are in USD and converted when displaying CNY |
97
105
  | `prices` | `{}` | Per-model price table, highest priority |
98
106
 
99
- The **Current API price** section shows the model you're using (provider / model) and its catalog price. DSH's pi-ai adapter ships a model catalog (Claude, GPT, Gemini, Grok, Groq, Kimi, GLM, MiMo, MiniMax, OpenCode Go, DeepSeek, …); the plugin reads it directly and falls back to its built-in prices or your custom price when a model is missing. A one-click **Copy catalog price into custom price** lets you tweak from the catalog value.
107
+ The **Current API price** section shows the model you're using (provider / model) and its catalog price. DSH's pi-ai adapter ships a model catalog (Claude, GPT, Gemini, Grok, Groq, Kimi, GLM, MiMo, MiniMax, OpenCode Go, DeepSeek, …); the plugin reads it directly and falls back to its built-in prices or your custom price when a model is missing. It is found automatically for the desktop app and for `dsh web` (including global npm installs such as `~/.npm-global`); if the settings page says it wasn't found, set the `DSH_NOTIFY_TRAY_PI_AI` environment variable to the DSH install directory (e.g. `~/.npm-global/lib/node_modules/@deepseek-ai/dsh`) and restart. A one-click **Copy catalog price into custom price** lets you tweak from the catalog value.
100
108
 
101
109
  ### Plans
102
110
 
@@ -133,7 +141,7 @@ Anything that can't be fetched can be typed in by hand; empty fields are simply
133
141
  ## Notes
134
142
 
135
143
  - **When notifications fire** — a task that runs to completion counts as *completed*; an error, hitting the token limit or being blocked counts as *failed*; stopping a task yourself doesn't notify. For `ask_user_question`, questions with options and plan approvals count as *needs a choice*, questions without options as *needs input*; tool approvals count as *needs approval*. Only top-level sessions are tracked — sub-agents don't get their own notifications.
136
- - **How spend is computed** — when signed in with a DeepSeek account, today's spend is accumulated from drops in the account balance (top-ups don't count as negative spend; subject to the platform's billing delay). In parallel, it's estimated from each `provider/model` route's tokens × unit price (price sources described under `priceSource` above); the **Today's usage** submenu breaks it down per model. The ledger lives in `~/.dsh/storages/dsh-notify-tray/ledger.json` and keeps 31 days.
144
+ - **How spend is computed** — when signed in with a DeepSeek account, today's spend is accumulated from drops in the account balance (top-ups don't count as negative spend; the platform bills with a delay, so in `auto` the estimate stands in until the balance catches up). In parallel, it's estimated from each `provider/model` route's tokens × unit price (price sources described under `priceSource` above); the **Today's usage** submenu breaks it down per model. The ledger lives in `~/.dsh/storages/dsh-notify-tray/ledger.json` and keeps 31 days.
137
145
  - **Clicking a notification / the status-bar icon / "Open DeepSeek Harness" in the menu** — brings up the desktop app when there is one, otherwise (`dsh web`) opens the web UI in the browser. Browser notifications require granting notification permission first.
138
146
 
139
147
  ## Development
@@ -162,7 +170,7 @@ Requires Node ≥ 20. Linux uses [`dbus-next`](https://www.npmjs.com/package/dbu
162
170
 
163
171
  ## Known limitations
164
172
 
165
- - Verified on macOS and Windows only; Linux has not been fully verified yet.
173
+ - Verified on macOS, Windows and Linux (Linux verified under the web profile: notifications and the system tray).
166
174
 
167
175
  ## License
168
176
 
package/README.zh-CN.md CHANGED
@@ -27,18 +27,19 @@ DeepSeek Harness(DSH)的通知 + 状态栏插件,支持 macOS、Windows、
27
27
 
28
28
  插件已发布到 npm:[`dsh-notify-tray`](https://www.npmjs.com/package/dsh-notify-tray)。从 npm 安装只需要 DSH 本身,**不需要装 Git**。
29
29
 
30
+ > **⚠️ 想装最新版,请带上版本号**,例如 `dsh-notify-tray@0.1.4`(最新版本号见 [npm](https://www.npmjs.com/package/dsh-notify-tray))。
31
+ > DSH 用 pnpm 安装插件,pnpm 的供应链安全策略(`minimumReleaseAge`)不会自动安装刚发布、还没过观察期的版本,只写 `dsh-notify-tray` 时会退回装一个旧版本(例如 0.1.0)。已经装了旧版的,先卸载,再带版本号安装。
32
+
30
33
  **方式一:在 DSH 里装(推荐)**
31
- 打开 DSH「插件 → 添加插件」,输入框里填 `dsh-notify-tray`,点「安装」。
34
+ 打开 DSH「插件 → 添加插件」,输入框里填 `dsh-notify-tray@0.1.4`(带上版本号),点「安装」。
32
35
 
33
36
  **方式二:命令行**
34
37
 
35
38
  ```sh
36
- # 桌面版(App 内置的 dsh 命令)
37
- dsh plugin --profile desktop add dsh-notify-tray
39
+ # 桌面版(App 内置的 dsh 命令),带上版本号才能装到最新版
40
+ dsh plugin --profile desktop add dsh-notify-tray@0.1.4
38
41
  # 或者 Web / 命令行 profile
39
- dsh plugin --profile web add dsh-notify-tray
40
- # 指定版本
41
- dsh plugin --profile desktop add dsh-notify-tray@0.1.2
42
+ dsh plugin --profile web add dsh-notify-tray@0.1.4
42
43
  ```
43
44
 
44
45
  **方式三:从 Git 仓库装**(想用还没发版的最新代码时)
@@ -49,9 +50,16 @@ dsh plugin --profile desktop add dsh-notify-tray@0.1.2
49
50
 
50
51
  装好后重启 DSH。插件页上显示的版本号就是装上的版本,最新版见 [npm](https://www.npmjs.com/package/dsh-notify-tray)。
51
52
 
52
- > **装到的不是最新版?** 官方 npm 源连不上时,DSH 会退到 npmmirror(淘宝镜像)去装,镜像比官方源晚一点同步,刚发的新版可能还没到。等几分钟再更新,或指定版本 `dsh plugin --profile desktop add dsh-notify-tray@0.1.2`。
53
+ > **装到的不是最新版?** 最常见的原因是上面说的 pnpm `minimumReleaseAge`:新版本发布后要过一段观察期才会被自动安装,安装提示里会写「发布时间未满规定时长的版本不会被自动安装」。解决办法是先卸载,再带版本号安装:
54
+ >
55
+ > ```sh
56
+ > dsh plugin --profile desktop remove dsh-notify-tray
57
+ > dsh plugin --profile desktop add dsh-notify-tray@0.1.4
58
+ > ```
59
+ >
60
+ > 另外,官方 npm 源连不上时 DSH 会退到 npmmirror(淘宝镜像),镜像比官方源晚一点同步,刚发的新版可能要等几分钟才到。
53
61
 
54
- 更新:`dsh plugin --profile desktop update dsh-notify-tray`。卸载:`dsh plugin --profile desktop remove dsh-notify-tray`。
62
+ 更新:同样建议带版本号,先 `dsh plugin --profile desktop remove dsh-notify-tray`,再 `dsh plugin --profile desktop add dsh-notify-tray@<新版本号>`。卸载:`dsh plugin --profile desktop remove dsh-notify-tray`。
55
63
 
56
64
  ## 设置
57
65
 
@@ -78,7 +86,7 @@ dsh plugin --profile desktop add dsh-notify-tray@0.1.2
78
86
  | `channel` | `auto` | `auto`:有 DSH 窗口时由窗口弹,没有窗口时由系统弹 |
79
87
  | `suppressWhenFocused` | `true` | 你正在看这个会话时不弹通知(切到别的应用去就有了) |
80
88
  | `sound` | `true` | 系统通知带提示音(macOS「叮」一声、Windows 通知音、Linux 视桌面环境而定) |
81
- | `tray` | `true` | 是否显示状态栏图标(macOS / Linux,修改后重启生效;Windows 忽略) |
89
+ | `tray` | `true` | 是否显示状态栏图标(macOS / Linux,保存后立即生效;Windows 忽略)。在状态栏菜单里点「隐藏状态栏图标」后,可在插件设置页点「重新显示状态栏图标」把它找回来,不用重启 DSH |
82
90
  | `titleStyle` | `text` | macOS 菜单栏鲸鱼旁边显示什么:`text`(待处理 1 / 运行中 2)、`count`(只有数字)、`icon`(只有鲸鱼) |
83
91
  | `showSpendInTitle` | `false` | macOS 菜单栏文字里附带今日花费 |
84
92
  | `errorHoldMinutes` | `10` | 任务失败后图标保持红色 / 挂「×」的分钟数(macOS / Linux) |
@@ -87,7 +95,7 @@ dsh plugin --profile desktop add dsh-notify-tray@0.1.2
87
95
 
88
96
  | 选项 | 默认值 | 说明 |
89
97
  |---|---|---|
90
- | `spendSource` | `auto` | 有 DeepSeek 账户余额时用余额扣费,否则按价格估算 |
98
+ | `spendSource` | `auto` | 有 DeepSeek 账户余额时用余额扣费,否则按价格估算。`auto` 下余额扣费落后于 DeepSeek 模型的估算时(平台扣费有延迟),先按估算显示,余额追上后再改回余额;其它平台模型的花费始终按估算加上 |
91
99
  | `currency` | `CNY` | 显示币种 |
92
100
  | `balancePollMinutes` | `5` | DeepSeek 账户余额刷新间隔(分钟) |
93
101
  | `priceSource` | `auto` | 估算用哪个价:`auto`(价格表 → 自定义价 → DSH 自带的模型目录价 → 插件内置价)、`catalog`、`custom` |
@@ -96,7 +104,7 @@ dsh plugin --profile desktop add dsh-notify-tray@0.1.2
96
104
  | `exchangeRate` | `7.2` | 1 美元 = ? 人民币;目录价是美元,显示人民币时按它换算 |
97
105
  | `prices` | `{}` | 按模型的价格表,优先级最高 |
98
106
 
99
- 「当前 API 价格」区域会显示你正在用的模型(provider / model)和它的目录价:DSH 的 pi-ai 适配器自带一份模型目录(Claude、GPT、Gemini、Grok、Groq、Kimi、GLM、MiMo、MiniMax、OpenCode Go、DeepSeek 等),插件直接读它,拿不到的再用内置价或你填的自定义价。一键「把目录价填进自定义价」可以在目录价的基础上改。
107
+ 「当前 API 价格」区域会显示你正在用的模型(provider / model)和它的目录价:DSH 的 pi-ai 适配器自带一份模型目录(Claude、GPT、Gemini、Grok、Groq、Kimi、GLM、MiMo、MiniMax、OpenCode Go、DeepSeek 等),插件直接读它,拿不到的再用内置价或你填的自定义价。桌面版和 `dsh web`(含 `~/.npm-global` 等全局 npm 安装)都会自动找到这份目录;如果设置页提示没找到,可以设置环境变量 `DSH_NOTIFY_TRAY_PI_AI` 指向 DSH 的安装目录(例如 `~/.npm-global/lib/node_modules/@deepseek-ai/dsh`)后重启。一键「把目录价填进自定义价」可以在目录价的基础上改。
100
108
 
101
109
  ### 套餐
102
110
 
@@ -133,9 +141,9 @@ dsh plugin --profile desktop add dsh-notify-tray@0.1.2
133
141
  ## 说明
134
142
 
135
143
  - **通知的触发时机**:任务跑完算「完成」;出错、超出 Token 上限、被拦截算「失败」;你自己点停止不弹通知。调用 `ask_user_question` 时,带选项的问题和计划审批算「需要选择」,不带选项的算「需要输入」;工具审批算「需要批准」。只跟踪顶层会话,子 agent 不单独弹通知。
136
- - **花费怎么算**:用 DeepSeek 账户登录时,按账户余额的下降累计当天花费(充值不算负花费,会受平台扣费延迟影响);同时按当天各「provider/model」的 Token 乘以单价估算(单价来源见上面的 `priceSource`),「今日用量」子菜单里按模型分行显示。账本存在 `~/.dsh/storages/dsh-notify-tray/ledger.json`,保留 31 天。
144
+ - **花费怎么算**:用 DeepSeek 账户登录时,按账户余额的下降累计当天花费(充值不算负花费;平台扣费有延迟,`auto` 下余额没跟上时先按估算显示);同时按当天各「provider/model」的 Token 乘以单价估算(单价来源见上面的 `priceSource`),「今日用量」子菜单里按模型分行显示。账本存在 `~/.dsh/storages/dsh-notify-tray/ledger.json`,保留 31 天。
137
145
  - **点击通知 / 状态栏图标 / 菜单里的「打开 DeepSeek Harness」**:有桌面版时唤起桌面版,没有时(`dsh web`)在浏览器里打开 Web 界面。浏览器里的通知需要先允许通知权限。
138
146
 
139
147
  ## 已知限制
140
148
 
141
- - 只在 macOS 和 Windows 上完成了验证,Linux 上还没有完成验证。
149
+ - macOS、Windows、Linux 均已完成验证(Linux 在 web profile 下验证了通知与系统托盘)。
package/lib/client.js CHANGED
@@ -63,6 +63,7 @@ window.__ModuleLoader__.load({
63
63
  const PACKAGE_KEY = 'dsh-notify-tray'
64
64
  const CATALOG_ROUTE = 'notify-tray/catalog'
65
65
  const REFRESH_ROUTE = 'notify-tray/refresh'
66
+ const TRAY_ROUTE = 'notify-tray/tray'
66
67
  /** How often the page re-reads the host's live state (current model, plan quota). */
67
68
  const LIVE_MS = 5000
68
69
 
@@ -133,8 +134,13 @@ window.__ModuleLoader__.load({
133
134
  soundHint_linux: '系统通知的提示音(要桌面环境支持)。',
134
135
  sectionTray: '状态栏里的小鲸鱼',
135
136
  tray: '显示状态栏小鲸鱼',
136
- trayHint: '改了要重启 DSH 才生效。',
137
- trayHint_linux: '显示在系统托盘里(UOS / Deepin / 麒麟 / KDE 自带;GNOME 要装 AppIndicator 扩展)。改了要重启 DSH 才生效。',
137
+ trayHint: '保存后立即生效。',
138
+ trayHint_linux: '显示在系统托盘里(UOS / Deepin / 麒麟 / KDE 自带;GNOME 要装 AppIndicator 扩展)。保存后立即生效。',
139
+ trayHiddenNote: '状态栏图标已从它的菜单里隐藏。',
140
+ trayShowAgain: '重新显示状态栏图标',
141
+ trayShowing: '正在显示…',
142
+ trayFailedNote: '状态栏图标没能启动(没有托盘宿主或 D-Bus?),只保留通知。',
143
+ trayRetry: '重试',
138
144
  titleStyle: '鲸鱼旁边显示什么',
139
145
  titleText: '文字',
140
146
  titleCount: '只有数字',
@@ -164,7 +170,7 @@ window.__ModuleLoader__.load({
164
170
  effectivePrice: '实际按',
165
171
  perMillion: '每百万 token · 输入 / 缓存命中 / 输出',
166
172
  noListedPrice: '目录里没有这个模型的价格,请在下面填自定义价。',
167
- catalogOff: 'DSH 自带的模型目录没找到,只有插件内置价可用。',
173
+ catalogOff: 'DSH 自带的模型目录没找到,只有插件内置价可用。可设置环境变量 DSH_NOTIFY_TRAY_PI_AI 指向 DSH 的安装目录后重启。',
168
174
  fillCustom: '把目录价填进自定义价',
169
175
  priceSource: '估算用哪个价',
170
176
  priceAuto: '自动',
@@ -275,8 +281,13 @@ window.__ModuleLoader__.load({
275
281
  soundHint_linux: 'The notification sound, where the desktop supports one.',
276
282
  sectionTray: 'The whale in the status bar',
277
283
  tray: 'Show the status-bar whale',
278
- trayHint: 'Takes effect after restarting DSH.',
279
- trayHint_linux: 'Shown in the system tray (built into UOS / Deepin / Kylin / KDE; GNOME needs the AppIndicator extension). Takes effect after restarting DSH.',
284
+ trayHint: 'Takes effect as soon as you save.',
285
+ trayHint_linux: 'Shown in the system tray (built into UOS / Deepin / Kylin / KDE; GNOME needs the AppIndicator extension). Takes effect as soon as you save.',
286
+ trayHiddenNote: 'The status-bar icon was hidden from its own menu.',
287
+ trayShowAgain: 'Show the status-bar icon again',
288
+ trayShowing: 'Showing…',
289
+ trayFailedNote: 'The status-bar icon could not start (no tray host or D-Bus?); notifications still work.',
290
+ trayRetry: 'Retry',
280
291
  titleStyle: 'Text beside the whale',
281
292
  titleText: 'Words',
282
293
  titleCount: 'Count only',
@@ -306,7 +317,7 @@ window.__ModuleLoader__.load({
306
317
  effectivePrice: 'Effective',
307
318
  perMillion: 'per million tokens · input / cache hit / output',
308
319
  noListedPrice: 'No catalog price for this model; enter a custom price below.',
309
- catalogOff: 'DSH\'s bundled model catalog was not found; only the plugin\'s built-in prices apply.',
320
+ catalogOff: 'DSH\'s bundled model catalog was not found; only the plugin\'s built-in prices apply. Point the DSH_NOTIFY_TRAY_PI_AI environment variable at the DSH install directory and restart.',
310
321
  fillCustom: 'Copy listed price into custom price',
311
322
  priceSource: 'Which price to use',
312
323
  priceAuto: 'Auto',
@@ -621,6 +632,20 @@ window.__ModuleLoader__.load({
621
632
  return h('div', { style: S.card }, rows)
622
633
  }
623
634
 
635
+ /** Brings back a status-bar icon hidden from its own menu (or one that failed to start). */
636
+ function TrayStatus({ t, state }) {
637
+ const tray = state && state.tray
638
+ const [busy, setBusy] = React.useState(false)
639
+ if (!tray || !tray.supported || !tray.enabled || tray.shown || !(tray.hidden || tray.failed)) return null
640
+ const show = () => {
641
+ setBusy(true)
642
+ fetchJson(TRAY_ROUTE, { method: 'POST' }).then(() => loadState()).catch(() => {}).then(() => setBusy(false))
643
+ }
644
+ return h('div', { style: S.card },
645
+ h('div', { style: tray.failed && !tray.hidden ? S.error : S.muted }, t(tray.hidden ? 'trayHiddenNote' : 'trayFailedNote')),
646
+ h('div', { style: { marginTop: 8 } }, h('button', { type: 'button', style: S.button, disabled: busy, onClick: show }, busy ? t('trayShowing') : t(tray.hidden ? 'trayShowAgain' : 'trayRetry'))))
647
+ }
648
+
624
649
  function PlanSection({ t, f, common, state, catalog }) {
625
650
  const { edit, resetField, disabled } = common
626
651
  const providers = catalog?.providers ?? []
@@ -729,6 +754,7 @@ window.__ModuleLoader__.load({
729
754
  toggle('sound')),
730
755
  features.tray ? h(Section, { title: t('sectionTray') },
731
756
  toggle('tray'),
757
+ h(TrayStatus, { t, state: liveData.state }),
732
758
  features.menuBarTitle ? h(ChoiceRow, { name: 'titleStyle', field: f.titleStyle, hint: 'titleStyleHint', ...common, options: [['text', 'titleText'], ['count', 'titleCount'], ['icon', 'titleIcon']] }) : null,
733
759
  features.menuBarTitle ? toggle('showSpendInTitle') : null,
734
760
  h('div', { style: { marginTop: 12 } }, h(NumberField, { name: 'errorHoldMinutes', field: f.errorHoldMinutes, ...common }))) : null,
package/lib/format.js CHANGED
@@ -35,7 +35,29 @@ const KIND_ICON = {
35
35
  failed: 'xmark.circle',
36
36
  aborted: 'stop.circle',
37
37
  }
38
- const LABEL_MAX = 56
38
+ const LABEL_MAX = 44
39
+ /** Submenu rows: kept short so a submenu opened toward the screen edge stays readable. */
40
+ const SUB_MAX = 36
41
+
42
+ /** Long text as several short menu rows, broken at its own separators where it can be. */
43
+ export function wrapText(text, max = SUB_MAX) {
44
+ const pieces = String(text).split(/(?<=[;;,,。])|(?= · )/u).map(p => p.replace(/^ · /u, ''))
45
+ const rows = []
46
+ let current = ''
47
+ for (const piece of pieces) {
48
+ if (current && current.length + piece.length > max) {
49
+ rows.push(current)
50
+ current = ''
51
+ }
52
+ current += piece
53
+ while (current.length > max) {
54
+ rows.push(current.slice(0, max))
55
+ current = current.slice(max)
56
+ }
57
+ }
58
+ if (current.trim()) rows.push(current)
59
+ return rows.map(row => row.trim()).filter(Boolean)
60
+ }
39
61
 
40
62
  export function money(value, currency) {
41
63
  if (value === undefined || value === null) return undefined
@@ -74,18 +96,37 @@ function resetText(value) {
74
96
  return `${sameDay ? '' : `${d.getMonth() + 1}/${d.getDate()} `}${clock(ms)}`
75
97
  }
76
98
 
77
- /** Pick which spend figure to show: real balance drops when available, else the price-table estimate. */
99
+ /**
100
+ * Pick which spend figure to show: real balance drops when available, else the
101
+ * price-table estimate.
102
+ *
103
+ * In `auto` the balance only stands for what it actually pays for (DeepSeek
104
+ * routes), and the platform books charges a while after a turn ends: when the
105
+ * DeepSeek routes' estimate is ahead of the balance drops, the estimate is
106
+ * shown until the balance catches up. Other providers' routes are always
107
+ * added on as an estimate.
108
+ */
78
109
  export function spendOf(usage, source) {
79
- const fromBalance = usage.balanceSpend !== undefined || usage.balance !== undefined
80
- ? { value: usage.balanceSpend ?? 0, label: '余额扣费' }
81
- : undefined
110
+ const hasBalance = usage.balanceSpend !== undefined || usage.balance !== undefined
111
+ const fromBalance = hasBalance ? { value: usage.balanceSpend ?? 0, label: '余额扣费' } : undefined
82
112
  const sources = (usage.estimateSources ?? []).map(key => SOURCE_LABEL[key] ?? key)
83
- const fromEstimate = usage.estimate !== undefined ? { value: usage.estimate, label: sources.length ? `估算 · ${sources.join('+')}` : '估算' } : undefined
113
+ const estimateLabel = sources.length ? `估算 · ${sources.join('+')}` : '估算'
114
+ const fromEstimate = usage.estimate !== undefined ? { value: usage.estimate, label: estimateLabel } : undefined
84
115
  if (source === 'balance') return fromBalance
85
116
  if (source === 'estimate') return fromEstimate
86
- return fromBalance ?? fromEstimate
117
+ if (!fromBalance) return fromEstimate
118
+ if (!fromEstimate) return fromBalance
119
+ const deepseek = usage.estimateDeepseek ?? 0
120
+ const others = Math.max(0, round4(usage.estimate - deepseek))
121
+ const lagging = deepseek > fromBalance.value
122
+ const value = round4((lagging ? deepseek : fromBalance.value) + others)
123
+ const parts = [lagging ? '余额未到账,暂按估算' : '余额扣费']
124
+ if (others > 0) parts.push('含其它平台估算')
125
+ return { value, label: parts.join(','), mixed: lagging || others > 0 }
87
126
  }
88
127
 
128
+ const round4 = value => Math.round(value * 10000) / 10000
129
+
89
130
  /** How long the whale celebrates after a finish before going back to idle. */
90
131
  export const DONE_HOLD_MS = 6000
91
132
 
@@ -167,18 +208,29 @@ export function buildView(tasks, usage, config, now = Date.now(), plan = undefin
167
208
  const usageRows = []
168
209
  usageRows.push({ id: 'info', enabled: false, icon: 'checkmark.circle', label: `完成 ${today.completed} · 失败 ${today.failed}${today.aborted ? ` · 停止 ${today.aborted}` : ''}` })
169
210
  if (spend) usageRows.push({ id: 'info', enabled: false, icon: 'yensign.circle', label: `花费 ${spendText}(${spend.label})` })
170
- if (usage.estimate !== undefined && spend?.label !== undefined && !spend.label.startsWith('估算')) {
211
+ if (usage.estimate !== undefined && spend?.label !== undefined && !spend.label.startsWith('估算') && spend.value !== usage.estimate) {
171
212
  usageRows.push({ id: 'info', enabled: false, icon: 'function', label: `按价格估算 ${money(usage.estimate, usage.currency)}` })
172
213
  }
214
+ if (spend?.mixed || (spend && usage.balanceSpend !== undefined && spend.label.startsWith('估算'))) {
215
+ usageRows.push({ id: 'info', enabled: false, icon: 'creditcard', label: `余额已扣 ${money(usage.balanceSpend ?? 0, usage.currency)}` })
216
+ }
173
217
  usageRows.push({ id: 'info', enabled: false, icon: 'number', label: `Token ${compactTokens(usage.tokens.total)}(输出 ${compactTokens(usage.tokens.output)})` })
174
- // One row per provider/model route used today, biggest first.
175
- for (const row of (usage.byModel ?? []).slice(0, 6)) {
176
- const bits = [row.key === 'unknown' ? '未知模型' : row.key, `${compactTokens(row.tokens.input + row.tokens.cacheRead + row.tokens.cacheWrite + row.tokens.output)} token`]
177
- if (row.cost !== undefined) bits.push(`${money(row.cost, usage.currency)}(${SOURCE_LABEL[row.source] ?? row.source})`)
178
- usageRows.push({ id: 'info', enabled: false, icon: 'cpu', label: trim(bits.join(' · '), 72) })
218
+ // One row per provider/model route used today, biggest first. Rows stay
219
+ // short: Windows / Linux trays open submenus beside the panel and long rows
220
+ // run off the screen edge, so the provider only shows when two routes share
221
+ // a model id, and the route in use is split into model + provider rows.
222
+ const routes = (usage.byModel ?? []).slice(0, 6)
223
+ const modelCount = {}
224
+ for (const row of routes) modelCount[row.model] = (modelCount[row.model] ?? 0) + 1
225
+ for (const row of routes) {
226
+ const name = row.key === 'unknown' ? '未知模型' : modelCount[row.model] > 1 ? row.key : row.model
227
+ const bits = [name, compactTokens(row.tokens.input + row.tokens.cacheRead + row.tokens.cacheWrite + row.tokens.output)]
228
+ if (row.cost !== undefined) bits.push(`${money(row.cost, usage.currency)} ${SOURCE_LABEL[row.source] ?? row.source}`)
229
+ usageRows.push({ id: 'info', enabled: false, icon: 'cpu', label: trim(bits.join(' · '), SUB_MAX) })
179
230
  }
180
231
  if (usage.route?.model) {
181
- usageRows.push({ id: 'info', enabled: false, icon: 'point.3.connected.trianglepath.dotted', label: trim(`当前模型 ${usage.route.provider ? `${usage.route.provider}/` : ''}${usage.route.model}`, 72) })
232
+ usageRows.push({ id: 'info', enabled: false, icon: 'point.3.connected.trianglepath.dotted', label: trim(`当前模型 ${usage.route.model}`, SUB_MAX) })
233
+ if (usage.route.provider) usageRows.push({ id: 'info', enabled: false, icon: 'network', label: trim(`通道 ${usage.route.provider}`, SUB_MAX) })
182
234
  }
183
235
  const todayLabel = spendText ? `今日用量 · ${spendText}` : '今日用量'
184
236
  menu.push({ id: 'today', icon: 'chart.bar', label: todayLabel, children: usageRows })
@@ -192,10 +244,12 @@ export function buildView(tasks, usage, config, now = Date.now(), plan = undefin
192
244
  if (plan.balance !== undefined) planRows.push({ id: 'info', enabled: false, icon: 'wallet.pass', label: `套餐余额 ${money(plan.balance, plan.balanceCurrency)}` })
193
245
  if (plan.remaining !== undefined) planRows.push({ id: 'info', enabled: false, icon: 'gauge.with.dots.needle.33percent', label: `剩余额度 ${plan.remaining}${plan.remainingSource === 'manual' ? '(手填)' : ''}` })
194
246
  if (plan.resetAt) planRows.push({ id: 'info', enabled: false, icon: 'arrow.clockwise.circle', label: `重置 ${resetText(plan.resetAt)}` })
195
- for (const line of plan.lines.slice(0, 4)) planRows.push({ id: 'info', enabled: false, icon: 'line.3.horizontal.decrease.circle', label: trim(line, 72) })
196
- if (plan.quotaText) planRows.push({ id: 'info', enabled: false, icon: 'text.bubble', label: trim(plan.quotaText, 72) })
247
+ const textRows = (text, icon) => wrapText(text).slice(0, 4).forEach(label => planRows.push({ id: 'info', enabled: false, icon, label }))
248
+ for (const line of plan.lines.slice(0, 4)) textRows(line, 'line.3.horizontal.decrease.circle')
249
+ if (plan.quotaText) textRows(plan.quotaText, 'text.bubble')
197
250
  if (plan.fetch) {
198
- planRows.push({ id: 'info', enabled: false, icon: plan.fetch.ok ? 'checkmark.icloud' : 'exclamationmark.icloud', label: plan.fetch.ok ? `额度更新于 ${clock(plan.fetch.at)}` : trim(`获取失败:${plan.fetch.error}`, 72) })
251
+ if (plan.fetch.ok) planRows.push({ id: 'info', enabled: false, icon: 'checkmark.icloud', label: `额度更新于 ${clock(plan.fetch.at)}` })
252
+ else textRows(`获取失败:${plan.fetch.error}`, 'exclamationmark.icloud')
199
253
  } else if (plan.canFetch && !plan.apiKeyEnv) {
200
254
  planRows.push({ id: 'info', enabled: false, icon: 'key', label: '填入 API Key 引用后可自动获取额度' })
201
255
  }
@@ -209,7 +263,7 @@ export function buildView(tasks, usage, config, now = Date.now(), plan = undefin
209
263
  const rows = tasks.recent.map(item => ({
210
264
  id: `open:${item.sessionId}`,
211
265
  icon: KIND_ICON[item.kind],
212
- label: trim(`${clock(item.at)} ${KIND_LABEL[item.kind]} · ${item.title}`),
266
+ label: trim(`${clock(item.at)} ${KIND_LABEL[item.kind]} · ${item.title}`, SUB_MAX),
213
267
  }))
214
268
  menu.push({ id: 'recent', icon: 'clock.arrow.circlepath', label: '最近结束', children: rows })
215
269
  }
package/lib/icon.js CHANGED
@@ -1,13 +1,15 @@
1
1
  /**
2
2
  * Software rasterizer for the Linux tray icon: the whale from lib/whale.js
3
3
  * filled with the state colour, emitted as StatusNotifierItem IconPixmap data
4
- * (ARGB32, network byte order). No image libraries needed.
4
+ * (ARGB32, network byte order), plus RGBA / PNG for the notification icon.
5
+ * No image libraries needed.
5
6
  *
6
7
  * Polygons are the flattened bezier outlines, filled by scanline with the
7
8
  * nonzero winding rule at 4×4 supersampling, so the eye and cap band holes
8
9
  * come out and edges stay smooth. It runs on the host's main thread, so it
9
10
  * has to be quick: a 48 px frame takes about a millisecond.
10
11
  */
12
+ import { deflateSync } from 'node:zlib'
11
13
  import { BOUNDS, STATE_RGB, flatten, whalePaths } from './whale.js'
12
14
 
13
15
  export { STATE_RGB }
@@ -96,3 +98,62 @@ export function asciiIcon(size, state, frame = 0) {
96
98
  }
97
99
  return rows.join('\n')
98
100
  }
101
+
102
+ /** RGBA pixels (straight alpha, row-major), the layout freedesktop's `image-data` hint wants. */
103
+ export function rgbaIcon(size, state, frame = 0) {
104
+ const argb = renderIcon(size, state, frame)
105
+ const out = Buffer.alloc(argb.length)
106
+ for (let p = 0; p < argb.length; p += 4) {
107
+ out[p] = argb[p + 1]
108
+ out[p + 1] = argb[p + 2]
109
+ out[p + 2] = argb[p + 3]
110
+ out[p + 3] = argb[p]
111
+ }
112
+ return out
113
+ }
114
+
115
+ const CRC_TABLE = (() => {
116
+ const table = new Uint32Array(256)
117
+ for (let n = 0; n < 256; n += 1) {
118
+ let c = n
119
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
120
+ table[n] = c >>> 0
121
+ }
122
+ return table
123
+ })()
124
+
125
+ function crc32(buffer) {
126
+ let c = 0xffffffff
127
+ for (const byte of buffer) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8)
128
+ return (c ^ 0xffffffff) >>> 0
129
+ }
130
+
131
+ function chunk(type, data) {
132
+ const head = Buffer.alloc(8)
133
+ head.writeUInt32BE(data.length, 0)
134
+ head.write(type, 4, 'ascii')
135
+ const crc = Buffer.alloc(4)
136
+ crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])), 0)
137
+ return Buffer.concat([head, data, crc])
138
+ }
139
+
140
+ /** The whale as a PNG file's bytes (for notification servers that only take an icon path). */
141
+ export function pngIcon(size, state, frame = 0) {
142
+ const rgba = rgbaIcon(size, state, frame)
143
+ const raw = Buffer.alloc((size * 4 + 1) * size)
144
+ for (let y = 0; y < size; y += 1) {
145
+ raw[y * (size * 4 + 1)] = 0 // filter: none
146
+ rgba.copy(raw, y * (size * 4 + 1) + 1, y * size * 4, (y + 1) * size * 4)
147
+ }
148
+ const ihdr = Buffer.alloc(13)
149
+ ihdr.writeUInt32BE(size, 0)
150
+ ihdr.writeUInt32BE(size, 4)
151
+ ihdr[8] = 8 // bit depth
152
+ ihdr[9] = 6 // RGBA
153
+ return Buffer.concat([
154
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
155
+ chunk('IHDR', ihdr),
156
+ chunk('IDAT', deflateSync(raw)),
157
+ chunk('IEND', Buffer.alloc(0)),
158
+ ])
159
+ }
package/lib/index.js CHANGED
@@ -11,7 +11,7 @@
11
11
  * polls the provider's quota endpoint when it has one and an API key.
12
12
  * - Drives a status-bar icon on macOS (menu bar) and Linux (StatusNotifierItem).
13
13
  * Windows has no status bar of the kind: there the plugin only notifies.
14
- * - Serves `GET notify-tray/state` (+ `/catalog`, `POST /refresh`) to the
14
+ * - Serves `GET notify-tray/state` (+ `/catalog`, `POST /refresh`, `POST /tray`) to the
15
15
  * browser half, which shows native notifications from the DSH window and
16
16
  * renders the settings page; when no window is polling, the host falls
17
17
  * back to OS notifications itself.
@@ -37,12 +37,15 @@ export const inject = ['agents']
37
37
  const STATE_PATH = '/notify-tray/state'
38
38
  const CATALOG_PATH = '/notify-tray/catalog'
39
39
  const REFRESH_PATH = '/notify-tray/refresh'
40
+ const TRAY_PATH = '/notify-tray/tray'
40
41
  /** Harness version sent as account client metadata (what the built-in settings page sends). */
41
42
  const DSH_VERSION = '0.2.1-rc.2'
42
43
  /** A window that polled within this window counts as "listening". */
43
44
  const CLIENT_FRESH_MS = 8000
44
45
  /** Platforms with a status bar the whale can live in. */
45
46
  export const TRAY_PLATFORMS = new Set(['darwin', 'linux', 'freebsd'])
47
+ /** The whale's colour on a notification of each kind. */
48
+ const EVENT_STATE = { completed: 'done', failed: 'error', approval: 'attention', choice: 'attention', input: 'attention' }
46
49
  const EVENT_SWITCH = {
47
50
  completed: 'notifyCompleted',
48
51
  failed: 'notifyFailed',
@@ -74,7 +77,7 @@ export const Config = z.object({
74
77
  ]).default('auto').description('通知通道').volatile(),
75
78
  suppressWhenFocused: z.boolean().default(true).description('正在看这个会话时不弹').volatile(),
76
79
  sound: z.boolean().default(true).description('系统通知带提示音').volatile(),
77
- tray: z.boolean().default(true).description('显示状态栏图标(macOS / Linux,修改后重启 DSH 生效;Windows 没有状态栏,忽略此项)').volatile(),
80
+ tray: z.boolean().default(true).description('显示状态栏图标(macOS / Linux,立即生效;Windows 没有状态栏,忽略此项)').volatile(),
78
81
  titleStyle: z.union([
79
82
  z.const('text').description('文字:待处理 1 / 运行中 2'),
80
83
  z.const('count').description('只显示数字'),
@@ -209,9 +212,9 @@ export function apply(ctx, config) {
209
212
  if (action === 'refresh-quota') return void pollQuota(true)
210
213
  if (action.startsWith('url:')) return void openUrl(action.slice(4))
211
214
  if (action === 'hide-tray') {
212
- const t = tray
213
- tray = undefined
214
- t?.stop()
215
+ // Hidden for this run only: the settings page offers to bring it back.
216
+ trayHidden = true
217
+ syncTray()
215
218
  return
216
219
  }
217
220
  if (action.startsWith('open:')) {
@@ -222,25 +225,66 @@ export function apply(ctx, config) {
222
225
 
223
226
  // Windows has no status bar to live in (and the desktop app keeps a tray
224
227
  // icon of its own): there the plugin is notifications only.
225
- const trayWanted = cfg.tray && TRAY_PLATFORMS.has(process.platform)
228
+ // The icon follows the `tray` setting live, and "隐藏状态栏图标" in its menu
229
+ // hides it until the settings page (or a restart) brings it back.
230
+ let trayHidden = false
231
+ let trayStarting
232
+ let trayDisposed = false
233
+ /** A start that failed (no D-Bus, no tray host…) is not retried until the setting or the page asks again. */
234
+ let trayFailed = false
235
+ const trayWanted = () => Boolean(cfg.tray) && !trayHidden && !trayDisposed && TRAY_PLATFORMS.has(process.platform)
236
+ const stopTray = () => {
237
+ const t = tray
238
+ tray = undefined
239
+ return t?.stop()
240
+ }
241
+ const syncTray = () => {
242
+ if (trayStarting) return trayStarting
243
+ if (!trayWanted()) return stopTray()
244
+ if (tray) return undefined
245
+ trayStarting = startTray({ stateDir: dir, icon: iconSpec(), onAction, logger })
246
+ .then(t => {
247
+ if (!trayWanted()) return void t.stop()
248
+ tray = t
249
+ tray.update(view())
250
+ })
251
+ .catch(error => {
252
+ trayFailed = true
253
+ logger.warn('状态栏图标启动失败,只保留通知功能', error)
254
+ })
255
+ .finally(() => {
256
+ trayStarting = undefined
257
+ // The setting may have flipped while the helper was starting.
258
+ if (!trayFailed && Boolean(tray) !== trayWanted()) syncTray()
259
+ })
260
+ return trayStarting
261
+ }
262
+ const trayStatus = () => ({
263
+ supported: TRAY_PLATFORMS.has(process.platform),
264
+ enabled: Boolean(cfg.tray),
265
+ hidden: trayHidden,
266
+ shown: Boolean(tray),
267
+ failed: trayFailed,
268
+ })
226
269
  ctx.effect(() => {
227
- let disposed = false
228
- let started
229
- if (trayWanted) {
230
- started = startTray({ stateDir: dir, icon: iconSpec(), onAction, logger })
231
- .then(t => {
232
- if (disposed) return void t.stop()
233
- tray = t
234
- tray.update(view())
235
- })
236
- .catch(error => logger.warn('状态栏图标启动失败,只保留通知功能', error))
237
- }
270
+ trayDisposed = false
271
+ syncTray()
272
+ // Settings fields are read live; a cheap check picks up a flipped toggle without a restart.
273
+ let enabled = Boolean(cfg.tray)
274
+ const timer = setInterval(() => {
275
+ if (Boolean(cfg.tray) !== enabled) {
276
+ enabled = Boolean(cfg.tray)
277
+ trayFailed = false
278
+ // Switching the setting back on also undoes a hide from the tray menu.
279
+ if (enabled) trayHidden = false
280
+ }
281
+ if (!trayFailed && !trayStarting && Boolean(tray) !== trayWanted()) syncTray()
282
+ }, 2000)
238
283
  return () => {
239
- disposed = true
284
+ trayDisposed = true
285
+ clearInterval(timer)
240
286
  clearTimeout(refreshTimer)
241
- const t = tray
242
- tray = undefined
243
- t?.stop()
287
+ stopTray()
244
288
  }
245
289
  }, 'notify-tray: tray')
246
290
 
@@ -262,6 +306,8 @@ export function apply(ctx, config) {
262
306
  body: said.body,
263
307
  sound: cfg.sound,
264
308
  webOrigin,
309
+ state: EVENT_STATE[event.type],
310
+ iconDir: join(dir, 'icons'),
265
311
  onClick: () => onAction(`open:${event.sessionId}`),
266
312
  }).then(ok => debug('system notify', ok)).catch(error => logger.warn('系统通知失败', error))
267
313
  })
@@ -445,6 +491,7 @@ export function apply(ctx, config) {
445
491
  pricing: pricing(),
446
492
  plan: plan(),
447
493
  catalogLoaded: Boolean(pi),
494
+ tray: trayStatus(),
448
495
  }
449
496
  focusQueue = []
450
497
  json(res, body)
@@ -468,5 +515,18 @@ export function apply(ctx, config) {
468
515
  .catch(error => json(res, { quota: { ok: false, at: Date.now(), error: String(error?.message ?? error) }, plan: plan() }))
469
516
  },
470
517
  }), `notify-tray: POST ${REFRESH_PATH}`)
518
+ // The settings page's "show the whale again": undoes the tray menu's hide.
519
+ ctx.effect(() => ctx.webServer.register({
520
+ kind: 'exact',
521
+ path: TRAY_PATH,
522
+ handler: (req, res) => {
523
+ if (!guard(req, res, 'POST')) return
524
+ trayHidden = false
525
+ trayFailed = false
526
+ Promise.resolve(syncTray())
527
+ .catch(() => {})
528
+ .then(() => json(res, { tray: trayStatus() }))
529
+ },
530
+ }), `notify-tray: POST ${TRAY_PATH}`)
471
531
  })
472
532
  }
package/lib/ledger.js CHANGED
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
14
14
  import { dirname } from 'node:path'
15
+ import { providerForRoute } from './catalog.js'
15
16
  import { localDate } from './tracker.js'
16
17
 
17
18
  /** Days of history kept on disk. */
@@ -216,6 +217,7 @@ export class Ledger {
216
217
  return price ? { price, source: 'table' } : undefined
217
218
  }
218
219
  let estimate = 0
220
+ let deepseekEstimate = 0
219
221
  let priced = false
220
222
  const sources = new Set()
221
223
  const byModel = []
@@ -226,6 +228,7 @@ export class Ledger {
226
228
  priced = true
227
229
  sources.add(hit.source)
228
230
  estimate += cost
231
+ if (billedToDeepseek(key)) deepseekEstimate += cost
229
232
  }
230
233
  byModel.push({ ...splitRoute(key), key, tokens: buckets, cost, source: hit?.source })
231
234
  }
@@ -237,6 +240,8 @@ export class Ledger {
237
240
  byModel,
238
241
  estimate: priced ? round(estimate) : undefined,
239
242
  estimateSources: [...sources],
243
+ // The part of the estimate the DeepSeek account balance also pays for (DeepSeek routes).
244
+ estimateDeepseek: priced ? round(deepseekEstimate) : undefined,
240
245
  balance: day.balanceLast[currency],
241
246
  balanceSpend: day.balanceSpend[currency],
242
247
  currency,
@@ -245,6 +250,13 @@ export class Ledger {
245
250
  }
246
251
  }
247
252
 
253
+ /** Does usage filed under this route key come out of the DeepSeek account balance? */
254
+ export function billedToDeepseek(key) {
255
+ const { provider, model } = splitRoute(key)
256
+ if (provider) return providerForRoute(provider) === 'deepseek'
257
+ return /^deepseek/iu.test(model)
258
+ }
259
+
248
260
  const sumOf = t => t.input + t.cacheRead + t.cacheWrite + t.output
249
261
 
250
262
  function round(value) {
package/lib/pricing.js CHANGED
@@ -7,7 +7,8 @@
7
7
  * same catalog the model selector reads) → this plugin's own static catalog
8
8
  * (catalog.js). Everything comes out in the display currency.
9
9
  */
10
- import { existsSync, readdirSync } from 'node:fs'
10
+ import { existsSync, readdirSync, realpathSync } from 'node:fs'
11
+ import { homedir } from 'node:os'
11
12
  import { dirname, join } from 'node:path'
12
13
  import { pathToFileURL } from 'node:url'
13
14
  import { priceFor, splitRoute } from './ledger.js'
@@ -19,12 +20,53 @@ export const DEFAULT_RATE = 7.2
19
20
  /** Human labels for where a price came from. */
20
21
  export const SOURCE_LABEL = { table: '价格表', custom: '自定义价', catalog: '目录价', static: '内置价' }
21
22
 
23
+ const DSH_PACKAGE = join('@deepseek-ai', 'dsh')
24
+
25
+ /**
26
+ * Where a globally installed `@deepseek-ai/dsh` (the web / CLI profile) may
27
+ * live: npm's configured prefix, the common `~/.npm-global` user prefix, the
28
+ * prefix of the node running us, and pnpm's global store.
29
+ */
30
+ export function globalDshDirs(env = process.env, home = safeHome(), execPath = process.execPath) {
31
+ const prefixes = [env.npm_config_prefix, env.NPM_CONFIG_PREFIX, env.PREFIX]
32
+ if (home) prefixes.push(join(home, '.npm-global'), join(home, '.npm-packages'), join(home, '.local'))
33
+ if (execPath) prefixes.push(dirname(dirname(execPath)))
34
+ prefixes.push('/usr/local', '/usr', '/opt/homebrew')
35
+ const dirs = []
36
+ for (const prefix of prefixes) {
37
+ if (!prefix) continue
38
+ // POSIX prefixes keep packages under lib/; Windows prefixes keep them at the top.
39
+ dirs.push(join(prefix, 'lib', 'node_modules', DSH_PACKAGE), join(prefix, 'node_modules', DSH_PACKAGE))
40
+ }
41
+ const pnpmHome = env.PNPM_HOME || (home ? join(home, '.local', 'share', 'pnpm') : undefined)
42
+ if (pnpmHome) {
43
+ for (const store of safeReaddir(join(pnpmHome, 'global'))) dirs.push(join(pnpmHome, 'global', store, 'node_modules', DSH_PACKAGE))
44
+ }
45
+ return dirs
46
+ }
47
+
48
+ function safeHome() {
49
+ try { return homedir() } catch { return undefined }
50
+ }
51
+
52
+ function safeRealpath(path) {
53
+ try { return realpathSync(path) } catch { return undefined }
54
+ }
55
+
22
56
  /** Directories worth walking up from to find the pi-ai package DSH ships. */
23
57
  function defaultBases() {
24
58
  const bases = []
25
59
  if (process.env.DSH_NOTIFY_TRAY_PI_AI) bases.push(process.env.DSH_NOTIFY_TRAY_PI_AI)
26
- // Desktop host: argv[2] is the DSH runtime dir; CLI: argv[1] is the dsh entry script.
27
- for (const arg of [process.argv[2], process.argv[1]]) if (arg) bases.push(arg)
60
+ // Desktop host: argv[2] is the DSH runtime dir; CLI: argv[1] is the dsh entry script,
61
+ // usually a bin symlink (~/.npm-global/bin/dsh) whose real path sits inside the package.
62
+ for (const arg of [process.argv[2], process.argv[1]]) {
63
+ if (!arg) continue
64
+ const real = safeRealpath(arg)
65
+ if (real && real !== arg) bases.push(real)
66
+ bases.push(arg)
67
+ }
68
+ // `dsh web` started from a global install leaves neither argv entry pointing into the package.
69
+ bases.push(...globalDshDirs())
28
70
  bases.push(dirname(process.execPath), process.cwd())
29
71
  return bases
30
72
  }
@@ -39,6 +81,9 @@ export function findPiCatalogFile(bases = defaultBases()) {
39
81
  seen.add(dir)
40
82
  const direct = join(dir, 'node_modules', PI_AI_REL)
41
83
  if (safeExists(direct)) return direct
84
+ // A hoisted copy next to the package (global node_modules, pi-ai as a sibling).
85
+ const sibling = join(dir, PI_AI_REL)
86
+ if (safeExists(sibling)) return sibling
42
87
  const pnpm = join(dir, 'node_modules', '.pnpm')
43
88
  if (safeExists(pnpm)) {
44
89
  for (const entry of safeReaddir(pnpm)) {
package/lib/system.js CHANGED
@@ -77,7 +77,8 @@ function windowsToast(xml) {
77
77
 
78
78
  /**
79
79
  * Show one native notification.
80
- * @param {{title: string, body: string, sound?: boolean, onClick?: () => void, webOrigin?: () => string | undefined}} n
80
+ * @param {{title: string, body: string, sound?: boolean, onClick?: () => void, webOrigin?: () => string | undefined, state?: string, iconDir?: string}} n
81
+ * `state` picks the whale's colour and `iconDir` where its PNG is cached (Linux).
81
82
  */
82
83
  export async function systemNotify(n) {
83
84
  if (process.platform === 'darwin') {
@@ -94,10 +95,15 @@ export async function systemNotify(n) {
94
95
  // Linux / BSD: D-Bus first (clickable), notify-send as a fallback.
95
96
  try {
96
97
  const { linuxNotify } = await import('./tray/linux.js')
97
- await linuxNotify({ title: n.title, body: n.body, sound: n.sound !== false, onClick: n.onClick })
98
+ await linuxNotify({ title: n.title, body: n.body, sound: n.sound !== false, onClick: n.onClick, state: n.state, iconDir: n.iconDir })
98
99
  return true
99
100
  } catch {
100
- return run('notify-send', ['-a', 'DeepSeek Harness', n.title, n.body])
101
+ let icon = ''
102
+ try {
103
+ const { notifyIcon } = await import('./tray/linux.js')
104
+ icon = notifyIcon(n.state, n.iconDir).path
105
+ } catch {}
106
+ return run('notify-send', ['-a', 'DeepSeek Harness', ...(icon ? ['-i', icon] : []), n.title, n.body])
101
107
  }
102
108
  }
103
109
 
package/lib/tracker.js CHANGED
@@ -167,7 +167,7 @@ export class Tracker {
167
167
  return
168
168
  case 'approval/asked': {
169
169
  const body = data.reason || `工具 ${data.toolName} 需要你批准`
170
- entry.pending.set(`approval:${data.id}`, { kind: 'approval', text: body, since: this.now() })
170
+ entry.pending.set(`approval:${data.id}`, { kind: 'approval', text: body, since: this.now(), callId: data.callId })
171
171
  this.emit('approval', entry, body)
172
172
  break
173
173
  }
@@ -183,8 +183,15 @@ export class Tracker {
183
183
  break
184
184
  }
185
185
  case 'tool/result': {
186
- const callId = data.message?.callId
187
- if (callId === undefined || !entry.pending.delete(`question:${callId}`)) return
186
+ // ToolResultMessage names the call it answers `toolCallId` (mirrored in `source.callId`).
187
+ const callId = data.message?.toolCallId ?? data.message?.source?.callId
188
+ if (callId === undefined) return
189
+ let cleared = entry.pending.delete(`question:${callId}`)
190
+ // An approval for this call is settled once the call has a result, even if `approval/decided` was missed.
191
+ for (const [key, wait] of entry.pending) {
192
+ if (wait.callId === callId) cleared = entry.pending.delete(key) || cleared
193
+ }
194
+ if (!cleared) return
188
195
  break
189
196
  }
190
197
  case 'turn/end': {
package/lib/tray/linux.js CHANGED
@@ -8,10 +8,10 @@
8
8
  * AppIndicator extension, XFCE and LXQt.
9
9
  * Notifications: org.freedesktop.Notifications, with click-to-open actions.
10
10
  */
11
- import { existsSync } from 'node:fs'
11
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
12
12
  import { createRequire } from 'node:module'
13
13
  import { join } from 'node:path'
14
- import { renderIcon } from '../icon.js'
14
+ import { pngIcon, renderIcon, rgbaIcon } from '../icon.js'
15
15
  import { iconSpec } from '../whale.js'
16
16
 
17
17
  const require = createRequire(import.meta.url)
@@ -304,9 +304,37 @@ export async function startLinuxTray({ onAction, logger }) {
304
304
  }
305
305
 
306
306
  const notifyActions = new Map()
307
+ /** Edge of the whale drawn into notifications. */
308
+ const NOTIFY_ICON_SIZE = 64
309
+
310
+ const notifyIcons = new Map()
311
+ /**
312
+ * The whale for a notification: inline pixels for the `image-data` hint (spec
313
+ * 1.2; older servers read `image_data` / `icon_data`) and, when `iconDir` is
314
+ * writable, a PNG path for `app_icon`, which servers that ignore image hints
315
+ * (and history panes) show instead of a generic icon.
316
+ */
317
+ export function notifyIcon(state = 'idle', iconDir) {
318
+ const key = `${state}|${iconDir ?? ''}`
319
+ let icon = notifyIcons.get(key)
320
+ if (icon === undefined) {
321
+ const size = NOTIFY_ICON_SIZE
322
+ icon = { size, rgba: rgbaIcon(size, state), path: '' }
323
+ if (iconDir) {
324
+ try {
325
+ mkdirSync(iconDir, { recursive: true })
326
+ const file = join(iconDir, `whale-${state}.png`)
327
+ writeFileSync(file, pngIcon(size, state))
328
+ icon.path = file
329
+ } catch {}
330
+ }
331
+ notifyIcons.set(key, icon)
332
+ }
333
+ return icon
334
+ }
307
335
 
308
336
  /** Show one freedesktop notification; `onClick` runs when its default action is invoked. */
309
- export async function linuxNotify({ title, body, sound = true, onClick }) {
337
+ export async function linuxNotify({ title, body, sound = true, onClick, state = 'idle', iconDir }) {
310
338
  const link = await connect()
311
339
  const { dbus, bus } = link
312
340
  if (!link.notifications) {
@@ -320,11 +348,19 @@ export async function linuxNotify({ title, body, sound = true, onClick }) {
320
348
  link.notifications = iface
321
349
  }
322
350
  const iface = link.notifications
323
- const hints = { urgency: new dbus.Variant('y', 1), 'desktop-entry': new dbus.Variant('s', 'deepseek-harness') }
351
+ const icon = notifyIcon(state, iconDir)
352
+ const image = new dbus.Variant('(iiibiiay)', [icon.size, icon.size, icon.size * 4, true, 8, 4, icon.rgba])
353
+ const hints = {
354
+ urgency: new dbus.Variant('y', 1),
355
+ 'desktop-entry': new dbus.Variant('s', 'deepseek-harness'),
356
+ 'image-data': image,
357
+ image_data: image,
358
+ icon_data: image,
359
+ }
324
360
  // freedesktop sound-naming spec; servers that play sounds honour these hints.
325
361
  if (sound) hints['sound-name'] = new dbus.Variant('s', 'message-new-instant')
326
362
  else hints['suppress-sound'] = new dbus.Variant('b', true)
327
- const id = await iface.Notify('DeepSeek Harness', 0, 'dialog-information', title, body, ['default', '打开'], hints, -1)
363
+ const id = await iface.Notify('DeepSeek Harness', 0, icon.path, title, body, ['default', '打开'], hints, -1)
328
364
  if (onClick) notifyActions.set(id, onClick)
329
365
  return id
330
366
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-notify-tray",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "DeepSeek Harness 通知 + 状态栏插件:任务完成、需要输入、需要选择时弹系统通知(macOS / Windows / Linux);macOS 与 Linux(含 UOS、Deepin、麒麟)状态栏常驻小图标,显示任务进度与花费。Windows 没有状态栏,只弹通知。",
5
5
  "keywords": [
6
6
  "deepseek",