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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import { readFile } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import { DatabaseSync } from "node:sqlite";
  4. import { createToolSearchCliFixture } from "../helpers/toolsearch-cli-process.js";
  5. import { toolSearchBlocks } from "../helpers/toolsearch-provider.js";
  6. import {
  7. contentText,
  8. definitionsFor,
  9. feedbackCase,
  10. loadedCount,
  11. replyStage,
  12. resultFor,
  13. runFeedback,
  14. saveSearchEvidence,
  15. } from "../helpers/toolsearch-feedback.js";
  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(["WebFetch", "TodoWrite"]);
  37. expect(definitionsFor(body, "batch_two")).toEqual(["TodoWrite"]);
  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=WebFetch,TodoWrite",
  60. ]);
  61. const cold = fixture.requests[before]!.body;
  62. expect(loadedCount(cold)).toBe(0);
  63. expect(cold.tools?.some((tool) => tool.name === "ToolSearch")).toBe(true);
  64. for (const id of ["batch_one", "batch_two"]) {
  65. expect(contentText(resultFor(cold, id).content)).toContain("tools no longer available");
  66. expect(definitionsFor(cold, id)).toEqual([]);
  67. }
  68. const db = new DatabaseSync(join(fixture.root, "session.sqlite"), { readOnly: true });
  69. try {
  70. const rows = db
  71. .prepare(
  72. "select data from part where json_extract(data, '$.callID') in ('batch_one', 'batch_two')",
  73. )
  74. .all();
  75. expect(rows).toHaveLength(2);
  76. expect(JSON.stringify(rows)).toContain("tool_reference");
  77. expect(JSON.stringify(rows)).not.toContain("Tool loaded.");
  78. } finally {
  79. db.close();
  80. }
  81. } finally {
  82. try {
  83. await saveSearchEvidence(`result-${mode}`, fixture);
  84. } finally {
  85. await fixture.close();
  86. }
  87. }
  88. });
  89. it(`TS12-VALIDATION: 未发现工具的完整纠错和执行 ${mode}`, async function () {
  90. this.timeout(120_000);
  91. const fixture = await createToolSearchCliFixture(feedbackCase, { modelIo: true });
  92. try {
  93. fixture.setResponse((body, response) => replyStage(fixture, body, response, "done"));
  94. const seed = await fixture.start(["-p", "E2E_TOOLSEARCH_FEEDBACK_SCHEMA"]).done;
  95. expect(seed.code).toBe(0);
  96. const schema = fixture.requests[0]!.body.tools!.find(
  97. (tool) => tool.name === "TodoWrite",
  98. )!.input_schema;
  99. const before = fixture.requests.length;
  100. fixture.setResponse((body, response) => {
  101. const ids = new Set(
  102. toolSearchBlocks(body)
  103. .filter((block) => block.type === "tool_result")
  104. .map((block) => block.tool_use_id),
  105. );
  106. const stage = ids.has("good")
  107. ? "done"
  108. : ids.has("loaded")
  109. ? `${mode}-good`
  110. : ids.has("discover")
  111. ? `${mode}-loaded`
  112. : ids.has("unloaded")
  113. ? "discover"
  114. : `${mode}-unloaded`;
  115. replyStage(fixture, body, response, stage);
  116. });
  117. await runFeedback(fixture, mode, "E2E_TOOLSEARCH_FEEDBACK_VALIDATE");
  118. const requests = fixture.requests.slice(before);
  119. expect(requests).toHaveLength(5);
  120. expect(requests.every(({ body }) => body.stream === true)).toBe(true);
  121. expect(requests[0]!.body.tools?.some((tool) => tool.name === "TodoWrite")).toBe(false);
  122. const unloaded = resultFor(requests[1]!.body, "unloaded");
  123. expect(unloaded.is_error).toBe(true);
  124. const error = contentText(unloaded.content);
  125. expect(error).toContain(
  126. 'Load the tool first: call ToolSearch with query "select:TodoWrite"',
  127. );
  128. expect(
  129. JSON.parse(
  130. error.split("For reference, this tool's input schema is: ")[1]!.split("\n")[0]!,
  131. ),
  132. ).toEqual(schema);
  133. if (mode === "local")
  134. expect(error).toContain('Call DeferredToolCall with {name: "TodoWrite", input: {...}}.');
  135. else expect(error).not.toContain("DeferredToolCall");
  136. expect(loadedCount(requests[1]!.body)).toBe(0);
  137. const known = contentText(resultFor(requests[3]!.body, "loaded").content);
  138. expect(known).toContain("InputValidationError");
  139. expect(known).not.toContain("select:TodoWrite");
  140. expect(known).not.toContain("For reference, this tool's input schema is:");
  141. expect(resultFor(requests[4]!.body, "good").is_error).not.toBe(true);
  142. const db = new DatabaseSync(join(fixture.root, "session.sqlite"), { readOnly: true });
  143. try {
  144. const rows = db
  145. .prepare("select data from part where json_extract(data, '$.callID') = 'good'")
  146. .all() as { data: string }[];
  147. expect(rows).toHaveLength(1);
  148. expect(JSON.parse(rows[0]!.data)).toMatchObject({
  149. tool: "TodoWrite",
  150. state: { status: "completed", input: { todos: [{ status: "completed" }] } },
  151. });
  152. } finally {
  153. db.close();
  154. }
  155. } finally {
  156. try {
  157. await saveSearchEvidence(`validation-${mode}`, fixture);
  158. } finally {
  159. await fixture.close();
  160. }
  161. }
  162. });
  163. for (const mcs of [false, true]) {
  164. it(`TS12-REMINDER: 公告 wire 和旧历史冷恢复 ${mode}/MCS=${mcs}`, async function () {
  165. this.timeout(120_000);
  166. const fixture = await createToolSearchCliFixture(feedbackCase, { modelIo: true });
  167. try {
  168. await fixture.select("anthropic-messages", { supportsMidConversationSystem: mcs });
  169. fixture.setResponse((body, response) => replyStage(fixture, body, response, "done"));
  170. const sessionId = await runFeedback(
  171. fixture,
  172. mode,
  173. "E2E_TOOLSEARCH_FEEDBACK_ANNOUNCEMENT",
  174. );
  175. // 完成首轮后重启 CLI,验证旧公告恢复时仍沿用对应的 MCS 投影。
  176. const db = new DatabaseSync(join(fixture.root, "session.sqlite"));
  177. let announcement = "";
  178. try {
  179. const rows = db
  180. .prepare(
  181. "select id, data from part where json_extract(data, '$.metadata.runtimeMessage.toolSearchAnnouncement') is not null",
  182. )
  183. .all() as { id: string; data: string }[];
  184. expect(rows).toHaveLength(1);
  185. const part = JSON.parse(rows[0]!.data);
  186. announcement = part.text;
  187. expect(part.metadata.runtimeMessage.source).toBe("tool_search_announcement");
  188. // 旧记录 fixture 只改变存储表示,不改生产恢复入口。
  189. part.text = `<system-reminder>\n${part.text}\n</system-reminder>`;
  190. part.metadata.runtimeMessage.source = "legacy_synthetic";
  191. db.prepare("update part set data = ? where id = ?").run(
  192. JSON.stringify(part),
  193. rows[0]!.id,
  194. );
  195. } finally {
  196. db.close();
  197. }
  198. await runFeedback(fixture, mode, "E2E_TOOLSEARCH_FEEDBACK_COLD", ["--resume", sessionId]);
  199. const before = fixture.requests[0]!.body;
  200. const after = fixture.requests[1]!.body;
  201. for (const body of [before, after]) {
  202. const serialized = JSON.stringify(body);
  203. expect(serialized).not.toContain("toolSearchAnnouncement");
  204. expect(serialized).not.toContain("tool_search_announcement");
  205. const messages = body.messages.filter((message) =>
  206. contentText(message.content).includes(announcement),
  207. );
  208. expect(messages).toHaveLength(1);
  209. expect(messages[0]!.role).toBe(mcs ? "system" : "user");
  210. const announcementBlocks = messages
  211. .flatMap(({ content }) =>
  212. typeof content === "string"
  213. ? [content]
  214. : content
  215. .filter((block) => block.type === "text")
  216. .map((block) => block.text ?? ""),
  217. )
  218. .filter((text) => text.includes(announcement));
  219. expect(announcementBlocks).toEqual([
  220. mcs ? announcement : `<system-reminder>\n${announcement}\n</system-reminder>`,
  221. ]);
  222. }
  223. const readDb = new DatabaseSync(join(fixture.root, "session.sqlite"), { readOnly: true });
  224. try {
  225. expect(
  226. readDb
  227. .prepare(
  228. "select count(*) as count from part where json_extract(data, '$.metadata.runtimeMessage.toolSearchAnnouncement') is not null",
  229. )
  230. .get(),
  231. ).toMatchObject({ count: 1 });
  232. } finally {
  233. readDb.close();
  234. }
  235. } finally {
  236. try {
  237. await saveSearchEvidence(`reminder-${mode}-${mcs}`, fixture);
  238. } finally {
  239. await fixture.close();
  240. }
  241. }
  242. });
  243. }
  244. it(`TS12-MCP: 原始短名、规范化、冲突和作用域 ${mode}`, async function () {
  245. this.timeout(120_000);
  246. const fixture = await createToolSearchCliFixture(feedbackCase, { modelIo: true });
  247. try {
  248. const callLog = join(fixture.root, "mcp-calls.ndjson");
  249. const server = {
  250. type: "stdio",
  251. command: process.execPath,
  252. args: [resolve("test/e2e/fixtures/mcp/toolsearch-server.mjs")],
  253. env: { E2E_TOOLSEARCH_SHORT_NAMES: "1", E2E_TOOLSEARCH_MCP_LOG: callLog },
  254. };
  255. await fixture.configure({
  256. features: { memory: false, skill: false, subagent: false, mcp: true },
  257. mcp: { servers: { one: server, two: server } },
  258. });
  259. fixture.setResponse((body, response) =>
  260. replyStage(
  261. fixture,
  262. body,
  263. response,
  264. toolSearchBlocks(body).some((block) => block.tool_use_id === "raw") ? "done" : "mcp",
  265. ),
  266. );
  267. await runFeedback(fixture, mode, "E2E_TOOLSEARCH_FEEDBACK_MCP", [
  268. "--disallowedTools=mcp__two__blocked",
  269. ]);
  270. expect(fixture.requests).toHaveLength(2);
  271. const body = fixture.requests[1]!.body;
  272. for (const id of ["raw", "normalized"])
  273. expect(definitionsFor(body, id)).toEqual(["mcp__one__look_up", "mcp__two__look_up"]);
  274. expect(definitionsFor(body, "canonical")).toEqual(["TodoWrite"]);
  275. expect(definitionsFor(body, "alias")).toEqual(["TaskStop"]);
  276. expect(definitionsFor(body, "scoped")).toEqual(["mcp__one__blocked"]);
  277. expect(loadedCount(body)).toBe(mode === "native" ? 5 : 0);
  278. await expect(readFile(callLog, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
  279. } finally {
  280. try {
  281. await saveSearchEvidence(`mcp-${mode}`, fixture);
  282. } finally {
  283. await fixture.close();
  284. }
  285. }
  286. });
  287. }
  288. });