conversation-session-tool-diagnostics.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import {
  2. TID_CHAT_ASSISTANT_HISTORY_CONTENT,
  3. TID_CHAT_ASSISTANT_HISTORY_TRIGGER,
  4. TID_CHAT_ASSISTANT_MESSAGE,
  5. TID_CHAT_MESSAGE_EDIT_BUTTON,
  6. TID_CHAT_MESSAGE_FORK_BUTTON,
  7. TID_CHAT_TOOL_CALL_BLOCK,
  8. TID_CHAT_VIEW,
  9. TID_TOOL_SUMMARY_TRIGGER,
  10. TID_V4_SESSION_PANE,
  11. } from "@zcode/shared/test-ids";
  12. export interface ToolCallBlockSnapshot {
  13. exists: boolean;
  14. hasEditAction: boolean;
  15. hasForkAction: boolean;
  16. status: string | null;
  17. testId: string;
  18. text: string;
  19. toolCallId: string | null;
  20. toolName: string | null;
  21. }
  22. interface AssistantMessageSnapshot {
  23. messageId: string | null;
  24. text: string;
  25. }
  26. interface ChatStateSnapshot {
  27. activeInputId: string | null;
  28. queueCount: string | null;
  29. state: string | null;
  30. }
  31. export interface ToolCallDiagnostics {
  32. assistantMessages: AssistantMessageSnapshot[];
  33. assistantHistory: AssistantHistoryStateSnapshot[];
  34. blocks: ToolCallBlockSnapshot[];
  35. chatState: ChatStateSnapshot | null;
  36. matcher: ToolCallMatcher | null;
  37. matchedBlock: ToolCallBlockSnapshot | null;
  38. rendererStore: RendererStoreDiagnostics;
  39. }
  40. interface AssistantHistoryStateSnapshot {
  41. contentExists: boolean;
  42. contentOpen: string | null;
  43. contentText: string;
  44. expanded: boolean;
  45. hasContent: string | null;
  46. stateKey: string | null;
  47. triggerTestId: string;
  48. }
  49. interface RendererStoreDiagnostics {
  50. activeTaskId: string | null;
  51. available: boolean;
  52. messages: RendererStoreMessageSnapshot[];
  53. reason: string | null;
  54. }
  55. interface RendererStoreMessageSnapshot {
  56. content: string;
  57. id: string | null;
  58. partTypes: string[];
  59. role: string | null;
  60. taskId: string;
  61. toolCalls: RendererStoreToolCallSnapshot[];
  62. workspaceKey: string;
  63. }
  64. interface RendererStoreToolCallSnapshot {
  65. error: string | null;
  66. output: string | null;
  67. rawErrorDetail: string | null;
  68. rawErrorMessage: string | null;
  69. status: string | null;
  70. toolId: string | null;
  71. toolName: string | null;
  72. }
  73. export type ToolCallMatcher =
  74. | {
  75. type: "text";
  76. value: string;
  77. }
  78. | {
  79. type: "toolCallId";
  80. value: string;
  81. }
  82. | {
  83. type: "toolName";
  84. value: string;
  85. };
  86. export function expandAssistantHistoriesWithContent(): Promise<void> {
  87. return browser.execute((historyTriggerPrefix) => {
  88. const triggers = Array.from(
  89. document.querySelectorAll<HTMLElement>(`[data-testid^="${historyTriggerPrefix}-"]`),
  90. );
  91. for (const trigger of triggers) {
  92. const expanded =
  93. trigger.getAttribute("aria-expanded") === "true" ||
  94. trigger.getAttribute("data-history-open") === "true";
  95. if (trigger.getAttribute("data-history-has-content") !== "false" && !expanded) {
  96. trigger.click();
  97. }
  98. }
  99. }, TID_CHAT_ASSISTANT_HISTORY_TRIGGER);
  100. }
  101. /**
  102. * 展开当前已渲染的工具分组,令按原始 tool call id 的断言可以观察到 child。
  103. *
  104. * V4 会把连续的 Bash/terminal 调用折叠进 ExecuteGroup,父节点刻意只锚定
  105. * 首个 child 的 id 以避免流式新增时重建。若等待器只扫描折叠态 DOM,第二个
  106. * child 会被误判为未渲染,进而把分组 UI 的正常行为报告成 E2E 失败。
  107. */
  108. export function expandVisibleToolCallGroups(): Promise<void> {
  109. return browser.execute((summaryTriggerPrefix) => {
  110. const groupNames = new Set(["Explore", "ExecuteGroup", "ChangesGroup"]);
  111. const groups = Array.from(
  112. document.querySelectorAll<HTMLElement>("[data-tool-call-id][data-tool-name]"),
  113. ).filter((group) => groupNames.has(group.dataset.toolName ?? ""));
  114. for (const group of groups) {
  115. const trigger = group.querySelector<HTMLElement>(`[data-testid^="${summaryTriggerPrefix}-"]`);
  116. if (trigger?.getAttribute("aria-expanded") !== "true") {
  117. trigger?.click();
  118. }
  119. }
  120. }, TID_TOOL_SUMMARY_TRIGGER);
  121. }
  122. export function getToolCallDiagnostics(
  123. matcher: ToolCallMatcher | null,
  124. ): Promise<ToolCallDiagnostics> {
  125. return browser.execute(
  126. (
  127. toolBlockPrefix,
  128. editButtonPrefix,
  129. forkButtonPrefix,
  130. assistantMessagePrefix,
  131. chatViewTestId,
  132. historyTriggerPrefix,
  133. historyContentPrefix,
  134. v4PaneTestId,
  135. expectedMatcher,
  136. ) => {
  137. const normalizeText = (value: string) => value.replace(/\u00a0/g, " ").trim();
  138. const blocks = Array.from(
  139. document.querySelectorAll<HTMLElement>(`[data-testid^="${toolBlockPrefix}-"]`),
  140. ).map((block) => ({
  141. exists: true,
  142. hasEditAction: Boolean(
  143. // V4 消息操作已换前缀;负向断言必须检查现行入口,不能仅检查退役节点。
  144. block.querySelector(`[data-testid^="${editButtonPrefix}-"], [data-testid^="v4-edit-"]`),
  145. ),
  146. hasForkAction: Boolean(
  147. block.querySelector(`[data-testid^="${forkButtonPrefix}-"], [data-testid^="v4-fork-"]`),
  148. ),
  149. status: block.getAttribute("data-status"),
  150. testId: block.getAttribute("data-testid") ?? "",
  151. text: normalizeText(block.innerText),
  152. toolCallId: block.getAttribute("data-tool-call-id"),
  153. toolName: block.getAttribute("data-tool-name"),
  154. }));
  155. const matchedBlock =
  156. expectedMatcher === null
  157. ? null
  158. : (blocks.findLast((block) => {
  159. if (expectedMatcher.type === "text") {
  160. return block.text.includes(expectedMatcher.value);
  161. }
  162. if (expectedMatcher.type === "toolCallId") {
  163. return (
  164. block.toolCallId === expectedMatcher.value ||
  165. block.toolCallId?.startsWith(`${expectedMatcher.value}:`) ||
  166. // 现行 V4 会把连续 Bash 收拢到 ExecuteGroup;父组稳定地以首个真实
  167. // tool call id 作为 identity。折叠态不会渲染 child DOM,诊断必须在
  168. // 此处识别这个可追溯的投影,而不是要求 UI 恢复旧的平铺结构。
  169. block.toolCallId === `execute:${expectedMatcher.value}`
  170. );
  171. }
  172. return (
  173. block.toolName === expectedMatcher.value ||
  174. (expectedMatcher.value === "Bash" && block.toolName === "ExecuteGroup")
  175. );
  176. }) ?? null);
  177. const assistantMessages = Array.from(
  178. document.querySelectorAll<HTMLElement>(`[data-testid^="${assistantMessagePrefix}-"]`),
  179. ).map((message) => ({
  180. messageId: message.getAttribute("data-message-id"),
  181. text: normalizeText(message.innerText),
  182. }));
  183. const assistantHistory = Array.from(
  184. document.querySelectorAll<HTMLElement>(`[data-testid^="${historyTriggerPrefix}-"]`),
  185. ).map((trigger) => {
  186. const triggerTestId = trigger.getAttribute("data-testid") ?? "";
  187. // Bug 根因:V4 history 只把 unit.key 编入 test id,不再写
  188. // data-history-state-key;旧诊断因此找不到已存在的折叠内容,误导 E2E 归因。
  189. const stateKey =
  190. trigger.getAttribute("data-history-state-key") ??
  191. (triggerTestId.startsWith(`${historyTriggerPrefix}-`)
  192. ? triggerTestId.slice(historyTriggerPrefix.length + 1)
  193. : null);
  194. const content =
  195. stateKey !== null
  196. ? (Array.from(
  197. document.querySelectorAll<HTMLElement>(`[data-testid^="${historyContentPrefix}-"]`),
  198. ).find(
  199. (candidate) =>
  200. candidate.getAttribute("data-testid") === `${historyContentPrefix}-${stateKey}`,
  201. ) ?? null)
  202. : null;
  203. return {
  204. contentExists: Boolean(content),
  205. contentOpen: content?.getAttribute("data-history-open") ?? null,
  206. contentText: normalizeText(content?.innerText ?? ""),
  207. expanded: trigger.getAttribute("aria-expanded") === "true",
  208. hasContent: trigger.getAttribute("data-history-has-content"),
  209. stateKey,
  210. triggerTestId,
  211. };
  212. });
  213. const chatView = document.querySelector<HTMLElement>(`[data-testid="${chatViewTestId}"]`);
  214. const chatState = chatView
  215. ? {
  216. activeInputId: chatView.getAttribute("data-active-input-id"),
  217. queueCount: chatView.getAttribute("data-queue-count"),
  218. state: chatView.getAttribute("data-chat-state"),
  219. }
  220. : null;
  221. const v4SessionId = document
  222. // Bug 根因:V4 pane test id 始终带 paneId 后缀;精确匹配基础 id 会让
  223. // hooks/tool 失败诊断把真实 active task 误报成 null。
  224. .querySelector<HTMLElement>(`[data-testid^="${v4PaneTestId}-"]`)
  225. ?.getAttribute("data-session-id");
  226. // 修复原因:V4 不再渲染 chat-view;诊断若只从旧 root 取 taskId,
  227. // 会把 renderer store 误报为空,掩盖真正的 tool 投影问题。
  228. const activeTaskId =
  229. chatView?.getAttribute("data-task-id") ||
  230. (v4SessionId && v4SessionId !== "draft" ? v4SessionId : null);
  231. const e2eWindow = window as Window & {
  232. __zcodeSessionStoreE2E?: {
  233. getState: () => {
  234. workspaces?: Record<
  235. string,
  236. {
  237. taskMessagesByTaskId?: Record<string, RendererStoreRawMessage[]>;
  238. }
  239. >;
  240. };
  241. };
  242. };
  243. const storeApi = e2eWindow.__zcodeSessionStoreE2E;
  244. const rendererStore = (() => {
  245. if (!storeApi) {
  246. return {
  247. activeTaskId,
  248. available: false,
  249. messages: [],
  250. reason: "store-bridge-missing",
  251. };
  252. }
  253. const state = storeApi.getState();
  254. const readRecord = (value: unknown): Record<string, unknown> | null =>
  255. value && typeof value === "object" && !Array.isArray(value)
  256. ? (value as Record<string, unknown>)
  257. : null;
  258. const readString = (value: unknown): string | null =>
  259. typeof value === "string" ? value : null;
  260. const readRawToolError = (toolCall: RendererStoreRawToolCall) => {
  261. const raw = readRecord(toolCall.raw);
  262. const result = readRecord(raw?.result);
  263. const error = readRecord(raw?.error) ?? readRecord(result?.error);
  264. return {
  265. rawErrorDetail: readString(error?.detail),
  266. rawErrorMessage: readString(error?.message),
  267. };
  268. };
  269. const messages = Object.entries(state.workspaces ?? {}).flatMap(
  270. ([workspaceKey, workspace]) =>
  271. Object.entries(workspace.taskMessagesByTaskId ?? {}).flatMap(([taskId, taskMessages]) =>
  272. taskMessages.map((message) => ({
  273. content: message.content ?? "",
  274. id: message.id ?? null,
  275. partTypes: (message.parts ?? []).map((part) => part.type ?? ""),
  276. role: message.role ?? null,
  277. taskId,
  278. toolCalls: (message.toolCalls ?? []).map((toolCall) => {
  279. const rawError = readRawToolError(toolCall);
  280. return {
  281. error: toolCall.error ?? null,
  282. output: toolCall.output ?? null,
  283. rawErrorDetail: rawError.rawErrorDetail,
  284. rawErrorMessage: rawError.rawErrorMessage,
  285. status: toolCall.status ?? null,
  286. toolId: toolCall.toolId ?? null,
  287. toolName: toolCall.toolName ?? null,
  288. };
  289. }),
  290. workspaceKey,
  291. })),
  292. ),
  293. );
  294. return {
  295. activeTaskId,
  296. available: true,
  297. messages: activeTaskId
  298. ? messages.filter((message) => message.taskId === activeTaskId)
  299. : messages,
  300. reason: null,
  301. };
  302. })();
  303. return {
  304. assistantMessages,
  305. assistantHistory,
  306. blocks,
  307. chatState,
  308. matcher: expectedMatcher,
  309. matchedBlock,
  310. rendererStore,
  311. };
  312. },
  313. TID_CHAT_TOOL_CALL_BLOCK,
  314. TID_CHAT_MESSAGE_EDIT_BUTTON,
  315. TID_CHAT_MESSAGE_FORK_BUTTON,
  316. TID_CHAT_ASSISTANT_MESSAGE,
  317. TID_CHAT_VIEW,
  318. TID_CHAT_ASSISTANT_HISTORY_TRIGGER,
  319. TID_CHAT_ASSISTANT_HISTORY_CONTENT,
  320. TID_V4_SESSION_PANE,
  321. matcher,
  322. );
  323. }
  324. interface RendererStoreRawMessage {
  325. content?: string;
  326. id?: string;
  327. parts?: Array<{ type?: string }>;
  328. role?: string;
  329. toolCalls?: RendererStoreRawToolCall[];
  330. }
  331. interface RendererStoreRawToolCall {
  332. error?: string | null;
  333. output?: string | null;
  334. raw?: unknown;
  335. status?: string;
  336. toolId?: string;
  337. toolName?: string;
  338. }