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

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