conversation-session-dynamic-workflow-gray-always-on-questions.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import { mkdir, rm, writeFile } from "node:fs/promises";
  2. import { dirname } from "node:path";
  3. import { TID_CHAT_WORKFLOW_RUN_DIGEST } from "@zcode/shared";
  4. import { TID_CHAT_TOOL_CALL_BLOCK, testId } from "@zcode/shared/test-ids";
  5. import { clearAppData, pinE2ELocale } from "#e2e/helpers/desktop-app";
  6. import { resolveE2ERuntimePath } from "#e2e/helpers/e2e-runtime-paths";
  7. import {
  8. approveV4Permission,
  9. prepareV4ConversationE2E,
  10. sendV4Prompt,
  11. waitForV4AssistantMessageContaining,
  12. waitForV4Pane,
  13. } from "#e2e/helpers/v4-conversation";
  14. import {
  15. countUpstreamRequests,
  16. getLatestUpstreamToolResultByToolCallId,
  17. getUpstreamRequestEvidence,
  18. waitForUpstreamRequest,
  19. type UpstreamRequestQuery,
  20. } from "#e2e/helpers/conversation-session-network";
  21. import { isOutsideClosedHistory, openClosedHistoryFolds } from "#e2e/helpers/v4-history-folds";
  22. // 子代理升级问题(docs/dynamic-workflow/authoring.md 的 `escalate` 与「When a subagent escalates」、
  23. // docs/dynamic-workflow/transcript-and-notifications.md「Notifications」「The notification row」
  24. // 「The escalation row's live state」「What the model reads」、docs/dynamic-workflow/presentation.md 的
  25. // 问题芯片与侧板「Pending questions」):子代理调用 `escalate` 停驻,闲着的主代理被通知唤起一次;
  26. // 主代理用 ResolveWorkflowQuestion 作答,子代理带着答案继续,run 跑到完成。
  27. //
  28. // case-local 回放只决定模型调用;真实 Skill、工作流编译、审批、run 引擎、升级问答的停驻与恢复、
  29. // 通知的铸造与投递走产品链路。脚本先用 `world.run("node", …)` 等一个闸文件:用例在启动轮收尾之后
  30. // 才写闸文件,升级通知因此唤起自己的一轮。等待态检查完成后才发作答指令,等待态不会被自动作答抢走。
  31. //
  32. // 空闲提醒(`workflowBlocked`)不在本文件:它要会话空闲满 15 分钟才发(WORKFLOW_BLOCKED_REMINDER_DELAYS_MS,
  33. // 没有可注入的时钟),用例不能等这样的墙钟时长。
  34. const RUN_DIGEST = `[data-testid^="${TID_CHAT_WORKFLOW_RUN_DIGEST}"]`;
  35. const NOTIFICATION_ROW = `div[data-testid^="chat-workflow-notification-row-"]`;
  36. const RUN_NAME = "E2E 提问工作流";
  37. const ASKER = "核对员";
  38. const QUESTION = "E2E_DWQ_QUESTION 仓库里有两份发布清单,应该按哪一份核对?";
  39. const CONTEXT =
  40. "E2E_DWQ_CONTEXT release-a.md 和 release-b.md 的版本号互相矛盾,我无法判断哪份是最新的。";
  41. const ANSWER = "E2E_DWQ_ANSWER 按 release-b.md 核对,它是最新的一份。";
  42. const SYSTEM_BANNER = "[SYSTEM NOTIFICATION - NOT USER INPUT]";
  43. const SUBAGENT_MARKER = "You are a subagent inside a dynamic workflow run";
  44. const ESCALATION_QUERY: UpstreamRequestQuery = {
  45. lastUserMessageIncludes: ["<workflow-escalation>"],
  46. };
  47. let runId = "";
  48. let qid = "";
  49. describe("动态工作流 · 子代理升级问题", () => {
  50. before(async () => {
  51. await prepareV4ConversationE2E();
  52. // 断言中文文案:固定界面语言,不跟随宿主系统语言(容器里默认英文)。
  53. await pinE2ELocale("zh-CN");
  54. await rm(gatePath(), { force: true });
  55. });
  56. after(async () => {
  57. await browser.electron.restoreAllMocks();
  58. await clearAppData();
  59. });
  60. it("DWQ-01 子代理提问:闲着的主代理被唤起恰好一次并读到问题;通知行「子代理正在等待回答」,卡上「1 个待答问题」,侧板问题挂在提问者下面", async function () {
  61. this.timeout(300000);
  62. runId = await launchIdleRun();
  63. await openGate();
  64. await waitForUpstreamRequest(ESCALATION_QUERY, "升级通知没有唤起主代理", 120000);
  65. const payload = await readNotificationText(ESCALATION_QUERY);
  66. expect(payload).toContain(SYSTEM_BANNER);
  67. expect(payload).toContain(`<run-id>${runId}</run-id>`);
  68. expect(payload).toContain(`<run>${RUN_NAME}</run>`);
  69. expect(payload).toContain(`<subagent>${ASKER}</subagent>`);
  70. expect(payload).toContain(`<question>${QUESTION}</question>`);
  71. expect(payload).toContain(`<context>${CONTEXT}</context>`);
  72. qid = /<question-id>(dwfq-[^<]+)<\/question-id>/u.exec(payload)?.[1] ?? "";
  73. expect(qid).not.toBe("");
  74. // 下一步原样点名作答工具与问题 id;只停这一个子代理,不超时。
  75. const guidance = payload.slice(payload.indexOf("</workflow-escalation>"));
  76. expect(guidance).toContain(`call ResolveWorkflowQuestion with question_id="${qid}"`);
  77. expect(guidance).toContain("only the subagent that asked is parked");
  78. await waitForV4AssistantMessageContaining("E2E_DWQ_SEEN", 120000);
  79. await waitForV4Pane((pane) => !pane.canStop, "升级通知那一轮没有结束", 60000);
  80. // 通知行:问号图标那一行,kind 词按投影的待答问题活翻转,主文是问题本身。
  81. const row = await waitForEscalationRow("子代理正在等待回答");
  82. await row.$('[role="button"]').click();
  83. await browser.waitUntil(async () => (await row.getText()).includes(CONTEXT), {
  84. timeout: 10000,
  85. timeoutMsg: "通知行展开体没有画出背景",
  86. });
  87. expect(await row.getText()).toContain("背景");
  88. // 展开体以「查看实例详情」收尾:活会话里宿主能开侧板,投影也认得这次 run 的工具调用 id。
  89. await expectOpenRunLink(row);
  90. // 答案还不存在,行里也永远不引用答案原文。
  91. expect(await row.getText()).not.toContain("E2E_DWQ_ANSWER");
  92. // 卡:run 停驻但仍在跑,表头长出警示色问题芯片。
  93. const digest = runDigest(runId);
  94. expect(await digest.getAttribute("data-workflow-run-status")).toBe("running");
  95. const chip = await digest.$('[data-testid="workflow-digest-questions"]');
  96. await chip.waitForDisplayed({ timeout: 30000 });
  97. expect(await chip.getText()).toContain("1 个待答问题");
  98. // 侧栏运行行:没有问题芯片(问题由主代理回答,不由用户),只写当前阶段。
  99. const line = await $('[data-workflow-run-line="true"]');
  100. await line.waitForDisplayed({ timeout: 30000 });
  101. expect(await line.getText()).toContain("核对");
  102. expect(await line.getText()).not.toContain("问题");
  103. // 侧板:点问题芯片打开整个 run;问题挂在提问者那一行下面,带背景、等待时长与问题 id。
  104. await chip.click();
  105. const question = await $(`[data-testid="workflow-run-question"][data-qid="${qid}"]`);
  106. await question.waitForDisplayed({ timeout: 30000 });
  107. expect(await question.getText()).toContain(QUESTION);
  108. expect(await question.getText()).toContain(qid);
  109. await expect(question.$('[data-testid="workflow-run-question-context"]')).toHaveText(CONTEXT);
  110. await expect(question.$('[data-testid="workflow-run-question-waited"]')).toBeExisting();
  111. // 提问者在行上,所以不进末尾的「待答问题」孤儿块。
  112. await expect($('[data-testid="workflow-run-orphan-questions"]')).not.toBeExisting();
  113. // 每个 `escalation-raised` 恰好一条通知,不重发。
  114. expect(await countUpstreamRequests(ESCALATION_QUERY)).toBe(1);
  115. });
  116. it("DWQ-02 主代理作答:工具卡「已回答问题」,子代理下一次请求带着答案,问题行与芯片消失,通知行翻成「子代理的问题已回答」,run 完成", async function () {
  117. this.timeout(300000);
  118. expect(qid).not.toBe("");
  119. await sendV4Prompt("E2E_DWQ_REPLY_NOW 告诉子代理按 release-b.md 核对。");
  120. await browser.waitUntil(
  121. async () =>
  122. (await getLatestUpstreamToolResultByToolCallId("toolu_dwq_resolve"))?.isError === false,
  123. { timeout: 60_000, timeoutMsg: "ResolveWorkflowQuestion 未执行成功" },
  124. );
  125. const resolved = await getLatestUpstreamToolResultByToolCallId("toolu_dwq_resolve");
  126. expect(resolved?.content).toContain(`Answer delivered for question ${qid}`);
  127. // 答案原样成为那次 escalate 调用的结果:子代理的下一次请求里最后一条 user 消息就是它。
  128. const resumedQuery: UpstreamRequestQuery = {
  129. includes: [SUBAGENT_MARKER],
  130. lastUserMessageIncludes: [ANSWER],
  131. };
  132. await waitForUpstreamRequest(resumedQuery, "子代理没有带着答案继续", 60000);
  133. expect(await countUpstreamRequests(resumedQuery)).toBe(1);
  134. await waitForV4AssistantMessageContaining("E2E_DWQ_DONE", 180000);
  135. await waitForV4Pane((pane) => !pane.canStop, "完成通知那一轮没有结束", 60000);
  136. const digest = runDigest(runId);
  137. await browser.waitUntil(
  138. async () => (await digest.getAttribute("data-workflow-run-status")) === "completed",
  139. { timeout: 60000, timeoutMsg: "run 没有跑到完成" },
  140. );
  141. await expect(digest.$('[data-testid="workflow-digest-questions"]')).not.toBeExisting();
  142. await expect($('[data-testid="workflow-run-question"]')).not.toBeExisting();
  143. // 升级行按投影翻转:run 还在投影里,qid 已不在待答问题里。
  144. await waitForEscalationRow("子代理的问题已回答");
  145. // 作答一次,不会因为答过而多出一条升级通知。
  146. expect(await countUpstreamRequests(ESCALATION_QUERY)).toBe(1);
  147. // 答案只在相邻的 ResolveWorkflowQuestion 工具卡里(这一轮收尾后折进「已处理」,先展开)。
  148. const card = await revealToolRow(
  149. `[data-testid="${testId(TID_CHAT_TOOL_CALL_BLOCK, "toolu_dwq_resolve")}"]`,
  150. );
  151. await browser.waitUntil(
  152. async () => String(await card.getProperty("textContent")).includes("已回答问题"),
  153. { timeout: 15000, timeoutMsg: "作答工具卡没有写「已回答问题」" },
  154. );
  155. expect(String(await card.getProperty("textContent"))).toContain("E2E_DWQ_ANSWER");
  156. });
  157. });
  158. function gatePath() {
  159. return resolveE2ERuntimePath("dwq-gate");
  160. }
  161. /** 写闸文件:脚本里的 `world.run("node", …)` 看到它就退出,子代理随之开工。 */
  162. async function openGate() {
  163. const path = gatePath();
  164. await mkdir(dirname(path), { recursive: true });
  165. await writeFile(path, "open\n");
  166. }
  167. function runDigest(id: string) {
  168. return $(`${RUN_DIGEST}[data-workflow-run-id="${id}"]`);
  169. }
  170. /**
  171. * 发启动指令、批准、等启动轮收尾,返回新 run 的 id;返回时主代理闲着、run 停在闸上。
  172. * 启动轮先收尾,升级通知才会唤起自己的一轮,而不是被并进启动轮。
  173. */
  174. async function launchIdleRun() {
  175. await sendV4Prompt("E2E_DWQ_START 用工作流核对发布清单,子代理拿不准时会来问。");
  176. await approveV4Permission();
  177. await browser.waitUntil(
  178. async () =>
  179. (await getLatestUpstreamToolResultByToolCallId("toolu_dwq_create"))?.isError === false,
  180. { timeout: 60_000, timeoutMsg: "CreateWorkflow 未执行成功" },
  181. );
  182. await waitForV4AssistantMessageContaining("E2E_DWQ_STARTED", 60000);
  183. await waitForV4Pane((pane) => !pane.canStop, "启动轮没有结束", 30000);
  184. let id = "";
  185. await browser.waitUntil(
  186. async () => {
  187. id = await browser.execute(
  188. (selector) =>
  189. Array.from(document.querySelectorAll(selector))
  190. .find((node) => node.getAttribute("data-workflow-run-status") === "running")
  191. ?.getAttribute("data-workflow-run-id") ?? "",
  192. RUN_DIGEST,
  193. );
  194. return id !== "";
  195. },
  196. { timeout: 60000, timeoutMsg: "run 卡没有进入 running" },
  197. );
  198. // 闸还没开:子代理没有开工,也没有任何升级通知。
  199. expect(await countUpstreamRequests(ESCALATION_QUERY)).toBe(0);
  200. return id;
  201. }
  202. /**
  203. * 唤起那一轮请求里最后一条 user 消息的文本:模型读到的通知全文。
  204. * 块里的字段值按 XML 转义(`"` → `&quot;`),断言比的是模型读到的字,先还原实体。
  205. */
  206. async function readNotificationText(query: UpstreamRequestQuery): Promise<string> {
  207. const [evidence] = await getUpstreamRequestEvidence(query);
  208. const messages = (evidence?.requestJson as { messages?: unknown } | undefined)?.messages;
  209. if (!Array.isArray(messages)) return "";
  210. const last = [...messages]
  211. .reverse()
  212. .find((message) => (message as { role?: unknown } | null)?.role === "user") as
  213. | { content?: unknown }
  214. | undefined;
  215. const content = last?.content;
  216. const text =
  217. typeof content === "string"
  218. ? content
  219. : Array.isArray(content)
  220. ? content
  221. .map((block) => (block as { text?: unknown } | null)?.text)
  222. .filter((value): value is string => typeof value === "string")
  223. .join("\n")
  224. : "";
  225. return text
  226. .replaceAll("&quot;", '"')
  227. .replaceAll("&apos;", "'")
  228. .replaceAll("&lt;", "<")
  229. .replaceAll("&gt;", ">")
  230. .replaceAll("&amp;", "&");
  231. }
  232. /** 按 kind 词找那一条升级通知行(主文是问题本身,不是 run 名)。 */
  233. async function waitForEscalationRow(kindLabel: string) {
  234. let found: WebdriverIO.Element | undefined;
  235. await browser.waitUntil(
  236. async () => {
  237. for (const row of await $$(NOTIFICATION_ROW)) {
  238. const text = String(await row.getProperty("textContent"));
  239. if (text.includes(kindLabel) && text.includes(QUESTION)) {
  240. found = row;
  241. return true;
  242. }
  243. }
  244. return false;
  245. },
  246. { timeout: 60000, timeoutMsg: `没有出现「${kindLabel}」升级通知行` },
  247. );
  248. return found!;
  249. }
  250. /** 等展开体里出现「查看实例详情」;等不到时把 run 卡与投影的现场带进失败信息,便于区分时序与联查缺失。 */
  251. async function expectOpenRunLink(row: WebdriverIO.Element) {
  252. const appeared = await browser
  253. .waitUntil(async () => (await row.getText()).includes("查看实例详情"), { timeout: 15000 })
  254. .then(() => true)
  255. .catch(() => false);
  256. if (appeared) return;
  257. const digest = runDigest(runId);
  258. const digestExists = await digest.isExisting();
  259. const evidence = {
  260. rowText: await row.getText(),
  261. digestExists,
  262. digestStatus: digestExists ? await digest.getAttribute("data-workflow-run-status") : null,
  263. digestToolCallId: digestExists ? await digest.getAttribute("data-tool-call-id") : null,
  264. };
  265. throw new Error(`升级通知行展开体没有「查看实例详情」:${JSON.stringify(evidence)}`);
  266. }
  267. /** 收尾的一轮把工具行折进「已处理」:点开所有折叠,等目标行出现。 */
  268. async function revealToolRow(selector: string) {
  269. const row = $(selector);
  270. await browser.waitUntil(
  271. async () => {
  272. if (await isOutsideClosedHistory(selector)) return true;
  273. await openClosedHistoryFolds();
  274. return false;
  275. },
  276. { timeout: 30000, timeoutMsg: `工具行没有出现:${selector}` },
  277. );
  278. await row.waitForDisplayed({ timeout: 30000 });
  279. return row;
  280. }