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

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 (158) hide show
  1. package/CHANGELOG.md +497 -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 +3852 -0
  19. package/dist/entry/mock-provider.js +536 -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 +632 -0
  30. package/dist/kernel/render.js +444 -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 +415 -0
  87. package/scripts/repair-session-logs.mjs +403 -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 +3852 -0
  100. package/src/entry/mock-provider.ts +536 -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 +632 -0
  111. package/src/kernel/render.ts +444 -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/kernel/obs.test.ts +329 -0
  126. package/test/kernel/parser.test.ts +450 -0
  127. package/test/loop.test.ts +1393 -0
  128. package/test/mock-provider.test.ts +386 -0
  129. package/test/ptc-bridge.test.ts +356 -0
  130. package/test/render.test.ts +418 -0
  131. package/test/s2-install-check.test.ts +46 -0
  132. package/test/scenarios/3-file-basic.json +13 -0
  133. package/test/scenarios/5-file-basic.json +22 -0
  134. package/test/scenarios/burn-more.json +9 -0
  135. package/test/scenarios/degraded-final.json +10 -0
  136. package/test/scenarios/fault-abort-xml.json +11 -0
  137. package/test/scenarios/fault-malformed-command.json +12 -0
  138. package/test/scenarios/fault-midstream-abort.json +11 -0
  139. package/test/scenarios/fault-saturating-output.json +9 -0
  140. package/test/scenarios/fault-timeout.json +9 -0
  141. package/test/scenarios/peek-first.json +11 -0
  142. package/test/scenarios/peek-second.json +11 -0
  143. package/test/scenarios/peek-third.json +10 -0
  144. package/test/scenarios/recover-final.json +10 -0
  145. package/test/scenarios/reroute-first.json +17 -0
  146. package/test/scenarios/reroute-second.json +16 -0
  147. package/test/scenarios/starvation-final.json +10 -0
  148. package/test/scenarios/starvation-promote.json +11 -0
  149. package/test/scenarios/wait-tools-continue.json +10 -0
  150. package/test/scenarios/wait-tools-xml.json +22 -0
  151. package/test/scenarios/wait-tools.json +15 -0
  152. package/test/session-format.test.ts +234 -0
  153. package/test/state.test.ts +335 -0
  154. package/test/stream-v02.test.ts +264 -0
  155. package/test/v031-display.test.ts +333 -0
  156. package/ui/client.js +576 -0
  157. package/ui/index.js +282 -0
  158. package/ui/package.json +26 -0
@@ -0,0 +1,264 @@
1
+ // test/stream-v02.test.ts —— v0.2.0 优化项(对照上游 xuxiang-thinkflow 0.10.0 的语义对齐):
2
+ // T1 隐式写序:同流"先写后读"必须等写完成(上游 DESIGN:信息工具先等之前的写入)
3
+ // T2 重复 id 幂等:同 id 同内容返回原回执不重执行;同 id 不同内容拒绝
4
+ // T3 乐观 peek 延迟:同流 peek 未就绪句柄 → 流末 drain 后重试,成功交付
5
+ // T4 tf-read offset/limit:parser 接受行范围属性,映射透传数值
6
+ import { describe, it, beforeEach } from 'node:test';
7
+ import assert from 'node:assert/strict';
8
+ import { mkdtempSync, rmSync, writeFileSync, readFileSync } from 'node:fs';
9
+ import { tmpdir } from 'node:os';
10
+ import { join } from 'node:path';
11
+
12
+ import { SingleStreamDriver, DEFAULT_TOOL_MAPPING } from '../src/entry/loop.ts';
13
+ import type { DriverPorts, StreamRequestOptions, ToolBatchInputLike, ToolBatchResultLike, StreamDriverConfig } from '../src/entry/loop.ts';
14
+ import { normalizeStreamShim } from '../src/entry/loop.ts';
15
+ import { createMockModel } from '../src/entry/mock-provider.ts';
16
+ import type { Scenario } from '../src/entry/mock-provider.ts';
17
+ import { TfStreamParser } from '../src/kernel/parser.ts';
18
+
19
+ interface Harness {
20
+ driver: SingleStreamDriver;
21
+ sandboxDir: string;
22
+ execCounts: { write: number; read: number; bash: number };
23
+ wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }>;
24
+ cleanup: () => void;
25
+ }
26
+
27
+ function makeHarness(task: string, scenarios: Scenario[], seed?: Record<string, string>): Harness {
28
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-v02-'));
29
+ for (const [name, content] of Object.entries(seed ?? {})) writeFileSync(join(sandboxDir, name), content, 'utf8');
30
+ const execCounts = { write: 0, read: 0, bash: 0 };
31
+ const model = createMockModel({ scenarios, provider: 'mock' });
32
+ const wireRequests: Array<StreamRequestOptions & { contentTexts: string[] }> = [];
33
+ const execute = async (input: ToolBatchInputLike): Promise<ToolBatchResultLike> => {
34
+ const results: ToolBatchResultLike['results'] = [];
35
+ for (const call of input.calls) {
36
+ const args = JSON.parse(call.arguments) as Record<string, unknown>;
37
+ try {
38
+ if (call.name === 'write') {
39
+ execCounts.write += 1;
40
+ writeFileSync(join(sandboxDir, String(args['file_path'])), String(args['content'] ?? ''), 'utf8');
41
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: `written ${String(args['file_path'])}` }], isError: false } });
42
+ } else if (call.name === 'read') {
43
+ execCounts.read += 1;
44
+ const content = readFileSync(join(sandboxDir, String(args['file_path'])), 'utf8');
45
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: content }], isError: false } });
46
+ } else if (call.name === 'bash') {
47
+ execCounts.bash += 1;
48
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: `bash-echo:${String(args['command'] ?? '')}` }], isError: false } });
49
+ } else {
50
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: `unknown tool: ${call.name}` }], isError: true } });
51
+ }
52
+ } catch (error) {
53
+ results.push({ callId: call.id, result: { content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }], isError: true } });
54
+ }
55
+ }
56
+ return { results, additionalContexts: [], concluded: false };
57
+ };
58
+ const ports: DriverPorts = {
59
+ stream: (options) => {
60
+ wireRequests.push({ ...options, contentTexts: options.messages.map((m) => m.content.map((b) => b.text ?? '').join('\n')) });
61
+ return normalizeStreamShim(model.adapter.stream({
62
+ provider: options.provider, model: options.model, messages: options.messages, signal: options.signal,
63
+ }));
64
+ },
65
+ executeTools: execute,
66
+ onToolSettled: () => model.notifyToolResult(),
67
+ };
68
+ const config: StreamDriverConfig = { provider: 'mock', model: 'mock-scenario', streamIdleTimeoutMs: 30_000, maxReentries: 8 };
69
+ const driver = new SingleStreamDriver(ports, config);
70
+ driver.pushUserTask(task);
71
+ return {
72
+ driver, sandboxDir, execCounts, wireRequests,
73
+ cleanup: () => rmSync(sandboxDir, { recursive: true, force: true }),
74
+ };
75
+ }
76
+
77
+ describe('v0.2.0 优化项(上游 xuxiang-thinkflow 语义对齐)', () => {
78
+ let harness: Harness | undefined;
79
+ beforeEach(() => {
80
+ harness?.cleanup();
81
+ harness = undefined;
82
+ });
83
+
84
+ it('T1. 隐式写序:同流先写后读(无显式 depends_on)时,read 必须在 write ok 之后派发', async () => {
85
+ harness = makeHarness('先写后读', [
86
+ {
87
+ name: 'implicit-order',
88
+ match: { promptIncludes: '先写后读' },
89
+ chunking: { charsPerChunk: 0, delayMs: 0 },
90
+ steps: [
91
+ { type: 'text', text: '写入后读取。\n' },
92
+ {
93
+ type: 'commands',
94
+ commands: [
95
+ '<tf-write path="a.txt" id="w1">内容A</tf-write>',
96
+ '<tf-read path="a.txt" id="r1"/>',
97
+ '<tf-final id="f1" summary="write-read-done"/>',
98
+ ],
99
+ },
100
+ { type: 'finish', reason: 'stop' },
101
+ ],
102
+ },
103
+ ]);
104
+ try {
105
+ const reason = await harness.driver.runTurn();
106
+ assert.equal(reason.kind, 'completed');
107
+ const snap = harness.driver.snapshot();
108
+ const w1Ok = snap.records.find((r) => r.kind === 'command' && r.id === 'w1' && r.status === 'ok');
109
+ const r1Dispatched = snap.records.find((r) => r.kind === 'command' && r.id === 'r1' && r.status === 'dispatched');
110
+ assert.ok(w1Ok !== undefined && r1Dispatched !== undefined, '缺 write ok 或 read dispatched 记录');
111
+ assert.ok(r1Dispatched.seq > w1Ok.seq, `read 派发必须晚于 write ok(隐式写序);w1ok=${w1Ok.seq} r1dispatch=${r1Dispatched.seq}`);
112
+ assert.equal(harness.execCounts.read, 1);
113
+ assert.equal(readFileSync(join(harness.sandboxDir, 'a.txt'), 'utf8'), '内容A');
114
+ } finally {
115
+ harness?.cleanup();
116
+ }
117
+ });
118
+
119
+ it('T2. 重复 id 幂等:同 id 同内容返回原回执不重执行;同 id 不同内容拒绝', async () => {
120
+ harness = makeHarness('幂等重发', [
121
+ {
122
+ name: 'idempotent-dup',
123
+ match: { promptIncludes: '幂等重发' },
124
+ chunking: { charsPerChunk: 0, delayMs: 0 },
125
+ steps: [
126
+ { type: 'text', text: '写一次;等完成后同内容复用 id,再用同 id 写不同内容。\n' },
127
+ { type: 'commands', commands: ['<tf-write path="a.txt" id="w1">内容A</tf-write>'] },
128
+ { type: 'waitTools', 'count': 1, 'timeoutMs': 5000 },
129
+ {
130
+ type: 'commands',
131
+ commands: [
132
+ '<tf-write path="a.txt" id="w1">内容A</tf-write>',
133
+ '<tf-write path="b.txt" id="w1">内容B</tf-write>',
134
+ '<tf-final id="f1" summary="幂等完成"/>',
135
+ ],
136
+ },
137
+ { type: 'finish', reason: 'stop' },
138
+ ],
139
+ },
140
+ ]);
141
+ try {
142
+ const reason = await harness.driver.runTurn();
143
+ assert.equal(reason.kind, 'completed');
144
+ const snap = harness.driver.snapshot();
145
+ const dupRecord = snap.records.find((r) => r.kind === 'command' && r.id === 'w1' && r.status === 'ok' && String((r as { detail?: string }).detail ?? '').startsWith('duplicate-idempotent'));
146
+ assert.ok(dupRecord !== undefined, '同内容同 id 重复声明应记 duplicate-idempotent 原回执');
147
+ const conflict = snap.records.find((r) => r.kind === 'command' && r.id === 'w1' && r.status === 'rejected' && String((r as { detail?: string }).detail ?? '').includes('换新 id'));
148
+ assert.ok(conflict !== undefined, '同 id 不同内容应被拒绝并提示换新 id');
149
+ assert.equal(harness.execCounts.write, 1, '幂等声明不得重复执行工具');
150
+ assert.equal(readFileSync(join(harness.sandboxDir, 'a.txt'), 'utf8'), '内容A');
151
+ } finally {
152
+ harness?.cleanup();
153
+ }
154
+ });
155
+
156
+ it('T3. 乐观 peek 延迟:同流 peek 未就绪句柄 → 流末重试成功,内容注入下一请求', async () => {
157
+ harness = makeHarness('乐观peek', [
158
+ // 注意:mock 按首个命中的剧本选择——s2(含注入文本匹配)必须排在 s1 之前
159
+ {
160
+ name: 'optimistic-peek-final',
161
+ match: { promptIncludes: 'tf-stream:peek' },
162
+ chunking: { charsPerChunk: 0, delayMs: 0 },
163
+ steps: [
164
+ { type: 'text', text: 'peek 内容已取回。\n' },
165
+ { type: 'commands', commands: ['<tf-final id="f1" summary="answer-ERROR-42-l-q"/>'] },
166
+ { type: 'finish', reason: 'stop' },
167
+ ],
168
+ },
169
+ {
170
+ name: 'optimistic-peek',
171
+ match: { promptIncludes: '乐观peek' },
172
+ chunking: { charsPerChunk: 0, delayMs: 0 },
173
+ steps: [
174
+ { type: 'text', text: '读后立即 peek(同流乐观)。\n' },
175
+ {
176
+ type: 'commands',
177
+ commands: ['<tf-read path="log.txt" id="r1"/>', '<tf-peek handle="obs:read:r1@v1" id="p1"/>'],
178
+ },
179
+ { type: 'finish', reason: 'stop' },
180
+ ],
181
+ },
182
+ ], { 'log.txt': 'L1-alpha\nL42-ERROR-42-l-q\nL3-gamma\n' });
183
+ try {
184
+ const reason = await harness.driver.runTurn();
185
+ assert.equal(reason.kind, 'completed');
186
+ const snap = harness.driver.snapshot();
187
+ const peekOk = snap.records.filter((r) => r.kind === 'command' && r.id === 'p1' && r.status === 'ok');
188
+ assert.equal(peekOk.length, 1, `延迟重试后 peek 应恰一次 ok:${JSON.stringify(snap.records.filter((r) => r.kind === 'command' && r.id === 'p1'))}`);
189
+ const peekFailed = snap.records.find((r) => r.kind === 'command' && r.id === 'p1' && r.status === 'failed');
190
+ assert.equal(peekFailed, undefined, '乐观 peek 不应失败');
191
+ const req2 = harness.wireRequests[1]!;
192
+ assert.ok(
193
+ req2.contentTexts.some((t) => t.includes('L42-ERROR-42-l-q')),
194
+ '请求 2 应注入 peek 取回的内容',
195
+ );
196
+ } finally {
197
+ harness?.cleanup();
198
+ }
199
+ });
200
+
201
+ it('T5. tf-final 同 id 更新答案:重入流内复用 f1 携带新 summary → 覆盖最终答案(last-wins)', async () => {
202
+ harness = makeHarness('final覆盖', [
203
+ // 顺序敏感:s2(注入文本匹配)在前
204
+ {
205
+ name: 'final-update',
206
+ match: { promptIncludes: 'tf-stream:peek' },
207
+ chunking: { charsPerChunk: 0, delayMs: 0 },
208
+ steps: [
209
+ { type: 'text', text: '细节到手,更新最终答案。\n' },
210
+ { type: 'commands', commands: ['<tf-final id="f1" summary="answer-L42-zebra-final"/>'] },
211
+ { type: 'finish', reason: 'stop' },
212
+ ],
213
+ },
214
+ {
215
+ name: 'final-placeholder',
216
+ match: { promptIncludes: 'final覆盖' },
217
+ chunking: { charsPerChunk: 0, delayMs: 0 },
218
+ steps: [
219
+ { type: 'text', text: '读后乐观 peek,占位收尾。\n' },
220
+ {
221
+ type: 'commands',
222
+ commands: [
223
+ '<tf-read path="log.txt" id="r1"/>',
224
+ '<tf-peek handle="obs:read:r1@v1" id="p1"/>',
225
+ '<tf-final id="f1" summary="占位"/>',
226
+ ],
227
+ },
228
+ { type: 'finish', reason: 'stop' },
229
+ ],
230
+ },
231
+ ], { 'log.txt': 'L42-zebra: the answer lives here\n' });
232
+ try {
233
+ const reason = await harness.driver.runTurn();
234
+ assert.equal(reason.kind, 'completed');
235
+ const snap = harness.driver.snapshot();
236
+ const finals = snap.records.filter((r) => r.kind === 'final');
237
+ const last = finals[finals.length - 1] as { summary?: string } | undefined;
238
+ assert.ok(last !== undefined);
239
+ assert.equal(last.summary, 'answer-L42-zebra-final', `最终答案应被同 id 新 summary 覆盖,实际:${last.summary}`);
240
+ // 最终 assistant 消息 = 更新后的答案(headless 输出与 checks 的消费面)
241
+ const req2 = harness.wireRequests[1]!;
242
+ assert.ok(req2.contentTexts.some((t) => t.includes('[tf-stream:peek')), '重入流应注入 peek 结果');
243
+ } finally {
244
+ harness?.cleanup();
245
+ }
246
+ });
247
+
248
+ it('T4. tf-read offset/limit:parser 接受行范围属性,映射透传数值', () => {
249
+ const parser = new TfStreamParser();
250
+ const events = parser.feed('<tf-read path="big.log" id="r1" offset="100" limit="50"/>');
251
+ const cmdEvent = events.find((e) => e.type === 'command');
252
+ assert.ok(cmdEvent !== undefined && cmdEvent.type === 'command', '带 offset/limit 的 tf-read 应正常闭合');
253
+ const mapped = DEFAULT_TOOL_MAPPING.toToolCall(cmdEvent.command);
254
+ assert.ok(mapped !== null && mapped.name === 'read');
255
+ assert.equal((mapped.arguments as Record<string, unknown>)['offset'], 100);
256
+ assert.equal((mapped.arguments as Record<string, unknown>)['limit'], 50);
257
+ const parser2 = new TfStreamParser();
258
+ const events2 = parser2.feed('<tf-read path="big.log" id="r2" offset="abc"/>');
259
+ const cmdEvent2 = events2.find((e) => e.type === 'command');
260
+ assert.ok(cmdEvent2 !== undefined && cmdEvent2.type === 'command');
261
+ const mapped2 = DEFAULT_TOOL_MAPPING.toToolCall(cmdEvent2.command);
262
+ assert.equal((mapped2!.arguments as Record<string, unknown>)['offset'], undefined, '非数字 offset 不得进参数');
263
+ });
264
+ });
@@ -0,0 +1,333 @@
1
+ // test/v031-display.test.ts —— v0.3.1 思考过程显示修复(electron 乱码 bug)
2
+ //
3
+ // 覆盖三条修复面:
4
+ // - reasoning-delta 捕获:落盘 assistant/message 的 `{type:'reasoning'}` 内容块(桌面端
5
+ // 思考过程行的数据源;0.3.0 只计体积不落盘 → 思考区显示错误)
6
+ // - 落盘正文纯 prose 化:tf-* 协议标记与 DSML 噪声不再进 assistant/message 文本
7
+ // (0.3.0 落整段原文 → 桌面端过程区把标记渲染成乱码)
8
+ // - agent/assistant-stream 实时帧:start → reasoning-delta chunks → end(committed+seq),
9
+ // revision/index 契约与宿主 SessionAssistantStreamAccumulator.accept 对齐;发射异常熔断
10
+ //
11
+ // 取证锚(宿主面):dsh-client-ui-chat/src/client/conversation-nodes/{assistant,event-projection}.ts、
12
+ // dsh-api-session-controller/src/client/sessions/assistant-stream.ts。
13
+
14
+ import { test } from 'node:test';
15
+ import assert from 'node:assert/strict';
16
+ import { mkdtempSync, rmSync } from 'node:fs';
17
+ import { tmpdir } from 'node:os';
18
+ import { join } from 'node:path';
19
+
20
+ import { SingleStreamDriver, createSessionEventWriter } from '../src/entry/loop.ts';
21
+ import type {
22
+ DriverPorts,
23
+ StreamChunkLike,
24
+ StreamDriverConfig,
25
+ ToolBatchInputLike,
26
+ ToolBatchResultLike,
27
+ } from '../src/entry/loop.ts';
28
+ import { TfStreamParser } from '../src/kernel/parser.ts';
29
+
30
+ // ---------------------------------------------------------------- 测试设施
31
+
32
+ interface FakeSessionEvent {
33
+ type: string;
34
+ data: Record<string, unknown>;
35
+ opts?: unknown;
36
+ seq: number;
37
+ }
38
+
39
+ function createFakeSession() {
40
+ const events: FakeSessionEvent[] = [];
41
+ return {
42
+ id: 'session-display-test',
43
+ header: { id: 'session-display-test' },
44
+ events,
45
+ append(type: string, data: unknown, opts?: unknown) {
46
+ const seq = events.length + 1;
47
+ events.push({ type, data: data as Record<string, unknown>, opts, seq });
48
+ return { seq };
49
+ },
50
+ snapshotEvents(from = 0) {
51
+ return events.slice(from);
52
+ },
53
+ };
54
+ }
55
+
56
+ type ChunkGen = AsyncGenerator<StreamChunkLike, void, undefined>;
57
+
58
+ /** 逐块吐出的假流:reasoning 块(index 0)→ 文本块(index 1)。 */
59
+ async function* scriptedStream(chunks: StreamChunkLike[]): ChunkGen {
60
+ for (const c of chunks) yield c;
61
+ }
62
+
63
+ interface HarnessOpts {
64
+ chunks: StreamChunkLike[];
65
+ /** 沙箱工具执行器(缺省 = 空实现,全部 isError) */
66
+ executor?: (input: ToolBatchInputLike) => Promise<ToolBatchResultLike>;
67
+ /** 是否接线实时帧端口(缺省接线并记录帧) */
68
+ wireFrames?: boolean;
69
+ /** 实时帧发射行为覆写(熔断用例) */
70
+ emit?: (event: string, payload: unknown) => void;
71
+ signal?: AbortSignal;
72
+ }
73
+
74
+ function makeHarness(opts: HarnessOpts) {
75
+ const sandboxDir = mkdtempSync(join(tmpdir(), 'tf-v031-'));
76
+ const session = createFakeSession();
77
+ const frames: Array<{ agent: unknown; frame: Record<string, unknown> }> = [];
78
+ const ports: DriverPorts = {
79
+ stream: () => scriptedStream(opts.chunks),
80
+ executeTools: opts.executor ?? (async (input) => ({
81
+ results: input.calls.map((call) => ({
82
+ callId: call.id,
83
+ result: { content: [{ type: 'text', text: `sandbox: ${call.name}` }], isError: false },
84
+ })),
85
+ additionalContexts: [],
86
+ concluded: false,
87
+ })),
88
+ ...(opts.wireFrames === false ? {} : {
89
+ emitHostEvent: opts.emit ?? ((event: string, payload: unknown) => {
90
+ frames.push({ agent: (payload as { agent: unknown }).agent, frame: (payload as { frame: Record<string, unknown> }).frame });
91
+ }),
92
+ }),
93
+ events: createSessionEventWriter(session),
94
+ };
95
+ const config: StreamDriverConfig = { provider: 'mock', model: 'mock-display' };
96
+ const driver = new SingleStreamDriver(ports, config);
97
+ driver.setIdentity('session-display-test', 'task');
98
+ const agent = { session, id: 'agent-1' };
99
+ driver.setAgent(agent);
100
+ driver.pushUserTask('测试任务');
101
+ return {
102
+ driver,
103
+ session,
104
+ frames,
105
+ sandboxDir,
106
+ cleanup: () => rmSync(sandboxDir, { recursive: true, force: true }),
107
+ };
108
+ }
109
+
110
+ function assistantMessages(session: ReturnType<typeof createFakeSession>) {
111
+ return session.events
112
+ .filter((e) => e.type === 'assistant/message')
113
+ .map((e) => ({ seq: e.seq, message: e.data['message'] as { content: Array<{ type: string; text?: string }> } }));
114
+ }
115
+
116
+ /** 真机形态的块序列:思考 + prose + DSML 计划 + 命令(accepts 挂计划项)+ 收尾。 */
117
+ function realisticChunks(): StreamChunkLike[] {
118
+ return [
119
+ { type: 'block-start', index: 0, blockType: 'reasoning' } as never,
120
+ { type: 'reasoning-delta', index: 0, text: '先读文件,' } as never,
121
+ { type: 'reasoning-delta', index: 0, text: '然后写结果。' } as never,
122
+ { type: 'block-end', index: 0, block: { type: 'reasoning', text: '先读文件,然后写结果。' } } as never,
123
+ { type: 'block-start', index: 1, blockType: 'text' } as never,
124
+ { type: 'text-delta', index: 1, text: '我先读取数据文件。\n' } as never,
125
+ { type: 'text-delta', index: 1, text: '<||DSML|| calls>\n' } as never,
126
+ { type: 'text-delta', index: 1, text: '<||DSML|| invoke name="tf-plan" id="p1">\n- [a1] 完成读取\n</tf-plan>\n' } as never,
127
+ { type: 'text-delta', index: 1, text: '<tf-read path="data/x.md" id="r1" accepts="a1"/>\n' } as never,
128
+ { type: 'text-delta', index: 1, text: '<tf-final id="f1" summary="已完成读取 data/x.md"/>' } as never,
129
+ { type: 'block-end', index: 1, block: { type: 'text', text: 'full' } } as never,
130
+ { type: 'finish', reason: { kind: 'stop' } } as never,
131
+ ];
132
+ }
133
+
134
+ // ---------------------------------------------------------------- 用例
135
+
136
+ test('R1. reasoning-delta 落成 reasoning 内容块(桌面端思考过程数据源)', async () => {
137
+ const h = makeHarness({ chunks: realisticChunks() });
138
+ try {
139
+ const reason = await h.driver.runTurn();
140
+ assert.equal(reason.kind, 'completed');
141
+ const msgs = assistantMessages(h.session);
142
+ const streamMsg = msgs.find((m) => m.message.content.some((b) => b.type === 'reasoning'));
143
+ assert.ok(streamMsg !== undefined, 'assistant/message 应携带 reasoning 块');
144
+ const reasoning = streamMsg.message.content.find((b) => b.type === 'reasoning');
145
+ assert.equal(reasoning?.text, '先读文件,然后写结果。', '同 index 的 delta 无缝拼接');
146
+ // 块序:reasoning 在 text 前(镜像内建 BlockAssembler 流序)
147
+ assert.equal(streamMsg.message.content[0]?.type, 'reasoning');
148
+ assert.equal(streamMsg.message.content[1]?.type, 'text');
149
+ } finally {
150
+ h.cleanup();
151
+ }
152
+ });
153
+
154
+ test('R2. 落盘正文纯 prose 化:协议标记与 DSML 噪声不进 assistant/message 文本', async () => {
155
+ const h = makeHarness({ chunks: realisticChunks() });
156
+ try {
157
+ await h.driver.runTurn();
158
+ const msgs = assistantMessages(h.session);
159
+ const streamMsg = msgs.find((m) => m.message.content.some((b) => b.type === 'text'));
160
+ const text = streamMsg?.message.content.filter((b) => b.type === 'text').map((b) => b.text).join('') ?? '';
161
+ assert.ok(text.includes('我先读取数据文件。'), 'prose 保留');
162
+ assert.ok(!text.includes('<tf-read'), 'tf-* 命令标记不进落盘文本');
163
+ assert.ok(!text.includes('DSML'), 'DSML 噪声不进落盘文本');
164
+ assert.ok(!text.includes('tf-plan'), 'DSML 包装内的命令名不进落盘文本');
165
+ // 命令事实仍在台账(驱动器记录)
166
+ const snap = h.driver.snapshot();
167
+ const cmdNames = snap.records.filter((r) => r.kind === 'command').map((r) => (r as { name?: string }).name);
168
+ assert.ok(cmdNames.includes('tf-read') && cmdNames.includes('tf-plan') && cmdNames.includes('tf-final'), '命令照常登记');
169
+ // DSML 包装行按 malformed 记账
170
+ const malformed = snap.records.filter((r) => r.kind === 'malformed').map((r) => (r as { reason?: string }).reason);
171
+ assert.ok(malformed.includes('dsml-wrapper'), 'dsml-wrapper 记账');
172
+ } finally {
173
+ h.cleanup();
174
+ }
175
+ });
176
+
177
+ test('R3. 实时帧契约:start → 逐 delta chunk → end(committed, seq=落盘事件)', async () => {
178
+ const h = makeHarness({ chunks: realisticChunks() });
179
+ try {
180
+ await h.driver.runTurn();
181
+ assert.ok(h.frames.length >= 2, '至少 start + end 两帧');
182
+ // payload 形状:agent 引用 + 帧
183
+ for (const f of h.frames) {
184
+ const agent = f.agent as { id?: string };
185
+ assert.equal(agent?.id, 'agent-1');
186
+ }
187
+ // revision 全会话逐帧 +1(宿主 accumulator 契约:revision !== last+1 即整帧流失效)
188
+ const revisions = h.frames.map((f) => f.frame['revision'] as number);
189
+ for (let i = 1; i < revisions.length; i++) assert.equal(revisions[i], revisions[i - 1]! + 1);
190
+ assert.equal(revisions[0], 1);
191
+ // 首 attempt 分组:start → 全 chunk → end(重入产生的后续 attempt 各自成组)
192
+ const endIdx = h.frames.findIndex((f) => f.frame['type'] === 'end');
193
+ const firstAttempt = h.frames.slice(0, endIdx + 1);
194
+ assert.equal(firstAttempt[0]!.frame['type'], 'start');
195
+ assert.ok(firstAttempt.slice(1, -1).every((f) => f.frame['type'] === 'chunk'), 'attempt 内 start..end 之间全为 chunk 帧');
196
+ // chunk 帧:只透传 reasoning-delta;index 逐 chunk +1
197
+ const chunkFrames = firstAttempt.filter((f) => f.frame['type'] === 'chunk');
198
+ chunkFrames.forEach((f, i) => assert.equal(f.frame['index'], i));
199
+ const chunks = chunkFrames.map((f) => f.frame['chunk'] as { type: string; text: string });
200
+ assert.ok(chunks.every((c) => c.type === 'reasoning-delta'), '正文不进实时帧(协议标记不闪现)');
201
+ assert.deepEqual(chunks.map((c) => c.text), ['先读文件,', '然后写结果。']);
202
+ // 首 attempt 收束:本流有工具广告(流中落盘 assistant/message)→ 广告前 abandoned 收束,
203
+ // 避免广告条目滞留客户端 pending(会触发下一步 events.restart())
204
+ const end = firstAttempt[firstAttempt.length - 1]!.frame;
205
+ assert.deepEqual(end['outcome'], { kind: 'abandoned' });
206
+ // attemptId 会话内稳定且逐流唯一
207
+ const attemptId = h.frames[0]!.frame['attemptId'];
208
+ assert.equal(typeof attemptId, 'string');
209
+ assert.ok((attemptId as string).startsWith('session-display-test:'));
210
+ } finally {
211
+ h.cleanup();
212
+ }
213
+ });
214
+
215
+ test('R4. 无 reasoning 的流:空 attempt 帧(start→end)不产生 thinking 内容', async () => {
216
+ const h = makeHarness({
217
+ chunks: [
218
+ { type: 'block-start', index: 0, blockType: 'text' } as never,
219
+ { type: 'text-delta', index: 0, text: '<tf-final id="f1" summary="直接完成"/>' } as never,
220
+ { type: 'finish', reason: { kind: 'stop' } } as never,
221
+ ],
222
+ });
223
+ try {
224
+ const reason = await h.driver.runTurn();
225
+ assert.equal(reason.kind, 'completed');
226
+ const types = h.frames.map((f) => f.frame['type']);
227
+ assert.deepEqual(types, ['start', 'end'], '零 chunk 空 attempt 帧');
228
+ // 无工具流 → attempt 存活到流末,end 帧与 durable 结算配对(committed + seq)
229
+ // (本流无 prose 无原生调用 → 结算是 assistant/attempt;finalAnswer 的 message 在其后)
230
+ const end = h.frames[h.frames.length - 1]!.frame;
231
+ const settled = h.session.events.find((e) => e.type === 'assistant/attempt' || e.type === 'assistant/message');
232
+ assert.ok(settled !== undefined);
233
+ assert.deepEqual(end['outcome'], { kind: 'committed', eventType: settled.type, seq: settled.seq });
234
+ const msgs = assistantMessages(h.session);
235
+ const last = msgs[msgs.length - 1]!;
236
+ assert.ok(!last.message.content.some((b) => b.type === 'reasoning'), '无 reasoning 块');
237
+ } finally {
238
+ h.cleanup();
239
+ }
240
+ });
241
+
242
+ test('R5. 实时帧发射异常 → 熔断(fail-open),任务不受影响', async () => {
243
+ let calls = 0;
244
+ const h = makeHarness({
245
+ chunks: realisticChunks(),
246
+ emit: () => {
247
+ calls += 1;
248
+ throw new Error('host bus exploded');
249
+ },
250
+ });
251
+ try {
252
+ const reason = await h.driver.runTurn();
253
+ assert.equal(reason.kind, 'completed', '熔断不影响任务收敛');
254
+ assert.equal(calls, 1, '首帧抛错后不再发射(start 帧即熔断)');
255
+ assert.ok(assistantMessages(h.session).length > 0, '落盘路径不受影响');
256
+ } finally {
257
+ h.cleanup();
258
+ }
259
+ });
260
+
261
+ test('R6. 无 emitHostEvent 端口(headless/离线):不发帧,其余行为不变', async () => {
262
+ const h = makeHarness({ chunks: realisticChunks(), wireFrames: false });
263
+ try {
264
+ const reason = await h.driver.runTurn();
265
+ assert.equal(reason.kind, 'completed');
266
+ assert.equal(h.frames.length, 0);
267
+ const msgs = assistantMessages(h.session);
268
+ assert.ok(msgs.some((m) => m.message.content.some((b) => b.type === 'reasoning')), '落盘 reasoning 不依赖帧端口');
269
+ } finally {
270
+ h.cleanup();
271
+ }
272
+ });
273
+
274
+ test('R7. 流中断(abort finish):部分思考与 prose 如实落盘(interrupted 消息)', async () => {
275
+ const h = makeHarness({
276
+ chunks: [
277
+ { type: 'block-start', index: 0, blockType: 'reasoning' } as never,
278
+ { type: 'reasoning-delta', index: 0, text: '部分思考…' } as never,
279
+ { type: 'block-start', index: 1, blockType: 'text' } as never,
280
+ { type: 'text-delta', index: 1, text: '部分正文。' } as never,
281
+ { type: 'finish', reason: { kind: 'aborted', message: 'cancelled' } } as never,
282
+ ],
283
+ });
284
+ try {
285
+ await h.driver.runTurn();
286
+ const interrupted = h.session.events
287
+ .filter((e) => e.type === 'assistant/message' && (e.data as { interrupted?: boolean }).interrupted === true);
288
+ assert.ok(interrupted.length >= 1, '中断消息落盘(重入流可能产生多条,取首条断言)');
289
+ const content = (interrupted[0]!.data as { message: { content: Array<{ type: string; text?: string }> } }).message.content;
290
+ const reasoning = content.find((b) => b.type === 'reasoning');
291
+ assert.equal(reasoning?.text, '部分思考…', '中断路径也携带部分思考');
292
+ const text = content.find((b) => b.type === 'text');
293
+ assert.equal(text?.text, '部分正文。', '中断正文纯 prose');
294
+ } finally {
295
+ h.cleanup();
296
+ }
297
+ });
298
+
299
+ test('R8. DSML invoke 改写后的命令照常执行(命令事实不因噪声修复而丢)', async () => {
300
+ const h = makeHarness({
301
+ chunks: [
302
+ { type: 'block-start', index: 0, blockType: 'text' } as never,
303
+ { type: 'text-delta', index: 0, text: '<||DSML|| invoke name="tf-read" path="a.txt" id="r1"/>' } as never,
304
+ { type: 'text-delta', index: 0, text: '<tf-final id="f1" summary="读取完成" depends_on="r1"/>' } as never,
305
+ { type: 'finish', reason: { kind: 'stop' } } as never,
306
+ ],
307
+ executor: async (input) => ({
308
+ results: input.calls.map((call) => ({
309
+ callId: call.id,
310
+ result: { content: [{ type: 'text', text: `read ok: ${call.name}` }], isError: false },
311
+ })),
312
+ additionalContexts: [],
313
+ concluded: false,
314
+ }),
315
+ });
316
+ try {
317
+ const reason = await h.driver.runTurn();
318
+ assert.equal(reason.kind, 'completed', '改写命令执行成功 → tf-final 依赖满足 → 收敛');
319
+ const cmdNames = h.driver.snapshot().records.filter((r) => r.kind === 'command').map((r) => (r as { name?: string }).name);
320
+ assert.ok(cmdNames.includes('tf-read'));
321
+ } finally {
322
+ h.cleanup();
323
+ }
324
+ });
325
+
326
+ // parser 冒烟:确保 DSML 判定与 kernel 测试一致(防回归的独立锚点)
327
+ test('R9. parser 冒烟:DSML 前缀判定与驱动器使用同一内核', () => {
328
+ const p = new TfStreamParser();
329
+ const events = p.feed('<||DSML|| invoke name="tf-bash" cmd="echo hi" id="b1"/>');
330
+ const cmds = events.filter((e) => e.type === 'command').map((e) => (e as { command: { name: string } }).command);
331
+ assert.equal(cmds.length, 1);
332
+ assert.equal(cmds[0].name, 'tf-bash');
333
+ });