conversation-session-dynamic-workflow-gray-always-on-run.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import { TID_CHAT_WORKFLOW_RUN_DIGEST } from "@zcode/shared";
  2. import type { ChainablePromiseElement } from "webdriverio";
  3. import { clearAppData, pinE2ELocale } from "#e2e/helpers/desktop-app";
  4. import { releaseControlledReplay } from "#e2e/helpers/controlled-replay";
  5. import {
  6. approveV4Permission,
  7. prepareV4ConversationE2E,
  8. sendV4Prompt,
  9. waitForV4AssistantMessageContaining,
  10. waitForV4PermissionDialog,
  11. } from "#e2e/helpers/v4-conversation";
  12. import {
  13. getLatestUpstreamToolResultByToolCallId,
  14. getUpstreamRequestEvidence,
  15. } from "#e2e/helpers/conversation-session-network";
  16. // 模型发起的工作流主链路(docs/dynamic-workflow/launch.md「The `CreateWorkflow` tool」「The confirmation
  17. // window」、docs/dynamic-workflow/presentation.md「The chat area」「The run pane」「The sidebar run line」、
  18. // docs/dynamic-workflow/transcript-and-notifications.md「The completion card」):
  19. // 两个阶段,第一阶段两个子代理并行,第二阶段一个子代理汇总,脚本返回一个值。
  20. //
  21. // 文件名带 `gray-always-on`:配置 mock 网关按文件名下发 alwaysOn,工作流工具才在工具集里。
  22. // case-local 回放只决定模型调用(主代理与子代理);真实 Skill、编译、确认窗、run 引擎、子代理会话与
  23. // 完成通知仍走产品链路。第二阶段子代理的回答用受控流挂起,运行态断言做完再释放,不靠延时抢时序。
  24. const RUN_NAME = "E2E 调研汇总";
  25. const RUN_DIGEST = `[data-testid^="${TID_CHAT_WORKFLOW_RUN_DIGEST}"]`;
  26. const COMPLETION_CARD = '[data-workflow-completion-card="true"]';
  27. const RUN_LINE = '[data-workflow-run-line="true"]';
  28. const AGENTS = ["调研员甲", "调研员乙", "汇总员"];
  29. const HELD_AGENT_FIXTURE = "dwr-agent-c";
  30. let runId = "";
  31. async function readPillStatuses(scope: ChainablePromiseElement | WebdriverIO.Element) {
  32. const statuses: Record<string, string> = {};
  33. for (const pill of await scope.$$('[data-testid="workflow-agent-pill"]')) {
  34. // 失败原因:a6fb6916a8 给完成的子代理 pill 加了 sr-only 的「已完成」文字,整颗 pill 的
  35. // 文本变成「名字+状态」。名字只读 `.wf-pill-name`,状态仍读 data-agent-status。
  36. const name = (await pill.$(".wf-pill-name").getText()).trim();
  37. statuses[name] = (await pill.getAttribute("data-agent-status")) ?? "";
  38. }
  39. return statuses;
  40. }
  41. async function readStationStatuses(digest: ChainablePromiseElement | WebdriverIO.Element) {
  42. const stations: Array<{ text: string; status: string }> = [];
  43. for (const station of await digest.$$('[data-testid="workflow-timeline-station"]')) {
  44. stations.push({
  45. text: await station.getText(),
  46. status: (await station.getAttribute("data-station-status")) ?? "",
  47. });
  48. }
  49. return stations;
  50. }
  51. describe("动态工作流 · 模型发起的 run 主链路", () => {
  52. before(async () => {
  53. await prepareV4ConversationE2E();
  54. // 断言中文文案:固定界面语言,不跟随宿主系统语言(容器里默认英文)。
  55. await pinE2ELocale("zh-CN");
  56. });
  57. after(async () => {
  58. await browser.electron.restoreAllMocks();
  59. await clearAppData();
  60. });
  61. it("DWR-01 确认窗写明名字与阶段数;批准后工具结果成功,run 卡画出两站三枚药丸,运行中侧栏有运行行,最终到达完成态", async function () {
  62. this.timeout(300000);
  63. await sendV4Prompt("E2E_DWR_START 用工作流调研两份材料并汇总结论。");
  64. // 确认窗:标题「运行此工作流?」、工作流名与阶段数(launch.md「What the window shows」)。
  65. await waitForV4PermissionDialog();
  66. // 确认窗没有自己的 testid:从「需要权限」选项列表向上取整个窗口的文字。
  67. const readPermissionWindowText = () =>
  68. browser.execute(() => {
  69. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  70. (element) =>
  71. ["Permission required", "需要权限"].includes(element.getAttribute("aria-label") ?? ""),
  72. );
  73. return listbox?.closest<HTMLElement>(".bg-popover")?.innerText ?? "";
  74. });
  75. await browser.waitUntil(async () => (await readPermissionWindowText()).includes("2 个阶段"), {
  76. timeout: 30000,
  77. timeoutMsg: "确认窗没有写出阶段数",
  78. });
  79. const panelText = await readPermissionWindowText();
  80. expect(panelText).toContain("运行此工作流?");
  81. expect(panelText).toContain(RUN_NAME);
  82. await approveV4Permission();
  83. // 工具结果:编译通过、后台启动,并告诉模型 run id 与「完成时会通知」。
  84. await browser.waitUntil(
  85. async () =>
  86. (await getLatestUpstreamToolResultByToolCallId("toolu_dwr_create"))?.isError === false,
  87. { timeout: 60000, timeoutMsg: "CreateWorkflow 未执行成功" },
  88. );
  89. const toolResult = await getLatestUpstreamToolResultByToolCallId("toolu_dwr_create");
  90. const launched = /started in the background with ID: (\S+?)\./.exec(toolResult?.content ?? "");
  91. expect(launched).not.toBeNull();
  92. runId = launched![1]!;
  93. expect(toolResult?.content).toContain("you will be notified");
  94. // run 卡:按工具调用 id 接到这次 run;两站(调研、汇总),三枚带名字的药丸。
  95. const digest = await $(`${RUN_DIGEST}[data-workflow-run-id="${runId}"]`);
  96. await digest.waitForDisplayed({ timeout: 120000 });
  97. expect(await (await digest.$('[data-testid="workflow-card-name"]').getText()).trim()).toBe(
  98. RUN_NAME,
  99. );
  100. await browser.waitUntil(
  101. async () => (await digest.$$('[data-testid="workflow-agent-pill"]').length) === 3,
  102. { timeout: 60000, timeoutMsg: "run 卡没有画出三枚子代理药丸" },
  103. );
  104. const stations = await readStationStatuses(digest);
  105. expect(stations.map((station) => station.text)).toEqual([
  106. expect.stringContaining("调研"),
  107. expect.stringContaining("汇总"),
  108. ]);
  109. expect(Object.keys(await readPillStatuses(digest)).sort()).toEqual([...AGENTS].sort());
  110. // 运行态:第二阶段子代理的回答被挂起,第一阶段两人已完成,汇总员在跑。
  111. await browser.waitUntil(
  112. async () => {
  113. const pills = await readPillStatuses(digest);
  114. return (
  115. pills["调研员甲"] === "done" &&
  116. pills["调研员乙"] === "done" &&
  117. pills["汇总员"] === "running"
  118. );
  119. },
  120. {
  121. timeout: 120000,
  122. timeoutMsg: "第一阶段没有完成,或汇总员没有进入运行态",
  123. },
  124. );
  125. expect(await digest.getAttribute("data-workflow-run-status")).toBe("running");
  126. expect(await (await digest.$('[data-testid="workflow-card-kind"]')).getText()).toContain(
  127. "工作流运行中",
  128. );
  129. expect((await readStationStatuses(digest)).map((station) => station.status)).toEqual([
  130. "done",
  131. "running",
  132. ]);
  133. // 侧栏运行行:live run 总是画出,写当前阶段名(presentation.md「The sidebar run line」)。
  134. const line = await $(RUN_LINE);
  135. await line.waitForDisplayed({ timeout: 60000 });
  136. await browser.waitUntil(async () => (await line.getText()).includes("汇总"), {
  137. timeout: 60000,
  138. timeoutMsg: "侧栏运行行没有写出当前阶段「汇总」",
  139. });
  140. await releaseControlledReplay(HELD_AGENT_FIXTURE);
  141. await browser.waitUntil(
  142. async () => (await digest.getAttribute("data-workflow-run-status")) === "completed",
  143. { timeout: 120000, timeoutMsg: "run 没有到达完成态" },
  144. );
  145. expect(await (await digest.$('[data-testid="workflow-card-kind"]')).getText()).toContain(
  146. "工作流已完成",
  147. );
  148. expect(Object.values(await readPillStatuses(digest))).toEqual(["done", "done", "done"]);
  149. // 发起行折成一行摘要「工作流 · 3 个子代理 ↗」。已结束一轮的工具行收在「已处理」折叠里(默认收起),
  150. // 发起行在第一轮:先展开第一轮的折叠再读。
  151. await browser.execute(() => {
  152. const first = document.querySelector<HTMLElement>(
  153. '[data-testid^="chat-assistant-history-trigger-"]',
  154. );
  155. if (first?.dataset.historyOpen === "false") first.click();
  156. });
  157. const summary = await $(
  158. `[data-testid="workflow-tool-summary"][data-workflow-run-id="${runId}"]`,
  159. );
  160. await summary.waitForDisplayed({ timeout: 30000 });
  161. // 折叠展开动画期间 getText 读到空串(dwr-4):等 DOM 文字本身写出计数。
  162. await browser.waitUntil(
  163. async () =>
  164. (
  165. await browser.execute(
  166. (id: string) =>
  167. document.querySelector(
  168. `[data-testid="workflow-tool-summary"][data-workflow-run-id="${id}"] [data-testid="workflow-summary-agents"]`,
  169. )?.textContent ?? "",
  170. runId,
  171. )
  172. ).includes("3 个子代理"),
  173. { timeout: 30000, timeoutMsg: "发起行摘要没有写出「3 个子代理」" },
  174. );
  175. });
  176. it("DWR-02 完成通知把返回值交给主代理,通知行可展开出结果,收尾回复之后出现完成卡与四格数字", async function () {
  177. this.timeout(180000);
  178. // 完成通知:<task-notification> 带 completed 状态与脚本返回值(transcript-and-notifications.md「What the model reads」)。
  179. await waitForV4AssistantMessageContaining("E2E_DWR_DONE", 120000);
  180. const [notified] = await getUpstreamRequestEvidence({
  181. lastUserMessageIncludes: ["<task-notification>"],
  182. });
  183. expect(notified?.fixtureId).toBe("dwr-notified");
  184. const notifiedBody = JSON.stringify(notified?.requestJson);
  185. expect(notifiedBody).toContain(`<description>${RUN_NAME}</description>`);
  186. expect(notifiedBody).toContain("<result>");
  187. for (const answer of ["E2E_DWR_ANSWER_A", "E2E_DWR_ANSWER_B", "E2E_DWR_ANSWER_C"]) {
  188. expect(notifiedBody).toContain(answer);
  189. }
  190. // 通知行:「工作流已完成 · 名字」,展开体是返回值。
  191. const row = await $('[data-testid^="chat-workflow-notification-row-"]');
  192. await row.waitForDisplayed({ timeout: 60000 });
  193. expect(await row.getText()).toContain("工作流已完成");
  194. expect(await row.getText()).toContain(RUN_NAME);
  195. await row.$('[role="button"]').click();
  196. const result = await row.$('[data-testid="workflow-notification-result"]');
  197. await result.waitForDisplayed({ timeout: 10000 });
  198. await expect(result).toHaveText(expect.stringContaining("E2E_DWR_ANSWER_C"));
  199. // 完成卡:头部「工作流已完成」+ 名字 + ⤢;没有产物就不画产物区;四格数字依次是时间、tokens、子代理、阶段。
  200. const card = await $(COMPLETION_CARD);
  201. await card.waitForDisplayed({ timeout: 60000 });
  202. expect(await card.$('[data-testid="workflow-card-kind"]').getText()).toContain("工作流已完成");
  203. expect(await (await card.$('[data-testid="workflow-card-name"]').getText()).trim()).toBe(
  204. RUN_NAME,
  205. );
  206. await expect(card.$('[data-testid="workflow-card-open-details"]')).toBeExisting();
  207. await expect(card.$('[data-testid^="workflow-artifact"]')).not.toBeExisting();
  208. // 数字可能在做计数动画;等它停在终值,再读。
  209. await browser.waitUntil(
  210. async () =>
  211. (await card
  212. .$('[data-testid="workflow-completion-figure-subagents"]')
  213. .getAttribute("data-value")) === "3" &&
  214. (await card
  215. .$('[data-testid="workflow-completion-figure-phases"]')
  216. .getAttribute("data-value")) === "2",
  217. { timeout: 10000, timeoutMsg: "完成卡的子代理 / 阶段数字不是 3 / 2" },
  218. );
  219. // 时间与 tokens 都拿得到:不是「—」。
  220. for (const key of ["time", "tokens"]) {
  221. const figure = await card.$(`[data-testid="workflow-completion-figure-${key}"]`);
  222. expect(await figure.getAttribute("data-value")).toBeTruthy();
  223. expect(await figure.getText()).not.toContain("—");
  224. }
  225. expect(await card.$('[data-testid="workflow-completion-figures"]').getText()).toEqual(
  226. expect.stringMatching(/时间[\s\S]*tokens[\s\S]*子代理[\s\S]*阶段/),
  227. );
  228. });
  229. it("DWR-03 从完成卡打开 run 侧板:两段阶段、结果面板,打开子代理看到它的回答;会话在前台时完成的 run 不在侧栏留运行行", async function () {
  230. this.timeout(180000);
  231. await (await $(COMPLETION_CARD).$('[data-testid="workflow-card-open-details"]')).click();
  232. const phases = await $('[data-testid="workflow-run-phases"]');
  233. await phases.waitForDisplayed({ timeout: 60000 });
  234. const sections = await phases.$$('[data-testid="workflow-run-phase"]');
  235. expect(sections).toHaveLength(2);
  236. expect(await sections[0]!.$('[data-testid="workflow-run-phase-toggle"]').getText()).toContain(
  237. "调研",
  238. );
  239. expect(await sections[1]!.$('[data-testid="workflow-run-phase-toggle"]').getText()).toContain(
  240. "汇总",
  241. );
  242. for (const section of sections) {
  243. expect(await section.getAttribute("data-phase-status")).toBe("done");
  244. }
  245. // 结果面板:completed 写「结果」。
  246. const pane = await $(
  247. `div[data-workflow-run-id="${runId}"]:has([data-testid="workflow-run-phases"])`,
  248. );
  249. expect(await pane.getAttribute("data-workflow-run-status")).toBe("completed");
  250. expect(await pane.getText()).toContain("结果");
  251. // 展开「调研」:两行药丸是两位调研员。
  252. const research = sections[0]!;
  253. if ((await research.getAttribute("data-phase-open")) !== "true") {
  254. await research.$('[data-testid="workflow-run-phase-toggle"]').click();
  255. }
  256. await research
  257. .$('[data-testid="workflow-run-phase-body"]')
  258. .waitForDisplayed({ timeout: 10000 });
  259. const researchPills = await readPillStatuses(research);
  260. expect(Object.keys(researchPills).some((name) => name.includes("调研员甲"))).toBe(true);
  261. expect(Object.keys(researchPills).some((name) => name.includes("调研员乙"))).toBe(true);
  262. // 打开调研员甲:子代理 transcript 里有它(回放)的回答。
  263. let openedFirst = false;
  264. for (const pill of await research.$$(
  265. '[data-testid="workflow-agent-pill"][data-agent-open="true"]',
  266. )) {
  267. if ((await pill.getText()).includes("调研员甲")) {
  268. await pill.click();
  269. openedFirst = true;
  270. break;
  271. }
  272. }
  273. expect(openedFirst).toBe(true);
  274. await browser.waitUntil(
  275. async () =>
  276. browser.execute(() =>
  277. Array.from(document.querySelectorAll<HTMLElement>('[data-session-id^="sess_dwf-"]')).some(
  278. (pane) => (pane.textContent ?? "").includes("E2E_DWR_ANSWER_A"),
  279. ),
  280. ),
  281. { timeout: 60000, timeoutMsg: "子代理 transcript 没有显示调研员甲的回答" },
  282. );
  283. // 侧栏运行行:run 在会话打开时结束即被确认,运行行随即收起(presentation.md「Acknowledgement」)。
  284. await browser.waitUntil(async () => !(await $(RUN_LINE).isExisting()), {
  285. timeout: 30000,
  286. timeoutMsg: "会话在前台时完成的 run 仍在侧栏留着运行行",
  287. });
  288. });
  289. });