dsh-notify-tray 0.1.5 → 0.1.7
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 +12 -8
- package/README.zh-CN.md +12 -8
- package/lib/catalog.js +26 -3
- package/lib/client.js +62 -9
- package/lib/format.js +1 -1
- package/lib/host/context.js +89 -0
- package/lib/host/notify.js +89 -0
- package/lib/host/routes.js +155 -0
- package/lib/host/spend.js +159 -0
- package/lib/host/tray.js +120 -0
- package/lib/index.js +16 -423
- package/lib/ledger.js +15 -5
- package/lib/models-dev.json +2684 -0
- package/lib/notices.js +119 -0
- package/lib/pricing.js +121 -14
- package/lib/quota.js +46 -2
- package/lib/system.js +116 -10
- package/lib/tracker.js +7 -0
- package/lib/tray/linux.js +34 -7
- package/lib/voice.js +19 -1
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
A notification + status-bar plugin for DeepSeek Harness (DSH). Works on macOS, Windows and Linux. It is one npm package that adapts to the OS it is installed on: macOS / Linux get notifications plus the status-bar whale; Windows has no status bar, so it gets notifications only, and its settings page shows no status-bar options.
|
|
6
6
|
|
|
7
|
-
- **System notifications** — when a task finishes, fails, needs approval, needs you to pick an option, or waits for your input, you get a native notification written in the voice of a little whale (e.g. *"🐳 All done! 'Write the weekly report' is finished — come check it out"*). Clicking a notification jumps straight to the session.
|
|
7
|
+
- **System notifications** — when a task finishes, fails, needs approval, needs you to pick an option, or waits for your input, you get a native notification written in the voice of a little whale (e.g. *"🐳 All done! 'Write the weekly report' is finished — come check it out"*). Clicking a notification jumps straight to the session. Each session keeps a single notification (a new one replaces the old); a "needs you" notification is taken back once you answer or approve; and when several tasks finish within a few seconds, the first shows at once and the rest fold into one "n more done".
|
|
8
8
|
- **Status-bar whale** (macOS / Linux) — a small whale lives in your status bar and tells you what's going on through its posture. The drop-down menu lists running tasks, items waiting for you, today's usage and recently finished tasks; click any entry to open that session.
|
|
9
9
|
- **Settings page** — every option can be changed directly on the DSH **Plugins** page (only the options your OS can use are shown), including the API price of the model you're currently using and the plan you subscribe to (Kimi / GLM / OpenCode / MiMo / Gemini / Grok / Claude / GPT / MiniMax / DeepSeek or custom). Balance and remaining quota are fetched automatically where the provider exposes an API; anything else can be filled in by hand.
|
|
10
10
|
|
|
@@ -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.
|
|
30
|
+
> **⚠️ To get the latest release, include the version number**, e.g. `dsh-notify-tray@0.1.7` (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.
|
|
34
|
+
Open DSH **Plugins → Add plugin**, type `dsh-notify-tray@0.1.7` (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.
|
|
40
|
+
dsh plugin --profile desktop add dsh-notify-tray@0.1.7
|
|
41
41
|
# Or the web / CLI profile
|
|
42
|
-
dsh plugin --profile web add dsh-notify-tray@0.1.
|
|
42
|
+
dsh plugin --profile web add dsh-notify-tray@0.1.7
|
|
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.
|
|
57
|
+
> dsh plugin --profile desktop add dsh-notify-tray@0.1.7
|
|
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.
|
|
@@ -98,13 +98,13 @@ Every option can be changed on DSH's **Plugins → Whale Notify Station** page,
|
|
|
98
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 |
|
|
99
99
|
| `currency` | `CNY` | Display currency |
|
|
100
100
|
| `balancePollMinutes` | `5` | How often (minutes) to refresh the DeepSeek account balance |
|
|
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` |
|
|
101
|
+
| `priceSource` | `auto` | Which price to estimate with: `auto` (price table → custom price → DSH's built-in model catalog → plugin's built-in prices → a bundled [models.dev](https://models.dev) snapshot), `catalog`, `custom` |
|
|
102
102
|
| `customInput` / `customCacheRead` / `customOutput` | empty | Custom price per million tokens; leave empty to disable |
|
|
103
103
|
| `customPriceCurrency` | `CNY` | Currency of the custom price |
|
|
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` (
|
|
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, then a [models.dev](https://models.dev) price snapshot bundled with each release, 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, and an answered question's notification is taken back.
|
|
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
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
DeepSeek Harness(DSH)的通知 + 状态栏插件,支持 macOS、Windows、Linux。同一个 npm 包,装上后按系统自动区分:macOS / Linux 有通知 + 状态栏小鲸鱼;Windows 没有状态栏,只有通知,设置页里也不会出现状态栏相关的选项。
|
|
6
6
|
|
|
7
|
-
- **系统通知**:任务完成、任务失败、需要批准、需要你选择、需要你输入时弹系统通知,文案是小鲸鱼的口吻(比如「🐳
|
|
7
|
+
- **系统通知**:任务完成、任务失败、需要批准、需要你选择、需要你输入时弹系统通知,文案是小鲸鱼的口吻(比如「🐳 搞定啦~『写周报』做完了!快来验收」)。点击通知会跳到对应会话。每个会话只留一条通知(新的替换旧的);问题答完、批准完后,「需要你」的那条会自动收回;几个任务前后脚完成时,第一个照常弹,后面几秒内完成的合成一条「又搞定 n 个」。
|
|
8
8
|
- **状态栏小鲸鱼**(macOS / Linux):状态栏常驻一只小鲸鱼,用姿态告诉你现在的状态;下拉菜单里是正在运行的任务、等你处理的事项、今日用量和最近结束的任务,点一下就能跳到对应会话。
|
|
9
9
|
- **插件设置页**:所有选项都能在 DSH「插件」页里直接改(只显示当前系统用得上的选项),包括当前模型的 API 价格和你买的套餐(Kimi / GLM / OpenCode / MiMo / Gemini / Grok / Claude / GPT / MiniMax / DeepSeek 或自定义),能从接口拿到的余额 / 剩余额度自动拿,拿不到的手填。
|
|
10
10
|
|
|
@@ -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.
|
|
30
|
+
> **⚠️ 想装最新版,请带上版本号**,例如 `dsh-notify-tray@0.1.7`(最新版本号见 [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.
|
|
34
|
+
打开 DSH「插件 → 添加插件」,输入框里填 `dsh-notify-tray@0.1.7`(带上版本号),点「安装」。
|
|
35
35
|
|
|
36
36
|
**方式二:命令行**
|
|
37
37
|
|
|
38
38
|
```sh
|
|
39
39
|
# 桌面版(App 内置的 dsh 命令),带上版本号才能装到最新版
|
|
40
|
-
dsh plugin --profile desktop add dsh-notify-tray@0.1.
|
|
40
|
+
dsh plugin --profile desktop add dsh-notify-tray@0.1.7
|
|
41
41
|
# 或者 Web / 命令行 profile
|
|
42
|
-
dsh plugin --profile web add dsh-notify-tray@0.1.
|
|
42
|
+
dsh plugin --profile web add dsh-notify-tray@0.1.7
|
|
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.
|
|
57
|
+
> dsh plugin --profile desktop add dsh-notify-tray@0.1.7
|
|
58
58
|
> ```
|
|
59
59
|
>
|
|
60
60
|
> 另外,官方 npm 源连不上时 DSH 会退到 npmmirror(淘宝镜像),镜像比官方源晚一点同步,刚发的新版可能要等几分钟才到。
|
|
@@ -98,13 +98,13 @@ dsh plugin --profile web add dsh-notify-tray@0.1.5
|
|
|
98
98
|
| `spendSource` | `auto` | 有 DeepSeek 账户余额时用余额扣费,否则按价格估算。`auto` 下余额扣费落后于 DeepSeek 模型的估算时(平台扣费有延迟),先按估算显示,余额追上后再改回余额;其它平台模型的花费始终按估算加上 |
|
|
99
99
|
| `currency` | `CNY` | 显示币种 |
|
|
100
100
|
| `balancePollMinutes` | `5` | DeepSeek 账户余额刷新间隔(分钟) |
|
|
101
|
-
| `priceSource` | `auto` | 估算用哪个价:`auto`(价格表 → 自定义价 → DSH 自带的模型目录价 →
|
|
101
|
+
| `priceSource` | `auto` | 估算用哪个价:`auto`(价格表 → 自定义价 → DSH 自带的模型目录价 → 插件内置价 → 随插件发布的 [models.dev](https://models.dev) 价格快照)、`catalog`、`custom` |
|
|
102
102
|
| `customInput` / `customCacheRead` / `customOutput` | 空 | 自定义价,每百万 token;留空不用 |
|
|
103
103
|
| `customPriceCurrency` | `CNY` | 自定义价的币种 |
|
|
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
|
|
107
|
+
「当前 API 价格」区域会显示你正在用的模型(provider / model)和它的目录价:DSH 的 pi-ai 适配器自带一份模型目录(Claude、GPT、Gemini、Grok、Groq、Kimi、GLM、MiMo、MiniMax、OpenCode Go、DeepSeek 等),插件直接读它,拿不到的再用内置价、随每个版本打包的 [models.dev](https://models.dev) 价格快照,或你填的自定义价。桌面版和 `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)
|
|
@@ -313,6 +328,14 @@ export function planOf(providerId, planId) {
|
|
|
313
328
|
* Static fallback price for a model: the route's catalog provider first, then
|
|
314
329
|
* any provider listing that model id (exact, then prefix).
|
|
315
330
|
*/
|
|
331
|
+
/**
|
|
332
|
+
* Cache writes cost more than plain input at some providers; a static row
|
|
333
|
+
* without its own `cacheWrite` is priced at input × this. Anthropic bills
|
|
334
|
+
* 5-minute cache writes at 1.25× input.
|
|
335
|
+
*/
|
|
336
|
+
const CACHE_WRITE_FACTOR = { claude: 1.25 }
|
|
337
|
+
const cacheWriteOf = (row, id) => row.cacheWrite ?? Math.round(row.input * (CACHE_WRITE_FACTOR[id] ?? 1) * 1e6) / 1e6
|
|
338
|
+
|
|
316
339
|
export function staticPriceFor(route, model) {
|
|
317
340
|
if (!model) return undefined
|
|
318
341
|
const preferred = providerForRoute(route)
|
|
@@ -321,13 +344,13 @@ export function staticPriceFor(route, model) {
|
|
|
321
344
|
const table = providerOf(id)?.prices
|
|
322
345
|
if (!table) continue
|
|
323
346
|
const hit = table[model] ?? table[model.toLowerCase()]
|
|
324
|
-
if (hit) return { ...hit, cacheWrite: hit
|
|
347
|
+
if (hit) return { ...hit, cacheWrite: cacheWriteOf(hit, id), provider: id }
|
|
325
348
|
}
|
|
326
349
|
for (const id of order) {
|
|
327
350
|
const table = providerOf(id)?.prices
|
|
328
351
|
if (!table) continue
|
|
329
352
|
const key = Object.keys(table).filter(k => model.startsWith(k)).sort((a, b) => b.length - a.length)[0]
|
|
330
|
-
if (key) return { ...table[key], cacheWrite: table[key]
|
|
353
|
+
if (key) return { ...table[key], cacheWrite: cacheWriteOf(table[key], id), provider: id }
|
|
331
354
|
}
|
|
332
355
|
return undefined
|
|
333
356
|
}
|
|
@@ -399,7 +422,7 @@ export function planView(cfg, quota) {
|
|
|
399
422
|
remainingSource: manualRemaining ? 'manual' : fetched ? 'api' : undefined,
|
|
400
423
|
resetAt: cfg.planResetAt?.trim() || fetched?.resetAt,
|
|
401
424
|
lines: fetched?.lines ?? [],
|
|
402
|
-
fetch: quota ? { ok: quota.ok, at: quota.at, error: quota.ok ? undefined : quota.error } : undefined,
|
|
425
|
+
fetch: quota ? { ok: quota.ok, at: quota.at, error: quota.ok ? undefined : quota.error, attempts: quota.attempts } : undefined,
|
|
403
426
|
canFetch: Boolean(spec),
|
|
404
427
|
fetchKind: spec?.kind,
|
|
405
428
|
fetchUrl: spec?.url,
|
package/lib/client.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
// dsh-notify-tray, browser half (hand-written in DSH's client module format,
|
|
2
2
|
// so no build step is needed).
|
|
3
3
|
//
|
|
4
|
-
// Polls the host's `notify-tray/state` route
|
|
5
|
-
// each new
|
|
6
|
-
//
|
|
4
|
+
// Polls the host's `notify-tray/state` route (its light `lite=1` form), shows
|
|
5
|
+
// a native Notification for each new notice (completed / failed / approval /
|
|
6
|
+
// choice / input; one per session, closed again once a question is answered)
|
|
7
|
+
// and opens the session when a notification — or a tray menu row — is
|
|
8
|
+
// clicked. In the
|
|
7
9
|
// desktop app these notifications are OS-native and attributed to
|
|
8
10
|
// "DeepSeek Harness".
|
|
9
11
|
window.__ModuleLoader__.load({
|
|
@@ -14,6 +16,7 @@ window.__ModuleLoader__.load({
|
|
|
14
16
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
|
|
15
17
|
|
|
16
18
|
var ROUTE = 'notify-tray/state'
|
|
19
|
+
var RAISE_ROUTE = 'notify-tray/raise'
|
|
17
20
|
var POLL_MS = 2000
|
|
18
21
|
var SEEN_KEY = 'dsh-notify-tray:seen'
|
|
19
22
|
|
|
@@ -140,6 +143,8 @@ window.__ModuleLoader__.load({
|
|
|
140
143
|
spendNone: '还没有花费记录',
|
|
141
144
|
currentModelNone: '还没看到请求,先聊一句就知道了。',
|
|
142
145
|
perMillion: '每百万',
|
|
146
|
+
offPeakNow: '现在是空闲时段,按半价估算',
|
|
147
|
+
offPeakLater: '空闲时段(北京时间工作日 9–12、14–18 点以外)按半价估算',
|
|
143
148
|
noListedPrice: '目录里没有这个模型的价格,可在「高级设置」里填自定义单价。',
|
|
144
149
|
catalogOff: 'DSH 自带的模型目录没找到,只有插件内置价可用。可设置环境变量 DSH_NOTIFY_TRAY_PI_AI 指向 DSH 的安装目录后重启。',
|
|
145
150
|
myPlan: '我的套餐',
|
|
@@ -160,6 +165,8 @@ window.__ModuleLoader__.load({
|
|
|
160
165
|
refreshing: '刷新中…',
|
|
161
166
|
updatedAt: '更新',
|
|
162
167
|
fetchFailed: '获取失败',
|
|
168
|
+
attemptSkipped: '没用上',
|
|
169
|
+
attemptFailed: '失败',
|
|
163
170
|
noFetchYet: '还没获取过',
|
|
164
171
|
resetsAt: '重置',
|
|
165
172
|
remainingShort: '剩余',
|
|
@@ -242,6 +249,7 @@ window.__ModuleLoader__.load({
|
|
|
242
249
|
srcCustom: '自定义价',
|
|
243
250
|
srcCatalog: '目录价',
|
|
244
251
|
srcStatic: '内置价',
|
|
252
|
+
srcModelsDev: 'models.dev 价',
|
|
245
253
|
overridden: '已修改',
|
|
246
254
|
reset: '恢复默认',
|
|
247
255
|
readOnly: '本部署的设置为只读。',
|
|
@@ -289,6 +297,8 @@ window.__ModuleLoader__.load({
|
|
|
289
297
|
spendNone: 'No spend recorded yet',
|
|
290
298
|
currentModelNone: 'No request seen yet — send one message and it shows up here.',
|
|
291
299
|
perMillion: 'per million',
|
|
300
|
+
offPeakNow: 'Off-peak now: estimated at half price',
|
|
301
|
+
offPeakLater: 'Off-peak (outside 9–12 and 14–18 Beijing time on weekdays) is estimated at half price',
|
|
292
302
|
noListedPrice: 'No catalog price for this model; set a custom price under Advanced.',
|
|
293
303
|
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
304
|
myPlan: 'My plan',
|
|
@@ -309,6 +319,8 @@ window.__ModuleLoader__.load({
|
|
|
309
319
|
refreshing: 'Refreshing…',
|
|
310
320
|
updatedAt: 'updated',
|
|
311
321
|
fetchFailed: 'Fetch failed',
|
|
322
|
+
attemptSkipped: 'not used',
|
|
323
|
+
attemptFailed: 'failed',
|
|
312
324
|
noFetchYet: 'Not fetched yet',
|
|
313
325
|
resetsAt: 'resets',
|
|
314
326
|
remainingShort: 'Remaining',
|
|
@@ -391,6 +403,7 @@ window.__ModuleLoader__.load({
|
|
|
391
403
|
srcCustom: 'custom',
|
|
392
404
|
srcCatalog: 'catalog',
|
|
393
405
|
srcStatic: 'built-in',
|
|
406
|
+
srcModelsDev: 'models.dev',
|
|
394
407
|
overridden: 'Changed',
|
|
395
408
|
reset: 'Reset to default',
|
|
396
409
|
readOnly: 'This deployment stores settings read-only.',
|
|
@@ -472,7 +485,13 @@ window.__ModuleLoader__.load({
|
|
|
472
485
|
fetchJson(CATALOG_ROUTE).then(body => { if (body) { live.catalog = body; publishLive() } }).catch(() => {})
|
|
473
486
|
}
|
|
474
487
|
function loadState() {
|
|
475
|
-
|
|
488
|
+
// Sending back the rev we hold: an unchanged snapshot comes back as `unchanged` only.
|
|
489
|
+
const rev = live.state && live.state.rev ? '&rev=' + encodeURIComponent(live.state.rev) : ''
|
|
490
|
+
return fetchJson(ROUTE + '?after=-2' + rev).then(body => {
|
|
491
|
+
if (!body || body.unchanged) return
|
|
492
|
+
live.state = body
|
|
493
|
+
publishLive()
|
|
494
|
+
}).catch(() => {})
|
|
476
495
|
}
|
|
477
496
|
// Test seam: lets a test drive the loaders without React effects.
|
|
478
497
|
const currentPlatform = () => normalizePlatform(live.state && live.state.platform) || guessPlatform()
|
|
@@ -630,7 +649,7 @@ window.__ModuleLoader__.load({
|
|
|
630
649
|
const SYM = { CNY: '¥', USD: '$' }
|
|
631
650
|
const fmt = (n, currency) => (typeof n === 'number' ? `${SYM[currency] ?? ''}${Number.isInteger(n) ? n : (n < 1 ? n.toFixed(4).replace(/0+$/u, '').replace(/\.$/u, '') : n.toFixed(2))}` : '—')
|
|
632
651
|
const priceLine = (p, currency) => `${fmt(p.input, currency)} / ${fmt(p.cacheRead, currency)} / ${fmt(p.output, currency)}`
|
|
633
|
-
const SOURCE_KEY = { table: 'srcTable', custom: 'srcCustom', catalog: 'srcCatalog', static: 'srcStatic' }
|
|
652
|
+
const SOURCE_KEY = { table: 'srcTable', custom: 'srcCustom', catalog: 'srcCatalog', static: 'srcStatic', modelsDev: 'srcModelsDev' }
|
|
634
653
|
const clock = at => {
|
|
635
654
|
const d = new Date(at)
|
|
636
655
|
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
|
|
@@ -650,6 +669,7 @@ window.__ModuleLoader__.load({
|
|
|
650
669
|
if (price) {
|
|
651
670
|
const source = SOURCE_KEY[price.source] ? t(SOURCE_KEY[price.source]) : price.source
|
|
652
671
|
detail.push(h('div', { key: 'price', style: S.muted }, `${priceLine(price, price.currency)} ${t('perMillion')} · ${source}`))
|
|
672
|
+
if (price.offPeakFactor !== undefined) detail.push(h('div', { key: 'offpeak', style: S.muted }, t(price.offPeakNow ? 'offPeakNow' : 'offPeakLater')))
|
|
653
673
|
} else if (!pricing.listed) {
|
|
654
674
|
detail.push(h('div', { key: 'nolisted', style: S.muted }, t('noListedPrice')))
|
|
655
675
|
}
|
|
@@ -667,7 +687,15 @@ window.__ModuleLoader__.load({
|
|
|
667
687
|
/** One line on the last quota fetch, plus the fetched lines. */
|
|
668
688
|
function QuotaStatus({ t, plan }) {
|
|
669
689
|
if (!plan || !plan.fetch) return h('p', { style: S.hint }, t('noFetchYet'))
|
|
670
|
-
if (!plan.fetch.ok)
|
|
690
|
+
if (!plan.fetch.ok) {
|
|
691
|
+
// What was tried, in order, and what to fix (lib/quota.js runQuotaPlan).
|
|
692
|
+
const tried = (plan.fetch.attempts || []).filter(a => a.outcome !== 'ok')
|
|
693
|
+
return h('div', null,
|
|
694
|
+
h('p', { style: { ...S.hint, ...S.error } }, `${t('fetchFailed')}(${clock(plan.fetch.at)}):${plan.fetch.error}`),
|
|
695
|
+
tried.length > 1 || tried.some(a => a.hint)
|
|
696
|
+
? h('ul', { style: S.lines }, tried.map((a, i) => h('li', { key: i }, `${a.label}:${a.outcome === 'skipped' ? t('attemptSkipped') : t('attemptFailed')} · ${a.hint || a.detail}`)))
|
|
697
|
+
: null)
|
|
698
|
+
}
|
|
671
699
|
const bits = []
|
|
672
700
|
if (plan.remaining !== undefined) bits.push(`${t('remainingShort')} ${plan.remaining}`)
|
|
673
701
|
if (plan.resetAt) bits.push(`${String(plan.resetAt)} ${t('resetsAt')}`)
|
|
@@ -884,6 +912,8 @@ window.__ModuleLoader__.load({
|
|
|
884
912
|
var boot
|
|
885
913
|
var stopped = false
|
|
886
914
|
var timer
|
|
915
|
+
/** Focus at the previous poll: a window that just came forward claims the session a system toast announced. */
|
|
916
|
+
var wasFocused = false
|
|
887
917
|
|
|
888
918
|
function open(sessionId) {
|
|
889
919
|
try { window.focus() } catch (e) {}
|
|
@@ -892,20 +922,43 @@ window.__ModuleLoader__.load({
|
|
|
892
922
|
}
|
|
893
923
|
}
|
|
894
924
|
|
|
925
|
+
/** Notifications this window put up, by key (session): the next one for a key replaces it. */
|
|
926
|
+
var shown = {}
|
|
927
|
+
|
|
928
|
+
function withdraw(notice) {
|
|
929
|
+
var n = shown[notice.key]
|
|
930
|
+
if (!n) return
|
|
931
|
+
delete shown[notice.key]
|
|
932
|
+
try { n.close() } catch (e) {}
|
|
933
|
+
}
|
|
934
|
+
|
|
895
935
|
function show(event, state) {
|
|
936
|
+
if (event.kind === 'withdraw') return withdraw(event)
|
|
896
937
|
if (typeof Notification === 'undefined') return
|
|
897
938
|
if (state.suppressWhenFocused && document.hasFocus() && mainSessionId(ctx.sessions) === event.sessionId) return
|
|
898
939
|
// Without permission the host is not told we listen, so it notifies itself.
|
|
899
940
|
if (Notification.permission !== 'granted') return
|
|
900
941
|
if (!claim(boot, event.seq)) return
|
|
901
942
|
var display = event.display || { title: (state.titles[event.type] || 'DeepSeek Harness') + ' · ' + event.title, body: event.body }
|
|
902
|
-
var
|
|
903
|
-
|
|
943
|
+
var key = event.key || event.sessionId
|
|
944
|
+
// Same tag: the OS swaps the session's previous notification for this one.
|
|
945
|
+
var n = new Notification(display.title, { body: display.body, tag: 'dsh-notify-tray:' + key, renotify: true })
|
|
946
|
+
shown[key] = n
|
|
947
|
+
n.onclose = function () { if (shown[key] === n) delete shown[key] }
|
|
948
|
+
n.onclick = function () {
|
|
949
|
+
n.close()
|
|
950
|
+
// The renderer cannot move the OS foreground; the host brings the window forward where it can (Windows).
|
|
951
|
+
fetch(RAISE_ROUTE, { method: 'POST', cache: 'no-store' }).catch(function () {})
|
|
952
|
+
open(event.sessionId)
|
|
953
|
+
}
|
|
904
954
|
}
|
|
905
955
|
|
|
906
956
|
function poll() {
|
|
907
957
|
var granted = typeof Notification !== 'undefined' && Notification.permission === 'granted'
|
|
908
|
-
|
|
958
|
+
var focused = typeof document !== 'undefined' && typeof document.hasFocus === 'function' && document.hasFocus()
|
|
959
|
+
var claimToast = focused && !wasFocused
|
|
960
|
+
wasFocused = focused
|
|
961
|
+
fetch(ROUTE + '?lite=1&after=' + cursor + (granted ? '¬ify=1' : '') + (claimToast ? '&claim=1' : ''), { headers: { accept: 'application/json' }, cache: 'no-store' })
|
|
909
962
|
.then(function (res) { return res.ok ? res.json() : undefined })
|
|
910
963
|
.then(function (state) {
|
|
911
964
|
if (!state || stopped) return
|
package/lib/format.js
CHANGED
|
@@ -18,7 +18,7 @@ export const TITLES = {
|
|
|
18
18
|
|
|
19
19
|
const SYMBOL = { CNY: '¥', USD: '$' }
|
|
20
20
|
/** Where an estimate's price came from (mirrors pricing.js, kept here so this file stays DSH-free). */
|
|
21
|
-
const SOURCE_LABEL = { table: '价格表', custom: '自定义价', catalog: '目录价', static: '内置价' }
|
|
21
|
+
const SOURCE_LABEL = { table: '价格表', custom: '自定义价', catalog: '目录价', static: '内置价', modelsDev: 'models.dev 价' }
|
|
22
22
|
const KIND_LABEL = {
|
|
23
23
|
approval: '待批准',
|
|
24
24
|
choice: '待选择',
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The state every part of the host half shares: live settings, the session
|
|
3
|
+
* tracker, the spend ledger, and the few mutable facts (price catalog, plan
|
|
4
|
+
* quota, web origin…) one part learns and another shows. Each part
|
|
5
|
+
* (tray.js, notify.js, spend.js, routes.js) gets this one object and adds
|
|
6
|
+
* the functions others call on it.
|
|
7
|
+
*/
|
|
8
|
+
import { appendFileSync, mkdirSync } from 'node:fs'
|
|
9
|
+
import { homedir } from 'node:os'
|
|
10
|
+
import { join } from 'node:path'
|
|
11
|
+
import { planView, quotaSpecFor } from '../catalog.js'
|
|
12
|
+
import { buildView } from '../format.js'
|
|
13
|
+
import { Ledger } from '../ledger.js'
|
|
14
|
+
import { describeRoute, makeResolver } from '../pricing.js'
|
|
15
|
+
import { Tracker } from '../tracker.js'
|
|
16
|
+
|
|
17
|
+
export function storageDir() {
|
|
18
|
+
const home = process.env.DSH_HOME?.trim() || join(homedir(), '.dsh')
|
|
19
|
+
return join(home, 'storages', 'dsh-notify-tray')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createHost(ctx, config) {
|
|
23
|
+
// Settings-page fields are volatile references (read with `.get()`) so edits
|
|
24
|
+
// apply live; this proxy reads the current value of every field.
|
|
25
|
+
const cfg = new Proxy({}, {
|
|
26
|
+
get: (_, key) => {
|
|
27
|
+
const value = config?.[key]
|
|
28
|
+
return value !== null && typeof value === 'object' && typeof value.get === 'function' ? value.get() : value
|
|
29
|
+
},
|
|
30
|
+
})
|
|
31
|
+
const dir = storageDir()
|
|
32
|
+
|
|
33
|
+
const host = {
|
|
34
|
+
ctx,
|
|
35
|
+
cfg,
|
|
36
|
+
dir,
|
|
37
|
+
logger: ctx.logger?.('notify-tray') ?? console,
|
|
38
|
+
tracker: new Tracker(),
|
|
39
|
+
ledger: new Ledger({ file: join(dir, 'ledger.json') }),
|
|
40
|
+
account: { usageUrl: undefined },
|
|
41
|
+
/** pi-ai's model catalog (prices), once loaded. */
|
|
42
|
+
pi: undefined,
|
|
43
|
+
/** Latest plan quota reading: { ok, at, data | error, attempts, signature }. */
|
|
44
|
+
quota: undefined,
|
|
45
|
+
/** The web GUI's origin, once the web server is up: where "open DSH" goes when there is no desktop window. */
|
|
46
|
+
webOrigin: () => undefined,
|
|
47
|
+
/** Identifies this host run, so clients reset their cursor after a restart. */
|
|
48
|
+
boot: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
|
49
|
+
lastClientPoll: 0,
|
|
50
|
+
/** Session ids a tray click asked the window to open, consumed by the next poll. */
|
|
51
|
+
focusQueue: [],
|
|
52
|
+
/** The session the latest Windows toast announced: { sessionId, at }. */
|
|
53
|
+
toastPending: undefined,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Set DSH_NOTIFY_TRAY_DEBUG=1 to trace tracked events into storages/dsh-notify-tray/debug.log. */
|
|
57
|
+
host.debug = process.env.DSH_NOTIFY_TRAY_DEBUG
|
|
58
|
+
? (...parts) => {
|
|
59
|
+
try {
|
|
60
|
+
mkdirSync(dir, { recursive: true })
|
|
61
|
+
appendFileSync(join(dir, 'debug.log'), `${new Date().toISOString()} ${parts.map(p => typeof p === 'string' ? p : JSON.stringify(p)).join(' ')}\n`)
|
|
62
|
+
} catch {}
|
|
63
|
+
}
|
|
64
|
+
: () => {}
|
|
65
|
+
|
|
66
|
+
/** Which endpoint the plan's quota comes from, and what identifies one reading as current. */
|
|
67
|
+
host.quotaSpec = () => quotaSpecFor(cfg.planProvider, cfg.planId, cfg.planQuotaUrl)
|
|
68
|
+
host.quotaSignature = () => `${cfg.planProvider}|${cfg.planId}|${cfg.planApiKeyEnv ?? ''}|${cfg.planQuotaUrl ?? ''}`
|
|
69
|
+
/** The route in use: the latest request header anywhere, else DSH's default model selection. */
|
|
70
|
+
host.currentRoute = () => {
|
|
71
|
+
if (host.ledger.lastRoute) return host.ledger.lastRoute
|
|
72
|
+
try {
|
|
73
|
+
const selection = ctx.get('agentDefaultModel')?.currentSelection?.()
|
|
74
|
+
if (selection?.model) return { provider: selection.provider, model: selection.model }
|
|
75
|
+
} catch {}
|
|
76
|
+
return undefined
|
|
77
|
+
}
|
|
78
|
+
host.usage = () => ({
|
|
79
|
+
...host.ledger.summary(makeResolver({ cfg, models: host.pi?.models }), cfg.currency),
|
|
80
|
+
usageUrl: host.account.usageUrl,
|
|
81
|
+
route: host.currentRoute(),
|
|
82
|
+
})
|
|
83
|
+
// A reading taken for another provider / key is never shown as this one's.
|
|
84
|
+
host.plan = () => planView(cfg, host.quota && host.quota.signature === host.quotaSignature() ? host.quota : undefined)
|
|
85
|
+
host.pricing = () => describeRoute({ cfg, models: host.pi?.models, route: host.currentRoute() })
|
|
86
|
+
host.view = () => buildView(host.tracker.summary(), host.usage(), cfg, Date.now(), host.plan())
|
|
87
|
+
|
|
88
|
+
return host
|
|
89
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Notifications: the user's per-type switches, then the notice queue
|
|
3
|
+
* (lib/notices.js: one notification per session, "needs you" taken back once
|
|
4
|
+
* answered, bursts of completions folded), then the channel. The DSH window
|
|
5
|
+
* picks notices up from `GET notify-tray/state`; when no window is listening
|
|
6
|
+
* (or the channel says so) the host shows them through the OS.
|
|
7
|
+
*/
|
|
8
|
+
import { join } from 'node:path'
|
|
9
|
+
import { DONE_HOLD_MS } from '../format.js'
|
|
10
|
+
import { Notices } from '../notices.js'
|
|
11
|
+
import { consumeClicks, systemNotify, systemWithdraw, terminalNotifier } from '../system.js'
|
|
12
|
+
import { speak } from '../voice.js'
|
|
13
|
+
|
|
14
|
+
/** A window that polled within this window counts as "listening". */
|
|
15
|
+
export const CLIENT_FRESH_MS = 8000
|
|
16
|
+
/** The whale's colour on a notification of each kind. */
|
|
17
|
+
const EVENT_STATE = { completed: 'done', failed: 'error', approval: 'attention', choice: 'attention', input: 'attention' }
|
|
18
|
+
export const EVENT_SWITCH = {
|
|
19
|
+
completed: 'notifyCompleted',
|
|
20
|
+
failed: 'notifyFailed',
|
|
21
|
+
approval: 'notifyApproval',
|
|
22
|
+
choice: 'notifyChoice',
|
|
23
|
+
input: 'notifyInput',
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function setupNotifications(ctx, host) {
|
|
27
|
+
const { cfg, logger, tracker, debug } = host
|
|
28
|
+
const burstMs = Number(process.env.DSH_NOTIFY_TRAY_BURST_MS)
|
|
29
|
+
const notices = new Notices(Number.isFinite(burstMs) && burstMs >= 0 ? { windowMs: burstMs } : {})
|
|
30
|
+
host.notices = notices
|
|
31
|
+
ctx.effect(() => () => notices.dispose(), 'notify-tray: notice queue')
|
|
32
|
+
|
|
33
|
+
// A clicked macOS notification (sent through terminal-notifier) drops a file
|
|
34
|
+
// named after its session here; the host opens that session.
|
|
35
|
+
const clickDir = join(host.dir, 'clicks')
|
|
36
|
+
if (process.platform === 'darwin') {
|
|
37
|
+
ctx.effect(() => {
|
|
38
|
+
consumeClicks(clickDir) // stale clicks from an earlier run open nothing
|
|
39
|
+
const timer = setInterval(() => {
|
|
40
|
+
if (!terminalNotifier()) return
|
|
41
|
+
for (const id of consumeClicks(clickDir)) host.onAction(`open:${id}`)
|
|
42
|
+
}, 1000)
|
|
43
|
+
return () => clearInterval(timer)
|
|
44
|
+
}, 'notify-tray: notification clicks')
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
tracker.onEvent(event => {
|
|
48
|
+
debug('event', event)
|
|
49
|
+
// The celebration / error pose expires on its own: refresh once it does.
|
|
50
|
+
if (event.type === 'completed') setTimeout(host.refresh, DONE_HOLD_MS + 200).unref?.()
|
|
51
|
+
if (event.type === 'failed') setTimeout(host.refresh, Math.max(0, cfg.errorHoldMinutes) * 60_000 + 200).unref?.()
|
|
52
|
+
if (cfg[EVENT_SWITCH[event.type]]) notices.push(event)
|
|
53
|
+
})
|
|
54
|
+
// A question answered, an approval decided, a turn over: its "needs you" notification goes.
|
|
55
|
+
tracker.onChange(() => notices.settle(tracker.waitingSessions()))
|
|
56
|
+
|
|
57
|
+
/** Keys the OS currently shows a notification of ours for. */
|
|
58
|
+
const shownBySystem = new Set()
|
|
59
|
+
const systemSide = () => {
|
|
60
|
+
const clientListening = Date.now() - host.lastClientPoll < CLIENT_FRESH_MS
|
|
61
|
+
const channel = cfg.channel
|
|
62
|
+
return channel === 'system' || channel === 'both' || (channel === 'auto' && !clientListening)
|
|
63
|
+
}
|
|
64
|
+
notices.onNotice(notice => {
|
|
65
|
+
if (notice.kind === 'withdraw') {
|
|
66
|
+
if (!shownBySystem.delete(notice.key)) return
|
|
67
|
+
systemWithdraw(notice.key).then(ok => debug('system withdraw', notice.key, ok)).catch(() => {})
|
|
68
|
+
return
|
|
69
|
+
}
|
|
70
|
+
const side = systemSide()
|
|
71
|
+
debug('deliver', { channel: cfg.channel, systemSide: side })
|
|
72
|
+
if (!side) return // the window picks it up from the notice queue
|
|
73
|
+
const said = speak(notice)
|
|
74
|
+
if (process.platform === 'win32') host.toastPending = { sessionId: notice.sessionId, at: Date.now() }
|
|
75
|
+
shownBySystem.add(notice.key)
|
|
76
|
+
systemNotify({
|
|
77
|
+
title: said.title,
|
|
78
|
+
body: said.body,
|
|
79
|
+
sound: cfg.sound,
|
|
80
|
+
webOrigin: host.webOrigin,
|
|
81
|
+
state: EVENT_STATE[notice.type],
|
|
82
|
+
iconDir: join(host.dir, 'icons'),
|
|
83
|
+
sessionId: notice.sessionId,
|
|
84
|
+
key: notice.key,
|
|
85
|
+
clickDir,
|
|
86
|
+
onClick: () => host.onAction(`open:${notice.sessionId}`),
|
|
87
|
+
}).then(ok => debug('system notify', ok)).catch(error => logger.warn('系统通知失败', error))
|
|
88
|
+
})
|
|
89
|
+
}
|