conversation-session-tool-diagnostics.ts 12 KB

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