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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import { clearAppData, pinE2ELocale } from "#e2e/helpers/desktop-app";
  2. import {
  3. approveV4Permission,
  4. prepareV4ConversationE2E,
  5. scrollV4TimelineToTop,
  6. sendV4Prompt,
  7. waitForV4AssistantMessageContaining,
  8. waitForV4Pane,
  9. } from "#e2e/helpers/v4-conversation";
  10. import {
  11. countUpstreamRequests,
  12. getLatestUpstreamToolResultByToolCallId,
  13. } from "#e2e/helpers/conversation-session-network";
  14. import { isOutsideClosedHistory, openClosedHistoryFolds } from "#e2e/helpers/v4-history-folds";
  15. // 修订在跑的工作流(docs/dynamic-workflow/launch.md「The `AmendWorkflow` tool」「Amending this
  16. // session's runs」、docs/dynamic-workflow/presentation.md「The tool row」「The run card」、
  17. // docs/dynamic-workflow/concurrency.md「Retuning a live run」)的三条桌面链路:
  18. // 只改并发 = 就地生效、不起新 run;改脚本 = 新 run 替代旧 run、旧卡留着已完成的工作;
  19. // 两次调用各自告诉模型什么。
  20. //
  21. // case-local 回放只决定模型调用与子代理回复;真实 Skill、编译、审批、运行、留白通知、就地调并发、
  22. // 修订与替代都走产品链路。run 停在留白上保持 running(引擎活着、不需要计时器),
  23. // 留白通知里的 run id 也正好让回放的 `{{latestWorkflowRunId}}` 回填 AmendWorkflow 的 run_id。
  24. const RUN_DIGEST = '[data-workflow-run-digest="true"]';
  25. const digestOf = (runId: string) => $(`${RUN_DIGEST}[data-workflow-run-id="${runId}"]`);
  26. async function readDigestRunIds(): Promise<string[]> {
  27. return browser.execute((selector) => {
  28. const ids = Array.from(document.querySelectorAll<HTMLElement>(selector)).map(
  29. (element) => element.dataset.workflowRunId ?? "",
  30. );
  31. return Array.from(new Set(ids.filter(Boolean)));
  32. }, RUN_DIGEST);
  33. }
  34. // 时间线是虚拟化的:几轮之后,启动那一轮(旧 run 的卡挂在它下面)会被卸载出 DOM。
  35. // 需要读旧卡时先确认它在场,不在场就滚到顶把那一轮挂回来。
  36. async function revealDigest(runId: string) {
  37. if (!(await digestOf(runId).isExisting())) await scrollV4TimelineToTop();
  38. await digestOf(runId).waitForExist({ timeout: 30000 });
  39. await digestOf(runId).scrollIntoView({ block: "center" });
  40. return digestOf(runId);
  41. }
  42. // 已结束一轮的工具行收在「已处理」折叠里(默认收起),还在跑的一轮则直接画在时间线上。读工具行时
  43. // 两种状态都要接得住:行不在 DOM 里就展开所有收起的折叠,直到它出现,再等它可见。
  44. async function revealToolRow(selector: string) {
  45. const row = $(selector);
  46. await withTimelineEvidence(() =>
  47. browser.waitUntil(
  48. async () => {
  49. if (await isOutsideClosedHistory(selector)) return true;
  50. await openClosedHistoryFolds();
  51. return false;
  52. },
  53. { timeout: 30000, timeoutMsg: `工具行没有出现:${selector}` },
  54. ),
  55. );
  56. await row.waitForDisplayed({ timeout: 30000 });
  57. return row;
  58. }
  59. // 失败时把时间线末尾几行的 testid 与文字带进错误信息:容器里没有截图,靠它判断行画成了什么。
  60. async function describeTimelineTail(): Promise<string> {
  61. return browser.execute(() => {
  62. const rows = Array.from(document.querySelectorAll<HTMLElement>("[data-row-id]")).slice(-8);
  63. return rows
  64. .map((row) => {
  65. const ids = Array.from(row.querySelectorAll<HTMLElement>("[data-testid]"))
  66. .map((element) => element.dataset.testid)
  67. .slice(0, 12)
  68. .join(",");
  69. return `#${row.dataset.rowId} [${ids}] ${row.innerText.replace(/\s+/gu, " ").slice(0, 200)}`;
  70. })
  71. .join("\n")
  72. .concat(
  73. "\n--- run cards ---\n",
  74. Array.from(document.querySelectorAll<HTMLElement>('[data-workflow-run-digest="true"]'))
  75. .map(
  76. (card) =>
  77. `${card.dataset.workflowRunId} ${card.dataset.workflowRunStatus} ${card.getAttribute("aria-label")}`,
  78. )
  79. .join("\n"),
  80. );
  81. });
  82. }
  83. async function withTimelineEvidence<T>(step: () => Promise<T>): Promise<T> {
  84. try {
  85. return await step();
  86. } catch (error) {
  87. throw new Error(`${String(error)}\n--- timeline tail ---\n${await describeTimelineTail()}`, {
  88. cause: error,
  89. });
  90. }
  91. }
  92. // 「不弹确认窗」是一段时间里的否定:在发送前装上观察器,权限弹窗只要出现过一帧就记下,
  93. // 不靠固定等待去抽样。
  94. async function watchPermissionDialog() {
  95. await browser.execute(() => {
  96. const probe = window as Window & { __dwaPermissionSeen?: boolean };
  97. probe.__dwaPermissionSeen = false;
  98. const seen = () =>
  99. Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).some((element) => {
  100. const label = (element.getAttribute("aria-label") ?? "").trim();
  101. return label === "Permission required" || label === "需要权限";
  102. });
  103. const observer = new MutationObserver(() => {
  104. if (seen()) {
  105. probe.__dwaPermissionSeen = true;
  106. observer.disconnect();
  107. }
  108. });
  109. observer.observe(document.body, { childList: true, subtree: true, attributes: true });
  110. });
  111. }
  112. async function permissionDialogSeen(): Promise<boolean> {
  113. return browser.execute(
  114. () => (window as Window & { __dwaPermissionSeen?: boolean }).__dwaPermissionSeen === true,
  115. );
  116. }
  117. describe("动态工作流 · 修订在跑的 run", () => {
  118. let firstRunId = "";
  119. let amendedRunId = "";
  120. before(async () => {
  121. await prepareV4ConversationE2E();
  122. // 断言中文文案:固定界面语言,不跟随宿主系统语言(容器里默认英文)。
  123. await pinE2ELocale("zh-CN");
  124. });
  125. after(async () => {
  126. await browser.electron.restoreAllMocks();
  127. await clearAppData();
  128. });
  129. it("DWA-01 只改并发:不弹窗、不起新 run,卡不变,工具行是设置行,侧板芯片读出新界", async function () {
  130. this.timeout(300000);
  131. await sendV4Prompt("E2E_DWA_START 用工作流先整理条目,再等我决定下一步。");
  132. await approveV4Permission();
  133. await browser.waitUntil(
  134. async () =>
  135. (await getLatestUpstreamToolResultByToolCallId("toolu_dwa_create"))?.isError === false,
  136. { timeout: 60_000, timeoutMsg: "CreateWorkflow 未执行成功" },
  137. );
  138. const firstDigest = await $(RUN_DIGEST);
  139. await firstDigest.waitForDisplayed({ timeout: 120000 });
  140. firstRunId = (await firstDigest.getAttribute("data-workflow-run-id")) ?? "";
  141. expect(firstRunId).not.toBe("");
  142. // 子代理先做完一步(已完成的工作),run 随后停在留白上,留白通知唤醒的那一轮结束。
  143. await browser.waitUntil(
  144. async () =>
  145. (await digestOf(firstRunId)
  146. .$('[data-testid="workflow-agent-pill"][data-agent-status="done"]')
  147. .isExisting()) &&
  148. (await digestOf(firstRunId)
  149. .$('[data-testid="workflow-timeline-station"][data-station-hole="waiting"]')
  150. .isExisting()),
  151. { timeout: 120000, timeoutMsg: "run 没有做完第一步并停在留白上" },
  152. );
  153. await waitForV4AssistantMessageContaining("E2E_DWA_WAITING", 120000);
  154. await waitForV4Pane((pane) => !pane.canStop, "留白通知回复未结束", 60000);
  155. expect(await digestOf(firstRunId).getAttribute("data-workflow-run-status")).toBe("running");
  156. await watchPermissionDialog();
  157. await sendV4Prompt("E2E_DWA_RETUNE 把这个工作流的最大并发改成 2。");
  158. await browser.waitUntil(
  159. async () =>
  160. (await getLatestUpstreamToolResultByToolCallId("toolu_dwa_retune"))?.isError === false,
  161. { timeout: 60_000, timeoutMsg: "只改并发的 AmendWorkflow 未执行成功" },
  162. );
  163. await waitForV4AssistantMessageContaining("E2E_DWA_RETUNED", 120000);
  164. await waitForV4Pane((pane) => !pane.canStop, "调并发那一轮未结束", 60000);
  165. // 就地调并发不弹窗(launch.md「No window, for any owner」)。
  166. expect(await permissionDialogSeen()).toBe(false);
  167. // 工具行是 GUI 留下的那条设置行:「已调整设置 · 最多 2 个同时运行」,点名的是同一个 run。
  168. const retuneRow = await revealToolRow(
  169. `[data-testid="workflow-retune-row"][data-workflow-retune-run-id="${firstRunId}"]`,
  170. );
  171. // 折叠刚展开时还在动画里,innerText 可能暂时为空:读 textContent,并等它到齐。
  172. await browser.waitUntil(
  173. async () => {
  174. const text = String(await retuneRow.getProperty("textContent"));
  175. return text.includes("已调整设置") && text.includes("最多 2 个同时运行");
  176. },
  177. { timeout: 15000, timeoutMsg: "设置行没有写「已调整设置 · 最多 2 个同时运行」" },
  178. );
  179. // 不起新 run:没有「工作流已调整」摘要行,也没有第二张卡;原卡仍在跑、没有被替代。
  180. await expect(
  181. $('[data-testid="workflow-tool-summary"][data-tool-call-id="toolu_dwa_retune"]'),
  182. ).not.toBeExisting();
  183. expect((await readDigestRunIds()).every((runId) => runId === firstRunId)).toBe(true);
  184. const digest = await revealDigest(firstRunId);
  185. expect(await digest.getAttribute("data-workflow-run-status")).toBe("running");
  186. expect(await digest.getAttribute("aria-label")).not.toBe("工作流已被替代");
  187. // 用户看到的是芯片重新读出它的界(presentation.md「The settings popover」末段)。
  188. await digest.$('[data-testid="workflow-card-open-details"]').click();
  189. const chip = await $('[data-testid="workflow-run-concurrency"]');
  190. await browser.waitUntil(
  191. async () => (await chip.isExisting()) && /^最大并发数 2\b/u.test(await chip.getText()),
  192. { timeout: 30000, timeoutMsg: "run 侧板没有出现「最大并发数 2」芯片" },
  193. );
  194. });
  195. it("DWA-02 改脚本:本会话的 run 不弹窗;旧卡变「工作流已被替代」并留着已完成的一步,新卡跑到完成", async function () {
  196. this.timeout(300000);
  197. await watchPermissionDialog();
  198. await sendV4Prompt("E2E_DWA_AMEND 不用等了,改成整理完直接收尾。");
  199. await browser.waitUntil(
  200. async () =>
  201. (await getLatestUpstreamToolResultByToolCallId("toolu_dwa_amend"))?.isError === false,
  202. { timeout: 60_000, timeoutMsg: "改脚本的 AmendWorkflow 未执行成功" },
  203. );
  204. // 本会话启动、未被用户停止、没有带进新 provider 的 run:修订直接开始(rule.session.workflowOwner)。
  205. expect(await permissionDialogSeen()).toBe(false);
  206. // 修订行联接到新 run:「工作流已调整」摘要,新 run 的卡挂在这一轮下。
  207. const summary = await revealToolRow(
  208. '[data-testid="workflow-tool-summary"][data-tool-call-id="toolu_dwa_amend"]',
  209. );
  210. await browser.waitUntil(
  211. async () => String(await summary.getProperty("textContent")).includes("工作流已调整"),
  212. { timeout: 15000, timeoutMsg: "修订行没有写「工作流已调整」" },
  213. );
  214. amendedRunId = (await summary.getAttribute("data-workflow-run-id")) ?? "";
  215. expect(amendedRunId).not.toBe("");
  216. expect(amendedRunId).not.toBe(firstRunId);
  217. await browser.waitUntil(
  218. async () =>
  219. (await digestOf(amendedRunId).isExisting()) &&
  220. (await digestOf(amendedRunId).getAttribute("data-workflow-run-status")) === "completed",
  221. { timeout: 120000, timeoutMsg: "修订后的新 run 没有跑到 completed" },
  222. );
  223. // 旧卡留在原处:被替代(stopped,kind 词「工作流已被替代」),没有 Resume / Stop / Configure,
  224. // 它做完的那一步仍画在卡上。
  225. const oldDigest = await withTimelineEvidence(() => revealDigest(firstRunId));
  226. await withTimelineEvidence(() =>
  227. browser.waitUntil(
  228. async () =>
  229. (await oldDigest.isExisting()) &&
  230. (await oldDigest.getAttribute("aria-label")) === "工作流已被替代",
  231. { timeout: 60000, timeoutMsg: "旧 run 卡没有变成「工作流已被替代」" },
  232. ),
  233. );
  234. expect(await oldDigest.getAttribute("data-workflow-run-status")).toBe("stopped");
  235. await expect(oldDigest.$('[data-testid="workflow-digest-resume"]')).not.toBeExisting();
  236. await expect(oldDigest.$('[data-testid="workflow-digest-cancel"]')).not.toBeExisting();
  237. await expect(oldDigest.$('[data-testid="workflow-digest-configure"]')).not.toBeExisting();
  238. await expect(
  239. oldDigest.$('[data-testid="workflow-agent-pill"][data-agent-status="done"]'),
  240. ).toBeExisting();
  241. // 旧 run 做完的那一步作为缓存导入:同名子代理的同一句话不再发第二次模型请求。
  242. expect(await countUpstreamRequests({ lastUserMessageIncludes: ["E2E_DWA_PREP"] })).toBe(1);
  243. });
  244. it("DWA-03 模型被告知:就地调并发只点名一个 run;修订点名被替代的旧 run 与新 run,旧 run 不再单独通知", async function () {
  245. this.timeout(180000);
  246. // 新 run 完成的通知唤醒的那一轮结束,旧 run 若有终态通知也早该送到了。
  247. await waitForV4AssistantMessageContaining("E2E_DWA_DONE", 120000);
  248. await waitForV4Pane((pane) => !pane.canStop, "完成通知回复未结束", 60000);
  249. // 就地调并发的回话是这条路线唯一越过 v4 的事实,措辞逐字钉住(launch.md「What comes back」)。
  250. const retune = await getLatestUpstreamToolResultByToolCallId("toolu_dwa_retune");
  251. expect(retune?.content).toContain(
  252. `Applied to the running run ${firstRunId}; at most 2 subagents run at once. Run ${firstRunId} keeps running under it: nothing was stopped and no new run was started.`,
  253. );
  254. // 修订的回话点名两端:旧 run 被停止并替代、已完成的工作作为缓存导入,修订后的脚本作为新 run 启动。
  255. const amend = await getLatestUpstreamToolResultByToolCallId("toolu_dwa_amend");
  256. expect(amend?.isError).toBe(false);
  257. expect(amend?.content).toContain(`Run ${firstRunId} was still running`);
  258. expect(amend?.content).toContain("stopped and superseded");
  259. expect(amend?.content).toContain(
  260. `The revised script started in the background as run ${amendedRunId}`,
  261. );
  262. expect(amend?.content).toContain("It will not send a notification of its own.");
  263. // 新 run 的完成通知送达;旧 run 的终态通知不送(修订回话就是模型对那次停止的交代)。
  264. expect(
  265. await countUpstreamRequests({
  266. lastUserMessageIncludes: [
  267. "<task-notification>",
  268. amendedRunId,
  269. "<status>completed</status>",
  270. ],
  271. }),
  272. ).toBeGreaterThan(0);
  273. expect(
  274. await countUpstreamRequests({
  275. lastUserMessageIncludes: ["<task-notification>", `<task-id>${firstRunId}</task-id>`],
  276. }),
  277. ).toBe(0);
  278. });
  279. });