conversation-session-tool-diagnostics.ts 11 KB

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