dsh-notify-me 1.14.3 → 1.14.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,50 @@
2
2
 
3
3
  All notable changes to **dsh-notify-me** are documented here.
4
4
 
5
+ ## [1.14.5] — 2026-10-27
6
+
7
+ ### 修复
8
+
9
+ - **外部推送关掉后重试还会继续**:重试链挂在定时器上,旧代码不再复查总开关、也不复查目标还在不在,关掉转发后浏览器仍会往那个地址继续 POST,还把取消掉的投递记成失败。现在每次尝试前复查开关与目标列表,取消的投递不计失败、不写死信;测试按钮仍然照发。
10
+ - **服务码终于在页面侧生效**:`postOnce()` 读的是 `spec.type`,可 `spec` 只是请求体、目标类型在它外面,于是 `externalVerdict()` 的服务码分支(飞书 / Server酱 / WxPusher)从来没跑过,2xx 一律记「已发送」——飞书 token 错了也一样。现在类型正确传入:服务返回 `code != 0`(WxPusher 是 `1000`)记失败并带服务端文案;2xx 但 body 不是该服务的 JSON(空白、代理或 WAF 的网页)记「已送出不可确认」,不再冒充成功。
11
+ - **配置写不进去时页面会说了**:`localStorage.setItem` 抛错(配额、无痕模式、存储被禁)以前被空 `catch` 吞掉,开关看着已保存、刷新就还原。现在记 `configWriteFailed`,`debug().configStored` 给出真假,设置页底部写明「设置没能保存」;写入失败期间后续改动基于内存里的最新配置,不再从旧存储重建。
12
+ - **审批测试通知的按钮 6 秒后失效**:标题标记到点释放时把 `pendingActions` 记录一起删了,可测试通知还留在通知中心,此刻点「同意 / 拒绝」什么都不发生。现在标记照常释放、记录留到 12 秒后与通知一起收。
13
+ - **「从不关闭」对审批通知也作数**:没有按钮的那条路径原来 12 秒必收,选了「从不关闭」照样消失。
14
+ - **通知权限弹窗被关掉后还能再问**:`permAsked` 一旦置真就不再复位,测试按钮从此唤不起授权。现在显式点测试会重新请求一次。
15
+ - **输入监听从模块作用域移进 watchers effect**:客户端插件热重载时不再叠一套指针 / 键盘监听,dispose 能摘干净。
16
+
17
+ ### 测试
18
+
19
+ - 新增 `smoke/host-route-test.mjs` 并接进 `npm test`:不依赖本机 DSH,`lib/index.js` 的 exact 路由、GET 探针、403/405/501 闸门与脚本失败路径在任何平台都会跑。`cordis-host-test.mjs` 里原来那份挪走了,不再躲在「本机没装 DSH 就跳过」后面。
20
+ - 冒烟新增:关掉转发后不再重试且不计失败、2xx 非服务 JSON 记不可确认、服务码错误记失败、写配置失败提示与内存兜底、测试通知按钮活过标题标记、权限被拒后可再次请求。
21
+
22
+ ### 文档
23
+
24
+ - README 中英:审批通知到底什么时候收,按实际行为重写(带按钮的不设自动撤回,桌面端无按钮的按 12 秒收,「从不关闭」时都不收)。
25
+ - README / CONTRIBUTING 的开发自检改成跨平台写法(正斜杠、`sh` 围栏),PowerShell 那条单独标 Windows;硬刷新补上 macOS 的按键。
26
+ - SECURITY 中英:抬窗入口的鉴权口径改成实际的三条(回环对端、回环 `Host`、带 `Origin` 时须同源),并写明 PowerShell 只在 Windows。
27
+ - `docs/listing.md` 版本口径同步到 1.14.5。
28
+
29
+ ## [1.14.4] — 2026-10-27
30
+
31
+ ### 修复
32
+
33
+ - **非 Windows 桌面端点通知又能把窗口抬回前台了**:1.14.0 把抬窗整条换成宿主路由 + `lib/focus-window.ps1`,可这条路由只对 Windows 放行——宿主在非 `win32` 平台直接回 `501`,于是 Linux / macOS 上点通知只剩切会话,窗口留在后台(issue #21)。现在按平台分流:Windows 继续走宿主路由(深链在 `0.2.1-rc.2` 上复测 3/3 无效),其他桌面端恢复 1.5.2 到 1.13.0 的 `dsh://open` 隐藏 iframe——子框架导航绕过壳的顶层 `will-navigate`,交给系统协议注册,由壳的第二次启动处理 restore + show + focus。已在 Arch Linux + Electron 44.7(Plasma 6.8 / Wayland)上实测最小化与后台窗口都能抬回来;macOS 走同一条深链,未实测。
34
+ - **`debug().raiseChannel` 不再依赖第一次点击**:字段改成按平台直接算(Windows `host-route`、其他桌面端 `dsh-deeplink`、浏览器 `window-focus`),装完打开设置页就能看到这台机器会走哪条通道;`raiseLast` 照旧记录最近一次尝试(深链记 `deeplink`,抬没抬起来要肉眼确认,它说不了)。
35
+ - **「测试提醒」不再谎报已发送**:通知权限没给时,`showToast()` 在尝试之前就返回,设置页却照旧写「已发送测试提醒」;现在按钮直接报「通知权限还没给」。Service Worker 那条路径也一样——`showNotification()` 的拒收是异步的,旧代码同步读 `lastToastReject`,异步拒绝落地时页面早写过「已发送」了(issue #18 在唯一能带按钮的那条路径上的残余)。现在测试按钮等这个 promise 落定再报结果。
36
+ - **存储里的配置不是对象时不再让插件整个起不来**:`JSON.parse` 对 `null`、`"x"`、`7` 都照收,随后填默认值的 `in` 判断在非对象上抛错,整个客户端模块挂掉、页面一条提醒都没有。现在只认普通对象,其余一律回落默认值(`lib/client.js` 的 `readConfig()`)。
37
+
38
+ ### 测试
39
+
40
+ - 冒烟在 `desktopRaiseChannel()` 里补上点击前的通道断言(Windows / macOS / Linux 三个 UA),以及 macOS 点通知只插一个 `dsh://open` 帧、不 POST 宿主路由的用例;Windows 的 `iframe` 断言文案改成「Windows 不发深链」。`npm test` 全绿(`cordis-host-test` 在本机无宿主,照旧跳过)。
41
+ - 新增 `corruptStoredConfig()`(`null` / 字符串 / 数字 / 数组四种坏配置都能启动到默认值)、`deniedPermissionFeedback()`(权限被拒时测试按钮报没权限,不再写「已发送」)、`swRefusalFeedback()`(Worker 异步拒收后反馈行是「系统拒收了这条通知」)。两处修复都做过「改回去就挂」的反向验证。
42
+
43
+ ### 文档
44
+
45
+ - README 的抬窗章节改成按平台叙述,`501` 闸门的说明改成「非 Windows 宿主」,已知限制里补上非 Windows 深链的前提(系统注册 `x-scheme-handler/dsh`、壳处理第二次启动)。
46
+ - `lib/index.js` 顶部注释改成按平台表述:这条路由是 Windows 专用的,其他桌面端页面根本不发请求。
47
+ - `docs/listing.md` 版本口径同步到 1.14.4。
48
+
5
49
  ## [1.14.3] — 2026-10-26
6
50
 
7
51
  ### 修复
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 chromoany
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 chromoany
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.en.md CHANGED
@@ -51,12 +51,12 @@ Just the plugin's own panel (the real component, on the same dark theme as the h
51
51
 
52
52
  With the DSH CLI already installed, run in a terminal:
53
53
 
54
- ```powershell
54
+ ```sh
55
55
  # Install and auto-mount into the web profile
56
56
  dsh plugin --profile web add dsh-notify-me
57
57
  ```
58
58
 
59
- Restart `dsh web`, then hard-refresh the page (Ctrl+Shift+R). If you use another Web profile, replace `web` with its actual name.
59
+ Restart `dsh web`, then hard-refresh the page (Ctrl+Shift+R on Windows / Linux, Cmd+Shift+R on macOS). If you use another Web profile, replace `web` with its actual name.
60
60
 
61
61
  ### DSH Desktop
62
62
 
@@ -103,6 +103,8 @@ dsh-notify-me decouples **supervision** from **sitting in front of the screen**:
103
103
 
104
104
  **Reply finished** also covers background sessions. A finished but unread session keeps the `✅ Reply finished ·` title marker until opened. Title markers are independent of the alert policy.
105
105
 
106
+ The first line of the alert body is the session title: the conversation you have open is treated like any other, instead of falling back to "Current conversation"; the placeholder only appears for a brand-new session whose title the host has not published yet.
107
+
106
108
  > **Background** subagent child sessions are **not** alerted about by default: DSH lists each of them as its own session, but they are steps inside the parent conversation's turn, so an alert for them is only noise. The subagent session you have open is not part of this and alerts as usual. Settings → "Ignore subagent sessions" turns the mute off.
107
109
 
108
110
  ## Configure it from DSH Settings
@@ -122,7 +124,7 @@ Open **Settings → Notify me**. The page lays out three blocks — how you get
122
124
  - **When "reply finished" alerts** (default "background only"): background only / quiet for the open one / always — pick one;
123
125
  - **Dismiss the toast automatically** (default "keep while away"): keep while away / always close / never close — pick one;
124
126
  - **Ignore subagent sessions** (on by default): skips background subagent sessions, while the one you have open still alerts;
125
- - **Click a toast to open that conversation** (on by default): switches to that conversation and brings the window forward — on Desktop through native raising — and with several tabs only one is raised.
127
+ - **Click a toast to open that conversation** (on by default): switches to that conversation and brings the window forward — on Windows through the host route, on macOS / Linux through the `dsh://open` deep link — and with several tabs only one is raised.
126
128
 
127
129
  <details>
128
130
  <summary>Edge cases behind the switches</summary>
@@ -130,7 +132,7 @@ Open **Settings → Notify me**. The page lays out three blocks — how you get
130
132
  - **What counts as background**: switching to another app, being covered by another window, or minimizing all count; a window left in front with 3 minutes of no keyboard or mouse input counts too, and `idleMinutes: 0` falls back to looking only at the window.
131
133
  - **When "stay quiet for the conversation on screen" is replayed**: as usual once the window goes to the background or the idle timer fires; if you already handled it, it is dropped.
132
134
  - **The three "reply finished" choices**: "background only" = alert when you are not watching the page; "quiet for the open one" = the one on screen stays silent while other conversations still alert, useful with several open; "always" = never suppress. An old profile's "also alert 'reply finished' while in front" switch migrates to this setting automatically.
133
- - **"Keep while away"**: a toast only closes a few seconds later while you are actually at the page; one that arrived while you were away stays in the notification centre until you come back. Approval toasts with Approve / Reject still follow their 12 s rule and are likewise not withdrawn while you are away.
135
+ - **"Keep while away"**: while you are at the page a plain toast closes itself after a few seconds; one that arrived while you were away stays in the notification centre until you come back. A toast with Approve / Reject carries no auto-dismiss timer — it stays until you click a button, answer the request in the page, or a newer request replaces it; a desktop approval toast, which cannot render buttons, closes after 12 s and is likewise not withdrawn while you are away.
134
136
  - **Fallback for a toast click**: on Desktop a window that will not raise leaves only the conversation switch, with the reason in `debug().raiseLast`; turn this switch off and a click does nothing.
135
137
 
136
138
  </details>
@@ -168,13 +170,13 @@ Off by default. Supports Discord Webhook / Bark / Gotify / Feishu group bots / S
168
170
 
169
171
  #### Runtime & diagnostics
170
172
 
171
- The last block inside Advanced. The page protocol is detected automatically to tell Web from Desktop (DSH Desktop, `dsh-app://`); override it by hand if detection is wrong — on Desktop a toast click goes through the host route for native raising (see [How the Desktop window gets raised](#how-the-desktop-window-gets-raised)) and carries no quick-decision buttons, while Web uses `window.focus()` plus the Service Worker bridge. When the manual override disagrees with detection the page says so.
173
+ The last block inside Advanced. The page protocol is detected automatically to tell Web from Desktop (DSH Desktop, `dsh-app://`); override it by hand if detection is wrong — on Windows a toast click goes through the host route for native raising, on macOS / Linux through the `dsh://open` deep link (see [How the Desktop window gets raised](#how-the-desktop-window-gets-raised)), and it carries no quick-decision buttons, while Web uses `window.focus()` plus the Service Worker bridge. When the manual override disagrees with detection the page says so.
172
174
 
173
175
  <details>
174
176
  <summary>Alert language, Desktop window raising, and reset</summary>
175
177
 
176
178
  - **Alert language**: follow the UI / Simplified Chinese / English — governs the alert copy and the `🔔 …` title marker;
177
- - **Desktop window raising**: since 1.14.0 the host route does the native activation, and raising back a minimized or covered window is measured to work (see [How the Desktop window gets raised](#how-the-desktop-window-gets-raised));
179
+ - **Desktop window raising**: on Windows the host route does the native activation, on macOS / Linux the `dsh://open` deep link does; raising back a minimized or covered window is measured to work on Windows and Linux (see [How the Desktop window gets raised](#how-the-desktop-window-gets-raised));
178
180
  - **Reset settings**: restores every switch and sound setting to the factory defaults (external push targets and chosen custom audio files are kept).
179
181
 
180
182
  </details>
@@ -265,7 +267,7 @@ window.__dshNotifyMe.testExternal() // explicit outbound test to v
265
267
 
266
268
  ## How it works
267
269
 
268
- The reminder core watches session state and pending interactions; approval decisions happen in the page, and Desktop window raising goes through a host route plus native Win32 activation.
270
+ The reminder core watches session state and pending interactions; approval decisions happen in the page, and Desktop window raising goes through a host route plus native Win32 activation on Windows, and through the `dsh://open` deep link on macOS / Linux.
269
271
 
270
272
  <details>
271
273
  <summary>Event sources and graceful degradation</summary>
@@ -288,7 +290,7 @@ Notifications with Approve / Reject buttons can only be raised by a Service Work
288
290
  <details>
289
291
  <summary>Button-toast bookkeeping and window raising</summary>
290
292
 
291
- Each button toast is booked against its interaction key, and one toast claims only one wait; once the request has been answered in the page, or replaced by a newer request, clicking the leftover buttons decides nothing and just closes it quietly. Button toasts stay 12 s (plain ones 5 s) and are withdrawn on their own; if you miss the click, the approval in the conversation is still waiting for you.
293
+ Each button toast is booked against its interaction key, and one toast claims only one wait; once the request has been answered in the page, or replaced by a newer request, clicking the leftover buttons decides nothing and just closes it quietly. Button toasts carry no auto-dismiss timer — they stay until you click or answer; plain toasts close after 5 s, and a desktop approval toast without buttons after 12 s. With "never close" selected neither kind closes itself. If you miss the click, the approval in the conversation is still waiting for you.
292
294
 
293
295
  The "raise a window and switch its conversation" part of a body click is scheduled on the worker half as well: `client.focus()` raises exactly one window (a visible one first) and routes the conversation switch to that window alone, so several DSH tabs never fight over focus or all switch at once.
294
296
 
@@ -296,18 +298,18 @@ The "raise a window and switch its conversation" part of a body click is schedul
296
298
 
297
299
  ### How the Desktop window gets raised
298
300
 
299
- DSH Desktop is a thin Electron shell and its page lives under `dsh-app://app`: DOM `window.focus()` only moves the browsing-context window and never touches the native one, and the shell's `will-navigate` closes the usual page-side exit of firing a `dsh:` URL. The route now is the plugin's own host route — the page POSTs `/__dsh-notify-me/focus-window`, the host spawns `powershell.exe` to run `lib/focus-window.ps1`, which enumerates native windows and activates one adaptively (the `dsh://open` deep link used from 1.5.2 through 1.13.0 retested 3/3 ineffective on `0.2.1-rc.2`, and 1.14.0 deletes it entirely).
301
+ DSH Desktop is a thin Electron shell and its page lives under `dsh-app://app`: DOM `window.focus()` only moves the browsing-context window and never touches the native one, and the shell's `will-navigate` closes the usual page-side exit of firing a `dsh:` URL. The plugin therefore takes two channels by platform: on Windows it uses its own host route — the page POSTs `/__dsh-notify-me/focus-window`, the host spawns `powershell.exe` to run `lib/focus-window.ps1`, which enumerates native windows and activates one adaptively; on macOS / Linux it uses the shell's own `dsh://open` deep link — the page navigates a hidden iframe to `dsh://open` inside the click gesture (subframe navigation bypasses the shell's top-level `will-navigate` interception), which reaches the system protocol registration, and the shell's `second-instance` / `open-url` handler restores, shows, and focuses the main window. On Windows that deep link retested 3/3 ineffective on `0.2.1-rc.2`, so 1.14.0 moved Windows to the host route; on Linux (Plasma 6.8 / Wayland) it is measured to raise a minimized or background window back to the front, and macOS is untested.
300
302
 
301
303
  <details>
302
304
  <summary>The route, the raise order, the measurements, and the security gate</summary>
303
305
 
304
- The shell forwards every path under `dsh-app://app` other than static assets straight to the host HTTP server (with an origin check and the host cookie injected), so that POST is a same-origin request with no CORS involved; the host half (`lib/index.js`) already runs as a child of the Electron main process, so `process.ppid` is the browser process that owns the main window. On a toast click: the page POSTs → the host spawns one `powershell.exe` running `lib/focus-window.ps1 -ProcessId <ppid>` → the script enumerates that pid's visible, owner-less, non-toolwindow top-level windows (preferring class `Chrome_WidgetWin_1`, then the largest area from `GetWindowRect`) → activates adaptively → compares `GetForegroundWindow()` and prints `FOCUSED=1|0` → the host answers `200` / `202`.
306
+ On Windows the host route works like this: the shell forwards every path under `dsh-app://app` other than static assets straight to the host HTTP server (with an origin check and the host cookie injected), so that POST is a same-origin request with no CORS involved; the host half (`lib/index.js`) already runs as a child of the Electron main process, so `process.ppid` is the browser process that owns the main window. On a toast click: the page POSTs → the host spawns one `powershell.exe` running `lib/focus-window.ps1 -ProcessId <ppid>` → the script enumerates that pid's visible, owner-less, non-toolwindow top-level windows (preferring class `Chrome_WidgetWin_1`, then the largest area from `GetWindowRect`) → activates adaptively → compares `GetForegroundWindow()` and prints `FOCUSED=1|0` → the host answers `200` / `202`.
305
307
 
306
- The raise order is adaptive: already in front means do nothing (the common case, zero flicker); minimized means `SW_RESTORE` first; then a synthetic Alt tap (`keybd_event` down/up) grants the calling thread foreground permission before `SetForegroundWindow`; only if all of that fails does it fall back to `SW_MINIMIZE` + `SW_RESTORE`. `SetForegroundWindow` on its own gets refused by the foreground lock — per call, unrelated to `ForegroundLockTimeout`. That also re-reads why the 1.5.2 deep-link approach was "sometimes it works": the times the window did come forward were most likely the OS activating the app on the click itself.
308
+ On Windows the raise order is adaptive: already in front means do nothing (the common case, zero flicker); minimized means `SW_RESTORE` first; then a synthetic Alt tap (`keybd_event` down/up) grants the calling thread foreground permission before `SetForegroundWindow`; only if all of that fails does it fall back to `SW_MINIMIZE` + `SW_RESTORE`. `SetForegroundWindow` on its own gets refused by the foreground lock — per call, unrelated to `ForegroundLockTimeout`. That also re-reads why the 1.5.2 deep-link approach was "sometimes it works": the times the window did come forward were most likely the OS activating the app on the click itself.
307
309
 
308
310
  Measured with `powershell.exe` 5.1 in one round: window in front ×3, minimized with Notepad in front ×3, visible but covered ×3 — all `FOCUSED=1` with the foreground comparison matching and every `IsIconic` flipped back from `true` to `false`; Notepad maximized covering it completely, minimized plus fully covered, and `-ProcessId 0` auto-detection all succeeded too. Script-internal time peaked at 434 ms, process start to exit at 782 ms, well inside the 8 s cap; `pwsh` 7.6 behaved the same in a control round, only ~100 ms slower compiling the `Add-Type` helpers (the script deliberately avoids PowerShell 7 syntax). A pid that does not exist and a pid with no visible window both settle on `FOCUSED=0` with `exit 0`.
309
311
 
310
- Security-wise the plugin opens exactly one exact route. Requests outside the vocabulary are refused: anything other than GET / HEAD / POST answers `405` (including a preflight `OPTIONS`, and it never returns a CORS header), a non-Desktop host (Web, macOS / Linux, plain Node) `501`, and a missing `x-dsh-notify-me-focus: focus` header `403`.
312
+ Security-wise the plugin opens exactly one exact route. Requests outside the vocabulary are refused: anything other than GET / HEAD / POST answers `405` (including a preflight `OPTIONS`, and it never returns a CORS header), a non-Windows host (Web, macOS / Linux, plain Node) `501` (macOS / Linux use the deep link and never reach this route), and a missing `x-dsh-notify-me-focus: focus` header `403`.
311
313
 
312
314
  That header is only a "this came from the page" marker, not the defence — a DNS-rebinding page is same-origin with the address it resolved, so it can send any custom header and triggers no preflight. The real gate is three checks: the peer address must be loopback; `Host` must be a loopback name (`127.0.0.1` / `localhost` / `[::1]`, port optional), because the shell deletes `host` when forwarding and fetch refills it from the loopback URL, while a rebound page still has the attacker's domain in `Host`; and an `Origin`, when present, must be same-origin with that `Host`. Any failure answers `403`, with `reason` set to `bad-remote` / `bad-host` / `cross-origin`. A `GET` returns only `{ok, route, enabled, desktop, platform}`, so after installing you can open it in a browser to confirm the route is there. Calls within 400 ms coalesce into one, and a script that has not answered after 8 s is killed and counted as a failure.
313
315
 
@@ -329,6 +331,7 @@ The cases where it will not raise are the same ones listed under [Known limitati
329
331
  - Quick-decision buttons need a Service Worker: `http://127.0.0.1` and `https` work, `http://192.168.x.x`-style LAN addresses do not; **the Desktop (`dsh-app://`) is tested and cannot register a Service Worker** (the host does not grant the `allowServiceWorkers` privilege), so approval toasts fall back to their buttonless form. When the host renders no notification buttons, the `bridge` field of `debug()` explains why, and nothing else is affected.
330
332
  - Windows caps a toast tag at 64 characters, and Chromium hands the platform the whole `n#<origin>#<tag>` string — the desktop page's `dsh-app://app` alone takes 16. The plugin sizes each tag against the current `location.origin` and, when it does not fit, keeps a readable prefix and swaps the tail for a short hash, so a tag seen through `debug()` may be shortened; if the platform still refuses one, its message lands in `debug().lastToastReject` and the settings test button reports it instead of claiming the toast was sent.
331
333
  - On Desktop (Windows) a toast click can still fail to raise the window: when the target window is owned by a higher integrity level (elevated / UAC), sits on another virtual desktop, has its foreground repeatedly stolen by another process, or is hidden to the tray with `SW_HIDE`, the host script answers `FOCUSED=0` and the route answers `202`, with the conversation switch intact (see [How the Desktop window gets raised](#how-the-desktop-window-gets-raised)).
334
+ - Desktop (macOS / Linux) toast clicks rely on the `dsh://open` deep link: when the system has no `x-scheme-handler/dsh` registration, or the shell has no `second-instance` / `open-url` handling, the window will not raise. Measured to work on Linux; macOS is untested.
332
335
  - macOS: alerts, sound, the title marker and toast-click navigation carry no platform assumptions and work as usual; but DSH Desktop (Electron) system notifications require the app to be signed — an unsigned build simply emits no notification — and whether the official macOS build meets that precondition is untested; notification button rendering on the macOS desktop host is likewise untested (the Windows desktop host is tested and renders none).
333
336
 
334
337
  **Alert content and timing**
@@ -347,15 +350,21 @@ The cases where it will not raise are the same ones listed under [Known limitati
347
350
 
348
351
  ## Development
349
352
 
350
- ```powershell
351
- node --check lib\client.js
352
- node --check lib\index.js
353
- node smoke\smoke-test.cjs # offline state-machine test: three host generations + master switch + zh/en cases + the quick-decision bridge (worker half included) + idle detection and toast self-dismiss + toast tag length handling
354
- node smoke\cordis-host-test.mjs # real-cordis end-to-end (skips when no local DSH installation is found)
355
- powershell -NoProfile -File lib\focus-window.ps1 -ProcessId 0 # manual raise test, the last line should be FOCUSED=1
353
+ ```sh
354
+ node --check lib/client.js
355
+ node --check lib/index.js
356
+ npm test # smoke-test (state machine) + host-route-test (host half) + cordis-host-test
356
357
  npm pack --dry-run # preview the published tarball
357
358
  ```
358
359
 
360
+ `smoke/smoke-test.cjs` is the offline state-machine suite: three host generations + master switch + zh/en cases + the quick-decision bridge (worker half included) + idle detection and toast self-dismiss + toast tag length handling. `smoke/host-route-test.mjs` needs no local DSH and runs the `lib/index.js` route, its probe and the 403/405/501 gate on every platform.
361
+
362
+ When `lib/focus-window.ps1` changes (Windows only), also run it by hand:
363
+
364
+ ```powershell
365
+ powershell -NoProfile -File lib/focus-window.ps1 -ProcessId 0 # the last line should be FOCUSED=1
366
+ ```
367
+
359
368
  `cordis-host-test.mjs` borrows `@deepseek-ai/cordis` from a local DSH installation (it probes the global npm directory, `~/.dsh/profiles/web/node_modules` and the flat fallback `~/.dsh/profiles/node_modules` in turn); in a source checkout with no profile dependencies, point it there with `DSH_CORDIS_PATH=<checkout>/vendor/cordis/lib/index.js`.
360
369
 
361
370
  ## Credits & how contributions land
@@ -370,6 +379,8 @@ npm pack --dry-run # preview the published tarball
370
379
  | <a href="https://github.com/RiZhiZhaoYi"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/RiZhiZhaoYi.png" width="40" height="40" alt="@RiZhiZhaoYi"></a> | [#12](https://github.com/chromoany/dsh-notify-me/issues/12): external notification forwarding (Discord / Bark / Gotify / custom webhook) |
371
380
  | <a href="https://github.com/yuexian7"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/yuexian7.png" width="40" height="40" alt="@yuexian7"></a> | [#17](https://github.com/chromoany/dsh-notify-me/issues/17): the ask for Android delivery, which led to the Feishu / ServerChan / WxPusher targets |
372
381
  | <a href="https://github.com/shrekcg"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/shrekcg.png" width="40" height="40" alt="@shrekcg"></a> | [#16](https://github.com/chromoany/dsh-notify-me/pull/16): away detection (`idleMinutes`), reply-done routing (`donePolicy`), auto-dismiss (`autoDismiss`) |
382
+ | <a href="https://github.com/Donald-Yip"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/Donald-Yip.png" width="40" height="40" alt="@Donald-Yip"></a> | [#18](https://github.com/chromoany/dsh-notify-me/issues/18): the report that a Windows notification tag over the 64-character cap made the platform silently reject the approval test toast |
383
+ | <a href="https://github.com/dunxuan"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/dunxuan.png" width="40" height="40" alt="@dunxuan"></a> | [#20](https://github.com/chromoany/dsh-notify-me/issues/20): the report that alerts for the open session showed a placeholder instead of the session title |
373
384
 
374
385
  Attribution policy: external PRs are landed as maintainer commits — the original commit is not reused and no Co-authored-by trailer is added, so GitHub's contributors graph lists the maintainer only and contributors are credited above.
375
386
 
package/README.md CHANGED
@@ -51,12 +51,12 @@ DSH Web / Desktop 的通知插件,让你敢不开完整访问,也不必一
51
51
 
52
52
  已安装 DSH CLI 的用户,在终端执行:
53
53
 
54
- ```powershell
54
+ ```sh
55
55
  # 安装并自动挂载进 web profile
56
56
  dsh plugin --profile web add dsh-notify-me
57
57
  ```
58
58
 
59
- 重启 `dsh web`,然后硬刷新页面(Ctrl+Shift+R)。如果你使用其他 Web profile,请把命令中的 `web` 换成实际名称。
59
+ 重启 `dsh web`,然后硬刷新页面(Windows / Linux 是 Ctrl+Shift+R,macOS 是 Cmd+Shift+R)。如果你使用其他 Web profile,请把命令中的 `web` 换成实际名称。
60
60
 
61
61
  ### DSH Desktop
62
62
 
@@ -103,6 +103,8 @@ dsh-notify-me 把「监督」和「守在屏幕前」解耦:只在真的出现
103
103
 
104
104
  **回复完成**也覆盖后台会话;完成但还没看时,标题带 `✅ 回复完成 ·` 标记,打开对应会话即撤。标题标记不受提醒策略限制。
105
105
 
106
+ 通知正文的第一行是会话标题:当前正在看的会话和其他会话一样显示自己的标题,只有宿主还没给出标题的新会话才用「当前对话」占位符兜底。
107
+
106
108
  > **后台**子代理(subagent)子会话的等待与完成默认**不提醒**:DSH 把每个子代理子会话列成独立会话,但它们是所属主对话那一轮里的步骤,提醒只会是噪音。你当前打开的那个子代理会话不算在内,照常提醒。设置页「子代理会话不提醒」可关掉这个静音。
107
109
 
108
110
  ## 在 DSH 设置里改配置
@@ -122,7 +124,7 @@ dsh-notify-me 把「监督」和「守在屏幕前」解耦:只在真的出现
122
124
  - **「回复完成」什么时候提醒**(默认「仅后台」):仅后台 / 仅当前对话静默 / 总是提醒,三选一;
123
125
  - **通知自动消失**(默认「离开时保留」):离开时保留 / 总是关闭 / 从不关闭,三选一;
124
126
  - **子代理会话不提醒**(默认开):跳过后台子代理(subagent)会话,你正开着的那个照常提醒;
125
- - **点击通知回到对应对话**(默认开):切到对应对话并把窗口带到前台,桌面端走原生抬窗,多个标签页只调起一个。
127
+ - **点击通知回到对应对话**(默认开):切到对应对话并把窗口带到前台,Windows 桌面走宿主路由原生抬窗、macOS / Linux 走 `dsh://open` 深链,多个标签页只调起一个。
126
128
 
127
129
  <details>
128
130
  <summary>展开各开关的边界条件</summary>
@@ -130,7 +132,7 @@ dsh-notify-me 把「监督」和「守在屏幕前」解耦:只在真的出现
130
132
  - **后台的判定**:切到别的应用、被别的窗口盖住、最小化都算;窗口一直留在前台但 3 分钟没有任何键鼠输入同样算,`idleMinutes: 0` 退回只看窗口。
131
133
  - **「当前对话不弹通知」何时补发**:窗口转到后台或闲置超时后照常提醒;若你已处理掉就作废。
132
134
  - **「回复完成」三档**:「仅后台」=不在看页面才提醒;「仅当前对话静默」=屏幕上那条静默、别的对话照常提醒,多开对话时有用;「总是提醒」=从不静默。老配置里的「窗口在前台时也提醒『回复完成』」开关自动迁移到这一项。
133
- - **「离开时保留」**:只有你人在页面前时才几秒后关闭,人不在时收到的那条留在通知中心等你回来;带「同意 / 拒绝」的审批通知仍按 12 秒走,同样不会在人不在时被撤掉。
135
+ - **「离开时保留」**:你人在页面前时,普通通知几秒后自己收;人不在时收到的那条留在通知中心等你回来。带「同意 / 拒绝」的通知不设自动撤回,留到你点按钮、回页面把请求答掉、或被新请求顶替为止;桌面端画不出按钮的审批通知按 12 秒收,人不在时同样不撤。
134
136
  - **点击通知的兜底**:桌面端抬不起来时只切对话,原因记在 `debug().raiseLast` 里;关掉这一项后点通知不做任何事。
135
137
 
136
138
  </details>
@@ -168,13 +170,13 @@ dsh-notify-me 把「监督」和「守在屏幕前」解耦:只在真的出现
168
170
 
169
171
  #### 运行环境与诊断
170
172
 
171
- 在「高级设置」最后一块。默认自动识别当前是 Web 端还是桌面端(DSH Desktop,`dsh-app://`);识别不准时可手动指定——桌面端点通知走宿主路由做原生抬窗(见[桌面端怎么抬窗的](#桌面端怎么抬窗的))、通知上不带快捷裁决按钮;Web 端走 `window.focus()` 与 Service Worker 桥。手动覆盖与自动识别不一致时,设置页会明示检测结果。
173
+ 在「高级设置」最后一块。默认自动识别当前是 Web 端还是桌面端(DSH Desktop,`dsh-app://`);识别不准时可手动指定——Windows 桌面点通知走宿主路由做原生抬窗、macOS / Linux 走 `dsh://open` 深链(见[桌面端怎么抬窗的](#桌面端怎么抬窗的))、通知上不带快捷裁决按钮;Web 端走 `window.focus()` 与 Service Worker 桥。手动覆盖与自动识别不一致时,设置页会明示检测结果。
172
174
 
173
175
  <details>
174
176
  <summary>通知语言、桌面端抬窗与恢复默认</summary>
175
177
 
176
178
  - **通知语言**:跟随界面 / 简体中文 / English——决定通知文字与 `🔔 …` 标题标记使用的语言;
177
- - **桌面端抬窗**:1.14.0 起由宿主路由做原生激活,最小化、被别的窗口盖住的都实测能抬回来(见[桌面端怎么抬窗的](#桌面端怎么抬窗的));
179
+ - **桌面端抬窗**:Windows 走宿主路由做原生激活、macOS / Linux 走 `dsh://open` 深链;最小化、被别的窗口盖住的窗口在 Windows 与 Linux 上都实测能抬回来(见[桌面端怎么抬窗的](#桌面端怎么抬窗的));
178
180
  - **恢复默认设置**:把所有开关与音效设置还原成出厂值(不动外部推送目标和已选的自定义音频文件)。
179
181
 
180
182
  </details>
@@ -264,7 +266,7 @@ window.__dshNotifyMe.testExternal() // 显式外发测试:向有
264
266
 
265
267
  ## 工作原理
266
268
 
267
- 提醒核心监听会话状态与待处理交互;审批裁决由页面侧完成,桌面抬窗走宿主路由加 Win32 原生激活。
269
+ 提醒核心监听会话状态与待处理交互;审批裁决由页面侧完成,Windows 桌面抬窗走宿主路由加 Win32 原生激活、macOS / Linux 走 `dsh://open` 深链。
268
270
 
269
271
  <details>
270
272
  <summary>展开事件来源与降级说明</summary>
@@ -287,7 +289,7 @@ window.__dshNotifyMe.testExternal() // 显式外发测试:向有
287
289
  <details>
288
290
  <summary>展开按钮通知的记账与调窗口</summary>
289
291
 
290
- 每条按钮通知按交互 key 记账,一次只认领一条等待;请求被页面里答掉、或被新请求顶替之后,残留通知上的按钮再点也不会误裁,只是安静地关掉。带按钮的通知停留 12 秒(普通通知 5 秒),到点自动撤;没来得及点就回页面里裁决,对话里的审批一直等着你。
292
+ 每条按钮通知按交互 key 记账,一次只认领一条等待;请求被页面里答掉、或被新请求顶替之后,残留通知上的按钮再点也不会误裁,只是安静地关掉。带按钮的通知不设自动撤回,等你点按钮或把请求答掉才消失;普通通知 5 秒自收,桌面端没有按钮的审批通知 12 秒自收。「通知自动消失」选「从不关闭」时,这两类都不收。没来得及点就回页面里裁决,对话里的审批一直等着你。
291
293
 
292
294
  点正文的「调窗口 + 切对话」也归 worker 这半侧调度:`client.focus()` 只调起一个窗口(优先当前可见的),也只让那个窗口切对话——多个 DSH 标签页不会互相抢焦点或一起乱切。
293
295
 
@@ -295,18 +297,18 @@ window.__dshNotifyMe.testExternal() // 显式外发测试:向有
295
297
 
296
298
  ### 桌面端怎么抬窗的
297
299
 
298
- DSH Desktop 是一层 Electron 壳,页面跑在 `dsh-app://app` 下:DOM 的 `window.focus()` 只动浏览器窗口对象、碰不到原生窗口,壳的 `will-navigate` 又把页面里发 `dsh:` 的常规出口堵上了。现在走插件自己的宿主路由——页面 POST `/__dsh-notify-me/focus-window`,宿主起 `powershell.exe` 跑 `lib/focus-window.ps1`,由它枚举原生窗口、自适应激活(1.5.2 到 1.13.0 那条 `dsh://open` 深链在 `0.2.1-rc.2` 上复测 3/3 无效,1.14.0 起整条删掉)。
300
+ DSH Desktop 是一层 Electron 壳,页面跑在 `dsh-app://app` 下:DOM 的 `window.focus()` 只动浏览器窗口对象、碰不到原生窗口,壳的 `will-navigate` 又把页面里发 `dsh:` 的常规出口堵上了。插件按平台走两条通道:Windows 走插件自己的宿主路由——页面 POST `/__dsh-notify-me/focus-window`,宿主起 `powershell.exe` 跑 `lib/focus-window.ps1`,由它枚举原生窗口、自适应激活;macOS / Linux 走壳自己的 `dsh://open` 深链——页面在点击手势里插一个隐藏 iframe 导航 `dsh://open`(子框架导航不经过壳的顶层 `will-navigate` 拦截),交给系统协议注册,壳的 `second-instance` / `open-url` 处理器据此 restore + show + focus 主窗口。Windows 上这条深链在 `0.2.1-rc.2` 复测 3/3 无效,1.14.0 起改走宿主路由;Linux(Plasma 6.8 / Wayland)已实测能把最小化或后台的窗口抬回前台,macOS 未实测。
299
301
 
300
302
  <details>
301
303
  <summary>展开路由、激活顺序、实测数据与安全闸门</summary>
302
304
 
303
- 壳把 `dsh-app://app` 下除静态资源以外的所有路径原样转发给宿主 HTTP server(带 origin 校验、注入宿主 cookie),所以上面那个 POST 是同源请求,没有 CORS 问题;宿主半(`lib/index.js`)本来就跑在 Electron 主进程的子进程里,`process.ppid` 就是主窗口所属的浏览器进程。点通知时:页面 POST → 宿主起一次 `powershell.exe` 跑 `lib/focus-window.ps1 -ProcessId <ppid>` → 脚本枚举该 pid 下可见、无 owner、非 toolwindow 的顶层窗口(优先类名 `Chrome_WidgetWin_1`,再按 `GetWindowRect` 面积取最大)→ 自适应激活 → 比对 `GetForegroundWindow()` 打印 `FOCUSED=1|0` → 宿主回 `200` / `202`。
305
+ Windows 的宿主路由:壳把 `dsh-app://app` 下除静态资源以外的所有路径原样转发给宿主 HTTP server(带 origin 校验、注入宿主 cookie),所以上面那个 POST 是同源请求,没有 CORS 问题;宿主半(`lib/index.js`)本来就跑在 Electron 主进程的子进程里,`process.ppid` 就是主窗口所属的浏览器进程。点通知时:页面 POST → 宿主起一次 `powershell.exe` 跑 `lib/focus-window.ps1 -ProcessId <ppid>` → 脚本枚举该 pid 下可见、无 owner、非 toolwindow 的顶层窗口(优先类名 `Chrome_WidgetWin_1`,再按 `GetWindowRect` 面积取最大)→ 自适应激活 → 比对 `GetForegroundWindow()` 打印 `FOCUSED=1|0` → 宿主回 `200` / `202`。
304
306
 
305
- 激活顺序是实的:已经在前台就什么都不做(最常见的情况,零闪烁);最小化了先 `SW_RESTORE`;然后合成一次 ALT 按键(`keybd_event` 按下抬起)给本线程前台权限,再 `SetForegroundWindow`;这一串都不行才退到 `SW_MINIMIZE` + `SW_RESTORE` 兜底。单独调 `SetForegroundWindow` 会被前台锁直接拒,按调用算、跟 `ForegroundLockTimeout` 无关;这也重新解释了 1.5.2 那套深链「时灵时不灵」——能抬起来的那些次,多半是系统在通知被点击时自己激活了应用。
307
+ Windows 的激活顺序是实的:已经在前台就什么都不做(最常见的情况,零闪烁);最小化了先 `SW_RESTORE`;然后合成一次 ALT 按键(`keybd_event` 按下抬起)给本线程前台权限,再 `SetForegroundWindow`;这一串都不行才退到 `SW_MINIMIZE` + `SW_RESTORE` 兜底。单独调 `SetForegroundWindow` 会被前台锁直接拒,按调用算、跟 `ForegroundLockTimeout` 无关;这也重新解释了 1.5.2 那套深链「时灵时不灵」——能抬起来的那些次,多半是系统在通知被点击时自己激活了应用。
306
308
 
307
309
  实测(`powershell.exe` 5.1,同一轮跑完):窗口在前台 ×3、最小化 + 记事本在前台 ×3、可见但被盖住 ×3,全部 `FOCUSED=1` 且前台窗口比对一致,最小化那几个的 `IsIconic` 都从 `true` 变回 `false`;记事本最大化完全遮挡、最小化 + 完全遮挡、`-ProcessId 0` 自动探测同样成功。脚本内部耗时最坏 434 ms,进程启动到退出最坏 782 ms,都在 8 秒上限内;`pwsh` 7.6 对照一轮行为一致,只是 `Add-Type` 编译慢约 100 ms(脚本刻意不用 7 的语法)。不存在的 pid、存在但没有可见窗口的 pid 都稳定 `FOCUSED=0` 并 `exit 0`。
308
310
 
309
- 安全上只开一条 exact 路由。词表之外的请求一律拒:非 GET / HEAD / POST 回 `405`(包括预检的 `OPTIONS`,且从不回任何 CORS 头),非桌面宿主(Web 版、macOS / Linux、纯 Node)回 `501`,缺 `x-dsh-notify-me-focus: focus` 头回 `403`。
311
+ 安全上只开一条 exact 路由。词表之外的请求一律拒:非 GET / HEAD / POST 回 `405`(包括预检的 `OPTIONS`,且从不回任何 CORS 头),非 Windows 宿主(Web 版、macOS / Linux、纯 Node)回 `501`(macOS / Linux 走深链,不经过这条路由),缺 `x-dsh-notify-me-focus: focus` 头回 `403`。
310
312
 
311
313
  那个头只是「这是页面发来的」标记,不是防线——DNS rebinding 的恶意页对目标地址而言是同源的,能带任意自定义头、也不触发预检。真正的闸门是三层:对端地址必须是 loopback;`Host` 必须是 loopback 名(`127.0.0.1` / `localhost` / `[::1]`,可带端口),因为壳转发时 `host` 已被删掉、由 fetch 按 loopback URL 重填,而 rebinding 的页面 Host 仍是攻击者域名;带了 `Origin` 就必须和 `Host` 同源。任一条不符回 `403`,`reason` 分别是 `bad-remote` / `bad-host` / `cross-origin`。`GET` 只回 `{ok, route, enabled, desktop, platform}`,装完可以先用浏览器打开确认路由在不在。400 毫秒内的重复调用合并成一次,脚本超过 8 秒没回话就 kill 掉按失败处理。
312
314
 
@@ -328,6 +330,7 @@ DSH Desktop 是一层 Electron 壳,页面跑在 `dsh-app://app` 下:DOM 的
328
330
  - 快捷裁决按钮要 Service Worker:`http://127.0.0.1`、`https` 可用,`http://192.168.x.x` 这类局域网地址不行;**桌面端(`dsh-app://`)已实测无法注册 Service Worker**(宿主未开放 `allowServiceWorkers` 特权),审批通知退回无按钮样式。宿主不渲染通知按钮时,`debug()` 的 `bridge` 字段会说明原因,其余功能不受影响。
329
331
  - Windows 的系统通知标签上限 64 字符,而 Chromium 交给平台的是 `n#<origin>#<tag>` 整串——桌面页面 `dsh-app://app` 一项就占去 16 个。插件按当前 `location.origin` 算剩余预算,超长时保留可读前缀、尾部换成短哈希,所以 `debug()` 里看到的标签可能被截短;平台仍然拒发时,原文记在 `debug().lastToastReject`,设置页的测试按钮也会如实报出来,不再「提示已发送但什么都没弹」。
330
332
  - 桌面端(Windows)点通知后窗口仍可能抬不起来:目标窗口属于更高完整性级别(提权 / UAC)、在另一个虚拟桌面、前台被别的进程反复抢回去,或窗口被 `SW_HIDE` 隐藏到托盘时,宿主脚本回 `FOCUSED=0`、路由回 `202`,对话照常切(详见[桌面端怎么抬窗的](#桌面端怎么抬窗的))。
333
+ - 桌面端(macOS / Linux)点通知依赖 `dsh://open` 深链:系统未注册 `x-scheme-handler/dsh`、或壳没有 `second-instance` / `open-url` 处理时抬不起来;Linux 上已实测正常,macOS 未实测。
331
334
  - macOS:提醒、提示音、标题标记、点通知跳转都没有平台假设,照常工作;但 DSH Desktop(Electron)的系统通知要求应用已签名,未签名的通知直接发不出去,官方 macOS 版是否满足这一前提未实测;审批按钮在 macOS 桌面宿主上的渲染同样未实测(Windows 桌面端已实测不渲染)。
332
335
 
333
336
  **提醒内容与时机**
@@ -346,15 +349,21 @@ DSH Desktop 是一层 Electron 壳,页面跑在 `dsh-app://app` 下:DOM 的
346
349
 
347
350
  ## 开发自检
348
351
 
349
- ```powershell
350
- node --check lib\client.js
351
- node --check lib\index.js
352
- node smoke\smoke-test.cjs # 离线状态机冒烟测试:三代宿主 + 主开关 + 中英语言用例 + 快捷裁决桥(Service Worker 半侧一并跑)+ 闲置判定与通知自收 + 通知标签长度收口
353
- node smoke\cordis-host-test.mjs # 真 cordis 端到端(找不到本机 DSH 时自动跳过)
354
- powershell -NoProfile -File lib\focus-window.ps1 -ProcessId 0 # 手动验证抬窗脚本,末行应是 FOCUSED=1
352
+ ```sh
353
+ node --check lib/client.js
354
+ node --check lib/index.js
355
+ npm test # smoke-test(状态机)+ host-route-test(宿主半路由)+ cordis-host-test
355
356
  npm pack --dry-run # 预览发布包
356
357
  ```
357
358
 
359
+ `smoke/smoke-test.cjs` 是离线状态机测试:三代宿主 + 主开关 + 中英语言用例 + 快捷裁决桥(Service Worker 半侧一并跑)+ 闲置判定与通知自收 + 通知标签长度收口。`smoke/host-route-test.mjs` 不需要本机 DSH,`lib/index.js` 的路由、探针与 403/405/501 闸门在任何平台都会跑。
360
+
361
+ 改到 `lib/focus-window.ps1` 时(仅 Windows),另需手动跑一次:
362
+
363
+ ```powershell
364
+ powershell -NoProfile -File lib/focus-window.ps1 -ProcessId 0 # 末行应是 FOCUSED=1
365
+ ```
366
+
358
367
  `cordis-host-test.mjs` 会从本机 DSH 安装借 `@deepseek-ai/cordis`(依次探测 npm 全局目录、`~/.dsh/profiles/web/node_modules` 与 `~/.dsh/profiles/node_modules` 平铺回退目录);源码 checkout 里没有 profile 依赖时,用 `DSH_CORDIS_PATH=<checkout>/vendor/cordis/lib/index.js` 指定即可。
359
368
 
360
369
  ## 致谢与贡献须知
@@ -369,6 +378,8 @@ npm pack --dry-run # 预览发布包
369
378
  | <a href="https://github.com/RiZhiZhaoYi"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/RiZhiZhaoYi.png" width="40" height="40" alt="@RiZhiZhaoYi"></a> | [#12](https://github.com/chromoany/dsh-notify-me/issues/12):外部通知转发(Discord / Bark / Gotify / 自定义 Webhook) |
370
379
  | <a href="https://github.com/yuexian7"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/yuexian7.png" width="40" height="40" alt="@yuexian7"></a> | [#17](https://github.com/chromoany/dsh-notify-me/issues/17):安卓端收消息的诉求,促成飞书 / Server酱 / WxPusher 三种目标 |
371
380
  | <a href="https://github.com/shrekcg"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/shrekcg.png" width="40" height="40" alt="@shrekcg"></a> | [#16](https://github.com/chromoany/dsh-notify-me/pull/16):离开判定 `idleMinutes`、「回复完成」判定 `donePolicy`、自动消失 `autoDismiss` |
381
+ | <a href="https://github.com/Donald-Yip"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/Donald-Yip.png" width="40" height="40" alt="@Donald-Yip"></a> | [#18](https://github.com/chromoany/dsh-notify-me/issues/18):Windows 通知 tag 超过 64 字符上限、审批测试通知被平台静默拒收的报告 |
382
+ | <a href="https://github.com/dunxuan"><img src="https://raw.githubusercontent.com/chromoany/dsh-notify-me/main/docs/contributors/dunxuan.png" width="40" height="40" alt="@dunxuan"></a> | [#20](https://github.com/chromoany/dsh-notify-me/issues/20):当前会话的通知正文用占位符、未取会话标题的报告 |
372
383
 
373
384
  署名口径:本仓库收编外部 PR 时以维护者提交落地——不沿用原 commit、不挂 Co-authored-by,GitHub 的 contributors 图只显示维护者,贡献者以上面的致谢署名。
374
385
 
package/cordis.patch.yml CHANGED
@@ -1,7 +1,7 @@
1
- # dsh-notify-me profile patch layer — insert one loader entry for the
2
- # plugin package. The entry is a normal cordis loader entry (id + package
3
- # name); the browser half is picked up by dsh-client-modules through the
4
- # package's dsh.client declaration, exactly like the shipped ui-* packages.
5
- - insert:
6
- - id: notify-me
7
- name: 'dsh-notify-me'
1
+ # dsh-notify-me profile patch layer — insert one loader entry for the
2
+ # plugin package. The entry is a normal cordis loader entry (id + package
3
+ # name); the browser half is picked up by dsh-client-modules through the
4
+ # package's dsh.client declaration, exactly like the shipped ui-* packages.
5
+ - insert:
6
+ - id: notify-me
7
+ name: 'dsh-notify-me'
package/lib/client.js CHANGED
@@ -218,8 +218,8 @@
218
218
  language: "auto",
219
219
  // Which host environment this page runs in: 'auto' detects from the page
220
220
  // protocol (dsh-app:// = the packaged DSH Desktop shell), 'desktop' and
221
- // 'web' force it. The desktop rides the dsh:// deep-link raise path and
222
- // cannot carry quick-decision buttons at all; the browser uses
221
+ // 'web' force it. The desktop needs its own raise path (raiseWindow
222
+ // below) and cannot carry quick-decision buttons at all; the browser uses
223
223
  // window.focus() and the Service Worker bridge.
224
224
  hostEnv: "auto",
225
225
  // toast + sound are only useful while the user is elsewhere; the tab
@@ -304,6 +304,10 @@
304
304
  var raw = localStorage.getItem(LS_CONFIG);
305
305
  if (raw) cfg = JSON.parse(raw);
306
306
  } catch (e) { /* corrupt storage -> defaults */ }
307
+ // JSON.parse also accepts `null`, `"x"` and `7`. A non-object would make
308
+ // the default fill below throw on `in` and take the whole plugin down
309
+ // with it, so anything that is not a plain object falls back to defaults.
310
+ if (!cfg || typeof cfg !== "object" || Array.isArray(cfg)) cfg = {};
307
311
  // The in-page delivery options are gone: 1.11.0 removed the overlay as a
308
312
  // channel, 1.12.0 the approval card. An old config's `channel` / `overlay`
309
313
  // / `toast` / `overlayCorner` keys mean nothing now — dropped here so the
@@ -325,7 +329,10 @@
325
329
  return cfg;
326
330
  }
327
331
  function writeConfig(patch) {
328
- var cfg = readConfig();
332
+ // A failed write leaves the live config as the only copy; rebuilding from
333
+ // storage would drop the setting the user just changed and make the page
334
+ // disagree with itself on the next patch.
335
+ var cfg = configWriteFailed && config ? config : readConfig();
329
336
  for (var k in patch) cfg[k] = patch[k];
330
337
  // Legacy alias, live in both directions: patching the old boolean still
331
338
  // selects the policy, so an existing caller keeps its meaning instead of
@@ -335,9 +342,17 @@
335
342
  }
336
343
  cfg.donePolicy = cfg.donePolicy === "smart" || cfg.donePolicy === "always" ? cfg.donePolicy : "background";
337
344
  cfg.doneHiddenOnly = cfg.donePolicy !== "always";
338
- try { localStorage.setItem(LS_CONFIG, JSON.stringify(cfg)); } catch (e) {}
345
+ try {
346
+ localStorage.setItem(LS_CONFIG, JSON.stringify(cfg));
347
+ configWriteFailed = false;
348
+ } catch (e) {
349
+ // Quota, private-mode storage, a blocked origin: the switch looks saved
350
+ // but dies on reload, so the settings page says so.
351
+ configWriteFailed = true;
352
+ }
339
353
  return cfg;
340
354
  }
355
+ var configWriteFailed = false;
341
356
  var config = readConfig();
342
357
  // Persist a patch, swap the live module config and re-apply any active
343
358
  // title marker (its prefix follows the notification language).
@@ -468,8 +483,11 @@
468
483
 
469
484
  // ─────────────────────── notification plumbing ───────────────────
470
485
  var permAsked = false;
471
- function requestPermission() {
472
- if (!("Notification" in window) || permAsked) return;
486
+ function requestPermission(force) {
487
+ // An explicit "test" click is a fresh intent: after a dismissed prompt
488
+ // (permission stayed "default") the old latch made every later click a
489
+ // no-op until a reload.
490
+ if (!("Notification" in window) || (permAsked && !force)) return;
473
491
  permAsked = true;
474
492
  try {
475
493
  if (Notification.permission === "default") {
@@ -506,26 +524,53 @@
506
524
  var FOCUS_HEADERS = { "x-dsh-notify-me-focus": "focus" };
507
525
  // What the last raise attempt did, surfaced through debug() so a failing
508
526
  // host path can be diagnosed from the settings page instead of by guesswork.
509
- var raiseState = { channel: "window-focus", last: null };
527
+ var raiseState = { last: null };
528
+ // The desktop is one shell, but the channel that can raise its window is
529
+ // not: Windows has the host route (the deep link is a measured no-op there,
530
+ // see below), macOS / Linux only have the shell's own dsh://open handler.
531
+ // Read from the platform, not from the first click, so debug() can answer
532
+ // what a toast click would do before anything has been clicked.
533
+ function isWindowsPage() {
534
+ try {
535
+ return /Windows/i.test(String((typeof navigator !== "undefined" && navigator.userAgent) || ""));
536
+ } catch (e) { return false; }
537
+ }
538
+ function desktopRaiseChannel() {
539
+ return isWindowsPage() ? "host-route" : "dsh-deeplink";
540
+ }
510
541
  // Bring the OS window forward. A browser tab answers to window.focus(); the
511
542
  // Electron shell does not — DOM focus() never touches the native window, and
512
- // Chromium only activates a window the OS already treats as foreground. The
513
- // shell exposes no focus IPC either (preload's dshDesktop carries none), so
514
- // the activation has to run in the host process: lib/index.js registers
515
- // /__dsh-notify-me/focus-window there, and this click posts to it. Every
516
- // non-static dsh-app://app path is forwarded by the shell to the host web
517
- // server with the host cookie attached, so a relative same-origin fetch
518
- // reaches that route exactly as it would from a browser tab.
543
+ // Chromium only activates a window the OS already treats as foreground.
519
544
  //
520
- // The old path fired the dsh://open deep link through a hidden iframe and
521
- // leaned on the single-instance owner to restore the window. Measured on
522
- // DSH Desktop 0.2.1-rc.2 (issue #9): three attempts, three failures — the
523
- // second instance exited in ~130 ms and the window's IsIconic state never
524
- // changed — so that channel is gone rather than kept as a silent fallback.
545
+ // Two desktop channels exist. Windows keeps the host route — lib/index.js
546
+ // spawns lib/focus-window.ps1 from the process that owns the window, because
547
+ // the deep link below was measured there as three failures (DSH Desktop
548
+ // 0.2.1-rc.2, issue #9: the second instance exited in ~130 ms and IsIconic
549
+ // never changed). Every other desktop uses the shell's own dsh://open
550
+ // handler: the hidden-frame navigation reaches the system protocol
551
+ // registration, whose single-instance owner restores and focuses the
552
+ // window. That was the only channel before 1.14.0 and it still works
553
+ // outside Windows.
554
+ function raiseViaDeepLink() {
555
+ try {
556
+ var f = document.createElement("iframe");
557
+ f.setAttribute("aria-hidden", "true");
558
+ f.setAttribute("tabindex", "-1");
559
+ f.style.cssText = "position:fixed;left:-10px;top:-10px;width:0;height:0;border:0;visibility:hidden";
560
+ f.src = "dsh://open";
561
+ (document.body || document.documentElement).appendChild(f);
562
+ setTimeout(function () {
563
+ try { if (f.parentNode) f.parentNode.removeChild(f); } catch (e) {}
564
+ }, 4000);
565
+ raiseState.last = "deeplink";
566
+ } catch (e) {
567
+ raiseState.last = "error";
568
+ }
569
+ }
525
570
  function raiseWindow() {
526
571
  try { window.focus(); } catch (e) {}
527
- if (!isDesktopShell()) { raiseState.channel = "window-focus"; raiseState.last = "browser"; return; }
528
- raiseState.channel = "host-route";
572
+ if (!isDesktopShell()) { raiseState.last = "browser"; return; }
573
+ if (!isWindowsPage()) { raiseViaDeepLink(); return; }
529
574
  try {
530
575
  if (typeof fetch !== "function") { raiseState.last = "no-fetch"; return; }
531
576
  raiseState.last = "pending";
@@ -841,6 +886,12 @@
841
886
  // failure issue #18 reported. Keeping the reason here makes it readable from
842
887
  // debug() and lets the test buttons stop claiming success.
843
888
  var lastToastReject = null;
889
+ // The Service Worker's showNotification() settles asynchronously, so its
890
+ // refusal lands a tick later than the click that raised it. The settings
891
+ // test keeps this promise and reports only after it settles; otherwise the
892
+ // page claimed "sent" for a toast the platform had already dropped (the
893
+ // surviving half of issue #18 on the only path that carries buttons).
894
+ var lastToastPending = null;
844
895
  function noteToastReject(tag, err) {
845
896
  var message = "unknown";
846
897
  try { message = String((err && err.message) || err || "unknown"); } catch (e) {}
@@ -876,8 +927,12 @@
876
927
  });
877
928
  // The worker call can refuse asynchronously for the same platform
878
929
  // reason; leaving the rejection unhandled would hide it just like
879
- // the swallowed constructor throw did (issue #18).
880
- if (shown && typeof shown.then === "function") shown.catch(function (e) { noteToastReject(tag, e); });
930
+ // the swallowed constructor throw did (issue #18). The same promise
931
+ // is what runTest() waits on before it reports "sent".
932
+ if (shown && typeof shown.then === "function") {
933
+ lastToastPending = shown;
934
+ shown.catch(function (e) { noteToastReject(tag, e); });
935
+ }
881
936
  // No auto-close on purpose: an unanswered approval stays clickable
882
937
  // (toast, then Action Center) until the request is settled — the
883
938
  // wait-teardown path closes it through closeNotificationTag().
@@ -910,7 +965,12 @@
910
965
  // picks between the three behaviours (see DEFAULTS).
911
966
  var policy = config.autoDismiss === "always" || config.autoDismiss === "never" ? config.autoDismiss : "present";
912
967
  if (quick) {
913
- setTimeout(function () { if (policy !== "always" && hidden()) return; n.close(); }, 12000);
968
+ // "Never close" means never, approval toast or not.
969
+ setTimeout(function () {
970
+ if (policy === "never") return;
971
+ if (policy !== "always" && hidden()) return;
972
+ n.close();
973
+ }, 12000);
914
974
  } else if (policy !== "never") {
915
975
  setTimeout(function () { if (policy !== "always" && hidden()) return; n.close(); }, 5000);
916
976
  }
@@ -1269,8 +1329,10 @@
1269
1329
  if (type === "feishu" || type === "serverchan" || type === "wxpusher") {
1270
1330
  // These answer 200 with a service code; a wrong token shows up there,
1271
1331
  // not in the HTTP status. DingTalk does the same but cannot be reached
1272
- // from a page at all, hence no branch for it.
1273
- if (!parsed || typeof parsed !== "object") return { status: "sent", retry: false };
1332
+ // from a page at all, hence no branch for it. Anything else on a 2xx —
1333
+ // an empty body, a proxy or WAF HTML page — cannot confirm delivery,
1334
+ // so it is unverified rather than a success the user never got.
1335
+ if (!parsed || typeof parsed !== "object") return { status: "unverified", retry: false };
1274
1336
  var code = parsed.code;
1275
1337
  var okCode = type === "wxpusher" ? 1000 : 0;
1276
1338
  if (code === okCode) return { status: "sent", retry: false };
@@ -1280,7 +1342,7 @@
1280
1342
  return { status: "sent", retry: false };
1281
1343
  }
1282
1344
  // One attempt. Resolves to {status, retry}; never rejects.
1283
- function postOnce(spec, plain) {
1345
+ function postOnce(spec, plain, type) {
1284
1346
  var headers = {};
1285
1347
  headers["Content-Type"] = plain ? spec.noCorsType : spec.contentType;
1286
1348
  if (!plain) {
@@ -1298,11 +1360,11 @@
1298
1360
  if (plain) return { status: "unverified", retry: false }; // opaque: delivered, reply unreadable
1299
1361
  // Some hosts (and the smoke harness) hand back a response-like object
1300
1362
  // without a body reader; the HTTP status is then all there is to judge.
1301
- if (typeof res.text !== "function") return externalVerdict(spec.type, res, "");
1363
+ if (typeof res.text !== "function") return externalVerdict(type, res, "");
1302
1364
  return res.text().then(function (text) {
1303
- return externalVerdict(spec.type, res, text);
1365
+ return externalVerdict(type, res, text);
1304
1366
  }, function () {
1305
- return externalVerdict(spec.type, res, "");
1367
+ return externalVerdict(type, res, "");
1306
1368
  });
1307
1369
  });
1308
1370
  }
@@ -1322,11 +1384,11 @@
1322
1384
  var built;
1323
1385
  try { built = externalRequest(target, ev); } catch (e) { return Promise.resolve({ status: "failed (payload)", retry: false }); }
1324
1386
  var spec = built.req;
1325
- return postOnce(spec, false).catch(function (err) {
1387
+ return postOnce(spec, false, built.type).catch(function (err) {
1326
1388
  var msg = "failed (" + (err && err.message ? err.message : String(err)) + ")";
1327
1389
  // The browser refused the exchange (CORS or the network): the opaque
1328
1390
  // path still gets the request out, only the reply is unreadable.
1329
- return postOnce(spec, true).catch(function () {
1391
+ return postOnce(spec, true, built.type).catch(function () {
1330
1392
  if (built.type !== "bark") return { status: msg, retry: true };
1331
1393
  return barkGet(target.url, ev).then(null, function () { return { status: msg, retry: true }; });
1332
1394
  });
@@ -1388,19 +1450,42 @@
1388
1450
  // lockstep). A final failure is written to the dead-letter log — the alert
1389
1451
  // itself was already shown locally, so this log is the only trace that the
1390
1452
  // phone did not get it.
1391
- function sendToTarget(target, ev) {
1453
+ // Same target across two externalTargets() reads: the list is rebuilt from
1454
+ // the config on every call, so identity cannot be compared.
1455
+ function sameExternalTarget(a, b) {
1456
+ if (a.id && b.id) return a.id === b.id;
1457
+ return a.type === b.type && a.url === b.url;
1458
+ }
1459
+ function externalTargetStillWanted(target) {
1460
+ var list = externalTargets();
1461
+ for (var i = 0; i < list.length; i++) if (sameExternalTarget(list[i], target)) return true;
1462
+ return false;
1463
+ }
1464
+ function sendToTarget(target, ev, forced) {
1392
1465
  var delays = externalRetryDelays();
1393
1466
  var attempts = 0;
1467
+ // Switching forwarding off (or deleting / disabling the target) has to
1468
+ // stop a retry chain that is already asleep on a timer: without this the
1469
+ // browser kept posting to an endpoint the user had just turned off, and
1470
+ // logged the aborted delivery as a failure (`forced` marks the explicit
1471
+ // test button, which posts even while forwarding is off).
1472
+ function wanted() {
1473
+ if (!forced && !config.externalEnabled) return false;
1474
+ return externalTargetStillWanted(target);
1475
+ }
1394
1476
  function run() {
1477
+ if (!wanted()) return Promise.resolve({ status: "cancelled" });
1395
1478
  attempts++;
1396
1479
  return deliverAttempt(target, ev).then(function (r) {
1397
1480
  if (r.status === "sent" || r.status === "unverified") return r;
1398
1481
  if (!r.retry || attempts > delays.length) return r;
1482
+ if (!wanted()) return { status: "cancelled" };
1399
1483
  var wait = Math.round(delays[attempts - 1] * (1 + Math.random() * 0.25));
1400
1484
  return new Promise(function (resolve) { setTimeout(function () { resolve(run()); }, wait); });
1401
1485
  });
1402
1486
  }
1403
1487
  return run().then(function (r) {
1488
+ if (r.status === "cancelled") return r.status;
1404
1489
  var failed = r.status.indexOf("failed") === 0;
1405
1490
  recordExternalHealth(target.id, r.status, attempts, failed ? r.status.slice(7) : "");
1406
1491
  if (failed) {
@@ -1432,9 +1517,9 @@
1432
1517
  if (!config.externalEnabled) return;
1433
1518
  if (kind === "attention" && !config.externalAttention) return;
1434
1519
  if (kind === "done" && !config.externalDone) return;
1435
- sendExternalToAll(kind, title, body, sessionId, onDone);
1520
+ sendExternalToAll(kind, title, body, sessionId, false, onDone);
1436
1521
  }
1437
- function sendExternalToAll(kind, title, body, sessionId, onDone) {
1522
+ function sendExternalToAll(kind, title, body, sessionId, forced, onDone) {
1438
1523
  var targets = externalTargets();
1439
1524
  if (!targets.length) { if (typeof onDone === "function") onDone([]); return; }
1440
1525
  var ev = {
@@ -1446,7 +1531,7 @@
1446
1531
  };
1447
1532
  var ps = [];
1448
1533
  for (var i = 0; i < targets.length; i++) {
1449
- try { ps.push(sendToTarget(targets[i], ev)); } catch (e) { ps.push(Promise.resolve("failed (dispatch)")); }
1534
+ try { ps.push(sendToTarget(targets[i], ev, !!forced)); } catch (e) { ps.push(Promise.resolve("failed (dispatch)")); }
1450
1535
  }
1451
1536
  if (typeof onDone === "function") Promise.all(ps).then(onDone, function () {});
1452
1537
  }
@@ -1534,16 +1619,18 @@
1534
1619
  attentionKeysMarked[key] = true;
1535
1620
  acquireTitleMark();
1536
1621
  }
1537
- function unmarkAttention(key) {
1622
+ function unmarkAttention(key, keepPending) {
1538
1623
  delete quietedAttention[key]; // the wait is over; a queued alert dies with it
1539
1624
  // A toast that still carries buttons for this wait dies with it too —
1540
1625
  // otherwise a settled request would leave a clickable (but stale)
1541
- // approval toast behind. Test toasts are exempt: their click is the
1542
- // proof, so they outlive the short title mark on purpose.
1626
+ // approval toast behind. A test toast releases its title mark long before
1627
+ // its buttons are done being useful, so that call passes keepPending: the
1628
+ // record stays until the later unmark(), which closes the toast with it.
1629
+ // Without that the buttons went dead while the toast was still on screen.
1543
1630
  var rec = pendingActions[key];
1544
- if (rec) {
1631
+ if (rec && !(keepPending && rec.test)) {
1545
1632
  delete pendingActions[key];
1546
- if (!rec.test) closeNotificationTag(rec.tag);
1633
+ closeNotificationTag(rec.tag);
1547
1634
  }
1548
1635
  if (!attentionKeysMarked[key]) return;
1549
1636
  delete attentionKeysMarked[key];
@@ -1595,12 +1682,9 @@
1595
1682
  lastActivityAt = Date.now();
1596
1683
  if (!idleTimer) armIdle();
1597
1684
  }
1598
- (function watchActivity() {
1599
- var events = ["pointerdown", "pointermove", "keydown", "wheel", "touchstart"];
1600
- for (var ai = 0; ai < events.length; ai++) {
1601
- try { window.addEventListener(events[ai], noteActivity, { passive: true, capture: true }); } catch (e) {}
1602
- }
1603
- })();
1685
+ // Registered from the watchers effect (see apply below) so a client-plugin
1686
+ // reload removes the previous set instead of stacking another one.
1687
+ var ACTIVITY_EVENTS = ["pointerdown", "pointermove", "keydown", "wheel", "touchstart"];
1604
1688
  function idleMinutes() {
1605
1689
  var m = config && config.idleMinutes;
1606
1690
  return (typeof m === "number" && isFinite(m) && m > 0) ? m : 0;
@@ -1839,9 +1923,12 @@
1839
1923
  var quick = quickForTest(key);
1840
1924
  deliver("attention", "DSH · " + d.kind.approval, d.testApproval, null, quick);
1841
1925
  markAttention(key);
1842
- // The title mark drops like every other test's, but the toast is NOT
1843
- // closed with it — its buttons are the very thing being tested.
1844
- setTimeout(function () { unmarkAttention(key); }, TEST_MARK_RELEASE_MS);
1926
+ // The title mark drops like every other test's, but the toast outlives
1927
+ // it — its buttons are the very thing being tested. It gets the same
1928
+ // 12 s a real approval toast has on the constructor path, then the
1929
+ // record and the toast go together.
1930
+ setTimeout(function () { unmarkAttention(key, true); }, TEST_MARK_RELEASE_MS);
1931
+ setTimeout(function () { unmarkAttention(key); }, 12000);
1845
1932
  return;
1846
1933
  }
1847
1934
  if (kind === "attention") {
@@ -2319,7 +2406,7 @@
2319
2406
  });
2320
2407
  } catch (e) {}
2321
2408
  // keep in sync with package.json "version" on every release
2322
- api.version = "1.14.3";
2409
+ api.version = "1.14.5";
2323
2410
  api.setConfig = function (patch) { return setConfigLocal(patch); };
2324
2411
  api.resetConfig = function () {
2325
2412
  try {
@@ -2362,7 +2449,7 @@
2362
2449
  var targets = externalTargets();
2363
2450
  if (!targets.length) { resolve({ sent: 0, unverified: 0, failed: 0, statuses: [] }); return; }
2364
2451
  var d = texts();
2365
- sendExternalToAll("attention", d.testExternalTitle, d.testExternalBody, currentSessionId(), function (statuses) {
2452
+ sendExternalToAll("attention", d.testExternalTitle, d.testExternalBody, currentSessionId(), true, function (statuses) {
2366
2453
  var out = { sent: 0, unverified: 0, failed: 0, statuses: statuses };
2367
2454
  for (var i = 0; i < statuses.length; i++) {
2368
2455
  if (statuses[i] === "sent") out.sent++;
@@ -2423,8 +2510,9 @@
2423
2510
  hostEnv: config.hostEnv,
2424
2511
  hostEnvDetected: detectedDesktop() ? "desktop" : "web",
2425
2512
  desktop: isDesktopShell(),
2426
- raiseChannel: isDesktopShell() ? "host-route" : "window-focus",
2513
+ raiseChannel: isDesktopShell() ? desktopRaiseChannel() : "window-focus",
2427
2514
  raiseLast: raiseState.last,
2515
+ configStored: !configWriteFailed,
2428
2516
  actionKeys: Object.keys(pendingActions),
2429
2517
  permission: ("Notification" in window) ? Notification.permission : "n/a",
2430
2518
  visibility: hidden() ? "hidden" : "visible",
@@ -2602,8 +2690,10 @@
2602
2690
  resetDone: "已恢复默认设置。",
2603
2691
  sent: "已发送测试提醒 · 通知语言:",
2604
2692
  testRefused: "系统拒收了这条通知:",
2693
+ testNoPermission: "通知权限还没给:先在页面上允许一次,再点测试。",
2605
2694
  permHint: "通知权限尚未授予:先在页面上点击一次并允许通知,系统通知才能弹出(提示音不受影响)。",
2606
2695
  offHint: "已关闭提醒:先打开「启用提醒」再测试。",
2696
+ storageFailed: "设置没能保存:浏览器拒绝了这次本地存储写入(空间不足或存储被禁用),改动只在当前页面有效,刷新即还原。",
2607
2697
  versionLine: "插件版本:dsh-notify-me v"
2608
2698
  };
2609
2699
  var UI_en = {
@@ -2752,8 +2842,10 @@
2752
2842
  resetDone: "Defaults restored.",
2753
2843
  sent: "Test alert sent · notification language: ",
2754
2844
  testRefused: "The platform refused this toast: ",
2845
+ testNoPermission: "Notification permission is not granted: allow it once from the page, then test again.",
2755
2846
  permHint: "Notification permission is not granted yet — click once on the page and allow notifications so toasts can appear (sound is unaffected).",
2756
2847
  offHint: "Reminders are off: enable them first, then test.",
2848
+ storageFailed: "Settings were not saved: the browser refused this local-storage write (quota or storage disabled), so the change lasts only for this page and is gone on reload.",
2757
2849
  versionLine: "Plugin version: dsh-notify-me v"
2758
2850
  };
2759
2851
  // ─────────────────── sidebar row glyph ───────────────────────────
@@ -3231,22 +3323,37 @@
3231
3323
  }
3232
3324
  function runTest(kind) {
3233
3325
  if (!config.enabled) { setFeedback(t("offHint")); return; }
3326
+ // A denied permission means showToast() returns before it tries
3327
+ // anything and records no refusal; saying "sent" there would be the
3328
+ // same lie issue #18 was about, one layer earlier.
3329
+ if (!canToast()) {
3330
+ requestPermission(true);
3331
+ setFeedback(t("testNoPermission"));
3332
+ return;
3333
+ }
3234
3334
  unlockOnce();
3235
3335
  // Bypasses the visibility rules on purpose: a test must fire while the
3236
3336
  // page is open, otherwise the button proves nothing.
3237
3337
  var before = lastToastReject;
3338
+ var report = function () {
3339
+ // "sent" would be a lie when the platform refused the toast: the
3340
+ // constructor throws synchronously, and the worker's
3341
+ // showNotification() rejects a tick later, so the worker path waits
3342
+ // for that promise before it reports (issue #18).
3343
+ var refused = lastToastReject && lastToastReject !== before ? lastToastReject : null;
3344
+ if (refused) { setFeedback(t("testRefused") + refused.message); return; }
3345
+ var langName = effectiveLang() === "en" ? t("langEn") : t("langZh");
3346
+ var msg = t("sent") + langName;
3347
+ if (kind === "approval" && !bridgeActive()) {
3348
+ msg += " · " + (isDesktopShell() ? t("testApprovalNoBridge") : t("bridgeOff") + swState + t("bridgeOffTail"));
3349
+ }
3350
+ setFeedback(msg);
3351
+ };
3352
+ lastToastPending = null;
3238
3353
  testAlert(kind);
3239
- // "sent" would be a lie when the platform refused the toast: the
3240
- // constructor threw before anything reached the notification centre,
3241
- // which is exactly the mystery issue #18 came from.
3242
- var refused = lastToastReject && lastToastReject !== before ? lastToastReject : null;
3243
- if (refused) { setFeedback(t("testRefused") + refused.message); return; }
3244
- var langName = effectiveLang() === "en" ? t("langEn") : t("langZh");
3245
- var msg = t("sent") + langName;
3246
- if (kind === "approval" && !bridgeActive()) {
3247
- msg += " · " + (isDesktopShell() ? t("testApprovalNoBridge") : t("bridgeOff") + swState + t("bridgeOffTail"));
3248
- }
3249
- setFeedback(msg);
3354
+ var pending = lastToastPending;
3355
+ if (pending && typeof pending.then === "function") pending.then(report, report);
3356
+ else report();
3250
3357
  }
3251
3358
  // External forwarding rows. Target edits always patch with a fresh array
3252
3359
  // (readConfig may hand out the DEFAULTS entry itself; in-place mutation
@@ -3400,7 +3507,7 @@
3400
3507
  if (!externalTargets().length) { setFeedback(t("externalNoTargets")); return; }
3401
3508
  setFeedback(t("externalSending"));
3402
3509
  var d = texts();
3403
- sendExternalToAll("attention", d.testExternalTitle, d.testExternalBody, currentSessionId(), function (statuses) {
3510
+ sendExternalToAll("attention", d.testExternalTitle, d.testExternalBody, currentSessionId(), true, function (statuses) {
3404
3511
  var s = 0, u = 0, f = 0;
3405
3512
  for (var i = 0; i < statuses.length; i++) {
3406
3513
  if (statuses[i] === "sent") s++;
@@ -3698,7 +3805,8 @@
3698
3805
  ] : null,
3699
3806
  // Always-visible version line at the page foot: bug reports need it,
3700
3807
  // and "which build am I on" should not require the console.
3701
- h("p", { className: "dnm-hint" }, t("versionLine") + api.version)
3808
+ h("p", { className: "dnm-hint" }, t("versionLine") + api.version),
3809
+ configWriteFailed ? h("p", { className: "dnm-warn" }, t("storageFailed")) : null
3702
3810
  ]);
3703
3811
  }
3704
3812
 
@@ -3774,6 +3882,14 @@
3774
3882
  var onVisibility = function () { try { flushQuieted(); } catch (e) {} };
3775
3883
  try { document.addEventListener("visibilitychange", onVisibility); } catch (e) {}
3776
3884
  unsubs.push(function () { try { document.removeEventListener("visibilitychange", onVisibility); } catch (e) {} });
3885
+ for (var ai = 0; ai < ACTIVITY_EVENTS.length; ai++) {
3886
+ try { window.addEventListener(ACTIVITY_EVENTS[ai], noteActivity, { passive: true, capture: true }); } catch (e) {}
3887
+ }
3888
+ unsubs.push(function () {
3889
+ for (var ai = 0; ai < ACTIVITY_EVENTS.length; ai++) {
3890
+ try { window.removeEventListener(ACTIVITY_EVENTS[ai], noteActivity, { capture: true }); } catch (e) {}
3891
+ }
3892
+ });
3777
3893
  // Same re-arm for the other half of "went away": losing window focus.
3778
3894
  try { window.addEventListener("focus", onPageFocus); } catch (e) {}
3779
3895
  try { window.addEventListener("blur", onPageBlur); } catch (e) {}
package/lib/index.js CHANGED
@@ -6,9 +6,11 @@
6
6
  * desktop shell it is not enough, because the shell exposes no focus IPC and
7
7
  * Chromium only honours `window.focus()` for a window the OS already treats as
8
8
  * foreground. This module therefore owns one loopback route on the host web
9
- * server: the notification click posts to it, and the host activates the
10
- * Electron window through Win32 (lib/focus-window.ps1) from the process that is
11
- * allowed to do so.
9
+ * server: on Windows the notification click posts to it and the host activates
10
+ * the Electron window through Win32 (lib/focus-window.ps1) from the process
11
+ * that is allowed to do so. Every other desktop never posts here — its page
12
+ * fires the shell's own `dsh://open` deep link instead, and this route answers
13
+ * 501.
12
14
  *
13
15
  * The route is reachable from the desktop page because the shell forwards every
14
16
  * non-static `dsh-app://app` path verbatim to the host web server, host cookie
@@ -50,10 +52,12 @@ const OUTPUT_LIMIT = 4096;
50
52
  export const name = "dsh-notify-me";
51
53
 
52
54
  /**
53
- * True when this host process runs on the Electron binary, i.e. inside the
54
- * desktop shell the window belongs to. `process.versions.electron` is the only
55
- * trustworthy signal: the shell also exports `ELECTRON_RUN_AS_NODE=1` into the
56
- * host's environment, and every child of the host inherits it, so keying on the
55
+ * True when this host process runs on the Windows Electron binary, i.e. inside
56
+ * the desktop shell whose window this route can activate through Win32. Other
57
+ * desktop platforms raise through the page's `dsh://open` deep link instead and
58
+ * never reach this route. `process.versions.electron` is the only trustworthy
59
+ * signal: the shell also exports `ELECTRON_RUN_AS_NODE=1` into the host's
60
+ * environment, and every child of the host inherits it, so keying on the
57
61
  * variable reports "desktop" from a plain Node test process.
58
62
  * @returns whether native window activation is worth attempting here.
59
63
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-notify-me",
3
- "version": "1.14.3",
3
+ "version": "1.14.5",
4
4
  "description": "离开 DSH 页面也能收到提醒:需要你操作 / 后台回复完成时发系统通知、标题标记与提示音,支持审批快捷裁决与外部推送,Web 版与桌面版均可用。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -66,7 +66,7 @@
66
66
  "node": ">=18"
67
67
  },
68
68
  "scripts": {
69
- "test": "node smoke/smoke-test.cjs && node smoke/cordis-host-test.mjs",
69
+ "test": "node smoke/smoke-test.cjs && node smoke/host-route-test.mjs && node smoke/cordis-host-test.mjs",
70
70
  "pack": "npm pack --dry-run"
71
71
  },
72
72
  "publishConfig": {