conversation-session-tool.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. import {
  2. TID_CHAT_ASSISTANT_HISTORY_CONTENT,
  3. TID_CHAT_ASSISTANT_HISTORY_TRIGGER,
  4. TID_CHAT_ASSISTANT_MESSAGE,
  5. TID_CHAT_TOOL_CALL_BLOCK,
  6. testId,
  7. } from "@zcode/shared/test-ids";
  8. import {
  9. getLatestUpstreamToolResultByToolCallId,
  10. type UpstreamToolResultSnapshot,
  11. } from "./conversation-session-network.js";
  12. import {
  13. expandAssistantHistoriesWithContent,
  14. expandVisibleSummaryGroups,
  15. getToolCallDiagnostics,
  16. type ToolCallBlockSnapshot,
  17. type ToolCallDiagnostics,
  18. type ToolCallMatcher,
  19. } from "./conversation-session-tool-diagnostics.js";
  20. export { expandAssistantHistoriesWithContent } from "./conversation-session-tool-diagnostics.js";
  21. interface AssistantHistoryOpenSnapshot {
  22. assistantText: string;
  23. contentExists: boolean;
  24. contentOpen: string | null;
  25. expanded: boolean;
  26. reason: string | null;
  27. triggerTestId: string | null;
  28. }
  29. export async function waitForToolCallBlockContaining(
  30. text: string,
  31. timeout = 20000,
  32. ): Promise<ToolCallBlockSnapshot> {
  33. return waitForToolCallBlock({ type: "text", value: text }, timeout);
  34. }
  35. export async function waitForToolCallBlockByToolName(
  36. toolName: string,
  37. timeout = 20000,
  38. ): Promise<ToolCallBlockSnapshot> {
  39. return waitForToolCallBlock({ type: "toolName", value: toolName }, timeout);
  40. }
  41. export async function waitForToolCallBlockByToolCallId(
  42. toolCallId: string,
  43. timeout = 20000,
  44. ): Promise<ToolCallBlockSnapshot> {
  45. return waitForToolCallBlock({ type: "toolCallId", value: toolCallId }, timeout);
  46. }
  47. /**
  48. * 等已结束轮次的工具卡片收进“工作记录”后再返回。
  49. * Bug 根因:轮次结束(canStop=false)约 0.3 秒后,卡片才从展开区收进工作记录并重新挂载;
  50. * waitForToolCallBlockByToolCallId 可能在收起前命中旧节点,调用方随后按 testid 再查 DOM
  51. * 会落空(运行时采样:命中后 213ms 仍在、319ms 消失,展开工作记录后卡片恢复且文案正确)。
  52. * 修复:以“卡片位于展开的工作记录内容里”作为收起完成的信号,再交给通用等待器取快照。
  53. * 只用于以正文结束的轮次(已在 TS11/TS14 运行时验证);进行中或已停止的卡片沿用通用等待器。
  54. */
  55. export async function waitForFoldedToolCallBlockByToolCallId(
  56. toolCallId: string,
  57. timeout = 20000,
  58. ): Promise<ToolCallBlockSnapshot> {
  59. await browser.waitUntil(
  60. async () => {
  61. await expandAssistantHistoriesWithContent();
  62. await expandVisibleSummaryGroups();
  63. return browser.execute(
  64. (contentPrefix, blockTestId) =>
  65. document.querySelector(
  66. `[data-testid^="${contentPrefix}-"] [data-testid="${blockTestId}"]`,
  67. ) !== null,
  68. TID_CHAT_ASSISTANT_HISTORY_CONTENT,
  69. testId(TID_CHAT_TOOL_CALL_BLOCK, toolCallId),
  70. );
  71. },
  72. { timeout, timeoutMsg: `工具卡片没有收进工作记录: ${toolCallId}` },
  73. );
  74. return waitForToolCallBlockByToolCallId(toolCallId, timeout);
  75. }
  76. /**
  77. * 展开已完成回合里某个工具卡的详情,直到触发器真的是展开态。
  78. *
  79. * 失败原因:回合结束后,已完成回合会把工具块收进折叠的 assistant history,折叠内容不挂载。
  80. * 先找到块、再点击的两步写法,可能在收起前一刻看到块,随后点击落在已卸载的节点上,
  81. * 而 history 之后保持收起。这里每轮都先展开 history 与摘要组,再点工具卡,
  82. * 直到 `aria-expanded="true"`,不依赖收起发生的时刻。
  83. */
  84. export async function expandToolCallDetails(toolCallId: string, timeout = 30000): Promise<void> {
  85. const trigger = `[data-tool-call-id="${toolCallId}"] [role="button"][aria-expanded]`;
  86. await browser.waitUntil(
  87. async () => {
  88. await expandAssistantHistoriesWithContent();
  89. await expandVisibleSummaryGroups();
  90. return browser.execute((selector: string) => {
  91. const element = document.querySelector<HTMLElement>(selector);
  92. if (!element) return false;
  93. if (element.getAttribute("aria-expanded") === "true") return true;
  94. element.click();
  95. return false;
  96. }, trigger);
  97. },
  98. { timeout, interval: 250, timeoutMsg: `工具卡没有展开:${toolCallId}` },
  99. );
  100. }
  101. export async function listToolCallBlocks(): Promise<ToolCallBlockSnapshot[]> {
  102. const diagnostics = await getToolCallDiagnostics(null);
  103. return diagnostics.blocks;
  104. }
  105. export interface SuccessfulToolCallSnapshot {
  106. output: string;
  107. status: "completed";
  108. toolCallId: string;
  109. toolName: string | null;
  110. }
  111. export async function assertToolCallNotFailedByToolCallId(toolCallId: string): Promise<void> {
  112. const diagnostics = await getToolCallDiagnostics({
  113. type: "toolCallId",
  114. value: toolCallId,
  115. });
  116. const toolCall = findRendererStoreToolCall(diagnostics, toolCallId);
  117. if (toolCall?.status === "failed" || diagnostics.matchedBlock?.status === "failed") {
  118. throw createToolCallFailure(toolCallId, toolCall, diagnostics.matchedBlock);
  119. }
  120. const providerResult = await getLatestUpstreamToolResultByToolCallId(toolCallId);
  121. if (providerResult?.isError) {
  122. // Bug 根因:V4 历史投影可能在工具已经返回 is_error 后仍短暂显示 pending,
  123. // 直接读取模型实际收到的 tool_result,避免错误再次退化为 guest/UI 超时。
  124. throw createProviderToolResultFailure(providerResult);
  125. }
  126. }
  127. export async function waitForSuccessfulToolCallByToolCallId(
  128. toolCallId: string,
  129. expectedOutputIncludes: readonly string[] = [],
  130. timeout = 20000,
  131. ): Promise<SuccessfulToolCallSnapshot> {
  132. const deadline = Date.now() + timeout;
  133. let latest: ReturnType<typeof findRendererStoreToolCall> = null;
  134. while (Date.now() <= deadline) {
  135. const diagnostics = await getToolCallDiagnostics({
  136. type: "toolCallId",
  137. value: toolCallId,
  138. });
  139. latest = findRendererStoreToolCall(diagnostics, toolCallId);
  140. const block = diagnostics.matchedBlock;
  141. if (latest?.status === "failed" || block?.status === "failed") {
  142. // Bug 根因:Browser 无状态化后旧 fixture 的跨 cell binding 会直接令工具失败,
  143. // 但旧 E2E 继续等待 guest/UI,最终只报焦点超时。工具错误必须在真实边界立即暴露。
  144. throw createToolCallFailure(toolCallId, latest, block);
  145. }
  146. const providerResult = await getLatestUpstreamToolResultByToolCallId(toolCallId);
  147. if (providerResult?.isError) {
  148. throw createProviderToolResultFailure(providerResult);
  149. }
  150. if (latest?.status === "completed") {
  151. const output = latest.output ?? "";
  152. assertToolResultContains(toolCallId, output, expectedOutputIncludes);
  153. return {
  154. output,
  155. status: "completed",
  156. toolCallId: latest.toolId ?? toolCallId,
  157. toolName: latest.toolName,
  158. };
  159. }
  160. if (providerResult) {
  161. assertToolResultContains(toolCallId, providerResult.content, expectedOutputIncludes);
  162. return {
  163. output: providerResult.content,
  164. status: "completed",
  165. toolCallId,
  166. toolName: block?.toolName ?? latest?.toolName ?? null,
  167. };
  168. }
  169. if (block?.status === "completed" && expectedOutputIncludes.length === 0) {
  170. // V4 history case 的 renderer-store 旧消息投影可能为空,但 DOM tool block 是
  171. // 真实执行终态;要求 marker 时必须继续等模型实际收到的 provider tool_result。
  172. return {
  173. output: block.text,
  174. status: "completed",
  175. toolCallId: block.toolCallId ?? toolCallId,
  176. toolName: block.toolName,
  177. };
  178. }
  179. await new Promise<void>((resolveDelay) => setTimeout(resolveDelay, 100));
  180. }
  181. throw new Error(
  182. `toolCallId=${toolCallId} 没有在 ${timeout}ms 内成功完成; latest=${JSON.stringify(latest)}`,
  183. );
  184. }
  185. export async function openAssistantHistoryForAssistantContaining(
  186. text: string,
  187. timeout = 15000,
  188. ): Promise<AssistantHistoryOpenSnapshot> {
  189. let latest: AssistantHistoryOpenSnapshot | null = null;
  190. try {
  191. await browser.waitUntil(
  192. async () => {
  193. latest = await clickAssistantHistoryForAssistantContaining(text);
  194. return latest.expanded;
  195. },
  196. {
  197. timeout,
  198. timeoutMsg: `没有展开包含指定内容的 assistant history: ${text}`,
  199. },
  200. );
  201. } catch {
  202. latest = await safeClickAssistantHistoryForAssistantContaining(text, latest);
  203. throw new Error(
  204. `没有展开包含指定内容的 assistant history: ${text}; latest=${JSON.stringify(latest)}`,
  205. );
  206. }
  207. const result = await clickAssistantHistoryForAssistantContaining(text);
  208. if (!result.expanded) {
  209. throw new Error(`assistant history 等待后仍未展开: ${text}; latest=${JSON.stringify(result)}`);
  210. }
  211. return result;
  212. }
  213. export function getToolCallBlockContaining(text: string): Promise<ToolCallBlockSnapshot | null> {
  214. return getMatchingToolCallBlock({ type: "text", value: text });
  215. }
  216. export function getToolCallBlockByToolName(
  217. toolName: string,
  218. ): Promise<ToolCallBlockSnapshot | null> {
  219. return getMatchingToolCallBlock({ type: "toolName", value: toolName });
  220. }
  221. export function getToolCallBlockByToolCallId(
  222. toolCallId: string,
  223. ): Promise<ToolCallBlockSnapshot | null> {
  224. return getMatchingToolCallBlock({ type: "toolCallId", value: toolCallId });
  225. }
  226. async function waitForToolCallBlock(
  227. matcher: ToolCallMatcher,
  228. timeout: number,
  229. ): Promise<ToolCallBlockSnapshot> {
  230. let latest: ToolCallDiagnostics | null = null;
  231. let matchedBlock: ToolCallBlockSnapshot | null = null;
  232. try {
  233. await browser.waitUntil(
  234. async () => {
  235. latest = await getToolCallDiagnostics(matcher);
  236. if (latest.matchedBlock?.exists === true) {
  237. matchedBlock = latest.matchedBlock;
  238. return true;
  239. }
  240. await expandAssistantHistoriesWithContent();
  241. await expandVisibleSummaryGroups();
  242. return false;
  243. },
  244. {
  245. timeout,
  246. timeoutMsg: `没有出现匹配的 tool call block: ${JSON.stringify(matcher)}`,
  247. },
  248. );
  249. } catch {
  250. latest = await safeGetToolCallDiagnostics(matcher, latest);
  251. throw new Error(
  252. `没有出现匹配的 tool call block: ${JSON.stringify(
  253. matcher,
  254. )}; diagnostics=${JSON.stringify(latest)}`,
  255. );
  256. }
  257. if (!matchedBlock) {
  258. latest = await safeGetToolCallDiagnostics(matcher, latest);
  259. throw new Error(
  260. `tool call block 等待后仍不存在: ${JSON.stringify(
  261. matcher,
  262. )}; diagnostics=${JSON.stringify(latest)}`,
  263. );
  264. }
  265. // 修复原因:tool block 命中后可能立即被折叠进 assistant history。重新查询 DOM
  266. // 会把已经成功观察到的短生命周期节点误判为不存在,应返回成功轮询捕获的快照。
  267. return matchedBlock;
  268. }
  269. async function getMatchingToolCallBlock(
  270. matcher: ToolCallMatcher,
  271. ): Promise<ToolCallBlockSnapshot | null> {
  272. const diagnostics = await getToolCallDiagnostics(matcher);
  273. return diagnostics.matchedBlock;
  274. }
  275. function findRendererStoreToolCall(diagnostics: ToolCallDiagnostics, toolCallId: string) {
  276. for (const message of diagnostics.rendererStore.messages) {
  277. const match = message.toolCalls.find(
  278. (toolCall) =>
  279. toolCall.toolId === toolCallId || toolCall.toolId?.startsWith(`${toolCallId}:`) === true,
  280. );
  281. if (match) return match;
  282. }
  283. return null;
  284. }
  285. function createToolCallFailure(
  286. toolCallId: string,
  287. toolCall: ReturnType<typeof findRendererStoreToolCall>,
  288. block: ToolCallBlockSnapshot | null,
  289. ): Error {
  290. return new Error(
  291. `toolCallId=${toolCallId} 执行失败; error=${JSON.stringify(toolCall?.error)}; ` +
  292. `rawError=${JSON.stringify(toolCall?.rawErrorMessage ?? toolCall?.rawErrorDetail)}; ` +
  293. `output=${JSON.stringify(toolCall?.output)}; block=${JSON.stringify(block)}`,
  294. );
  295. }
  296. function createProviderToolResultFailure(result: UpstreamToolResultSnapshot): Error {
  297. return new Error(
  298. `toolCallId=${result.toolCallId} 执行失败; providerToolResult=${JSON.stringify(
  299. result.content,
  300. )}; isError=true`,
  301. );
  302. }
  303. function assertToolResultContains(
  304. toolCallId: string,
  305. output: string,
  306. expectedOutputIncludes: readonly string[],
  307. ): void {
  308. const missing = expectedOutputIncludes.filter((value) => !output.includes(value));
  309. if (missing.length > 0) {
  310. throw new Error(
  311. `toolCallId=${toolCallId} 已返回 tool_result,但结果缺少 ${JSON.stringify(
  312. missing,
  313. )}; output=${output}`,
  314. );
  315. }
  316. }
  317. async function safeGetToolCallDiagnostics(
  318. matcher: ToolCallMatcher,
  319. fallback: ToolCallDiagnostics | null,
  320. ): Promise<ToolCallDiagnostics | null> {
  321. try {
  322. return await getToolCallDiagnostics(matcher);
  323. } catch {
  324. return fallback;
  325. }
  326. }
  327. function clickAssistantHistoryForAssistantContaining(
  328. text: string,
  329. ): Promise<AssistantHistoryOpenSnapshot> {
  330. return browser.execute(
  331. (assistantMessagePrefix, historyTriggerPrefix, historyContentPrefix, expectedText) => {
  332. const normalizeText = (value: string) => value.replace(/\u00a0/g, " ").trim();
  333. const assistantMessages = Array.from(
  334. document.querySelectorAll<HTMLElement>(`[data-testid^="${assistantMessagePrefix}-"]`),
  335. );
  336. const assistantMessage = assistantMessages.find((message) =>
  337. normalizeText(message.innerText).includes(expectedText),
  338. );
  339. if (!assistantMessage) {
  340. return {
  341. assistantText: assistantMessages
  342. .map((message) => normalizeText(message.innerText))
  343. .join("\n---\n"),
  344. contentExists: false,
  345. contentOpen: null,
  346. expanded: false,
  347. reason: "assistant-not-found",
  348. triggerTestId: null,
  349. };
  350. }
  351. const trigger = assistantMessage.querySelector<HTMLElement>(
  352. `[data-testid^="${historyTriggerPrefix}-"]`,
  353. );
  354. if (!trigger) {
  355. return {
  356. assistantText: normalizeText(assistantMessage.innerText),
  357. contentExists: false,
  358. contentOpen: null,
  359. expanded: false,
  360. reason: "history-trigger-not-found",
  361. triggerTestId: null,
  362. };
  363. }
  364. const stateKey = trigger.getAttribute("data-history-state-key");
  365. const content =
  366. stateKey !== null
  367. ? document.querySelector<HTMLElement>(
  368. `[data-testid^="${historyContentPrefix}-"][data-history-state-key="${stateKey}"]`,
  369. )
  370. : null;
  371. const expanded =
  372. trigger.getAttribute("aria-expanded") === "true" ||
  373. trigger.getAttribute("data-history-open") === "true";
  374. if (!expanded) {
  375. trigger.click();
  376. }
  377. return {
  378. assistantText: normalizeText(assistantMessage.innerText),
  379. contentExists: Boolean(content),
  380. contentOpen: content?.getAttribute("data-history-open") ?? null,
  381. expanded,
  382. reason: expanded ? null : "clicked-history-trigger",
  383. triggerTestId: trigger.getAttribute("data-testid"),
  384. };
  385. },
  386. TID_CHAT_ASSISTANT_MESSAGE,
  387. TID_CHAT_ASSISTANT_HISTORY_TRIGGER,
  388. TID_CHAT_ASSISTANT_HISTORY_CONTENT,
  389. text,
  390. );
  391. }
  392. async function safeClickAssistantHistoryForAssistantContaining(
  393. text: string,
  394. fallback: AssistantHistoryOpenSnapshot | null,
  395. ): Promise<AssistantHistoryOpenSnapshot | null> {
  396. try {
  397. return await clickAssistantHistoryForAssistantContaining(text);
  398. } catch {
  399. return fallback;
  400. }
  401. }