conversation-session-tool-cross-product.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import { mkdir, rm, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { resolveE2ERuntimePath } from "./e2e-runtime-paths.js";
  4. export const TOOL_CROSS_PRODUCT_ROOT = resolveE2ERuntimePath(
  5. "conversation-session-tool-cross-product",
  6. );
  7. export const TOOL_CROSS_PRODUCT_MARKER_PREFIX = "E2E_TOOL_CROSS_PRODUCT";
  8. export const TOOL_CROSS_PRODUCT_READ_FILE = join(
  9. TOOL_CROSS_PRODUCT_ROOT,
  10. "read-fixture.txt",
  11. );
  12. export const TOOL_CROSS_PRODUCT_GLOB_FILE = join(
  13. TOOL_CROSS_PRODUCT_ROOT,
  14. "glob-fixture.e2e",
  15. );
  16. export const TOOL_CROSS_PRODUCT_GREP_FILE = join(
  17. TOOL_CROSS_PRODUCT_ROOT,
  18. "grep-fixture.txt",
  19. );
  20. export type ToolCrossProductScenario = "compact" | "fork" | "goal";
  21. export interface ToolCrossProductCase {
  22. markerName: string;
  23. toolName: string;
  24. historyAssertion?: "visibleToolBlock" | "providerRequest";
  25. providerHistoryMarker?: string;
  26. }
  27. export const TOOL_CROSS_PRODUCT_CASES: ToolCrossProductCase[] = [
  28. { markerName: "READ", toolName: "Read" },
  29. { markerName: "WRITE", toolName: "Write" },
  30. { markerName: "EDIT", toolName: "Edit" },
  31. { markerName: "BASH", toolName: "Bash" },
  32. { markerName: "GLOB", toolName: "Glob" },
  33. { markerName: "GREP", toolName: "Grep" },
  34. { markerName: "WEBFETCH", toolName: "WebFetch" },
  35. {
  36. markerName: "TODO_READ",
  37. toolName: "TodoRead",
  38. historyAssertion: "providerRequest",
  39. providerHistoryMarker: "toolu_e2e_tool_cross_product_todo_read",
  40. },
  41. { markerName: "TODO_WRITE", toolName: "TodoWrite" },
  42. { markerName: "GOAL_READ", toolName: "GoalRead" },
  43. {
  44. markerName: "ENTER_PLAN_MODE",
  45. toolName: "EnterPlanMode",
  46. historyAssertion: "providerRequest",
  47. providerHistoryMarker: "toolu_e2e_tool_cross_product_enter_plan_mode",
  48. },
  49. { markerName: "EXIT_PLAN_MODE", toolName: "ExitPlanMode" },
  50. { markerName: "ASK_USER_QUESTION", toolName: "AskUserQuestion" },
  51. { markerName: "READ_SESSION_CONTEXT", toolName: "ReadSessionContext" },
  52. { markerName: "SEND_MESSAGE", toolName: "SendMessage" },
  53. { markerName: "AGENT", toolName: "Agent" },
  54. { markerName: "SKILL", toolName: "Skill" },
  55. // 修复原因:当前 desktop E2E 的 agent runtime 没有注册 Workflow 工具。
  56. // replay fixture 若强制调用 Workflow 会稳定得到 "Tool not found",后续 compact/fork/goal
  57. // 断言验证的是失败工具卡而不是工具历史能力,应该从正式叉乘集合剪掉。
  58. ];
  59. export function markerForToolCase(toolCase: ToolCrossProductCase) {
  60. return `${TOOL_CROSS_PRODUCT_MARKER_PREFIX}_${toolCase.markerName}`;
  61. }
  62. export function buildToolCrossProductPrompt(
  63. toolCase: ToolCrossProductCase,
  64. scenario: ToolCrossProductScenario,
  65. runId: string,
  66. ) {
  67. return [
  68. `${markerForToolCase(toolCase)}_${scenario.toUpperCase()}_${runId}:`,
  69. `Trigger the ${toolCase.toolName} tool exactly once.`,
  70. 'Then reply with exactly "upstream-e2e-ok" and no other text.',
  71. ].join(" ");
  72. }
  73. export async function prepareToolCrossProductFixtures() {
  74. await cleanupToolCrossProductFixtures();
  75. await mkdir(TOOL_CROSS_PRODUCT_ROOT, { recursive: true });
  76. await writeFile(
  77. TOOL_CROSS_PRODUCT_READ_FILE,
  78. [
  79. "E2E_TOOL_RESULT_READ",
  80. "E2E_TOOL_RESULT_GREP",
  81. "This file is read by the conversation tool cross product e2e.",
  82. "",
  83. ].join("\n"),
  84. "utf-8",
  85. );
  86. await writeFile(
  87. TOOL_CROSS_PRODUCT_GLOB_FILE,
  88. "E2E_TOOL_RESULT_GLOB\n",
  89. "utf-8",
  90. );
  91. await writeFile(
  92. TOOL_CROSS_PRODUCT_GREP_FILE,
  93. "E2E_TOOL_RESULT_GREP content search fixture\n",
  94. "utf-8",
  95. );
  96. }
  97. export async function cleanupToolCrossProductFixtures() {
  98. await rm(TOOL_CROSS_PRODUCT_ROOT, { recursive: true, force: true });
  99. }
  100. export async function ensureToolCrossProductFullAccessMode() {
  101. if (await isFullAccessModeSelected()) {
  102. return;
  103. }
  104. // Bug 根因:长 suite 中上一个 mode 选择器可能仍处于打开状态;再次点击 trigger
  105. // 会把菜单关闭,后续就会稳定报“找不到 Full access”。只在当前没有可见目标项时
  106. // 打开选择器,避免 toggle 竞态。
  107. if (!(await hasVisibleFullAccessModeItem())) {
  108. await clickModeTrigger();
  109. }
  110. await clickFullAccessModeItem();
  111. await browser.waitUntil(async () => isFullAccessModeSelected(), {
  112. timeout: 30000,
  113. timeoutMsg: "工具叉乘 e2e 没有切换到 Full access/yolo mode",
  114. });
  115. }
  116. async function hasVisibleFullAccessModeItem(): Promise<boolean> {
  117. const normalizeText = (value: string | null | undefined) =>
  118. (value ?? "").replace(/\u00a0/g, " ").trim();
  119. const items = await browser.$$('[data-slot="select-item"],[role="option"]');
  120. for (const item of items) {
  121. if (!(await item.isDisplayed()) || !(await item.isEnabled())) {
  122. continue;
  123. }
  124. const value = await item.getAttribute("data-value");
  125. const text = normalizeText(await item.getText());
  126. if (
  127. value === "yolo" ||
  128. ["Full access", "完全访问", "Yolo", "全自动模式"].some((expected) =>
  129. text.includes(expected),
  130. )
  131. ) {
  132. return true;
  133. }
  134. }
  135. return false;
  136. }
  137. export async function respondToToolCrossProductBlockers() {
  138. const result = (await browser.execute(() => {
  139. const normalizeText = (value: string | null | undefined) =>
  140. (value ?? "").replace(/\u00a0/g, " ").trim();
  141. const clickFirstPermissionOption = () => {
  142. const listbox = Array.from(
  143. document.querySelectorAll<HTMLElement>('[role="listbox"]'),
  144. ).find((element) => {
  145. const label = normalizeText(element.getAttribute("aria-label"));
  146. return label === "Permission required" || label === "需要权限";
  147. });
  148. const option = listbox?.querySelector<HTMLButtonElement>(
  149. 'button[role="option"]',
  150. );
  151. option?.click();
  152. return Boolean(option);
  153. };
  154. const clickFirstQuestionOption = () => {
  155. const listbox = Array.from(
  156. document.querySelectorAll<HTMLElement>('[role="listbox"]'),
  157. ).find((element) =>
  158. normalizeText(element.getAttribute("aria-label")).includes(
  159. "E2E_TOOL_CROSS_PRODUCT_ASK_USER_QUESTION",
  160. ),
  161. );
  162. const option = listbox?.querySelector<HTMLButtonElement>(
  163. 'button[role="option"]',
  164. );
  165. option?.click();
  166. return Boolean(option);
  167. };
  168. const clickPlanApprovalSubmit = () => {
  169. const normalizeText = (value: string | null | undefined) =>
  170. (value ?? "").replace(/\u00a0/g, " ").trim();
  171. const body = document.querySelector<HTMLElement>(
  172. '[data-elicitation-dialog-body="true"]',
  173. );
  174. const footer = document.querySelector<HTMLElement>(
  175. '[data-elicitation-dialog-footer="true"]',
  176. );
  177. const hasApproveOption = Array.from(
  178. body?.querySelectorAll<HTMLButtonElement>('button[role="option"]') ?? [],
  179. ).some((button) =>
  180. ["Approve", "批准"].some((label) =>
  181. normalizeText(button.textContent).includes(label),
  182. ),
  183. );
  184. const submit = Array.from(
  185. footer?.querySelectorAll<HTMLButtonElement>("button") ?? [],
  186. ).find((button) =>
  187. ["Submit", "提交"].includes(normalizeText(button.textContent)),
  188. );
  189. if (!hasApproveOption || !submit || submit.disabled) {
  190. return false;
  191. }
  192. submit.click();
  193. return true;
  194. };
  195. return {
  196. elicitationClicked: clickFirstQuestionOption(),
  197. planApprovalClicked: clickPlanApprovalSubmit(),
  198. permissionClicked: clickFirstPermissionOption(),
  199. };
  200. })) as {
  201. elicitationClicked: boolean;
  202. planApprovalClicked: boolean;
  203. permissionClicked: boolean;
  204. };
  205. if (
  206. result.elicitationClicked ||
  207. result.planApprovalClicked ||
  208. result.permissionClicked
  209. ) {
  210. // Bug 根因:ExitPlanMode 在 V4 中走独立计划审批弹窗,不再是 legacy
  211. // PermissionDialog;只点击 permission option 会让整轮永久停在 interaction。
  212. await browser.pause(250);
  213. }
  214. return result;
  215. }
  216. async function isFullAccessModeSelected() {
  217. const result = (await browser.execute(() => {
  218. const normalizeText = (value: string | null | undefined) =>
  219. (value ?? "").replace(/\u00a0/g, " ").trim();
  220. const store = (
  221. window as typeof window & {
  222. __zcodeSessionStoreE2E?: {
  223. getState?: () => {
  224. workspaces?: Record<
  225. string,
  226. {
  227. activeTaskId?: string | null;
  228. configOptions?: Array<ConfigOptionLike> | null;
  229. taskConfigOptionsByTaskId?: Record<
  230. string,
  231. Array<ConfigOptionLike>
  232. >;
  233. }
  234. >;
  235. };
  236. };
  237. }
  238. ).__zcodeSessionStoreE2E;
  239. const workspaceValues: string[] = [];
  240. const activeTaskValues: string[] = [];
  241. const collect = (
  242. options: Array<ConfigOptionLike> | null | undefined,
  243. target: string[],
  244. ) => {
  245. for (const option of options ?? []) {
  246. if (
  247. option.type === "select" &&
  248. (option.category === "mode" || option.id === "mode") &&
  249. typeof option.currentValue === "string"
  250. ) {
  251. target.push(option.currentValue);
  252. }
  253. }
  254. };
  255. for (const workspace of Object.values(
  256. store?.getState?.().workspaces ?? {},
  257. )) {
  258. collect(workspace.configOptions, workspaceValues);
  259. const activeTaskId = workspace.activeTaskId;
  260. if (activeTaskId) {
  261. collect(
  262. workspace.taskConfigOptionsByTaskId?.[activeTaskId],
  263. activeTaskValues,
  264. );
  265. }
  266. }
  267. const labels = Array.from(
  268. document.querySelectorAll<HTMLElement>(
  269. 'button[aria-label="Switch mode"],button[aria-label="切换模式"]',
  270. ),
  271. )
  272. .filter((element) => element.getClientRects().length > 0)
  273. .map((element) => normalizeText(element.textContent));
  274. const labelShowsYolo = labels.some((label) =>
  275. ["Full access", "完全访问", "Yolo", "全自动模式"].some((expected) =>
  276. label.includes(expected),
  277. ),
  278. );
  279. return {
  280. activeTaskValues,
  281. labels,
  282. workspaceValues,
  283. // Bug 根因:EnterPlanMode 后 workspace default 仍是 yolo,但 active task 已是 plan;
  284. // 旧逻辑聚合后只要看到任意 yolo 就误判。可见 V4 trigger 是当前 pane 权威值,
  285. // DOM 不可用时才按 active task → workspace default 的优先级降级。
  286. yolo: labels.length > 0
  287. ? labelShowsYolo
  288. : activeTaskValues.length > 0
  289. ? activeTaskValues.includes("yolo")
  290. : workspaceValues.includes("yolo"),
  291. };
  292. })) as {
  293. activeTaskValues: string[];
  294. labels: string[];
  295. workspaceValues: string[];
  296. yolo: boolean;
  297. };
  298. return result.yolo;
  299. }
  300. async function clickModeTrigger() {
  301. let latestReason = "not-started";
  302. await browser.waitUntil(
  303. async () => {
  304. const triggers = await browser.$$(
  305. 'button[aria-label="Switch mode"],button[aria-label="切换模式"]',
  306. );
  307. for (const trigger of triggers) {
  308. if (!(await trigger.isDisplayed()) || !(await trigger.isEnabled())) {
  309. continue;
  310. }
  311. // Bug 根因:旧 helper 用 renderer click,长 suite 中会命中隐藏的旧 trigger,
  312. // 菜单看似打开但没有改变当前 task。只对当前可见控件走真实 WebDriver 点击。
  313. await trigger.click();
  314. return true;
  315. }
  316. latestReason = (await triggers.length) === 0 ? "missing" : "not-interactable";
  317. return false;
  318. },
  319. {
  320. timeout: 15000,
  321. timeoutMsg: `没有打开 mode 选择器: ${latestReason}`,
  322. },
  323. );
  324. }
  325. async function clickFullAccessModeItem() {
  326. let latestReason = "not-started";
  327. await browser.waitUntil(
  328. async () => {
  329. const normalizeText = (value: string | null | undefined) =>
  330. (value ?? "").replace(/\u00a0/g, " ").trim();
  331. const items = await browser.$$('[data-slot="select-item"],[role="option"]');
  332. const visibleTexts: string[] = [];
  333. for (const item of items) {
  334. if (!(await item.isDisplayed()) || !(await item.isEnabled())) {
  335. continue;
  336. }
  337. const value = await item.getAttribute("data-value");
  338. const text = normalizeText(await item.getText());
  339. visibleTexts.push(text);
  340. if (
  341. value === "yolo" ||
  342. ["Full access", "完全访问", "Yolo", "全自动模式"].some((expected) =>
  343. text.includes(expected),
  344. )
  345. ) {
  346. // Bug 根因:旧 helper 未过滤可见性,可能点击已卸载菜单留下的隐藏 item;
  347. // 当前可见 item 用 WebDriver 点击,保证与用户选择 Full access 的路径一致。
  348. await item.click();
  349. return true;
  350. }
  351. }
  352. latestReason =
  353. (await items.length) === 0
  354. ? "missing"
  355. : `missing; visibleItems=${visibleTexts.join("|")}`;
  356. return false;
  357. },
  358. {
  359. timeout: 15000,
  360. timeoutMsg: `没有点击 Full access/yolo mode: ${latestReason}`,
  361. },
  362. );
  363. }
  364. interface ConfigOptionLike {
  365. category?: string;
  366. currentValue?: unknown;
  367. id?: string;
  368. type?: string;
  369. }