conversation-session-tool-detail-toggle-stability.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import { mkdir, rm, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { TID_TOOL_SUMMARY_TRIGGER } from "@zcode/shared/test-ids";
  4. import { clearAppData, seedSettings } from "#e2e/helpers/desktop-app";
  5. import { waitForUpstreamRequestContaining } from "#e2e/helpers/conversation-session-network";
  6. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  7. import { expandAssistantHistoriesWithContent } from "#e2e/helpers/conversation-session-tool-diagnostics";
  8. import {
  9. ensureToolCrossProductFullAccessMode,
  10. respondToToolCrossProductBlockers,
  11. } from "#e2e/helpers/conversation-session-tool-cross-product";
  12. import { resolveE2ERuntimePath } from "#e2e/helpers/e2e-runtime-paths";
  13. import {
  14. E2E_REPLY_TOKEN,
  15. clickV4Stop,
  16. getV4PaneSnapshot,
  17. prepareV4ConversationE2E,
  18. sendV4Prompt,
  19. waitForV4AssistantMessageContaining,
  20. waitForV4Pane,
  21. waitForV4TimelineContaining,
  22. } from "#e2e/helpers/v4-conversation";
  23. const CASE_MARKER = "E2E_TOOL_DETAIL_TOGGLE_READ";
  24. const TOOL_TURN_TIMEOUT_MS = 150000;
  25. const TOOL_DETAIL_TOGGLE_EPSILON_PX = 2;
  26. const TOOL_DETAIL_RUNTIME_ROOT = resolveE2ERuntimePath(
  27. "conversation-session-tool-detail-toggle-stability",
  28. );
  29. const TOOL_DETAIL_READ_FILES = [
  30. join(TOOL_DETAIL_RUNTIME_ROOT, "read-fixture-a.txt"),
  31. join(TOOL_DETAIL_RUNTIME_ROOT, "read-fixture-b.txt"),
  32. ] as const;
  33. interface ToolDetailToggleSample {
  34. contentDisplay: string;
  35. contentExists: boolean;
  36. contentHeight: number;
  37. contentHidden: boolean;
  38. expanded: boolean;
  39. shellHeight: number;
  40. time: number;
  41. }
  42. interface ToolDetailToggleProbe {
  43. error?: string;
  44. samples: ToolDetailToggleSample[];
  45. targetOpen: boolean;
  46. }
  47. describe("P08 摘要组折叠与 Read 行稳定性", () => {
  48. before(async function () {
  49. this.timeout(TOOL_TURN_TIMEOUT_MS);
  50. await seedSettings({ messageStreamShowTodos: true });
  51. await prepareV4ConversationE2E();
  52. });
  53. afterEach(async () => {
  54. await stopIfBusy();
  55. await cleanupReadFixture();
  56. });
  57. after(async () => {
  58. await cleanupReadFixture();
  59. await browser.electron.restoreAllMocks();
  60. await clearAppData();
  61. });
  62. it("连续 Read 摘要组展开收起高度连续归零且 Read 不创建详情", async function () {
  63. this.timeout(TOOL_TURN_TIMEOUT_MS);
  64. await prepareReadFixture();
  65. await ensureToolCrossProductFullAccessMode();
  66. const prompt = [
  67. `${CASE_MARKER}_${Date.now()}:`,
  68. `Read ${TOOL_DETAIL_READ_FILES[0]} and ${TOOL_DETAIL_READ_FILES[1]}.`,
  69. `Then reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`,
  70. ].join(" ");
  71. await sendV4Prompt(prompt);
  72. await waitForV4TimelineContaining(CASE_MARKER);
  73. await waitForUpstreamRequestContaining(CASE_MARKER);
  74. await waitForToolTurnIdle();
  75. // 修复原因:正式 v4 replay 可能在下一条 DOM 断言前已完成整轮,工具块此时
  76. // 已进入折叠历史;先展开完成态历史,再访问真实 Read,避免只在慢响应下通过。
  77. await expandAssistantHistoriesWithContent();
  78. const groupTrigger = await $("[data-summary-group-trigger]");
  79. await groupTrigger.waitForDisplayed();
  80. await expect(groupTrigger).toHaveAttribute("aria-expanded", "false");
  81. assertExploreToolDetailToggleProbe(
  82. await probeLatestExploreToolDetailToggle(true, "[data-summary-group-trigger]"),
  83. );
  84. assertExploreToolDetailToggleProbe(
  85. await probeLatestExploreToolDetailToggle(false, "[data-summary-group-trigger]"),
  86. );
  87. const block = await waitForToolCallBlockByToolName("Read", 30000);
  88. expect(block.exists).toBe(true);
  89. expect(block.toolName).toBe("Read");
  90. // Read 当前仅显示文件摘要(canToggle=false);不应沿用旧 Explore 的详情折叠断言。
  91. const readTrigger = await $('[data-tool-name="Read"] [data-testid^="tool-summary-trigger-"]');
  92. await expect(readTrigger).not.toHaveAttribute("aria-expanded");
  93. expect((await $$('[data-tool-name="Read"]')).length).toBe(2);
  94. });
  95. });
  96. async function prepareReadFixture(): Promise<void> {
  97. await cleanupReadFixture();
  98. await mkdir(TOOL_DETAIL_RUNTIME_ROOT, { recursive: true });
  99. await Promise.all(
  100. TOOL_DETAIL_READ_FILES.map((filePath, index) =>
  101. writeFile(
  102. filePath,
  103. [
  104. `P08_READ_FILE_${index + 1}_CONTENT`,
  105. "This file is read by the P08 Explore toggle stability e2e.",
  106. "",
  107. ].join("\n"),
  108. "utf-8",
  109. ),
  110. ),
  111. );
  112. }
  113. async function cleanupReadFixture(): Promise<void> {
  114. await rm(TOOL_DETAIL_RUNTIME_ROOT, { recursive: true, force: true });
  115. }
  116. async function waitForToolTurnIdle(): Promise<void> {
  117. let latestState = "not-started";
  118. await browser.waitUntil(
  119. async () => {
  120. await respondToToolCrossProductBlockers();
  121. const snapshot = await getV4PaneSnapshot();
  122. latestState = JSON.stringify({
  123. canStop: snapshot.canStop,
  124. sessionId: snapshot.sessionId,
  125. });
  126. return !snapshot.canStop;
  127. },
  128. {
  129. timeout: TOOL_TURN_TIMEOUT_MS,
  130. timeoutMsg: `P08 Read 工具轮没有结束,latest=${latestState}`,
  131. },
  132. );
  133. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  134. }
  135. function probeLatestExploreToolDetailToggle(
  136. targetOpen: boolean,
  137. selector = `[data-tool-name="Read"] [data-testid^="${TID_TOOL_SUMMARY_TRIGGER}-"]`,
  138. ): Promise<ToolDetailToggleProbe> {
  139. return browser.executeAsync(
  140. (triggerSelector, shouldOpen, done) => {
  141. const trigger = Array.from(document.querySelectorAll<HTMLElement>(triggerSelector)).at(-1);
  142. const shell = trigger?.closest<HTMLElement>('[data-slot="collapsible"]');
  143. if (!trigger || !shell) {
  144. done({
  145. error: "explore-toggle-elements-missing",
  146. samples: [],
  147. targetOpen: shouldOpen,
  148. });
  149. return;
  150. }
  151. const readSample = (): ToolDetailToggleSample => {
  152. const content = Array.from(shell.children).find(
  153. (child): child is HTMLElement =>
  154. child instanceof HTMLElement && child.dataset.slot === "collapsible-content",
  155. );
  156. const contentStyle = content ? window.getComputedStyle(content) : null;
  157. return {
  158. contentDisplay: contentStyle?.display ?? "none",
  159. contentExists: content !== undefined,
  160. contentHeight: content?.getBoundingClientRect().height ?? 0,
  161. contentHidden: content?.hasAttribute("hidden") ?? true,
  162. expanded: trigger.getAttribute("aria-expanded") === "true",
  163. shellHeight: shell.getBoundingClientRect().height,
  164. time: performance.now(),
  165. };
  166. };
  167. const samples = [readSample()];
  168. if (samples[0]?.expanded === shouldOpen) {
  169. done({
  170. error: "explore-toggle-already-at-target",
  171. samples,
  172. targetOpen: shouldOpen,
  173. });
  174. return;
  175. }
  176. trigger.click();
  177. const startedAt = performance.now();
  178. const sampleAnimation = () => {
  179. const current = readSample();
  180. samples.push(current);
  181. const elapsed = performance.now() - startedAt;
  182. const settled = shouldOpen
  183. ? current.expanded &&
  184. current.contentExists &&
  185. !current.contentHidden &&
  186. current.contentDisplay !== "none" &&
  187. current.contentHeight > 0
  188. : !current.expanded &&
  189. (!current.contentExists || current.contentHidden || current.contentDisplay === "none");
  190. if (elapsed >= 450 && settled) {
  191. done({ samples, targetOpen: shouldOpen });
  192. return;
  193. }
  194. if (elapsed >= 1200) {
  195. done({
  196. error: "explore-toggle-animation-not-settled",
  197. samples,
  198. targetOpen: shouldOpen,
  199. });
  200. return;
  201. }
  202. requestAnimationFrame(sampleAnimation);
  203. };
  204. requestAnimationFrame(sampleAnimation);
  205. },
  206. selector,
  207. targetOpen,
  208. ) as Promise<ToolDetailToggleProbe>;
  209. }
  210. function assertExploreToolDetailToggleProbe(probe: ToolDetailToggleProbe): void {
  211. if (probe.error || probe.samples.length < 10) {
  212. throw new Error(`P08 Explore 折叠采样不完整: ${JSON.stringify(probe)}`);
  213. }
  214. const samples = probe.samples;
  215. const finalSample = samples.at(-1)!;
  216. if (finalSample.expanded !== probe.targetOpen) {
  217. throw new Error(`P08 Explore 折叠终态不正确: ${JSON.stringify(probe)}`);
  218. }
  219. const reversals = samples.flatMap((sample, index) => {
  220. const previous = samples[index - 1];
  221. if (!previous) return [];
  222. const reversed = probe.targetOpen
  223. ? sample.contentHeight + TOOL_DETAIL_TOGGLE_EPSILON_PX < previous.contentHeight
  224. : sample.contentHeight - TOOL_DETAIL_TOGGLE_EPSILON_PX > previous.contentHeight;
  225. return reversed
  226. ? [
  227. {
  228. index,
  229. previous: previous.contentHeight,
  230. value: sample.contentHeight,
  231. },
  232. ]
  233. : [];
  234. });
  235. if (reversals.length > 0) {
  236. throw new Error(`P08 Explore 折叠高度方向反转: ${JSON.stringify({ reversals, probe })}`);
  237. }
  238. if (!probe.targetOpen) {
  239. const firstHiddenIndex = samples.findIndex(
  240. (sample, index) =>
  241. index > 0 &&
  242. (!sample.contentExists || sample.contentHidden || sample.contentDisplay === "none"),
  243. );
  244. const lastVisible = firstHiddenIndex <= 0 ? undefined : samples[firstHiddenIndex - 1];
  245. const firstHidden = firstHiddenIndex < 0 ? undefined : samples[firstHiddenIndex];
  246. const finalHeightJump =
  247. lastVisible === undefined || firstHidden === undefined
  248. ? Number.POSITIVE_INFINITY
  249. : Math.abs(firstHidden.shellHeight - lastVisible.shellHeight);
  250. if (
  251. lastVisible === undefined ||
  252. lastVisible.contentHeight > TOOL_DETAIL_TOGGLE_EPSILON_PX ||
  253. finalHeightJump > TOOL_DETAIL_TOGGLE_EPSILON_PX
  254. ) {
  255. throw new Error(
  256. `P08 Explore 收起仍有尾部间距跳变: ${JSON.stringify({ finalHeightJump, lastVisible, probe })}`,
  257. );
  258. }
  259. }
  260. }
  261. async function stopIfBusy(): Promise<void> {
  262. const snapshot = await getV4PaneSnapshot();
  263. if (!snapshot.canStop) {
  264. return;
  265. }
  266. await clickV4Stop();
  267. await waitForV4Pane(
  268. (nextSnapshot) => !nextSnapshot.canStop,
  269. "P08 afterEach stop 后没有退出 streaming",
  270. 30000,
  271. );
  272. }