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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import type { ChainablePromiseElement } from "webdriverio";
  2. import { mkdir, rm, writeFile } from "node:fs/promises";
  3. import { dirname } from "node:path";
  4. import { TID_CHAT_WORKFLOW_RUN_DIGEST } from "@zcode/shared";
  5. import { clearAppData, pinE2ELocale } from "#e2e/helpers/desktop-app";
  6. import { releaseControlledReplay } from "#e2e/helpers/controlled-replay";
  7. import { resolveE2ERuntimePath } from "#e2e/helpers/e2e-runtime-paths";
  8. import {
  9. approveV4Permission,
  10. getV4PaneSnapshot,
  11. prepareV4ConversationE2E,
  12. sendV4Prompt,
  13. waitForV4AssistantMessageContaining,
  14. waitForV4Pane,
  15. } from "#e2e/helpers/v4-conversation";
  16. import {
  17. countUpstreamRequests,
  18. findFirstUpstreamRequestIndex,
  19. getLatestUpstreamToolResultByToolCallId,
  20. getUpstreamRequestEvidence,
  21. waitForUpstreamRequest,
  22. type UpstreamRequestQuery,
  23. } from "#e2e/helpers/conversation-session-network";
  24. // run 自己结束时主代理怎么知道(docs/dynamic-workflow/transcript-and-notifications.md「Notifications」
  25. // 「The notification row」「What the model reads」「The completion card」):主代理闲着时 run 结束,
  26. // 通知唤起一轮,模型读到 `<task-notification>`,时间线画出工作流通知行;完成的那轮回复尾部长出完成卡。
  27. //
  28. // case-local 回放只决定主模型的选择;真实 Skill、工作流编译、审批、run 引擎、通知的铸造与投递走产品链路。
  29. // 脚本零 agent,用 `world.run("node", …)` 等一个闸文件:用例在主代理那一轮收尾之后才写闸文件,
  30. // run 何时结束由用例决定,不靠计时。
  31. const RUN_DIGEST = `[data-testid^="${TID_CHAT_WORKFLOW_RUN_DIGEST}"]`;
  32. const NOTIFICATION_ROW = `div[data-testid^="chat-workflow-notification-row-"]`;
  33. const COMPLETION_CARD = `[data-testid^="workflow-completion-card-"]`;
  34. const OK_RUN = "E2E 通知完成工作流";
  35. const FAIL_RUN = "E2E 通知出错工作流";
  36. const BUSY_RUN = "E2E 通知忙碌工作流";
  37. const SYSTEM_BANNER = "[SYSTEM NOTIFICATION - NOT USER INPUT]";
  38. const notificationQuery = (marker: string): UpstreamRequestQuery => ({
  39. lastUserMessageIncludes: ["<task-notification>", marker],
  40. });
  41. describe("动态工作流 · run 结束的通知", () => {
  42. before(async () => {
  43. await prepareV4ConversationE2E();
  44. // 断言中文文案:固定界面语言,不跟随宿主系统语言(容器里默认英文)。
  45. await pinE2ELocale("zh-CN");
  46. await Promise.all(["ok", "fail", "busy"].map((name) => rm(gatePath(name), { force: true })));
  47. });
  48. after(async () => {
  49. await browser.electron.restoreAllMocks();
  50. await clearAppData();
  51. });
  52. it("DWN-01 完成:闲着的主代理被唤起,读到 completed 载荷;通知行「工作流已完成」展开是 JSON 结果;回复尾部有完成卡", async function () {
  53. this.timeout(300000);
  54. const runId = await launchIdleRun(
  55. "ok",
  56. "E2E_DWN_OK_START 用工作流检查三个文件,放行后返回结论。",
  57. );
  58. await openGate("ok");
  59. await waitForUpstreamRequest(
  60. notificationQuery("E2E_DWN_OK_RESULT"),
  61. "完成通知没有唤起主代理",
  62. 120000,
  63. );
  64. const payload = await readNotificationText(notificationQuery("E2E_DWN_OK_RESULT"));
  65. expect(payload).toContain(SYSTEM_BANNER);
  66. expect(payload).toContain(`<task-id>${runId}</task-id>`);
  67. expect(payload).toContain("<tool-use-id>toolu_dwn_ok_create</tool-use-id>");
  68. expect(payload).toContain("<status>completed</status>");
  69. expect(payload).not.toContain("<stop-reason>");
  70. expect(payload).toContain(`<description>${OK_RUN}</description>`);
  71. expect(payload).toContain(`<summary>Workflow "${OK_RUN}" completed.</summary>`);
  72. // `<result>` 是脚本的返回值,不回落到启动输出。
  73. expect(payload).toMatch(/<result>[\s\S]*"verdict":\s*"E2E_DWN_OK_RESULT"[\s\S]*<\/result>/u);
  74. expect(payload).not.toContain("<error>");
  75. // 交付指引在块之后:按交付物呈现结论。
  76. expect(payload.indexOf("</task-notification>")).toBeLessThan(
  77. payload.lastIndexOf("deliverable"),
  78. );
  79. await waitForV4AssistantMessageContaining("E2E_DWN_OK_DIGESTED", 120000);
  80. await waitForV4Pane((pane) => !pane.canStop, "完成通知那一轮没有结束", 60000);
  81. const row = await waitForNotificationRow("工作流已完成", OK_RUN);
  82. expect(await row.$('[data-testid="workflow-notification-result"]').isExisting()).toBe(false);
  83. await row.$('[role="button"]').click();
  84. const result = await row.$('[data-testid="workflow-notification-result"]');
  85. await result.waitForDisplayed({ timeout: 10000 });
  86. // JSON 结果在代码块里按缩进排版(不是原样一行)。
  87. await browser.waitUntil(
  88. async () => /"verdict":\s+"E2E_DWN_OK_RESULT"/u.test(await result.getText()),
  89. { timeout: 10000, timeoutMsg: "展开体没有画出 JSON 结果" },
  90. );
  91. expect(await result.getText()).toContain('"checked": 3');
  92. // 完成卡只在消化完成通知的那一轮尾部出现,一轮一张。
  93. await expect($$(COMPLETION_CARD)).toBeElementsArrayOfSize(1);
  94. expect(await countUpstreamRequests(notificationQuery("E2E_DWN_OK_RESULT"))).toBe(1);
  95. // 展开体以「查看实例详情」收尾:活会话里宿主能开侧板,投影也认得这次 run 的工具调用 id。
  96. await expectOpenRunLink(result, runId);
  97. });
  98. it("DWN-02 出错:载荷 status=errored 带 error 与 AmendWorkflow 指引;通知行「工作流出错」展开是错误面板;没有完成卡", async function () {
  99. this.timeout(300000);
  100. const runId = await launchIdleRun(
  101. "fail",
  102. "E2E_DWN_FAIL_START 用工作流读取清单,放行后按清单汇总。",
  103. );
  104. await openGate("fail");
  105. await waitForUpstreamRequest(
  106. notificationQuery("E2E_DWN_FAIL_BOOM"),
  107. "出错通知没有唤起主代理",
  108. 120000,
  109. );
  110. const payload = await readNotificationText(notificationQuery("E2E_DWN_FAIL_BOOM"));
  111. expect(payload).toContain(SYSTEM_BANNER);
  112. expect(payload).toContain(`<task-id>${runId}</task-id>`);
  113. expect(payload).toContain("<status>errored</status>");
  114. expect(payload).toContain(
  115. `<summary>Workflow "${FAIL_RUN}" errored: the script failed.</summary>`,
  116. );
  117. expect(payload).toMatch(/<error>[\s\S]*E2E_DWN_FAIL_BOOM[\s\S]*<\/error>/u);
  118. // 出错的指引:修脚本后用 AmendWorkflow 提交;ResumeWorkflowRun 会拒绝出错的 run。
  119. const guidance = payload.slice(payload.indexOf("</task-notification>"));
  120. expect(guidance).toContain(`AmendWorkflow (run_id="${runId}"`);
  121. // run 记下了脚本文件:指引点名它,让模型就地编辑并传 `path`,不再贴脚本。
  122. expect(guidance).toMatch(/\.dwf\.ts\. Edit that file in place[\s\S]*path="/u);
  123. await waitForV4AssistantMessageContaining("E2E_DWN_FAIL_DIGESTED", 120000);
  124. await waitForV4Pane((pane) => !pane.canStop, "出错通知那一轮没有结束", 60000);
  125. const row = await waitForNotificationRow("工作流出错", FAIL_RUN);
  126. await row.$('[role="button"]').click();
  127. await browser.waitUntil(async () => (await row.getText()).includes("E2E_DWN_FAIL_BOOM"), {
  128. timeout: 10000,
  129. timeoutMsg: "展开体没有画出错误",
  130. });
  131. // 错误在错误面板里,不是结果体。
  132. expect(await row.$('[data-testid="workflow-notification-result"]').isExisting()).toBe(false);
  133. await expect(row.$('p[class*="border-destructive"]')).toHaveText(
  134. expect.stringContaining("E2E_DWN_FAIL_BOOM"),
  135. );
  136. // 出错的 run 没有完成卡:只有 DWN-01 那一张。
  137. await expect($$(COMPLETION_CARD)).toBeElementsArrayOfSize(1);
  138. expect(await countUpstreamRequests(notificationQuery("E2E_DWN_FAIL_BOOM"))).toBe(1);
  139. });
  140. it("DWN-03 主代理忙着时 run 结束:通知不另起并行请求,这一轮结束后恰好送达一次", async function () {
  141. this.timeout(300000);
  142. const runId = await launchIdleRun("busy", "E2E_DWN_BUSY_START 用工作流跑一个等放行的任务。");
  143. // 主代理开一轮新的,回放停在流中途:主代理忙着。
  144. await sendV4Prompt("E2E_DWN_BUSY_HOLD 先回答我一个问题。");
  145. await waitForUpstreamRequest(
  146. { lastUserMessageIncludes: ["E2E_DWN_BUSY_HOLD"] },
  147. "忙碌的那一轮没有发出请求",
  148. 60000,
  149. );
  150. await waitForV4Pane((pane) => pane.canStop, "忙碌的那一轮没有进入运行态", 30000);
  151. // 忙着的时候 run 结束。
  152. await openGate("busy");
  153. await browser.waitUntil(
  154. async () => (await runDigest(runId).getAttribute("data-workflow-run-status")) === "completed",
  155. { timeout: 120000, timeoutMsg: "忙碌期间 run 没有结束" },
  156. );
  157. // run 已结束而这一轮还卡在流中途:通知没有另起一个并行的模型请求。
  158. expect((await getV4PaneSnapshot()).canStop).toBe(true);
  159. expect(await countUpstreamRequests(notificationQuery("E2E_DWN_BUSY_RESULT"))).toBe(0);
  160. const holdIndex = await findFirstUpstreamRequestIndex({
  161. lastUserMessageIncludes: ["E2E_DWN_BUSY_HOLD"],
  162. });
  163. await releaseControlledReplay("dwn-busy-hold");
  164. await waitForV4AssistantMessageContaining("E2E_DWN_BUSY_HELD", 60000);
  165. await waitForUpstreamRequest(
  166. notificationQuery("E2E_DWN_BUSY_RESULT"),
  167. "忙碌期间结束的 run 的通知没有送达",
  168. 120000,
  169. );
  170. const notifiedIndex = await findFirstUpstreamRequestIndex(
  171. notificationQuery("E2E_DWN_BUSY_RESULT"),
  172. );
  173. expect(notifiedIndex).not.toBeNull();
  174. expect(notifiedIndex!).toBeGreaterThan(holdIndex!);
  175. const payload = await readNotificationText(notificationQuery("E2E_DWN_BUSY_RESULT"));
  176. expect(payload).toContain(`<task-id>${runId}</task-id>`);
  177. expect(payload).toContain("<status>completed</status>");
  178. expect(payload).toContain(`<summary>Workflow "${BUSY_RUN}" completed.</summary>`);
  179. await waitForV4AssistantMessageContaining("E2E_DWN_BUSY_DIGESTED", 120000);
  180. await waitForV4Pane((pane) => !pane.canStop, "忙碌通知那一轮没有结束", 60000);
  181. await waitForNotificationRow("工作流已完成", BUSY_RUN);
  182. // 不丢也不重:恰好一次。
  183. expect(await countUpstreamRequests(notificationQuery("E2E_DWN_BUSY_RESULT"))).toBe(1);
  184. });
  185. });
  186. function gatePath(name: string) {
  187. return resolveE2ERuntimePath(`dwn-gate-${name}`);
  188. }
  189. /** 写闸文件:脚本里的 `world.run("node", …)` 看到它就退出,run 随之结束。 */
  190. async function openGate(name: string) {
  191. const path = gatePath(name);
  192. await mkdir(dirname(path), { recursive: true });
  193. await writeFile(path, "open\n");
  194. }
  195. /** 等展开体里出现「查看实例详情」;等不到时把 run 卡与投影的现场带进失败信息,便于区分时序与联查缺失。 */
  196. async function expectOpenRunLink(body: ChainablePromiseElement, runId: string) {
  197. const appeared = await browser
  198. .waitUntil(async () => (await body.getText()).includes("查看实例详情"), { timeout: 15000 })
  199. .then(() => true)
  200. .catch(() => false);
  201. if (appeared) return;
  202. const digest = runDigest(runId);
  203. const digestExists = await digest.isExisting();
  204. const evidence = {
  205. bodyText: await body.getText(),
  206. digestExists,
  207. digestStatus: digestExists ? await digest.getAttribute("data-workflow-run-status") : null,
  208. digestOpenLinks: digestExists
  209. ? await digest.$$("button").map((button) => button.getText())
  210. : [],
  211. };
  212. throw new Error(`通知行展开体没有「查看实例详情」:${JSON.stringify(evidence)}`);
  213. }
  214. function runDigest(runId: string) {
  215. return $(`${RUN_DIGEST}[data-workflow-run-id="${runId}"]`);
  216. }
  217. /**
  218. * 发启动指令、批准、等启动轮收尾,返回新 run 的 id;返回时主代理闲着、run 停在闸上。
  219. * 启动轮先收尾,通知才会唤起自己的一轮,而不是被并进启动轮。
  220. */
  221. async function launchIdleRun(name: "ok" | "fail" | "busy", prompt: string) {
  222. const known = new Set(
  223. await browser.execute(
  224. (selector) =>
  225. Array.from(document.querySelectorAll(selector)).map(
  226. (node) => node.getAttribute("data-workflow-run-id") ?? "",
  227. ),
  228. RUN_DIGEST,
  229. ),
  230. );
  231. await sendV4Prompt(prompt);
  232. await approveV4Permission();
  233. await browser.waitUntil(
  234. async () =>
  235. (await getLatestUpstreamToolResultByToolCallId(`toolu_dwn_${name}_create`))?.isError ===
  236. false,
  237. { timeout: 60_000, timeoutMsg: "CreateWorkflow 未执行成功" },
  238. );
  239. await waitForV4AssistantMessageContaining(`E2E_DWN_${name.toUpperCase()}_STARTED`, 60000);
  240. await waitForV4Pane((pane) => !pane.canStop, "启动轮没有结束", 30000);
  241. let runId = "";
  242. await browser.waitUntil(
  243. async () => {
  244. const ids = await browser.execute(
  245. (selector) =>
  246. Array.from(document.querySelectorAll(selector))
  247. .filter((node) => node.getAttribute("data-workflow-run-status") === "running")
  248. .map((node) => node.getAttribute("data-workflow-run-id") ?? ""),
  249. RUN_DIGEST,
  250. );
  251. runId = ids.find((id) => id !== "" && !known.has(id)) ?? "";
  252. return runId !== "";
  253. },
  254. { timeout: 60000, timeoutMsg: "新 run 的卡没有进入 running" },
  255. );
  256. // 闸还没开:主代理闲着,run 停在 world.run 上,没有任何通知。
  257. expect(
  258. await countUpstreamRequests({ lastUserMessageIncludes: ["<task-notification>", runId] }),
  259. ).toBe(0);
  260. return runId;
  261. }
  262. /**
  263. * 唤起那一轮请求里最后一条 user 消息的文本:模型读到的通知全文。
  264. * 块里的字段值按 XML 转义(`"` → `&quot;`),断言比的是模型读到的字,先还原实体。
  265. */
  266. async function readNotificationText(query: UpstreamRequestQuery): Promise<string> {
  267. const [evidence] = await getUpstreamRequestEvidence(query);
  268. const messages = (evidence?.requestJson as { messages?: unknown } | undefined)?.messages;
  269. if (!Array.isArray(messages)) return "";
  270. const last = [...messages]
  271. .reverse()
  272. .find((message) => (message as { role?: unknown } | null)?.role === "user") as
  273. | { content?: unknown }
  274. | undefined;
  275. const content = last?.content;
  276. const text =
  277. typeof content === "string"
  278. ? content
  279. : Array.isArray(content)
  280. ? content
  281. .map((block) => (block as { text?: unknown } | null)?.text)
  282. .filter((value): value is string => typeof value === "string")
  283. .join("\n")
  284. : "";
  285. return text
  286. .replaceAll("&quot;", '"')
  287. .replaceAll("&apos;", "'")
  288. .replaceAll("&lt;", "<")
  289. .replaceAll("&gt;", ">")
  290. .replaceAll("&amp;", "&");
  291. }
  292. /** 按 kind 词与 run 名找到那一行通知(同一会话里有多条)。 */
  293. async function waitForNotificationRow(kindLabel: string, runName: string) {
  294. let found: WebdriverIO.Element | undefined;
  295. await browser.waitUntil(
  296. async () => {
  297. for (const row of await $$(NOTIFICATION_ROW)) {
  298. const text = await row.getText();
  299. if (text.includes(kindLabel) && text.includes(runName)) {
  300. found = row;
  301. return true;
  302. }
  303. }
  304. return false;
  305. },
  306. { timeout: 60000, timeoutMsg: `没有出现「${kindLabel} · ${runName}」通知行` },
  307. );
  308. return found!;
  309. }