conversation-session-guarded.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // DCA-V1-01/05/07/09..15:真实桌面 broker → handler → provider result。
  2. // 所有目标均在 case 自有目录;Git 使用不存在的仓库,matcher 回归也不会破坏工作区。
  3. import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { join } from "node:path";
  6. import {
  7. TID_CHAT_MODE_SELECT_ITEM,
  8. TID_CHAT_MODE_SELECT_TRIGGER,
  9. testId,
  10. } from "@zcode/shared/test-ids";
  11. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  12. import { resolveE2ERuntimePath } from "#e2e/helpers/e2e-runtime-paths";
  13. import { skipOccupationOnboardingIfPresent } from "#e2e/helpers/occupation-onboarding";
  14. import {
  15. getV4ModelConfig,
  16. clickV4Stop,
  17. getV4PaneSnapshot,
  18. denyV4PermissionWithFeedback,
  19. prepareV4ConversationE2E,
  20. sendV4Prompt,
  21. switchV4Mode,
  22. waitForV4PermissionDialogInComposerDock,
  23. waitForV4TimelineContaining,
  24. } from "#e2e/helpers/v4-conversation";
  25. import { getLatestUpstreamToolResultByToolCallId } from "#e2e/helpers/conversation-session-network";
  26. const CASE = "conversation-session-guarded";
  27. const ROOT = resolveE2ERuntimePath(CASE);
  28. const DENIED = [
  29. "E2E_GUARDED_RM",
  30. "E2E_GUARDED_STORAGE",
  31. "E2E_GUARDED_RESET",
  32. "E2E_GUARDED_CLEAN",
  33. "E2E_GUARDED_PUSH",
  34. "E2E_GUARDED_DISCARD",
  35. "E2E_GUARDED_STASH",
  36. "E2E_GUARDED_WORKTREE",
  37. "E2E_GUARDED_RSYNC",
  38. ] as const;
  39. const executedPath = (marker: string) => resolveE2ERuntimePath(CASE, marker + ".executed");
  40. const exists = (path: string) =>
  41. access(path).then(
  42. () => true,
  43. () => false,
  44. );
  45. describe("Guarded dangerous command once approval", () => {
  46. let originalRules = "";
  47. before(async () => {
  48. await mkdir(ROOT, { recursive: true });
  49. // 新隔离 profile 先完成 staging 的职业引导,再进入原审批测试。
  50. await skipOccupationOnboardingIfPresent();
  51. });
  52. beforeEach(async () => {
  53. originalRules = await readProjectRules();
  54. });
  55. afterEach(async () => {
  56. expect(await readProjectRules()).toBe(originalRules);
  57. if ((await getV4PaneSnapshot()).canStop) await clickV4Stop();
  58. });
  59. after(async () => {
  60. await browser.electron.restoreAllMocks();
  61. await clearAppData();
  62. await rm(ROOT, { recursive: true, force: true });
  63. });
  64. for (const marker of DENIED) {
  65. it(marker + " refuses without running any part of Bash", async () => {
  66. const protectedFiles =
  67. marker === "E2E_GUARDED_RM" ? ["remove-target/keep.txt", "--help", "--version"] : [];
  68. // macOS 将路径后的帮助词当作删除目标;fixture 先进入 case 目录,避免失败时触及其它文件。
  69. for (const name of protectedFiles) {
  70. await mkdir(join(ROOT, "remove-target"), { recursive: true });
  71. await writeFile(join(ROOT, name), "case-owned preserved content");
  72. }
  73. await prepareV4ConversationE2E();
  74. if (marker === "E2E_GUARDED_RM") {
  75. // 菜单候选替换不迁移历史 edit;真实选择后的拒绝闭环继续检查 Runtime 权限。
  76. await $(`[data-testid="${TID_CHAT_MODE_SELECT_TRIGGER}"]`).click();
  77. const guardedItemTestId = testId(TID_CHAT_MODE_SELECT_ITEM, "guarded");
  78. const guardedItem = $(`[data-testid="${guardedItemTestId}"]`);
  79. await guardedItem.waitForDisplayed();
  80. expect(await guardedItem.$("svg.lucide-shield-check").isExisting()).toBe(true);
  81. const modeIds = await browser.execute(
  82. (prefix) =>
  83. Array.from(document.querySelectorAll(`[data-testid^="${prefix}-"]`)).map((item) =>
  84. item.getAttribute("data-testid")?.slice(prefix.length + 1),
  85. ),
  86. TID_CHAT_MODE_SELECT_ITEM,
  87. );
  88. // staging 的 Plan 已独立置顶;权限候选仍以 Guarded 替换 Edit。
  89. expect(modeIds).toEqual(["plan", "build", "guarded", "yolo"]);
  90. // 直接确认已打开菜单中的选项,避免 Escape 后再次切换菜单造成状态竞态。
  91. await browser.execute((id) => {
  92. document.querySelector<HTMLElement>(`[data-testid="${id}"]`)!.focus();
  93. }, guardedItemTestId);
  94. await browser.keys("Enter");
  95. await guardedItem.waitForExist({ reverse: true, timeout: 5000 });
  96. } else {
  97. await switchV4Mode("guarded");
  98. }
  99. await sendV4Prompt(marker + " Execute the requested test command exactly once.");
  100. await waitForV4PermissionDialogInComposerDock();
  101. expect(
  102. await browser.execute(
  103. () => document.querySelectorAll('[data-permission-option-kind="allowAlways"]').length,
  104. ),
  105. ).toBe(0);
  106. expect(await exists(executedPath(marker))).toBe(false);
  107. expect(await denyV4PermissionWithFeedback("Guarded test: do not execute.")).toBe(true);
  108. await waitForV4TimelineContaining(marker + "_DONE", 60000);
  109. const result = await getLatestUpstreamToolResultByToolCallId("toolu_" + marker);
  110. expect(result?.isError).toBe(true);
  111. expect(result?.content).toContain("Guarded test: do not execute.");
  112. expect(await exists(executedPath(marker))).toBe(false);
  113. for (const name of protectedFiles) {
  114. expect(await readFile(join(ROOT, name), "utf8")).toBe("case-owned preserved content");
  115. }
  116. });
  117. }
  118. for (const [marker, mode] of [
  119. ["E2E_GUARDED_ALLOW", "guarded"],
  120. ["E2E_GUARDED_YOLO", "yolo"],
  121. ] as const) {
  122. it(marker + " uses the real isolated Bash handler exactly once", async () => {
  123. await prepareV4ConversationE2E();
  124. const target = resolveE2ERuntimePath(CASE, marker + ".target");
  125. await writeFile(target, "case-owned disposable input");
  126. await switchV4Mode(mode);
  127. // 展示与权限分开:Guarded 复用 Edit 图标并显示浅蓝色,YOLO 仍为橙色警示。
  128. const trigger = $(`[data-testid="${TID_CHAT_MODE_SELECT_TRIGGER}"]`);
  129. const icon = mode === "guarded" ? "shield-check" : "shield-alert";
  130. const color = mode === "guarded" ? "icon-blue" : "warning";
  131. expect(await trigger.$(`svg.lucide-${icon}`).isExisting()).toBe(true);
  132. await browser.waitUntil(
  133. () =>
  134. browser.execute(
  135. (triggerId, token) => {
  136. const element = document.querySelector<HTMLElement>(`[data-testid="${triggerId}"]`)!;
  137. const probe = document.createElement("span");
  138. probe.style.color = `var(--color-${token})`;
  139. element.append(probe);
  140. const expected = getComputedStyle(probe).color;
  141. probe.remove();
  142. return getComputedStyle(element).color === expected;
  143. },
  144. TID_CHAT_MODE_SELECT_TRIGGER,
  145. color,
  146. ),
  147. { timeout: 5000, timeoutMsg: `${mode} trigger color` },
  148. );
  149. await sendV4Prompt(marker + " Run the isolated cleanup command once.");
  150. if (mode === "guarded") {
  151. await waitForV4PermissionDialogInComposerDock();
  152. expect(await exists(target)).toBe(true);
  153. const changeMode = $('[data-testid="permission-allow-switch"]');
  154. await changeMode.waitForDisplayed();
  155. expect(await $('[data-testid="permission-target-picker"]').isExisting()).toBe(false);
  156. await changeMode.click();
  157. await $('[data-testid="yolo-confirmation-risk"]').click();
  158. await $('[data-testid="yolo-confirmation-confirm"]').click();
  159. await browser.waitUntil(async () => (await getV4ModelConfig()).mode === "yolo");
  160. }
  161. await waitForV4TimelineContaining(marker + "_DONE", 60000);
  162. expect(await exists(target)).toBe(false);
  163. expect((await readFile(executedPath(marker), "utf8")).trim()).toBe("executed");
  164. const result = await getLatestUpstreamToolResultByToolCallId("toolu_" + marker);
  165. expect(result?.isError).toBe(false);
  166. });
  167. }
  168. for (const answerKind of ["preset", "custom", "empty", "deny"] as const) {
  169. it(`AskUserQuestion ${answerKind} completes once in Guarded`, async () => {
  170. const marker = `E2E_GUARDED_QUESTION_${answerKind.toUpperCase()}`;
  171. await prepareV4ConversationE2E();
  172. await switchV4Mode("guarded");
  173. await sendV4Prompt(marker + " Ask the fixture question exactly once.");
  174. const body = await $('[data-elicitation-dialog-body="true"]');
  175. await body.waitForDisplayed({ timeout: 60000 });
  176. if (answerKind === "custom") {
  177. const input = await body.$("textarea");
  178. await input.click();
  179. await input.setValue("Guarded custom answer");
  180. await browser.keys("Enter");
  181. } else if (answerKind === "preset") {
  182. await body.$('button[role="option"]').click();
  183. } else {
  184. const position = answerKind === "deny" ? "first-child" : "last-child";
  185. await $(`[data-elicitation-dialog-footer="true"] button:${position}`).click();
  186. }
  187. await waitForV4TimelineContaining(marker + "_DONE", 60000);
  188. const result = await getLatestUpstreamToolResultByToolCallId("toolu_" + marker);
  189. expect(result?.isError).toBe(answerKind === "deny");
  190. if (answerKind !== "deny")
  191. expect(result?.content).toContain(
  192. answerKind === "preset"
  193. ? "Blue"
  194. : answerKind === "custom"
  195. ? "Guarded custom answer"
  196. : "The user did not provide answers",
  197. );
  198. expect(await $('[data-elicitation-dialog-body="true"]').isExisting()).toBe(false);
  199. });
  200. }
  201. it("a child dangerous request is answered in the parent dock and returned to the child model", async () => {
  202. await prepareV4ConversationE2E();
  203. await switchV4Mode("guarded");
  204. await sendV4Prompt(
  205. "E2E_GUARDED_PARENT Delegate the fixture command to a general-purpose child.",
  206. );
  207. await waitForV4PermissionDialogInComposerDock();
  208. expect(await $('[data-interaction-origin-badge="subagent"]').isExisting()).toBe(true);
  209. expect(await exists(executedPath("E2E_GUARDED_CHILD"))).toBe(false);
  210. expect(await $('[data-testid="permission-allow-switch"]').isExisting()).toBe(false);
  211. expect(await denyV4PermissionWithFeedback("Guarded child refused")).toBe(true);
  212. await waitForV4TimelineContaining("E2E_GUARDED_PARENT_DONE", 60000);
  213. const result = await getLatestUpstreamToolResultByToolCallId("toolu_E2E_GUARDED_CHILD");
  214. expect(result?.isError).toBe(true);
  215. expect(result?.content).toContain("Guarded child refused");
  216. expect(await exists(executedPath("E2E_GUARDED_CHILD"))).toBe(false);
  217. });
  218. });
  219. async function readProjectRules(): Promise<string> {
  220. const path = join(getE2EAppDataPaths().storageRoot, "cli", "db", "db.sqlite");
  221. if (!(await exists(path))) return "[]";
  222. const database = new DatabaseSync(path, { readOnly: true });
  223. try {
  224. return JSON.stringify(
  225. database
  226. .prepare(
  227. "select scope, scope_id, value from local_setting where namespace = 'permission' and key = 'ruleset' order by scope, scope_id",
  228. )
  229. .all(),
  230. );
  231. } finally {
  232. database.close();
  233. }
  234. }