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

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