@hugesb/dsh-stream-agent 0.0.0-stage → 0.3.2

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.
Files changed (161) hide show
  1. package/CHANGELOG.md +622 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +202 -0
  4. package/README.en.md +349 -0
  5. package/README.md +300 -3
  6. package/cordis.patch.yml +77 -0
  7. package/dist/entry/action-gate.js +206 -0
  8. package/dist/entry/adapter-kit.js +192 -0
  9. package/dist/entry/context-render.js +119 -0
  10. package/dist/entry/control-bar-cli.js +289 -0
  11. package/dist/entry/control-bar.js +123 -0
  12. package/dist/entry/control-session.js +115 -0
  13. package/dist/entry/control-state.js +125 -0
  14. package/dist/entry/cordis-compat.js +95 -0
  15. package/dist/entry/eval-probe.js +112 -0
  16. package/dist/entry/intent-log.js +121 -0
  17. package/dist/entry/json-persistence.js +306 -0
  18. package/dist/entry/loop.js +4163 -0
  19. package/dist/entry/mock-provider.js +549 -0
  20. package/dist/entry/obs-broker.js +178 -0
  21. package/dist/entry/ptc-bridge.js +405 -0
  22. package/dist/entry/state-handle.js +217 -0
  23. package/dist/entry/takeover-registry.js +60 -0
  24. package/dist/kernel/control-bar.js +559 -0
  25. package/dist/kernel/final.js +62 -0
  26. package/dist/kernel/gate.js +464 -0
  27. package/dist/kernel/modes.js +253 -0
  28. package/dist/kernel/obs.js +517 -0
  29. package/dist/kernel/parser.js +1081 -0
  30. package/dist/kernel/render.js +466 -0
  31. package/dist/kernel/state.js +416 -0
  32. package/dist/version.js +9 -0
  33. package/docs/TEST-PROPOSITIONS.md +139 -0
  34. package/docs/adr-001-segment-boundary.md +61 -0
  35. package/docs/architecture.md +104 -0
  36. package/docs/desktop-ui-feasibility.md +277 -0
  37. package/docs/disabled-lines-audit.md +53 -0
  38. package/docs/limitations.md +181 -0
  39. package/docs/protocol.md +99 -0
  40. package/docs/v0.4.0-plan.md +50 -0
  41. package/eval/METRICS.md +128 -0
  42. package/eval/RESULTS.md +246 -0
  43. package/eval/tasks/fixtures/big-report.md +298 -0
  44. package/eval/tasks/fixtures/build-manifest.txt +5 -0
  45. package/eval/tasks/fixtures/deploy.yaml +4 -0
  46. package/eval/tasks/fixtures/error.log +200 -0
  47. package/eval/tasks/fixtures/features.yaml +4 -0
  48. package/eval/tasks/fixtures/pipeline.yaml +4 -0
  49. package/eval/tasks/fixtures/sales-q1.csv +61 -0
  50. package/eval/tasks/fixtures/settings.yaml +4 -0
  51. package/eval/tasks/fixtures/users-roster.json +304 -0
  52. package/eval/tasks/fixtures/users-scores.json +20 -0
  53. package/eval/tasks/gen-fixtures.cjs +80 -0
  54. package/eval/tasks/tasks.json +150 -0
  55. package/eval/tools/f6-kill-drill.cjs +176 -0
  56. package/eval/tools/f6-kill-drill.worker.cjs +131 -0
  57. package/eval/tools/gen-results.cjs +191 -0
  58. package/eval/tools/machine-test.cjs +200 -0
  59. package/eval/tools/manual-code-scenarios.md +59 -0
  60. package/eval/tools/replay-check.cjs +311 -0
  61. package/eval/tools/runner.cjs +219 -0
  62. package/eval/tools/session-log.cjs +106 -0
  63. package/eval/tools/summarize.cjs +185 -0
  64. package/eval/tools/t3-cells.cjs +173 -0
  65. package/package.json +73 -6
  66. package/patches/adapters-smoke.yml +41 -0
  67. package/patches/eval-account.yml +36 -0
  68. package/patches/eval-baseline.yml +33 -0
  69. package/patches/eval-stream-code-off.yml +46 -0
  70. package/patches/eval-stream-code-on.yml +47 -0
  71. package/patches/eval-stream.yml +54 -0
  72. package/patches/takeover.yml +42 -0
  73. package/patches/test-preset.yml +23 -0
  74. package/preset/stream/cordis.patch.yml +39 -0
  75. package/preset/stream/package.json +13 -0
  76. package/preset.yml +56 -0
  77. package/profiles/stream/README.md +66 -0
  78. package/profiles/stream/cordis.patch.yml +12 -0
  79. package/profiles/stream/package.json +17 -0
  80. package/profiles/stream-headless/package.json +16 -0
  81. package/scripts/build.mjs +103 -0
  82. package/scripts/check-consistency.mjs +146 -0
  83. package/scripts/gate.mjs +138 -0
  84. package/scripts/install-check.mjs +116 -0
  85. package/scripts/install-cycle.mjs +88 -0
  86. package/scripts/release.mjs +428 -0
  87. package/scripts/repair-session-logs.mjs +498 -0
  88. package/src/entry/action-gate.ts +206 -0
  89. package/src/entry/adapter-kit.ts +192 -0
  90. package/src/entry/context-render.ts +119 -0
  91. package/src/entry/control-bar-cli.ts +289 -0
  92. package/src/entry/control-bar.ts +123 -0
  93. package/src/entry/control-session.ts +115 -0
  94. package/src/entry/control-state.ts +125 -0
  95. package/src/entry/cordis-compat.ts +95 -0
  96. package/src/entry/eval-probe.ts +112 -0
  97. package/src/entry/intent-log.ts +121 -0
  98. package/src/entry/json-persistence.ts +306 -0
  99. package/src/entry/loop.ts +4163 -0
  100. package/src/entry/mock-provider.ts +549 -0
  101. package/src/entry/obs-broker.ts +178 -0
  102. package/src/entry/ptc-bridge.ts +405 -0
  103. package/src/entry/state-handle.ts +217 -0
  104. package/src/entry/takeover-registry.ts +60 -0
  105. package/src/kernel/control-bar.ts +559 -0
  106. package/src/kernel/final.ts +62 -0
  107. package/src/kernel/gate.ts +464 -0
  108. package/src/kernel/modes.ts +253 -0
  109. package/src/kernel/obs.ts +517 -0
  110. package/src/kernel/parser.ts +1081 -0
  111. package/src/kernel/render.ts +466 -0
  112. package/src/kernel/state.ts +416 -0
  113. package/src/version.ts +9 -0
  114. package/test/activation.test.ts +187 -0
  115. package/test/adapters.test.ts +676 -0
  116. package/test/control-bar.test.ts +486 -0
  117. package/test/desktop-ui.test.ts +359 -0
  118. package/test/eval-probe.test.ts +139 -0
  119. package/test/f5-plan.test.ts +221 -0
  120. package/test/f6-intent.test.ts +168 -0
  121. package/test/f7-segment.test.ts +190 -0
  122. package/test/fix-limits.test.ts +599 -0
  123. package/test/gate.test.ts +380 -0
  124. package/test/helpers/stub-loop.ts +240 -0
  125. package/test/host-conformance.test.ts +418 -0
  126. package/test/kernel/obs.test.ts +329 -0
  127. package/test/kernel/parser.test.ts +451 -0
  128. package/test/loop.test.ts +1393 -0
  129. package/test/mock-provider.test.ts +386 -0
  130. package/test/ptc-bridge.test.ts +356 -0
  131. package/test/render.test.ts +418 -0
  132. package/test/s2-install-check.test.ts +46 -0
  133. package/test/scenarios/3-file-basic.json +13 -0
  134. package/test/scenarios/5-file-basic.json +22 -0
  135. package/test/scenarios/burn-more.json +9 -0
  136. package/test/scenarios/degraded-final.json +10 -0
  137. package/test/scenarios/fault-abort-xml.json +11 -0
  138. package/test/scenarios/fault-malformed-command.json +12 -0
  139. package/test/scenarios/fault-midstream-abort.json +11 -0
  140. package/test/scenarios/fault-saturating-output.json +9 -0
  141. package/test/scenarios/fault-timeout.json +9 -0
  142. package/test/scenarios/peek-first.json +11 -0
  143. package/test/scenarios/peek-second.json +11 -0
  144. package/test/scenarios/peek-third.json +10 -0
  145. package/test/scenarios/recover-final.json +10 -0
  146. package/test/scenarios/reroute-first.json +17 -0
  147. package/test/scenarios/reroute-second.json +16 -0
  148. package/test/scenarios/starvation-final.json +10 -0
  149. package/test/scenarios/starvation-promote.json +11 -0
  150. package/test/scenarios/wait-tools-continue.json +10 -0
  151. package/test/scenarios/wait-tools-xml.json +22 -0
  152. package/test/scenarios/wait-tools.json +15 -0
  153. package/test/session-format.test.ts +234 -0
  154. package/test/state.test.ts +335 -0
  155. package/test/stream-v02.test.ts +264 -0
  156. package/test/v031-display.test.ts +333 -0
  157. package/test/v032-conflict.test.ts +191 -0
  158. package/test/v032-truncation.test.ts +291 -0
  159. package/ui/client.js +576 -0
  160. package/ui/index.js +282 -0
  161. package/ui/package.json +26 -0
@@ -0,0 +1,359 @@
1
+ // test/desktop-ui.test.ts —— 桌面控制页的静态契约与宿主路由(v0.2.1)
2
+ //
3
+ // 这组测试盯的是两个"装错就整页起不来"的点:
4
+ // 1. dsh-client-modules 以包为单位扫描 dsh.client。主包已有七个 entry,
5
+ // 若主包声明 dsh.client 会抛多源错误,整个客户端 boot 失败。
6
+ // 2. ui/client.js 由宿主原样拼接进 boot 包,语法错误同样会炸 boot。
7
+ // 这里用 new Function 只编译不执行(顶层 window 由浏览器提供)。
8
+
9
+ import { test } from 'node:test';
10
+ import assert from 'node:assert/strict';
11
+ import { EventEmitter } from 'node:events';
12
+ import { mkdtempSync, readFileSync, existsSync } from 'node:fs';
13
+ import { tmpdir } from 'node:os';
14
+ import { dirname, join, resolve } from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+
17
+ import { handleControlRequest } from '../ui/index.js';
18
+
19
+ const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
20
+
21
+ function readJson(path: string): any {
22
+ return JSON.parse(readFileSync(join(pkgRoot, path), 'utf8'));
23
+ }
24
+
25
+ function makeRes(): any {
26
+ return {
27
+ status: 0,
28
+ headers: {},
29
+ payload: '',
30
+ writeHead(status: number, headers?: Record<string, string>) {
31
+ this.status = status;
32
+ this.headers = headers ?? {};
33
+ },
34
+ end(chunk?: string) {
35
+ this.payload = chunk ?? '';
36
+ },
37
+ };
38
+ }
39
+
40
+ function makeReq(options: {
41
+ method?: string;
42
+ headers?: Record<string, string>;
43
+ body?: string;
44
+ remoteAddress?: string;
45
+ } = {}): any {
46
+ const req = new EventEmitter() as any;
47
+ req.method = options.method ?? 'GET';
48
+ req.headers = options.headers ?? {};
49
+ req.socket = { remoteAddress: options.remoteAddress ?? '127.0.0.1' };
50
+ req.body = options.body;
51
+ return req;
52
+ }
53
+
54
+ async function invoke(ctx: any, req: any): Promise<any> {
55
+ const res = makeRes();
56
+ const promise = handleControlRequest(ctx, req, res);
57
+ if (req.body !== undefined) {
58
+ req.emit('data', Buffer.from(req.body));
59
+ req.emit('end');
60
+ }
61
+ await promise;
62
+ return res;
63
+ }
64
+
65
+ function runtimeStub(overrides: Record<string, unknown> = {}): any {
66
+ const calls: string[] = [];
67
+ const status = {
68
+ version: '0.2.1',
69
+ takeover: true,
70
+ mode: 'balanced',
71
+ modeSource: 'file',
72
+ modeLocked: false,
73
+ lang: 'zh',
74
+ langSource: 'file',
75
+ langLocked: false,
76
+ effective: {
77
+ selfReadFeedback: 'receipt',
78
+ enableCode: 'auto',
79
+ persistFallback: true,
80
+ maxParallelToolCalls: 3,
81
+ maxReentries: 8,
82
+ budgetTokens: null,
83
+ },
84
+ modes: [],
85
+ updatedAt: '2026-11-16T00:00:00.000Z',
86
+ stateFile: '/tmp/control.json',
87
+ ...overrides,
88
+ };
89
+ return {
90
+ calls,
91
+ status: () => status,
92
+ setMode(mode: string) {
93
+ calls.push(`mode:${mode}`);
94
+ return { ok: true, persisted: true };
95
+ },
96
+ setLang(lang: string) {
97
+ calls.push(`lang:${lang}`);
98
+ return { ok: true, persisted: true };
99
+ },
100
+ };
101
+ }
102
+
103
+ function ctxWith(services: Record<string, unknown>): any {
104
+ return {
105
+ get(name: string) {
106
+ if (name === 'connection') return { admit: () => ({ peer: {} }) };
107
+ return services[name];
108
+ },
109
+ };
110
+ }
111
+
112
+ test('包声明:主包不得有 dsh.client,UI 子包必须声明 web + ./client', () => {
113
+ const root = readJson('package.json');
114
+ const ui = readJson('ui/package.json');
115
+ assert.equal(root.dsh.client, undefined, '主包声明 dsh.client 会让 dsh-client-modules 抛多源错误');
116
+ assert.equal(ui.dsh?.client?.platform, 'web');
117
+ assert.equal(ui.exports?.['./client'], './client.js');
118
+ assert.ok(ui.dsh.client.inject.includes('@deepseek-ai/dsh-client-ui-layout'));
119
+ assert.ok(ui.dsh.client.external.includes('react'));
120
+ assert.ok(root.files.includes('ui/'), 'npm 包必须带上 ui/');
121
+ });
122
+
123
+ test('客户端 bundle:__ModuleLoader__ 包装、id、apply/inject 全部合规', () => {
124
+ const source = readFileSync(join(pkgRoot, 'ui', 'client.js'), 'utf8');
125
+ let captured: any;
126
+ const fakeWindow = { __ModuleLoader__: { load(definition: any) { captured = definition; } } };
127
+ const fakeRequire = () => ({
128
+ createElement() {},
129
+ useState() {},
130
+ useEffect() {},
131
+ useCallback() {},
132
+ useMemo() {},
133
+ });
134
+
135
+ assert.doesNotThrow(() => new Function('window', 'require', source)(fakeWindow, fakeRequire));
136
+ assert.equal(captured?.id, '@hugesb/dsh-stream-agent-ui');
137
+
138
+ const exports = captured.factory(fakeRequire);
139
+ assert.equal(typeof exports.apply, 'function');
140
+ assert.deepEqual(exports.inject, ['slots']);
141
+ assert.equal(exports.ROUTE, '/stream-agent/control');
142
+ });
143
+
144
+ test('文案表:中英键集合完全一致,且没有空串或遗漏翻译', () => {
145
+ const source = readFileSync(join(pkgRoot, 'ui', 'client.js'), 'utf8');
146
+ let captured: any;
147
+ const fakeWindow = { __ModuleLoader__: { load(definition: any) { captured = definition; } } };
148
+ new Function('window', 'require', source)(fakeWindow, () => ({}));
149
+ const TEXT = captured.factory(() => ({})).TEXT;
150
+
151
+ const flatten = (node: any, prefix = ''): Map<string, unknown> => {
152
+ const out = new Map<string, unknown>();
153
+ for (const [key, value] of Object.entries(node)) {
154
+ const path = prefix ? `${prefix}.${key}` : key;
155
+ if (value && typeof value === 'object') {
156
+ for (const [k, v] of flatten(value, path)) out.set(k, v);
157
+ } else {
158
+ out.set(path, value);
159
+ }
160
+ }
161
+ return out;
162
+ };
163
+
164
+ const zh = flatten(TEXT.zh);
165
+ const en = flatten(TEXT.en);
166
+ // 专有名词与命令行示例在两语言里本来就该一样(tf-code 是产品内部叫法,命令不能翻译)。
167
+ const sameOnPurpose = new Set(['params.enableCode', 'cliHint']);
168
+ assert.deepEqual([...en.keys()].sort(), [...zh.keys()].sort(), '两个语言表的键路径必须一一对应');
169
+ for (const [path, value] of zh) {
170
+ assert.equal(typeof value, 'string', `zh.${path} 必须是字符串`);
171
+ assert.notEqual(value.trim(), '', `zh.${path} 不能为空`);
172
+ const other = en.get(path);
173
+ assert.equal(typeof other, 'string', `en.${path} 必须是字符串`);
174
+ assert.notEqual(String(other).trim(), '', `en.${path} 不能为空`);
175
+ if (!sameOnPurpose.has(path)) {
176
+ assert.notEqual(String(other), value, `en.${path} 与中文完全相同,疑似漏翻`);
177
+ }
178
+ }
179
+ });
180
+
181
+ test('路由 GET:运行时在位时返回接管状态与四模式目录', async () => {
182
+ const runtime = runtimeStub();
183
+ const res = await invoke(ctxWith({ streamAgentRuntime: runtime }), makeReq());
184
+ assert.equal(res.status, 200);
185
+ const body = JSON.parse(res.payload);
186
+ assert.equal(body.ok, true);
187
+ assert.equal(body.status.takeover, true);
188
+ assert.equal(body.status.mode, 'balanced');
189
+ assert.equal(body.status.modeSource, 'file');
190
+ });
191
+
192
+ test('路由 GET:模式目录带省 token 档位、可用性与标注(页面据此渲染,不自己编)', async () => {
193
+ // 运行时缺席时走 fallbackStatus(),它自己拼 modes——这条路径以前漏过字段,
194
+ // 所以专门在降级分支上断言,避免"有 loop 时页面有标注、没 loop 时没有"。
195
+ const res = await invoke(ctxWith({}), makeReq());
196
+ const body = JSON.parse(res.payload);
197
+ assert.equal(body.status.modes.length, 4);
198
+ for (const mode of body.status.modes) {
199
+ assert.ok(['most', 'more', 'baseline', 'least'].includes(mode.saving), `${mode.id} 缺省 token 档位`);
200
+ assert.ok(mode.savingLabel.zh && mode.savingLabel.en, `${mode.id} 缺双语档位标签`);
201
+ assert.ok(['default', 'ready', 'needs-ptc'].includes(mode.availability), `${mode.id} 缺可用性`);
202
+ assert.ok(mode.availabilityLabel.zh && mode.availabilityLabel.en, `${mode.id} 缺双语可用性标签`);
203
+ assert.ok(mode.note.zh && mode.note.en, `${mode.id} 缺双语标注`);
204
+ }
205
+ });
206
+
207
+ test('路由 POST:切模式/语言走运行时服务,并回报 persisted', async () => {
208
+ const runtime = runtimeStub();
209
+ const ctx = ctxWith({ streamAgentRuntime: runtime });
210
+
211
+ const modeRes = await invoke(
212
+ ctx,
213
+ makeReq({
214
+ method: 'POST',
215
+ headers: { 'content-type': 'application/json' },
216
+ body: JSON.stringify({ mode: 'lean', expectedUpdatedAt: '2026-11-16T00:00:00.000Z' }),
217
+ }),
218
+ );
219
+ assert.equal(modeRes.status, 200);
220
+ assert.equal(JSON.parse(modeRes.payload).persisted, true);
221
+ assert.deepEqual(runtime.calls, ['mode:lean']);
222
+
223
+ const langRes = await invoke(
224
+ ctx,
225
+ makeReq({
226
+ method: 'POST',
227
+ headers: { 'content-type': 'application/json' },
228
+ body: JSON.stringify({ lang: 'en', expectedUpdatedAt: '2026-11-16T00:00:00.000Z' }),
229
+ }),
230
+ );
231
+ assert.equal(langRes.status, 200);
232
+ assert.deepEqual(runtime.calls, ['mode:lean', 'lang:en']);
233
+ });
234
+
235
+ test('路由 POST:过期 expectedUpdatedAt 返回 409 + 最新状态(多窗口不互相覆盖)', async () => {
236
+ const runtime = runtimeStub();
237
+ const res = await invoke(
238
+ ctxWith({ streamAgentRuntime: runtime }),
239
+ makeReq({
240
+ method: 'POST',
241
+ headers: { 'content-type': 'application/json' },
242
+ body: JSON.stringify({ mode: 'lean', expectedUpdatedAt: '2020-01-01T00:00:00.000Z' }),
243
+ }),
244
+ );
245
+ assert.equal(res.status, 409);
246
+ const body = JSON.parse(res.payload);
247
+ assert.equal(body.error.code, 'stale');
248
+ assert.equal(body.status.mode, 'balanced');
249
+ assert.deepEqual(runtime.calls, []);
250
+ });
251
+
252
+ test('路由 POST:expectedUpdatedAt=null 只在文件尚未写入时放行(首次写入不加锁)', async () => {
253
+ // 客户端总是发送 expectedUpdatedAt = status.updatedAt ?? null。
254
+ // null 的语义是"我以为这文件还不存在",所以只有真正未写入时才该放行;
255
+ // 若别人已经写过,null 必须被判为过期,否则两个窗口的首次点击会互相覆盖。
256
+ const virgin = runtimeStub({ updatedAt: null });
257
+ const first = await invoke(
258
+ ctxWith({ streamAgentRuntime: virgin }),
259
+ makeReq({
260
+ method: 'POST',
261
+ headers: { 'content-type': 'application/json' },
262
+ body: JSON.stringify({ mode: 'lean', expectedUpdatedAt: null }),
263
+ }),
264
+ );
265
+ assert.equal(first.status, 200);
266
+ assert.deepEqual(virgin.calls, ['mode:lean']);
267
+
268
+ const written = runtimeStub();
269
+ const late = await invoke(
270
+ ctxWith({ streamAgentRuntime: written }),
271
+ makeReq({
272
+ method: 'POST',
273
+ headers: { 'content-type': 'application/json' },
274
+ body: JSON.stringify({ mode: 'lean', expectedUpdatedAt: null }),
275
+ }),
276
+ );
277
+ assert.equal(late.status, 409);
278
+ assert.equal(JSON.parse(late.payload).error.code, 'stale');
279
+ assert.deepEqual(written.calls, [], '被判过期时不得触碰运行时');
280
+
281
+ // 不发送该字段 = 显式放弃栅栏(终端 curl 手改场景),保持向后兼容。
282
+ const bare = runtimeStub();
283
+ const unfenced = await invoke(
284
+ ctxWith({ streamAgentRuntime: bare }),
285
+ makeReq({
286
+ method: 'POST',
287
+ headers: { 'content-type': 'application/json' },
288
+ body: JSON.stringify({ lang: 'en' }),
289
+ }),
290
+ );
291
+ assert.equal(unfenced.status, 200);
292
+ assert.deepEqual(bare.calls, ['lang:en']);
293
+ });
294
+
295
+ test('路由 POST:装配配置/环境变量锁定时拒绝修改', async () => {
296
+ const runtime = runtimeStub({ modeSource: 'config', modeLocked: true });
297
+ const res = await invoke(
298
+ ctxWith({ streamAgentRuntime: runtime }),
299
+ makeReq({
300
+ method: 'POST',
301
+ headers: { 'content-type': 'application/json' },
302
+ body: JSON.stringify({ mode: 'power' }),
303
+ }),
304
+ );
305
+ assert.equal(res.status, 409);
306
+ assert.equal(JSON.parse(res.payload).error.code, 'locked');
307
+ assert.deepEqual(runtime.calls, []);
308
+ });
309
+
310
+ test('路由边界:未鉴权 401、跨站 403、非 JSON 415、非法模式 400', async () => {
311
+ const deniedCtx = { get: () => ({ admit: () => ({ rejection: 401 }) }) };
312
+ assert.equal((await invoke(deniedCtx, makeReq())).status, 401);
313
+
314
+ const cross = await invoke(
315
+ ctxWith({}),
316
+ makeReq({ method: 'POST', headers: { 'content-type': 'application/json', 'sec-fetch-site': 'cross-site' }, body: '{}' }),
317
+ );
318
+ assert.equal(cross.status, 403);
319
+
320
+ const notJson = await invoke(
321
+ ctxWith({}),
322
+ makeReq({ method: 'POST', headers: { 'content-type': 'text/plain' }, body: 'mode=lean' }),
323
+ );
324
+ assert.equal(notJson.status, 415);
325
+
326
+ const badMode = await invoke(
327
+ ctxWith({}),
328
+ makeReq({ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ mode: 'turbo' }) }),
329
+ );
330
+ assert.equal(badMode.status, 400);
331
+ assert.equal(JSON.parse(badMode.payload).error.code, 'invalid-mode');
332
+ });
333
+
334
+ test('降级路径:运行时缺席时写状态文件,并明确告知需要重启', async () => {
335
+ const dir = mkdtempSync(join(tmpdir(), 'tf-ui-fallback-'));
336
+ const previous = process.env.STREAM_AGENT_STATE_DIR;
337
+ process.env.STREAM_AGENT_STATE_DIR = dir;
338
+ try {
339
+ const res = await invoke(
340
+ ctxWith({}),
341
+ makeReq({
342
+ method: 'POST',
343
+ headers: { 'content-type': 'application/json' },
344
+ body: JSON.stringify({ mode: 'compat', lang: 'en' }),
345
+ }),
346
+ );
347
+ assert.equal(res.status, 200);
348
+ const body = JSON.parse(res.payload);
349
+ assert.equal(body.degraded, true);
350
+ assert.equal(body.status.takeover, false);
351
+ assert.equal(body.status.mode, 'compat');
352
+ assert.equal(body.status.lang, 'en');
353
+ assert.ok(body.notice.includes('重启'));
354
+ assert.ok(existsSync(join(dir, 'control.json')));
355
+ } finally {
356
+ if (previous === undefined) delete process.env.STREAM_AGENT_STATE_DIR;
357
+ else process.env.STREAM_AGENT_STATE_DIR = previous;
358
+ }
359
+ });
@@ -0,0 +1,139 @@
1
+ // test/eval-probe.test.ts —— 分派 08:中立评测探针(透传保真 / 原文留存 / fail-open)
2
+ import { describe, it } from 'node:test';
3
+ import assert from 'node:assert/strict';
4
+ import { mkdtempSync, readFileSync, existsSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import applyProbe from '../src/entry/eval-probe.ts';
8
+
9
+ /** 收集 ctx.on 注册的监听器(duck-type HostCtxLike) */
10
+ function captureCtx(): { ctx: Parameters<typeof applyProbe>[0]; listeners: Map<string, (...a: never[]) => unknown>; warns: string[] } {
11
+ const listeners = new Map<string, (...a: never[]) => unknown>();
12
+ const warns: string[] = [];
13
+ const ctx = {
14
+ on(event: string, listener: (...a: never[]) => unknown) { listeners.set(event, listener); },
15
+ get(service: string) {
16
+ return service === 'logger' ? { warn: (m: string) => warns.push(m) } : undefined;
17
+ },
18
+ } as unknown as Parameters<typeof applyProbe>[0];
19
+ return { ctx, listeners, warns };
20
+ }
21
+
22
+ async function* fakeStream(chunks: unknown[]): AsyncIterable<unknown> {
23
+ for (const c of chunks) yield c;
24
+ }
25
+
26
+ function readLines(file: string): Array<Record<string, unknown>> {
27
+ return readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l) as Record<string, unknown>);
28
+ }
29
+
30
+ describe('eval-probe(08 号插桩)', () => {
31
+ it('P1. 透传保真:chunk 逐个原样转发,顺序不变', async () => {
32
+ const dir = mkdtempSync(join(tmpdir(), 'eval-probe-'));
33
+ try {
34
+ const { ctx, listeners } = captureCtx();
35
+ applyProbe(ctx, { dumpDir: dir });
36
+ const onStream = listeners.get('llm/stream') as unknown as (o: Record<string, unknown>, next: () => AsyncIterable<unknown>) => AsyncIterable<unknown>;
37
+ assert.ok(onStream, 'llm/stream 监听器应注册');
38
+ const chunks = [
39
+ { type: 'text', text: 'hello' },
40
+ { type: 'usage', usage: { inputTokens: 12, outputTokens: 34, cacheReadTokens: 100, cacheWriteTokens: 5 } },
41
+ { type: 'finish', reason: { kind: 'stop' } },
42
+ ];
43
+ const out: unknown[] = [];
44
+ const stream = onStream({ messages: [{ role: 'user', content: [{ type: 'text', text: 'task' }] }] }, () => fakeStream(chunks));
45
+ for await (const c of stream) out.push(c);
46
+ assert.deepEqual(out, chunks, '探针不得改写任何 chunk');
47
+ } finally {
48
+ rmSync(dir, { recursive: true, force: true });
49
+ }
50
+ });
51
+
52
+ it('P2. 原文留存:request 记录含 messages 原文,chunk 记录含 usage 原文 JSON(M1/M4 数据源)', async () => {
53
+ const dir = mkdtempSync(join(tmpdir(), 'eval-probe-'));
54
+ try {
55
+ const { ctx, listeners } = captureCtx();
56
+ applyProbe(ctx, { dumpDir: dir });
57
+ const onStream = listeners.get('llm/stream') as unknown as (o: Record<string, unknown>, next: () => AsyncIterable<unknown>) => AsyncIterable<unknown>;
58
+ const options = {
59
+ sessionId: 'session-test',
60
+ messages: [{ role: 'system', content: [{ type: 'text', text: 'SYS' }] }, { role: 'user', content: [{ type: 'text', text: 'task-body' }] }],
61
+ provider: 'deepseek-official', model: 'deepseek-chat',
62
+ };
63
+ const chunks = [{ type: 'usage', usage: { inputTokens: 0, outputTokens: 9, totalTokens: 9, cacheReadTokens: 512 } }];
64
+ const stream = onStream(options, () => fakeStream(chunks));
65
+ for await (const _c of stream) { void _c; }
66
+
67
+ const file = join(dir, 'probe.jsonl');
68
+ assert.ok(existsSync(file), 'probe.jsonl 应落盘');
69
+ const lines = readLines(file);
70
+ const req = lines.find((l) => l.kind === 'request');
71
+ assert.ok(req !== undefined, 'request 记录存在');
72
+ const parsed = JSON.parse(req.options as string);
73
+ assert.equal(parsed.provider, 'deepseek-official');
74
+ assert.equal(parsed.messages.length, 2);
75
+ assert.equal(parsed.messages[0].content[0].text, 'SYS', 'messages 原文逐字留存(prefix_hash 数据源)');
76
+ const usageChunk = lines.find((l) => l.kind === 'chunk');
77
+ assert.ok(usageChunk !== undefined, 'chunk 记录存在');
78
+ const uc = JSON.parse(usageChunk.chunk as string);
79
+ assert.equal(uc.type, 'usage');
80
+ assert.equal(uc.usage.cacheReadTokens, 512, 'usage 原文含 cache 字段(M4 取证)');
81
+ assert.equal(usageChunk.seq, req.seq, 'chunk 归属同请求');
82
+ assert.ok(lines.some((l) => l.kind === 'stream-end'), 'stream-end 收尾记录');
83
+ } finally {
84
+ rmSync(dir, { recursive: true, force: true });
85
+ }
86
+ });
87
+
88
+ it('P3. fail-open:落盘不可写 → 停用记录 + 一次告警,流照常透传', async () => {
89
+ const { ctx, listeners, warns } = captureCtx();
90
+ // 用「普通文件充当目录」构造必然失败的路径:mkdirSync 在 Windows 与 POSIX 上都报
91
+ // ENOTDIR,且不依赖盘符是否存在、也不依赖运行用户是否有权限——CI 以 root 跑也稳定。
92
+ // 早先这里用 Z:\... 盘符路径,在 POSIX 上只是普通相对路径,mkdir 会成功,断言假绿。
93
+ const blockerRoot = mkdtempSync(join(tmpdir(), 'eval-probe-blocker-'));
94
+ const blockerFile = join(blockerRoot, 'not-a-dir');
95
+ writeFileSync(blockerFile, 'x');
96
+ try {
97
+ applyProbe(ctx, { dumpDir: join(blockerFile, 'eval-probe') });
98
+ const onStream = listeners.get('llm/stream') as unknown as (o: Record<string, unknown>, next: () => AsyncIterable<unknown>) => AsyncIterable<unknown>;
99
+ assert.ok(onStream);
100
+ const chunks = [{ type: 'text', text: 'survives' }];
101
+ const out: unknown[] = [];
102
+ const stream = onStream({ messages: [] }, () => fakeStream(chunks));
103
+ for await (const c of stream) out.push(c);
104
+ assert.deepEqual(out, chunks, '记录停用后流必须原样透传');
105
+ assert.ok(warns.some((w) => w.includes('eval-probe')), '必须留痕告警(不许静默)');
106
+ } finally {
107
+ rmSync(blockerRoot, { recursive: true, force: true });
108
+ }
109
+ });
110
+
111
+ it('P4. 未配置 dumpDir:只透传不记录 + 告警(评测装配遗漏可发现)', async () => {
112
+ const { ctx, listeners, warns } = captureCtx();
113
+ applyProbe(ctx, {});
114
+ const onStream = listeners.get('llm/stream') as unknown as (o: Record<string, unknown>, next: () => AsyncIterable<unknown>) => AsyncIterable<unknown>;
115
+ const out: unknown[] = [];
116
+ for await (const c of onStream({}, () => fakeStream([{ type: 'finish', reason: { kind: 'stop' } }]))) out.push(c);
117
+ assert.equal(out.length, 1);
118
+ assert.ok(warns.some((w) => w.includes('dumpDir')), '未配置必须告警');
119
+ });
120
+
121
+ it('P5. 多请求 seq 单调(M2 对账口径)', async () => {
122
+ const dir = mkdtempSync(join(tmpdir(), 'eval-probe-'));
123
+ try {
124
+ const { ctx, listeners } = captureCtx();
125
+ const handle = applyProbe(ctx, { dumpDir: dir });
126
+ const onStream = listeners.get('llm/stream') as unknown as (o: Record<string, unknown>, next: () => AsyncIterable<unknown>) => AsyncIterable<unknown>;
127
+ for (let i = 0; i < 3; i++) {
128
+ const s = onStream({ messages: [{ role: 'user', content: [{ type: 'text', text: `r${i}` }] }] }, () => fakeStream([]));
129
+ for await (const _c of s) { void _c; }
130
+ }
131
+ assert.equal(handle.requestCount(), 3);
132
+ const reqs = readLines(join(dir, 'probe.jsonl')).filter((l) => l.kind === 'request');
133
+ assert.deepEqual(reqs.map((r) => r.seq), [1, 2, 3]);
134
+ assert.equal(reqs[1].session, '', 'sessionId 缺省记空串不抛');
135
+ } finally {
136
+ rmSync(dir, { recursive: true, force: true });
137
+ }
138
+ });
139
+ });