conversation-session-toolsearch-feedback.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import { readFile } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import { DatabaseSync } from "node:sqlite";
  4. import { createToolSearchCliFixture } from "#e2e/helpers/toolsearch-cli-process";
  5. import { toolSearchBlocks } from "#e2e/helpers/toolsearch-provider";
  6. import {
  7. contentText,
  8. definitionsFor,
  9. feedbackCase,
  10. loadedCount,
  11. replyStage,
  12. resultFor,
  13. runFeedback,
  14. saveSearchEvidence,
  15. } from "#e2e/helpers/toolsearch-feedback";
  16. describe("ToolSearch 结果、纠错、提醒和 MCP 短名(真实 CLI / HTTP)", () => {
  17. for (const mode of ["native", "local"] as const) {
  18. it(`TS12-RESULT: 并行结果、失败与失效引用 ${mode}`, async function () {
  19. this.timeout(120_000);
  20. const fixture = await createToolSearchCliFixture(feedbackCase, { modelIo: true });
  21. try {
  22. fixture.setResponse((body, response) =>
  23. replyStage(
  24. fixture,
  25. body,
  26. response,
  27. toolSearchBlocks(body).some((block) => block.tool_use_id === "batch_one")
  28. ? "done"
  29. : "batch",
  30. ),
  31. );
  32. const sessionId = await runFeedback(fixture, mode, "E2E_TOOLSEARCH_FEEDBACK_BATCH");
  33. expect(fixture.requests).toHaveLength(2);
  34. expect(fixture.requests.every(({ body }) => body.stream === true)).toBe(true);
  35. const body = fixture.requests[1]!.body;
  36. expect(definitionsFor(body, "batch_one")).toEqual(["TaskOutput", "TodoRead"]);
  37. expect(definitionsFor(body, "batch_two")).toEqual(["TodoRead"]);
  38. expect(contentText(resultFor(body, "batch_empty").content)).toContain("No matching");
  39. expect(resultFor(body, "batch_bad").is_error).toBe(true);
  40. expect(loadedCount(body)).toBe(mode === "native" ? 2 : 0);
  41. const blocks = toolSearchBlocks(body);
  42. const resultIndices = blocks.flatMap((block, i) =>
  43. block.type === "tool_result" ? [i] : [],
  44. );
  45. expect(resultIndices).toHaveLength(4);
  46. expect(resultIndices).toEqual(Array.from({ length: 4 }, (_, i) => resultIndices[0]! + i));
  47. const hintIndex = blocks.findIndex(
  48. (block) => block.type === "text" && block.text?.includes("Tool loaded."),
  49. );
  50. if (mode === "native") expect(hintIndex).toBeGreaterThan(resultIndices.at(-1)!);
  51. else expect(hintIndex).toBe(-1);
  52. for (const id of ["batch_one", "batch_two", "batch_empty", "batch_bad"])
  53. expect(JSON.stringify(resultFor(body, id).content)).not.toContain("Tool loaded.");
  54. fixture.setResponse((request, response) => replyStage(fixture, request, response, "done"));
  55. const before = fixture.requests.length;
  56. await runFeedback(fixture, mode, "E2E_TOOLSEARCH_FEEDBACK_UNAVAILABLE", [
  57. "--resume",
  58. sessionId,
  59. "--disallowedTools=TaskOutput,TodoRead",
  60. ]);
  61. const cold = fixture.requests[before]!.body;
  62. // Native 保留已交付定义与引用;禁用改变执行资格,不改写已经发出的历史。
  63. expect(loadedCount(cold)).toBe(mode === "native" ? 2 : 0);
  64. expect(
  65. cold.tools?.some(
  66. (tool) => tool.name === (mode === "local" ? "LocalToolSearch" : "ToolSearch"),
  67. ),
  68. ).toBe(true);
  69. for (const id of ["batch_one", "batch_two"]) {
  70. if (mode === "native") {
  71. expect(resultFor(cold, id).content).toEqual(resultFor(body, id).content);
  72. expect(definitionsFor(cold, id)).toEqual(definitionsFor(body, id));
  73. } else {
  74. expect(contentText(resultFor(cold, id).content)).toContain("tools no longer available");
  75. expect(definitionsFor(cold, id)).toEqual([]);
  76. }
  77. }
  78. const db = new DatabaseSync(join(fixture.root, "session.sqlite"), { readOnly: true });
  79. try {
  80. const rows = db
  81. .prepare(
  82. "select data from part where json_extract(data, '$.callID') in ('batch_one', 'batch_two')",
  83. )
  84. .all();
  85. expect(rows).toHaveLength(2);
  86. expect(JSON.stringify(rows)).toContain("tool_reference");
  87. expect(JSON.stringify(rows)).not.toContain("Tool loaded.");
  88. } finally {
  89. db.close();
  90. }
  91. } finally {
  92. try {
  93. await saveSearchEvidence(`result-${mode}`, fixture);
  94. } finally {
  95. await fixture.close();
  96. }
  97. }
  98. });
  99. it(`TS12-VALIDATION: 未发现工具的完整纠错和执行 ${mode}`, async function () {
  100. this.timeout(120_000);
  101. const fixture = await createToolSearchCliFixture(feedbackCase, { modelIo: true });
  102. try {
  103. fixture.setResponse((body, response) => replyStage(fixture, body, response, "done"));
  104. const seed = await fixture.start(["-p", "E2E_TOOLSEARCH_FEEDBACK_SCHEMA"]).done;
  105. expect(seed.code).toBe(0);
  106. const schema = fixture.requests[0]!.body.tools!.find(
  107. (tool) => tool.name === "TodoRead",
  108. )!.input_schema;
  109. const before = fixture.requests.length;
  110. fixture.setResponse((body, response) => {
  111. const ids = new Set(
  112. toolSearchBlocks(body)
  113. .filter((block) => block.type === "tool_result")
  114. .map((block) => block.tool_use_id),
  115. );
  116. const stage = ids.has("good")
  117. ? "done"
  118. : ids.has("loaded")
  119. ? `${mode}-good`
  120. : ids.has("discover")
  121. ? `${mode}-loaded`
  122. : ids.has("unloaded")
  123. ? "discover"
  124. : `${mode}-unloaded`;
  125. replyStage(fixture, body, response, stage);
  126. });
  127. await runFeedback(fixture, mode, "E2E_TOOLSEARCH_FEEDBACK_VALIDATE");
  128. const requests = fixture.requests.slice(before);
  129. expect(requests).toHaveLength(5);
  130. expect(requests.every(({ body }) => body.stream === true)).toBe(true);
  131. expect(requests[0]!.body.tools?.some((tool) => tool.name === "TodoRead")).toBe(false);
  132. const unloaded = resultFor(requests[1]!.body, "unloaded");
  133. expect(unloaded.is_error).toBe(true);
  134. const error = contentText(unloaded.content);
  135. expect(error).toContain(
  136. `Load the tool first: call ${mode === "local" ? "LocalToolSearch" : "ToolSearch"} with query "select:TodoRead"`,
  137. );
  138. // 纠错段落在 `</tool_use_error>` 之内:结尾是包装标签,schema 之后不再有包装外的文字。
  139. expect(error.endsWith("</tool_use_error>")).toBe(true);
  140. expect(
  141. JSON.parse(
  142. error
  143. .split("For reference, this tool's input schema is: ")[1]!
  144. .split("\n")[0]!
  145. .replace(/<\/tool_use_error>$/, ""),
  146. ),
  147. ).toEqual(schema);
  148. if (mode === "local")
  149. expect(error).toContain('Call DeferredToolCall with {name: "TodoRead", input: {...}}.');
  150. else expect(error).not.toContain("DeferredToolCall");
  151. expect(loadedCount(requests[1]!.body)).toBe(0);
  152. const known = contentText(resultFor(requests[3]!.body, "loaded").content);
  153. expect(known).toContain("InputValidationError");
  154. expect(known).not.toContain("select:TodoRead");
  155. expect(known).not.toContain("For reference, this tool's input schema is:");
  156. expect(resultFor(requests[4]!.body, "good").is_error).not.toBe(true);
  157. const db = new DatabaseSync(join(fixture.root, "session.sqlite"), { readOnly: true });
  158. try {
  159. const rows = db
  160. .prepare("select data from part where json_extract(data, '$.callID') = 'good'")
  161. .all() as { data: string }[];
  162. expect(rows).toHaveLength(1);
  163. const part = JSON.parse(rows[0]!.data);
  164. expect(part).toMatchObject({
  165. tool: "TodoRead",
  166. state: { status: "completed", output: '{"todos":[]}' },
  167. });
  168. // toMatchObject 里的 {} 能匹配任何对象;严格比较才能发现 Local 包装字段混入 input。
  169. expect(part.state.input).toEqual({});
  170. } finally {
  171. db.close();
  172. }
  173. } finally {
  174. try {
  175. await saveSearchEvidence(`validation-${mode}`, fixture);
  176. } finally {
  177. await fixture.close();
  178. }
  179. }
  180. });
  181. for (const mcs of [false, true]) {
  182. it(`TS12-REMINDER: 公告 wire 和旧历史冷恢复 ${mode}/MCS=${mcs}`, async function () {
  183. this.timeout(120_000);
  184. const fixture = await createToolSearchCliFixture(feedbackCase, { modelIo: true });
  185. try {
  186. await fixture.select("anthropic-messages", { supportsMidConversationSystem: mcs });
  187. fixture.setResponse((body, response) => replyStage(fixture, body, response, "done"));
  188. const sessionId = await runFeedback(
  189. fixture,
  190. mode,
  191. "E2E_TOOLSEARCH_FEEDBACK_ANNOUNCEMENT",
  192. );
  193. // 完成首轮后重启 CLI,验证旧公告恢复时仍沿用对应的 MCS 投影。
  194. const db = new DatabaseSync(join(fixture.root, "session.sqlite"));
  195. let announcement = "";
  196. try {
  197. const rows = db
  198. .prepare(
  199. "select id, data from part where json_extract(data, '$.metadata.runtimeMessage.toolSearchAnnouncement') is not null",
  200. )
  201. .all() as { id: string; data: string }[];
  202. expect(rows).toHaveLength(1);
  203. const part = JSON.parse(rows[0]!.data);
  204. announcement = part.text;
  205. expect(part.metadata.runtimeMessage.source).toBe("tool_search_announcement");
  206. // 旧记录 fixture 只改变存储表示,不改生产恢复入口。
  207. part.text = `<system-reminder>\n${part.text}\n</system-reminder>`;
  208. part.metadata.runtimeMessage.source = "legacy_synthetic";
  209. db.prepare("update part set data = ? where id = ?").run(
  210. JSON.stringify(part),
  211. rows[0]!.id,
  212. );
  213. } finally {
  214. db.close();
  215. }
  216. await runFeedback(fixture, mode, "E2E_TOOLSEARCH_FEEDBACK_COLD", ["--resume", sessionId]);
  217. const before = fixture.requests[0]!.body;
  218. const after = fixture.requests[1]!.body;
  219. for (const body of [before, after]) {
  220. const serialized = JSON.stringify(body);
  221. expect(serialized).not.toContain("toolSearchAnnouncement");
  222. expect(serialized).not.toContain("tool_search_announcement");
  223. const messages = body.messages.filter((message) =>
  224. contentText(message.content).includes(announcement),
  225. );
  226. expect(messages).toHaveLength(1);
  227. expect(messages[0]!.role).toBe(mcs ? "system" : "user");
  228. const announcementBlocks = messages
  229. .flatMap(({ content }) =>
  230. typeof content === "string"
  231. ? [content]
  232. : content
  233. .filter((block) => block.type === "text")
  234. .map((block) => block.text ?? ""),
  235. )
  236. .filter((text) => text.includes(announcement));
  237. expect(announcementBlocks).toHaveLength(1);
  238. if (mcs) {
  239. // MCS 下同一段 user run 的 system 文本合成一条、以空行分隔(环境、模型、日期公告可能并入);
  240. // 公告必须是其中完整的一段。
  241. expect(`\n\n${announcementBlocks[0]}\n\n`).toContain(`\n\n${announcement}\n\n`);
  242. } else {
  243. expect(announcementBlocks[0]).toBe(
  244. `<system-reminder>\n${announcement}\n</system-reminder>`,
  245. );
  246. }
  247. }
  248. const readDb = new DatabaseSync(join(fixture.root, "session.sqlite"), { readOnly: true });
  249. try {
  250. expect(
  251. readDb
  252. .prepare(
  253. "select count(*) as count from part where json_extract(data, '$.metadata.runtimeMessage.toolSearchAnnouncement') is not null",
  254. )
  255. .get(),
  256. ).toMatchObject({ count: 1 });
  257. } finally {
  258. readDb.close();
  259. }
  260. } finally {
  261. try {
  262. await saveSearchEvidence(`reminder-${mode}-${mcs}`, fixture);
  263. } finally {
  264. await fixture.close();
  265. }
  266. }
  267. });
  268. }
  269. it(`TS12-MCP: 原始短名、规范化、冲突和作用域 ${mode}`, async function () {
  270. this.timeout(120_000);
  271. const fixture = await createToolSearchCliFixture(feedbackCase, { modelIo: true });
  272. try {
  273. const callLog = join(fixture.root, "mcp-calls.ndjson");
  274. const server = {
  275. type: "stdio",
  276. command: process.execPath,
  277. args: [resolve("test/e2e/fixtures/mcp/toolsearch-server.mjs")],
  278. env: { E2E_TOOLSEARCH_SHORT_NAMES: "1", E2E_TOOLSEARCH_MCP_LOG: callLog },
  279. };
  280. await fixture.configure({
  281. features: { memory: false, skill: false, subagent: false, mcp: true },
  282. mcp: { servers: { one: server, two: server } },
  283. });
  284. fixture.setResponse((body, response) =>
  285. replyStage(
  286. fixture,
  287. body,
  288. response,
  289. toolSearchBlocks(body).some((block) => block.tool_use_id === "raw") ? "done" : "mcp",
  290. ),
  291. );
  292. await runFeedback(fixture, mode, "E2E_TOOLSEARCH_FEEDBACK_MCP", [
  293. "--disallowedTools=mcp__two__blocked",
  294. ]);
  295. expect(fixture.requests).toHaveLength(2);
  296. const body = fixture.requests[1]!.body;
  297. for (const id of ["raw", "normalized"])
  298. expect(definitionsFor(body, id)).toEqual(["mcp__one__look_up", "mcp__two__look_up"]);
  299. expect(definitionsFor(body, "canonical")).toEqual(["TodoRead"]);
  300. expect(definitionsFor(body, "alias")).toEqual(["TaskStop"]);
  301. expect(definitionsFor(body, "scoped")).toEqual(["mcp__one__blocked"]);
  302. expect(loadedCount(body)).toBe(mode === "native" ? 5 : 0);
  303. await expect(readFile(callLog, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
  304. } finally {
  305. try {
  306. await saveSearchEvidence(`mcp-${mode}`, fixture);
  307. } finally {
  308. await fixture.close();
  309. }
  310. }
  311. });
  312. }
  313. });