conversation-session-edit.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import {
  2. TID_CHAT_ASSISTANT_MESSAGE,
  3. TID_CHAT_MESSAGE_EDIT_BUTTON,
  4. TID_CHAT_MESSAGE_EDIT_INPUT,
  5. TID_CHAT_MESSAGE_EDIT_SUBMIT,
  6. TID_CHAT_USER_MESSAGE,
  7. testId,
  8. } from "@zcode/shared/test-ids";
  9. import { clickTestIdByDom } from "./desktop-app.js";
  10. export interface EditButtonSnapshot {
  11. ariaDisabled: boolean;
  12. disabled: boolean;
  13. exists: boolean;
  14. messageId: string;
  15. testId: string;
  16. text: string;
  17. }
  18. type LexicalInputE2EBridge = {
  19. focus: () => void;
  20. getText: () => string;
  21. setText: (text: string) => void;
  22. };
  23. type LexicalInputE2EElement = HTMLElement & {
  24. __zcodeLexicalInputE2E?: LexicalInputE2EBridge;
  25. };
  26. export async function waitForEditButtonForUserContaining(
  27. text: string,
  28. options: { enabled?: boolean } = {},
  29. ): Promise<EditButtonSnapshot> {
  30. const expectEnabled = options.enabled ?? true;
  31. let latest: EditButtonSnapshot | null = null;
  32. try {
  33. await browser.waitUntil(
  34. async () => {
  35. latest = await getEditButtonForUserContaining(text);
  36. if (!latest?.exists) {
  37. return false;
  38. }
  39. if (!expectEnabled) {
  40. return true;
  41. }
  42. return !latest.disabled && !latest.ariaDisabled;
  43. },
  44. {
  45. timeout: 30000,
  46. timeoutMsg: `user 消息没有出现可用 edit 按钮: ${text}`,
  47. }
  48. );
  49. } catch (error) {
  50. latest = await getEditButtonForUserContaining(text);
  51. throw new Error(
  52. `user 消息没有出现可用 edit 按钮: ${text}; latest=${JSON.stringify(latest)}`,
  53. { cause: error },
  54. );
  55. }
  56. if (!latest) {
  57. throw new Error(`user edit 按钮在等待后仍不存在: ${text}`);
  58. }
  59. return latest;
  60. }
  61. async function waitForStableEditButtonForUserContaining(
  62. text: string,
  63. options: { enabled?: boolean } = {},
  64. ): Promise<EditButtonSnapshot> {
  65. const expectEnabled = options.enabled ?? true;
  66. const startedAt = Date.now();
  67. let latest: EditButtonSnapshot | null = null;
  68. while (Date.now() - startedAt < 30000) {
  69. const first = await getEditButtonForUserContaining(text);
  70. if (
  71. first?.exists &&
  72. (!expectEnabled || (!first.disabled && !first.ariaDisabled))
  73. ) {
  74. await browser.pause(250);
  75. const second = await getEditButtonForUserContaining(text);
  76. if (
  77. second?.exists &&
  78. second.messageId === first.messageId &&
  79. second.testId === first.testId &&
  80. (!expectEnabled || (!second.disabled && !second.ariaDisabled))
  81. ) {
  82. return second;
  83. }
  84. latest = second;
  85. } else {
  86. latest = first;
  87. }
  88. await browser.pause(100);
  89. }
  90. throw new Error(
  91. `user 消息 edit 按钮没有稳定下来: ${text}; latest=${JSON.stringify(latest)}`,
  92. );
  93. }
  94. export async function clickEditButtonForUserContaining(text: string) {
  95. const button = await waitForStableEditButtonForUserContaining(text, {
  96. enabled: true,
  97. });
  98. await clickTestIdByDom(button.testId, {
  99. timeout: 15000,
  100. timeoutMsg: `user edit 按钮不可点击: ${text}`,
  101. });
  102. return button;
  103. }
  104. export async function editUserMessageContaining(
  105. currentText: string,
  106. nextText: string,
  107. ) {
  108. let lastError: unknown = null;
  109. for (let attempt = 0; attempt < 3; attempt += 1) {
  110. const button = await clickEditButtonForUserContaining(currentText);
  111. try {
  112. await setMessageEditInputText(button.messageId, nextText);
  113. await clickTestIdByDom(
  114. testId(TID_CHAT_MESSAGE_EDIT_SUBMIT, button.messageId),
  115. {
  116. timeout: 15000,
  117. timeoutMsg: `user edit 提交按钮不可点击: ${button.messageId}`,
  118. },
  119. );
  120. return button;
  121. } catch (error) {
  122. lastError = error;
  123. // 修复原因:完成态最后一轮可能刚从 optimistic renderer id 切到快照 id。
  124. // 这时 edit 输入框会随着旧消息节点卸载;重新定位用户看见的同一条消息再编辑。
  125. if (!(error instanceof Error) || !isRetryableEditInputError(error)) {
  126. throw error;
  127. }
  128. }
  129. }
  130. throw lastError instanceof Error
  131. ? lastError
  132. : new Error(`user edit 重试失败: ${currentText}`);
  133. }
  134. function isRetryableEditInputError(error: Error) {
  135. return (
  136. error.message.includes("input-missing") ||
  137. // Bugfix: Windows Electron 下 edit button 点击后,旧 optimistic message id 对应的
  138. // 输入框可能已挂载但还未显示;重新定位用户可见消息后再点一次更稳定。
  139. error.message.includes("edit 输入框没有显示")
  140. );
  141. }
  142. export function getEditButtonForUserContaining(
  143. text: string,
  144. ): Promise<EditButtonSnapshot | null> {
  145. return getEditButtonForMessageContaining(TID_CHAT_USER_MESSAGE, text);
  146. }
  147. export function getEditButtonForAssistantContaining(
  148. text: string,
  149. ): Promise<EditButtonSnapshot | null> {
  150. return getEditButtonForMessageContaining(TID_CHAT_ASSISTANT_MESSAGE, text);
  151. }
  152. export async function setMessageEditInputText(messageId: string, text: string) {
  153. const inputTestId = testId(TID_CHAT_MESSAGE_EDIT_INPUT, messageId);
  154. await setLexicalInputTextByTestId(inputTestId, text);
  155. }
  156. async function setLexicalInputTextByTestId(testIdValue: string, text: string) {
  157. await browser.waitUntil(
  158. async () =>
  159. browser.execute((inputTestId) => {
  160. return Boolean(document.querySelector(`[data-testid="${inputTestId}"]`));
  161. }, testIdValue),
  162. {
  163. timeout: 15000,
  164. timeoutMsg: `edit 输入框没有出现: ${testIdValue}`,
  165. },
  166. );
  167. const inputElement = await $(`[data-testid="${testIdValue}"]`);
  168. await inputElement.waitForDisplayed({
  169. timeout: 15000,
  170. timeoutMsg: `edit 输入框没有显示: ${testIdValue}`,
  171. });
  172. await waitForEditInputInitializers(testIdValue);
  173. let actual = "";
  174. for (let attempt = 0; attempt < 5; attempt += 1) {
  175. const result = await replaceContentEditableTextByDom(testIdValue, text);
  176. actual = result.actual;
  177. if (result.ok) {
  178. return;
  179. }
  180. await waitForEditInputInitializers(testIdValue);
  181. }
  182. throw new Error(
  183. `edit 输入框没有写入完整 prompt: expected=${text}, actual=${actual}`,
  184. );
  185. }
  186. function getEditInputDiagnostics(testIdValue: string) {
  187. return browser.execute((inputTestId) => {
  188. const input = document.querySelector<HTMLElement>(
  189. `[data-testid="${inputTestId}"]`,
  190. );
  191. const nearby = Array.from(
  192. document.querySelectorAll<HTMLElement>(
  193. `[data-testid^="chat-message-edit-input-"]`,
  194. ),
  195. ).map((element) => ({
  196. bridgeAttr: element.getAttribute("data-e2e-lexical-bridge"),
  197. contentEditable: element.getAttribute("contenteditable"),
  198. testId: element.getAttribute("data-testid"),
  199. text: (element.innerText ?? element.textContent ?? "").slice(0, 80),
  200. }));
  201. return {
  202. bridgeAttr: input?.getAttribute("data-e2e-lexical-bridge") ?? null,
  203. bridgeProperty: Boolean(
  204. (input as LexicalInputE2EElement | null)?.__zcodeLexicalInputE2E,
  205. ),
  206. contentEditable: input?.getAttribute("contenteditable") ?? null,
  207. exists: Boolean(input),
  208. nearby,
  209. tagName: input?.tagName ?? null,
  210. text: (input?.innerText ?? input?.textContent ?? "").slice(0, 120),
  211. };
  212. }, testIdValue);
  213. }
  214. async function waitForEditInputInitializers(testIdValue: string) {
  215. await browser.executeAsync((inputTestId, done) => {
  216. const input = document.querySelector<LexicalInputE2EElement>(
  217. `[data-testid="${inputTestId}"]`,
  218. );
  219. input?.__zcodeLexicalInputE2E?.focus();
  220. // 修复原因:UserMessage 和 ChatPromptEditor 都会在 RAF 回填 initialValue。
  221. // 等两帧后再模拟用户输入,避免刚写入的新文本被初始化回填覆盖。
  222. requestAnimationFrame(() => {
  223. requestAnimationFrame(() => {
  224. done(null);
  225. });
  226. });
  227. }, testIdValue);
  228. }
  229. async function replaceContentEditableTextByDom(testIdValue: string, text: string) {
  230. const result = (await browser.executeAsync(
  231. (inputTestId, nextText, done) => {
  232. const input = document.querySelector<LexicalInputE2EElement>(
  233. `[data-testid="${inputTestId}"]`,
  234. );
  235. if (!input) {
  236. done({ actual: "", ok: false, reason: "input-missing" });
  237. return;
  238. }
  239. const readActualText = () => {
  240. const latestInput = document.querySelector<LexicalInputE2EElement>(
  241. `[data-testid="${inputTestId}"]`,
  242. );
  243. const latestBridge = latestInput?.__zcodeLexicalInputE2E;
  244. return (
  245. latestBridge?.getText() ??
  246. latestInput?.innerText ??
  247. latestInput?.textContent ??
  248. ""
  249. )
  250. .replace(/\u00a0/g, " ")
  251. .trim();
  252. };
  253. const bridge = input.__zcodeLexicalInputE2E;
  254. if (bridge) {
  255. bridge.focus();
  256. bridge.setText("");
  257. // 修复原因:Lexical 对 contenteditable 的 selection/delete 接管较强,
  258. // DOM execCommand 只能把新文本插到旧内容前面。测试 bridge 模拟的是
  259. // 编辑器自身更新路径,先清空再写入才能得到用户真实提交的 prompt。
  260. requestAnimationFrame(() => {
  261. const latestInput = document.querySelector<LexicalInputE2EElement>(
  262. `[data-testid="${inputTestId}"]`,
  263. );
  264. const latestBridge = latestInput?.__zcodeLexicalInputE2E;
  265. if (!latestBridge) {
  266. done({
  267. actual: "",
  268. ok: false,
  269. reason: "bridge-missing-after-clear",
  270. });
  271. return;
  272. }
  273. latestBridge.setText(nextText);
  274. requestAnimationFrame(() => {
  275. requestAnimationFrame(() => {
  276. const actual = readActualText();
  277. done({
  278. actual,
  279. inserted: true,
  280. ok: actual === nextText.trim(),
  281. via: "bridge",
  282. });
  283. });
  284. });
  285. });
  286. return;
  287. }
  288. input.focus();
  289. const selection = window.getSelection();
  290. const range = document.createRange();
  291. range.selectNodeContents(input);
  292. selection?.removeAllRanges();
  293. selection?.addRange(range);
  294. document.execCommand("delete");
  295. let inserted = true;
  296. const lines = nextText.split("\n");
  297. for (const [lineIndex, line] of lines.entries()) {
  298. inserted = document.execCommand("insertText", false, line) && inserted;
  299. if (lineIndex < lines.length - 1) {
  300. inserted = document.execCommand("insertLineBreak") && inserted;
  301. }
  302. }
  303. // 修复原因:edit 输入框打开后会经历 initialValue 回填和 Lexical state 同步。
  304. // 这里用 contenteditable 的真实编辑命令驱动,避免直接改 React state 绕过 UI 行为。
  305. requestAnimationFrame(() => {
  306. requestAnimationFrame(() => {
  307. const actual = readActualText();
  308. done({ actual, inserted, ok: actual === nextText.trim(), via: "dom" });
  309. });
  310. });
  311. },
  312. testIdValue,
  313. text,
  314. )) as {
  315. actual: string;
  316. inserted?: boolean;
  317. ok: boolean;
  318. reason?: string;
  319. via?: "bridge" | "dom";
  320. };
  321. if (!result.ok && result.reason === "input-missing") {
  322. const diagnostics = await getEditInputDiagnostics(testIdValue);
  323. return {
  324. ...result,
  325. actual: `${result.actual}; reason=${result.reason}; diagnostics=${JSON.stringify(diagnostics)}`,
  326. };
  327. }
  328. return result;
  329. }
  330. function getEditButtonForMessageContaining(
  331. messagePrefix: string,
  332. text: string,
  333. ): Promise<EditButtonSnapshot | null> {
  334. return browser.execute(
  335. (targetMessagePrefix, editButtonPrefix, expectedText) => {
  336. const messages = Array.from(
  337. document.querySelectorAll<HTMLElement>(
  338. `[data-testid^="${targetMessagePrefix}-"]`,
  339. ),
  340. );
  341. const message = messages.find((element) =>
  342. element.innerText.replace(/\u00a0/g, " ").includes(expectedText),
  343. );
  344. const messageId = message?.getAttribute("data-message-id");
  345. if (!message || !messageId) {
  346. return null;
  347. }
  348. const button = Array.from(
  349. document.querySelectorAll<HTMLButtonElement>(
  350. `[data-testid^="${editButtonPrefix}-"]`,
  351. ),
  352. ).find((candidate) => candidate.getAttribute("data-message-id") === messageId);
  353. const resolvedTestId =
  354. button?.getAttribute("data-testid") ?? `${editButtonPrefix}-${messageId}`;
  355. return {
  356. ariaDisabled: button?.getAttribute("aria-disabled") === "true",
  357. disabled: button?.disabled ?? false,
  358. exists: Boolean(button),
  359. messageId,
  360. testId: resolvedTestId,
  361. text: button?.innerText.trim() ?? "",
  362. };
  363. },
  364. messagePrefix,
  365. TID_CHAT_MESSAGE_EDIT_BUTTON,
  366. text,
  367. );
  368. }