conversation-session-dynamic-workflow-gray-always-on-stop.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import { TID_CHAT_WORKFLOW_RUN_DIGEST } from "@zcode/shared";
  2. import { clearAppData, pinE2ELocale } from "#e2e/helpers/desktop-app";
  3. import {
  4. approveV4Permission,
  5. getV4ComposerBackgroundWorkCounts,
  6. prepareV4ConversationE2E,
  7. sendV4Prompt,
  8. waitForV4AssistantMessageContaining,
  9. waitForV4Pane,
  10. } from "#e2e/helpers/v4-conversation";
  11. import {
  12. getLatestUpstreamToolResultByToolCallId,
  13. waitForUpstreamRequest,
  14. } from "#e2e/helpers/conversation-session-network";
  15. // 用户从 GUI 停止一次在跑的 run(docs/dynamic-workflow/presentation.md「The run card」「The run pane」
  16. // 「The sidebar run line」、docs/dynamic-workflow/transcript-and-notifications.md「The notification row」
  17. // 「What the model reads」):卡、侧板、侧栏运行行一起落到「已停止 · 你停止的」,主代理收到
  18. // stop-reason=user 的通知,对话还能接着走。
  19. //
  20. // case-local 回放只决定主模型的选择;真实 Skill、工作流编译、审批、run 引擎、停止与通知走产品链路。
  21. // 脚本零 agent,靠 `world.run("sleep", …)` 停在 running(沙箱里没有 setTimeout),sleep 远长于本用例。
  22. const RUN_DIGEST = `[data-testid^="${TID_CHAT_WORKFLOW_RUN_DIGEST}"]`;
  23. const RUN_NAME = "E2E 停止工作流";
  24. let runId = "";
  25. describe("动态工作流 · 停止在跑的 run", () => {
  26. before(async () => {
  27. await prepareV4ConversationE2E();
  28. // 断言中文文案:固定界面语言,不跟随宿主系统语言(容器里默认英文)。
  29. await pinE2ELocale("zh-CN");
  30. });
  31. after(async () => {
  32. await browser.electron.restoreAllMocks();
  33. await clearAppData();
  34. });
  35. it("DWX-01 从 run 卡停止:卡、侧板、侧栏运行行都落到「已停止 · 你停止的」,没有一处还显示运行中", async function () {
  36. this.timeout(240000);
  37. await sendV4Prompt("E2E_DWX_START 使用工作流跑一个长时间等待的任务。");
  38. await approveV4Permission();
  39. await browser.waitUntil(
  40. async () =>
  41. (await getLatestUpstreamToolResultByToolCallId("toolu_dwx_create"))?.isError === false,
  42. { timeout: 60_000, timeoutMsg: "CreateWorkflow 未执行成功" },
  43. );
  44. // 启动轮先收尾,停止通知才会唤起自己的一轮,而不是被并进启动轮。
  45. await waitForV4AssistantMessageContaining("E2E_DWX_STARTED", 60000);
  46. await waitForV4Pane((pane) => !pane.canStop, "启动轮没有结束", 30000);
  47. // 每次都按 DOM 现读:工具行从流式态换成定稿态时卡会重挂,缓存的元素引用会过期。
  48. let digests: DigestSnapshot[] = [];
  49. try {
  50. await browser.waitUntil(
  51. async () => {
  52. digests = await readDigests();
  53. return digests.some((item) => item.status === "running");
  54. },
  55. { timeout: 60000 },
  56. );
  57. } catch {
  58. throw new Error(`run 卡没有进入 running; digests=${JSON.stringify(digests)}`);
  59. }
  60. runId = digests.find((item) => item.status === "running")?.runId ?? "";
  61. expect(runId).not.toBe("");
  62. const digest = await $(`${RUN_DIGEST}[data-workflow-run-id="${runId}"]`);
  63. await expect(digest.$('[data-testid="workflow-card-kind"]')).toHaveText(
  64. expect.stringContaining("工作流运行中"),
  65. );
  66. // 停之前三处都在说「运行中」:侧栏运行行、composer 徽标、侧板。
  67. const runLine = `[data-workflow-run-line][data-run-id="${runId}"]`;
  68. await browser.waitUntil(
  69. async () => (await $(runLine).getAttribute("data-run-status")) === "running",
  70. { timeout: 60000, timeoutMsg: "侧栏没有长出 running 的运行行" },
  71. );
  72. // 运行行写当前阶段名(「The sidebar run line」)。阶段标记可能比 run-started 晚一帧到,所以等它;
  73. // 不在这里断言,先把停止链路走完,再在用例末尾判定,避免一个文案问题挡住停止的证据。
  74. let runLineText = "";
  75. let cardStationText = "";
  76. await browser
  77. .waitUntil(
  78. async () => {
  79. runLineText = await $(runLine).getText();
  80. return runLineText.includes("等待");
  81. },
  82. { timeout: 20000 },
  83. )
  84. .catch(() => undefined);
  85. cardStationText = await browser.execute(
  86. (selector) =>
  87. Array.from(document.querySelectorAll(selector))
  88. .map((station) => station.textContent ?? "")
  89. .join(" | "),
  90. `${RUN_DIGEST}[data-workflow-run-id="${runId}"] [data-testid="workflow-timeline-station"]`,
  91. );
  92. await browser.waitUntil(
  93. async () => (await getV4ComposerBackgroundWorkCounts())?.workflowCount === 1,
  94. { timeout: 30000, timeoutMsg: "composer 徽标没有计入在跑的工作流" },
  95. );
  96. await digest.$('[data-testid="workflow-card-open-details"]').click();
  97. const paneCancel = await $('[data-testid="workflow-run-cancel"]');
  98. await paneCancel.waitForDisplayed({ timeout: 30000 });
  99. await browser.waitUntil(async () => paneCancel.isEnabled(), {
  100. timeout: 30000,
  101. timeoutMsg: "侧板的「停止运行」在 running 时不可用",
  102. });
  103. await expect($('[data-testid="workflow-run-status"]')).toHaveText("运行中");
  104. // 按下后按钮禁用、名字换成「正在停止…」,直到状态变化让它重挂(无确认窗)。这是个瞬态:
  105. // 投影可能很快把状态换掉,所以在点击前挂观察器记录,不靠抢时序读 DOM。
  106. await browser.execute(() => {
  107. const probe = window as Window & { __dwxStoppingSeen?: boolean };
  108. probe.__dwxStoppingSeen = false;
  109. const seen = () =>
  110. Array.from(
  111. document.querySelectorAll<HTMLButtonElement>('[data-testid="workflow-digest-cancel"]'),
  112. ).some((button) => button.disabled && button.getAttribute("aria-label") === "正在停止…");
  113. const observer = new MutationObserver(() => {
  114. if (seen()) {
  115. probe.__dwxStoppingSeen = true;
  116. observer.disconnect();
  117. }
  118. });
  119. observer.observe(document.body, {
  120. subtree: true,
  121. attributes: true,
  122. attributeFilter: ["disabled", "aria-label"],
  123. });
  124. });
  125. const cardCancel = await digest.$('[data-testid="workflow-digest-cancel"]');
  126. await expect(cardCancel).toHaveAttribute("aria-label", "停止运行");
  127. await cardCancel.click();
  128. // 卡:种类词换成「工作流已停止」,Stop 退场,停下的 run 可恢复,所以 Resume 进场。
  129. try {
  130. await browser.waitUntil(
  131. async () => {
  132. digests = await readDigests();
  133. return digests.some((item) => item.runId === runId && item.status === "stopped");
  134. },
  135. { timeout: 60000 },
  136. );
  137. } catch {
  138. throw new Error(`run 卡没有落到 stopped; digests=${JSON.stringify(digests)}`);
  139. }
  140. expect(
  141. await browser.execute(
  142. () => (window as Window & { __dwxStoppingSeen?: boolean }).__dwxStoppingSeen,
  143. ),
  144. ).toBe(true);
  145. await expect(digest.$('[data-testid="workflow-card-kind"]')).toHaveText(
  146. expect.stringContaining("工作流已停止"),
  147. );
  148. await expect(digest.$('[data-testid="workflow-digest-cancel"]')).not.toBeExisting();
  149. await expect(digest.$('[data-testid="workflow-digest-resume"]')).toBeDisplayed();
  150. // 侧板:状态行「已停止 · 你停止的」,Stop 仍在但不可用,Resume 出现,结果面板写「实例已停止 · 你停止的」。
  151. await expect($('[data-testid="workflow-run-status"]')).toHaveText("已停止");
  152. await expect($('[data-testid="workflow-run-status-reason"]')).toHaveText(
  153. expect.stringContaining("你停止的"),
  154. );
  155. await expect($('[data-testid="workflow-run-cancel"]')).toBeDisabled();
  156. await expect($('[data-testid="workflow-run-resume"]')).toBeDisplayed();
  157. const errorPanel = await $('[data-testid="workflow-run-error"]');
  158. await errorPanel.waitForDisplayed({ timeout: 30000 });
  159. expect(await errorPanel.getText()).toContain("实例已停止");
  160. await expect($('[data-testid="workflow-run-stop-reason"]')).toHaveText(
  161. expect.stringContaining("你停止的"),
  162. );
  163. // 侧栏:会话正打开着,run 在读者眼前结束即被确认,运行行折叠;任何地方都不再有 running 的运行行。
  164. await browser.waitUntil(async () => !(await $(runLine).isExisting()), {
  165. timeout: 30000,
  166. timeoutMsg: "当前会话里停下的 run 的运行行没有折叠",
  167. });
  168. await expect($('[data-workflow-run-line][data-run-status="running"]')).not.toBeExisting();
  169. // composer 徽标不再计入这条工作流。
  170. await browser.waitUntil(
  171. async () => ((await getV4ComposerBackgroundWorkCounts())?.workflowCount ?? 0) === 0,
  172. { timeout: 30000, timeoutMsg: "composer 徽标仍在计入已停止的工作流" },
  173. );
  174. expect({ runLineText, cardStationText }).toEqual({
  175. runLineText: expect.stringContaining("等待"),
  176. cardStationText: expect.stringContaining("等待"),
  177. });
  178. });
  179. it("DWX-02 主代理读到 stop-reason=user 的通知;通知行写「工作流已停止 · 你停止的」,对话可以继续", async function () {
  180. this.timeout(180000);
  181. // 模型读到的终态通知:status=stopped、stop-reason=user、摘要句与「用户有意停止」的交付指引。
  182. await waitForUpstreamRequest(
  183. {
  184. lastUserMessageIncludes: [
  185. "<task-notification>",
  186. "<status>stopped</status>",
  187. "<stop-reason>user</stop-reason>",
  188. `<description>${RUN_NAME}</description>`,
  189. // 摘要句里的引号按 XML 转义成 &quot;,只匹配句尾。
  190. "was stopped by the user.</summary>",
  191. "The user stopped this workflow on purpose.",
  192. ],
  193. },
  194. "主代理没有收到 stop-reason=user 的停止通知",
  195. 60000,
  196. );
  197. await waitForV4AssistantMessageContaining("E2E_DWX_NOTIFIED", 60000);
  198. // 通知行:工作流图标的工具行,种类词带原因词,主文本是 run 名。
  199. const row = await $(
  200. `//*[starts-with(@data-testid, "chat-workflow-notification-row-")][contains(., "工作流已停止 · 你停止的")]`,
  201. );
  202. await row.waitForDisplayed({ timeout: 30000 });
  203. expect(await row.getText()).toContain(RUN_NAME);
  204. // 对话继续:下一条提示正常得到回复,停下的 run 仍是 stopped(主代理没有自行恢复它)。
  205. await waitForV4Pane((pane) => !pane.canStop, "停止通知的回复轮没有结束", 30000);
  206. await sendV4Prompt("E2E_DWX_AFTER 好的,接下来做别的。");
  207. await waitForV4AssistantMessageContaining("E2E_DWX_AFTER_OK", 60000);
  208. await expect($(`${RUN_DIGEST}[data-workflow-run-id="${runId}"]`)).toHaveAttribute(
  209. "data-workflow-run-status",
  210. "stopped",
  211. );
  212. });
  213. });
  214. interface DigestSnapshot {
  215. runId: string | null;
  216. status: string | null;
  217. kind: string | null;
  218. }
  219. /** 读当前 DOM 里所有 run 卡的 run id、状态与种类词;失败时连同快照一起报出。 */
  220. function readDigests(): Promise<DigestSnapshot[]> {
  221. return browser.execute((selector) => {
  222. return Array.from(document.querySelectorAll<HTMLElement>(selector)).map((card) => ({
  223. runId: card.getAttribute("data-workflow-run-id"),
  224. status: card.getAttribute("data-workflow-run-status"),
  225. kind: card.querySelector('[data-testid="workflow-card-kind"]')?.textContent ?? null,
  226. }));
  227. }, RUN_DIGEST);
  228. }