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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import { mkdir, rm, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { TID_TOOL_SUMMARY_TRIGGER } from "@zcode/shared";
  4. import { clearAppData, seedSettings } from "../helpers/desktop-app.js";
  5. import { waitForUpstreamRequestContaining } from "../helpers/conversation-session-network.js";
  6. import { waitForToolCallBlockByToolName } from "../helpers/conversation-session-tool.js";
  7. import { expandAssistantHistoriesWithContent } from "../helpers/conversation-session-tool-diagnostics.js";
  8. import {
  9. ensureToolCrossProductFullAccessMode,
  10. respondToToolCrossProductBlockers,
  11. } from "../helpers/conversation-session-tool-cross-product.js";
  12. import { resolveE2ERuntimePath } from "../helpers/e2e-runtime-paths.js";
  13. import {
  14. E2E_REPLY_TOKEN,
  15. clickV4Stop,
  16. getV4PaneSnapshot,
  17. prepareV4ConversationE2E,
  18. sendV4Prompt,
  19. waitForV4AssistantMessageContaining,
  20. waitForV4Pane,
  21. waitForV4TimelineContaining,
  22. } from "../helpers/v4-conversation.js";
  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 Explore 工具详情折叠稳定性", () => {
  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 聚合 Explore 的详情展开与收起高度连续归零", 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. // 已进入折叠历史;先展开完成态历史,再判断 Explore,避免只在慢响应下通过。
  77. await expandAssistantHistoriesWithContent();
  78. const block = await waitForToolCallBlockByToolName("Explore", 30000);
  79. expect(block.exists).toBe(true);
  80. expect(block.toolName).toBe("Explore");
  81. await assertExploreToolDetailToggleStability();
  82. });
  83. });
  84. async function prepareReadFixture(): Promise<void> {
  85. await cleanupReadFixture();
  86. await mkdir(TOOL_DETAIL_RUNTIME_ROOT, { recursive: true });
  87. await Promise.all(
  88. TOOL_DETAIL_READ_FILES.map((filePath, index) =>
  89. writeFile(
  90. filePath,
  91. [
  92. `P08_READ_FILE_${index + 1}_CONTENT`,
  93. "This file is read by the P08 Explore toggle stability e2e.",
  94. "",
  95. ].join("\n"),
  96. "utf-8",
  97. ),
  98. ),
  99. );
  100. }
  101. async function cleanupReadFixture(): Promise<void> {
  102. await rm(TOOL_DETAIL_RUNTIME_ROOT, { recursive: true, force: true });
  103. }
  104. async function waitForToolTurnIdle(): Promise<void> {
  105. let latestState = "not-started";
  106. await browser.waitUntil(
  107. async () => {
  108. await respondToToolCrossProductBlockers();
  109. const snapshot = await getV4PaneSnapshot();
  110. latestState = JSON.stringify({
  111. canStop: snapshot.canStop,
  112. sessionId: snapshot.sessionId,
  113. });
  114. return !snapshot.canStop;
  115. },
  116. {
  117. timeout: TOOL_TURN_TIMEOUT_MS,
  118. timeoutMsg: `P08 Read 工具轮没有结束,latest=${latestState}`,
  119. },
  120. );
  121. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  122. }
  123. async function assertExploreToolDetailToggleStability(): Promise<void> {
  124. await expandAssistantHistoriesWithContent();
  125. await browser.waitUntil(
  126. () =>
  127. browser.execute(
  128. (summaryTriggerPrefix) =>
  129. Boolean(document.querySelector(`[data-testid^="${summaryTriggerPrefix}-explore:"]`)),
  130. TID_TOOL_SUMMARY_TRIGGER,
  131. ),
  132. {
  133. timeout: 10000,
  134. timeoutMsg: "P08 连续 Read 工具没有聚合为可展开的 Explore 详情",
  135. },
  136. );
  137. const opening = await probeLatestExploreToolDetailToggle(true);
  138. assertExploreToolDetailToggleProbe(opening);
  139. const closing = await probeLatestExploreToolDetailToggle(false);
  140. assertExploreToolDetailToggleProbe(closing);
  141. }
  142. function probeLatestExploreToolDetailToggle(targetOpen: boolean): Promise<ToolDetailToggleProbe> {
  143. return browser.executeAsync(
  144. (summaryTriggerPrefix, shouldOpen, done) => {
  145. const trigger = Array.from(
  146. document.querySelectorAll<HTMLElement>(`[data-testid^="${summaryTriggerPrefix}-explore:"]`),
  147. ).at(-1);
  148. const shell = trigger?.closest<HTMLElement>('[data-slot="collapsible"]');
  149. if (!trigger || !shell) {
  150. done({
  151. error: "explore-toggle-elements-missing",
  152. samples: [],
  153. targetOpen: shouldOpen,
  154. });
  155. return;
  156. }
  157. const readSample = (): ToolDetailToggleSample => {
  158. const content = Array.from(shell.children).find(
  159. (child): child is HTMLElement =>
  160. child instanceof HTMLElement && child.dataset.slot === "collapsible-content",
  161. );
  162. const contentStyle = content ? window.getComputedStyle(content) : null;
  163. return {
  164. contentDisplay: contentStyle?.display ?? "none",
  165. contentExists: content !== undefined,
  166. contentHeight: content?.getBoundingClientRect().height ?? 0,
  167. contentHidden: content?.hasAttribute("hidden") ?? true,
  168. expanded: trigger.getAttribute("aria-expanded") === "true",
  169. shellHeight: shell.getBoundingClientRect().height,
  170. time: performance.now(),
  171. };
  172. };
  173. const samples = [readSample()];
  174. if (samples[0]?.expanded === shouldOpen) {
  175. done({
  176. error: "explore-toggle-already-at-target",
  177. samples,
  178. targetOpen: shouldOpen,
  179. });
  180. return;
  181. }
  182. trigger.click();
  183. const startedAt = performance.now();
  184. const sampleAnimation = () => {
  185. const current = readSample();
  186. samples.push(current);
  187. const elapsed = performance.now() - startedAt;
  188. const settled = shouldOpen
  189. ? current.expanded &&
  190. current.contentExists &&
  191. !current.contentHidden &&
  192. current.contentDisplay !== "none" &&
  193. current.contentHeight > 0
  194. : !current.expanded &&
  195. (!current.contentExists || current.contentHidden || current.contentDisplay === "none");
  196. if (elapsed >= 450 && settled) {
  197. done({ samples, targetOpen: shouldOpen });
  198. return;
  199. }
  200. if (elapsed >= 1200) {
  201. done({
  202. error: "explore-toggle-animation-not-settled",
  203. samples,
  204. targetOpen: shouldOpen,
  205. });
  206. return;
  207. }
  208. requestAnimationFrame(sampleAnimation);
  209. };
  210. requestAnimationFrame(sampleAnimation);
  211. },
  212. TID_TOOL_SUMMARY_TRIGGER,
  213. targetOpen,
  214. ) as Promise<ToolDetailToggleProbe>;
  215. }
  216. function assertExploreToolDetailToggleProbe(probe: ToolDetailToggleProbe): void {
  217. if (probe.error || probe.samples.length < 10) {
  218. throw new Error(`P08 Explore 折叠采样不完整: ${JSON.stringify(probe)}`);
  219. }
  220. const samples = probe.samples;
  221. const finalSample = samples.at(-1)!;
  222. if (finalSample.expanded !== probe.targetOpen) {
  223. throw new Error(`P08 Explore 折叠终态不正确: ${JSON.stringify(probe)}`);
  224. }
  225. const reversals = samples.flatMap((sample, index) => {
  226. const previous = samples[index - 1];
  227. if (!previous) return [];
  228. const reversed = probe.targetOpen
  229. ? sample.contentHeight + TOOL_DETAIL_TOGGLE_EPSILON_PX < previous.contentHeight
  230. : sample.contentHeight - TOOL_DETAIL_TOGGLE_EPSILON_PX > previous.contentHeight;
  231. return reversed
  232. ? [
  233. {
  234. index,
  235. previous: previous.contentHeight,
  236. value: sample.contentHeight,
  237. },
  238. ]
  239. : [];
  240. });
  241. if (reversals.length > 0) {
  242. throw new Error(`P08 Explore 折叠高度方向反转: ${JSON.stringify({ reversals, probe })}`);
  243. }
  244. if (!probe.targetOpen) {
  245. const firstHiddenIndex = samples.findIndex(
  246. (sample, index) =>
  247. index > 0 &&
  248. (!sample.contentExists || sample.contentHidden || sample.contentDisplay === "none"),
  249. );
  250. const lastVisible = firstHiddenIndex <= 0 ? undefined : samples[firstHiddenIndex - 1];
  251. const firstHidden = firstHiddenIndex < 0 ? undefined : samples[firstHiddenIndex];
  252. const finalHeightJump =
  253. lastVisible === undefined || firstHidden === undefined
  254. ? Number.POSITIVE_INFINITY
  255. : Math.abs(firstHidden.shellHeight - lastVisible.shellHeight);
  256. if (
  257. lastVisible === undefined ||
  258. lastVisible.contentHeight > TOOL_DETAIL_TOGGLE_EPSILON_PX ||
  259. finalHeightJump > TOOL_DETAIL_TOGGLE_EPSILON_PX
  260. ) {
  261. throw new Error(
  262. `P08 Explore 收起仍有尾部间距跳变: ${JSON.stringify({ finalHeightJump, lastVisible, probe })}`,
  263. );
  264. }
  265. }
  266. }
  267. async function stopIfBusy(): Promise<void> {
  268. const snapshot = await getV4PaneSnapshot();
  269. if (!snapshot.canStop) {
  270. return;
  271. }
  272. await clickV4Stop();
  273. await waitForV4Pane(
  274. (nextSnapshot) => !nextSnapshot.canStop,
  275. "P08 afterEach stop 后没有退出 streaming",
  276. 30000,
  277. );
  278. }