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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { DatabaseSync } from "node:sqlite";
  4. import { startToolSearchTerminal } from "../helpers/toolsearch-terminal.js";
  5. import { createToolSearchCliFixture } from "../helpers/toolsearch-cli-process.js";
  6. import { toolSearchBlocks, type ToolSearchRequest } from "../helpers/toolsearch-provider.js";
  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 搜索 TodoWrite 和 WebFetch 后记录验证完成。",
  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("TodoWrite");
  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("TodoWrite");
  142. expect(part.metadata.modelCallWrapper).toBe("DeferredToolCall");
  143. expect(part.metadata).not.toHaveProperty("modelToolCall");
  144. expect(part.state.input).not.toHaveProperty("name");
  145. expect(part.state.status).toBe(part.callID === "local_good" ? "completed" : "error");
  146. }
  147. } finally {
  148. db.close();
  149. }
  150. for (const coldMode of [
  151. "off",
  152. ...(api === "anthropic-messages" ? ["native"] : []),
  153. "local",
  154. ] as const) {
  155. const before = fixture.requests.length;
  156. const cold = await fixture.start([
  157. "--toolsearch-mode",
  158. coldMode,
  159. "--resume",
  160. sessionId,
  161. "-p",
  162. "E2E_TOOLSEARCH_LOCAL_COLD 检查历史并结束。",
  163. ]).done;
  164. expect({ code: cold.code, stderr: cold.code === 0 ? "" : cold.stderr }).toEqual({
  165. code: 0,
  166. stderr: "",
  167. });
  168. const request = fixture.requests[before]!.body;
  169. if (coldMode === "local") expectLocalSearchDescription(request);
  170. expect(toolNames(request).includes("LocalToolSearch")).toBe(coldMode === "local");
  171. expect(toolNames(request).includes("ToolSearch")).toBe(coldMode === "native");
  172. if (api === "anthropic-messages" && coldMode !== "off")
  173. expect(
  174. toolSearchBlocks(request).find(
  175. (block) => block.type === "tool_use" && block.id === "local_search",
  176. )?.name,
  177. ).toBe(coldMode === "local" ? "LocalToolSearch" : "ToolSearch");
  178. expect(JSON.stringify(request.messages).match(/Tool loaded\./g) ?? []).toHaveLength(
  179. coldMode === "native" ? 1 : 0,
  180. );
  181. expect(hasResult(request, "local_good")).toBe(true);
  182. expect(JSON.stringify(request.messages)).toContain("DeferredToolCall");
  183. expect(JSON.stringify(request.messages)).not.toContain("modelCallWrapper");
  184. expect(toolNames(request).includes("DeferredToolCall")).toBe(coldMode === "local");
  185. expect(JSON.stringify(request.messages).includes("<functions>")).toBe(
  186. coldMode === "local",
  187. );
  188. }
  189. } finally {
  190. await fixture.close();
  191. }
  192. });
  193. }
  194. }
  195. });
  196. function expectLocalSearchDescription(body: ToolSearchRequest): void {
  197. const definition = (body.tools ?? [])
  198. .map((tool) => {
  199. const entry = tool as { name: string; description?: string; function?: unknown };
  200. return (entry.function ?? entry) as { name: string; description?: string };
  201. })
  202. .find((tool) => tool.name === "LocalToolSearch");
  203. expect(toolNames(body)).toContain("LocalToolSearch");
  204. expect(toolNames(body)).not.toContain("ToolSearch");
  205. expect(definition?.description).toContain("called using DeferredToolCall.");
  206. expect(definition?.description).toContain(
  207. "For deferred tools, parameters describes the input object passed to DeferredToolCall.",
  208. );
  209. expect(definition?.description).toContain('DeferredToolCall({"name":"TodoWrite","input":');
  210. expect(definition?.description?.match(/<example>/g)).toHaveLength(1);
  211. expect(definition?.description).not.toContain("<commentary>");
  212. expect(definition?.description).not.toContain("the same encoding");
  213. expect(definition?.description).not.toContain("does not change a tool's classification");
  214. }
  215. function hasResult(body: ToolSearchRequest, id: string): boolean {
  216. return (
  217. toolSearchBlocks(body).some((b) => b.type === "tool_result" && b.tool_use_id === id) ||
  218. body.messages.some(
  219. (m) => m.role === "tool" && (m as unknown as { tool_call_id?: string }).tool_call_id === id,
  220. )
  221. );
  222. }
  223. function expectSuccessfulTodoResult(body: ToolSearchRequest): void {
  224. const result =
  225. toolSearchBlocks(body).find(
  226. (block) => block.type === "tool_result" && block.tool_use_id === "local_good",
  227. ) ??
  228. body.messages.find(
  229. (message) =>
  230. message.role === "tool" &&
  231. (message as { tool_call_id?: string }).tool_call_id === "local_good",
  232. );
  233. expect(result).toBeDefined();
  234. expect(result).not.toMatchObject({ is_error: true });
  235. expect(JSON.stringify(result?.content)).not.toContain("InputValidationError");
  236. expect(JSON.parse(String(result?.content))).toMatchObject({
  237. todos: [{ status: "completed", priority: "medium" }],
  238. });
  239. }
  240. function toolNames(body: ToolSearchRequest): string[] {
  241. return (body.tools ?? []).map(
  242. (tool) => tool.name ?? (tool as unknown as { function: { name: string } }).function.name,
  243. );
  244. }