4 Commits
4 changed files with 436 additions and 129 deletions
+11
View File
@@ -2,6 +2,17 @@
版本说明按倒序排列。提交信息遵循 [CONTRIBUTING.md](CONTRIBUTING.md) 的单行规范,因此每次改动"为什么这样改、影响面是什么"记在这里,而不是提交信息里。 版本说明按倒序排列。提交信息遵循 [CONTRIBUTING.md](CONTRIBUTING.md) 的单行规范,因此每次改动"为什么这样改、影响面是什么"记在这里,而不是提交信息里。
## v1.0.6
- 修复:**窗口不在前台时,提醒有可能一次都看不到**。排查证据:一次真实投递(会话 17:52:29 结束)在插件页留下 `09:52:30 · 系统通知`——`09:52:30` 是 UTC,本机时间是 17:52:30;而 Windows 的通知平台记录 `LastNotificationAddedTime` 停在 70 分钟前。也就是说 `new Notification()` 没抛错,但**构造函数成功不等于通知真的弹出来了**,加上系统通知的气泡只存在几秒,人不在电脑前时它等于没送达。这一版不再把"发出去"当成"收到了":
- 每条系统通知都订阅 `show` / `error`:系统是否确认显示会写进插件页的「最近一次投递」,不再只报"系统通知"三个字;
- **凡是在窗口不在前台时投递的提醒,都会在窗口回到前台的那一刻用应用内轻弹窗补发一次**。同一会话同一类只保留最新一条,超过 30 分钟不再补发;"正在看的会话不打扰"这条规则不适用于补发,因为它发生的时候你并不在看。唯一的例外是系统确认气泡已弹出、且你在 20 秒内就回到窗口(气泡还在屏幕上,不再重复);
- 点掉系统通知本身(`click`)会取消对应的补发,不重复打扰。
- 修复「最近一次投递」的时间显示成 UTC(比本地时间早 8 小时,17:52 显示成 09:52)的问题,现在显示本机时间。
- 修复确认窗口的队列会把提醒永久卡住的问题:一次确认窗口只投递一条,剩下没轮到的会自己再排一次(以前排完之后队列里再没人触发,后面的提醒就被吞了)。
- 系统通知对象改为有界持有引用:防御性改动,避免显示还没落定时对象被回收(实测中保留引用与否都能送达,所以这不是那次丢失的原因)。
- 插件页「运行状态」新增一行:还有几条提醒在等你回到窗口时补发。
## v1.0.5 ## v1.0.5
- 修复:**应用在后台时不发系统通知**。前台/后台以前只靠 `window` 的 `focus`/`blur` 事件记住,桌面外壳里 `blur` 可能不到,插件就一直以为窗口在前台,于是走了轻弹窗分支(而用户没在看,表现就是完全没有通知)。现在每次投递都现读 `document.visibilityState` 与 `document.hasFocus()`,任一表示不可见即走系统通知;观察器订阅的事件只是让重算更及时,不再决定通道。 - 修复:**应用在后台时不发系统通知**。前台/后台以前只靠 `window` 的 `focus`/`blur` 事件记住,桌面外壳里 `blur` 可能不到,插件就一直以为窗口在前台,于是走了轻弹窗分支(而用户没在看,表现就是完全没有通知)。现在每次投递都现读 `document.visibilityState` 与 `document.hasFocus()`,任一表示不可见即走系统通知;观察器订阅的事件只是让重算更及时,不再决定通道。
+62 -72
View File
@@ -1,53 +1,70 @@
# 会话通知 # 会话通知
DeepSeek Harness(DSH)插件:会话**需要你注意**时提醒你——窗口不在前台时用**系统通知**,窗口在前台时用**应用内轻弹窗**。 DeepSeek Harness(DSH)插件:会话**需要你注意**时提醒你——窗口不在前台用**系统通知**,窗口在前台用**应用内轻弹窗**。
Windows / macOS / Linux 三个平台走的是同一条通知通道(渲染进程的 Web Notification API),插件里没有平台分支。
## 提醒什么 ## 提醒什么
| 触发 | 通知标题 | | 什么时候提醒 | 通知标题 | 内容里带什么 |
| --- | --- | --- |
| 会话从「运行中」变为「空闲」(一轮回答结束) | 会话已完成 | 会话题目 |
| 出现等待你处理的工具授权请求 | 需要授权 | 等待授权的工具名 |
| 出现等待你回答的提问,或等待你确认的计划 | 需要回答 | 提问提醒带问题原文,计划确认带会话题目 |
三类提醒可以分别开关。
每条只提醒一次:同一会话的同一轮只报一次完成,同一个待处理请求只报一次;请求消失之后再次出现,会重新提醒。
## 提醒送到哪里
按 DSH 窗口**当时**的状态选通道,你不需要预先设置:
| 窗口状态 | 怎么提醒 |
| --- | --- | | --- | --- |
| 会话从「运行中」变为「空闲」(一轮回答结束) | 会话已完成 | | 窗口**不在前台** | **系统通知**(Windows 通知中心 / macOS 通知中心 / Linux 通知守护)。点一下通知:窗口回到前台,并跳到那个会话 |
| 待处理的工具授权请求(`approval`) | 需要授权 | | 窗口在**前台**,但不是你正在看的那个会话 | **应用内轻弹窗**:右上角浮出一张卡片,标题是提醒类型,下面一行是会话题目与细节 |
| 待处理的提问 / 计划确认(`question` / `plan-review`) | 需要回答 | | 窗口在**前台**,且正是你**在看的**那个会话 | 不打扰(你就在看着,不需要弹) |
每条只提醒一次:同一会话的同一轮只报一次完成,同一个待处理请求只报一次;请求消失后再来才会再报。 系统通知的气泡只存在几秒,**人不在电脑前时它等于没送到**,所以:
## 走哪个通道 - 凡是在窗口不在前台时投递的提醒,**窗口回到前台的那一刻会再用轻弹窗补发一次**(同一会话同一类只留最新一条,超过 30 分钟不再补发);
- 唯一的例外:系统确认气泡已经弹出来、而且你 20 秒内就回到窗口——那条气泡还在屏幕上,就不再重复;
- 补发不受「正在看的会话不打扰」限制——这条提醒发生的时候你并不在看;
- 点掉系统通知本身就会取消对应的补发;
- 插件页「最近一次投递」会写清系统到底有没有确认显示(`系统已确认弹出` / `系统没有回报` / `没弹出来`)。
| 状态 | 行为 | 轻弹窗的用法:
| --- | --- |
| DSH 窗口**不在前台** | **系统通知**(这是插件唯一能拿到的系统通知通道,三个平台一致)。点通知:窗口回到前台并跳到该会话 | - 点「查看」跳到该会话;
| DSH 窗口在前台,且**不是**你正在看的那个会话 | **应用内轻弹窗**:右上角悬浮,标题是提醒类型、下面一行是会话题目与细节;点「查看」跳过去,6 秒自动消失,鼠标悬停时不消失,Esc 或者 ✕ 关掉 | - 6 秒后自动消失;鼠标停在上面期间不消失,移开后重新计时;
| DSH 窗口在前台,且就是你**正在看的**那个会话 | 不打扰(你在看,不需要弹) | - 按 `Esc` 关掉最新的一条,或点 ✕ 关掉这一条;
- 同屏最多叠 3 条,更早的会被挤掉。
## 设置 ## 设置
**插件 → 会话通知**(插件自己的介绍页里): **插件 → 会话通知**:
- 显示系统通知权限状态; | 分组 | 内容 |
- 未授权时点「允许通知」请求权限(浏览器要求必须由你手动点击才能弹权限框),授权后自动发一条测试通知; | --- | --- |
- 已授权时点「测试通知」随时验证; | 提醒内容 | **完成 / 授权 / 提问** 三个开关,分别控制三类提醒,默认全开;开关保存在浏览器本地,重开页面、重装插件都保留 |
- 权限被系统层关闭时,按平台给出开启路径(Windows / macOS 的通知设置、Linux 桌面环境的通知设置); | 系统通知权限 | 当前权限状态;尚未授权时点「允许通知」请求授权(浏览器要求必须由你手动点击),授权成功后会自动发一条测试提醒。权限被系统层关闭时,会按当前平台告诉你去哪里打开 |
- 三个开关分别控制**完成 / 授权 / 提问**三类提醒(默认全开),状态存在浏览器本地,重装插件不丢; | 运行状态 | 窗口现在是前台还是后台(即会走哪条通道)、插件是否真的在读会话状态、**最近一次提醒走的通道、系统是否确认弹出、时间**(本机时间),以及还有几条提醒在等你回到窗口时补发;旁边「测试提醒」按钮发一条测试提醒 |
- 最后一段显示观察器自身的健康状态(收不到会话状态时直接标红)。
设置放在插件自己的页面里,而不是「设置 → 通用」:它是这个插件的配置,不是 DSH 的通用偏好。 - 已经授权时,权限行的按钮变成「测试系统通知」:它直接走系统通知通道(窗口在前台也照发),专门用来验证系统通知本身是否可用。
- 开关只影响提醒,不改 DSH 本身的任何设置。
## 安装 ## 安装
### 1. 从 Git 仓库安装(推荐) ### 从 Git 仓库安装(推荐)
在 DSH 的 **插件 → 添加插件** 的上方输入框里填: 在 DSH 的 **插件 → 添加插件** 的上方输入框里填:
```text ```text
https://gitea.iwake.top/dsh-plugin/session-notify.git#v1.0.3 https://gitea.iwake.top/dsh-plugin/session-notify.git#v1.0.6
``` ```
`#` 后面跟标签或提交,用来锁定版本;不写则取默认分支。跟随 1.x 最新版可以写 `#semver:^1.0.3`。仓库是公开的,不需要凭据,也不用改「安装源」。 `#` 后面跟标签或提交,用来锁定版本;不写则取默认分支。跟随 1.x 最新版可以写 `#semver:^1.0.6`。仓库是公开的,不需要凭据,也不用改「安装源」。
### 2. 本地路径安装 ### 本地路径安装
把仓库克隆或下载到本机,在同一个输入框里填包目录的绝对路径,例如: 把仓库克隆或下载到本机,在同一个输入框里填包目录的绝对路径,例如:
@@ -55,60 +72,33 @@ https://gitea.iwake.top/dsh-plugin/session-notify.git#v1.0.3
D:\DeepSeek Harness Plugins\dsh-session-notify D:\DeepSeek Harness Plugins\dsh-session-notify
``` ```
### 装完之后 ### 安装之后
- **浏览器半**随页面加载,**刷新页面**即生效; - 装好**刷新页面**即生效;本插件没有第三方依赖,也不需要 pnpm 下载或构建步骤。
- **宿主半**是空壳(不改任何 DSH 状态、不注册服务与路由),只有它变化时才需要完全退出 DSH 再打开; - 卸载:在插件页里移除 `@dsh-plugin/session-notify`。
- 本插件没有第三方依赖,不需要 pnpm 下载,也没有构建步骤。
卸载:插件页里移除 `@dsh-plugin/session-notify`(它同时是 profile 的一个 bundle)。 ## 提醒规则
## 平台说明与验证范围 - **只在「运行中 → 空闲」的转变上提醒**:打开应用时已经在跑的会话只建立基线,不补发;历史里早已结束的会话不会被翻出来提醒。
- **正在看的那个会话完成后不打扰**。
- **子智能体的会话不单独提醒**,等它归属的主会话结束时才提醒。
- **空白会话完成不提醒**。
- **授权 / 提问如果出现的当下会话仍在运行,会先记下、等这一轮真正停下来再提醒**,不在模型还在跑的时候打扰你。
- **节流**:1.5 秒内只投递一条,多个会话同时完成不会刷屏。
- **完成提醒有 400ms 的确认窗口**:如果那一轮马上又跑起来,就不报了。
- **同一会话的完成提醒会覆盖上一条**(通知带 `tag`),不叠加堆积。
- **窗口不在前台时投递过的提醒,回到前台会补发一次轻弹窗**(30 分钟内有效)。
- 提醒只在 DSH 运行、页面打开时产生:**DSH 完全退出期间结束的会话不会再补发通知**。
- **通道是跨平台统一的**:插件的提醒都通过页面(Electron 渲染进程)的 `Notification` 构造器发出,Windows 通知中心 / macOS 通知中心 / Linux 通知守护(libnotify、GNOME、KDE)都由系统把它转成原生通知;应用内轻弹窗是纯 DOM,与平台无关。 ## 平台
- **宿主半拿不到系统通知**:DSH Desktop 的宿主进程是纯 Node 进程(不是 Electron 主进程),没有 Electron 的 `Notification` 可用,所以插件的所有提醒都在浏览器半产生——这也正是"三个平台一套代码"的原因。
- **已验证**:Windows 上的安装、三个 slot 条目注册、以及 52 项离线断言(接线 / 国际化 / 轻弹窗结构 / 开关持久化 / 全部投递规则)。
- **未验证**:macOS 与 Linux 上的实际弹窗效果本机无法测试。结构上它们与 Windows 共用同一条通道、同一份代码,只有"权限被系统关闭时显示的开启路径"是分平台的。
- 提醒只在 DSH 进程运行、页面打开时产生:**DSH 完全退出期间结束的会话不会再补发通知**。
## 行为细节(都已验证) - Windows / macOS / Linux 都支持,三个平台走同一条通知通道,行为一致;应用内轻弹窗与平台无关。
- 当前环境不支持系统通知时(权限一行会显示「不可用」),提醒仍然以应用内轻弹窗的形式送达。
- **只有观测到「运行中 → 空闲」的转变才提醒**:打开应用时已经在跑的会话只建立基线,不补发;历史里早已结束的会话不会被翻出来提醒。 - 系统通知被拒绝或发送失败时,插件会改用轻弹窗,并把原因写在插件页的权限 / 状态那一段,不会静默失败。
- **子智能体会话不单独提醒**(`origin === 'subagent'`),归属它的主会话结束时才提醒。
- **新会话(空白会话)完成不提醒**。
- **授权/提问在会话仍在运行时被延后提醒**:先记下,等这一轮真正停下来再报,避免在模型还在跑的时候就打扰你。
- **节流**:1.5 秒内只投递一条,多个会话同时完成不会刷屏;完成提醒前有 400ms 的确认窗口,如果那一轮马上又跑起来就不报。
- **同一会话的完成提醒会覆盖上一条**(通知带 `tag`),不堆叠。
## 兼容性 ## 兼容性
基于 **DeepSeek Harness 0.2.0-rc.2** 编写,遵循 DSH 插件规范:`dsh.manifestVersion: 1`、`dsh.bundle.patch` 声明宿主行、`dsh.client` 声明 `platform: "web"` 的浏览器半。 需要 **DeepSeek Harness 0.2.0-rc.2 或更高**。
依赖的都是稳定契约:
- 浏览器半只依赖 **slot 的标准 props**(`useSessions`、`useSessionStatus`)读取会话状态,这是 DSH 官方给插件读会话数据的方式;不轮询、不自己订阅会话事件、不读别的插件的 DOM;
- 只往两个官方 slot 注册:`plugins.bundle.config`(本插件在插件页里的配置,key 就是包名)与 `shell.overlay`(两个条目:轻弹窗层 + 无渲染的观察器,内容永远是 `null`);
- **配置放在插件页**:`plugins.bundle.config` 的 key 取包名(`@dsh-plugin/session-notify`),插件页就会渲染这块配置;官方 `dsh-experimental-voice-input-bundle` 用的就是这个口子。行级口子是 `plugins.row.config`,key 形如 `<包名>#<行 id>`,会在该行上多出一个「配置」入口;
- **不要**把"无渲染"条目放进 `sidebar.panellist`:该 slot 的宿主会把**每个条目的 id 当成一个左侧面板按钮**(`entriesOfSlot('sidebar.panellist')` → 面板列表,按钮文字取 `options.label ?? options.id`,条目本身作为图标内联渲染),放进去会在左侧多出一行空面板并挤坏侧边栏。本插件第一版踩过这个坑,现已改挂到通用浮层;
- **文案必须注册字典**:`ctx.locale.register('session-notify', { zh, en })`,否则 `locale.bind(ns)` 在查不到该命名空间时会把 key 原样返回——界面上就会显示成 `settings.title` 这样的原始键(本插件第二版踩过这个坑)。注册会在 locale 修订号上打点,已经渲染出来的部件会自动换上文案,不需要刷新;
- 另外自带一份本地字典兜底:即使拿不到框架的 `t`、或 locale 服务没有保存注册,也会渲染中文/英文文案而不是原始键;
- 样式只用主题 token,不 import 任何 `@deepseek-ai/dsh-client-*` 包(规范要求,也是渲染不被上游改动打断的前提);
- 宿主半不声明 `inject`、不注册服务、不注册路由;三个开关存浏览器本地,不改 DSH 的配置文件。
上游若改动 slot 名或 hook 名:注册会静默跳过而不是把页面弄坏,插件会退化成"不提醒";这类情况请按上面的契约名核对。
## 验证方式(开发记录)
`client.js` 是纯 JavaScript、浏览器端运行,可以在 Node 里用桩模块加载器评估并驱动:
- 模块接线:插件返回值、`inject` 声明、注册集合(含"配置挂在插件页""观察器绝不在 `sidebar.*` 里"这两条);
- 国际化:字典已注册且中英键集合一致、插件页与弹窗渲染出的每个字符串都不是原始键、拿不到框架 `t` 时本地字典兜底、locale 服务不保存注册时仍然有文案;
- 轻弹窗结构:标题是触发类型、描述含会话名与细节;
- 开关:切换即写入浏览器本地,重开页面能读回;
- 渲染健壮性:各组件在空状态 / 权限被拒 / 无 Notification API 下渲染都不报错;
- 投递规则:完成提醒一次、当前会话不打扰、后台走系统通知、授权/提问各提醒一次、运行中延后、子会话跳过、空白会话跳过、历史不补发、开关生效、弹窗自动消失等。
合计 52 项断言。
## License ## License
+362 -56
View File
@@ -49,6 +49,18 @@ window.__ModuleLoader__.load({
/** In-app popup lifetime, and how many may stack. */ /** In-app popup lifetime, and how many may stack. */
const TOAST_DURATION_MS = 6000 const TOAST_DURATION_MS = 6000
const TOAST_LIMIT = 3 const TOAST_LIMIT = 3
/** Notifications kept referenced, so a collection can never cancel a pending display. */
const RAISED_LIMIT = 8
/** Alerts carried by the system channel and still worth replaying in-app on return. */
const REPLAY_LIMIT = 8
/** How long a system notification outlives the moment the user comes back. */
const REPLAY_TTL_MS = 30 * 60 * 1000
/**
* A confirmed banner that the user came back to within this window is treated as
* seen: the desktop notification is still on screen at that moment, so replaying
* it in-app would be a duplicate rather than a reminder.
*/
const REPLAY_QUIET_MS = 20 * 1000
const zh = { const zh = {
'notification.completion': '会话已完成', 'notification.completion': '会话已完成',
@@ -73,7 +85,8 @@ window.__ModuleLoader__.load({
'settings.permission.hint.mac': '系统设置 → 通知 → DeepSeek Harness', 'settings.permission.hint.mac': '系统设置 → 通知 → DeepSeek Harness',
'settings.permission.hint.linux': '在桌面环境的通知设置(GNOME / KDE)中允许 DeepSeek Harness', 'settings.permission.hint.linux': '在桌面环境的通知设置(GNOME / KDE)中允许 DeepSeek Harness',
'settings.action.allow': '允许通知', 'settings.action.allow': '允许通知',
'settings.action.test': '测试通知', 'settings.action.testSystem': '测试系统通知',
'settings.action.testAny': '测试提醒',
'settings.action.unsupported': '不可用', 'settings.action.unsupported': '不可用',
'settings.permission.promptFailed': '无法请求通知权限:{message}', 'settings.permission.promptFailed': '无法请求通知权限:{message}',
'settings.health.watching': '正在监听会话状态', 'settings.health.watching': '正在监听会话状态',
@@ -84,12 +97,27 @@ window.__ModuleLoader__.load({
'settings.kind.completion': '完成', 'settings.kind.completion': '完成',
'settings.kind.approval': '授权', 'settings.kind.approval': '授权',
'settings.kind.question': '提问', 'settings.kind.question': '提问',
'config.title': '会话通知',
'config.note': '只在会话需要你注意时提醒,而且只在 DSH 运行时。',
'config.section.kinds': '提醒内容', 'config.section.kinds': '提醒内容',
'config.section.permission': '系统通知权限', 'config.section.permission': '系统通知权限',
'config.section.status': '运行状态', 'config.section.status': '运行状态',
'config.intro': '提醒都从当前页面发出:窗口不在前台时是系统通知,窗口在前台时是这里的轻弹窗。',
'config.saveNote': '开关保存在浏览器本地,重装插件不会丢失。', 'config.saveNote': '开关保存在浏览器本地,重装插件不会丢失。',
'config.testHint': '这里的按钮直接走系统通知通道,用来验证系统通知本身是否可用(窗口在前台也照发)。',
'config.testAny': '测试提醒',
'config.testSystem': '测试系统通知',
'config.diag.window': '窗口状态',
'config.diag.inFront': '在前台(会走轻弹窗)',
'config.diag.away': '不在前台(会走系统通知)',
'config.diag.last': '最近一次投递',
'config.diag.none': '还没有投递过',
'config.diag.systemShown': '系统通知(系统已确认弹出)',
'config.diag.systemUnconfirmed': '系统通知(系统没有回报,回到窗口时补发轻弹窗)',
'config.diag.systemFailed': '系统通知没弹出来,回到窗口时补发轻弹窗',
'config.diag.replayDelivery': '应用内轻弹窗(回到窗口时补发)',
'config.diag.popup': '应用内轻弹窗',
'config.diag.refused': '系统通知被拒绝,改用了轻弹窗',
'config.diag.replay': '等你回到窗口时补发:{count} 条',
'config.diag.replayNone': '没有待补发的提醒',
} }
const en = { const en = {
'notification.completion': 'Conversation finished', 'notification.completion': 'Conversation finished',
@@ -114,7 +142,8 @@ window.__ModuleLoader__.load({
'settings.permission.hint.mac': 'System Settings → Notifications → DeepSeek Harness', 'settings.permission.hint.mac': 'System Settings → Notifications → DeepSeek Harness',
'settings.permission.hint.linux': 'Allow DeepSeek Harness in your desktop notification settings (GNOME / KDE)', 'settings.permission.hint.linux': 'Allow DeepSeek Harness in your desktop notification settings (GNOME / KDE)',
'settings.action.allow': 'Allow notifications', 'settings.action.allow': 'Allow notifications',
'settings.action.test': 'Test notification', 'settings.action.testSystem': 'Test system notification',
'settings.action.testAny': 'Test alert',
'settings.action.unsupported': 'Unavailable', 'settings.action.unsupported': 'Unavailable',
'settings.permission.promptFailed': 'Could not request notification permission: {message}', 'settings.permission.promptFailed': 'Could not request notification permission: {message}',
'settings.health.watching': 'Watching session status', 'settings.health.watching': 'Watching session status',
@@ -125,12 +154,27 @@ window.__ModuleLoader__.load({
'settings.kind.completion': 'Finished', 'settings.kind.completion': 'Finished',
'settings.kind.approval': 'Approval', 'settings.kind.approval': 'Approval',
'settings.kind.question': 'Questions', 'settings.kind.question': 'Questions',
'config.title': 'Session notifications',
'config.note': 'Alerts you when a conversation needs attention, while DSH is running.',
'config.section.kinds': 'What to notify about', 'config.section.kinds': 'What to notify about',
'config.section.permission': 'System notification permission', 'config.section.permission': 'System notification permission',
'config.section.status': 'Status', 'config.section.status': 'Status',
'config.intro': 'Every alert comes from this page: a system notification while the window is in the background, the light popup here while it is in the foreground.',
'config.saveNote': 'The switches are stored in this browser and survive reinstalling the plugin.', 'config.saveNote': 'The switches are stored in this browser and survive reinstalling the plugin.',
'config.testHint': 'The buttons here go straight to the system channel, so you can verify it on its own (they fire even while the window is in front).',
'config.testAny': 'Test alert',
'config.testSystem': 'Test system notification',
'config.diag.window': 'Window',
'config.diag.inFront': 'in front (popup is used)',
'config.diag.away': 'not in front (system notification is used)',
'config.diag.last': 'Last delivery',
'config.diag.none': 'nothing delivered yet',
'config.diag.systemShown': 'system notification (confirmed on screen)',
'config.diag.systemUnconfirmed': 'system notification (no confirmation, replayed in-app on return)',
'config.diag.systemFailed': 'system notification never appeared, replayed in-app on return',
'config.diag.replayDelivery': 'in-app popup (replayed when you came back)',
'config.diag.popup': 'in-app popup',
'config.diag.refused': 'system channel refused, popup was used instead',
'config.diag.replay': 'waiting for you to come back: {count}',
'config.diag.replayNone': 'nothing waiting to be replayed',
} }
/** /**
@@ -311,13 +355,33 @@ window.__ModuleLoader__.load({
return 'default' return 'default'
} }
/**
* Whether the Harness window is somewhere the user cannot see the app.
*
* Two independent browser facts are consulted, and ANY of them counts as "not
* in the foreground": the page's visibility and the document's focus. They are
* read at delivery time rather than remembered from an event, because a missed
* blur in the desktop shell made this plugin believe the window was in front
* and swallow the alert.
* @returns whether the alert must go to the system notification channel.
*/
function windowIsAway() {
try {
if (document.visibilityState === 'hidden') return true
} catch {
/* an unreadable visibility state leaves the focus fact */
}
try {
if (typeof document.hasFocus === 'function') return !document.hasFocus()
} catch {
/* an unreadable focus state leaves the default below */
}
return false
}
/** Read the window's live focus state rather than a cached value. */ /** Read the window's live focus state rather than a cached value. */
function currentFocus() { function currentFocus() {
try { return !windowIsAway()
return typeof document.hasFocus === 'function' ? document.hasFocus() : true
} catch {
return true
}
} }
/** Focus the window without letting a refusal stop the navigation. */ /** Focus the window without letting a refusal stop the navigation. */
@@ -506,9 +570,10 @@ window.__ModuleLoader__.load({
toasts: [], toasts: [],
promptError: '', promptError: '',
health: { state: 'starting', message: '' }, health: { state: 'starting', message: '' },
lastDelivery: null,
}) })
const notify = (message) => { const notify = (message) => {
report(`session-notify: ${message}`) report(message)
} }
/** Every component translates through this: the slot's own seat when the owner supplies one, else the locale service. */ /** Every component translates through this: the slot's own seat when the owner supplies one, else the locale service. */
const seatFor = (props) => (typeof props.t === 'function' ? props.t : t) const seatFor = (props) => (typeof props.t === 'function' ? props.t : t)
@@ -520,10 +585,14 @@ window.__ModuleLoader__.load({
settleTimer: 0, settleTimer: 0,
lastDelivery: 0, lastDelivery: 0,
toastSeq: 0, toastSeq: 0,
deliverySeq: 0,
/** System notifications this page still holds open, so nothing collects them mid-display. */
raised: new Set(),
/** Alerts the user has not been able to see yet, replayed in-app when the window returns. */
replay: [],
live: { live: {
list: undefined, list: undefined,
status: undefined, status: undefined,
focus: true,
}, },
} }
const timers = new Map() const timers = new Map()
@@ -634,12 +703,48 @@ window.__ModuleLoader__.load({
} }
} }
/** Raise one system notification, tolerating every refusal a browser may give. */ /**
* The system-notification channel's own answer about one notification.
*
* A browser reports the platform's verdict asynchronously: `show` means the
* notification reached the desktop, `error` means the platform refused it, and
* silence means neither answer arrived. That third case is the one that used to
* lose alerts silently, so it is recorded rather than assumed to be a success.
* @param monitor - the record returned by {@link systemNotify} for this notification.
* @param shown - `true` when the platform displayed it, `false` when it refused.
*/
const confirmDelivery = (monitor, shown) => {
if (monitor === null || monitor === undefined || typeof monitor !== 'object') return
monitor.shown = shown
const snapshot = store.getSnapshot()
const last = snapshot.lastDelivery
if (last === null || last === undefined || last.monitor !== monitor || last.shown === shown) return
store.set({ ...snapshot, lastDelivery: { ...last, shown } })
}
/** Hold one raised notification open, bounded, so it cannot be collected while pending. */
const keepRaised = (notification) => {
state.raised.add(notification)
while (state.raised.size > RAISED_LIMIT) {
const oldest = state.raised.values().next().value
if (oldest === undefined) break
state.raised.delete(oldest)
}
}
/**
* Raise one system notification, tolerating every refusal a browser may give,
* and report what the platform said about it.
* @returns a record whose `outcome` is the channel's verdict (`raised`,
* `permission`, `unsupported`, or `threw`) and whose `shown` is filled in
* later by {@link confirmDelivery} — `true` displayed, `false` refused,
* `undefined` while the platform has said nothing.
*/
const systemNotify = (candidate, force) => { const systemNotify = (candidate, force) => {
const Ctor = globalThis.Notification const Ctor = globalThis.Notification
const permission = notificationPermission() const permission = notificationPermission()
if (permission === 'unsupported') return false if (permission === 'unsupported') return { outcome: 'unsupported' }
if (!force && permission !== 'granted') return false if (!force && permission !== 'granted') return { outcome: 'permission' }
try { try {
const notice = copyFor(candidate) const notice = copyFor(candidate)
const options = { const options = {
@@ -649,7 +754,20 @@ window.__ModuleLoader__.load({
} }
if (systemIcon !== undefined) options.icon = systemIcon if (systemIcon !== undefined) options.icon = systemIcon
const notification = new Ctor(notice.title, options) const notification = new Ctor(notice.title, options)
const record = { outcome: 'raised', notice, shown: undefined }
keepRaised(notification)
notification.onshow = () => {
confirmDelivery(record, true)
}
notification.onerror = (event) => {
confirmDelivery(record, false)
notify(`system notification was refused: ${String(event?.message ?? 'unknown')}`)
}
notification.onclose = () => {
state.raised.delete(notification)
}
notification.onclick = () => { notification.onclick = () => {
dropReplay(candidate)
focusWindow() focusWindow()
openSession(candidate.sessionId) openSession(candidate.sessionId)
try { try {
@@ -658,13 +776,70 @@ window.__ModuleLoader__.load({
/* close is best effort on every platform */ /* close is best effort on every platform */
} }
} }
return true return record
} catch (error) { } catch (error) {
notify(`system notification failed: ${text(error)}`) notify(`system notification failed: ${text(error)}`)
return false return { outcome: 'threw' }
} }
} }
// ------------------------------------------------------------ replay
/** Forget one queued replay: the user has just answered that alert in the system channel. */
const dropReplay = (candidate) => {
const next = state.replay.filter((entry) => (
entry.candidate.sessionId !== candidate.sessionId || entry.candidate.kind !== candidate.kind
))
if (next.length === state.replay.length) return
state.replay = next
publish()
}
/**
* Keep one away-channel alert for an in-app replay.
*
* A desktop notification raised while nobody is looking at the machine is
* easy to miss: its banner lives a few seconds, its history lives in the
* system's own notification centre, which the user may never open, and a
* refused display leaves no trace at all on the page. The alert is therefore
* replayed as a light in-app popup as soon as the window is back in the
* foreground, except when the platform confirmed the banner and the user was
* back within {@link REPLAY_QUIET_MS} — then the banner is still on screen and
* a second surface would only be noise. Entries older than
* {@link REPLAY_TTL_MS} are dropped instead of waiting for a user who has
* moved on.
* @param candidate - the alert to keep for a replay.
* @param monitor - the system channel's own record, so its confirmation can be read later.
*/
const holdForReplay = (candidate, monitor) => {
const now = Date.now()
state.replay = [
...state.replay.filter((entry) => (
entry.candidate.sessionId !== candidate.sessionId || entry.candidate.kind !== candidate.kind
)),
{ candidate, at: now, monitor },
].slice(-REPLAY_LIMIT)
publish()
}
/** Show every away-channel alert the user has not had a chance to see yet. */
const flushReplay = () => {
if (state.replay.length === 0) return
const now = Date.now()
const waiting = state.replay
state.replay = []
const due = waiting.filter((entry) => {
if (now - entry.at > REPLAY_TTL_MS) return false
// A banner that the platform confirmed and that is still inside its own
// visible window has already told the user; do not say it twice.
return !(entry.monitor?.shown === true && now - entry.at <= REPLAY_QUIET_MS)
})
const shown = due.slice(-TOAST_LIMIT)
for (const entry of shown) showToast(entry.candidate)
if (shown.length > 0) recordDelivery('replay', shown[shown.length - 1].candidate)
else publish()
}
// -------------------------------------------------------------- delivery // -------------------------------------------------------------- delivery
/** Whether the user is looking at this exact conversation right now. */ /** Whether the user is looking at this exact conversation right now. */
@@ -677,6 +852,37 @@ window.__ModuleLoader__.load({
return false return false
} }
/**
* Record what actually happened to the newest alert.
*
* Everything on the delivery path used to fail invisibly: the alert simply
* never appeared, with no way to tell a wrong channel decision from a
* refused constructor. The config page shows this record, so the next
* question ("did it even try?") has an answer.
*
* The time is the user's own clock, not UTC: a log line the reader has to
* translate by eight hours is worse than no log line.
* @param outcome - which channel carried the alert, or why it fell back.
* @param candidate - the alert being recorded.
* @param monitor - the system channel's own record, when that is the channel.
* @returns the stored record, so a later platform answer can update it.
*/
const recordDelivery = (outcome, candidate, monitor) => {
state.deliverySeq += 1
const now = new Date()
const pad = (value) => String(value).padStart(2, '0')
const record = {
seq: state.deliverySeq,
outcome,
at: `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`,
title: copyFor(candidate).title,
shown: monitor?.shown,
monitor,
}
store.set({ ...store.getSnapshot(), lastDelivery: record })
return record
}
/** /**
* Whether a queued candidate is still worth delivering. Read from the LIVE * Whether a queued candidate is still worth delivering. Read from the LIVE
* snapshot rather than the one captured when the transition was seen: a * snapshot rather than the one captured when the transition was seen: a
@@ -696,9 +902,15 @@ window.__ModuleLoader__.load({
/** /**
* Deliver one candidate through exactly one channel: the system * Deliver one candidate through exactly one channel: the system
* notification while the window is in the background, the light popup while * notification while the window is away, the light popup while it is in
* it is in the foreground, and nothing at all for the conversation on * front, and nothing at all for the conversation on screen.
* screen. *
* The channel decision reads the window state right here, at delivery time,
* instead of trusting the state the observer last remembered — that is what
* an unreported blur used to defeat. An alert that leaves through the system
* channel is additionally held for an in-app replay, because a desktop banner
* raised while nobody is looking at the machine is a notification the user
* never actually receives.
*/ */
const deliver = (candidate, ignoreThrottle) => { const deliver = (candidate, ignoreThrottle) => {
if (ignoreThrottle !== true) { if (ignoreThrottle !== true) {
@@ -706,23 +918,37 @@ window.__ModuleLoader__.load({
if (now - state.lastDelivery < THROTTLE_MS) return if (now - state.lastDelivery < THROTTLE_MS) return
state.lastDelivery = now state.lastDelivery = now
} }
if (state.live.focus) { if (!windowIsAway()) {
if (!isOnScreen(candidate.sessionId, state.live.list)) showToast(candidate) if (isOnScreen(candidate.sessionId, state.live.list)) return
showToast(candidate)
recordDelivery('popup', candidate)
return return
} }
if (systemNotify(candidate, candidate.test === true)) return const result = systemNotify(candidate, candidate.test === true)
if (candidate.test === true) showToast(candidate) if (result.outcome === 'raised') {
recordDelivery('system', candidate, result)
if (candidate.test !== true) holdForReplay(candidate, result)
return
}
// A test alert still has to reach the user, and so does a real one when
// the system channel refuses: the popup is the channel that remains.
showToast(candidate)
recordDelivery(`system-refused-${result.outcome}`, candidate)
} }
/** /**
* Take the delivery decision on a later tick, from the freshest state. * Take the delivery decision on a later tick, from the freshest state.
*
* One candidate per tick keeps the throttle meaningful, and anything still
* queued arms its own follow-up tick — a burst used to leave every candidate
* after the first stranded in the queue with no timer to flush it.
*/ */
const flushSettle = () => { const flushSettle = () => {
state.settleTimer = 0 state.settleTimer = 0
if (disposed) return
const candidate = state.pending.shift() const candidate = state.pending.shift()
if (disposed || candidate === undefined) return if (candidate !== undefined && stillWorth(candidate)) deliver(candidate, false)
if (!stillWorth(candidate)) return if (state.pending.length > 0) state.settleTimer = setTimeout(() => flushSettle(), SETTLE_MS)
deliver(candidate, false)
} }
/** Hold one candidate for the settle tick, collapsing a burst onto one timer. */ /** Hold one candidate for the settle tick, collapsing a burst onto one timer. */
@@ -738,11 +964,13 @@ window.__ModuleLoader__.load({
* One derivation pass over the client's own session state: remember the * One derivation pass over the client's own session state: remember the
* freshest snapshot for the settle tick, compare it against what this page * freshest snapshot for the settle tick, compare it against what this page
* already observed, emit at most one candidate per transition, and let the * already observed, emit at most one candidate per transition, and let the
* settle tick decide delivery. * settle tick decide delivery. The window state is deliberately NOT captured
* here — the delivery reads it fresh, because it can change inside the
* settle window.
*/ */
const observe = (focus, list, status) => { const observe = (list, status) => {
if (list === undefined || status === undefined) return if (list === undefined || status === undefined) return
state.live = { list, status, focus } state.live = { list, status }
const kinds = store.getSnapshot().kinds const kinds = store.getSnapshot().kinds
for (const sessionId of Object.keys(list.byId ?? {})) { for (const sessionId of Object.keys(list.byId ?? {})) {
const summary = list.byId[sessionId] const summary = list.byId[sessionId]
@@ -802,18 +1030,36 @@ window.__ModuleLoader__.load({
// --------------------------------------------------------------- actions // --------------------------------------------------------------- actions
/** Raise one test notification through the channel the current state selects. */ /** Build one test alert that skips the throttle and the "on screen" rule. */
const testCandidate = (title) => ({
kind: 'completion',
sessionId: 'test',
title,
detail: '',
pendingKind: '',
test: true,
})
/**
* Raise one test alert through whichever channel the window state selects.
* Verified from the config page, where the user is looking at the app, so it
* normally lands in the popup — the way to prove the system channel is to
* press the button in a channel-specific test instead.
*/
const sendTest = () => { const sendTest = () => {
const candidate = { deliver(testCandidate(t('config.testAny')), true)
kind: 'completion', }
sessionId: 'test',
title: t('settings.title'), /** Raise the test alert on the system channel specifically, whatever the focus is. */
detail: '', const sendTestSystem = () => {
pendingKind: '', const candidate = testCandidate(t('config.testSystem'))
test: true, const result = systemNotify(candidate, true)
if (result.outcome === 'raised') {
recordDelivery('system', candidate, result)
return
} }
if (!currentFocus() && notificationPermission() === 'granted' && systemNotify(candidate, true)) return
showToast(candidate) showToast(candidate)
recordDelivery(`system-refused-${result.outcome}`, candidate)
} }
/** Request notification permission inside a user gesture, then report the outcome. */ /** Request notification permission inside a user gesture, then report the outcome. */
@@ -856,21 +1102,27 @@ window.__ModuleLoader__.load({
return React.useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot) return React.useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot)
} }
/** The window's focus state as a React value, kept current by the DOM's own events. */ /**
function useFocus() { * Subscribe to every browser signal that says whether the app is visible:
* the window's focus events and the document's visibility change. The value
* itself is a boolean, so the observer re-renders once per transition.
*/
function useWindowState() {
const subscribe = React.useCallback((listener) => { const subscribe = React.useCallback((listener) => {
try { try {
window.addEventListener('focus', listener) window.addEventListener('focus', listener)
window.addEventListener('blur', listener) window.addEventListener('blur', listener)
document.addEventListener('visibilitychange', listener)
} catch { } catch {
return () => {} return () => {}
} }
return () => { return () => {
window.removeEventListener('focus', listener) window.removeEventListener('focus', listener)
window.removeEventListener('blur', listener) window.removeEventListener('blur', listener)
document.removeEventListener('visibilitychange', listener)
} }
}, []) }, [])
return React.useSyncExternalStore(subscribe, currentFocus, () => true) return React.useSyncExternalStore(subscribe, () => !windowIsAway(), () => true)
} }
/** /**
@@ -878,9 +1130,13 @@ window.__ModuleLoader__.load({
* how a plugin reaches the session hooks without occupying visible UI. It * how a plugin reaches the session hooks without occupying visible UI. It
* renders `null`, and any failure in its own derivation is contained here so * renders `null`, and any failure in its own derivation is contained here so
* a slot entry can never crash. * a slot entry can never crash.
*
* It subscribes to the window state only so a foreground/background change
* re-derives promptly; the delivery itself re-reads that state, so a missed
* event can no longer pick the wrong channel.
*/ */
function NotifyObserver(props) { function NotifyObserver(props) {
const focus = useFocus() useWindowState()
const useSessions = props.useSessions const useSessions = props.useSessions
const useSessionStatus = props.useSessionStatus const useSessionStatus = props.useSessionStatus
const select = React.useCallback((snapshot) => snapshot, []) const select = React.useCallback((snapshot) => snapshot, [])
@@ -896,7 +1152,7 @@ window.__ModuleLoader__.load({
applyHealth(store, { state: 'starting', message: '' }) applyHealth(store, { state: 'starting', message: '' })
return return
} }
observe(focus, list, status) observe(list, status)
applyHealth(store, { state: 'watching', message: '' }) applyHealth(store, { state: 'watching', message: '' })
} catch (error) { } catch (error) {
applyHealth(store, { state: 'error', message: text(error) }) applyHealth(store, { state: 'error', message: text(error) })
@@ -1012,9 +1268,11 @@ window.__ModuleLoader__.load({
return h(React.Fragment, null, return h(React.Fragment, null,
h('style', null, CSS), h('style', null, CSS),
h('div', { className: 'dsn-sections' }, h('div', { className: 'dsn-sections' },
// The page header already shows this bundle's title and description, so
// this section opens with what the header cannot say: how alerts are
// carried, and what this form changes.
h('section', { className: 'dsn-section' }, h('section', { className: 'dsn-section' },
h('h3', { className: 'dsn-section-title' }, tr('config.title')), h('p', { className: 'dsn-section-desc' }, tr('config.intro'))),
h('p', { className: 'dsn-section-desc' }, tr('config.note'))),
h('section', { className: 'dsn-section' }, h('section', { className: 'dsn-section' },
h('h3', { className: 'dsn-section-title' }, tr('config.section.kinds')), h('h3', { className: 'dsn-section-title' }, tr('config.section.kinds')),
KINDS.map((kind) => h(KindRow, { KINDS.map((kind) => h(KindRow, {
@@ -1037,37 +1295,82 @@ window.__ModuleLoader__.load({
type: 'button', type: 'button',
className: 'dsn-button', className: 'dsn-button',
disabled: !supported, disabled: !supported,
onClick: permission === 'granted' ? props.test : props.ask, onClick: permission === 'granted' ? props.testSystem : props.ask,
}, tr(!supported }, tr(!supported
? 'settings.action.unsupported' ? 'settings.action.unsupported'
: permission === 'granted' ? 'settings.action.test' : 'settings.action.allow')))), : permission === 'granted' ? 'settings.action.testSystem' : 'settings.action.allow'))),
h('p', { className: 'dsn-section-desc' }, tr('config.testHint'))),
h('section', { className: 'dsn-section' }, h('section', { className: 'dsn-section' },
h('h3', { className: 'dsn-section-title' }, tr('config.section.status')), h('h3', { className: 'dsn-section-title' }, tr('config.section.status')),
h('div', { className: 'dsn-row' }, h('div', { className: 'dsn-row' },
h('div', { className: 'dsn-row-text' }, h('div', { className: 'dsn-row-text' },
h('p', { className: 'dsn-status' }, `${tr('config.diag.window')}: ${tr(windowIsAway() ? 'config.diag.away' : 'config.diag.inFront')}`),
h('p', { h('p', {
className: `dsn-status${healthFailed ? ' dsn-status-error' : ''}`, className: `dsn-status${healthFailed ? ' dsn-status-error' : ''}`,
role: healthFailed ? 'alert' : 'status', role: healthFailed ? 'alert' : 'status',
}, healthText)))))) }, healthText),
h('p', { className: 'dsn-status' }, deliveryText(tr)),
h('p', { className: 'dsn-status' }, replayText(tr))),
h('button', {
type: 'button',
className: 'dsn-button',
onClick: props.testAny,
}, tr('settings.action.testAny'))))))
}
/** Describe the newest alert's fate in one line. */
function deliveryText(tr) {
const last = store.getSnapshot().lastDelivery
if (last === null || last === undefined) return tr('config.diag.none')
const outcome = last.outcome.startsWith('system-refused')
? tr('config.diag.refused')
: last.outcome === 'system'
? last.shown === true
? tr('config.diag.systemShown')
: last.shown === false
? tr('config.diag.systemFailed')
: tr('config.diag.systemUnconfirmed')
: last.outcome === 'replay'
? tr('config.diag.replayDelivery')
: tr('config.diag.popup')
return `${tr('config.diag.last')}: ${last.at} · ${outcome} · ${last.title}`
}
/** Say how many away-channel alerts are still waiting to be replayed in-app. */
function replayText(tr) {
const pending = state.replay.length
return pending === 0 ? tr('config.diag.replayNone') : tr('config.diag.replay', { count: pending })
} }
// ---------------------------------------------------------- registration // ---------------------------------------------------------- registration
/** Keep the page's own focus events owned by this plugin's effect. */ /** Keep the page's own focus events owned by this plugin's effect. */
const installBridges = () => { const installBridges = () => {
const onFocusChange = () => { const onBlur = () => {
state.lastDelivery = 0 state.lastDelivery = 0
} }
// Coming back is the moment the user can finally be told about whatever the
// system channel carried while the window was away, and it also clears the
// throttle so the first alert after returning is never swallowed.
const onReturn = () => {
state.lastDelivery = 0
flushReplay()
}
const onVisibilityChange = () => {
if (!windowIsAway()) onReturn()
}
try { try {
window.addEventListener('focus', onFocusChange) window.addEventListener('focus', onReturn)
window.addEventListener('blur', onFocusChange) window.addEventListener('blur', onBlur)
document.addEventListener('visibilitychange', onVisibilityChange)
} catch { } catch {
/* an unreadable window still delivers through live focus reads */ /* an unreadable window still delivers through live focus reads */
} }
return () => { return () => {
try { try {
window.removeEventListener('focus', onFocusChange) window.removeEventListener('focus', onReturn)
window.removeEventListener('blur', onFocusChange) window.removeEventListener('blur', onBlur)
document.removeEventListener('visibilitychange', onVisibilityChange)
} catch { } catch {
/* nothing to detach */ /* nothing to detach */
} }
@@ -1077,6 +1380,8 @@ window.__ModuleLoader__.load({
} }
for (const timer of timers.values()) clearTimeout(timer) for (const timer of timers.values()) clearTimeout(timer)
timers.clear() timers.clear()
state.raised.clear()
state.replay = []
} }
} }
@@ -1116,7 +1421,8 @@ window.__ModuleLoader__.load({
store, store,
platform: platformKey(), platform: platformKey(),
ask: requestPermission, ask: requestPermission,
test: sendTest, testAny: sendTest,
testSystem: sendTestSystem,
setKind: setKindEnabled, setKind: setKindEnabled,
}), }),
}, ConfigSection)) }, ConfigSection))
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@dsh-plugin/session-notify", "name": "@dsh-plugin/session-notify",
"version": "1.0.3", "version": "1.0.6",
"private": true, "private": true,
"type": "module", "type": "module",
"description": "会话完成、需要授权、需要回答时提醒你:窗口不在前台用系统通知,窗口在前台用应用内轻弹窗。", "description": "会话完成、需要授权、需要回答时提醒你:窗口不在前台用系统通知,窗口在前台用应用内轻弹窗。",