conversation-session-tool-discovery-card.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import {
  2. TID_SETTINGS_BACK_BUTTON,
  3. TID_SETTINGS_SECTION_NAV,
  4. TID_SETTINGS_TOOL_SEARCH_OPTION,
  5. TID_SETTINGS_TOOL_SEARCH_SELECT,
  6. TID_TASK_SETTINGS_BUTTON,
  7. TID_TOOL_SUMMARY_TRIGGER,
  8. testId,
  9. } from "@zcode/shared/test-ids";
  10. import { releaseControlledReplay } from "#e2e/helpers/controlled-replay";
  11. import { seedCustomAnthropicMessagesProvider } from "#e2e/helpers/custom-openai-provider";
  12. import { restartIntoWorkspace } from "#e2e/helpers/model-provider-restart";
  13. import {
  14. DEFAULT_WORKSPACE,
  15. clickTestIdByDom,
  16. readSettings,
  17. waitForWorkspaceApp,
  18. } from "#e2e/helpers/desktop-app";
  19. import {
  20. getLatestUpstreamToolResultByToolCallId,
  21. getUpstreamRequestToolNames,
  22. } from "#e2e/helpers/conversation-session-network";
  23. import { waitForToolCallBlockByToolCallId } from "#e2e/helpers/conversation-session-tool";
  24. import { startConversationModelProviderReplayServer } from "#e2e/helpers/model-provider-replay";
  25. import {
  26. selectUpstreamProviderModelById,
  27. waitForUpstreamModelSelected,
  28. } from "#e2e/helpers/upstream-provider";
  29. import {
  30. clickV4Stop,
  31. getV4TimelineScrollState,
  32. prepareV4ConversationE2E,
  33. sendV4Prompt,
  34. waitForV4AssistantMessageContaining,
  35. waitForV4Pane,
  36. } from "#e2e/helpers/v4-conversation";
  37. const CASE_NAME = "conversation-session-tool-discovery-card";
  38. const MODEL_ID = "e2e-tool-discovery-card-model";
  39. let replay: Awaited<ReturnType<typeof startConversationModelProviderReplayServer>>;
  40. describe("LocalToolSearch 与 ToolSearch 共用不可展开卡片", () => {
  41. before(async function () {
  42. this.timeout(240_000);
  43. replay = await startConversationModelProviderReplayServer(CASE_NAME);
  44. // 工作区 helper 通过 Escape 退出新 profile 引导,避免旧跳过按钮路径等待隐藏元素。
  45. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30_000);
  46. const providerId = "e2e-tool-discovery-card-provider";
  47. const providerName = "Tool discovery card E2E";
  48. await restartIntoWorkspace({
  49. afterElectronProcessExit: async () => {
  50. await seedCustomAnthropicMessagesProvider({
  51. baseURL: replay.baseUrl,
  52. modelId: MODEL_ID,
  53. providerId,
  54. providerName,
  55. });
  56. },
  57. });
  58. await prepareV4ConversationE2E({ skipProvider: true });
  59. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  60. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "general"));
  61. const select = await browser.$(`[data-testid="${TID_SETTINGS_TOOL_SEARCH_SELECT}"]`);
  62. await select.scrollIntoView();
  63. await select.click();
  64. await clickTestIdByDom(testId(TID_SETTINGS_TOOL_SEARCH_OPTION, "local"));
  65. await browser.waitUntil(async () => (await readSettings()).toolSearchMode === "local", {
  66. timeout: 15_000,
  67. timeoutMsg: "Local 模式未保存",
  68. });
  69. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  70. await prepareV4ConversationE2E({ skipProvider: true, skipShellReady: true });
  71. // 新草稿有独立模型偏好;在最终草稿上选模型,避免后续初始化重新采用默认模型。
  72. await selectUpstreamProviderModelById(MODEL_ID, {
  73. includePlainModelFallback: false,
  74. providerId,
  75. providerName,
  76. });
  77. await waitForUpstreamModelSelected(MODEL_ID, {
  78. includePlainModelFallback: false,
  79. providerId,
  80. });
  81. });
  82. after(async () => {
  83. await replay?.stop();
  84. });
  85. it("TS14-SUMMARY:空输入、单选、多选、关键词、无匹配及失败只显示摘要", async function () {
  86. this.timeout(180_000);
  87. await sendV4Prompt("E2E_TOOL_DISCOVERY_CARD_SUMMARY 搜索工具并检查卡片,不执行目标工具。");
  88. // fixture 先提交正文,越过原有可重试前奏缓冲,再观察真实工具占位并释放参数。
  89. try {
  90. await expectCard("card_single", /^(搜索工具|Search tools)$/u, "pending");
  91. } finally {
  92. await releaseControlledReplay("tool-discovery-card-summary");
  93. }
  94. await waitForV4AssistantMessageContaining("E2E_TOOL_DISCOVERY_CARD_DONE");
  95. await waitForV4Pane((pane) => !pane.canStop, "搜索轮次未结束", 30_000);
  96. const toolNames = await getUpstreamRequestToolNames({
  97. includes: ["E2E_TOOL_DISCOVERY_CARD_SUMMARY"],
  98. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  99. });
  100. expect(toolNames).toContain("LocalToolSearch");
  101. expect(toolNames).not.toContain("ToolSearch");
  102. for (const [id, query] of [
  103. ["card_single", "TodoWrite"],
  104. ["card_multi", "Read, TodoWrite, WebFetch"],
  105. ["card_keyword", "checklist"],
  106. ["card_none", "zztoolcardnomatch987654321"],
  107. ["card_invalid", "TodoWrite"],
  108. ] as const) {
  109. await expectCard(
  110. id,
  111. new RegExp(`(?:搜索工具:|Search tools: )${query}`),
  112. id === "card_invalid" ? "failed" : "completed",
  113. );
  114. const result = await getLatestUpstreamToolResultByToolCallId(id);
  115. expect(result).not.toBeNull();
  116. expect(result!.isError).toBe(id === "card_invalid");
  117. if (id === "card_invalid") expect(result!.content).toContain("max_results");
  118. else if (id === "card_none")
  119. expect(result!.content).toContain(
  120. "No matching deferred tools found. Loaded tools are not searchable here and need no loading. Check your loaded tool list and query; try corrected spelling, alternative names, or broader keywords before concluding a tool is missing.",
  121. );
  122. else expect(result!.content).toContain("<functions>");
  123. }
  124. for (const locale of ["zh-CN", "en-US"] as const) {
  125. for (const theme of ["zai-light", "zai-dark"] as const) {
  126. await setPresentation(locale, theme);
  127. const label = locale === "zh-CN" ? "搜索工具:" : "Search tools: ";
  128. await expectCard(
  129. "card_multi",
  130. new RegExp(`${label}Read, TodoWrite, WebFetch`),
  131. "completed",
  132. );
  133. await expectCard("card_invalid", new RegExp(`${label}TodoWrite`), "failed");
  134. }
  135. }
  136. });
  137. it("TS14-STOP:参数流式生成时停止,卡片不展示部分 JSON 或结果", async function () {
  138. this.timeout(90_000);
  139. await sendV4Prompt("E2E_TOOL_DISCOVERY_CARD_STOP 搜索工具,在参数未完成时停止。");
  140. await expectCard("card_stopped", /搜索工具|Search tools/u, "pending");
  141. await clickV4Stop();
  142. await waitForV4Pane((pane) => !pane.canStop, "停止后会话仍在运行", 30_000);
  143. await expectCard("card_stopped", /搜索工具|Search tools/u, "stopped");
  144. expect(await getLatestUpstreamToolResultByToolCallId("card_stopped")).toBeNull();
  145. // 用户停止会关闭 HTTP 连接并取消测试 gate,无需再释放已取消的流。
  146. });
  147. it("TS14-DEFERRED:隐藏包装参数预览和待办,保留包装错误", async function () {
  148. this.timeout(90_000);
  149. expect((await readSettings()).messageStreamShowTodos ?? false).toBe(false);
  150. const before = await getV4TimelineScrollState();
  151. await sendV4Prompt("E2E_TOOL_DISCOVERY_CARD_DEFERRED 更新待办并检查包装错误。");
  152. try {
  153. await browser.waitUntil(
  154. async () => {
  155. const response = await fetch(`${replay.baseUrl}/__e2e__/gates`);
  156. return ((await response.json()) as string[]).includes("tool-discovery-card-deferred");
  157. },
  158. { timeout: 15_000, timeoutMsg: "包装调用未进入受控参数流" },
  159. );
  160. await waitForV4AssistantMessageContaining("Preparing a deferred todo.");
  161. // 等待原始投影包含本轮 header、user、正文及包装行,避免在事件到达前断言不存在。
  162. await browser.waitUntil(
  163. async () => (await getV4TimelineScrollState()).totalRowCount >= before.totalRowCount + 4,
  164. { timeout: 15_000, timeoutMsg: "包装行尚未到达 UI 投影" },
  165. );
  166. expect(await browser.$('[data-tool-call-id="card_deferred_todo"]').isExisting()).toBe(false);
  167. await waitForV4Pane((pane) => pane.canStop, "隐藏卡片后丢失 Stop 入口", 10_000);
  168. } finally {
  169. await releaseControlledReplay("tool-discovery-card-deferred");
  170. }
  171. await waitForV4AssistantMessageContaining("E2E_TOOL_DISCOVERY_CARD_DEFERRED_DONE");
  172. await waitForV4Pane((pane) => !pane.canStop, "包装调用轮次未结束", 30_000);
  173. const result = await getLatestUpstreamToolResultByToolCallId("card_deferred_todo");
  174. expect(result?.isError).toBe(false);
  175. expect(JSON.parse(result!.content)).toMatchObject({
  176. todos: [{ content: "Deferred visibility verified", status: "completed" }],
  177. });
  178. expect(await browser.$('[data-tool-call-id="card_deferred_todo"]').isExisting()).toBe(false);
  179. const failed = await waitForToolCallBlockByToolCallId("card_deferred_invalid");
  180. expect(failed.toolName).toBe("DeferredToolCall");
  181. expect(failed.status).toBe("failed");
  182. });
  183. });
  184. async function expectCard(callId: string, label: RegExp, status: string) {
  185. const snapshot = await waitForToolCallBlockByToolCallId(callId, 30_000);
  186. const block = await browser.$(`[data-testid="${snapshot.testId}"]`);
  187. await browser.waitUntil(async () => (await block.getAttribute("data-status")) === status, {
  188. timeout: 15_000,
  189. timeoutMsg: `${callId} 未变为 ${status}`,
  190. });
  191. if (status === "pending" || status === "stopped") {
  192. expect(await block.getAttribute("data-tool-name")).toBe("LocalToolSearch");
  193. }
  194. const summary = await block.$(`[data-testid="${testId(TID_TOOL_SUMMARY_TRIGGER, callId)}"]`);
  195. await expect(summary).toHaveText(label);
  196. expect(await summary.getAttribute("title")).toBe("ToolSearch");
  197. expect(await summary.getAttribute("role")).not.toBe("button");
  198. expect(await summary.getAttribute("aria-expanded")).toBeNull();
  199. await summary.scrollIntoView();
  200. await summary.click();
  201. expect(await summary.getAttribute("aria-expanded")).toBeNull();
  202. expect(await block.$("pre").isExisting()).toBe(false);
  203. expect(await block.getText()).not.toMatch(
  204. /select:|max_results|<functions>|inputSchema|Tool loaded\./u,
  205. );
  206. }
  207. async function setPresentation(locale: "zh-CN" | "en-US", theme: "zai-light" | "zai-dark") {
  208. const changed = await browser.execute(
  209. (nextLocale, nextTheme) => {
  210. const actions = (window as typeof window & { __testActions?: Record<string, unknown> })
  211. .__testActions;
  212. if (typeof actions?.setLocale !== "function" || typeof actions.setTheme !== "function")
  213. return false;
  214. (actions.setLocale as (value: string) => void)(nextLocale);
  215. (actions.setTheme as (value: string) => void)(nextTheme);
  216. return true;
  217. },
  218. locale,
  219. theme,
  220. );
  221. expect(changed).toBe(true);
  222. await browser.waitUntil(
  223. async () =>
  224. (await browser.$("html").getAttribute("class"))?.split(" ").includes(`theme-${theme}`),
  225. {
  226. timeout: 10_000,
  227. timeoutMsg: "主题未更新",
  228. },
  229. );
  230. }