@morgan9668/dsh-task-notify 0.0.0-stage → 1.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 chenzhao
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.md CHANGED
@@ -1,3 +1,127 @@
1
- # Temporary Holding Version
1
+ # 任务完成通知 · @morgan9668/dsh-task-notify
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 每个回合结束后,把 **任务概要 + 耗时 + token 消耗** 推送到你配置的群机器人。
4
+
5
+ ## 安装
6
+
7
+ 在 DSH 里:**设置 → 插件 → 添加插件**,粘贴包名 `@morgan9668/dsh-task-notify`。
8
+
9
+ 装完重启 DSH,然后打开 **设置 → 任务完成通知** 配置渠道。
10
+
11
+
12
+ ## 通知长这样
13
+
14
+ ```
15
+ 重构通知插件 · workbuddy/glm-5.3
16
+
17
+ **✅ 任务完成** 已完成
18
+
19
+ **📋 任务概要**
20
+ > 已完成后端接入。
21
+ > 并补齐了三个渠道的签名。
22
+ 工具调用:3 次(bash×2、read×1)
23
+
24
+ **⏱️ 耗时**
25
+ > 3分12秒
26
+
27
+ **🔢 token 消耗**
28
+ > 输入 12,340 输出 2,891
29
+ > 合计 **15,231**(含缓存命中 800)
30
+ ```
31
+
32
+ ## 渠道与接入
33
+
34
+ 四个渠道互相独立,可同时开启。**留空即未启用**,不会发送任何请求。
35
+
36
+ ### 企业微信(个人可用)
37
+
38
+ 1. 打开手机/桌面企业微信,进入任意**内部群**
39
+ 2. 群右上角 → **群机器人** → **添加机器人** → **新创建一个机器人**
40
+ 3. 起个名字,创建后**复制 Webhook 地址**
41
+ 4. 填到 `channels.wecom.webhook`,并把 `enabled` 设为 `true`
42
+
43
+ ### 飞书(个人可用)
44
+
45
+ 1. 打开飞书,进入群 → **设置** → **群机器人** → **添加机器人** → **自定义机器人**
46
+ 2. 复制 **Webhook 地址**
47
+ 3. 如果开启了「签名校验」,把密钥填到 `channels.feishu.secret`;没开就留空
48
+ 4. 填到 `channels.feishu.webhook`,`enabled: true`
49
+
50
+ ### 钉钉(个人可用,必须加签)
51
+
52
+ 1. 钉钉群 → **群设置** → **智能群助手** → **添加机器人** → **自定义**
53
+ 2. 安全设置里勾选 **加签**,复制密钥
54
+ 3. 复制 Webhook 地址
55
+ 4. 两个都填:`channels.dingtalk.webhook` 与 `channels.dingtalk.secret`,`enabled: true`
56
+
57
+ > 钉钉的加签是**强制**的,不填 secret 会被服务端拒绝。插件在请求时自动补
58
+ > `timestamp` 与 `sign` 参数。
59
+
60
+ ### 微信(预留,当前非默认路径)
61
+
62
+ 微信不开放第三方直接推送到个人号。合规做法是经服务号中转,常见两种:
63
+
64
+ - **Server酱**:`sct.ftqq.com` 微信扫码登录,领取 SendKey
65
+ - **WxPusher**:`wxpusher.zjiecode.com` 注册拿 appToken
66
+
67
+ 把凭据填进 `channels.wechat.serverchanSendKey` 或 `wxpusherAppToken`,
68
+ `enabled: true` 即可用。**没有凭据时会明确回报「未配置」,不会静默失败。**
69
+
70
+ > 关于自建服务号:微信公众平台的官方规则里,**服务号的注册主体只能是
71
+ > 政府 / 媒体 / 企业 / 其他组织,个人主体不提供该选项**;个人类型也
72
+ > 「暂不支持微信认证、微信支付及高级接口能力」。所以个人身份无法自建
73
+ > 服务号,这也是本插件默认走服务商通道的原因。
74
+
75
+ ## 配置
76
+
77
+ 全部配置项:
78
+
79
+ | 字段 | 默认 | 说明 |
80
+ |---|---|---|
81
+ | `enabled` | `true` | 总开关 |
82
+ | `reasons` | `[completed, error, blocked]` | 在哪些回合结局下通知 |
83
+ | `notifySubagents` | `false` | 是否给子代理会话也发(默认关,避免刷屏) |
84
+ | `maxExcerptChars` | `400` | 概要正文字数上限 |
85
+ | `timeoutMs` | `8000` | 单次请求超时 |
86
+ | `channels.*.enabled` | `false` | 各渠道开关 |
87
+ | `channels.*.webhook` | `''` | 群机器人 Webhook |
88
+
89
+ 可选结局:`completed`、`error`、`blocked`、`max-tokens`、`aborted`。
90
+
91
+ ## 数据来源与诚实边界
92
+
93
+ | 内容 | 来源 | 拿不到时 |
94
+ |---|---|---|
95
+ | token | DSH 提交的 `assistant/message` 事件里的 `data.usage`,按回合累加 | 显示「本轮未提供用量数据」,**不填 0** |
96
+ | 耗时 | `turn/start` 到 `turn/end` 的真实时间差 | 显示「未知」 |
97
+ | 概要 | 最后一条 assistant 消息的 `text` 块(不含思考过程) | 显示「本轮没有文字回复」 |
98
+ | 工具调用 | 本回合 `tool/call` 事件的名称统计 | 该行整行省略 |
99
+
100
+ 多步推理会一次性产生多条 `assistant/message`,插件**累加**它们的 usage,
101
+ 而不是只取最后一条。
102
+
103
+ ## 失败处理
104
+
105
+ 所有发送都是 fire-and-forget:
106
+
107
+ - 网络异常、超时、HTTP 非 2xx → 记日志,**绝不抛出,绝不阻塞 agent 主循环**
108
+ - 三个平台都会用 **HTTP 200 + 业务错误码** 回话(webhook 失效也返回 200),
109
+ 所以插件会读 `errcode` / `code`,非 0 一律判为失败并带上服务端原文
110
+ - 200 但正文不是 JSON(被代理或 WAF 拦截)→ 记为「已送出不可确认」,
111
+ 既不冒充成功,也不谎报失败
112
+
113
+ ## 测试
114
+
115
+ ```bash
116
+ node __tests__/unit.mjs
117
+ ```
118
+
119
+ 39 项纯逻辑测试,不联外网。覆盖签名算法独立复算、token 累加、耗时格式化、
120
+ 各渠道业务错误码判定、网络异常不抛出、配置回落等。
121
+
122
+ ## 已知限制
123
+
124
+ - 微信通道未接自建服务号(平台资质限制,见上)
125
+ - 消息正文按各渠道上限裁剪,企业微信/飞书 3800 字、钉钉 4800 字
126
+ - 只统计 `assistant/message` 上的 usage;若上游适配器不提供该字段,
127
+ 通知里会如实显示未提供
@@ -0,0 +1,274 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 浏览器半身(client.js)结构测试。
4
+ *
5
+ * 这一层最容易出的错是「模块导出为空」:文件看起来是合法 JS,但 factory
6
+ * 裸 return 一个对象而不是挂到 module.exports 上,加载器就取不到插件对象,
7
+ * 设置卡一条也注册不上,控制台还不一定报错。
8
+ *
9
+ * 这里真的把 client.js 当浏览器脚本执行一遍,再调用 factory,
10
+ * 断言拿到的插件对象确实带 inject 与 apply,并且注册到正确的 slot。
11
+ *
12
+ * node __tests__/client.mjs
13
+ */
14
+
15
+ import assert from 'node:assert/strict';
16
+ import { readFile } from 'node:fs/promises';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { dirname, join } from 'node:path';
19
+
20
+ const here = dirname(fileURLToPath(import.meta.url));
21
+ const clientPath = join(here, '..', 'client.js');
22
+
23
+ let failures = 0;
24
+ const queue = [];
25
+ const test = (name, fn) => queue.push({ name, fn });
26
+
27
+ async function run() {
28
+ for (const { name, fn } of queue) {
29
+ try {
30
+ await fn();
31
+ console.log(`✓ ${name}`);
32
+ } catch (error) {
33
+ failures += 1;
34
+ console.log(`✗ ${name}`);
35
+ console.log(` ${error instanceof Error ? error.message : String(error)}`);
36
+ }
37
+ }
38
+ console.log(failures === 0 ? '\n全部通过' : `\n${failures} 项失败`);
39
+ process.exit(failures === 0 ? 0 : 1);
40
+ }
41
+
42
+ /** 在模拟的浏览器环境里加载 client.js,返回 { definition, plugin, warnings }。 */
43
+ async function loadClient() {
44
+ const source = await readFile(clientPath, 'utf8');
45
+
46
+ let definition = null;
47
+ const head = { appendChild: () => {}, removeChild: () => {} };
48
+ const fakeDocument = {
49
+ head,
50
+ createElement: () => ({ setAttribute: () => {}, textContent: '', remove: () => {} }),
51
+ };
52
+
53
+ const fakeWindow = {
54
+ __ModuleLoader__: {
55
+ load: (def) => {
56
+ definition = def;
57
+ },
58
+ },
59
+ };
60
+
61
+ const warnings = [];
62
+ const sandboxConsole = {
63
+ log: () => {},
64
+ warn: (...args) => warnings.push(args.map(String).join(' ')),
65
+ error: (...args) => warnings.push(args.map(String).join(' ')),
66
+ };
67
+
68
+ // eslint-disable-next-line no-new-func
69
+ const execute = new Function('window', 'document', 'console', 'fetch', 'setTimeout', source);
70
+ execute(fakeWindow, fakeDocument, sandboxConsole, async () => {
71
+ throw new Error('测试环境不发真实请求');
72
+ }, () => 0);
73
+
74
+ assert.ok(definition, 'client.js 必须调用 window.__ModuleLoader__.load');
75
+
76
+ const fakeRequire = (name) => {
77
+ if (name === 'react') {
78
+ const createElement = () => null;
79
+ return {
80
+ createElement,
81
+ useState: (initial) => [typeof initial === 'function' ? initial() : initial, () => {}],
82
+ useEffect: () => {},
83
+ useCallback: (fn) => fn,
84
+ useMemo: (factory) => factory(),
85
+ useRef: (value) => ({ current: value }),
86
+ };
87
+ }
88
+ throw new Error(`client.js 不该 require 未声明的模块:${name}`);
89
+ };
90
+
91
+ const plugin = definition.factory(fakeRequire);
92
+ return { definition, plugin, warnings };
93
+ }
94
+
95
+ /* ------------------------------------------------------------------ */
96
+
97
+ test('client.js 注册的模块 id 等于 package.json 的 name', async () => {
98
+ // 不写死名字:包名带 scope 后改一次名就够,测试跟着自动对齐。
99
+ const manifest = JSON.parse(
100
+ await readFile(join(here, '..', 'package.json'), 'utf8'),
101
+ );
102
+ const { definition } = await loadClient();
103
+ assert.equal(
104
+ definition.id,
105
+ manifest.name,
106
+ `client.js 的模块 id 必须等于包名(期望 ${manifest.name})`,
107
+ );
108
+ });
109
+
110
+ test('factory 返回的插件对象带 inject 与 apply(不是空对象)', async () => {
111
+ const { plugin } = await loadClient();
112
+ assert.equal(typeof plugin, 'object');
113
+ assert.ok(plugin !== null, '插件对象不能是 null');
114
+ assert.equal(typeof plugin.apply, 'function', '插件对象必须有 apply');
115
+ assert.ok(Array.isArray(plugin.inject), '插件对象必须有 inject 数组');
116
+ });
117
+
118
+ test('inject 只声明 slots 与 locale(与 our-free-model 一致)', async () => {
119
+ const { plugin } = await loadClient();
120
+ assert.deepEqual(plugin.inject.slice().sort(), ['locale', 'slots']);
121
+ });
122
+
123
+ test('只依赖 react,不偷偷引入别的包', async () => {
124
+ // fakeRequire 对未知模块直接抛错,能跑通就说明没乱引。
125
+ const { plugin } = await loadClient();
126
+ assert.equal(typeof plugin.apply, 'function');
127
+ });
128
+
129
+ test('注册到 settings.section,用 id 而不是 key', async () => {
130
+ const { plugin } = await loadClient();
131
+
132
+ const registered = [];
133
+ const slots = {
134
+ inject: (name, register) => {
135
+ registered.push({ slotName: name });
136
+ return register();
137
+ },
138
+ register: (options, component) => {
139
+ const last = registered[registered.length - 1];
140
+ last.options = options;
141
+ last.component = component;
142
+ return () => {};
143
+ },
144
+ };
145
+ const locale = {
146
+ register: () => {},
147
+ bind: () => (key) => key,
148
+ };
149
+ const ctx = {
150
+ slots,
151
+ locale,
152
+ effect: (fn) => fn(),
153
+ get: () => undefined,
154
+ };
155
+
156
+ plugin.apply(ctx);
157
+
158
+ const section = registered.find((entry) => entry.slotName === 'settings.section');
159
+ assert.ok(section, `必须注册 settings.section,实际:${registered.map((e) => e.slotName).join(',')}`);
160
+ assert.equal(section.options.id, 'task-notify', 'id 决定命名空间,必须是 task-notify');
161
+ assert.equal(typeof section.options.order, 'number', 'order 决定排序');
162
+ assert.equal(typeof section.options.label, 'function', 'label 是函数');
163
+ assert.equal(typeof section.component, 'function', '必须带组件');
164
+ });
165
+
166
+ test('注册的组件能渲染成一个元素(不抛错)', async () => {
167
+ const { plugin } = await loadClient();
168
+
169
+ let captured = null;
170
+ const slots = {
171
+ inject: (name, register) => register(),
172
+ register: (options, component) => {
173
+ captured = component;
174
+ return () => {};
175
+ },
176
+ };
177
+ const locale = { register: () => {}, bind: () => (key) => key };
178
+ plugin.apply({ slots, locale, effect: (fn) => fn(), get: () => undefined });
179
+
180
+ assert.equal(typeof captured, 'function');
181
+ // 组件内部用了 hooks,直接调用会失败;这里只验证它是函数且接收 props。
182
+ assert.ok(captured.length === 0 || captured.length === 1, '组件签名应为 (props)');
183
+ });
184
+
185
+ test('注册后可以撤销(返回 disposer)', async () => {
186
+ const { plugin } = await loadClient();
187
+
188
+ let disposed = false;
189
+ const slots = {
190
+ inject: (name, register) => register(),
191
+ register: () => () => {
192
+ disposed = true;
193
+ },
194
+ };
195
+ const locale = { register: () => {}, bind: () => (key) => key };
196
+ const ctx = {
197
+ slots,
198
+ locale,
199
+ effect: (fn) => {
200
+ const cleanup = fn();
201
+ return cleanup;
202
+ },
203
+ get: () => undefined,
204
+ };
205
+
206
+ plugin.apply(ctx);
207
+ // effect 内返回的 disposer 应当能被调用而不抛错。
208
+ assert.equal(typeof ctx.effect(() => () => {}), 'function');
209
+ });
210
+
211
+ test('客户端只与 /api/task-notify 通信,不写死别的前缀', async () => {
212
+ const source = await readFile(clientPath, 'utf8');
213
+ assert.ok(source.includes("const API = '/api/task-notify'"), 'API 前缀必须是 /api/task-notify');
214
+
215
+ // 真正的约束是「没有对外发请求」:只允许 fetch 这个同源前缀。
216
+ // placeholder 文案里的 Webhook 示例不算外链,所以只检查 fetch 调用。
217
+ const fetchCalls = [...source.matchAll(/fetch\(\s*([^,)]+)/g)].map((m) => m[1].trim());
218
+ for (const call of fetchCalls) {
219
+ assert.ok(
220
+ call === 'API + path' || call.startsWith('API'),
221
+ `fetch 只应打同源 API,实际:${call}`,
222
+ );
223
+ }
224
+ });
225
+
226
+ /* ------------------------- 布局:按钮不换行 ------------------------- */
227
+
228
+ test('发送测试按钮与「子代理」开关同一行,靠右,文案不换行', async () => {
229
+ const source = await readFile(clientPath, 'utf8');
230
+
231
+ // 样式层:按钮不折行、不被 flex 压缩;所在行两端对齐。
232
+ assert.ok(
233
+ /\.tn-btn\s*\{[^}]*white-space:\s*nowrap/.test(source),
234
+ 'tn-btn 必须 white-space: nowrap,否则「发送测试」会被拆成两行',
235
+ );
236
+ assert.ok(
237
+ /\.tn-btn\s*\{[^}]*flex:\s*none/.test(source),
238
+ 'tn-btn 必须 flex: none,否则会被 flex 容器压窄',
239
+ );
240
+ assert.ok(
241
+ /\.tn-row-split\s*\{[^}]*justify-content:\s*space-between/.test(source),
242
+ 'tn-row-split 必须两端对齐(左开关、右按钮)',
243
+ );
244
+ assert.ok(
245
+ /\.tn-row-split\s*>\s*\.tn-row\s*\{[^}]*margin-bottom:\s*0/.test(source),
246
+ '行内的 Toggle 必须去掉 margin-bottom,否则整行会偏',
247
+ );
248
+
249
+ // 结构层:按钮与「子代理」开关是 tn-row-split 的两个子节点。
250
+ assert.ok(source.includes("className: 'tn-row-split'"), '要有 tn-row-split 容器');
251
+ assert.ok(!source.includes('tn-actionbar'), '不再需要独立的 tn-actionbar 行');
252
+
253
+ // 按钮必须出现在 notifySubagents 之后、渠道块之前。
254
+ const splitIndex = source.indexOf("className: 'tn-row-split'");
255
+ const subagentIndex = source.indexOf("['notifySubagents']");
256
+ const feishuIndex = source.indexOf("'飞书',");
257
+ assert.ok(splitIndex > 0 && subagentIndex > splitIndex, '子代理开关应在 tn-row-split 内');
258
+ assert.ok(feishuIndex > splitIndex, '按钮行应在渠道列表之前');
259
+ });
260
+
261
+ test('渠道顺序:飞书、钉钉在前,企业微信、微信在后', async () => {
262
+ const source = await readFile(clientPath, 'utf8');
263
+ const order = ['飞书', '钉钉', '企业微信', '微信'].map((name) => {
264
+ const index = source.indexOf(`'${name}',`);
265
+ assert.ok(index > 0, `找不到渠道 ${name}`);
266
+ return index;
267
+ });
268
+ for (let i = 1; i < order.length; i += 1) {
269
+ assert.ok(order[i] > order[i - 1], '渠道顺序应为 飞书 → 钉钉 → 企业微信 → 微信');
270
+ }
271
+ });
272
+
273
+
274
+ await run();
@@ -0,0 +1,192 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 端到端验证:用真实的 apply() 跑一遍事件流,确认通知真的发得出去、内容对不对。
4
+ *
5
+ * 起一个本地 HTTP 服务当「群机器人」,把请求体记下来再回报 errcode:0,
6
+ * 然后用假 ctx 派发 turn/start → assistant/message → turn/end,
7
+ * 断言收到的内容里有概要、耗时、token 三块。
8
+ *
9
+ * node __tests__/e2e.mjs
10
+ */
11
+
12
+ import assert from 'node:assert/strict';
13
+ import { createServer } from 'node:http';
14
+
15
+ import { apply } from '../index.js';
16
+
17
+ const received = [];
18
+
19
+ const server = createServer((request, response) => {
20
+ const chunks = [];
21
+ request.on('data', (chunk) => chunks.push(chunk));
22
+ request.on('end', () => {
23
+ received.push({
24
+ url: request.url,
25
+ body: Buffer.concat(chunks).toString('utf8'),
26
+ });
27
+ response.writeHead(200, { 'content-type': 'application/json' });
28
+ response.end(JSON.stringify({ errcode: 0, errmsg: 'ok' }));
29
+ });
30
+ });
31
+
32
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
33
+ const port = server.address().port;
34
+ const webhook = `http://127.0.0.1:${port}/robot/send?access_token=test`;
35
+
36
+ console.log(`假群机器人已启动:${webhook}`);
37
+
38
+ // 假 ctx:只实现插件用到的那几样。
39
+ const handlers = [];
40
+ const logs = [];
41
+ const ctx = {
42
+ on: (event, handler) => {
43
+ if (event === 'session/event') handlers.push(handler);
44
+ return () => {};
45
+ },
46
+ logger: { info: (message) => logs.push(message), warn: (message) => logs.push(message) },
47
+ };
48
+
49
+ const plugin = apply(ctx, {
50
+ enabled: true,
51
+ reasons: ['completed'],
52
+ timeoutMs: 5000,
53
+ channels: {
54
+ wecom: { enabled: true, webhook },
55
+ },
56
+ });
57
+
58
+ assert.equal(handlers.length, 1, '应订阅一个 session/event');
59
+
60
+ // 造一个会话事件流。
61
+ const events = [
62
+ { type: 'turn/start', data: { turn: 7 } },
63
+ { type: 'session/title', data: { title: '端到端验证' } },
64
+ { type: 'tool/call', data: { turn: 7, name: 'bash' } },
65
+ { type: 'tool/call', data: { turn: 7, name: 'read' } },
66
+ {
67
+ type: 'assistant/message',
68
+ data: {
69
+ turn: 7,
70
+ usage: { inputTokens: 12340, outputTokens: 2891, totalTokens: 15231, cachedReadTokens: 800 },
71
+ message: {
72
+ content: [
73
+ { type: 'reasoning', text: '思考过程不该外泄' },
74
+ { type: 'text', text: '三个渠道的签名都已补齐。' },
75
+ ],
76
+ },
77
+ },
78
+ },
79
+ ];
80
+
81
+ const session = {
82
+ id: 'sess-e2e',
83
+ header: { cwd: '/tmp', delegationDepth: 0 },
84
+ requestHeader: () => ({ config: { provider: 'workbuddy', model: 'glm-5.3' } }),
85
+ snapshotEvents: () => events,
86
+ };
87
+
88
+ // 依次派发:先是 turn/start,再是其余事件。
89
+ handlers[0](session, events[0]);
90
+ await new Promise((resolve) => setTimeout(resolve, 60));
91
+
92
+ handlers[0](session, events[1]);
93
+ handlers[0](session, events[2]);
94
+ handlers[0](session, events[3]);
95
+ handlers[0](session, events[4]);
96
+
97
+ // 让耗时至少 1 秒,验证格式化走的是真实差值。
98
+ await new Promise((resolve) => setTimeout(resolve, 1100));
99
+ handlers[0](session, { type: 'turn/end', data: { turn: 7, reason: { kind: 'completed' } } });
100
+
101
+ // 等火并发的发送落地。
102
+ await new Promise((resolve) => setTimeout(resolve, 600));
103
+ server.close();
104
+
105
+ console.log(`\n收到 ${received.length} 条通知请求`);
106
+
107
+ let failures = 0;
108
+ const check = (name, fn) => {
109
+ try {
110
+ fn();
111
+ console.log(`✓ ${name}`);
112
+ } catch (error) {
113
+ failures += 1;
114
+ console.log(`✗ ${name}`);
115
+ console.log(` ${error instanceof Error ? error.message : String(error)}`);
116
+ }
117
+ };
118
+
119
+ check('确实发出了 1 条通知', () => {
120
+ assert.equal(received.length, 1);
121
+ });
122
+
123
+ if (received.length > 0) {
124
+ const payload = JSON.parse(received[0].body);
125
+ const content = payload.markdown.content;
126
+
127
+ console.log('\n─── 实际通知正文 ───');
128
+ console.log(content);
129
+ console.log('───────────────────\n');
130
+
131
+ check('是企业微信 markdown 形状', () => {
132
+ assert.equal(payload.msgtype, 'markdown');
133
+ });
134
+
135
+ check('标题带对话名与模型', () => {
136
+ assert.ok(content.includes('端到端验证'), content);
137
+ assert.ok(content.includes('workbuddy/glm-5.3'), content);
138
+ });
139
+
140
+ check('含任务概要块', () => assert.ok(content.includes('任务概要')));
141
+ check('概要取到真实回复', () => assert.ok(content.includes('三个渠道的签名都已补齐')));
142
+ check('思考过程未外泄', () => assert.ok(!content.includes('思考过程不该外泄')));
143
+
144
+ check('工具调用次数正确', () => {
145
+ assert.ok(content.includes('工具调用:2 次'), content);
146
+ });
147
+
148
+ check('耗时是真实差值(>=1 秒)', () => {
149
+ assert.ok(/耗时[\s\S]*?[0-9]+分?[0-9]*秒/.test(content), content);
150
+ assert.ok(!content.includes('未知'), content);
151
+ });
152
+
153
+ check('token 三行齐全', () => {
154
+ assert.ok(content.includes('12,340'), content);
155
+ assert.ok(content.includes('2,891'), content);
156
+ assert.ok(content.includes('15,231'), content);
157
+ });
158
+
159
+ check('缓存命中被标注', () => assert.ok(content.includes('800'), content));
160
+ }
161
+
162
+ // 再验证一次失败路径:webhook 指向一个不存在的端口,插件不能抛。
163
+ console.log('\n─── 验证失败路径不会抛出 ───');
164
+ const ctx2 = {
165
+ on: (event, handler) => {
166
+ if (event === 'session/event') ctx2.handler = handler;
167
+ return () => {};
168
+ },
169
+ logger: { info: () => {}, warn: () => {} },
170
+ };
171
+ apply(ctx2, {
172
+ enabled: true,
173
+ reasons: ['error'],
174
+ timeoutMs: 800,
175
+ channels: { wecom: { enabled: true, webhook: 'http://127.0.0.1:1/dead' } },
176
+ });
177
+
178
+ let threw = false;
179
+ try {
180
+ ctx2.handler(
181
+ { id: 's', header: { delegationDepth: 0 }, snapshotEvents: () => [] },
182
+ { type: 'turn/end', data: { turn: 1, reason: { kind: 'error' } } },
183
+ );
184
+ await new Promise((resolve) => setTimeout(resolve, 500));
185
+ } catch {
186
+ threw = true;
187
+ }
188
+
189
+ check('发送失败时 turn/end 处理不抛出异常', () => assert.equal(threw, false));
190
+
191
+ console.log(failures === 0 ? '\n端到端验证全部通过' : `\n${failures} 项失败`);
192
+ process.exit(failures === 0 ? 0 : 1);