@idoall/dsh-notify 0.5.2 → 0.6.0

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,23 @@
2
2
 
3
3
  All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). GitHub Releases use the same bilingual layout as [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness/releases/tag/dsh-v0.1.6-alpha.1).
4
4
 
5
+ ## [0.6.0] - 2026-11-28
6
+
7
+ ### Added
8
+
9
+ - **The subtask switch now covers subagent sessions.** `subtaskNotify` used to gate only background jobs and workflows; subagent completions were unconditionally silent even though the settings row said otherwise. When the switch is on, each finished child session becomes one `子任务完成` card (or `子任务失败` for an error), with the label the parent recorded in `subagent/catalog` as its body and the child session as its target. Off stays the default, so the page announces the main task only.
10
+
11
+ ### Fixed
12
+
13
+ - **An auto-continuing goal no longer raises one completion card per round.** A goal that stays `armed` keeps starting another round; each round's `turn/end` plus native `idle` looked exactly like a finished task, so a long anchor session produced a green card for every round. The host now follows `goal/activation-changed`: while a goal is armed, a round end is an intermediate idle and is dropped; the card appears after the goal disarms and the final turn ends. The same rule applies to the race where the next round starts in a later stack instead of synchronously.
14
+ - **A stopped goal no longer masquerades as 任务完成.** When the model or a supervisor blocks the goal, the turn that stops is announced once as `任务受阻` with the recorded reason (and an error tone) instead of a green completion; a deliberate pause or clear stays silent.
15
+ - **A parent completion waits for its running subagents.** The async `subagent` tool returns before the child ends, so a parent can reach `idle` while its child still works. The parent's card is now held until the last child stops; if the parent wakes to consume the child result, the held card is cancelled, otherwise it is released once after a short settle window. A subagent that only runs inline (parent stays running) is unchanged.
16
+ - **Deferred completions can no longer be stranded by an ended goal.** The legacy engaged-goal hold is retained for hosts without `agent/status`; on lifecycle-capable hosts a disarm edge now clears an intermediate candidate instead of leaving it queued behind a goal that already stopped.
17
+
18
+ ### Verified
19
+
20
+ - Static checks, **137 automated tests**, build and package checks pass. New coverage: goal-armed rounds stay silent while the disarmed final turn announces exactly once; a blocked goal reports `任务受阻` with its reason while a pause stays silent; a parent completion waits for a running child and is cancelled when the parent resumes; the subtask switch keeps subagent turns silent by default and, when enabled, emits one labelled card with a stable identity across `agent/error` and its later `turn/end`.
21
+
5
22
  ## [0.5.2] - 2026-11-24
6
23
 
7
24
  ### Fixed
package/README.md CHANGED
@@ -35,8 +35,8 @@ When a session really stops, fails, asks a question, or needs approval, a card a
35
35
  - **Direct, traceable navigation.** Clicking a card opens its session and the exact originating turn. After the host selects that session, the selected row is smoothly revealed in the left session tree, even when it lives in a different off-screen workspace. A card stays put with an explanation if navigation cannot succeed.
36
36
  - **Answer in the toast.** A pending question or approval renders the same compatible options as the composer. Execution approvals and plan reviews share DSH's amber decision colour; ordinary questions remain blue. In-card and composer answers share the same host interaction.
37
37
  - **Sound and background attention.** Built-in WebAudio cues and validated custom uploads play only after a card is admitted to an enabled visual Toast queue, including while the page is hidden. One polling batch produces one cue. A background tab with unseen notifications receives a temporary bell prefix and favicon attention marker.
38
- - **Completion means native idle, once per task.** A green card waits until DSH reports the owning Agent as `idle`, matching the session-tree spinner instead of guessing from a rendered answer or an elapsed timer. A plan review and an execution approval are control gates, so their temporary idle pause does not create an extra completion card; the later work turn supplies the one card. An ordinary question is different: if its answer directly finishes the task, that same turn still produces one green card. If work resumes, the prior candidate is cancelled and only the final native-idle transition is announced.
39
- - **Task-noise control.** Subtask, background-job, and workflow completion notifications are off by default.
38
+ - **Completion means native idle, once per task.** A green card waits until DSH reports the owning Agent as `idle`, matching the session-tree spinner instead of guessing from a rendered answer or an elapsed timer. A plan review and an execution approval are control gates, so their temporary idle pause does not create an extra completion card; the later work turn supplies the one card. An ordinary question is different: if its answer directly finishes the task, that same turn still produces one green card. If work resumes, the prior candidate is cancelled and only the final native-idle transition is announced. A goal that keeps auto-continuing is treated the same way: while it is armed, every round end is an intermediate idle and stays silent; the card appears only after the goal disarms and the final turn ends. A goal that stops because the model or a supervisor blocks it says `任务受阻` with the recorded reason (error tone), and a deliberate pause or clear stays silent. While a dispatched subagent is still running, its parent's completion is held; if the parent wakes to consume the result, the held card is cancelled, otherwise it is released once the parent really stays idle.
39
+ - **Task-noise control.** Subtask, background-job, and workflow completion notifications are off by default, so the main task is the only thing the page announces. Turning the switch on adds one card per finished subagent session (`子任务完成` / `子任务失败`), background job, or workflow.
40
40
  - **Online version detection.** The settings page shows the running version against the newest one published on npm, with **Check for updates**, GitHub, Changelog and Issues links. The check is read-only: the host asks the registry, reports, and shows a copyable upgrade command — it never installs anything and never restarts DSH. An unreachable registry renders as a failed check instead of presenting the running version as the newest.
41
41
  - **No history by design.** Notification records are held only in the open page's in-memory queue. Settled history is never replayed after a refresh or overlay remount; an interaction that is still open when the host can report it is restored silently.
42
42
 
@@ -87,7 +87,7 @@ Reload the profile or restart DSH only when its plugin host has not hot-reloaded
87
87
  | Notification style | **Enhanced** | Enhanced uses clear status colours and a short attention bar; Soft uses a quieter presentation. |
88
88
  | Collapse multiple notifications | **on** | From two cards onward, show the newest card fully and stack older cards below it; hover or focus expands them. |
89
89
  | In-page sound | **on** | Plays one cue when a polling batch admits one or more new visible Toasts, including while DSH is in a background tab. Built-ins: chime, ping, alert, silent; custom uploads are supported. |
90
- | Subtask / background completion | **off** | Enables notifications for subagents, background jobs, and workflows, which can otherwise be noisy. |
90
+ | Subtask / background completion | **off** | Keeps the page to main-task completion only. Turn it on to also announce every finished subagent session (with the catalog label), background job, and workflow. |
91
91
  | Preview and self-test | — | Sends page-local examples only: **Completed**, **Confirm**, **Failed**, **Info**, replay all four styles, fold the active examples, or clear them. No test sends a system notification or changes a real task. |
92
92
 
93
93
  Custom sounds are stored in `<dataDir>/sounds/` in the profile data directory, not the plugin installation. Uploads are limited to 1 MB and `mp3 / m4a / aac / wav / ogg / flac`; names must be a single path segment.
@@ -100,11 +100,12 @@ Above the cards, the page shows the running version against the newest one on np
100
100
 
101
101
  ## Compatibility
102
102
 
103
- Current release: plugin **`0.5.2`** is verified against DeepSeek Harness **`0.2.3-alpha.2`**.
103
+ Current release: plugin **`0.6.0`** is verified against DeepSeek Harness **`0.2.3-alpha.2`**.
104
104
 
105
105
  | Plugin | Verified DeepSeek Harness | What that version is |
106
106
  | --- | --- | --- |
107
- | **`0.5.2`** | `0.2.3-alpha.2` | Fixes the tab marker outliving the notification: closing, clearing, answering or jumping from a card now drops it from the unread set at the click, and the marker is recomputed from the cards still on screen. Stopping also stops reverting a session title the host renamed meanwhile. |
107
+ | **`0.6.0`** | `0.2.3-alpha.2` | Notifies only when the main task really ends. A goal that is still auto-continuing no longer raises one card per round, and a parent whose subagent is still running holds its completion until the child settles. The subtask switch now actually covers subagent sessions: when enabled, each finished child produces one `子任务完成` / `子任务失败` card labelled from `subagent/catalog`; it stays off by default. |
108
+ | `0.5.2` | `0.2.3-alpha.2` | Fixes the tab marker outliving the notification: closing, clearing, answering or jumping from a card now drops it from the unread set at the click, and the marker is recomputed from the cards still on screen. Stopping also stops reverting a session title the host renamed meanwhile. |
108
109
  | `0.5.1` | `0.2.3-alpha.2` | Fixes the window covering the session toolbar: its vertical start is now measured from the conversation body (8px below it, 56px floor) instead of a hardcoded 56px offset, and follows resizes and zoom. The screen-corner placement keeps its own variable. |
109
110
  | `0.5.0` | `0.2.3-alpha.2` | Puts the notification window in the conversation's **top-left** corner by default — the settings page keeps the top-right corner, the screen corner and off as alternatives. Adds the left-edge anchor and re-anchors it through the same sidebar-following observer. Notification content, sounds and triggers are unchanged. |
110
111
  | `0.4.17` | `0.2.3-alpha.2` | **Fixes two breaks on the current host.** DSH moved HTTP admission into the WebServer and removed `Connection.requestRejection` — routes now declare `auth: 'required'` and call the method only when it still exists — and moved the Session status snapshot behind a `uiSession.sessionStatus` service that throws unless injected, so the toast reads the injection-free `uiSession.pendingInteractions` source instead. `0.4.16` failed every plugin endpoint and lost in-toast answering on this host. |
@@ -172,8 +173,8 @@ npm run pack:check # publish preconditions + client registration check
172
173
  Releases are tag-driven. Bump `package.json` and the lockfile root versions, synchronize both READMEs and the DSH declarations, move the matching CHANGELOG section out of `Unreleased`, write `release-notes/v<version>.md`, then push the release commit and tag:
173
174
 
174
175
  ```sh
175
- git tag v0.5.2
176
- git push origin v0.5.2
176
+ git tag v0.6.0
177
+ git push origin v0.6.0
177
178
  ```
178
179
 
179
180
  The release workflow runs `npm run verify`, packs the plugin, publishes through npm trusted publishing (OIDC), and creates a GitHub Release with the package tarball and sha256.
package/README.zh.md CHANGED
@@ -35,8 +35,8 @@
35
35
  - **可追溯的会话跳转**:点通知会打开对应会话并定位到来源轮次。宿主选中会话后,左侧会话树会自动平滑滚动并展示已选行,即使它位于另一个屏幕外工作区。跳转失败时卡片会留在原地说明原因。
36
36
  - **在卡片内回答**:待回复问题或审批会显示可兼容的输入框选项;执行审批与计划待审沿用 DSH 的橙色决策语义,普通需要回复保持蓝色;卡片内回答与输入框操作同一份宿主交互。
37
37
  - **提示音与后台提醒**:通知成功进入已启用的可视 Toast 队列后,才会播放内置 WebAudio 或经过校验的自定义提示音;页面在后台时也适用。同一轮轮询的一批通知只播放一次。后台标签有未查看通知时,标题和 favicon 会短暂提示。
38
- - **完成以原生 idle 为准,并且每项任务只通知一次**:绿色完成卡等待 DSH 报告所属 Agent 为 `idle` 才发送,和左侧会话树转圈停止一致;不再依据已渲染的回答或计时器猜测。计划待审和执行审批是控制门:它们短暂进入 idle 不会额外生成完成卡,批准后的后续工作轮才产生唯一一张。普通需要回复不同:如果你的回答直接结束任务,该轮仍会产生一张绿色完成卡;若之后又继续运行,旧候选会被取消,最终只通知真正结束的 native-idle 状态。
39
- - **任务噪声控制**:子任务、后台任务与工作流完成通知默认关闭。
38
+ - **完成以原生 idle 为准,并且每项任务只通知一次**:绿色完成卡等待 DSH 报告所属 Agent 为 `idle` 才发送,和左侧会话树转圈停止一致;不再依据已渲染的回答或计时器猜测。计划待审和执行审批是控制门:它们短暂进入 idle 不会额外生成完成卡,批准后的后续工作轮才产生唯一一张。普通需要回复不同:如果你的回答直接结束任务,该轮仍会产生一张绿色完成卡;若之后又继续运行,旧候选会被取消,最终只通知真正结束的 native-idle 状态。goal 自动续跑同理:只要 goal 仍处于 `armed`,每一轮结束都只是中间 idle,不会通知;直到 goal 解除自动续跑、收尾轮真正结束才出现一张卡。若 goal 因为模型或督导判定受阻而停下,会发一张带原因的「任务受阻」(错误色);主动暂停或清除则保持安静。派出的子代理仍在运行时,主会话的完成卡会被压住:主会话醒来继续处理就取消,确实停住才补发。
39
+ - **任务噪声控制**:子任务、后台任务与工作流完成通知默认关闭,页面只通知主任务。开启后,每个结束的子代理会话(带 `subagent/catalog` 的可读标签,显示「子任务完成 / 子任务失败」)、后台任务与工作流各发一条。
40
40
  - **在线版本检测**:设置页会显示当前版本与 npm 上最新版本,并提供**检查更新**、GitHub、更新日志、反馈 Issue 入口。检测只读:宿主只查询 registry 并汇报,同时给出可复制的升级命令,绝不自动安装、也绝不重启 DSH。registry 不可达时显示「检查失败」,而不会把当前版本谎称为最新。
41
41
  - **无历史设计**:通知仅保存在当前页面内存中;刷新或 Toast 浮层重新挂载后,不会回放已结算历史;若宿主仍能报告未处理交互,则会静默恢复。
42
42
 
@@ -87,7 +87,7 @@ dsh plugin --profile web add "link:$(pwd)"
87
87
  | 通知样式 | **增强版** | 增强版使用清晰状态色和短提醒条;柔和版更克制。 |
88
88
  | 多条通知折叠显示 | **开** | 从两条开始完整显示最新一条,旧卡叠在下方;悬停或聚焦即可展开。 |
89
89
  | 页内提示音 | **开** | 一轮轮询只要有一条或多条新 Toast 成功进入可视队列,就播放一次提示音,即使 DSH 标签在后台。内置 chime / ping / alert / 静音,也可上传自定义声音。 |
90
- | 子任务 / 后台任务完成时通知 | **关** | 开启子代理、后台任务与工作流的完成通知;默认避免噪声。 |
90
+ | 子任务 / 后台任务完成时通知 | **关** | 默认只通知主任务。开启后,每个结束的子代理会话(正文取自 `subagent/catalog` 的标签)、后台任务与工作流也会各发一条。 |
91
91
  | 预览与自测 | — | 仅发送当前页面的完成、确认、失败、信息示例;也可重播四种状态、折叠当前示例或清空。不会发系统通知,也不影响真实任务。 |
92
92
 
93
93
  自定义提示音保存在 profile 数据目录的 `<dataDir>/sounds/`,而非插件安装目录。上传限制 1 MB,支持 `mp3 / m4a / aac / wav / ogg / flac`,文件名必须是单段路径。
@@ -100,11 +100,12 @@ dsh plugin --profile web add "link:$(pwd)"
100
100
 
101
101
  ## 兼容性
102
102
 
103
- 当前发布:插件 **`0.5.2`** 已在 DeepSeek Harness **`0.2.3-alpha.2`** 上验证。
103
+ 当前发布:插件 **`0.6.0`** 已在 DeepSeek Harness **`0.2.3-alpha.2`** 上验证。
104
104
 
105
105
  | 插件 | 已验证的 DeepSeek Harness | 这一版是什么 |
106
106
  | --- | --- | --- |
107
- | **`0.5.2`** | `0.2.3-alpha.2` | 修复「通知已处理、标签页提示还在」:关闭/全部清除/回答/跳转卡片时立刻把它从未读集合里移除,并按仍在屏上的卡片重算提示;同时不再把宿主期间改过的会话标题回滚。 |
107
+ | **`0.6.0`** | `0.2.3-alpha.2` | 只在主任务真正结束时通知。goal 仍在自动续跑时不再每轮弹一张完成卡;主会话还有子代理在跑时先压住,子代理结束而主会话确实停住才补发。设置里的「子任务 / 后台任务完成时通知」现在真正覆盖子代理会话:开启后每个结束的子会话都会生成一张带目录标签的「子任务完成 / 子任务失败」卡,默认保持关闭。 |
108
+ | `0.5.2` | `0.2.3-alpha.2` | 修复「通知已处理、标签页提示还在」:关闭/全部清除/回答/跳转卡片时立刻把它从未读集合里移除,并按仍在屏上的卡片重算提示;同时不再把宿主期间改过的会话标题回滚。 |
108
109
  | `0.5.1` | `0.2.3-alpha.2` | 修复浮层盖住会话工具栏的问题:起点改为量取会话正文上沿(再下移 8px,56px 为下限),不再是写死的 56px 偏移,并随窗口尺寸与缩放跟随。屏幕右上仍用自己的变量定位。 |
109
110
  | `0.5.0` | `0.2.3-alpha.2` | 通知浮层默认改到会话区**左上角**——设置页保留「会话区右上」「屏幕右上」「关闭页面通知」作为备选。新增左边缘锚点,并复用同一套跟随侧栏的观察器实时重定位。通知内容、提示音与触发时机均未变。 |
110
111
  | `0.4.17` | `0.2.3-alpha.2` | **修复当前宿主上的两处断裂。** DSH 把 HTTP admission 移进 WebServer 并删除了 `Connection.requestRejection`——路由改为声明 `auth: 'required'`,仅在该方法仍存在时才调用;同时把 Session 状态快照移到需要注入的 `uiSession.sessionStatus` 服务,浮层改用无需注入的 `uiSession.pendingInteractions`。在本宿主上 `0.4.16` 的所有插件端点失败,卡片内回答也失效。 |
@@ -172,8 +173,8 @@ npm run pack:check # 发布前置条件 + 客户端注册校验
172
173
  发版由 tag 驱动。更新 `package.json` 与锁文件根版本、同步中英文 README 和 DSH 声明、将对应 CHANGELOG 段落移出 `Unreleased`、编写 `release-notes/v<版本>.md` 后,推送发版提交与 tag:
173
174
 
174
175
  ```sh
175
- git tag v0.5.2
176
- git push origin v0.5.2
176
+ git tag v0.6.0
177
+ git push origin v0.6.0
177
178
  ```
178
179
 
179
180
  发版工作流会运行 `npm run verify`、打包插件、通过 npm trusted publishing(OIDC)发布,并创建附带 tarball 与 sha256 的 GitHub Release。
package/dist/client.js CHANGED
@@ -578,7 +578,7 @@ window.__ModuleLoader__.load({
578
578
  function toastOrder(records = []) {
579
579
  return [...records.filter((record) => record?.phase === "open"), ...records.filter((record) => record?.phase !== "open")];
580
580
  }
581
- var TOAST_TONE_BY_KIND = Object.freeze({ approval: "warning", question: "info", "plan-review": "warning", completed: "success", failed: "error", "job-end": "neutral", "workflow-end": "neutral", test: "neutral" });
581
+ var TOAST_TONE_BY_KIND = Object.freeze({ approval: "warning", question: "info", "plan-review": "warning", completed: "success", "subagent-end": "success", failed: "error", "job-end": "neutral", "workflow-end": "neutral", test: "neutral" });
582
582
  function toastTone(kind) {
583
583
  return TOAST_TONE_BY_KIND[kind] ?? "neutral";
584
584
  }
@@ -1393,7 +1393,7 @@ window.__ModuleLoader__.load({
1393
1393
  event.target.value = "";
1394
1394
  if (file) void uploadSound(file);
1395
1395
  } }))), soundNotice ? import_react.default.createElement("p", { className: "dsh-notify-result", role: "status" }, soundNotice) : null, customSounds.length > 0 && import_react.default.createElement("div", { className: "dsh-notify-actions" }, customSounds.map((sound) => action(`\u5220\u9664 ${sound.name}`, () => void removeSound(sound.name), { "data-variant": "danger" }))))),
1396
- config && card("\u2713", "\u4EFB\u52A1\u63D0\u9192", "\u9009\u62E9\u54EA\u4E9B\u4EFB\u52A1\u7ED3\u679C\u4F1A\u4E3B\u52A8\u51FA\u73B0\u5728\u4F60\u7684\u901A\u77E5\u5217\u8868\u4E2D\u3002", import_react.default.createElement("div", { className: "dsh-notify-rows" }, toggle("\u5B50\u4EFB\u52A1 / \u540E\u53F0\u4EFB\u52A1\u5B8C\u6210\u65F6\u901A\u77E5", "\u9ED8\u8BA4\u5173\u95ED\u3002\u5F00\u542F\u540E\uFF0C\u6BCF\u4E2A\u5B50\u4EE3\u7406\u6216\u540E\u53F0\u4EFB\u52A1\u7ED3\u675F\u65F6\u90FD\u4F1A\u901A\u77E5\u4F60\u3002", Boolean(config.subtaskNotify), (event) => update({ subtaskNotify: event.target.checked }), "\u5B50\u4EFB\u52A1 / \u540E\u53F0\u4EFB\u52A1\u5B8C\u6210\u65F6\u901A\u77E5"))),
1396
+ config && card("\u2713", "\u4EFB\u52A1\u63D0\u9192", "\u9009\u62E9\u54EA\u4E9B\u4EFB\u52A1\u7ED3\u679C\u4F1A\u4E3B\u52A8\u51FA\u73B0\u5728\u4F60\u7684\u901A\u77E5\u5217\u8868\u4E2D\u3002", import_react.default.createElement("div", { className: "dsh-notify-rows" }, toggle("\u5B50\u4EFB\u52A1 / \u540E\u53F0\u4EFB\u52A1\u5B8C\u6210\u65F6\u901A\u77E5", "\u9ED8\u8BA4\u5173\u95ED\uFF1A\u53EA\u5728\u4E3B\u4EFB\u52A1\u771F\u6B63\u7ED3\u675F\u65F6\u901A\u77E5\u4E00\u6B21\u3002\u5F00\u542F\u540E\uFF0C\u6BCF\u4E2A\u5B50\u4EE3\u7406\u4F1A\u8BDD\u3001\u540E\u53F0\u4EFB\u52A1\u6216\u5DE5\u4F5C\u6D41\u7ED3\u675F\u65F6\u4E5F\u4F1A\u5404\u53D1\u4E00\u6761\u3002", Boolean(config.subtaskNotify), (event) => update({ subtaskNotify: event.target.checked }), "\u5B50\u4EFB\u52A1 / \u540E\u53F0\u4EFB\u52A1\u5B8C\u6210\u65F6\u901A\u77E5"))),
1397
1397
  config && card("\u2197", "\u9884\u89C8\u4E0E\u81EA\u6D4B", "\u4EC5\u5728\u5F53\u524D\u9875\u9762\u5C55\u793A\u6A21\u62DF\u901A\u77E5\uFF0C\u4E0D\u53D1\u9001\u7CFB\u7EDF\u901A\u77E5\uFF0C\u4E5F\u4E0D\u5F71\u54CD\u771F\u5B9E\u4EFB\u52A1\u3002", import_react.default.createElement(NotificationSelfTests))
1398
1398
  );
1399
1399
  }
package/dist/core.js CHANGED
@@ -64,7 +64,12 @@ export class EventReducer {
64
64
  // An interrupted turn emits no `approval/decided`, so a replay re-asks an interaction the user
65
65
  // already settled. A resolved interaction stays resolved; a replay of it is not news.
66
66
  if (existing.phase !== 'open' && (input.phase ?? 'settled') === 'open') return null;
67
- return Object.assign(existing, input, { eventId: existing.eventId });
67
+ const patch = { ...input, eventId: existing.eventId };
68
+ // An update must go through the same redaction as a first arrival, and an empty follow-up body
69
+ // (a `turn/end` that carried no message) must not erase the error the immediate card already had.
70
+ if (patch.body === undefined || patch.body === '') delete patch.body;
71
+ else patch.body = sanitizeBody(patch.body, input.verbosity);
72
+ return Object.assign(existing, patch);
68
73
  }
69
74
  const record = { eventId: this.makeId(), kind: input.kind, mergeKey: input.mergeKey, sessionId: input.sessionId, title: sanitizeBody(input.title || input.kind), body: sanitizeBody(input.body, input.verbosity), at: this.now(), phase: input.phase || 'settled', outcome: input.outcome, deepLink: input.deepLink, ...(Number.isSafeInteger(input.turn) && input.turn > 0 ? { turn: input.turn } : {}) };
70
75
  this.records.set(input.mergeKey, record);
@@ -148,13 +153,39 @@ export class EventReducer {
148
153
  }
149
154
  return expired;
150
155
  }
151
- turnEnd(event) {
152
- if (event.origin === 'subagent' || !isNotifiableEnd(event.reason)) return null;
153
- const reason = typeof event.reason === 'string' ? event.reason : event.reason.kind;
156
+ turnEnd(event, options = {}) {
157
+ const reason = isNotifiableEnd(event.reason) ? (typeof event.reason === 'string' ? event.reason : event.reason.kind) : undefined;
154
158
  const failed = reason === 'error';
159
+ // A subagent turn is a subtask, not the main task: it stays silent unless the user opted into
160
+ // subtask notifications. The label comes from the parent's `subagent/catalog` record.
161
+ if (event.origin === 'subagent') {
162
+ if (!isNotifiableEnd(event.reason) || options.subagentNotify !== true) return null;
163
+ const label = event.label || options.label;
164
+ const key = `subagent:${event.sessionId}:${event.turn}`;
165
+ // A label is a title-grade hint, not an error detail: never let it overwrite the message an
166
+ // earlier `agent/error` already delivered on this card.
167
+ const body = failed
168
+ ? (event.body || event.reason?.error?.message || (this.records.get(key)?.body ? undefined : label))
169
+ : (label || event.body);
170
+ return this.upsert({ kind: failed ? 'failed' : 'subagent-end', mergeKey: key, sessionId: event.sessionId, title: failed ? '子任务失败' : '子任务完成', body, phase: 'settled', outcome: reason, turn: event.turn });
171
+ }
172
+ // A goal that had to stop is not a completion, but it still ends the main task the human was
173
+ // waiting on. Report the state and the supervisor/model reason instead of a green 任务完成.
174
+ if (event.goalStop?.state === 'blocked') {
175
+ // If an error already produced this turn's card, update that card instead of adding a second.
176
+ const failKey = `fail:${event.sessionId}:${event.turn}`;
177
+ const key = failed || this.records.has(failKey) ? failKey : `turn:${event.sessionId}:${event.turn}`;
178
+ return this.upsert({ kind: 'failed', mergeKey: key, sessionId: event.sessionId, title: '任务受阻', body: event.goalStop.reason || event.body, phase: 'settled', outcome: 'blocked', turn: event.turn });
179
+ }
180
+ if (!isNotifiableEnd(event.reason)) return null;
155
181
  return this.upsert({ kind: failed ? 'failed' : 'completed', mergeKey: `${failed ? 'fail' : 'turn'}:${event.sessionId}:${event.turn}`, sessionId: event.sessionId, title: failed ? '运行失败' : '任务完成', body: event.body || event.reason?.error?.message, phase: 'settled', outcome: reason, turn: event.turn });
156
182
  }
157
- agentError(event) {
183
+ agentError(event, options = {}) {
184
+ // A subtask failure shares its card identity with the `turn/end` that may follow, so the two
185
+ // arrivals update one card instead of queueing two.
186
+ if (options.subagent === true) {
187
+ return this.upsert({ kind: 'failed', mergeKey: `subagent:${event.sessionId}:${event.turn}`, sessionId: event.sessionId, title: '子任务失败', body: event.message || event.error?.message || options.label || String(event.error || ''), phase: 'settled', outcome: 'error', turn: event.turn });
188
+ }
158
189
  return this.upsert({ kind: 'failed', mergeKey: `fail:${event.sessionId}:${event.turn}`, sessionId: event.sessionId, title: '运行失败', body: event.message || event.error?.message || String(event.error || ''), phase: 'settled', outcome: 'error', turn: event.turn });
159
190
  }
160
191
  }
package/dist/index.js CHANGED
@@ -299,24 +299,104 @@ export async function apply(ctx, config = {}) {
299
299
  const completionGraceMs = Number.isSafeInteger(config.completionGraceMs) ? config.completionGraceMs : 8_000;
300
300
  const deferredCompletions = new Map(); // sessionId -> { payload, timer }
301
301
  const engagedGoals = new Set(); // only used for a legacy host without agent/status
302
+ const armedGoals = new Set(); // status-capable sessions whose goal auto-continues
303
+ const goalStops = new Map(); // sessionId -> { state, reason?, turn }, one terminal goal edge
302
304
  const agentStatuses = new Map(); // sessionId -> 'idle' | 'running'
303
305
  const statusCapable = new Set(); // sessions for which the Host has emitted agent/status
306
+ const childParents = new Map(); // child sessionId -> parent sessionId
307
+ const runningChildren = new Map(); // parent sessionId -> Set<child sessionId>
308
+ const childLabels = new Map(); // child sessionId -> human label from `subagent/catalog`
309
+ const childSettledAt = new Map(); // parent sessionId -> last child idle timestamp
310
+ const childSettleTimers = new Map(); // parent sessionId -> timer, waiting for the parent to resume
311
+ const CHILD_SETTLE_MS = 300;
312
+ const SUBAGENT_LABEL_LIMIT = 500;
313
+ const CHILD_PARENT_LIMIT = 1000;
314
+ const subtasksWanted = () => ({ ...settings, ...preferences.get() }).subtaskNotify === true;
315
+ const rememberChildParent = (childId, parentId) => {
316
+ childParents.delete(childId);
317
+ childParents.set(childId, parentId);
318
+ while (childParents.size > CHILD_PARENT_LIMIT) childParents.delete(childParents.keys().next().value);
319
+ };
320
+ const clearChildSettle = (sessionId) => {
321
+ const timer = childSettleTimers.get(sessionId);
322
+ if (timer) clearTimeout(timer);
323
+ childSettleTimers.delete(sessionId);
324
+ };
304
325
  const clearDeferred = (sessionId) => { const entry = deferredCompletions.get(sessionId); if (entry?.timer) clearTimeout(entry.timer); };
305
- const flushCompletion = async (sessionId) => {
326
+ const cancelCompletion = (sessionId) => {
327
+ clearChildSettle(sessionId);
306
328
  const entry = deferredCompletions.get(sessionId);
307
329
  if (!entry) return;
330
+ clearDeferred(sessionId);
308
331
  deferredCompletions.delete(sessionId);
309
- if (entry.timer) clearTimeout(entry.timer);
310
- await dispatch(reducer.turnEnd(entry.payload));
332
+ diagnostics.deferredCancelled = (diagnostics.deferredCancelled ?? 0) + 1;
311
333
  };
312
- const cancelCompletion = (sessionId) => {
334
+ /** The last child stopped very recently: a parent that is about to consume that result must win. */
335
+ const childJustSettled = (sessionId) => {
336
+ const at = childSettledAt.get(sessionId);
337
+ return typeof at === 'number' && Date.now() - at < CHILD_SETTLE_MS;
338
+ };
339
+ /**
340
+ * An armed goal will continue on its own: its turn ends are round boundaries, not the end of the
341
+ * user's task. The candidate is kept rather than delivered, because a supervisor can also stop the
342
+ * goal just after a round ends; the disarm edge then decides whether that round was final. The next
343
+ * round (`turn/start`, `tool/call` or `running`) cancels the kept candidate.
344
+ *
345
+ * A running subagent still owns work for its parent. The parent's turn may end while it waits, so
346
+ * its card is held until the last child settles; a parent that wakes up in the meantime cancels the
347
+ * held card and supplies a fresh turn end later.
348
+ */
349
+ const flushCompletion = async (sessionId, { force = false } = {}) => {
313
350
  const entry = deferredCompletions.get(sessionId);
314
351
  if (!entry) return;
315
- clearDeferred(sessionId);
352
+ if (armedGoals.has(sessionId)) return;
353
+ if (runningChildren.get(sessionId)?.size) return;
354
+ if (!force && childJustSettled(sessionId)) { scheduleChildSettledFlush(sessionId); return; }
316
355
  deferredCompletions.delete(sessionId);
317
- diagnostics.deferredCancelled = (diagnostics.deferredCancelled ?? 0) + 1;
356
+ clearChildSettle(sessionId);
357
+ if (entry.timer) clearTimeout(entry.timer);
358
+ await dispatch(reducer.turnEnd({ ...entry.payload, label: childLabels.get(sessionId) }, { subagentNotify: subtasksWanted() }));
359
+ };
360
+ /**
361
+ * The last running child stopped. A parent that only waited for it may have already stopped, so
362
+ * give the wake-up one short settle window: a parent that starts a new turn inside it cancels the
363
+ * held card, and only a parent that really stays idle releases it.
364
+ */
365
+ const scheduleChildSettledFlush = (parentSessionId) => {
366
+ if (typeof parentSessionId !== 'string' || parentSessionId === '' || !deferredCompletions.has(parentSessionId)) return;
367
+ clearChildSettle(parentSessionId);
368
+ const timer = setTimeout(() => {
369
+ childSettleTimers.delete(parentSessionId);
370
+ if (!deferredCompletions.has(parentSessionId)) return;
371
+ if (armedGoals.has(parentSessionId)) return;
372
+ if (runningChildren.get(parentSessionId)?.size) return;
373
+ if (agentStatuses.get(parentSessionId) === 'running') { cancelCompletion(parentSessionId); return; }
374
+ void flushCompletion(parentSessionId, { force: true }).catch(() => { diagnostics.eventErrors += 1; });
375
+ }, CHILD_SETTLE_MS);
376
+ if (typeof timer.unref === 'function') timer.unref();
377
+ childSettleTimers.set(parentSessionId, timer);
318
378
  };
319
379
  const deferCompletion = (sessionId, payload) => {
380
+ if (armedGoals.has(sessionId) && statusCapable.has(sessionId)) {
381
+ // Keep the round candidate without delivering it. A later round cancels it; a disarm edge
382
+ // decides whether it was the final round (including a supervisor stopping the goal just after
383
+ // the turn ended).
384
+ const existing = deferredCompletions.get(sessionId);
385
+ if (existing?.timer) { clearTimeout(existing.timer); existing.timer = null; }
386
+ deferredCompletions.set(sessionId, { payload, timer: null });
387
+ return;
388
+ }
389
+ // A terminal goal edge is one notification, not a green "任务完成": a blocked goal says so and
390
+ // carries the reason. Only an exact same-turn match may attach it; an old stop never labels a
391
+ // later ordinary turn. Pause/clear are handled on the disarm edge, where they stay silent.
392
+ const stop = goalStops.get(sessionId);
393
+ if (stop) {
394
+ goalStops.delete(sessionId);
395
+ if (stop.state === 'paused' || stop.state === 'cleared') { cancelCompletion(sessionId); return; }
396
+ if (stop.state === 'blocked' && Number.isSafeInteger(stop.turn) && stop.turn === payload.turn) {
397
+ payload = { ...payload, goalStop: stop };
398
+ }
399
+ }
320
400
  const existing = deferredCompletions.get(sessionId);
321
401
  if (existing?.timer) clearTimeout(existing.timer);
322
402
  // Current DSH: wait for exactly the same idle state that clears the native sidebar spinner.
@@ -387,6 +467,30 @@ export async function apply(ctx, config = {}) {
387
467
  if (status !== 'idle' && status !== 'running') return;
388
468
  statusCapable.add(sessionId);
389
469
  agentStatuses.set(sessionId, status);
470
+ // Subagent liveness belongs to its parent. While a child runs, the parent's turn end is not the
471
+ // end of the user's task — the async subagent tool returns immediately and the parent may stop
472
+ // while it waits. The catalog event supplies the parent link and the human label for the card.
473
+ const header = agent?.session?.header;
474
+ const knownParent = typeof childParents.get(sessionId) === 'string' ? childParents.get(sessionId) : undefined;
475
+ const parentSessionId = header?.parentSession ?? knownParent;
476
+ const isChild = header?.origin === 'subagent' || (knownParent !== undefined && typeof parentSessionId === 'string');
477
+ if (isChild && typeof parentSessionId === 'string' && parentSessionId !== '') {
478
+ rememberChildParent(sessionId, parentSessionId);
479
+ const running = runningChildren.get(parentSessionId) ?? new Set();
480
+ if (status === 'running') {
481
+ running.add(sessionId);
482
+ runningChildren.set(parentSessionId, running);
483
+ childSettledAt.delete(parentSessionId);
484
+ clearChildSettle(parentSessionId);
485
+ } else {
486
+ running.delete(sessionId);
487
+ if (!running.size) {
488
+ runningChildren.delete(parentSessionId);
489
+ childSettledAt.set(parentSessionId, Date.now());
490
+ scheduleChildSettledFlush(parentSessionId);
491
+ }
492
+ }
493
+ }
390
494
  if (status === 'running') { cancelCompletion(sessionId); return; }
391
495
  // Re-check the status when the deferred flush actually runs. Every `session/event` is handled
392
496
  // through `safely` too, so a synchronous `idle -> running` flap — DSH resumes queued work in the
@@ -401,6 +505,21 @@ export async function apply(ctx, config = {}) {
401
505
  const data = event?.data ?? {};
402
506
  const sessionId = session?.id;
403
507
  if (Number.isSafeInteger(data.turn) && data.turn > 0) liveTurns.set(sessionId, data.turn);
508
+ // `goal/change` lands just before the activation edge it causes. Remember the terminal state so
509
+ // that edge can tell a completed goal from one the model or a supervisor had to stop.
510
+ if (event?.type === 'goal/change') {
511
+ const operation = data.operation;
512
+ const turn = liveTurns.get(sessionId);
513
+ // A block needs the exact turn it happened in; without one it can never be attached to a
514
+ // completion, and a wildcard would mislabel a later ordinary turn.
515
+ if (operation === 'block' && Number.isSafeInteger(turn) && turn > 0) goalStops.set(sessionId, { state: 'blocked', reason: data.goal?.blockedReason?.message, turn });
516
+ else if (operation === 'pause') goalStops.set(sessionId, { state: 'paused', turn });
517
+ else if (operation === 'clear') goalStops.set(sessionId, { state: 'cleared', turn });
518
+ else if (operation === 'complete') goalStops.set(sessionId, { state: 'complete', turn });
519
+ else goalStops.delete(sessionId);
520
+ }
521
+ // A new turn starts from a clean slate: any stop recorded before it belongs to the previous round.
522
+ if (event?.type === 'turn/start') goalStops.delete(sessionId);
404
523
  if (event?.type === 'tool/call' && data.callId && (data.name === 'ask_user_question' || data.name === 'exit_plan_mode')) {
405
524
  // A plan review gates its turn until the verdict returns to it; an ordinary question does not
406
525
  // (it may be the last operation of the task), so only the plan review opens a gate here.
@@ -456,18 +575,79 @@ export async function apply(ctx, config = {}) {
456
575
  // the past is not news, so a rebuild would only re-announce an approval the user can already see in
457
576
  // the DSH UI, and it would do it on every session open.
458
577
  ctx?.on?.('approval/request', (request, next) => { try { /* live reason is non-authoritative */ } catch { diagnostics.eventErrors += 1; } return next(); });
459
- // Older Hosts may not publish agent/status. Keep goal awareness only for that legacy fallback;
460
- // lifecycle-capable Hosts flush on native `idle`, not when a separate goal bookkeeping event arrives.
578
+ // A goal that keeps running on its own turns every round boundary into an intermediate idle. On a
579
+ // lifecycle-capable host the idle transition still owns delivery, but only the disarm edge can tell
580
+ // that this turn is the final one; while `armed`, every round end is silent. Older hosts without
581
+ // `agent/status` keep the original behaviour: hold while a goal is engaged, flush when it ends.
461
582
  ctx?.on?.('goal/activation-changed', (payload) => safely(async () => {
462
- const sessionId = sessionIdOf(payload?.sessionId) ?? payload?.sessionId;
463
- if (typeof sessionId !== 'string' || sessionId === '' || statusCapable.has(sessionId)) return;
464
- if (payload?.goal) {
583
+ const raw = payload?.sessionId;
584
+ const sessionId = typeof raw === 'string' ? raw : sessionIdOf(raw);
585
+ if (typeof sessionId !== 'string' || sessionId === '') return;
586
+ const goal = payload?.goal;
587
+ const armed = goal != null
588
+ // A pre-lifecycle host's payload may carry the goal without an activation field; the old
589
+ // contract treated any present goal as engaged.
590
+ && (goal.activation === 'armed' || goal.activation === undefined);
591
+ if (armed) {
592
+ const wasArmed = armedGoals.has(sessionId);
593
+ armedGoals.add(sessionId);
465
594
  engagedGoals.add(sessionId);
466
- const entry = deferredCompletions.get(sessionId);
467
- if (entry?.timer) { clearTimeout(entry.timer); entry.timer = null; }
595
+ if (!wasArmed) {
596
+ // A fresh arm starts a new run: whatever was queued belongs to a finished task.
597
+ cancelCompletion(sessionId);
598
+ } else {
599
+ // A revision-only re-arm keeps the held round candidate, but its grace timer must not fire.
600
+ const entry = deferredCompletions.get(sessionId);
601
+ if (entry?.timer) { clearTimeout(entry.timer); entry.timer = null; }
602
+ }
468
603
  return;
469
604
  }
605
+ const wasArmed = armedGoals.delete(sessionId);
470
606
  engagedGoals.delete(sessionId);
607
+ const stop = goalStops.get(sessionId);
608
+ if (statusCapable.has(sessionId)) {
609
+ if (wasArmed && (stop?.state === 'paused' || stop?.state === 'cleared')) {
610
+ // A deliberate pause or clear is not news: the run stopped by intent.
611
+ goalStops.delete(sessionId);
612
+ cancelCompletion(sessionId);
613
+ return;
614
+ }
615
+ if (stop?.state === 'blocked') {
616
+ // Two orders are possible. A supervisor can block just after the round's turn ended, in
617
+ // which case the held candidate takes the reason now; a block inside the turn has no
618
+ // candidate yet, so the stop stays for the turn end that follows this edge.
619
+ const entry = deferredCompletions.get(sessionId);
620
+ if (entry) {
621
+ if (Number.isSafeInteger(stop.turn) && stop.turn === entry.payload.turn) {
622
+ entry.payload = { ...entry.payload, goalStop: stop };
623
+ }
624
+ goalStops.delete(sessionId);
625
+ }
626
+ } else if (stop?.state === 'complete') {
627
+ goalStops.delete(sessionId);
628
+ }
629
+ const entry = deferredCompletions.get(sessionId);
630
+ // A goal that stopped after its final round already ended (an external block/complete between
631
+ // turns) owns that last round: deliver it once. A disarm inside a turn has no candidate yet;
632
+ // its own turn end arrives next and goes through the normal path.
633
+ if (wasArmed && entry && agentStatuses.get(sessionId) === 'idle' && !runningChildren.get(sessionId)?.size) {
634
+ void flushCompletion(sessionId).catch(() => { diagnostics.eventErrors += 1; });
635
+ }
636
+ return;
637
+ }
638
+ // Legacy host: no idle authority, so the disarmed edge is the delivery point.
639
+ if (stop?.state === 'paused' || stop?.state === 'cleared') {
640
+ goalStops.delete(sessionId);
641
+ cancelCompletion(sessionId);
642
+ return;
643
+ }
644
+ if (stop?.state === 'blocked') {
645
+ const entry = deferredCompletions.get(sessionId);
646
+ if (entry) {
647
+ entry.payload = { ...entry.payload, goalStop: stop };
648
+ goalStops.delete(sessionId);
649
+ }
650
+ }
471
651
  await flushCompletion(sessionId);
472
652
  }));
473
653
  ctx?.on?.('user-questions/request', (request, next) => {
@@ -508,21 +688,20 @@ export async function apply(ctx, config = {}) {
508
688
  * `fail:<session>:<turn>`, so the second arrival updates the same card instead of adding one — and
509
689
  * the error message is still carried onto that update through `pendingErrors`.
510
690
  *
511
- * A subtask failure stays as quiet as a subtask completion: `turn/end` already skips subagents.
691
+ * A subtask failure is now opt-in with the same `subtaskNotify` switch as a subtask completion: by
692
+ * default the main task is the only thing the page announces.
512
693
  */
513
694
  ctx?.on?.('agent/error', ({ agent, turn, error }) => {
514
695
  const sessionId = sessionIdOf(agent);
515
696
  if (typeof sessionId !== 'string' || sessionId === '') return;
516
697
  pendingErrors.set(`${sessionId}:${turn}`, error);
517
- if (originOf(agent?.session) === 'subagent') return;
518
- safely(() => dispatch(reducer.agentError({ sessionId, turn, error: error ?? '', message: error?.message })));
698
+ while (pendingErrors.size > 500) pendingErrors.delete(pendingErrors.keys().next().value);
699
+ const subagent = originOf(agent?.session) === 'subagent';
700
+ if (subagent && !subtasksWanted()) return;
701
+ safely(() => dispatch(reducer.agentError({ sessionId, turn, error: error ?? '', message: error?.message }, { subagent, label: childLabels.get(sessionId) })));
519
702
  });
520
- // v1 user preference: subagent completion is intentionally silent. Keep the
521
- // historical kind schema for stored legacy records, but do not create records
522
- // or dispatch A/B/C/D for new subagent/end events.
523
703
  // Subtask/background completions are the biggest noise source (one record per subagent run and
524
704
  // per background job, often titled with the raw command). They are opt-in via `subtaskNotify`.
525
- const subtasksWanted = () => ({ ...settings, ...preferences.get() }).subtaskNotify === true;
526
705
  /**
527
706
  * Which session a workflow run belongs to.
528
707
  *
@@ -537,7 +716,29 @@ export async function apply(ctx, config = {}) {
537
716
  const workflowOwners = new Map();
538
717
  const WORKFLOW_OWNER_LIMIT = 50;
539
718
  ctx?.on?.('session/event', (session, event) => {
540
- const sessionId = session?.id; const runId = event?.data?.runId;
719
+ const sessionId = session?.id;
720
+ // The parent's log carries the child id together with the human label the `subagent` call was
721
+ // given. It is the only place that maps a child session to a readable card body.
722
+ if (event?.type === 'subagent/catalog') {
723
+ const data = event?.data ?? {};
724
+ const childId = data.childId;
725
+ if (typeof sessionId !== 'string' || typeof childId !== 'string' || childId === '') return;
726
+ rememberChildParent(childId, sessionId);
727
+ // A fast child can report `running` before its catalog record arrives; register that liveness
728
+ // here too, otherwise the parent would ignore a child that is already running.
729
+ if (agentStatuses.get(childId) === 'running') {
730
+ const running = runningChildren.get(sessionId) ?? new Set();
731
+ running.add(childId);
732
+ runningChildren.set(sessionId, running);
733
+ }
734
+ const label = [data.label, data.name].find((value) => typeof value === 'string' && value.trim() !== '');
735
+ if (label) {
736
+ childLabels.set(childId, label.trim());
737
+ while (childLabels.size > SUBAGENT_LABEL_LIMIT) childLabels.delete(childLabels.keys().next().value);
738
+ }
739
+ return;
740
+ }
741
+ const runId = event?.data?.runId;
541
742
  if (event?.type !== 'tool-workflow/run-start' || typeof sessionId !== 'string' || typeof runId !== 'string') return;
542
743
  workflowOwners.delete(runId);
543
744
  workflowOwners.set(runId, sessionId);
@@ -669,6 +870,11 @@ export async function apply(ctx, config = {}) {
669
870
  // Cordis plugins may resolve asynchronously, but an async effect must resolve
670
871
  // to a disposer (or null), never an arbitrary runtime object. Keep the
671
872
  // diagnostics surface on the callable disposer for controlled tests/tools.
672
- const dispose = () => {};
873
+ const dispose = () => {
874
+ for (const timer of childSettleTimers.values()) clearTimeout(timer);
875
+ childSettleTimers.clear();
876
+ for (const entry of deferredCompletions.values()) if (entry?.timer) clearTimeout(entry.timer);
877
+ deferredCompletions.clear();
878
+ };
673
879
  return Object.assign(dispose, { buffer, preferences, reducer, diagnostics, updates, guiAvailable, reason: guiAvailable ? undefined : 'authenticated web routes unavailable' });
674
880
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@idoall/dsh-notify",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "description": "DSH web plugin: in-page task notifications for DeepSeek Harness — enhanced or soft status toasts, a collapsible stack in the conversation top-left corner, answer buttons, background-tab attention, and a WebAudio cue that also plays while the page is hidden. Live delivery only: no history, no service worker, no web push, no OS notification matrix.",
6
6
  "main": "./dist/index.js",