conversation-session-toolsearch-local.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { DatabaseSync } from "node:sqlite";
  4. import { startToolSearchTerminal } from "#e2e/helpers/toolsearch-terminal";
  5. import { createToolSearchCliFixture } from "#e2e/helpers/toolsearch-cli-process";
  6. import { toolSearchBlocks, type ToolSearchRequest } from "#e2e/helpers/toolsearch-provider";
  7. describe("Local ToolSearch CLI 请求与恢复", () => {
  8. it("TS10-TUI: Local 真实终端搜索和包装调用", async function () {
  9. this.timeout(120_000);
  10. const fixture = await createToolSearchCliFixture("conversation-session-toolsearch-local");
  11. let terminal: ReturnType<typeof startToolSearchTerminal> | undefined;
  12. try {
  13. await mkdir(join(fixture.root, ".zcode", "v2"), { recursive: true });
  14. await writeFile(
  15. join(fixture.root, ".zcode", "v2", "credentials.json"),
  16. JSON.stringify({
  17. "account-provider:account:zai-individual-coding-plan:identity": "toolsearch-e2e",
  18. "account-provider:coding-plan:account:zai-individual-coding-plan:account:toolsearch-e2e:api-key":
  19. "test-only",
  20. }),
  21. );
  22. fixture.setResponse((body, response) => {
  23. const stage = hasResult(body, "local_good")
  24. ? "done"
  25. : hasResult(body, "local_bad")
  26. ? "good"
  27. : hasResult(body, "local_search")
  28. ? "bad"
  29. : "search";
  30. fixture.reply(body, response, `anthropic-${stage}-${body.stream ? "stream" : "json"}`);
  31. });
  32. terminal = startToolSearchTerminal(fixture, ["--toolsearch-mode", "local"]);
  33. await browser.waitUntil(async () => terminal!.ready(), { timeout: 30_000 });
  34. const submit = async (value: string, expected: string) => {
  35. const before = terminal!.frameCount();
  36. terminal!.write(value);
  37. await browser.waitUntil(async () => terminal!.frameCount() > before, { timeout: 10_000 });
  38. terminal!.write("\r");
  39. await browser.waitUntil(async () => terminal!.output().includes(expected), {
  40. timeout: 30_000,
  41. });
  42. };
  43. await submit(
  44. "/model toolsearch-process/test-toolsearch",
  45. "Model switched to toolsearch-process/test-toolsearch",
  46. );
  47. await submit("/effort disabled", "Reasoning effort switched to disabled");
  48. await submit("E2E_TOOLSEARCH_LOCAL 验证清单。", "E2E_TOOLSEARCH_LOCAL_DONE");
  49. const requests = fixture.requests.filter(({ body }) => body.tools?.length);
  50. expect(requests).toHaveLength(4);
  51. expectSuccessfulTodoResult(requests[3]!.body);
  52. expect(toolNames(requests[0]!.body)).toContain("DeferredToolCall");
  53. expectLocalSearchDescription(requests[0]!.body);
  54. for (const request of requests) expect(request.body.tools).toEqual(requests[0]!.body.tools);
  55. expect(JSON.stringify(requests[1]!.body.messages)).toContain("<functions>");
  56. expect(hasResult(requests[3]!.body, "local_good")).toBe(true);
  57. const beforeExit = terminal.frameCount();
  58. terminal.write("\x03");
  59. await browser.waitUntil(async () => terminal!.frameCount() > beforeExit, { timeout: 10_000 });
  60. terminal.write("\x03");
  61. expect(await terminal.done).toBe(0);
  62. } finally {
  63. await terminal?.close();
  64. await fixture.close();
  65. }
  66. });
  67. for (const api of ["anthropic-messages", "openai-chat-completions"] as const) {
  68. for (const mode of ["local", "auto"] as const) {
  69. it(`TS10-LOCAL: ${api}/${mode} 搜索、包装纠错、冷恢复与模式切换`, async function () {
  70. this.timeout(180_000);
  71. const fixture = await createToolSearchCliFixture("conversation-session-toolsearch-local");
  72. try {
  73. await fixture.select(api);
  74. fixture.setResponse((body, response) => {
  75. const text = JSON.stringify(body.messages);
  76. const stage = text.includes("E2E_TOOLSEARCH_LOCAL_COLD")
  77. ? "done"
  78. : hasResult(body, "local_good")
  79. ? "done"
  80. : hasResult(body, "local_bad")
  81. ? "good"
  82. : hasResult(body, "local_search")
  83. ? "bad"
  84. : "search";
  85. fixture.reply(
  86. body,
  87. response,
  88. `${api === "anthropic-messages" ? "anthropic" : "openai"}-${stage}-${body.stream ? "stream" : "json"}`,
  89. );
  90. });
  91. const result = await fixture.start([
  92. "--toolsearch-mode",
  93. mode,
  94. "-p",
  95. "E2E_TOOLSEARCH_LOCAL 搜索 TodoRead 和 TaskOutput 后记录验证完成。",
  96. ]).done;
  97. expect({ code: result.code, stderr: result.code === 0 ? "" : result.stderr }).toEqual({
  98. code: 0,
  99. stderr: "",
  100. });
  101. expect(fixture.requests).toHaveLength(4);
  102. const first = fixture.requests[0]!.body;
  103. expectLocalSearchDescription(first);
  104. const searched = fixture.requests[1]!.body;
  105. const text = JSON.stringify(searched.messages);
  106. expect(text.match(/<functions>/g)).toHaveLength(1);
  107. expect(text.match(/<function>/g)).toHaveLength(2);
  108. expect(text).toContain("parameters");
  109. expect(text).not.toContain("Tool loaded.");
  110. const searchResult = toolSearchBlocks(searched).find(
  111. (block) => block.type === "tool_result" && block.tool_use_id === "local_search",
  112. );
  113. if (api === "anthropic-messages")
  114. expect(JSON.stringify(searchResult?.content)).not.toContain("Tool loaded.");
  115. expect(JSON.stringify(fixture.requests[2]!.body.messages)).toContain(
  116. "InputValidationError",
  117. );
  118. expect(hasResult(fixture.requests[3]!.body, "local_good")).toBe(true);
  119. expectSuccessfulTodoResult(fixture.requests[3]!.body);
  120. for (const request of fixture.requests) {
  121. expect(request.body.tools).toEqual(first.tools);
  122. expect(JSON.stringify(request.body)).not.toContain('"type":"tool_reference"');
  123. expect(JSON.stringify(request.body.tools)).not.toContain("defer_loading");
  124. expect(String(request.headers["anthropic-beta"] ?? "")).not.toContain(
  125. "advanced-tool-use",
  126. );
  127. }
  128. expect(toolNames(first)).toContain("DeferredToolCall");
  129. expect(toolNames(first)).not.toContain("TodoRead");
  130. const sessionId = (JSON.parse(result.stdout) as { sessionId: string }).sessionId;
  131. const db = new DatabaseSync(join(fixture.root, "session.sqlite"), { readOnly: true });
  132. try {
  133. const parts = db
  134. .prepare(
  135. "select data from part where json_extract(data, '$.callID') in ('local_bad', 'local_good')",
  136. )
  137. .all() as { data: string }[];
  138. expect(parts).toHaveLength(2);
  139. for (const row of parts) {
  140. const part = JSON.parse(row.data);
  141. expect(part.tool).toBe("TodoRead");
  142. expect(part.metadata.modelCallWrapper).toBe("DeferredToolCall");
  143. expect(part.metadata).not.toHaveProperty("modelToolCall");
  144. // TodoRead 的合法输入恒为 {},用 local_bad 的非法输入证明包装调用的 input
  145. // 原样透传到目标工具,且包装字段 name 不混入。
  146. expect(part.state.input).toEqual(
  147. part.callID === "local_good" ? {} : { todos: "invalid" },
  148. );
  149. expect(part.state.status).toBe(part.callID === "local_good" ? "completed" : "error");
  150. }
  151. } finally {
  152. db.close();
  153. }
  154. for (const coldMode of [
  155. "off",
  156. ...(api === "anthropic-messages" ? ["native"] : []),
  157. "local",
  158. ] as const) {
  159. const before = fixture.requests.length;
  160. const cold = await fixture.start([
  161. "--toolsearch-mode",
  162. coldMode,
  163. "--resume",
  164. sessionId,
  165. "-p",
  166. "E2E_TOOLSEARCH_LOCAL_COLD 检查历史并结束。",
  167. ]).done;
  168. expect({ code: cold.code, stderr: cold.code === 0 ? "" : cold.stderr }).toEqual({
  169. code: 0,
  170. stderr: "",
  171. });
  172. const request = fixture.requests[before]!.body;
  173. if (coldMode === "local") expectLocalSearchDescription(request);
  174. expect(toolNames(request).includes("LocalToolSearch")).toBe(coldMode === "local");
  175. expect(toolNames(request).includes("ToolSearch")).toBe(coldMode === "native");
  176. if (api === "anthropic-messages" && coldMode !== "off")
  177. expect(
  178. toolSearchBlocks(request).find(
  179. (block) => block.type === "tool_use" && block.id === "local_search",
  180. )?.name,
  181. ).toBe(coldMode === "local" ? "LocalToolSearch" : "ToolSearch");
  182. expect(JSON.stringify(request.messages).match(/Tool loaded\./g) ?? []).toHaveLength(
  183. coldMode === "native" ? 1 : 0,
  184. );
  185. expect(hasResult(request, "local_good")).toBe(true);
  186. expect(JSON.stringify(request.messages)).toContain("DeferredToolCall");
  187. expect(JSON.stringify(request.messages)).not.toContain("modelCallWrapper");
  188. expect(toolNames(request).includes("DeferredToolCall")).toBe(coldMode === "local");
  189. expect(JSON.stringify(request.messages).includes("<functions>")).toBe(
  190. coldMode === "local",
  191. );
  192. }
  193. } finally {
  194. await fixture.close();
  195. }
  196. });
  197. }
  198. }
  199. });
  200. function expectLocalSearchDescription(body: ToolSearchRequest): void {
  201. const definition = (body.tools ?? [])
  202. .map((tool) => {
  203. const entry = tool as { name: string; description?: string; function?: unknown };
  204. return (entry.function ?? entry) as { name: string; description?: string };
  205. })
  206. .find((tool) => tool.name === "LocalToolSearch");
  207. expect(toolNames(body)).toContain("LocalToolSearch");
  208. expect(toolNames(body)).not.toContain("ToolSearch");
  209. expect(definition?.description).toContain("called using DeferredToolCall.");
  210. expect(definition?.description).toContain(
  211. "For deferred tools, parameters describes the input object passed to DeferredToolCall.",
  212. );
  213. // 示例点名的工具须仍是 deferred:TodoWrite 转为常驻后示例改为 TaskStop,参数值为占位符。
  214. expect(definition?.description).toContain('DeferredToolCall({"name":"TaskStop","input":');
  215. expect(definition?.description?.match(/<example>/g)).toHaveLength(1);
  216. expect(definition?.description).not.toContain("<commentary>");
  217. expect(definition?.description).not.toContain("the same encoding");
  218. expect(definition?.description).not.toContain("does not change a tool's classification");
  219. }
  220. function hasResult(body: ToolSearchRequest, id: string): boolean {
  221. return (
  222. toolSearchBlocks(body).some((b) => b.type === "tool_result" && b.tool_use_id === id) ||
  223. body.messages.some(
  224. (m) => m.role === "tool" && (m as unknown as { tool_call_id?: string }).tool_call_id === id,
  225. )
  226. );
  227. }
  228. function expectSuccessfulTodoResult(body: ToolSearchRequest): void {
  229. const result =
  230. toolSearchBlocks(body).find(
  231. (block) => block.type === "tool_result" && block.tool_use_id === "local_good",
  232. ) ??
  233. body.messages.find(
  234. (message) =>
  235. message.role === "tool" &&
  236. (message as { tool_call_id?: string }).tool_call_id === "local_good",
  237. );
  238. expect(result).toBeDefined();
  239. expect(result).not.toMatchObject({ is_error: true });
  240. expect(JSON.stringify(result?.content)).not.toContain("InputValidationError");
  241. // 新会话没有待办,TodoRead 的真实执行输出是空清单。
  242. expect(JSON.parse(String(result?.content))).toEqual({ todos: [] });
  243. }
  244. function toolNames(body: ToolSearchRequest): string[] {
  245. return (body.tools ?? []).map(
  246. (tool) => tool.name ?? (tool as unknown as { function: { name: string } }).function.name,
  247. );
  248. }