conversation-session.ts 29 KB

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