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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { dirname } from "node:path";
  3. import { TID_CHAT_WORKFLOW_RUN_DIGEST } from "@zcode/shared";
  4. import { clearAppData, pinE2ELocale } from "#e2e/helpers/desktop-app";
  5. import { resolveE2ERuntimePath } from "#e2e/helpers/e2e-runtime-paths";
  6. import {
  7. approveV4Permission,
  8. denyV4PermissionWithFeedback,
  9. getV4ConfigProjection,
  10. getV4PaneSnapshot,
  11. hasV4PermissionDialog,
  12. prepareV4ConversationE2E,
  13. sendV4Prompt,
  14. switchV4Mode,
  15. waitForV4AssistantMessageContaining,
  16. waitForV4Pane,
  17. } from "#e2e/helpers/v4-conversation";
  18. import {
  19. countUpstreamRequests,
  20. getLatestUpstreamToolResultByToolCallId,
  21. getUpstreamRequestEvidence,
  22. } from "#e2e/helpers/conversation-session-network";
  23. // run 里的权限(docs/dynamic-workflow/launch.md「Permissions inside a run」):子代理跑在发起 run 的会话的
  24. // 权限模式上,模式在建 run 时定下(记进 run-launched 的 subagentPermissionMode),之后会话换模式不影响
  25. // 在飞的 run。子代理的询问用父会话的 id 发出,权限窗画在父会话里,带「子智能体 · <名字> (<siteId>@<序号>)」
  26. // 来源徽标,且不提供「完全访问」。
  27. //
  28. // 文件名带 `gray-always-on`:配置 mock 网关按文件名下发 alwaysOn,工作流工具才在工具集里。
  29. // case-local 回放只决定模型调用(主代理与子代理);真实 Skill、编译、确认窗、run 引擎、权限判定、
  30. // Bash 执行与完成通知走产品链路。会话模式由 composer 的模式选择器设定,随下一次发送生效。
  31. // 模式固定那条 run 用 `world.run("node", …)` 等闸文件,用例在会话换模式之后才写闸文件,不靠计时。
  32. const RUN_DIGEST = `[data-testid^="${TID_CHAT_WORKFLOW_RUN_DIGEST}"]`;
  33. const DENY_FEEDBACK = "E2E_DWM_DENY_FEEDBACK 这次不要写文件";
  34. const KEEP_GATE = "dwm-gate-keep";
  35. const OUTPUT_FILES = ["dwm-ask.txt", "dwm-yolo.txt", "dwm-keep.txt", "dwm-keep-main.txt"];
  36. interface SubagentAskSnapshot {
  37. parentSessionId: string | null;
  38. badgeText: string;
  39. badgeTitle: string;
  40. options: Array<{ kind: string; label: string }>;
  41. text: string;
  42. }
  43. describe("动态工作流 · run 里的权限询问", () => {
  44. before(async () => {
  45. await prepareV4ConversationE2E();
  46. // 断言中文文案:固定界面语言,不跟随宿主系统语言(容器里默认英文)。
  47. await pinE2ELocale("zh-CN");
  48. await Promise.all(
  49. [KEEP_GATE, ...OUTPUT_FILES].map((name) => rm(resolveE2ERuntimePath(name), { force: true })),
  50. );
  51. });
  52. after(async () => {
  53. await browser.electron.restoreAllMocks();
  54. await clearAppData();
  55. });
  56. it("DWM-01 Build 会话起的 run:子代理的 Bash 在父会话弹出权限窗,带「子智能体 · 写手甲 (…@…)」徽标,不提供完全访问", async function () {
  57. this.timeout(240000);
  58. await useSessionMode("build");
  59. await sendV4Prompt("E2E_DWM_ASK_START 用工作流让一个子代理写文件。");
  60. await approveWorkflowWindow();
  61. const runId = await readLaunchedRunId("toolu_dwm_ask_create");
  62. const ask = await waitForSubagentAsk("E2E_DWM_ASK_OUTPUT");
  63. // 询问走父会话:权限窗画在发起 run 的会话的 pane 里。
  64. expect(ask.parentSessionId).toBe((await getV4PaneSnapshot()).sessionId);
  65. expect(ask.badgeText).toMatch(/^子智能体 · 写手甲 \(\S+@\d+\)$/);
  66. expect(ask.badgeTitle).toContain("写手甲");
  67. // 与普通子代理同样的选项:允许 / 拒绝,从不提供完全访问。
  68. const kinds = ask.options.map((option) => option.kind);
  69. expect(kinds).toContain("allowOnce");
  70. expect(kinds).toContain("rejectOnce");
  71. for (const option of ask.options) {
  72. expect(option.label).not.toMatch(/完全访问|Full access/);
  73. }
  74. // 还没答:命令没跑,run 在等。
  75. await expect(readFile(resolveE2ERuntimePath("dwm-ask.txt"), "utf8")).rejects.toMatchObject({
  76. code: "ENOENT",
  77. });
  78. expect(await runDigest(runId).getAttribute("data-workflow-run-status")).toBe("running");
  79. });
  80. it("DWM-02 拒绝:子代理下一次请求带着拒绝的工具结果(含反馈)继续,回答后 run 完成,文件没写", async function () {
  81. this.timeout(240000);
  82. expect(await denyV4PermissionWithFeedback(DENY_FEEDBACK)).toBe(true);
  83. await browser.waitUntil(
  84. async () =>
  85. (await getLatestUpstreamToolResultByToolCallId("toolu_dwm_ask_agent_bash")) !== null,
  86. { timeout: 60000, timeoutMsg: "子代理下一次请求没有带上 Bash 的工具结果" },
  87. );
  88. const denied = await getLatestUpstreamToolResultByToolCallId("toolu_dwm_ask_agent_bash");
  89. expect(denied?.isError).toBe(true);
  90. expect(denied?.content).toContain("E2E_DWM_DENY_FEEDBACK");
  91. expect(denied?.content).not.toContain("E2E_DWM_ASK_OUTPUT\n");
  92. // 子代理照常回答,run 完成,主代理被通知唤起;通知里带子代理的回答。
  93. await waitForV4AssistantMessageContaining("E2E_DWM_ASK_DONE", 120000);
  94. const [notified] = await getUpstreamRequestEvidence({
  95. lastUserMessageIncludes: ["<task-notification>", "E2E_DWM_ASK_RESULT"],
  96. });
  97. expect(JSON.stringify(notified?.requestJson)).toContain("E2E_DWM_ASK_ANSWER");
  98. await waitForV4Pane((pane) => !pane.canStop, "通知那一轮没有结束", 60000);
  99. expect(await hasV4PermissionDialog()).toBe(false);
  100. await expect(readFile(resolveE2ERuntimePath("dwm-ask.txt"), "utf8")).rejects.toMatchObject({
  101. code: "ENOENT",
  102. });
  103. });
  104. it("DWM-03 完全访问会话起的 run:确认窗照样出现;子代理的 Bash 不弹权限窗直接执行", async function () {
  105. this.timeout(240000);
  106. await useSessionMode("yolo");
  107. await sendV4Prompt("E2E_DWM_YOLO_START 用工作流让一个子代理写文件。");
  108. // CreateWorkflow 声明 alwaysAsk:完全访问下也问(launch.md「Why the window always appears」)。
  109. await approveWorkflowWindow();
  110. await readLaunchedRunId("toolu_dwm_yolo_create");
  111. const result = await waitForToolResultWithoutAsk("toolu_dwm_yolo_agent_bash");
  112. expect(result.isError).toBe(false);
  113. expect(result.content).toContain("E2E_DWM_YOLO_OUTPUT");
  114. expect(await readFile(resolveE2ERuntimePath("dwm-yolo.txt"), "utf8")).toBe(
  115. "E2E_DWM_YOLO_OUTPUT\n",
  116. );
  117. await waitForV4AssistantMessageContaining("E2E_DWM_YOLO_DONE", 120000);
  118. await waitForV4Pane((pane) => !pane.canStop, "通知那一轮没有结束", 60000);
  119. });
  120. it("DWM-04 run 保持建 run 时的模式:Build 起的 run 停在闸上时会话换成完全访问,子代理的 Bash 仍然询问,允许一次后写入", async function () {
  121. this.timeout(300000);
  122. await useSessionMode("build");
  123. await sendV4Prompt("E2E_DWM_KEEP_START 用工作流让一个子代理在放行后写文件。");
  124. await approveWorkflowWindow();
  125. const runId = await readLaunchedRunId("toolu_dwm_keep_create");
  126. await waitForV4AssistantMessageContaining("E2E_DWM_KEEP_STARTED", 60000);
  127. await waitForV4Pane((pane) => !pane.canStop, "启动轮没有结束", 30000);
  128. expect(await runDigest(runId).getAttribute("data-workflow-run-status")).toBe("running");
  129. // 闸没开:子代理还没起。
  130. expect(await countUpstreamRequests({ lastUserMessageIncludes: ["E2E_DWM_KEEP_TASK"] })).toBe(0);
  131. // 会话换成完全访问并发一句话:主代理这一轮自己的 Bash 不询问,证明会话已在 YOLO。
  132. await useSessionMode("yolo");
  133. await sendV4Prompt("E2E_DWM_KEEP_SWITCH 换成完全访问后跑一条命令。");
  134. const mainResult = await waitForToolResultWithoutAsk("toolu_dwm_keep_main_bash");
  135. expect(mainResult.isError).toBe(false);
  136. await waitForV4AssistantMessageContaining("E2E_DWM_KEEP_SWITCHED", 60000);
  137. await waitForV4Pane((pane) => !pane.canStop, "换模式那一轮没有结束", 30000);
  138. await openGate(KEEP_GATE);
  139. // run 记下的是 Build:子代理照样询问。
  140. const ask = await waitForSubagentAsk("E2E_DWM_KEEP_OUTPUT");
  141. expect(ask.badgeText).toMatch(/^子智能体 · 写手丙 \(\S+@\d+\)$/);
  142. expect(ask.options.map((option) => option.label).join("|")).not.toMatch(/完全访问|Full access/);
  143. expect(await approveV4Permission()).toBe(true);
  144. await browser.waitUntil(
  145. async () =>
  146. (await getLatestUpstreamToolResultByToolCallId("toolu_dwm_keep_agent_bash")) !== null,
  147. { timeout: 60000, timeoutMsg: "子代理下一次请求没有带上 Bash 的工具结果" },
  148. );
  149. const allowed = await getLatestUpstreamToolResultByToolCallId("toolu_dwm_keep_agent_bash");
  150. expect(allowed?.isError).toBe(false);
  151. expect(allowed?.content).toContain("E2E_DWM_KEEP_OUTPUT");
  152. expect(await readFile(resolveE2ERuntimePath("dwm-keep.txt"), "utf8")).toBe(
  153. "E2E_DWM_KEEP_OUTPUT\n",
  154. );
  155. await waitForV4AssistantMessageContaining("E2E_DWM_KEEP_DONE", 120000);
  156. await waitForV4Pane((pane) => !pane.canStop, "通知那一轮没有结束", 60000);
  157. });
  158. });
  159. function runDigest(runId: string) {
  160. return $(`${RUN_DIGEST}[data-workflow-run-id="${runId}"]`);
  161. }
  162. /** 在 composer 选择器里换模式;它只改草稿,下一次发送才把模式带给会话。 */
  163. async function useSessionMode(mode: "build" | "yolo") {
  164. await switchV4Mode(mode);
  165. await browser.waitUntil(async () => (await getV4ConfigProjection()).mode === mode, {
  166. timeout: 30000,
  167. timeoutMsg: `composer 没有切到 mode=${mode}`,
  168. });
  169. }
  170. /**
  171. * 只批准工作流确认窗。通用的 approveV4Permission 在窗还开着时会再点首项,子代理的询问紧跟着弹出时
  172. * 会被它误批;这里只认带工作流块的那个窗。
  173. */
  174. async function approveWorkflowWindow() {
  175. const clickAllow = () =>
  176. browser.execute(() => {
  177. const block = document.querySelector('[data-workflow-permission-block="true"]');
  178. const dock = block?.closest<HTMLElement>('[data-v4-composer-dock="true"]');
  179. const option = dock?.querySelector<HTMLButtonElement>(
  180. 'button[role="option"][data-permission-option-kind="allowOnce"]',
  181. );
  182. option?.click();
  183. return Boolean(option);
  184. });
  185. await browser.waitUntil(clickAllow, { timeout: 60000, timeoutMsg: "工作流确认窗没有出现" });
  186. await browser.waitUntil(
  187. async () => {
  188. const open = await browser.execute(() =>
  189. Boolean(document.querySelector('[data-workflow-permission-block="true"]')),
  190. );
  191. if (open) await clickAllow();
  192. return !open;
  193. },
  194. { timeout: 15000, timeoutMsg: "工作流确认窗批准后没有关闭" },
  195. );
  196. }
  197. /** CreateWorkflow 的工具结果写着新 run 的 id。 */
  198. async function readLaunchedRunId(toolCallId: string) {
  199. await browser.waitUntil(
  200. async () => (await getLatestUpstreamToolResultByToolCallId(toolCallId))?.isError === false,
  201. { timeout: 60000, timeoutMsg: `${toolCallId} 未执行成功` },
  202. );
  203. const result = await getLatestUpstreamToolResultByToolCallId(toolCallId);
  204. const launched = /started in the background with ID: (\S+?)\./.exec(result?.content ?? "");
  205. expect(launched).not.toBeNull();
  206. return launched![1]!;
  207. }
  208. /** 等父会话里出现带子代理来源徽标、且写着这条命令的权限窗。 */
  209. async function waitForSubagentAsk(commandMarker: string): Promise<SubagentAskSnapshot> {
  210. let latest: SubagentAskSnapshot | null = null;
  211. await browser.waitUntil(
  212. async () => {
  213. latest = await readSubagentAsk();
  214. return Boolean(latest?.badgeText && latest.text.includes(commandMarker));
  215. },
  216. {
  217. timeout: 90000,
  218. timeoutMsg: `父会话没有出现子代理的权限窗; latest=${JSON.stringify(latest)}`,
  219. },
  220. );
  221. return latest!;
  222. }
  223. function readSubagentAsk(): Promise<SubagentAskSnapshot | null> {
  224. return browser.execute(() => {
  225. const normalize = (value: string | null | undefined) => (value ?? "").replace(/ /g, " ").trim();
  226. const listbox = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).find(
  227. (element) =>
  228. ["Permission required", "需要权限"].includes(normalize(element.getAttribute("aria-label"))),
  229. );
  230. const dock = listbox?.closest<HTMLElement>('[data-v4-composer-dock="true"]');
  231. const badge = dock?.querySelector<HTMLElement>('[data-interaction-origin-badge="subagent"]');
  232. if (!listbox || !dock || !badge) return null;
  233. return {
  234. parentSessionId:
  235. dock
  236. .closest<HTMLElement>('[data-testid^="v4-session-pane-"]')
  237. ?.getAttribute("data-session-id") ?? null,
  238. // 徽标按宽度截断,完整文字在 DOM 与 tooltip 里。
  239. badgeText: normalize(badge.textContent),
  240. badgeTitle: normalize(badge.getAttribute("title")),
  241. options: Array.from(listbox.querySelectorAll<HTMLElement>('button[role="option"]')).map(
  242. (option) => ({
  243. kind: option.getAttribute("data-permission-option-kind") ?? "",
  244. label: normalize(
  245. `${option.getAttribute("aria-label") ?? ""} ${option.textContent ?? ""}`,
  246. ),
  247. }),
  248. ),
  249. text: normalize(dock.textContent),
  250. };
  251. });
  252. }
  253. /** 等某个 Bash 的工具结果进入下一次请求;途中一旦出现权限窗就失败(这里不该询问)。 */
  254. async function waitForToolResultWithoutAsk(toolCallId: string) {
  255. let asked = false;
  256. await browser.waitUntil(
  257. async () => {
  258. if (await hasV4PermissionDialog()) {
  259. asked = true;
  260. return true;
  261. }
  262. return (await getLatestUpstreamToolResultByToolCallId(toolCallId)) !== null;
  263. },
  264. { timeout: 90000, timeoutMsg: `${toolCallId} 的工具结果没有出现` },
  265. );
  266. if (asked) {
  267. throw new Error(
  268. `${toolCallId} 弹出了权限窗:完全访问下不该询问; ask=${JSON.stringify(await readSubagentAsk())}`,
  269. );
  270. }
  271. return (await getLatestUpstreamToolResultByToolCallId(toolCallId))!;
  272. }
  273. /** 写闸文件:脚本里的 `world.run("node", …)` 看到它就退出,run 往下走到子代理。 */
  274. async function openGate(name: string) {
  275. const path = resolveE2ERuntimePath(name);
  276. await mkdir(dirname(path), { recursive: true });
  277. await writeFile(path, "open\n");
  278. }