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

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