conversation-session-guarded.test.ts 10 KB

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