conversation-session.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. /* eslint-disable max-lines -- conversation e2e 聚合 helper 需要集中导出通用会话操作,过度拆分会让测试步骤更难读 */
  2. import {
  3. TID_CHAT_ASSISTANT_MESSAGE,
  4. TID_CHAT_INPUT,
  5. TID_CHAT_MESSAGES,
  6. TID_CHAT_SEND_BUTTON,
  7. TID_CHAT_SUMMARY_PANEL,
  8. TID_CHAT_STOP_BUTTON,
  9. TID_CHAT_USER_MESSAGE,
  10. TID_CHAT_VIEW,
  11. TID_LOGIN_API_KEY_CONTINUE_BUTTON,
  12. TID_LOGIN_API_KEY_INPUT,
  13. TID_LOGIN_USE_API_KEY_BUTTON,
  14. TID_TASK_ITEM,
  15. TID_TASK_NEW_BUTTON,
  16. TID_V4_COMPOSER_INPUT,
  17. TID_V4_COMPOSER_SEND,
  18. TID_V4_QUEUE_ITEM,
  19. TID_V4_SESSION_PANE,
  20. TID_V4_STOP,
  21. TID_V4_TIMELINE,
  22. testId,
  23. } from "@zcode/shared/test-ids";
  24. import AppPage from "../pages/app.page.js";
  25. import {
  26. clickTestIdByDom,
  27. setInputValueByTestIdDom,
  28. waitForDefaultWorkspaceReady,
  29. } from "./desktop-app.js";
  30. import { ensureUpstreamProviderForE2E } from "./upstream-provider.js";
  31. import { getQueueItems as readQueueItemsForDiagnostics } from "./conversation-session-queue.js";
  32. import { getTaskStoreSnapshot as readTaskStoreSnapshotForDiagnostics } from "./conversation-session-store.js";
  33. import { readV4ChatRootSnapshotInBrowser } from "./conversation-session-chat-root-snapshot-script.js";
  34. import {
  35. E2E_READONLY_TOOL_FILE_CONTENT,
  36. E2E_READONLY_TOOL_FILE_PATH,
  37. buildReadonlyToolPrompt,
  38. ensureReadonlyToolFixtureFile,
  39. } from "./conversation-session-readonly-tool.js";
  40. type LexicalInputE2EBridge = {
  41. focus: () => void;
  42. getText: () => string;
  43. setText: (text: string) => void;
  44. };
  45. type LexicalInputE2EElement = HTMLElement & {
  46. __zcodeLexicalInputE2E?: LexicalInputE2EBridge;
  47. };
  48. export const E2E_REPLY_TOKEN = "upstream-e2e-ok";
  49. export const LOGIN_API_KEY = "e2e-login-api-key";
  50. export {
  51. E2E_READONLY_TOOL_FILE_CONTENT,
  52. E2E_READONLY_TOOL_FILE_PATH,
  53. buildReadonlyToolPrompt,
  54. ensureReadonlyToolFixtureFile,
  55. };
  56. export {
  57. getCompactMarkers,
  58. waitForCompactMarkerStatuses,
  59. waitForCompactMarkerStatus,
  60. } from "./conversation-session-compact.js";
  61. export type { CompactMarkerSnapshot } from "./conversation-session-compact.js";
  62. export {
  63. setComposerPrefill,
  64. waitForVisibleAttachmentNames,
  65. writeComposerPrefillPngFixture,
  66. writeOversizedComposerPrefillPngFixture,
  67. } from "./conversation-session-composer-prefill.js";
  68. export type { ComposerPrefillExpectation } from "./conversation-session-composer-prefill.js";
  69. export {
  70. clickForkButtonForAssistantContaining,
  71. getForkButtonForAssistantContaining,
  72. getForkButtonForUserContaining,
  73. waitForForkButtonForAssistantContaining,
  74. } from "./conversation-session-fork.js";
  75. export {
  76. clickEditButtonForUserContaining,
  77. editUserMessageContaining,
  78. getEditButtonForAssistantContaining,
  79. getEditButtonForUserContaining,
  80. setMessageEditInputText,
  81. waitForEditButtonForUserContaining,
  82. } from "./conversation-session-edit.js";
  83. export {
  84. countUpstreamRequests,
  85. countUpstreamRequestsContaining,
  86. countUpstreamRequestsContainingAll,
  87. countUpstreamTitleRequestsContaining,
  88. expectNoUpstreamRequestForTextWithin,
  89. findFirstUpstreamRequestIndex,
  90. findLastUpstreamRequestIndex,
  91. getUpstreamRequestRecordCount,
  92. waitForUpstreamRequest,
  93. waitForUpstreamRequestContaining,
  94. } from "./conversation-session-network.js";
  95. export type { UpstreamRequestQuery } from "./conversation-session-network.js";
  96. export type { QueueItemSnapshot } from "./conversation-session-queue.js";
  97. export {
  98. clickFirstQueueSendNow,
  99. clickQueueSendNow,
  100. clickQueueEdit,
  101. clickQueueEditSave,
  102. clickQueueRemove,
  103. dragQueueItemOnto,
  104. getQueueItems,
  105. setQueueEditInputText,
  106. waitForQueueContaining,
  107. waitForQueueCount,
  108. waitForQueueOrderContaining,
  109. } from "./conversation-session-queue.js";
  110. export {
  111. assertToolCallNotFailedByToolCallId,
  112. expandAssistantHistoriesWithContent,
  113. getToolCallBlockByToolCallId,
  114. getToolCallBlockByToolName,
  115. getToolCallBlockContaining,
  116. listToolCallBlocks,
  117. openAssistantHistoryForAssistantContaining,
  118. waitForSuccessfulToolCallByToolCallId,
  119. waitForToolCallBlockByToolCallId,
  120. waitForToolCallBlockByToolName,
  121. waitForToolCallBlockContaining,
  122. } from "./conversation-session-tool.js";
  123. export {
  124. getTaskStoreSnapshot,
  125. waitForTaskStoreSnapshot,
  126. type ConfigOptionSnapshot,
  127. type TaskStoreSnapshot,
  128. } from "./conversation-session-store.js";
  129. export {
  130. getToastMessages,
  131. waitForToastContaining,
  132. } from "./conversation-session-toast.js";
  133. export interface ChatRootSnapshot {
  134. activeInputId: string | null;
  135. queueCount: number;
  136. runtimeStatus: string | null;
  137. sessionId: string | null;
  138. state: string | null;
  139. modelSwitchPending: boolean;
  140. stopRequested: boolean;
  141. targetId: string | null;
  142. targetObjective: string | null;
  143. targetStatus: string | null;
  144. taskId: string | null;
  145. }
  146. export interface MessageSnapshot {
  147. id: string | null;
  148. role: string | null;
  149. text: string;
  150. }
  151. interface PrepareConversationE2EOptions {
  152. resetDraftBeforeProvider?: boolean;
  153. skipProvider?: boolean;
  154. }
  155. export async function prepareConversationE2E(
  156. options: PrepareConversationE2EOptions = {},
  157. ) {
  158. await ensureReadonlyToolFixtureFile();
  159. await ensureConversationShellReady();
  160. if (options.resetDraftBeforeProvider) {
  161. // 修复原因:连续 case 可能停在上一条带 goal 的 active session 上。
  162. // 先进入空草稿,避免 provider 初始化把默认模型断言写到旧 session。
  163. await startNewTask();
  164. }
  165. if (!options.skipProvider) {
  166. await ensureUpstreamProviderForE2E();
  167. }
  168. await ensureConversationDraftReady();
  169. }
  170. async function ensureConversationShellReady() {
  171. try {
  172. await waitForDefaultWorkspaceReady(30000);
  173. return;
  174. } catch (error) {
  175. if (!(await hasApiKeyLoginButton())) {
  176. throw error;
  177. }
  178. // 修复原因:renderer target 切换失败时曾被登录兜底吞掉,误报成
  179. // “欢迎页没有出现 API Key 登录入口”。只有确认当前页面真是欢迎页时才回退登录。
  180. await loginWithApiKey();
  181. await waitForDefaultWorkspaceReady(30000);
  182. }
  183. }
  184. async function hasApiKeyLoginButton() {
  185. const exists = await browser
  186. .execute(
  187. (currentTestId) =>
  188. Boolean(document.querySelector(`[data-testid="${currentTestId}"]`)),
  189. TID_LOGIN_USE_API_KEY_BUTTON,
  190. )
  191. .catch(() => false);
  192. return Boolean(exists);
  193. }
  194. export async function loginWithApiKey() {
  195. await clickTestIdByDom(TID_LOGIN_USE_API_KEY_BUTTON, {
  196. timeout: 30000,
  197. timeoutMsg: "欢迎页没有出现 API Key 登录入口",
  198. });
  199. await setInputValueByTestIdDom(TID_LOGIN_API_KEY_INPUT, LOGIN_API_KEY, {
  200. timeout: 15000,
  201. timeoutMsg: "API Key 登录输入框没有出现",
  202. });
  203. await waitForApiKeyContinueEnabled();
  204. await clickTestIdByDom(TID_LOGIN_API_KEY_CONTINUE_BUTTON, {
  205. timeout: 15000,
  206. timeoutMsg: "API Key 登录继续按钮没有出现或不可点击",
  207. });
  208. }
  209. export async function startNewTask() {
  210. await clickTestIdByDom(TID_TASK_NEW_BUTTON, {
  211. timeout: 15000,
  212. timeoutMsg: "侧栏新任务按钮没有出现或不可点击",
  213. });
  214. await waitForConversationDraftReady("新建任务后没有进入空草稿态");
  215. }
  216. async function ensureConversationDraftReady() {
  217. const current = await inspectConversationComposer();
  218. if (current.displayed && current.draftReady) {
  219. return;
  220. }
  221. await startNewTask();
  222. }
  223. async function waitForConversationDraftReady(timeoutMsg: string) {
  224. try {
  225. await browser.waitUntil(
  226. async () => {
  227. const current = await inspectConversationComposer();
  228. return current.displayed && current.draftReady;
  229. },
  230. { timeout: 30000, timeoutMsg },
  231. );
  232. } catch (error) {
  233. const diagnostics = await collectConversationDraftDiagnostics();
  234. throw new Error(
  235. `${timeoutMsg}; diagnostics=${JSON.stringify(diagnostics)}`,
  236. {
  237. cause: error,
  238. },
  239. );
  240. }
  241. }
  242. function inspectConversationComposer(): Promise<{
  243. displayed: boolean;
  244. draftReady: boolean;
  245. inputTestId: string | null;
  246. variant: "legacy" | "v4" | null;
  247. }> {
  248. return browser.execute(
  249. (v4InputTestId, legacyInputTestId, v4PaneTestId, legacyViewTestId) => {
  250. const isDisplayed = (element: Element | null) => {
  251. if (!(element instanceof HTMLElement)) return false;
  252. const style = window.getComputedStyle(element);
  253. const rect = element.getBoundingClientRect();
  254. return (
  255. style.display !== "none" &&
  256. style.visibility !== "hidden" &&
  257. rect.width > 0 &&
  258. rect.height > 0
  259. );
  260. };
  261. const v4Input = document.querySelector(
  262. `[data-testid="${v4InputTestId}"]`,
  263. );
  264. if (isDisplayed(v4Input)) {
  265. const pane = document.querySelector<HTMLElement>(
  266. `[data-testid="${v4PaneTestId}"]`,
  267. );
  268. return {
  269. displayed: true,
  270. draftReady: pane?.getAttribute("data-session-id") === "draft",
  271. inputTestId: v4InputTestId,
  272. variant: "v4" as const,
  273. };
  274. }
  275. const legacyInput = document.querySelector(
  276. `[data-testid="${legacyInputTestId}"]`,
  277. );
  278. const root = document.querySelector<HTMLElement>(
  279. `[data-testid="${legacyViewTestId}"]`,
  280. );
  281. return {
  282. displayed: isDisplayed(legacyInput),
  283. draftReady:
  284. Boolean(root) &&
  285. !root?.getAttribute("data-task-id") &&
  286. !root?.getAttribute("data-session-id") &&
  287. root?.getAttribute("data-state") === "idle" &&
  288. root?.getAttribute("data-model-switch-pending") !== "true",
  289. inputTestId: isDisplayed(legacyInput) ? legacyInputTestId : null,
  290. variant: isDisplayed(legacyInput) ? ("legacy" as const) : null,
  291. };
  292. },
  293. TID_V4_COMPOSER_INPUT,
  294. TID_CHAT_INPUT,
  295. testId(TID_V4_SESSION_PANE, "workspace-main"),
  296. TID_CHAT_VIEW,
  297. );
  298. }
  299. async function collectConversationDraftDiagnostics() {
  300. const composer = await inspectConversationComposer().catch((error) => ({
  301. error: error instanceof Error ? error.message : String(error),
  302. }));
  303. const visibleTestIds = await browser.execute(() =>
  304. Array.from(document.querySelectorAll<HTMLElement>("[data-testid]"))
  305. .filter((element) => {
  306. const style = window.getComputedStyle(element);
  307. const rect = element.getBoundingClientRect();
  308. return (
  309. style.display !== "none" &&
  310. style.visibility !== "hidden" &&
  311. rect.width > 0 &&
  312. rect.height > 0
  313. );
  314. })
  315. .map((element) => element.getAttribute("data-testid"))
  316. .filter((value): value is string => Boolean(value))
  317. .slice(0, 80),
  318. );
  319. return { composer, visibleTestIds };
  320. }
  321. export async function selectTaskById(
  322. taskId: string,
  323. {
  324. timeout = 15000,
  325. timeoutMsg = `任务列表没有可点击的 task: ${taskId}`,
  326. }: { timeout?: number; timeoutMsg?: string } = {},
  327. ) {
  328. await clickTestIdByDom(testId(TID_TASK_ITEM, taskId), {
  329. timeout,
  330. timeoutMsg,
  331. });
  332. }
  333. export async function sendPrompt(prompt: string) {
  334. await typeChatPrompt(prompt);
  335. await clickChatSend();
  336. }
  337. export async function typeChatPrompt(prompt: string) {
  338. const composer = await inspectConversationComposer();
  339. if (composer.variant === "v4") {
  340. await setInputValueByTestIdDom(TID_V4_COMPOSER_INPUT, prompt, {
  341. timeout: 15000,
  342. timeoutMsg: "v4 composer 输入框没有出现或不可输入",
  343. });
  344. return;
  345. }
  346. await AppPage.chatInput.waitForDisplayed({ timeout: 15000 });
  347. await AppPage.chatInput.click();
  348. const lexicalBridgeResult = await writePromptWithLexicalBridge(prompt);
  349. if (lexicalBridgeResult.ok) {
  350. return;
  351. }
  352. if (
  353. shouldTypePromptWithKeyboard(prompt) &&
  354. (await getComposerText()) === ""
  355. ) {
  356. // 修复原因:Lexical bridge 是稳定路径;只有 bridge 未挂载时才退回真实键盘输入。
  357. // 这仍能触发 React draft 状态,避免旧 DOM 兜底只改可见文本。
  358. await browser.keys(prompt);
  359. await browser.waitUntil(
  360. async () => (await getComposerText()) === prompt.trim(),
  361. {
  362. timeout: 10000,
  363. timeoutMsg: `聊天输入框没有通过键盘写入 prompt: ${prompt}`,
  364. },
  365. );
  366. return;
  367. }
  368. // 修复原因:Lexical E2E bridge 理论上总会随输入框挂载;这里保留旧 DOM 写法只作为
  369. // bridge 尚未初始化时的兜底,并把原因带进失败上下文,避免 slash command 再次静默丢状态。
  370. const result = (await browser.executeAsync(
  371. (inputTestId, text, bridgeReason, done) => {
  372. const input = document.querySelector<LexicalInputE2EElement>(
  373. `[data-testid="${inputTestId}"]`,
  374. );
  375. if (!input) {
  376. done({
  377. actual: "",
  378. inserted: false,
  379. ok: false,
  380. reason: "input-missing",
  381. });
  382. return;
  383. }
  384. input.focus();
  385. const selection = window.getSelection();
  386. const range = document.createRange();
  387. range.selectNodeContents(input);
  388. selection?.removeAllRanges();
  389. selection?.addRange(range);
  390. document.execCommand("delete");
  391. let inserted = true;
  392. const lines = text.split("\n");
  393. for (const [lineIndex, line] of lines.entries()) {
  394. inserted = document.execCommand("insertText", false, line) && inserted;
  395. if (lineIndex < lines.length - 1) {
  396. inserted = document.execCommand("insertLineBreak") && inserted;
  397. }
  398. }
  399. requestAnimationFrame(() => {
  400. const actual = (input.innerText || input.textContent || "")
  401. .replace(/\u00a0/g, " ")
  402. .trim();
  403. done({
  404. actual,
  405. bridgeReason,
  406. inserted,
  407. ok: actual === text.trim(),
  408. });
  409. });
  410. },
  411. TID_CHAT_INPUT,
  412. prompt,
  413. lexicalBridgeResult.reason ?? "bridge-unavailable",
  414. )) as {
  415. actual: string;
  416. bridgeReason?: string;
  417. inserted: boolean;
  418. ok: boolean;
  419. reason?: string;
  420. };
  421. if (!result.ok) {
  422. throw new Error(`聊天输入框没有写入完整 prompt: ${JSON.stringify(result)}`);
  423. }
  424. }
  425. function shouldTypePromptWithKeyboard(prompt: string) {
  426. // 修复原因:可见 slash 命令 case 验证的是命令分发本身,不是 slash panel 选项。
  427. // 真实键盘输入会打开 Lexical slash suggestion,CI 慢帧里可能把 `/goal`
  428. // 变成 suggestion 的编辑器状态,导致点击发送后没有产生可见 user query。
  429. return !prompt.includes("\n") && !isVisibleSlashCommandPrompt(prompt);
  430. }
  431. function isVisibleSlashCommandPrompt(prompt: string) {
  432. return /^\/(?:goal|target|compact|compress)(?:\s|$)/i.test(prompt.trim());
  433. }
  434. async function writePromptWithLexicalBridge(prompt: string): Promise<{
  435. actual?: string;
  436. ok: boolean;
  437. reason?: string;
  438. }> {
  439. try {
  440. await browser.waitUntil(
  441. async () =>
  442. browser.execute((inputTestId) => {
  443. const input = document.querySelector<LexicalInputE2EElement>(
  444. `[data-testid="${inputTestId}"]`,
  445. );
  446. return Boolean(input?.__zcodeLexicalInputE2E);
  447. }, TID_CHAT_INPUT),
  448. {
  449. timeout: 5000,
  450. timeoutMsg: "聊天输入框 Lexical E2E bridge 没有就绪",
  451. },
  452. );
  453. } catch (error) {
  454. return {
  455. ok: false,
  456. reason: error instanceof Error ? error.message : String(error),
  457. };
  458. }
  459. const setResult = (await browser.execute(
  460. (inputTestId, text) => {
  461. try {
  462. const input = document.querySelector<LexicalInputE2EElement>(
  463. `[data-testid="${inputTestId}"]`,
  464. );
  465. const bridge = input?.__zcodeLexicalInputE2E;
  466. if (!bridge) {
  467. return { ok: false, reason: "bridge-missing" };
  468. }
  469. bridge.setText(text);
  470. bridge.focus();
  471. return { ok: true };
  472. } catch (error) {
  473. return {
  474. ok: false,
  475. reason: error instanceof Error ? error.message : String(error),
  476. };
  477. }
  478. },
  479. TID_CHAT_INPUT,
  480. prompt,
  481. )) as { ok: boolean; reason?: string };
  482. if (!setResult.ok) {
  483. return setResult;
  484. }
  485. let latest: {
  486. bridgeText?: string;
  487. domText?: string;
  488. ok: boolean;
  489. reason?: string;
  490. } = {
  491. ok: false,
  492. };
  493. try {
  494. await browser.waitUntil(
  495. async () => {
  496. latest = await readLexicalBridgePromptSnapshot();
  497. return latest.bridgeText === prompt.trim();
  498. },
  499. {
  500. timeout: 10000,
  501. timeoutMsg: `聊天输入框没有通过 Lexical bridge 写入 prompt: ${prompt}`,
  502. },
  503. );
  504. } catch (error) {
  505. throw new Error(
  506. `聊天输入框没有通过 Lexical bridge 写入 prompt: ${prompt}; latest=${JSON.stringify(
  507. latest,
  508. )}`,
  509. { cause: error },
  510. );
  511. }
  512. return { actual: latest.bridgeText, ok: true };
  513. }
  514. function readLexicalBridgePromptSnapshot(): Promise<{
  515. bridgeText?: string;
  516. domText?: string;
  517. ok: boolean;
  518. reason?: string;
  519. }> {
  520. return browser.execute((inputTestId) => {
  521. try {
  522. const input = document.querySelector<LexicalInputE2EElement>(
  523. `[data-testid="${inputTestId}"]`,
  524. );
  525. const bridge = input?.__zcodeLexicalInputE2E;
  526. if (!bridge) {
  527. return { ok: false, reason: "bridge-missing" };
  528. }
  529. return {
  530. bridgeText: bridge.getText().trim(),
  531. domText: (input.innerText || input.textContent || "")
  532. .replace(/\u00a0/g, " ")
  533. .trim(),
  534. ok: true,
  535. };
  536. } catch (error) {
  537. return {
  538. ok: false,
  539. reason: error instanceof Error ? error.message : String(error),
  540. };
  541. }
  542. }, TID_CHAT_INPUT);
  543. }
  544. export async function clickChatSend() {
  545. const sendButtonTestId = await resolveVisibleComposerControlTestId(
  546. TID_V4_COMPOSER_SEND,
  547. TID_CHAT_SEND_BUTTON,
  548. );
  549. await browser.waitUntil(
  550. async () =>
  551. browser.execute((sendButtonTestId) => {
  552. const button = document.querySelector<HTMLButtonElement>(
  553. `[data-testid="${sendButtonTestId}"]`,
  554. );
  555. return Boolean(button && !button.disabled);
  556. }, sendButtonTestId),
  557. {
  558. timeout: 30000,
  559. timeoutMsg: "聊天发送按钮没有变为可用",
  560. },
  561. );
  562. await clickTestIdByDom(sendButtonTestId, {
  563. timeout: 15000,
  564. timeoutMsg: "聊天发送按钮没有出现或不可点击",
  565. });
  566. }
  567. export async function clickChatStop() {
  568. const stopButtonTestId = await resolveVisibleComposerControlTestId(
  569. TID_V4_STOP,
  570. TID_CHAT_STOP_BUTTON,
  571. );
  572. await clickTestIdByDom(stopButtonTestId, {
  573. timeout: 30000,
  574. timeoutMsg: "聊天停止按钮没有出现或不可点击",
  575. });
  576. }
  577. export async function waitForComposerText(
  578. expected: string,
  579. timeoutMsg: string,
  580. ) {
  581. await browser.waitUntil(async () => (await getComposerText()) === expected, {
  582. timeout: 10000,
  583. timeoutMsg,
  584. });
  585. }
  586. export function getComposerText() {
  587. return browser.execute(
  588. (inputTestIds) => {
  589. const input = inputTestIds
  590. .map((inputTestId) =>
  591. document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`),
  592. )
  593. .find(Boolean);
  594. return (input?.innerText || input?.textContent || "")
  595. .replace(/\u00a0/g, " ")
  596. .trim();
  597. },
  598. [TID_V4_COMPOSER_INPUT, TID_CHAT_INPUT],
  599. );
  600. }
  601. async function resolveVisibleComposerControlTestId(
  602. v4TestId: string,
  603. legacyTestId: string,
  604. ) {
  605. return browser.execute(
  606. (testIds) => {
  607. const visible = testIds.find((currentTestId) => {
  608. const element = document.querySelector<HTMLElement>(
  609. `[data-testid="${currentTestId}"]`,
  610. );
  611. if (!element) return false;
  612. const style = window.getComputedStyle(element);
  613. const rect = element.getBoundingClientRect();
  614. return (
  615. style.display !== "none" &&
  616. style.visibility !== "hidden" &&
  617. rect.width > 0 &&
  618. rect.height > 0
  619. );
  620. });
  621. return visible ?? testIds[0]!;
  622. },
  623. [v4TestId, legacyTestId],
  624. );
  625. }
  626. export async function waitForChatState(
  627. predicate: (snapshot: ChatRootSnapshot) => boolean,
  628. timeoutMsg: string,
  629. timeout = 30000,
  630. ) {
  631. let latest: ChatRootSnapshot | null = null;
  632. try {
  633. await browser.waitUntil(
  634. async () => {
  635. latest = await getChatRootSnapshot();
  636. return predicate(latest);
  637. },
  638. {
  639. timeout,
  640. timeoutMsg,
  641. },
  642. );
  643. } catch (error) {
  644. // 修复原因:WebdriverIO 的 timeoutMsg 在 waitUntil 开始时就会固定,
  645. // 直接拼 latest 会一直显示 null,导致定位状态枚举失败时缺少真实 UI 状态。
  646. latest = await getChatRootSnapshot();
  647. throw new Error(`${timeoutMsg}; latest=${JSON.stringify(latest)}`, {
  648. cause: error,
  649. });
  650. }
  651. return getChatRootSnapshot();
  652. }
  653. export async function getChatRootSnapshot(): Promise<ChatRootSnapshot> {
  654. const legacySnapshot = await browser.execute((chatViewTestId) => {
  655. const root = document.querySelector<HTMLElement>(
  656. `[data-testid="${chatViewTestId}"]`,
  657. );
  658. if (!root) {
  659. return null;
  660. }
  661. const rawQueueCount = root.getAttribute("data-queue-count");
  662. return {
  663. activeInputId: root.getAttribute("data-active-input-id") || null,
  664. queueCount: rawQueueCount ? Number(rawQueueCount) : 0,
  665. runtimeStatus: root.getAttribute("data-runtime-status") || null,
  666. sessionId: root.getAttribute("data-session-id") || null,
  667. state: root.getAttribute("data-state") || null,
  668. modelSwitchPending:
  669. root.getAttribute("data-model-switch-pending") === "true",
  670. stopRequested: root.getAttribute("data-stop-requested") === "true",
  671. targetId: root.getAttribute("data-target-id") || null,
  672. targetObjective: root.getAttribute("data-target-objective") || null,
  673. targetStatus: root.getAttribute("data-target-status") || null,
  674. taskId: root.getAttribute("data-task-id") || null,
  675. } satisfies ChatRootSnapshot;
  676. }, TID_CHAT_VIEW);
  677. if (legacySnapshot) {
  678. return legacySnapshot;
  679. }
  680. // 修复原因:V4 硬切后 chat-view 的 data-* 状态合同已经删除;共享 helper
  681. // 仍需保留 legacy ChatRootSnapshot 的 Goal/stop/workspace 隔离语义。
  682. const v4Snapshot = await browser.execute(
  683. readV4ChatRootSnapshotInBrowser,
  684. testId(TID_V4_SESSION_PANE, "workspace-main"),
  685. TID_V4_QUEUE_ITEM,
  686. TID_V4_STOP,
  687. );
  688. if (v4Snapshot.bridgeError) {
  689. throw new Error(
  690. `无法读取 V4 conversation workspace: ${v4Snapshot.bridgeError}; ` +
  691. `workspaceKey=${v4Snapshot.workspaceKey}; paneSessionId=${v4Snapshot.paneSessionId}`,
  692. );
  693. }
  694. if (!v4Snapshot.taskId) {
  695. return {
  696. activeInputId: null,
  697. queueCount: v4Snapshot.queueCount,
  698. runtimeStatus: v4Snapshot.runtimeStatus,
  699. sessionId: null,
  700. state: v4Snapshot.runtimeStatus === "streaming" ? "streaming" : "idle",
  701. modelSwitchPending: v4Snapshot.modelSwitchPending,
  702. stopRequested: false,
  703. targetId: null,
  704. targetObjective: null,
  705. targetStatus: null,
  706. taskId: null,
  707. };
  708. }
  709. const taskStore = await readTaskStoreSnapshotForDiagnostics(
  710. v4Snapshot.taskId,
  711. v4Snapshot.workspaceKey ?? undefined,
  712. );
  713. if (!taskStore.workspaceKey) {
  714. throw new Error(
  715. `无法读取 V4 conversation task: ${taskStore.error}; ` +
  716. `workspaceKey=${v4Snapshot.workspaceKey}; taskId=${v4Snapshot.taskId}`,
  717. );
  718. }
  719. // 修复原因:V4 的 active goal 是 session status panel 的实时投影,taskListCache
  720. // 只承载侧栏摘要,首次创建的 session 在 title/cache 尚未回流时 taskMeta 可以为空。
  721. // 继续只读 taskMeta 会把已经运行的 goal 误判成无 target。
  722. const goalProjection = await browser.execute(
  723. (paneTestId, panelTestId) => {
  724. const pane = document.querySelector<HTMLElement>(
  725. `[data-testid="${paneTestId}"]`,
  726. );
  727. const panel = pane?.querySelector<HTMLElement>(
  728. `[data-testid="${panelTestId}"]`,
  729. );
  730. if (!panel) {
  731. return null;
  732. }
  733. return {
  734. objective: panel.getAttribute("data-goal-objective"),
  735. status: panel.getAttribute("data-goal-status"),
  736. };
  737. },
  738. testId(TID_V4_SESSION_PANE, "workspace-main"),
  739. TID_CHAT_SUMMARY_PANEL,
  740. );
  741. const hasBlockingGoalWork =
  742. goalProjection?.status === "active" ||
  743. goalProjection?.status === "verifying";
  744. // Bug 根因:V4 Stop 控件已经可见时,store bridge 仍可能停在上一帧 completed。
  745. // 旧逻辑虽然在 DOM snapshot 合成了 streaming,最终却又被 taskStore 覆盖,
  746. // 导致 running/queue E2E 把真实运行轮误判成 idle。
  747. const effectiveRuntimeStatus =
  748. v4Snapshot.runtimeStatus === "streaming"
  749. ? "streaming"
  750. : taskStore.runtimeStatus;
  751. return {
  752. activeInputId: taskStore.activeInputId,
  753. queueCount: v4Snapshot.queueCount,
  754. runtimeStatus: effectiveRuntimeStatus,
  755. sessionId: v4Snapshot.taskId,
  756. // Goal continuation/verifier 是独立的 completion work,普通 turn runtime 在这段
  757. // 时间可以保持 completed;V4 helper 必须合成两套状态,才能保留 legacy 的
  758. // completion-blocking `state=streaming` 合同。
  759. state:
  760. effectiveRuntimeStatus === "streaming" || hasBlockingGoalWork
  761. ? "streaming"
  762. : "idle",
  763. modelSwitchPending: v4Snapshot.modelSwitchPending,
  764. stopRequested: taskStore.stopRequested,
  765. targetId: taskStore.taskMeta?.targetId ?? null,
  766. targetObjective:
  767. goalProjection?.objective ?? taskStore.taskMeta?.targetObjective ?? null,
  768. targetStatus:
  769. goalProjection?.status ?? taskStore.taskMeta?.targetStatus ?? null,
  770. taskId: v4Snapshot.taskId,
  771. };
  772. }
  773. export async function waitForAssistantMessageContaining(text: string) {
  774. await browser.waitUntil(
  775. async () =>
  776. (await getMessages("assistant")).some((message) =>
  777. message.text.includes(text),
  778. ),
  779. {
  780. timeout: 90000,
  781. timeoutMsg: `assistant 消息中没有出现: ${text}`,
  782. },
  783. );
  784. }
  785. export async function waitForUserMessageContaining(text: string) {
  786. let latestMessages: MessageSnapshot[] = [];
  787. try {
  788. await browser.waitUntil(
  789. async () => {
  790. latestMessages = await getMessages("user");
  791. return latestMessages.some((message) => message.text.includes(text));
  792. },
  793. {
  794. timeout: 60000,
  795. timeoutMsg: `user 消息中没有出现: ${text}`,
  796. },
  797. );
  798. } catch (error) {
  799. // 修复原因:CI 上 conversation case 失败时,单看 DOM 消息列表无法判断
  800. // 输入是被 renderer 队列拦住,还是 slash command 没解析。失败信息直接带状态快照。
  801. const chat = await getChatRootSnapshot().catch((snapshotError) => ({
  802. error:
  803. snapshotError instanceof Error
  804. ? snapshotError.message
  805. : String(snapshotError),
  806. }));
  807. const queue = await readQueueItemsForDiagnostics().catch((queueError) => [
  808. {
  809. content:
  810. queueError instanceof Error ? queueError.message : String(queueError),
  811. id: "<queue-read-error>",
  812. index: -1,
  813. kind: null,
  814. status: null,
  815. },
  816. ]);
  817. const taskStore =
  818. "taskId" in chat && chat.taskId
  819. ? await readTaskStoreSnapshotForDiagnostics(chat.taskId).catch(
  820. (storeError) => ({
  821. error:
  822. storeError instanceof Error
  823. ? storeError.message
  824. : String(storeError),
  825. }),
  826. )
  827. : null;
  828. const composer = await getComposerText().catch((composerError) =>
  829. composerError instanceof Error
  830. ? composerError.message
  831. : String(composerError),
  832. );
  833. throw new Error(
  834. `user 消息中没有出现: ${text}; latestMessages=${JSON.stringify(latestMessages)}; chat=${JSON.stringify(chat)}; queue=${JSON.stringify(queue)}; taskStore=${JSON.stringify(taskStore)}; composer=${JSON.stringify(composer)}`,
  835. { cause: error },
  836. );
  837. }
  838. }
  839. export async function assertVisibleUserMessagesNotContaining(text: string) {
  840. const messages = await getMessages("user");
  841. expect(messages.map((message) => message.text).join("\n")).not.toContain(
  842. text,
  843. );
  844. }
  845. export function getMessages(
  846. role?: "assistant" | "user",
  847. ): Promise<MessageSnapshot[]> {
  848. return browser.execute(
  849. (
  850. messagesTestId: string,
  851. userPrefix: string,
  852. assistantPrefix: string,
  853. selectedRole: "assistant" | "user" | undefined,
  854. v4TimelineTestId: string,
  855. ) => {
  856. const legacyRoot = document.querySelector<HTMLElement>(
  857. `[data-testid="${messagesTestId}"]`,
  858. );
  859. if (legacyRoot) {
  860. const selector =
  861. selectedRole === "user"
  862. ? `[data-testid^="${userPrefix}-"]`
  863. : selectedRole === "assistant"
  864. ? `[data-testid^="${assistantPrefix}-"]`
  865. : `[data-testid^="${userPrefix}-"],[data-testid^="${assistantPrefix}-"]`;
  866. return Array.from(
  867. legacyRoot.querySelectorAll<HTMLElement>(selector),
  868. ).map((element) => ({
  869. id: element.getAttribute("data-message-id"),
  870. role: element.getAttribute("data-role"),
  871. text: element.innerText.replace(/\u00a0/g, " ").trim(),
  872. }));
  873. }
  874. const timeline = document.querySelector<HTMLElement>(
  875. `[data-testid="${v4TimelineTestId}"]`,
  876. );
  877. return Array.from(
  878. timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [],
  879. )
  880. .map((element) => {
  881. const role = element.classList.contains("group/user-row")
  882. ? "user"
  883. : element.classList.contains("group/assistant-row")
  884. ? "assistant"
  885. : null;
  886. return {
  887. id: element.getAttribute("data-row-id"),
  888. role,
  889. text: element.innerText.replace(/\u00a0/g, " ").trim(),
  890. };
  891. })
  892. .filter(
  893. (message) =>
  894. message.role && (!selectedRole || message.role === selectedRole),
  895. );
  896. },
  897. TID_CHAT_MESSAGES,
  898. TID_CHAT_USER_MESSAGE,
  899. TID_CHAT_ASSISTANT_MESSAGE,
  900. role,
  901. TID_V4_TIMELINE,
  902. );
  903. }
  904. async function waitForApiKeyContinueEnabled() {
  905. await browser.waitUntil(
  906. async () =>
  907. browser.execute((continueButtonTestId) => {
  908. const button = document.querySelector<HTMLElement>(
  909. `[data-testid="${continueButtonTestId}"]`,
  910. );
  911. return button instanceof HTMLButtonElement && !button.disabled;
  912. }, TID_LOGIN_API_KEY_CONTINUE_BUTTON),
  913. {
  914. timeout: 15000,
  915. timeoutMsg: "API Key 登录继续按钮没有变为可用",
  916. },
  917. );
  918. }