dsh-notify-tray 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,19 +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.5` (the latest version is listed on [npm](https://www.npmjs.com/package/dsh-notify-tray)).
30
+ > **⚠️ To get the latest release, include the version number**, e.g. `dsh-notify-tray@0.1.6` (the latest version is listed on [npm](https://www.npmjs.com/package/dsh-notify-tray)).
31
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
32
 
33
33
  **Option 1 — from inside DSH (recommended)**
34
- Open DSH **Plugins → Add plugin**, type `dsh-notify-tray@0.1.5` (with the version number) into the input box and click **Install**.
34
+ Open DSH **Plugins → Add plugin**, type `dsh-notify-tray@0.1.6` (with the version number) into the input box and click **Install**.
35
35
 
36
36
  **Option 2 — command line**
37
37
 
38
38
  ```sh
39
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.5
40
+ dsh plugin --profile desktop add dsh-notify-tray@0.1.6
41
41
  # Or the web / CLI profile
42
- dsh plugin --profile web add dsh-notify-tray@0.1.5
42
+ dsh plugin --profile web add dsh-notify-tray@0.1.6
43
43
  ```
44
44
 
45
45
  **Option 3 — from the Git repository** (latest unreleased code)
@@ -54,7 +54,7 @@ Restart DSH after installing. The version on the plugin page is the one installe
54
54
  >
55
55
  > ```sh
56
56
  > dsh plugin --profile desktop remove dsh-notify-tray
57
- > dsh plugin --profile desktop add dsh-notify-tray@0.1.5
57
+ > dsh plugin --profile desktop add dsh-notify-tray@0.1.6
58
58
  > ```
59
59
  >
60
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.
@@ -104,7 +104,7 @@ Every option can be changed on DSH's **Plugins → Whale Notify Station** page,
104
104
  | `exchangeRate` | `7.2` | 1 USD = ? CNY; catalog prices are in USD and converted when displaying CNY |
105
105
  | `prices` | `{}` | Per-model price table, highest priority |
106
106
 
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.
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` (global npm installs such as `~/.npm-global` or `%APPDATA%\npm` on Windows, pnpm, and nodes installed by nvm / fnm / volta; as a last resort the plugin asks `npm root -g`). If it isn't there at startup, the plugin looks again every 10 minutes. If the settings page still 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.
108
108
 
109
109
  ### Plans
110
110
 
@@ -142,7 +142,11 @@ Anything that can't be fetched can be typed in by hand; empty fields are simply
142
142
 
143
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.
144
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** submenu breaks it down per model (top 3). The ledger lives in `~/.dsh/storages/dsh-notify-tray/ledger.json` and keeps 31 days.
145
+ - **DeepSeek off-peak prices** — DeepSeek's listed prices are peak prices (Beijing time, weekdays 9–12 and 14–18). Tokens used outside those hours are estimated at half price; prices you type yourself (price table or custom price) are used as they are.
145
146
  - **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.
147
+ - With the default `channel: auto` and a DSH window open, notifications come from the window, and clicking one jumps to its session on every OS.
148
+ - **macOS system notifications** (`dsh web`, or `channel: system`) are sent with `osascript`, which can't tell DSH which session was clicked. Install [terminal-notifier](https://github.com/julienXX/terminal-notifier) (`brew install terminal-notifier`) and the plugin uses it automatically: clicking the notification opens the session.
149
+ - **Windows toasts** can only launch the app, so the window that comes forward within a minute of a toast opens that toast's session. Windows won't let a background process pull a *visible* window that is behind another one to the front (see [#4](https://github.com/ROYLeXJ/dsh-notify-tray/issues/4)); a minimized window is restored.
146
150
 
147
151
  ## Development
148
152
 
package/README.zh-CN.md CHANGED
@@ -27,19 +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.5`(最新版本号见 [npm](https://www.npmjs.com/package/dsh-notify-tray))。
30
+ > **⚠️ 想装最新版,请带上版本号**,例如 `dsh-notify-tray@0.1.6`(最新版本号见 [npm](https://www.npmjs.com/package/dsh-notify-tray))。
31
31
  > DSH 用 pnpm 安装插件,pnpm 的供应链安全策略(`minimumReleaseAge`)不会自动安装刚发布、还没过观察期的版本,只写 `dsh-notify-tray` 时会退回装一个旧版本(例如 0.1.0)。已经装了旧版的,先卸载,再带版本号安装。
32
32
 
33
33
  **方式一:在 DSH 里装(推荐)**
34
- 打开 DSH「插件 → 添加插件」,输入框里填 `dsh-notify-tray@0.1.5`(带上版本号),点「安装」。
34
+ 打开 DSH「插件 → 添加插件」,输入框里填 `dsh-notify-tray@0.1.6`(带上版本号),点「安装」。
35
35
 
36
36
  **方式二:命令行**
37
37
 
38
38
  ```sh
39
39
  # 桌面版(App 内置的 dsh 命令),带上版本号才能装到最新版
40
- dsh plugin --profile desktop add dsh-notify-tray@0.1.5
40
+ dsh plugin --profile desktop add dsh-notify-tray@0.1.6
41
41
  # 或者 Web / 命令行 profile
42
- dsh plugin --profile web add dsh-notify-tray@0.1.5
42
+ dsh plugin --profile web add dsh-notify-tray@0.1.6
43
43
  ```
44
44
 
45
45
  **方式三:从 Git 仓库装**(想用还没发版的最新代码时)
@@ -54,7 +54,7 @@ dsh plugin --profile web add dsh-notify-tray@0.1.5
54
54
  >
55
55
  > ```sh
56
56
  > dsh plugin --profile desktop remove dsh-notify-tray
57
- > dsh plugin --profile desktop add dsh-notify-tray@0.1.5
57
+ > dsh plugin --profile desktop add dsh-notify-tray@0.1.6
58
58
  > ```
59
59
  >
60
60
  > 另外,官方 npm 源连不上时 DSH 会退到 npmmirror(淘宝镜像),镜像比官方源晚一点同步,刚发的新版可能要等几分钟才到。
@@ -104,7 +104,7 @@ dsh plugin --profile web add dsh-notify-tray@0.1.5
104
104
  | `exchangeRate` | `7.2` | 1 美元 = ? 人民币;目录价是美元,显示人民币时按它换算 |
105
105
  | `prices` | `{}` | 按模型的价格表,优先级最高 |
106
106
 
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`)后重启。一键「把目录价填进自定义价」可以在目录价的基础上改。
107
+ 「当前 API 价格」区域会显示你正在用的模型(provider / model)和它的目录价:DSH 的 pi-ai 适配器自带一份模型目录(Claude、GPT、Gemini、Grok、Groq、Kimi、GLM、MiMo、MiniMax、OpenCode Go、DeepSeek 等),插件直接读它,拿不到的再用内置价或你填的自定义价。桌面版和 `dsh web` 都会自动找到这份目录(全局 npm 安装如 `~/.npm-global`、Windows 的 `%APPDATA%\npm`,pnpm,以及 nvm / fnm / volta 装的 node;实在找不到时会问一次 `npm root -g`)。启动时没找到的话,插件每 10 分钟再找一次。如果设置页仍提示没找到,可以设置环境变量 `DSH_NOTIFY_TRAY_PI_AI` 指向 DSH 的安装目录(例如 `~/.npm-global/lib/node_modules/@deepseek-ai/dsh`)后重启。一键「把目录价填进自定义价」可以在目录价的基础上改。
108
108
 
109
109
  ### 套餐
110
110
 
@@ -142,7 +142,11 @@ dsh plugin --profile web add dsh-notify-tray@0.1.5
142
142
 
143
143
  - **通知的触发时机**:任务跑完算「完成」;出错、超出 Token 上限、被拦截算「失败」;你自己点停止不弹通知。调用 `ask_user_question` 时,带选项的问题和计划审批算「需要选择」,不带选项的算「需要输入」;工具审批算「需要批准」。只跟踪顶层会话,子 agent 不单独弹通知。
144
144
  - **花费怎么算**:用 DeepSeek 账户登录时,按账户余额的下降累计当天花费(充值不算负花费;平台扣费有延迟,`auto` 下余额没跟上时先按估算显示);同时按当天各「provider/model」的 Token 乘以单价估算(单价来源见上面的 `priceSource`),「今日」子菜单里按模型分行显示(最多 3 个模型)。账本存在 `~/.dsh/storages/dsh-notify-tray/ledger.json`,保留 31 天。
145
+ - **DeepSeek 空闲时段价格**:DeepSeek 的标价是高峰价(北京时间工作日 9–12、14–18 点),其余时间用的 token 按半价估算;你自己填的价(价格表或自定义价)按原样算。
145
146
  - **点击通知 / 状态栏图标 / 菜单里的「打开 DeepSeek Harness」**:有桌面版时唤起桌面版,没有时(`dsh web`)在浏览器里打开 Web 界面。浏览器里的通知需要先允许通知权限。
147
+ - 默认的 `channel: auto` 下,只要开着 DSH 窗口,通知就由窗口弹,三个系统上点击都能跳到对应会话。
148
+ - **macOS 系统通知**(`dsh web` 或 `channel: system`)用 `osascript` 发,点击时没法告诉 DSH 是哪个会话。装上 [terminal-notifier](https://github.com/julienXX/terminal-notifier)(`brew install terminal-notifier`)后插件会自动改用它,点通知就能打开对应会话。
149
+ - **Windows 系统通知**只能唤起应用,所以通知弹出后一分钟内被拉到前面的窗口,会打开这条通知对应的会话。Windows 不允许后台进程把被别的窗口挡住的*可见*窗口拉到最前(见 [#4](https://github.com/ROYLeXJ/dsh-notify-tray/issues/4));最小化的窗口会被恢复。
146
150
 
147
151
  ## 已知限制
148
152
 
package/lib/catalog.js CHANGED
@@ -293,6 +293,21 @@ export const PROVIDERS = [
293
293
  },
294
294
  ]
295
295
 
296
+ /**
297
+ * DeepSeek's list prices are peak prices (Beijing time, weekdays 9–12 and
298
+ * 14–18); outside those hours the API bills `factor` of them.
299
+ */
300
+ export const DEEPSEEK_OFF_PEAK = { factor: 0.5, peakHours: [[9, 12], [14, 18]], utcOffsetHours: 8 }
301
+
302
+ /** Is `time` in DeepSeek's off-peak window (weekends count as off-peak; public holidays are not known)? */
303
+ export function isDeepseekOffPeak(time = Date.now()) {
304
+ const beijing = new Date(time + DEEPSEEK_OFF_PEAK.utcOffsetHours * 3_600_000)
305
+ const weekday = beijing.getUTCDay()
306
+ if (weekday === 0 || weekday === 6) return true
307
+ const hour = beijing.getUTCHours() + beijing.getUTCMinutes() / 60
308
+ return !DEEPSEEK_OFF_PEAK.peakHours.some(([from, to]) => hour >= from && hour < to)
309
+ }
310
+
296
311
  /** Catalog provider for an id (`custom` and `none` have no catalog entry). */
297
312
  export function providerOf(id) {
298
313
  return PROVIDERS.find(p => p.id === id)
package/lib/client.js CHANGED
@@ -14,6 +14,7 @@ window.__ModuleLoader__.load({
14
14
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
15
15
 
16
16
  var ROUTE = 'notify-tray/state'
17
+ var RAISE_ROUTE = 'notify-tray/raise'
17
18
  var POLL_MS = 2000
18
19
  var SEEN_KEY = 'dsh-notify-tray:seen'
19
20
 
@@ -140,6 +141,8 @@ window.__ModuleLoader__.load({
140
141
  spendNone: '还没有花费记录',
141
142
  currentModelNone: '还没看到请求,先聊一句就知道了。',
142
143
  perMillion: '每百万',
144
+ offPeakNow: '现在是空闲时段,按半价估算',
145
+ offPeakLater: '空闲时段(北京时间工作日 9–12、14–18 点以外)按半价估算',
143
146
  noListedPrice: '目录里没有这个模型的价格,可在「高级设置」里填自定义单价。',
144
147
  catalogOff: 'DSH 自带的模型目录没找到,只有插件内置价可用。可设置环境变量 DSH_NOTIFY_TRAY_PI_AI 指向 DSH 的安装目录后重启。',
145
148
  myPlan: '我的套餐',
@@ -289,6 +292,8 @@ window.__ModuleLoader__.load({
289
292
  spendNone: 'No spend recorded yet',
290
293
  currentModelNone: 'No request seen yet — send one message and it shows up here.',
291
294
  perMillion: 'per million',
295
+ offPeakNow: 'Off-peak now: estimated at half price',
296
+ offPeakLater: 'Off-peak (outside 9–12 and 14–18 Beijing time on weekdays) is estimated at half price',
292
297
  noListedPrice: 'No catalog price for this model; set a custom price under Advanced.',
293
298
  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.',
294
299
  myPlan: 'My plan',
@@ -650,6 +655,7 @@ window.__ModuleLoader__.load({
650
655
  if (price) {
651
656
  const source = SOURCE_KEY[price.source] ? t(SOURCE_KEY[price.source]) : price.source
652
657
  detail.push(h('div', { key: 'price', style: S.muted }, `${priceLine(price, price.currency)} ${t('perMillion')} · ${source}`))
658
+ if (price.offPeakFactor !== undefined) detail.push(h('div', { key: 'offpeak', style: S.muted }, t(price.offPeakNow ? 'offPeakNow' : 'offPeakLater')))
653
659
  } else if (!pricing.listed) {
654
660
  detail.push(h('div', { key: 'nolisted', style: S.muted }, t('noListedPrice')))
655
661
  }
@@ -884,6 +890,8 @@ window.__ModuleLoader__.load({
884
890
  var boot
885
891
  var stopped = false
886
892
  var timer
893
+ /** Focus at the previous poll: a window that just came forward claims the session a system toast announced. */
894
+ var wasFocused = false
887
895
 
888
896
  function open(sessionId) {
889
897
  try { window.focus() } catch (e) {}
@@ -900,12 +908,20 @@ window.__ModuleLoader__.load({
900
908
  if (!claim(boot, event.seq)) return
901
909
  var display = event.display || { title: (state.titles[event.type] || 'DeepSeek Harness') + ' · ' + event.title, body: event.body }
902
910
  var n = new Notification(display.title, { body: display.body, tag: 'dsh-notify-tray:' + event.seq })
903
- n.onclick = function () { n.close(); open(event.sessionId) }
911
+ n.onclick = function () {
912
+ n.close()
913
+ // The renderer cannot move the OS foreground; the host brings the window forward where it can (Windows).
914
+ fetch(RAISE_ROUTE, { method: 'POST', cache: 'no-store' }).catch(function () {})
915
+ open(event.sessionId)
916
+ }
904
917
  }
905
918
 
906
919
  function poll() {
907
920
  var granted = typeof Notification !== 'undefined' && Notification.permission === 'granted'
908
- fetch(ROUTE + '?after=' + cursor + (granted ? '&notify=1' : ''), { headers: { accept: 'application/json' }, cache: 'no-store' })
921
+ var focused = typeof document !== 'undefined' && typeof document.hasFocus === 'function' && document.hasFocus()
922
+ var claimToast = focused && !wasFocused
923
+ wasFocused = focused
924
+ fetch(ROUTE + '?after=' + cursor + (granted ? '&notify=1' : '') + (claimToast ? '&claim=1' : ''), { headers: { accept: 'application/json' }, cache: 'no-store' })
909
925
  .then(function (res) { return res.ok ? res.json() : undefined })
910
926
  .then(function (state) {
911
927
  if (!state || stopped) return
package/lib/index.js CHANGED
@@ -23,9 +23,9 @@ import { join } from 'node:path'
23
23
  import { planView, publicCatalog, quotaSpecFor } from './catalog.js'
24
24
  import { buildView, DONE_HOLD_MS, spendOf, TITLES } from './format.js'
25
25
  import { Ledger } from './ledger.js'
26
- import { describeRoute, loadPiCatalog, makeResolver } from './pricing.js'
26
+ import { describeRoute, findDshVersion, findPiCatalogFile, loadPiCatalog, makeResolver, npmGlobalDshDir } from './pricing.js'
27
27
  import { fetchQuota } from './quota.js'
28
- import { openUrl, showApp, systemNotify } from './system.js'
28
+ import { consumeClicks, desktopHosted, openUrl, showApp, systemNotify, terminalNotifier } from './system.js'
29
29
  import { startTray } from './tray/index.js'
30
30
  import { Tracker } from './tracker.js'
31
31
  import { speak } from './voice.js'
@@ -38,8 +38,17 @@ const STATE_PATH = '/notify-tray/state'
38
38
  const CATALOG_PATH = '/notify-tray/catalog'
39
39
  const REFRESH_PATH = '/notify-tray/refresh'
40
40
  const TRAY_PATH = '/notify-tray/tray'
41
- /** Harness version sent as account client metadata (what the built-in settings page sends). */
42
- const DSH_VERSION = '0.2.1-rc.2'
41
+ const RAISE_PATH = '/notify-tray/raise'
42
+ /**
43
+ * A clicked Windows toast can only launch `dsh://open` (or the web GUI), so no
44
+ * session travels with it: a window that comes forward within this long after
45
+ * a toast opens the session that toast announced.
46
+ */
47
+ const TOAST_CLAIM_MS = 60_000
48
+ /** Harness version sent as account client metadata when the installed one cannot be read. */
49
+ const DSH_VERSION_FALLBACK = '0.2.1-rc.2'
50
+ /** How often a price catalog that was not found is looked for again. */
51
+ const CATALOG_RETRY_MS = 10 * 60_000
43
52
  /** A window that polled within this window counts as "listening". */
44
53
  const CLIENT_FRESH_MS = 8000
45
54
  /** Platforms with a status bar the whale can live in. */
@@ -154,6 +163,8 @@ export function apply(ctx, config) {
154
163
  let lastClientPoll = 0
155
164
  /** Session ids a tray click asked the window to open, consumed by the next poll. */
156
165
  let focusQueue = []
166
+ /** The session the latest Windows toast announced: { sessionId, at }. */
167
+ let toastPending
157
168
 
158
169
  /** Set DSH_NOTIFY_TRAY_DEBUG=1 to trace tracked events into storages/dsh-notify-tray/debug.log. */
159
170
  const debug = process.env.DSH_NOTIFY_TRAY_DEBUG
@@ -289,6 +300,19 @@ export function apply(ctx, config) {
289
300
  }, 'notify-tray: tray')
290
301
 
291
302
  // ---- notifications ----------------------------------------------------
303
+ // A clicked macOS notification (sent through terminal-notifier) drops a file
304
+ // named after its session here; the host opens that session.
305
+ const clickDir = join(dir, 'clicks')
306
+ if (process.platform === 'darwin') {
307
+ ctx.effect(() => {
308
+ consumeClicks(clickDir) // stale clicks from an earlier run open nothing
309
+ const timer = setInterval(() => {
310
+ if (!terminalNotifier()) return
311
+ for (const id of consumeClicks(clickDir)) onAction(`open:${id}`)
312
+ }, 1000)
313
+ return () => clearInterval(timer)
314
+ }, 'notify-tray: notification clicks')
315
+ }
292
316
  tracker.onEvent(event => {
293
317
  debug('event', event)
294
318
  // The celebration / error pose expires on its own: refresh once it does.
@@ -301,6 +325,7 @@ export function apply(ctx, config) {
301
325
  debug('deliver', { channel, clientListening, systemSide })
302
326
  if (!systemSide) return // the window picks it up from the event queue
303
327
  const said = speak(event)
328
+ if (process.platform === 'win32') toastPending = { sessionId: event.sessionId, at: Date.now() }
304
329
  systemNotify({
305
330
  title: said.title,
306
331
  body: said.body,
@@ -308,6 +333,8 @@ export function apply(ctx, config) {
308
333
  webOrigin,
309
334
  state: EVENT_STATE[event.type],
310
335
  iconDir: join(dir, 'icons'),
336
+ sessionId: event.sessionId,
337
+ clickDir,
311
338
  onClick: () => onAction(`open:${event.sessionId}`),
312
339
  }).then(ok => debug('system notify', ok)).catch(error => logger.warn('系统通知失败', error))
313
340
  })
@@ -340,15 +367,35 @@ export function apply(ctx, config) {
340
367
  }, 'notify-tray: ledger')
341
368
 
342
369
  // ---- pi-ai price catalog (the one DSH's model selector reads) -------------
370
+ // Not found at startup (an install layout we do not guess, npm still busy…):
371
+ // ask npm once, then keep looking every few minutes until it turns up.
343
372
  ctx.effect(() => {
344
373
  let disposed = false
345
- loadPiCatalog().then(loaded => {
346
- if (disposed || !loaded) return
374
+ let timer
375
+ let askedNpm = false
376
+ const attempt = async () => {
377
+ let loaded = await loadPiCatalog()
378
+ if (!loaded && !askedNpm) {
379
+ askedNpm = true
380
+ const dir = await npmGlobalDshDir()
381
+ const file = dir ? findPiCatalogFile([dir]) : undefined
382
+ if (file) loaded = await loadPiCatalog({ file })
383
+ }
384
+ if (disposed) return
385
+ if (!loaded) {
386
+ timer = setTimeout(() => attempt().catch(() => {}), CATALOG_RETRY_MS)
387
+ timer.unref?.()
388
+ return
389
+ }
347
390
  pi = loaded
348
391
  debug('pi catalog', loaded.file)
349
392
  refresh()
350
- }).catch(() => {})
351
- return () => { disposed = true }
393
+ }
394
+ attempt().catch(() => {})
395
+ return () => {
396
+ disposed = true
397
+ clearTimeout(timer)
398
+ }
352
399
  }, 'notify-tray: price catalog')
353
400
 
354
401
  // ---- plan quota polling ---------------------------------------------------
@@ -404,8 +451,8 @@ export function apply(ctx, config) {
404
451
  // ---- DeepSeek account balance (optional service) ------------------------
405
452
  ctx.inject(['deepseekAccount'], (ctx) => {
406
453
  const client = {
407
- // Mirrors DSH's own settings page: the harness version and the UI locale.
408
- version: DSH_VERSION,
454
+ // Mirrors DSH's own settings page: the installed harness version and the UI locale.
455
+ version: findDshVersion() ?? DSH_VERSION_FALLBACK,
409
456
  locale: 'zh-CN',
410
457
  timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
411
458
  }
@@ -470,6 +517,11 @@ export function apply(ctx, config) {
470
517
  // a browser tab without permission must not silence the system channel.
471
518
  if (url.searchParams.get('notify') === '1') lastClientPoll = Date.now()
472
519
  const after = Number(url.searchParams.get('after') ?? '-1')
520
+ // A window that just came forward after a toast takes that toast's session, once.
521
+ if (url.searchParams.get('claim') === '1' && toastPending) {
522
+ if (Date.now() - toastPending.at < TOAST_CLAIM_MS) focusQueue.push(toastPending.sessionId)
523
+ toastPending = undefined
524
+ }
473
525
  const channel = cfg.channel
474
526
  const clientSide = channel === 'auto' || channel === 'client' || channel === 'both'
475
527
  const currentUsage = usage()
@@ -518,6 +570,19 @@ export function apply(ctx, config) {
518
570
  .catch(error => json(res, { quota: { ok: false, at: Date.now(), error: String(error?.message ?? error) }, plan: plan() }))
519
571
  },
520
572
  }), `notify-tray: POST ${REFRESH_PATH}`)
573
+ // A click on an in-window notification: the renderer cannot change the OS
574
+ // foreground, so in the Windows desktop app the host relaunches it, and the
575
+ // single-instance handler restores a minimized window (a visible window
576
+ // behind another one stays put: Windows' foreground lock, see issue #4).
577
+ ctx.effect(() => ctx.webServer.register({
578
+ kind: 'exact',
579
+ path: RAISE_PATH,
580
+ handler: (req, res) => {
581
+ if (!guard(req, res, 'POST')) return
582
+ const raise = process.platform === 'win32' && desktopHosted() ? open() : Promise.resolve(false)
583
+ raise.then(raised => json(res, { raised: Boolean(raised) }))
584
+ },
585
+ }), `notify-tray: POST ${RAISE_PATH}`)
521
586
  // The settings page's "show the whale again": undoes the tray menu's hide.
522
587
  ctx.effect(() => ctx.webServer.register({
523
588
  kind: 'exact',
package/lib/ledger.js CHANGED
@@ -6,13 +6,15 @@
6
6
  * samples with token-meter's dedupe rule (each (turn, step) slot keeps its
7
7
  * last sample; `llm/retry-started` opens a new slot), filed under the
8
8
  * `provider/model` route the session's latest `request/header` announced
9
- * and priced by a resolver (see pricing.js) per million tokens;
9
+ * and priced by a resolver (see pricing.js) per million tokens; DeepSeek
10
+ * tokens used off-peak are also counted apart (`offPeak`), so the
11
+ * resolver's `offPeakFactor` can discount them;
10
12
  * - balance: polled DeepSeek account balance; the day's spend is the sum of
11
13
  * balance drops, so a top-up never reads as negative spend.
12
14
  */
13
15
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
14
16
  import { dirname } from 'node:path'
15
- import { providerForRoute } from './catalog.js'
17
+ import { isDeepseekOffPeak, providerForRoute } from './catalog.js'
16
18
  import { localDate } from './tracker.js'
17
19
 
18
20
  /** Days of history kept on disk. */
@@ -114,7 +116,7 @@ export class Ledger {
114
116
  const date = localDate(this.now())
115
117
  let day = this.days[date]
116
118
  if (day === undefined) {
117
- day = { date, tokens: zero(), byModel: {}, balanceSpend: {}, balanceLast: {} }
119
+ day = { date, tokens: zero(), byModel: {}, offPeak: {}, balanceSpend: {}, balanceLast: {} }
118
120
  // Carry the last known balance across midnight so the first poll of the day diffs against it.
119
121
  const previous = Object.keys(this.days).sort().pop()
120
122
  if (previous !== undefined) day.balanceLast = { ...this.days[previous].balanceLast }
@@ -172,10 +174,13 @@ export class Ledger {
172
174
  const previous = slot && slot.turn === turn && slot.step === step ? slot : undefined
173
175
  const day = this.today()
174
176
  const byModel = (day.byModel[key] ??= zero())
177
+ // Days recorded before off-peak tracking have no `offPeak` map.
178
+ const offPeak = billedToDeepseek(key) && isDeepseekOffPeak(this.now()) ? ((day.offPeak ??= {})[key] ??= zero()) : undefined
175
179
  for (const bucket of Object.keys(next)) {
176
180
  const delta = next[bucket] - (previous?.buckets[bucket] ?? 0)
177
181
  day.tokens[bucket] += delta
178
182
  byModel[bucket] += delta
183
+ if (offPeak) offPeak[bucket] += delta
179
184
  }
180
185
  this.slots.set(id, { turn, step, buckets: next })
181
186
  this.changed()
@@ -208,7 +213,9 @@ export class Ledger {
208
213
  * Today's totals. `pricing` is either a user price table (per million tokens,
209
214
  * keyed by route / model id / prefix) or a resolver
210
215
  * `(routeKey) => { price, source } | undefined` whose price is already in the
211
- * display currency. The estimate is undefined until at least one route priced.
216
+ * display currency. A hit with `offPeakFactor` bills the route's off-peak
217
+ * tokens at that fraction of its price. The estimate is undefined until at
218
+ * least one route priced.
212
219
  */
213
220
  summary(pricing, currency) {
214
221
  const day = this.today()
@@ -223,7 +230,10 @@ export class Ledger {
223
230
  const byModel = []
224
231
  for (const [key, buckets] of Object.entries(day.byModel)) {
225
232
  const hit = resolve(key)
226
- const cost = hit ? round(costOf(buckets, hit.price)) : undefined
233
+ const offPeak = hit?.offPeakFactor !== undefined ? day.offPeak?.[key] : undefined
234
+ const cost = hit
235
+ ? round(costOf(buckets, hit.price) - (offPeak ? costOf(offPeak, hit.price) * (1 - hit.offPeakFactor) : 0))
236
+ : undefined
227
237
  if (hit) {
228
238
  priced = true
229
239
  sources.add(hit.source)
package/lib/pricing.js CHANGED
@@ -7,12 +7,13 @@
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, realpathSync } from 'node:fs'
10
+ import { execFile } from 'node:child_process'
11
+ import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
11
12
  import { homedir } from 'node:os'
12
13
  import { dirname, join } from 'node:path'
13
14
  import { pathToFileURL } from 'node:url'
14
- import { priceFor, splitRoute } from './ledger.js'
15
- import { staticPriceFor } from './catalog.js'
15
+ import { billedToDeepseek, priceFor, splitRoute } from './ledger.js'
16
+ import { DEEPSEEK_OFF_PEAK, isDeepseekOffPeak, staticPriceFor } from './catalog.js'
16
17
 
17
18
  const PI_AI_REL = join('@earendil-works', 'pi-ai', 'dist', 'models.generated.js')
18
19
  /** Fallback CNY-per-USD rate when the user leaves the setting blank. */
@@ -25,26 +26,64 @@ const DSH_PACKAGE = join('@deepseek-ai', 'dsh')
25
26
  /**
26
27
  * Where a globally installed `@deepseek-ai/dsh` (the web / CLI profile) may
27
28
  * 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
+ * prefix of the node running us, npm's Windows prefix (`%APPDATA%\npm`),
30
+ * pnpm's global store, and every node a version manager (nvm, nvm-windows,
31
+ * fnm, volta) installed.
29
32
  */
30
33
  export function globalDshDirs(env = process.env, home = safeHome(), execPath = process.execPath) {
31
34
  const prefixes = [env.npm_config_prefix, env.NPM_CONFIG_PREFIX, env.PREFIX]
32
35
  if (home) prefixes.push(join(home, '.npm-global'), join(home, '.npm-packages'), join(home, '.local'))
33
- if (execPath) prefixes.push(dirname(dirname(execPath)))
36
+ if (execPath) prefixes.push(dirname(dirname(execPath)), dirname(execPath))
37
+ if (env.APPDATA) prefixes.push(join(env.APPDATA, 'npm'))
34
38
  prefixes.push('/usr/local', '/usr', '/opt/homebrew')
39
+ // Version managers keep one prefix per installed node; DSH may sit under any of them.
40
+ const nvmDir = env.NVM_DIR || (home ? join(home, '.nvm') : undefined)
41
+ if (nvmDir) for (const v of safeReaddir(join(nvmDir, 'versions', 'node'))) prefixes.push(join(nvmDir, 'versions', 'node', v))
42
+ if (env.NVM_HOME) for (const v of safeReaddir(env.NVM_HOME)) prefixes.push(join(env.NVM_HOME, v))
43
+ const fnmDirs = [env.FNM_DIR, home && join(home, '.local', 'share', 'fnm'), home && join(home, '.fnm'), home && join(home, 'Library', 'Application Support', 'fnm'), env.APPDATA && join(env.APPDATA, 'fnm')]
44
+ for (const fnm of fnmDirs) {
45
+ if (!fnm) continue
46
+ for (const v of safeReaddir(join(fnm, 'node-versions'))) prefixes.push(join(fnm, 'node-versions', v, 'installation'))
47
+ }
35
48
  const dirs = []
36
49
  for (const prefix of prefixes) {
37
50
  if (!prefix) continue
38
51
  // POSIX prefixes keep packages under lib/; Windows prefixes keep them at the top.
39
52
  dirs.push(join(prefix, 'lib', 'node_modules', DSH_PACKAGE), join(prefix, 'node_modules', DSH_PACKAGE))
40
53
  }
41
- const pnpmHome = env.PNPM_HOME || (home ? join(home, '.local', 'share', 'pnpm') : undefined)
42
- if (pnpmHome) {
54
+ // Volta installs each global package into its own image.
55
+ const volta = env.VOLTA_HOME || (home ? join(home, '.volta') : undefined)
56
+ if (volta) {
57
+ const image = join(volta, 'tools', 'image', 'packages', DSH_PACKAGE)
58
+ dirs.push(join(image, 'lib', 'node_modules', DSH_PACKAGE), join(image, 'node_modules', DSH_PACKAGE))
59
+ }
60
+ const pnpmHomes = [env.PNPM_HOME, home && join(home, '.local', 'share', 'pnpm'), home && join(home, 'Library', 'pnpm'), env.LOCALAPPDATA && join(env.LOCALAPPDATA, 'pnpm')]
61
+ for (const pnpmHome of pnpmHomes) {
62
+ if (!pnpmHome) continue
43
63
  for (const store of safeReaddir(join(pnpmHome, 'global'))) dirs.push(join(pnpmHome, 'global', store, 'node_modules', DSH_PACKAGE))
44
64
  }
45
65
  return dirs
46
66
  }
47
67
 
68
+ /**
69
+ * Last resort for an install no guess above covers: ask npm where its global
70
+ * packages live (`npm root -g`). Resolves to the dsh package dir or undefined.
71
+ */
72
+ export function npmGlobalDshDir({ run = execFile, timeoutMs = 8000 } = {}) {
73
+ return new Promise(resolve => {
74
+ try {
75
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'
76
+ // npm.cmd is a batch file: Node only runs it through a shell.
77
+ run(npm, ['root', '-g'], { timeout: timeoutMs, windowsHide: true, shell: process.platform === 'win32' }, (error, stdout) => {
78
+ const root = String(stdout ?? '').trim()
79
+ resolve(error || !root ? undefined : join(root, DSH_PACKAGE))
80
+ })
81
+ } catch {
82
+ resolve(undefined)
83
+ }
84
+ })
85
+ }
86
+
48
87
  function safeHome() {
49
88
  try { return homedir() } catch { return undefined }
50
89
  }
@@ -100,6 +139,36 @@ export function findPiCatalogFile(bases = defaultBases()) {
100
139
  return undefined
101
140
  }
102
141
 
142
+ /**
143
+ * The version of the `@deepseek-ai/dsh` package this host runs from, read
144
+ * from its package.json (the package itself, or one found in a
145
+ * node_modules on the way up), or undefined when none is found.
146
+ */
147
+ export function findDshVersion(bases = defaultBases()) {
148
+ const seen = new Set()
149
+ const read = file => {
150
+ try {
151
+ const pkg = JSON.parse(readFileSync(file, 'utf8'))
152
+ return pkg?.name === '@deepseek-ai/dsh' && typeof pkg.version === 'string' ? pkg.version : undefined
153
+ } catch {
154
+ return undefined
155
+ }
156
+ }
157
+ for (const base of bases) {
158
+ let dir = base
159
+ for (let depth = 0; depth < 8 && dir; depth += 1) {
160
+ if (seen.has(dir)) break
161
+ seen.add(dir)
162
+ const version = read(join(dir, 'package.json')) ?? read(join(dir, 'node_modules', DSH_PACKAGE, 'package.json'))
163
+ if (version) return version
164
+ const parent = dirname(dir)
165
+ if (parent === dir) break
166
+ dir = parent
167
+ }
168
+ }
169
+ return undefined
170
+ }
171
+
103
172
  function safeExists(path) {
104
173
  try { return existsSync(path) } catch { return false }
105
174
  }
@@ -155,6 +224,8 @@ export function customPrice(cfg) {
155
224
  /**
156
225
  * Build the resolver the ledger prices each `provider/model` route with.
157
226
  * Returns rows already converted to `currency`, tagged with their source.
227
+ * Listed prices of DeepSeek routes are peak prices, so those hits carry the
228
+ * off-peak discount; prices the user typed are taken as they are.
158
229
  */
159
230
  export function makeResolver({ cfg, models, currency = cfg.currency ?? 'CNY' }) {
160
231
  const rate = typeof cfg.exchangeRate === 'number' && cfg.exchangeRate > 0 ? cfg.exchangeRate : DEFAULT_RATE
@@ -171,16 +242,17 @@ export function makeResolver({ cfg, models, currency = cfg.currency ?? 'CNY' })
171
242
  if (table && mode === 'auto') return { price: table, source: 'table' }
172
243
  if (custom && (mode === 'auto' || mode === 'custom')) return { price: toDisplay(custom, custom.currency), source: 'custom' }
173
244
  if (mode === 'custom') return undefined
245
+ const offPeak = billedToDeepseek(key) ? { offPeakFactor: DEEPSEEK_OFF_PEAK.factor } : {}
174
246
  const fromCatalog = catalogCost(models, provider, model)
175
- if (fromCatalog) return { price: toDisplay(fromCatalog, 'USD'), source: 'catalog' }
247
+ if (fromCatalog) return { price: toDisplay(fromCatalog, 'USD'), source: 'catalog', ...offPeak }
176
248
  const fallback = staticPriceFor(provider, model)
177
- if (fallback) return { price: toDisplay(fallback, fallback.currency), source: 'static' }
249
+ if (fallback) return { price: toDisplay(fallback, fallback.currency), source: 'static', ...offPeak }
178
250
  return undefined
179
251
  }
180
252
  }
181
253
 
182
254
  /** What the settings page shows about the route in use: the listed price and where it comes from. */
183
- export function describeRoute({ cfg, models, route }) {
255
+ export function describeRoute({ cfg, models, route, now = Date.now() }) {
184
256
  if (!route?.model) return undefined
185
257
  const resolve = makeResolver({ cfg, models })
186
258
  const hit = resolve(`${route.provider ?? ''}/${route.model}`.replace(/^\//u, ''))
@@ -190,6 +262,13 @@ export function describeRoute({ cfg, models, route }) {
190
262
  model: route.model,
191
263
  name: listed?.name,
192
264
  listed: listed ? { input: listed.input, cacheRead: listed.cacheRead, cacheWrite: listed.cacheWrite, output: listed.output, currency: listed.currency } : undefined,
193
- effective: hit ? { ...hit.price, currency: cfg.currency ?? 'CNY', source: hit.source } : undefined,
265
+ effective: hit
266
+ ? {
267
+ ...hit.price,
268
+ currency: cfg.currency ?? 'CNY',
269
+ source: hit.source,
270
+ ...(hit.offPeakFactor !== undefined ? { offPeakFactor: hit.offPeakFactor, offPeakNow: isDeepseekOffPeak(now) } : {}),
271
+ }
272
+ : undefined,
194
273
  }
195
274
  }
package/lib/system.js CHANGED
@@ -3,6 +3,8 @@
3
3
  * when no DSH window is listening) and bringing the DSH window forward.
4
4
  */
5
5
  import { spawn } from 'node:child_process'
6
+ import { existsSync, mkdirSync, readdirSync, unlinkSync } from 'node:fs'
7
+ import { delimiter, join, posix } from 'node:path'
6
8
 
7
9
  function run(file, args, options = {}) {
8
10
  return new Promise(resolve => {
@@ -75,13 +77,67 @@ function windowsToast(xml) {
75
77
  return run(powershell(), ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-EncodedCommand', encoded])
76
78
  }
77
79
 
80
+ /** POSIX shell single-quoted literal. */
81
+ const sh = text => `'${String(text).replace(/'/gu, "'\\''")}'`
82
+
83
+ let notifierPath
84
+ /**
85
+ * `terminal-notifier` (Homebrew), when installed. Unlike `display notification`
86
+ * (attributed to Script Editor, whose click only opens Script Editor), it runs
87
+ * a command when its notification is clicked, which is how a click reaches the
88
+ * session it is about.
89
+ */
90
+ export function terminalNotifier(env = process.env, exists = existsSync) {
91
+ if (notifierPath !== undefined && env === process.env) return notifierPath || undefined
92
+ const dirs = [...String(env.PATH ?? '').split(delimiter), '/opt/homebrew/bin', '/usr/local/bin']
93
+ const found = dirs.filter(Boolean).map(dir => join(dir, 'terminal-notifier')).find(file => {
94
+ try { return exists(file) } catch { return false }
95
+ })
96
+ if (env === process.env) notifierPath = found ?? ''
97
+ return found
98
+ }
99
+
100
+ /** A session id as a file name: anything outside [A-Za-z0-9._-] is dropped. */
101
+ const clickName = id => String(id).replace(/[^\w.-]/gu, '')
102
+
103
+ /**
104
+ * The shell command a clicked macOS notification runs: it drops a file named
105
+ * after the session into `clickDir`, which the host picks up (consumeClicks).
106
+ */
107
+ export function clickCommand(clickDir, sessionId) {
108
+ // A macOS shell command: always '/'-joined, whatever OS builds it (tests run everywhere).
109
+ return `/usr/bin/touch ${sh(posix.join(clickDir, clickName(sessionId)))}`
110
+ }
111
+
112
+ /** Session ids whose notification was clicked since the last call; each file is removed as it is read. */
113
+ export function consumeClicks(clickDir) {
114
+ let names
115
+ try { names = readdirSync(clickDir) } catch { return [] }
116
+ const ids = []
117
+ for (const name of names) {
118
+ try {
119
+ unlinkSync(join(clickDir, name))
120
+ ids.push(name)
121
+ } catch {}
122
+ }
123
+ return ids
124
+ }
125
+
78
126
  /**
79
127
  * Show one native notification.
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).
128
+ * @param {{title: string, body: string, sound?: boolean, onClick?: () => void, webOrigin?: () => string | undefined, state?: string, iconDir?: string, sessionId?: string, clickDir?: string}} n
129
+ * `state` picks the whale's colour and `iconDir` where its PNG is cached (Linux);
130
+ * `sessionId` + `clickDir` make a macOS notification clickable when terminal-notifier is installed.
82
131
  */
83
132
  export async function systemNotify(n) {
84
133
  if (process.platform === 'darwin') {
134
+ const notifier = n.clickDir && n.sessionId ? terminalNotifier() : undefined
135
+ if (notifier) {
136
+ try { mkdirSync(n.clickDir, { recursive: true }) } catch {}
137
+ const args = ['-title', n.title, '-message', n.body, '-execute', clickCommand(n.clickDir, n.sessionId)]
138
+ if (n.sound) args.push('-sound', 'Glass')
139
+ if (await run(notifier, args)) return true
140
+ }
85
141
  const sound = n.sound ? ' sound name "Glass"' : ''
86
142
  return run('/usr/bin/osascript', ['-e', `display notification ${as(n.body)} with title ${as(n.title)}${sound}`])
87
143
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-notify-tray",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "DeepSeek Harness 通知 + 状态栏插件:任务完成、需要输入、需要选择时弹系统通知(macOS / Windows / Linux);macOS 与 Linux(含 UOS、Deepin、麒麟)状态栏常驻小图标,显示任务进度与花费。Windows 没有状态栏,只弹通知。",
5
5
  "keywords": [
6
6
  "deepseek",
@@ -49,7 +49,8 @@
49
49
  "node": ">=20"
50
50
  },
51
51
  "scripts": {
52
- "test": "node --test --test-force-exit test/*.test.js"
52
+ "test": "node --test --test-force-exit test/*.test.js",
53
+ "version": "node scripts/sync-readme-version.mjs && git add README.md README.zh-CN.md"
53
54
  },
54
55
  "dsh": {
55
56
  "bundle": {