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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. import { TID_CHAT_WORKFLOW_RUN_DIGEST } from "@zcode/shared";
  2. import { clearAppData, pinE2ELocale } from "#e2e/helpers/desktop-app";
  3. import { readDynamicWorkflowGrayMockStatus } from "#e2e/helpers/dynamic-workflow-gray";
  4. import {
  5. hasV4PermissionDialog,
  6. prepareV4ConversationE2E,
  7. sendV4Prompt,
  8. startNewV4Draft,
  9. waitForV4AssistantMessageContaining,
  10. waitForV4Pane,
  11. waitForV4PermissionDialogInComposerDock,
  12. } from "#e2e/helpers/v4-conversation";
  13. import {
  14. countUpstreamRequests,
  15. countUpstreamRequestsContaining,
  16. getLatestUpstreamToolResultByToolCallId,
  17. getUpstreamRequestEvidence,
  18. type UpstreamToolResultSnapshot,
  19. } from "#e2e/helpers/conversation-session-network";
  20. // CreateWorkflow 确认窗的选项(docs/dynamic-workflow/launch.md「The confirmation window」:The options、
  21. // Adjusting the settings in the window、Refine、Always allow in this session;外观见
  22. // docs/dynamic-workflow/presentation.md「The confirmation window」)。
  23. //
  24. // 文件名带 `gray-always-on`:配置 mock 网关按文件名下发 alwaysOn,工作流工具才在工具集里。
  25. // case-local 回放只固定模型的 Skill / CreateWorkflow 选择与收尾文本;真实 Skill 加载、脚本编译、
  26. // 确认窗、应答、会话授权、设置调整、run 启动与完成通知都走产品链路。脚本不调 agent(),
  27. // 放行后的 run 不产生子代理请求。每个 it 开一个新会话:会话授权只活在它自己的会话里。
  28. const RUN_DIGEST = `[data-testid^="${TID_CHAT_WORKFLOW_RUN_DIGEST}"]`;
  29. const WORKFLOW_BLOCK = '[data-workflow-permission-block="true"]';
  30. const REFINE_INPUT = 'textarea[data-permission-feedback-option="workflowRefine"]';
  31. const RUN_LINE = '[data-workflow-run-line="true"]';
  32. type OptionKind = "allowOnce" | "allowAlways" | "rejectOnce";
  33. interface WindowOption {
  34. kind: string | null;
  35. label: string | null;
  36. text: string;
  37. }
  38. /** 等确认窗进入 composer dock,且画的是这一次调用(按工作流名认)。 */
  39. async function waitForWorkflowWindow(name: string) {
  40. await waitForV4PermissionDialogInComposerDock(120000);
  41. await browser.waitUntil(
  42. async () =>
  43. browser.execute(
  44. (selector: string, expected: string) =>
  45. document.querySelector<HTMLElement>(selector)?.innerText.includes(expected) ?? false,
  46. WORKFLOW_BLOCK,
  47. name,
  48. ),
  49. { timeout: 30000, timeoutMsg: `确认窗没有画出工作流 ${name}` },
  50. );
  51. }
  52. function readWindowOptions(): Promise<WindowOption[]> {
  53. return browser.execute(() =>
  54. Array.from(
  55. document.querySelectorAll<HTMLButtonElement>(
  56. '[data-v4-composer-dock="true"] [role="listbox"] button[role="option"]',
  57. ),
  58. ).map((button) => ({
  59. kind: button.getAttribute("data-permission-option-kind"),
  60. label: button.getAttribute("aria-label"),
  61. text: button.innerText.replace(/\s+/g, " ").trim(),
  62. })),
  63. );
  64. }
  65. /**
  66. * 点某一种选项:未选中时第一次点击只选中,再点才应答(PermissionDialog 的点击语义),
  67. * 所以点到窗关闭为止。
  68. */
  69. async function answerWorkflowWindow(kind: OptionKind) {
  70. const clickOption = () =>
  71. browser.execute((optionKind: string) => {
  72. const option = document.querySelector<HTMLButtonElement>(
  73. `[data-v4-composer-dock="true"] [role="listbox"] button[role="option"][data-permission-option-kind="${optionKind}"]`,
  74. );
  75. option?.click();
  76. return Boolean(option);
  77. }, kind);
  78. expect(await clickOption()).toBe(true);
  79. await browser.waitUntil(
  80. async () => {
  81. if (!(await hasV4PermissionDialog())) return true;
  82. await clickOption();
  83. return false;
  84. },
  85. { timeout: 15000, timeoutMsg: `选了 ${kind} 后确认窗没有关闭` },
  86. );
  87. }
  88. async function waitForToolResult(toolCallId: string): Promise<UpstreamToolResultSnapshot> {
  89. let result: UpstreamToolResultSnapshot | null = null;
  90. await browser.waitUntil(
  91. async () => {
  92. result = await getLatestUpstreamToolResultByToolCallId(toolCallId);
  93. return result !== null;
  94. },
  95. { timeout: 60000, timeoutMsg: `${toolCallId} 的工具结果没有回到模型请求里` },
  96. );
  97. return result as unknown as UpstreamToolResultSnapshot;
  98. }
  99. async function waitForTurnIdle(timeoutMsg: string) {
  100. await waitForV4Pane((pane) => !pane.canStop, timeoutMsg, 60000);
  101. }
  102. /** 放行的 run 跑完后,主代理读到它的 <task-notification> 并回完话,会话才回到空闲。 */
  103. async function waitForRunNotificationConsumed(runName: string) {
  104. await browser.waitUntil(
  105. async () =>
  106. (await countUpstreamRequests({
  107. lastUserMessageIncludes: ["<task-notification>", runName],
  108. })) > 0,
  109. { timeout: 120000, timeoutMsg: `${runName} 的完成通知没有送到主代理` },
  110. );
  111. await waitForTurnIdle(`${runName} 的完成通知那一轮没有结束`);
  112. }
  113. describe("动态工作流 · CreateWorkflow 确认窗的选项", () => {
  114. before(async () => {
  115. await prepareV4ConversationE2E();
  116. // 断言中文文案:固定界面语言,不跟随宿主系统语言(容器里默认英文)。
  117. await pinE2ELocale("zh-CN");
  118. });
  119. after(async () => {
  120. await browser.electron.restoreAllMocks();
  121. await clearAppData();
  122. });
  123. it("DWC-01 窗的形状与拒绝:三个选项加修改行;拒绝不带修改行草稿、不起 run,模型被告知未获批准,turn 收口", async function () {
  124. this.timeout(240000);
  125. expect((await readDynamicWorkflowGrayMockStatus()).scenario).toBe("alwaysOn");
  126. await startNewV4Draft();
  127. await sendV4Prompt("E2E_DWC_DENY 用工作流检查一下仓库");
  128. await waitForWorkflowWindow("E2E_DWC_DENY_RUN");
  129. // 表头问句;两项 run 设置(agent 回填了 adjustable_settings 时总画出来)。
  130. const block = await $(WORKFLOW_BLOCK);
  131. expect(await block.getText()).toContain("运行此工作流?");
  132. await expect(block.$('[data-testid="workflow-permission-settings-model"]')).toBeExisting();
  133. await expect(block.$('[data-testid="workflow-permission-settings-bound"]')).toBeExisting();
  134. // 选项:允许 / 本会话内始终允许 / 拒绝,第 4 项是 Refine 的修改行,不在按钮列表里。
  135. const options = await readWindowOptions();
  136. expect(options.map((option) => option.kind)).toEqual([
  137. "allowOnce",
  138. "allowAlways",
  139. "rejectOnce",
  140. ]);
  141. expect(options.map((option) => option.label)).toEqual(["允许", "本会话内始终允许", "拒绝"]);
  142. expect(options[0]?.text).toContain("仅允许这一次");
  143. expect(options[1]?.text).toContain("本会话内运行工作流不再询问");
  144. const refineInput = await $(REFINE_INPUT);
  145. await expect(refineInput).toBeDisplayed();
  146. expect(await refineInput.getAttribute("aria-label")).toBe("提出修改");
  147. expect(await refineInput.getAttribute("placeholder")).toBe("描述这个工作流应该怎么改…");
  148. // 修改行里留一段草稿再点拒绝:草稿属于 Refine,普通拒绝就是普通拒绝。
  149. const draft = "E2E_DWC_DENY_DRAFT 这段草稿不应发给模型";
  150. await refineInput.setValue(draft);
  151. await answerWorkflowWindow("rejectOnce");
  152. const result = await waitForToolResult("toolu_dwc_deny_create");
  153. expect(result.isError).toBe(true);
  154. // 普通拒绝走标准权限拒绝文案,不是 Refine 的「未获批准」+ 跟随的用户消息。
  155. expect(result.content).toContain("The tool use was rejected");
  156. expect(result.content).not.toContain("The workflow run was not approved by the user.");
  157. expect(result.content).not.toContain("E2E_DWC_DENY_DRAFT");
  158. await waitForV4AssistantMessageContaining("E2E_DWC_DENY_DONE", 60000);
  159. await waitForTurnIdle("拒绝后 turn 没有收口");
  160. expect(await countUpstreamRequestsContaining("E2E_DWC_DENY_DRAFT")).toBe(0);
  161. // 没有 run:卡与侧栏运行行都不出现。
  162. expect(await $(RUN_DIGEST).isExisting()).toBe(false);
  163. expect(await $(RUN_LINE).isExisting()).toBe(false);
  164. });
  165. it("DWC-02 Refine:修改意见作为真实用户消息排在工具结果之后发给模型,不起 run;模型重提后窗再次出现", async function () {
  166. this.timeout(240000);
  167. await startNewV4Draft();
  168. await sendV4Prompt("E2E_DWC_REFINE_START 用工作流检查一下仓库");
  169. await waitForWorkflowWindow("E2E_DWC_REFINE_RUN_1");
  170. const feedback = "E2E_DWC_REFINE_FEEDBACK 拆成两个阶段再跑";
  171. const refineInput = await $(REFINE_INPUT);
  172. await refineInput.click();
  173. await refineInput.setValue(feedback);
  174. // 修改行里回车即提交修改意见。
  175. await browser.keys("Enter");
  176. await browser.waitUntil(
  177. async () =>
  178. browser.execute(
  179. (selector: string, expected: string) =>
  180. !document.querySelector<HTMLElement>(selector)?.innerText.includes(expected),
  181. WORKFLOW_BLOCK,
  182. "E2E_DWC_REFINE_RUN_1",
  183. ),
  184. { timeout: 15000, timeoutMsg: "提交修改意见后第一个确认窗没有关闭" },
  185. );
  186. // 工具结果:运行未获批准;修改意见作为用户消息,排在 tool_result 之后。
  187. const result = await waitForToolResult("toolu_dwc_refine_create_1");
  188. expect(result.isError).toBe(true);
  189. expect(result.content).toContain("The workflow run was not approved by the user.");
  190. expect(result.content).not.toContain("E2E_DWC_REFINE_FEEDBACK");
  191. const [revised] = await getUpstreamRequestEvidence({
  192. lastUserMessageIncludes: ["E2E_DWC_REFINE_FEEDBACK"],
  193. });
  194. expect(revised).toBeDefined();
  195. const body = JSON.stringify(revised!.requestJson);
  196. const toolResultAt = body.indexOf('"tool_use_id":"toolu_dwc_refine_create_1"');
  197. expect(toolResultAt).toBeGreaterThanOrEqual(0);
  198. expect(body.indexOf("E2E_DWC_REFINE_FEEDBACK")).toBeGreaterThan(toolResultAt);
  199. // 模型修订重提:新窗画出修订后的名字;用数字键 3 直接拒绝。
  200. await waitForWorkflowWindow("E2E_DWC_REFINE_RUN_2");
  201. await browser.waitUntil(
  202. async () =>
  203. browser.execute(
  204. () => document.activeElement?.getAttribute("data-permission-option-kind") === "allowOnce",
  205. ),
  206. { timeout: 5000, timeoutMsg: "修订后的确认窗打开后焦点不在第一个选项上" },
  207. );
  208. await browser.keys("3");
  209. await browser.waitUntil(async () => !(await hasV4PermissionDialog()), {
  210. timeout: 15000,
  211. timeoutMsg: "数字键 3 没有直接拒绝",
  212. });
  213. expect((await waitForToolResult("toolu_dwc_refine_create_2")).isError).toBe(true);
  214. await waitForV4AssistantMessageContaining("E2E_DWC_REFINE_DONE", 60000);
  215. await waitForTurnIdle("修订窗被拒绝后 turn 没有收口");
  216. expect(await $(RUN_DIGEST).isExisting()).toBe(false);
  217. expect(await $(RUN_LINE).isExisting()).toBe(false);
  218. });
  219. it("DWC-03 本会话内始终允许:同一会话下一次 CreateWorkflow 不再弹窗直接起 run;新会话再次弹窗", async function () {
  220. this.timeout(360000);
  221. await startNewV4Draft();
  222. await sendV4Prompt("E2E_DWC_SESSION_FIRST 用工作流检查一下仓库");
  223. await waitForWorkflowWindow("E2E_DWC_SESSION_RUN_1");
  224. await answerWorkflowWindow("allowAlways");
  225. expect((await waitForToolResult("toolu_dwc_session_create_1")).isError).toBe(false);
  226. await $(RUN_DIGEST).waitForDisplayed({ timeout: 120000 });
  227. await waitForRunNotificationConsumed("E2E_DWC_SESSION_RUN_1");
  228. // 第二次调用之前装上观察器:只要确认窗出现过一次就记下来。
  229. await browser.execute(() => {
  230. const probe = window as Window & { __dwcPermissionSeen?: boolean };
  231. probe.__dwcPermissionSeen = false;
  232. const seen = () =>
  233. Array.from(document.querySelectorAll('[role="listbox"]')).some((element) =>
  234. ["Permission required", "需要权限"].includes(element.getAttribute("aria-label") ?? ""),
  235. );
  236. const observer = new MutationObserver(() => {
  237. if (seen()) {
  238. probe.__dwcPermissionSeen = true;
  239. observer.disconnect();
  240. }
  241. });
  242. observer.observe(document.body, { childList: true, subtree: true });
  243. });
  244. await sendV4Prompt("E2E_DWC_SESSION_AGAIN 再用工作流检查一遍");
  245. expect((await waitForToolResult("toolu_dwc_session_create_2")).isError).toBe(false);
  246. await browser.waitUntil(async () => (await $$(RUN_DIGEST).length) >= 2, {
  247. timeout: 120000,
  248. timeoutMsg: "会话授权后的第二次 CreateWorkflow 没有起 run",
  249. });
  250. await waitForRunNotificationConsumed("E2E_DWC_SESSION_RUN_2");
  251. expect(
  252. await browser.execute(
  253. () => (window as Window & { __dwcPermissionSeen?: boolean }).__dwcPermissionSeen,
  254. ),
  255. ).toBe(false);
  256. // 授权只属于那个会话:新会话的 CreateWorkflow 照常弹窗。拒绝收尾。
  257. await startNewV4Draft();
  258. await sendV4Prompt("E2E_DWC_SESSION_NEW 换个会话再用工作流检查");
  259. await waitForWorkflowWindow("E2E_DWC_SESSION_RUN_NEW");
  260. await answerWorkflowWindow("rejectOnce");
  261. expect((await waitForToolResult("toolu_dwc_session_new_create")).isError).toBe(true);
  262. await waitForV4AssistantMessageContaining("E2E_DWC_SESSION_NEW_DONE", 60000);
  263. });
  264. it("DWC-04 在窗里调高并发上限:选项描述改说「按调整后的设置运行」,放行后 run 按新上限启动并告诉模型", async function () {
  265. this.timeout(240000);
  266. await startNewV4Draft();
  267. await sendV4Prompt("E2E_DWC_ADJUST 用工作流检查一下仓库");
  268. await waitForWorkflowWindow("E2E_DWC_ADJUST_RUN");
  269. // 调用没设 max_concurrency:步进器从默认并发起,尾巴写「= 默认」。
  270. const bound = await $('[data-testid="workflow-permission-settings-bound"]');
  271. const value = await bound.$('[data-testid="workflow-permission-settings-bound-value"]');
  272. const initial = Number.parseInt(await value.getValue(), 10);
  273. expect(Number.isFinite(initial)).toBe(true);
  274. expect(await bound.getAttribute("data-changed")).toBeNull();
  275. expect(
  276. await bound.$('[data-testid="workflow-permission-settings-bound-tail"]').getText(),
  277. ).toContain("= 默认");
  278. await bound.$('[data-testid="workflow-permission-settings-bound-increase"]').click();
  279. const adjusted = initial + 1;
  280. await browser.waitUntil(async () => (await value.getValue()) === String(adjusted), {
  281. timeout: 5000,
  282. timeoutMsg: "并发步进器没有加一",
  283. });
  284. expect(await bound.getAttribute("data-changed")).toBe("true");
  285. expect(
  286. await bound.$('[data-testid="workflow-permission-settings-bound-tail"]').getText(),
  287. ).toContain(`默认 ${initial}`);
  288. expect(
  289. await bound.$('[data-testid="workflow-permission-settings-bound-was"]').getText(),
  290. ).toContain(`原为 ${initial}`);
  291. // 改过设置后,前两个选项换描述。
  292. const options = await readWindowOptions();
  293. expect(options[0]?.text).toContain("按调整后的设置运行一次");
  294. expect(options[1]?.text).toContain(
  295. "本次按调整后的设置运行;之后的工作流不再询问,各用各的设置",
  296. );
  297. await answerWorkflowWindow("allowOnce");
  298. const result = await waitForToolResult("toolu_dwc_adjust_create");
  299. expect(result.isError).toBe(false);
  300. expect(result.content).toContain(
  301. "Before approving, the user adjusted the settings in the confirmation window:",
  302. );
  303. expect(result.content).toContain(
  304. `at most ${adjusted} subagents run at once (the default is ${initial})`,
  305. );
  306. // 模型没被告知换了模型:只说改了的那一半。
  307. expect(result.content).not.toContain("back on the session model");
  308. await $(RUN_DIGEST).waitForDisplayed({ timeout: 120000 });
  309. await waitForRunNotificationConsumed("E2E_DWC_ADJUST_RUN");
  310. });
  311. });