api.test.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. /** BFF HTTP 接口 + 对话 + 核验的端到端测试(假工具服务 + 剧本模型,不联网)。 */
  2. import { test, before, after } from 'node:test';
  3. import assert from 'node:assert/strict';
  4. import { createApp } from '../src/app.js';
  5. import { ReplayLlmClient } from '../src/harness/llm.js';
  6. import { FakeToolsClient, asToolsClient, collectSse, listen, tempDir, testSettings } from './fakes.js';
  7. let server;
  8. let base;
  9. let fake;
  10. before(async () => {
  11. fake = new FakeToolsClient();
  12. const llm = new ReplayLlmClient([
  13. // 第 1 轮:先读表,再给出正确答案
  14. { toolCalls: [{ name: 'data_read', arguments: { object_id: 'obj_stat', table: '1.0-3.0_MLCC', limit: 5 } }] },
  15. { text: '2025 年 1 月 MLCC 进口额为 400316.13 美元。' },
  16. ]);
  17. const { server: httpServer } = createApp({
  18. settings: testSettings(tempDir()),
  19. tools: asToolsClient(fake),
  20. llm,
  21. serveStatic: false,
  22. });
  23. server = await listen(httpServer);
  24. base = server.url;
  25. });
  26. after(async () => {
  27. await server.close();
  28. });
  29. async function api(path, init) {
  30. const response = await fetch(`${base}${path}`, init);
  31. const text = await response.text();
  32. let payload = null;
  33. try {
  34. payload = text ? JSON.parse(text) : null;
  35. }
  36. catch {
  37. payload = text;
  38. }
  39. if (!response.ok) {
  40. throw Object.assign(new Error(`HTTP ${response.status}: ${text.slice(0, 300)}`), { status: response.status, payload });
  41. }
  42. return payload;
  43. }
  44. test('GET /api/health 报告工具服务状态', async () => {
  45. const health = await api('/api/health');
  46. assert.equal(health.ok, true);
  47. assert.equal(health.harness, 'embedded-dsh-compatible');
  48. assert.equal(health.tools.ok, true);
  49. });
  50. test('GET /api/meta 暴露 preset 与工具清单', async () => {
  51. const meta = await api('/api/meta');
  52. assert.equal(meta.preset.name, 'customs-analyst');
  53. assert.equal(meta.tools.length, 4);
  54. const names = meta.tools.map((tool) => tool.name);
  55. assert.deepEqual(names.sort(), ['calculator', 'customs_process', 'data_read', 'list_objects']);
  56. assert.equal(meta.verification.enabled, true);
  57. });
  58. test('工作区 CRUD', async () => {
  59. const created = await api('/api/workspaces', {
  60. method: 'POST',
  61. headers: { 'Content-Type': 'application/json' },
  62. body: JSON.stringify({ name: '接口测试区' }),
  63. });
  64. assert.equal(created.name, '接口测试区');
  65. const list = await api('/api/workspaces');
  66. assert.ok(list.items.some((item) => item.id === created.id));
  67. await api(`/api/workspaces/${created.id}`, { method: 'DELETE' });
  68. });
  69. test('multipart 上传(真实边界解析)', async () => {
  70. const form = new FormData();
  71. const csv = 'I_E_FLAG,HS_CODE,YEAR,WEEK,MONORSUM,COUNT,G_MODEL\nI,8532241000,2025,1,10.5,2,x\n';
  72. form.append('file', new Blob([csv], { type: 'text/csv' }), '测试 上传.csv');
  73. const object = await api('/api/workspaces/ws_test/files', { method: 'POST', body: form });
  74. assert.equal(object.kind, 'raw');
  75. assert.match(object.name, /测试 上传\.csv/);
  76. });
  77. test('原始字节上传(X-Filename)', async () => {
  78. const object = await api('/api/workspaces/ws_test/files', {
  79. method: 'POST',
  80. headers: { 'Content-Type': 'application/octet-stream', 'X-Filename': encodeURIComponent('raw-upload.csv') },
  81. body: 'a,b\n1,2\n',
  82. });
  83. assert.equal(object.name, 'raw-upload.csv');
  84. });
  85. test('对象预览与下载', async () => {
  86. const preview = await api('/api/objects/obj_stat/preview?table=1.0-3.0_MLCC&limit=1');
  87. assert.equal(preview.rows.length, 1);
  88. const response = await fetch(`${base}/api/objects/obj_stat/download?name=${encodeURIComponent('统计结果.xlsx')}`);
  89. assert.equal(response.status, 200);
  90. assert.match(response.headers.get('content-disposition') ?? '', /filename/);
  91. });
  92. test('处理任务接口', async () => {
  93. const run = await api('/api/process', {
  94. method: 'POST',
  95. headers: { 'Content-Type': 'application/json' },
  96. body: JSON.stringify({ workspace_id: 'ws_test', input_object_id: 'obj_raw' }),
  97. });
  98. assert.equal(run.status, 'succeeded');
  99. const fetched = await api(`/api/process/${run.id}`);
  100. assert.equal(fetched.id, run.id);
  101. const list = await api('/api/process');
  102. assert.ok(list.items.length >= 1);
  103. });
  104. test('会话创建 + 历史 + 删除', async () => {
  105. const session = await api('/api/sessions', {
  106. method: 'POST',
  107. headers: { 'Content-Type': 'application/json' },
  108. body: JSON.stringify({ workspace_id: 'ws_test' }),
  109. });
  110. assert.equal(session.workspace_id, 'ws_test');
  111. const messages = await api(`/api/sessions/${session.id}/messages`);
  112. assert.deepEqual(messages.items, []);
  113. const renamed = await api(`/api/sessions/${session.id}`, {
  114. method: 'PUT',
  115. headers: { 'Content-Type': 'application/json' },
  116. body: JSON.stringify({ title: '改名后的会话' }),
  117. });
  118. assert.equal(renamed.title, '改名后的会话');
  119. await api(`/api/sessions/${session.id}`, { method: 'DELETE' });
  120. });
  121. test('对话:工具调用 → 数字核验通过 → 交付', async () => {
  122. const session = await api('/api/sessions', {
  123. method: 'POST',
  124. headers: { 'Content-Type': 'application/json' },
  125. body: JSON.stringify({ workspace_id: 'ws_test' }),
  126. });
  127. const response = await fetch(`${base}/api/sessions/${session.id}/chat`, {
  128. method: 'POST',
  129. headers: { 'Content-Type': 'application/json' },
  130. body: JSON.stringify({ message: '2025 年 1 月 MLCC 进口额是多少?' }),
  131. });
  132. assert.equal(response.status, 200);
  133. assert.match(response.headers.get('content-type') ?? '', /text\/event-stream/);
  134. const events = await collectSse(response);
  135. const names = events.map((event) => event.event);
  136. assert.ok(names.includes('token'), '缺少 token 事件');
  137. assert.ok(names.includes('tool_call'), '缺少 tool_call 事件');
  138. assert.ok(names.includes('tool_result'), '缺少 tool_result 事件');
  139. assert.ok(names.includes('verification'), '缺少 verification 事件');
  140. const verification = events.find((event) => event.event === 'verification').data;
  141. assert.equal(verification.verdict, 'accept');
  142. assert.ok(verification.chips.length >= 1);
  143. assert.equal(verification.chips[0].call_id.startsWith('call_'), true);
  144. const final = events.find((event) => event.event === 'final').data;
  145. assert.equal(final.delivered, true);
  146. assert.match(final.text, /400316\.13/);
  147. const stored = await api(`/api/sessions/${session.id}/messages`);
  148. assert.equal(stored.items.length, 2); // user + assistant
  149. assert.equal(stored.items[1].role, 'assistant');
  150. assert.ok(stored.items[1].tool_calls.length >= 1);
  151. assert.equal(stored.items[1].verification.verdict, 'accept');
  152. const ledger = await api(`/api/sessions/${session.id}/ledger`);
  153. assert.ok(ledger.calls.length >= 1);
  154. });
  155. test('空消息与不存在的会话被拒绝', async () => {
  156. const session = await api('/api/sessions', {
  157. method: 'POST',
  158. headers: { 'Content-Type': 'application/json' },
  159. body: JSON.stringify({ workspace_id: 'ws_test' }),
  160. });
  161. await assert.rejects(() => api(`/api/sessions/${session.id}/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: ' ' }) }), /400/);
  162. await assert.rejects(() => api('/api/sessions/sess_not_exist/messages'), /404/);
  163. });
  164. test('静态资源未配置时返回 404', async () => {
  165. const response = await fetch(`${base}/`);
  166. assert.equal(response.status, 404);
  167. });
  168. test('未知接口返回结构化 404', async () => {
  169. const response = await fetch(`${base}/api/nope`);
  170. assert.equal(response.status, 404);
  171. const payload = await response.json();
  172. assert.equal(payload.error, 'NOT_FOUND');
  173. });
  174. test('按行取数(溯源抽屉)与嵌套对象路径', async () => {
  175. const row = await api('/api/objects/obj_stat/row?table=1.0-3.0_MLCC&row=1');
  176. assert.equal(row.row_index, 1);
  177. assert.equal(row.values['基础类目'], '多层瓷介电容器(MLCC)');
  178. assert.match(row.row_hash, /^sha256:/);
  179. // 契约里的嵌套写法应等价
  180. const nested = await api('/api/workspaces/ws_test/objects/obj_stat');
  181. assert.equal(nested.id, 'obj_stat');
  182. await assert.rejects(() => api('/api/workspaces/ws_other/objects/obj_stat'), /404/);
  183. const missing = await fetch(`${base}/api/objects/obj_stat/row?table=1.0-3.0_MLCC&row=9999`);
  184. assert.equal(missing.status, 404);
  185. });
  186. test('预览支持 offset 与行号(用于高亮跳转)', async () => {
  187. const preview = await api('/api/objects/obj_stat/preview?table=1.0-3.0_MLCC&limit=2&offset=1');
  188. assert.equal(preview.offset, 1);
  189. assert.deepEqual(preview.row_indexes, [1]);
  190. assert.equal(preview.total, 2);
  191. });
  192. test('处理进度 SSE 推送 progress 与 done', async () => {
  193. const run = await api('/api/process', {
  194. method: 'POST',
  195. headers: { 'Content-Type': 'application/json' },
  196. body: JSON.stringify({ workspace_id: 'ws_test', input_object_id: 'obj_raw' }),
  197. });
  198. const response = await fetch(`${base}/api/process/${run.id}/stream`);
  199. assert.equal(response.status, 200);
  200. assert.match(response.headers.get('content-type') ?? '', /text\/event-stream/);
  201. const events = await collectSse(response);
  202. const names = events.map((event) => event.event);
  203. assert.ok(names.includes('progress'), '缺少 progress 事件');
  204. assert.ok(names.includes('done'), '缺少 done 事件');
  205. const done = events.find((event) => event.event === 'done').data;
  206. assert.equal(done.status, 'succeeded');
  207. assert.equal(done.object_id, 'obj_stat');
  208. const missing = await fetch(`${base}/api/process/run_not_exist/stream`);
  209. assert.equal(missing.status, 404);
  210. });
  211. test('会话台账单次调用详情(calculator chip 用)', async () => {
  212. // 这个用例需要一次"干净"的对话(剧本客户端是有状态的),所以自己起一个服务实例
  213. const llm = new ReplayLlmClient([
  214. { toolCalls: [{ name: 'data_read', arguments: { object_id: 'obj_stat', table: '1.0-3.0_MLCC' } }] },
  215. { text: '2025 年 1 月 MLCC 进口额为 400316.13 美元。' },
  216. ]);
  217. const fresh = createApp({ settings: testSettings(tempDir()), tools: asToolsClient(fake), llm, serveStatic: false });
  218. const running = await listen(fresh.server);
  219. try {
  220. const create = await fetch(`${running.url}/api/sessions`, {
  221. method: 'POST',
  222. headers: { 'Content-Type': 'application/json' },
  223. body: JSON.stringify({ workspace_id: 'ws_test' }),
  224. });
  225. const session = (await create.json());
  226. const chat = await fetch(`${running.url}/api/sessions/${session.id}/chat`, {
  227. method: 'POST',
  228. headers: { 'Content-Type': 'application/json' },
  229. body: JSON.stringify({ message: '2025 年 1 月 MLCC 进口额是多少?' }),
  230. });
  231. const events = await collectSse(chat);
  232. const final = events.find((event) => event.event === 'final').data;
  233. assert.equal(final.verification, 'accept');
  234. const ledger = (await (await fetch(`${running.url}/api/sessions/${session.id}/ledger`)).json());
  235. assert.ok(ledger.calls.length >= 1, '应该有台账记录');
  236. const call = ledger.calls[0];
  237. const detail = (await (await fetch(`${running.url}/api/sessions/${session.id}/ledger/${call.call_id}`)).json());
  238. assert.equal(detail.call.call_id, call.call_id);
  239. assert.equal(detail.call.tool, 'data_read');
  240. assert.ok(Array.isArray(detail.values) && detail.values.length > 0);
  241. assert.equal(detail.call.args.object_id, 'obj_stat');
  242. const wrongSession = await fetch(`${running.url}/api/sessions/sess_other/ledger/${call.call_id}`);
  243. assert.equal(wrongSession.status, 404);
  244. }
  245. finally {
  246. await running.close();
  247. }
  248. });
  249. //# sourceMappingURL=api.test.js.map