conversation-session-tool.ts 13 KB

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