@morgan9668/dsh-llm-gateway 1.2.0 → 1.3.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/README.md +183 -26
- package/client.js +1202 -0
- package/cordis.patch.yml +44 -0
- package/docs/DETAIL.md +132 -12
- package/index.js +540 -8
- package/locale/en.json +4 -1
- package/locale/zh.json +4 -1
- package/package.json +22 -6
- package/src/notify/channels.js +239 -0
- package/src/notify/config.js +171 -0
- package/src/notify/hub.js +137 -0
- package/src/notify/index.js +315 -0
- package/src/notify/render.js +342 -0
- package/src/notify/store.js +125 -0
- package/src/notify/stream-tap.js +114 -0
- package/tests/auth.mjs +11 -4
- package/tests/client.mjs +225 -0
- package/tests/notify-api.mjs +412 -0
- package/tests/notify.mjs +514 -0
package/tests/notify.mjs
ADDED
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 通知模块的单元测试(纯函数 + 调度器,不起 HTTP)。
|
|
4
|
+
*
|
|
5
|
+
* 覆盖三件最容易悄悄坏掉的事:
|
|
6
|
+
* 1. 配置收敛 —— 写错的字段不该让网关起不来,也不该被静默丢掉;
|
|
7
|
+
* 2. 网关请求的聚合窗口 —— 一个任务几十个请求必须压成一条,而不是刷屏;
|
|
8
|
+
* 3. 渲染 —— 上游没给 usage 就写「未提供」,绝不伪造 0。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import assert from 'node:assert/strict';
|
|
12
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
13
|
+
import { tmpdir } from 'node:os';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
DEFAULT_FLASH_COLOR,
|
|
18
|
+
flashPeriodMs,
|
|
19
|
+
normalizeColor,
|
|
20
|
+
normalizeInApp,
|
|
21
|
+
normalizeNotify,
|
|
22
|
+
} from '../src/notify/config.js';
|
|
23
|
+
import { createNotifier, readyChannels } from '../src/notify/index.js';
|
|
24
|
+
import {
|
|
25
|
+
formatDuration,
|
|
26
|
+
formatNumber,
|
|
27
|
+
reasonKindOf,
|
|
28
|
+
renderGatewayNotification,
|
|
29
|
+
renderSessionNotification,
|
|
30
|
+
statusBadge,
|
|
31
|
+
sumUsage,
|
|
32
|
+
} from '../src/notify/render.js';
|
|
33
|
+
import { createConfigStore } from '../src/notify/store.js';
|
|
34
|
+
import { createStreamCollector, summarizeCollected, tapStream } from '../src/notify/stream-tap.js';
|
|
35
|
+
|
|
36
|
+
let failures = 0;
|
|
37
|
+
let passed = 0;
|
|
38
|
+
const tests = [];
|
|
39
|
+
const test = (name, fn) => tests.push({ name, fn });
|
|
40
|
+
|
|
41
|
+
/** 假的渠道:记录被发出去的消息,不碰网络。 */
|
|
42
|
+
function fakeHub() {
|
|
43
|
+
const events = [];
|
|
44
|
+
return {
|
|
45
|
+
events,
|
|
46
|
+
size: 1,
|
|
47
|
+
emit(event, data) {
|
|
48
|
+
events.push({ event, data });
|
|
49
|
+
return 1;
|
|
50
|
+
},
|
|
51
|
+
attach() {},
|
|
52
|
+
dispose() {},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
57
|
+
|
|
58
|
+
/* ------------------------------ 配置 ------------------------------ */
|
|
59
|
+
|
|
60
|
+
test('normalizeColor 只放行安全的颜色形状', () => {
|
|
61
|
+
assert.equal(normalizeColor('#22c55e'), '#22c55e');
|
|
62
|
+
assert.equal(normalizeColor('#ABC'), '#abc');
|
|
63
|
+
assert.equal(normalizeColor('rgb(10, 20, 30)'), 'rgb(10, 20, 30)');
|
|
64
|
+
assert.equal(normalizeColor('green'), DEFAULT_FLASH_COLOR, '裸单词不在白名单里');
|
|
65
|
+
// 想拼出第二段 CSS 声明的输入必须被挡下。
|
|
66
|
+
assert.equal(normalizeColor('red;background:url(evil)'), DEFAULT_FLASH_COLOR);
|
|
67
|
+
assert.equal(normalizeColor(''), DEFAULT_FLASH_COLOR);
|
|
68
|
+
assert.equal(normalizeColor(undefined), DEFAULT_FLASH_COLOR);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test('闪动时长按次数均分,越界夹到边界而不是整块退回默认', () => {
|
|
72
|
+
assert.equal(flashPeriodMs(6, 18), Math.round(6000 / 18));
|
|
73
|
+
assert.equal(normalizeInApp({ flashes: 0 }).flashes, 1);
|
|
74
|
+
assert.equal(normalizeInApp({ flashes: 999 }).flashes, 60);
|
|
75
|
+
assert.equal(normalizeInApp({ durationSeconds: 999 }).durationSeconds, 80);
|
|
76
|
+
// 数量写成字符串也要能收敛,YAML 里手写常常忘了引号。
|
|
77
|
+
assert.equal(normalizeInApp({ flashes: '24' }).flashes, 24);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('normalizeNotify 缺字段取默认值,两个触发源默认都开', () => {
|
|
81
|
+
const config = normalizeNotify({});
|
|
82
|
+
assert.equal(config.enabled, true);
|
|
83
|
+
assert.deepEqual(config.sources, { gateway: true, session: true });
|
|
84
|
+
assert.equal(config.gateway.settleSeconds, 12);
|
|
85
|
+
assert.deepEqual(config.reasons, ['completed', 'error', 'blocked']);
|
|
86
|
+
assert.equal(config.timeoutMs, 8000);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test('normalizeNotify 认得出显式关掉的触发源', () => {
|
|
90
|
+
const config = normalizeNotify({ sources: { gateway: false } });
|
|
91
|
+
assert.equal(config.sources.gateway, false);
|
|
92
|
+
assert.equal(config.sources.session, true, '只关一个不该把另一个一起关掉');
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test('归一化后没有可用渠道时为 0 个就绪渠道', () => {
|
|
96
|
+
assert.deepEqual(readyChannels(normalizeNotify({})), []);
|
|
97
|
+
const ready = readyChannels(normalizeNotify({
|
|
98
|
+
channels: { feishu: { enabled: true, webhook: 'https://example.com/hook' } },
|
|
99
|
+
}));
|
|
100
|
+
assert.deepEqual(ready, ['feishu']);
|
|
101
|
+
// 勾了但没填地址 = 没就绪:发出去只会得到 400。
|
|
102
|
+
assert.deepEqual(readyChannels(normalizeNotify({
|
|
103
|
+
channels: { feishu: { enabled: true, webhook: '' } },
|
|
104
|
+
})), []);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
/* ------------------------------ 渲染 ------------------------------ */
|
|
108
|
+
|
|
109
|
+
test('耗时与数字排版', () => {
|
|
110
|
+
assert.equal(formatDuration(840), '840毫秒');
|
|
111
|
+
assert.equal(formatDuration(192_000), '3分12秒');
|
|
112
|
+
assert.equal(formatDuration(3_720_000), '1小时02分');
|
|
113
|
+
assert.equal(formatDuration(Number.NaN), '未知', '算不出来就说未知,不编一个 0');
|
|
114
|
+
assert.equal(formatNumber(15231), '15,231');
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('结局徽标:出错不能显示成完成', () => {
|
|
118
|
+
assert.match(statusBadge('completed'), /✅/);
|
|
119
|
+
assert.match(statusBadge('error'), /❌/);
|
|
120
|
+
assert.match(statusBadge('blocked'), /⏸/);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test('finish.reason 翻译成通知用的结局种类', () => {
|
|
124
|
+
assert.equal(reasonKindOf({ kind: 'stop' }), 'completed');
|
|
125
|
+
assert.equal(reasonKindOf({ kind: 'tool-calls' }), 'tool-calls');
|
|
126
|
+
assert.equal(reasonKindOf({ kind: 'error', failure: { code: 'X' } }), 'error');
|
|
127
|
+
assert.equal(reasonKindOf({ kind: 'aborted' }), 'aborted');
|
|
128
|
+
assert.equal(reasonKindOf({ kind: 'max-tokens' }), 'max-tokens');
|
|
129
|
+
assert.equal(reasonKindOf(undefined), 'completed');
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test('sumUsage 只累加本回合,缺字段记为缺失', () => {
|
|
133
|
+
const events = [
|
|
134
|
+
{ type: 'assistant/message', data: { turn: 1, usage: { inputTokens: 10, outputTokens: 5 } } },
|
|
135
|
+
{ type: 'assistant/message', data: { turn: 1, usage: { inputTokens: 20, outputTokens: 5 } } },
|
|
136
|
+
{ type: 'assistant/message', data: { turn: 2, usage: { inputTokens: 999, outputTokens: 999 } } },
|
|
137
|
+
];
|
|
138
|
+
const usage = sumUsage(events, 1);
|
|
139
|
+
assert.equal(usage.inputTokens, 30);
|
|
140
|
+
assert.equal(usage.outputTokens, 10);
|
|
141
|
+
assert.equal(usage.totalTokens, 40);
|
|
142
|
+
assert.equal(usage.available, true);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
test('sumUsage 读真实的 cacheReadTokens 字段,而不是 cachedReadTokens', () => {
|
|
146
|
+
// 回归:搬过来的实现读 `cachedReadTokens`,而会话日志里真实的字段名是
|
|
147
|
+
// `cacheReadTokens`。读错名字不报错,只让缓存数恒为 0——于是「合计」比
|
|
148
|
+
// 「输入 + 输出」大一大截,看起来像算错了。
|
|
149
|
+
const events = [{
|
|
150
|
+
type: 'assistant/message',
|
|
151
|
+
data: {
|
|
152
|
+
turn: 1,
|
|
153
|
+
// 这是从真实会话日志里抄下来的一条(time 字段无关)。
|
|
154
|
+
usage: { inputTokens: 1409, outputTokens: 138, totalTokens: 14091, cacheReadTokens: 12544 },
|
|
155
|
+
},
|
|
156
|
+
}];
|
|
157
|
+
const usage = sumUsage(events, 1);
|
|
158
|
+
assert.equal(usage.cachedReadTokens, 12544, '缓存命中必须读得到');
|
|
159
|
+
assert.equal(usage.totalTokens, 14091);
|
|
160
|
+
// 三者相加应当等于合计,否则通知里的数字自相矛盾。
|
|
161
|
+
assert.equal(usage.inputTokens + usage.outputTokens + usage.cachedReadTokens, usage.totalTokens);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test('会话通知正文会写出缓存命中,让合计对得上', () => {
|
|
165
|
+
const rendered = renderSessionNotification({
|
|
166
|
+
reasonKind: 'completed',
|
|
167
|
+
durationMs: 1000,
|
|
168
|
+
events: [{
|
|
169
|
+
type: 'assistant/message',
|
|
170
|
+
data: {
|
|
171
|
+
turn: 1,
|
|
172
|
+
usage: { inputTokens: 1409, outputTokens: 138, totalTokens: 14091, cacheReadTokens: 12544 },
|
|
173
|
+
message: { content: [{ type: 'text', text: '完成' }] },
|
|
174
|
+
},
|
|
175
|
+
}],
|
|
176
|
+
turn: 1,
|
|
177
|
+
});
|
|
178
|
+
assert.match(rendered.body, /含缓存命中 12,544/);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
test('sumUsage 一条都没有时标 available:false', () => {
|
|
182
|
+
const usage = sumUsage([{ type: 'turn/end', data: { turn: 1 } }], 1);
|
|
183
|
+
assert.equal(usage.available, false);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
test('会话通知:没有回复、没有用量时如实说「未提供」', () => {
|
|
187
|
+
const rendered = renderSessionNotification({
|
|
188
|
+
reasonKind: 'completed',
|
|
189
|
+
durationMs: 1200,
|
|
190
|
+
events: [{ type: 'session/title', data: { title: '重构网关' } }],
|
|
191
|
+
turn: 1,
|
|
192
|
+
});
|
|
193
|
+
assert.match(rendered.title, /重构网关/);
|
|
194
|
+
assert.match(rendered.body, /本轮没有文字回复/);
|
|
195
|
+
assert.match(rendered.body, /本轮未提供用量数据/);
|
|
196
|
+
// 不能出现一个假的 0
|
|
197
|
+
assert.ok(!/合计 \*\*0\*\*/.test(rendered.body));
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test('会话通知:正文超过上限会截断并带省略号', () => {
|
|
201
|
+
const long = '一'.repeat(500);
|
|
202
|
+
const rendered = renderSessionNotification({
|
|
203
|
+
reasonKind: 'completed',
|
|
204
|
+
durationMs: 1000,
|
|
205
|
+
events: [{ type: 'assistant/message', data: { turn: 1, message: { content: [{ type: 'text', text: long }] } } }],
|
|
206
|
+
turn: 1,
|
|
207
|
+
maxExcerptChars: 50,
|
|
208
|
+
});
|
|
209
|
+
assert.ok(rendered.body.includes('…'));
|
|
210
|
+
assert.ok(!rendered.body.includes(long), '超出的部分不该出现');
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
test('网关通知带出客户端与模型,失败时带失败原因', () => {
|
|
214
|
+
const rendered = renderGatewayNotification({
|
|
215
|
+
reasonKind: 'error',
|
|
216
|
+
durationMs: 5000,
|
|
217
|
+
modelLabel: 'buddy/deepseek-v4.1-flash',
|
|
218
|
+
clientLabel: 'codex_cli_rs',
|
|
219
|
+
protocol: 'Responses',
|
|
220
|
+
requestCount: 3,
|
|
221
|
+
reply: 'error: quota',
|
|
222
|
+
usage: { available: true, inputTokens: 100, outputTokens: 20, totalTokens: 120, cachedReadTokens: 0, missing: [] },
|
|
223
|
+
maxExcerptChars: 400,
|
|
224
|
+
failureMessage: 'Free usage limit reached.',
|
|
225
|
+
});
|
|
226
|
+
assert.match(rendered.title, /codex_cli_rs/);
|
|
227
|
+
assert.match(rendered.title, /buddy\/deepseek-v4\.1-flash/);
|
|
228
|
+
assert.match(rendered.body, /Free usage limit reached/);
|
|
229
|
+
assert.match(rendered.body, /3 次请求/);
|
|
230
|
+
assert.match(rendered.body, /120/);
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
/* --------------------------- 流式旁路采集 --------------------------- */
|
|
234
|
+
|
|
235
|
+
test('tapStream 原样转发每一个 chunk', async () => {
|
|
236
|
+
async function* upstream() {
|
|
237
|
+
yield { type: 'text-delta', text: 'a' };
|
|
238
|
+
yield { type: 'reasoning-delta', text: 'r' };
|
|
239
|
+
yield { type: 'finish', reason: { kind: 'stop' } };
|
|
240
|
+
}
|
|
241
|
+
const collector = createStreamCollector();
|
|
242
|
+
const seen = [];
|
|
243
|
+
for await (const chunk of tapStream(upstream(), collector)) seen.push(chunk);
|
|
244
|
+
assert.equal(seen.length, 3, '一个 chunk 都不能少');
|
|
245
|
+
assert.deepEqual(seen[0], { type: 'text-delta', text: 'a' });
|
|
246
|
+
assert.equal(collector.text, 'a');
|
|
247
|
+
assert.equal(collector.reasoning, 'r');
|
|
248
|
+
assert.deepEqual(collector.finish, { kind: 'stop' });
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
test('工具调用按 id 去重计数,不按增量片计数', () => {
|
|
252
|
+
const collector = createStreamCollector();
|
|
253
|
+
collector.push({ type: 'tool-call-delta', id: 'call-1', name: 'bash' });
|
|
254
|
+
collector.push({ type: 'tool-call-delta', id: 'call-1', argumentsDelta: '{}' });
|
|
255
|
+
collector.push({ type: 'tool-call-delta', id: 'call-2', name: 'read' });
|
|
256
|
+
assert.equal(collector.toolCalls, 2, '两个调用、四五个增量片,应该算 2');
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
test('summarizeCollected 把 DSH usage 换成通知形状', () => {
|
|
260
|
+
const collector = createStreamCollector();
|
|
261
|
+
collector.push({ type: 'usage', usage: { inputTokens: 100, outputTokens: 20, totalTokens: 120, cacheReadTokens: 30 } });
|
|
262
|
+
const summary = summarizeCollected(collector, (usage) => ({
|
|
263
|
+
prompt_tokens: usage.inputTokens,
|
|
264
|
+
completion_tokens: usage.outputTokens,
|
|
265
|
+
total_tokens: usage.totalTokens,
|
|
266
|
+
prompt_tokens_details: { cached_tokens: usage.cacheReadTokens },
|
|
267
|
+
}));
|
|
268
|
+
assert.equal(summary.usage.totalTokens, 120);
|
|
269
|
+
assert.equal(summary.usage.cachedReadTokens, 30);
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
/* ---------------------------- 配置存储 ---------------------------- */
|
|
273
|
+
|
|
274
|
+
test('配置存储:文件不存在时回落到 patch 层', () => {
|
|
275
|
+
const dir = mkdtempSync(join(tmpdir(), 'gw-notify-'));
|
|
276
|
+
try {
|
|
277
|
+
const store = createConfigStore({
|
|
278
|
+
filePath: join(dir, 'notify.json'),
|
|
279
|
+
readPatchConfig: () => ({ enabled: false, sources: { gateway: true } }),
|
|
280
|
+
log: () => {},
|
|
281
|
+
});
|
|
282
|
+
assert.equal(store.read().enabled, false);
|
|
283
|
+
} finally {
|
|
284
|
+
rmSync(dir, { recursive: true, force: true });
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
test('配置存储:setPath 逐层建对象,写出的是一份完整快照', () => {
|
|
289
|
+
const dir = mkdtempSync(join(tmpdir(), 'gw-notify-'));
|
|
290
|
+
try {
|
|
291
|
+
const filePath = join(dir, 'notify.json');
|
|
292
|
+
const store = createConfigStore({
|
|
293
|
+
filePath,
|
|
294
|
+
readPatchConfig: () => ({ enabled: false, reasons: ['error'] }),
|
|
295
|
+
log: () => {},
|
|
296
|
+
});
|
|
297
|
+
const { saved } = store.setPath(['channels', 'feishu', 'webhook'], 'https://example.com/hook');
|
|
298
|
+
assert.equal(saved, true);
|
|
299
|
+
const written = JSON.parse(readFileSync(filePath, 'utf8'));
|
|
300
|
+
assert.equal(written.channels.feishu.webhook, 'https://example.com/hook');
|
|
301
|
+
// 写出去的是归一化后的完整配置:patch 层的值也被带进来,不留半截文件。
|
|
302
|
+
assert.equal(written.enabled, false);
|
|
303
|
+
assert.deepEqual(written.reasons, ['error']);
|
|
304
|
+
assert.equal(written.gateway.settleSeconds, 12, '默认值补全,下次读不用再猜');
|
|
305
|
+
} finally {
|
|
306
|
+
rmSync(dir, { recursive: true, force: true });
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
test('配置存储:文件存在时优先于 patch 层', () => {
|
|
311
|
+
const dir = mkdtempSync(join(tmpdir(), 'gw-notify-'));
|
|
312
|
+
try {
|
|
313
|
+
const filePath = join(dir, 'notify.json');
|
|
314
|
+
const store = createConfigStore({
|
|
315
|
+
filePath,
|
|
316
|
+
readPatchConfig: () => ({ enabled: false }),
|
|
317
|
+
log: () => {},
|
|
318
|
+
});
|
|
319
|
+
store.setPath(['enabled'], true);
|
|
320
|
+
// 再读:文件说了算,patch 里的 enabled:false 不再生效。
|
|
321
|
+
assert.equal(store.read().enabled, true);
|
|
322
|
+
} finally {
|
|
323
|
+
rmSync(dir, { recursive: true, force: true });
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
test('配置存储:拒绝写入空列表(回落成默认值会被当成「没保存」)', () => {
|
|
328
|
+
const dir = mkdtempSync(join(tmpdir(), 'gw-notify-'));
|
|
329
|
+
try {
|
|
330
|
+
const store = createConfigStore({
|
|
331
|
+
filePath: join(dir, 'notify.json'),
|
|
332
|
+
readPatchConfig: () => ({}),
|
|
333
|
+
log: () => {},
|
|
334
|
+
});
|
|
335
|
+
assert.throws(() => store.setPath(['reasons'], []), /不能把列表清空/);
|
|
336
|
+
// 非空列表照常写入。
|
|
337
|
+
const { saved } = store.setPath(['reasons'], ['completed']);
|
|
338
|
+
assert.equal(saved, true);
|
|
339
|
+
assert.deepEqual(store.read().reasons, ['completed']);
|
|
340
|
+
} finally {
|
|
341
|
+
rmSync(dir, { recursive: true, force: true });
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
test('配置存储:文件写坏时回落到 patch,而不是让插件炸掉', () => {
|
|
346
|
+
const dir = mkdtempSync(join(tmpdir(), 'gw-notify-'));
|
|
347
|
+
try {
|
|
348
|
+
const filePath = join(dir, 'notify.json');
|
|
349
|
+
writeFileSync(filePath, '{ 这不是 JSON', 'utf8');
|
|
350
|
+
const store = createConfigStore({
|
|
351
|
+
filePath,
|
|
352
|
+
readPatchConfig: () => ({ enabled: true, reasons: ['error'] }),
|
|
353
|
+
log: () => {},
|
|
354
|
+
});
|
|
355
|
+
assert.deepEqual(store.read().reasons, ['error']);
|
|
356
|
+
} finally {
|
|
357
|
+
rmSync(dir, { recursive: true, force: true });
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
/* ----------------------------- 调度器 ----------------------------- */
|
|
362
|
+
|
|
363
|
+
test('网关请求:窗口内多个请求只发一条通知', async () => {
|
|
364
|
+
const hub = fakeHub();
|
|
365
|
+
const notifier = createNotifier({
|
|
366
|
+
readConfig: () => ({ gateway: { settleSeconds: 0.05 } }),
|
|
367
|
+
log: () => {},
|
|
368
|
+
hub,
|
|
369
|
+
});
|
|
370
|
+
const sent = [];
|
|
371
|
+
// 换掉渠道层不方便,这里直接观察 hub 的闪动事件 + 发送次数。
|
|
372
|
+
notifier.recordGatewayRequest({ usage: { available: true, inputTokens: 10, outputTokens: 1, totalTokens: 11, cachedReadTokens: 0, missing: [] } });
|
|
373
|
+
notifier.recordGatewayRequest({ usage: { available: true, inputTokens: 10, outputTokens: 1, totalTokens: 11, cachedReadTokens: 0, missing: [] } });
|
|
374
|
+
notifier.recordGatewayRequest({ usage: { available: true, inputTokens: 10, outputTokens: 1, totalTokens: 11, cachedReadTokens: 0, missing: [] } });
|
|
375
|
+
await wait(120);
|
|
376
|
+
// 没有可用渠道 → 不发,但聚合槽必须已经清空(flush 后不应再发)。
|
|
377
|
+
assert.equal(sent.length, 0);
|
|
378
|
+
await notifier.flush();
|
|
379
|
+
notifier.dispose();
|
|
380
|
+
assert.equal(hub.events.length, 0, 'inApp 默认关,不该闪');
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
test('网关请求:settleSeconds=0 时每个请求都立刻收口', async () => {
|
|
384
|
+
const hub = fakeHub();
|
|
385
|
+
let dispatched = 0;
|
|
386
|
+
const notifier = createNotifier({
|
|
387
|
+
readConfig: () => ({
|
|
388
|
+
gateway: { settleSeconds: 0 },
|
|
389
|
+
inApp: { enabled: true, flashes: 2, durationSeconds: 1, color: '#22c55e' },
|
|
390
|
+
}),
|
|
391
|
+
log: () => {},
|
|
392
|
+
hub,
|
|
393
|
+
});
|
|
394
|
+
// 闪动只在真的 dispatch 后发出,用它数 dispatch 次数。
|
|
395
|
+
notifier.recordGatewayRequest({});
|
|
396
|
+
await wait(10);
|
|
397
|
+
notifier.recordGatewayRequest({});
|
|
398
|
+
await wait(10);
|
|
399
|
+
dispatched = hub.events.length;
|
|
400
|
+
notifier.dispose();
|
|
401
|
+
assert.equal(dispatched, 2, '窗口关闭时两个请求各发一次');
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
test('网关请求的耗时取自请求进网关的时刻,不是收尾时刻', async () => {
|
|
405
|
+
// 回归:曾经 startedAt 在 recordGatewayRequest 里取 Date.now(),
|
|
406
|
+
// 而这个函数在请求收尾时才调用,于是单请求任务的耗时恒为 0——通知里
|
|
407
|
+
// 写过「⏱️ 耗时 > 0毫秒」。
|
|
408
|
+
const hub = fakeHub();
|
|
409
|
+
const notifier = createNotifier({
|
|
410
|
+
readConfig: () => ({
|
|
411
|
+
gateway: { settleSeconds: 0 },
|
|
412
|
+
inApp: { enabled: true, flashes: 1, durationSeconds: 1, color: '#22c55e' },
|
|
413
|
+
}),
|
|
414
|
+
log: () => {},
|
|
415
|
+
hub,
|
|
416
|
+
});
|
|
417
|
+
const startedAt = Date.now() - 2500;
|
|
418
|
+
notifier.recordGatewayRequest({ startedAt });
|
|
419
|
+
await wait(30);
|
|
420
|
+
notifier.dispose();
|
|
421
|
+
assert.equal(hub.events.length, 1, '应该发了一次闪动');
|
|
422
|
+
// 闪动事件本身不带耗时,这里直接验证渲染层拿到的是真实差值:
|
|
423
|
+
// 用同一份 startedAt 渲染一条通知,耗时必须是非零的人类可读文本。
|
|
424
|
+
const rendered = renderGatewayNotification({
|
|
425
|
+
reasonKind: 'completed',
|
|
426
|
+
durationMs: Date.now() - startedAt,
|
|
427
|
+
usage: { available: true, inputTokens: 1, outputTokens: 1, totalTokens: 2, cachedReadTokens: 0, missing: [] },
|
|
428
|
+
});
|
|
429
|
+
// formatDuration 会把毫秒四舍五入到整秒,2500ms → 「3秒」。断言它落在
|
|
430
|
+
// 合理区间,而不是钉死某一种取整方式。
|
|
431
|
+
assert.ok(/[23]秒/.test(rendered.body), `耗时应当约 2–3 秒,实际正文:${rendered.body}`);
|
|
432
|
+
assert.ok(!/> 0毫秒/.test(rendered.body), '不能显示 0 毫秒');
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
test('总开关关掉时连闪动都不发', async () => {
|
|
436
|
+
const hub = fakeHub();
|
|
437
|
+
const notifier = createNotifier({
|
|
438
|
+
readConfig: () => ({ enabled: false, inApp: { enabled: true } }),
|
|
439
|
+
log: () => {},
|
|
440
|
+
hub,
|
|
441
|
+
});
|
|
442
|
+
notifier.recordGatewayRequest({});
|
|
443
|
+
await wait(20);
|
|
444
|
+
assert.equal(hub.events.length, 0);
|
|
445
|
+
notifier.dispose();
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
test('触发源关掉网关时,网关请求不产生通知也不闪', async () => {
|
|
449
|
+
const hub = fakeHub();
|
|
450
|
+
const notifier = createNotifier({
|
|
451
|
+
readConfig: () => ({ sources: { gateway: false }, inApp: { enabled: true } }),
|
|
452
|
+
log: () => {},
|
|
453
|
+
hub,
|
|
454
|
+
});
|
|
455
|
+
notifier.recordGatewayRequest({});
|
|
456
|
+
await wait(20);
|
|
457
|
+
assert.equal(hub.events.length, 0);
|
|
458
|
+
notifier.dispose();
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
test('会话触发源关掉时不发会话通知', async () => {
|
|
462
|
+
const hub = fakeHub();
|
|
463
|
+
const notifier = createNotifier({
|
|
464
|
+
readConfig: () => ({ sources: { session: false }, inApp: { enabled: true } }),
|
|
465
|
+
log: () => {},
|
|
466
|
+
hub,
|
|
467
|
+
});
|
|
468
|
+
await notifier.notifySession({ session: {}, events: [], reasonKind: 'completed', durationMs: 1, turn: 1 });
|
|
469
|
+
assert.equal(hub.events.length, 0);
|
|
470
|
+
notifier.dispose();
|
|
471
|
+
});
|
|
472
|
+
|
|
473
|
+
test('会话回合命中白名单时闪一下', async () => {
|
|
474
|
+
const hub = fakeHub();
|
|
475
|
+
const notifier = createNotifier({
|
|
476
|
+
readConfig: () => ({ inApp: { enabled: true, flashes: 3, durationSeconds: 1, color: '#22c55e' } }),
|
|
477
|
+
log: () => {},
|
|
478
|
+
hub,
|
|
479
|
+
});
|
|
480
|
+
await notifier.notifySession({ session: {}, events: [], reasonKind: 'completed', durationMs: 1, turn: 1 });
|
|
481
|
+
assert.equal(hub.events.length, 1);
|
|
482
|
+
assert.equal(hub.events[0].event, 'flash');
|
|
483
|
+
assert.equal(hub.events[0].data.flashes, 3);
|
|
484
|
+
notifier.dispose();
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
test('不在白名单里的结局不通知', async () => {
|
|
488
|
+
const hub = fakeHub();
|
|
489
|
+
const notifier = createNotifier({
|
|
490
|
+
readConfig: () => ({ reasons: ['error'], inApp: { enabled: true } }),
|
|
491
|
+
log: () => {},
|
|
492
|
+
hub,
|
|
493
|
+
});
|
|
494
|
+
await notifier.notifySession({ session: {}, events: [], reasonKind: 'completed', durationMs: 1, turn: 1 });
|
|
495
|
+
assert.equal(hub.events.length, 0);
|
|
496
|
+
notifier.dispose();
|
|
497
|
+
});
|
|
498
|
+
|
|
499
|
+
/* ------------------------------ 跑测试 ------------------------------ */
|
|
500
|
+
|
|
501
|
+
for (const { name, fn } of tests) {
|
|
502
|
+
try {
|
|
503
|
+
await fn();
|
|
504
|
+
passed += 1;
|
|
505
|
+
console.log(`✓ ${name}`);
|
|
506
|
+
} catch (error) {
|
|
507
|
+
failures += 1;
|
|
508
|
+
console.error(`✗ ${name}`);
|
|
509
|
+
console.error(` ${error?.message ?? error}`);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
console.log(`\n${failures === 0 ? '全部通过' : '有失败'}(通过 ${passed}/${tests.length})`);
|
|
514
|
+
process.exit(failures === 0 ? 0 : 1);
|