@morgan9668/dsh-llm-gateway 1.2.1 → 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.
@@ -0,0 +1,412 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 设置页 API 与「网关请求结束触发通知」的端到端测试。
4
+ *
5
+ * 这些用例真正起插件:一个假的 ctx 提供 llm / webServer / 一个假的上游流,
6
+ * 然后像浏览器那样调 /api/llm-gateway/*,像 Codex 那样打 /v1/chat/completions。
7
+ *
8
+ * 断言的四件事,都是这类改动最容易翻车的地方:
9
+ * 1. 改设置不会重启网关(端口不变、监听不断);
10
+ * 2. 勾选框的 POST 真的被当成 POST,不会拿回「当前配置」;
11
+ * 3. 网关请求结束后确实产生了通知,而且工具调用步被压进同一条;
12
+ * 4. 通知发送失败不会把请求带崩。
13
+ */
14
+
15
+ import assert from 'node:assert/strict';
16
+ import http from 'node:http';
17
+ import net from 'node:net';
18
+ import { mkdtempSync, rmSync } from 'node:fs';
19
+ import { tmpdir } from 'node:os';
20
+ import { join } from 'node:path';
21
+
22
+ import { apply } from '../index.js';
23
+
24
+ let failures = 0;
25
+ let passed = 0;
26
+ const tests = [];
27
+ const test = (name, fn) => tests.push({ name, fn });
28
+
29
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
30
+
31
+ function freePort() {
32
+ return new Promise((resolve, reject) => {
33
+ const srv = net.createServer();
34
+ srv.once('error', reject);
35
+ srv.listen(0, '127.0.0.1', () => {
36
+ const { port } = srv.address();
37
+ srv.close(() => resolve(port));
38
+ });
39
+ });
40
+ }
41
+
42
+ /**
43
+ * 最小可用的 ctx。
44
+ *
45
+ * `webServer` 手写一个 register:只记下路由表,调用时按精确路径分发——
46
+ * 这正是设置页请求走的路径,也顺带验证了我们注册的 kind 是 exact。
47
+ */
48
+ function fakeCtx({ llmStream }) {
49
+ const routes = new Map();
50
+ const cleanups = [];
51
+ return {
52
+ llm: {
53
+ listProviders: () => ['fake'],
54
+ listModels: async () => [{ id: 'fake-model', name: 'Fake' }],
55
+ resolveModelInfo: async () => ({ name: 'Fake', context: { contextWindow: 8192 } }),
56
+ stream: llmStream,
57
+ },
58
+ get: (key) => {
59
+ if (key === 'webServer') return undefined; // 走 ctx.inject 那条路
60
+ return undefined;
61
+ },
62
+ inject: (deps, callback) => {
63
+ // 插件用 ctx.inject(['webServer'], scoped => …) 等浏览器半身发布服务。
64
+ if (!deps.includes('webServer')) return;
65
+ const scoped = {
66
+ webServer: {
67
+ register(route) {
68
+ routes.set(`${route.kind}:${route.path}`, route);
69
+ return () => routes.delete(`${route.kind}:${route.path}`);
70
+ },
71
+ },
72
+ effect: (fn) => {
73
+ cleanups.push(fn());
74
+ },
75
+ };
76
+ callback(scoped);
77
+ },
78
+ effect: (fn) => {
79
+ cleanups.push(fn());
80
+ },
81
+ on: () => () => {},
82
+ dispose: () => {
83
+ for (const cleanup of cleanups.reverse()) {
84
+ try {
85
+ cleanup();
86
+ } catch {
87
+ /* 已经关掉了 */
88
+ }
89
+ }
90
+ },
91
+ routes,
92
+ };
93
+ }
94
+
95
+ /** 一个正常的流:回答 + 用量 + finish。 */
96
+ function okStreamScript(text = 'done', usage = { inputTokens: 100, outputTokens: 20, totalTokens: 120 }) {
97
+ return async function* stream() {
98
+ yield { type: 'text-delta', text };
99
+ yield { type: 'usage', usage };
100
+ yield { type: 'finish', reason: { kind: 'stop' } };
101
+ };
102
+ }
103
+
104
+ /** 一个「工具调用步」:没有正文,finish 是 tool-calls。 */
105
+ function toolStepScript() {
106
+ return async function* stream() {
107
+ yield { type: 'tool-call-delta', id: 'call-1', name: 'bash' };
108
+ yield { type: 'usage', usage: { inputTokens: 50, outputTokens: 10 } };
109
+ yield { type: 'finish', reason: { kind: 'tool-calls' } };
110
+ };
111
+ }
112
+
113
+ async function withGateway(config, run) {
114
+ const port = await freePort();
115
+ const ctx = fakeCtx(config);
116
+ apply(ctx, {
117
+ host: '127.0.0.1',
118
+ port,
119
+ apiKey: '',
120
+ allowedHosts: [`127.0.0.1:${port}`],
121
+ ...config.config,
122
+ });
123
+ await wait(80);
124
+ try {
125
+ await run({ port, ctx });
126
+ } finally {
127
+ ctx.dispose();
128
+ await wait(40);
129
+ }
130
+ }
131
+
132
+ function request(port, { path = '/healthz', method = 'GET', headers = {}, body = undefined } = {}) {
133
+ return new Promise((resolve, reject) => {
134
+ const req = http.request({ host: '127.0.0.1', port, path, method, headers }, (res) => {
135
+ const chunks = [];
136
+ res.on('data', (c) => chunks.push(c));
137
+ res.on('end', () => resolve({
138
+ status: res.statusCode,
139
+ headers: res.headers,
140
+ text: Buffer.concat(chunks).toString('utf8'),
141
+ }));
142
+ });
143
+ req.on('error', reject);
144
+ if (body !== undefined) req.write(body);
145
+ req.end();
146
+ });
147
+ }
148
+
149
+ /** 像浏览器那样调设置 API。路由是手写 webServer 注册的,这里直接调它。 */
150
+ function callRoute(ctx, path, { method = 'GET', body = undefined } = {}) {
151
+ const route = ctx.routes.get(`exact:${path}`);
152
+ assert.ok(route !== undefined, `路由 ${path} 没注册`);
153
+ return new Promise((resolve, reject) => {
154
+ const req = {
155
+ method,
156
+ headers: { 'content-type': 'application/json' },
157
+ async *[Symbol.asyncIterator]() {
158
+ if (body !== undefined) yield Buffer.from(JSON.stringify(body));
159
+ },
160
+ on: () => {},
161
+ };
162
+ let status = 0;
163
+ const headers = {};
164
+ const chunks = [];
165
+ const res = {
166
+ writeHead(code, hdrs) {
167
+ status = code;
168
+ Object.assign(headers, hdrs ?? {});
169
+ },
170
+ end(payload) {
171
+ if (payload !== undefined) chunks.push(Buffer.from(payload));
172
+ resolve({ status, headers, text: Buffer.concat(chunks).toString('utf8') });
173
+ },
174
+ };
175
+ try {
176
+ Promise.resolve(route.handler(req, res)).catch(reject);
177
+ } catch (error) {
178
+ reject(error);
179
+ }
180
+ });
181
+ }
182
+
183
+ /* ----------------------------- 设置 API ----------------------------- */
184
+
185
+ test('GET /api/llm-gateway/settings 返回配置与网关状态', async () => {
186
+ const dir = mkdtempSync(join(tmpdir(), 'gw-api-'));
187
+ process.env.HOME = dir;
188
+ try {
189
+ await withGateway({ llmStream: okStreamScript() }, async ({ ctx }) => {
190
+ const res = await callRoute(ctx, '/api/llm-gateway/settings');
191
+ assert.equal(res.status, 200);
192
+ const data = JSON.parse(res.text);
193
+ assert.equal(data.ok, true);
194
+ assert.equal(data.settings.enabled, true);
195
+ assert.equal(data.settings.sources.gateway, true);
196
+ assert.equal(typeof data.status.port, 'number');
197
+ assert.equal(data.status.listening, true, '网关应当已经在监听');
198
+ assert.equal(data.status.auth, false);
199
+ });
200
+ } finally {
201
+ rmSync(dir, { recursive: true, force: true });
202
+ }
203
+ });
204
+
205
+ test('POST settings 写入后 GET 读得到,且网关没有重启', async () => {
206
+ const dir = mkdtempSync(join(tmpdir(), 'gw-api-'));
207
+ process.env.HOME = dir;
208
+ try {
209
+ await withGateway({ llmStream: okStreamScript() }, async ({ port, ctx }) => {
210
+ const before = JSON.parse((await request(port, { path: '/healthz' })).text);
211
+ const post = await callRoute(ctx, '/api/llm-gateway/settings', {
212
+ method: 'POST',
213
+ body: { path: ['channels', 'feishu', 'webhook'], value: 'https://example.com/hook' },
214
+ });
215
+ assert.equal(post.status, 200);
216
+ const saved = JSON.parse(post.text);
217
+ assert.equal(saved.saved, true);
218
+ assert.equal(saved.settings.channels.feishu.webhook, 'https://example.com/hook');
219
+
220
+ // 关键:同一个端口还在服务,说明没有走 reconcile 重启。
221
+ const after = await request(port, { path: '/healthz' });
222
+ assert.equal(after.status, 200);
223
+ assert.equal(JSON.parse(after.text).ok, before.ok);
224
+ });
225
+ } finally {
226
+ rmSync(dir, { recursive: true, force: true });
227
+ }
228
+ });
229
+
230
+ test('POST settings 拿回的是「已保存」而不是「当前配置」', async () => {
231
+ const dir = mkdtempSync(join(tmpdir(), 'gw-api-'));
232
+ process.env.HOME = dir;
233
+ try {
234
+ await withGateway({ llmStream: okStreamScript() }, async ({ ctx }) => {
235
+ // 上一版把 GET 和 POST 拆成两条同路径路由,先注册的 GET 把 POST 吞了,
236
+ // 客户端勾选框立刻弹回、配置永远写不进去,而状态码还是 200。
237
+ const post = await callRoute(ctx, '/api/llm-gateway/settings', {
238
+ method: 'POST',
239
+ body: { path: ['notifySubagents'], value: true },
240
+ });
241
+ const data = JSON.parse(post.text);
242
+ assert.equal(data.settings.notifySubagents, true, 'POST 必须返回写入后的值');
243
+ });
244
+ } finally {
245
+ rmSync(dir, { recursive: true, force: true });
246
+ }
247
+ });
248
+
249
+ test('POST /flash 带未保存的覆盖值,预览的效果就是真实效果', async () => {
250
+ const dir = mkdtempSync(join(tmpdir(), 'gw-api-'));
251
+ process.env.HOME = dir;
252
+ try {
253
+ await withGateway({ llmStream: okStreamScript() }, async ({ ctx }) => {
254
+ const res = await callRoute(ctx, '/api/llm-gateway/flash', {
255
+ method: 'POST',
256
+ body: { inApp: { flashes: 40, durationSeconds: 3, color: '#ff0000' } },
257
+ });
258
+ const data = JSON.parse(res.text);
259
+ assert.equal(data.settings.flashes, 40);
260
+ assert.equal(data.settings.durationSeconds, 3);
261
+ assert.equal(data.settings.color, '#ff0000');
262
+ // 一个页面连着(假 webServer 不建真实 EventSource),送达数应当如实回报。
263
+ assert.equal(typeof data.viewers, 'number');
264
+ });
265
+ } finally {
266
+ rmSync(dir, { recursive: true, force: true });
267
+ }
268
+ });
269
+
270
+ test('POST /test 没有渠道时如实回报空结果,不假装成功', async () => {
271
+ const dir = mkdtempSync(join(tmpdir(), 'gw-api-'));
272
+ process.env.HOME = dir;
273
+ try {
274
+ await withGateway({ llmStream: okStreamScript() }, async ({ ctx }) => {
275
+ const res = await callRoute(ctx, '/api/llm-gateway/test', { method: 'POST' });
276
+ const data = JSON.parse(res.text);
277
+ assert.deepEqual(data.results, []);
278
+ assert.equal(data.ok, false, '一个渠道都没发出去,不该报成功');
279
+ });
280
+ } finally {
281
+ rmSync(dir, { recursive: true, force: true });
282
+ }
283
+ });
284
+
285
+ /* --------------------------- 网关请求触发 --------------------------- */
286
+
287
+ test('非流式请求结束后会记一条通知(窗口到期后收口)', async () => {
288
+ const dir = mkdtempSync(join(tmpdir(), 'gw-api-'));
289
+ process.env.HOME = dir;
290
+ try {
291
+ await withGateway({
292
+ llmStream: okStreamScript('任务已完成'),
293
+ config: { notify: { gateway: { settleSeconds: 1 }, inApp: { enabled: true, flashes: 2, durationSeconds: 1 } } },
294
+ }, async ({ port, ctx }) => {
295
+ const res = await request(port, {
296
+ path: '/v1/chat/completions',
297
+ method: 'POST',
298
+ headers: { 'content-type': 'application/json' },
299
+ body: JSON.stringify({ model: 'fake/fake-model', messages: [{ role: 'user', content: 'hi' }] }),
300
+ });
301
+ assert.equal(res.status, 200);
302
+ // 窗口是 1 秒:等它到期。
303
+ await wait(1200);
304
+ // 没有可用渠道 → 不真的发群,但这不影响请求成功。
305
+ // 关键断言:请求本身没被通知拖慢或改变。
306
+ assert.match(res.text, /任务已完成/);
307
+ // 设置页能读到网关状态,说明插件还活着。
308
+ const settings = await callRoute(ctx, '/api/llm-gateway/settings');
309
+ assert.equal(settings.status, 200);
310
+ });
311
+ } finally {
312
+ rmSync(dir, { recursive: true, force: true });
313
+ }
314
+ });
315
+
316
+ test('流式请求:通知旁路不改变客户端收到的 SSE', async () => {
317
+ const dir = mkdtempSync(join(tmpdir(), 'gw-api-'));
318
+ process.env.HOME = dir;
319
+ try {
320
+ await withGateway({ llmStream: okStreamScript('hello world') }, async ({ port }) => {
321
+ const res = await request(port, {
322
+ path: '/v1/chat/completions',
323
+ method: 'POST',
324
+ headers: { 'content-type': 'application/json' },
325
+ body: JSON.stringify({
326
+ model: 'fake/fake-model', messages: [{ role: 'user', content: 'hi' }], stream: true,
327
+ }),
328
+ });
329
+ assert.equal(res.status, 200);
330
+ assert.match(res.text, /hello world/);
331
+ assert.match(res.text, /\[DONE\]/);
332
+ // 只该有一份正文(旁路不能重复投递)
333
+ assert.equal(res.text.split('hello world').length - 1, 1);
334
+ });
335
+ } finally {
336
+ rmSync(dir, { recursive: true, force: true });
337
+ }
338
+ });
339
+
340
+ test('通知发送失败不会把请求变成 500', async () => {
341
+ const dir = mkdtempSync(join(tmpdir(), 'gw-api-'));
342
+ process.env.HOME = dir;
343
+ try {
344
+ await withGateway({ llmStream: okStreamScript('ok') }, async ({ port, ctx }) => {
345
+ // 配一个必然连不上的 webhook,并打开通知。
346
+ await callRoute(ctx, '/api/llm-gateway/settings', {
347
+ method: 'POST',
348
+ body: { path: ['channels', 'feishu', 'webhook'], value: 'http://127.0.0.1:1/nope' },
349
+ });
350
+ await callRoute(ctx, '/api/llm-gateway/settings', {
351
+ method: 'POST',
352
+ body: { path: ['channels', 'feishu', 'enabled'], value: true },
353
+ });
354
+ await callRoute(ctx, '/api/llm-gateway/settings', {
355
+ method: 'POST',
356
+ body: { path: ['gateway', 'settleSeconds'], value: 0 },
357
+ });
358
+ await callRoute(ctx, '/api/llm-gateway/settings', {
359
+ method: 'POST',
360
+ body: { path: ['timeoutMs'], value: 1000 },
361
+ });
362
+ const res = await request(port, {
363
+ path: '/v1/chat/completions',
364
+ method: 'POST',
365
+ headers: { 'content-type': 'application/json' },
366
+ body: JSON.stringify({ model: 'fake/fake-model', messages: [{ role: 'user', content: 'hi' }] }),
367
+ });
368
+ assert.equal(res.status, 200, 'webhook 挂了不该让模型请求失败');
369
+ await wait(300);
370
+ });
371
+ } finally {
372
+ rmSync(dir, { recursive: true, force: true });
373
+ }
374
+ });
375
+
376
+ test('宿主没有 webServer 时插件照常工作,只是没有设置页', async () => {
377
+ const dir = mkdtempSync(join(tmpdir(), 'gw-api-'));
378
+ process.env.HOME = dir;
379
+ try {
380
+ const port = await freePort();
381
+ const ctx = fakeCtx({ llmStream: okStreamScript() });
382
+ ctx.inject = () => {}; // 模拟没有浏览器半身的 headless 组合
383
+ apply(ctx, { host: '127.0.0.1', port, apiKey: '', allowedHosts: [`127.0.0.1:${port}`] });
384
+ await wait(80);
385
+ try {
386
+ const res = await request(port, { path: '/healthz' });
387
+ assert.equal(res.status, 200, '网关本身不受影响');
388
+ } finally {
389
+ ctx.dispose();
390
+ await wait(40);
391
+ }
392
+ } finally {
393
+ rmSync(dir, { recursive: true, force: true });
394
+ }
395
+ });
396
+
397
+ /* ------------------------------ 跑测试 ------------------------------ */
398
+
399
+ for (const { name, fn } of tests) {
400
+ try {
401
+ await fn();
402
+ passed += 1;
403
+ console.log(`✓ ${name}`);
404
+ } catch (error) {
405
+ failures += 1;
406
+ console.error(`✗ ${name}`);
407
+ console.error(` ${error?.message ?? error}`);
408
+ }
409
+ }
410
+
411
+ console.log(`\n${failures === 0 ? '全部通过' : '有失败'}(通过 ${passed}/${tests.length})`);
412
+ process.exit(failures === 0 ? 0 : 1);