conversation-session-hook-trust.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  2. /**
  3. * 正式 E2E —— Workspace Hook Trust 软门禁与逐条持久信任(HK05–HK07)。
  4. * 已通过人工 review 并由 e2e:promote 从 manual-review/pending 晋级,
  5. * 随默认 spec 发现进入常规回归门禁;fixture 走 case-local provider replay。
  6. *
  7. * 证据分层:
  8. * - UI/交互:composer Hook 图标浮层、Settings 钩子行内“信任”按钮、锁定 Switch
  9. * - Runtime:`.hook-trust-e2e/executions.jsonl` 执行证据(未信任零执行、不补跑、
  10. * 信任后自然事件执行)
  11. * - 持久化:`<E2E_HOME>/.zcode/security/workspace-hook-trust-v1.json` 精确落盘
  12. *
  13. * fixture 由 wdio.conf.ts 在 beforeSession 阶段(resetE2EHome 内)落盘,
  14. * 首个 agent 进程冷启动即加载 workspace hooks;spec 内不重复安装。
  15. */
  16. import {
  17. TID_CHAT_MODE_SELECT_TRIGGER,
  18. TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER,
  19. TID_V4_WORKSPACE_HOOK_PENDING_UNREAD,
  20. TID_SETTINGS_BACK_BUTTON,
  21. TID_SETTINGS_PAGE,
  22. TID_SETTINGS_SECTION_NAV,
  23. TID_TASK_SETTINGS_BUTTON,
  24. TID_V4_WORKSPACE_HOOK_PENDING_POPOVER,
  25. TID_V4_WORKSPACE_HOOK_PENDING_DISMISS,
  26. TID_V4_WORKSPACE_HOOK_PENDING_REVIEW,
  27. testId,
  28. } from "@zcode/shared/test-ids";
  29. import {
  30. DEFAULT_WORKSPACE,
  31. clearAppData,
  32. clickTestIdByDom,
  33. waitForWorkspaceApp,
  34. } from "#e2e/helpers/desktop-app";
  35. import { sel } from "#e2e/helpers/selectors";
  36. import {
  37. E2E_HOOK_TRUST_LABELS,
  38. readHookTrustExecutions,
  39. readHookTrustStore,
  40. waitForHookTrustExecution,
  41. waitForHookTrustStoreRecords,
  42. } from "#e2e/helpers/hook-trust-fixture";
  43. import {
  44. prepareV4ConversationE2E,
  45. sendV4Prompt,
  46. waitForV4Pane,
  47. } from "#e2e/helpers/v4-conversation";
  48. const HOOKS_SECTION_SELECTOR = '[data-testid="hooks-settings-section"]';
  49. const HOOK_ROW_SELECTOR = '//div[@data-testid="configured-hook-row"]';
  50. // 信任按钮通过 ShieldCheck 图标定位(lucide class),不依赖 locale 文案。
  51. const TRUST_BUTTON_IN_ROW = './/button[.//*[contains(@class, "lucide-shield-check")]]';
  52. describe("Workspace Hook Trust (HK05–HK07)", () => {
  53. before(async function () {
  54. this.timeout(120000);
  55. await prepareV4ConversationE2E();
  56. });
  57. after(async () => {
  58. await browser.electron.restoreAllMocks();
  59. await clearAppData();
  60. });
  61. it("HK05: 未信任 Hook 被软门禁跳过,图标浮层引导进设置,行内只提供信任与锁定开关", async function () {
  62. this.timeout(180000);
  63. expect(await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER)).isExisting()).toBe(false);
  64. await sendV4Prompt("E2E_HOOK_TRUST: reply with ok");
  65. await waitForIdle("Soft-gated turn did not return to idle");
  66. // 软门禁不阻塞对话,且未信任 Hook 零执行。
  67. const trigger = $(sel(TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER));
  68. await trigger.waitForDisplayed({ timeout: 30000 });
  69. expect(await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_UNREAD)).isDisplayed()).toBe(true);
  70. expect(await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER)).isExisting()).toBe(false);
  71. expect(await $('[data-testid="v4-workspace-hook-pending-banner"]').isExisting()).toBe(false);
  72. const adjacent = await browser.execute(
  73. (modeId, hookId) => {
  74. const mode = document.querySelector(`[data-testid="${modeId}"]`)!;
  75. const hook = document.querySelector(`[data-testid="${hookId}"]`)!;
  76. const a = mode.getBoundingClientRect();
  77. const b = hook.getBoundingClientRect();
  78. return b.left >= a.right && b.left - a.right <= 12 && Math.abs(a.top - b.top) <= 2;
  79. },
  80. TID_CHAT_MODE_SELECT_TRIGGER,
  81. TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER,
  82. );
  83. expect(adjacent).toBe(true);
  84. await trigger.click();
  85. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER)).waitForDisplayed();
  86. expect(await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_UNREAD)).isExisting()).toBe(false);
  87. await browser.keys("Escape");
  88. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER)).waitForDisplayed({ reverse: true });
  89. expect(await trigger.isFocused()).toBe(true);
  90. await browser.keys("Enter");
  91. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER)).waitForDisplayed();
  92. expect(await readHookTrustExecutions()).toHaveLength(0);
  93. // 从 composer Hook 图标浮层 进入 设置 → 钩子。
  94. await clickTestIdByDom(TID_V4_WORKSPACE_HOOK_PENDING_REVIEW, {
  95. timeout: 15000,
  96. });
  97. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15000 });
  98. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "hooks"), {
  99. timeout: 15000,
  100. });
  101. await $(HOOKS_SECTION_SELECTOR).waitForDisplayed({ timeout: 15000 });
  102. // 三条 workspace Hook 声明全部未信任:只有“信任”按钮 + 锁定关闭的开关,
  103. // 没有其他审核动作(Allow once / Trust all / Keep blocked 均不存在)。
  104. await waitForHookTrustRowCount(3);
  105. for (const label of Object.values(E2E_HOOK_TRUST_LABELS)) {
  106. await assertUntrustedHookRow(label);
  107. }
  108. // 忽略图标 是 renderer 本地行为,不产生 Trust mutation。
  109. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  110. timeout: 15000,
  111. });
  112. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30000);
  113. expect(await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_UNREAD)).isExisting()).toBe(false);
  114. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER)).click();
  115. await clickTestIdByDom(TID_V4_WORKSPACE_HOOK_PENDING_DISMISS, {
  116. timeout: 15000,
  117. });
  118. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER)).waitForDisplayed({
  119. timeout: 15000,
  120. reverse: true,
  121. });
  122. expect(await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER)).isExisting()).toBe(false);
  123. expect(await readHookTrustStore()).toBeNull();
  124. });
  125. it("HK06: 行内信任单条声明,只对该条精确持久落盘,其余行保持可审核", async function () {
  126. this.timeout(180000);
  127. await openHooksSettings();
  128. const trustButton = await findTrustButton(E2E_HOOK_TRUST_LABELS.sessionStartA);
  129. await trustButton.waitForDisplayed({ timeout: 15000 });
  130. await trustButton.click();
  131. const records = await waitForHookTrustStoreRecords(
  132. (items) => items.length === 1,
  133. "Trusting session-start-a did not persist exactly one store record",
  134. );
  135. expect(records[0]!.decision).toBe("trusted");
  136. expect(records[0]!.eventAtGrant).toBe("SessionStart");
  137. // 被信任的行按钮消失;其余两条仍显示“信任”。
  138. await assertNoTrustButton(E2E_HOOK_TRUST_LABELS.sessionStartA);
  139. for (const label of [E2E_HOOK_TRUST_LABELS.sessionStartB, E2E_HOOK_TRUST_LABELS.promptSubmit]) {
  140. await (await findTrustButton(label)).waitForDisplayed({ timeout: 15000 });
  141. }
  142. await closeHooksSettings();
  143. });
  144. it("HK07: 信任不补跑已跳过的 SessionStart,只作用于未来自然事件", async function () {
  145. this.timeout(240000);
  146. // 第一段(同 task):信任 UserPromptSubmit 后再发一条 prompt,
  147. // 出现 prompt-submit 记录 = 信任只作用于未来自然事件;
  148. // 全程无 SessionStart 记录 = 已信任的 session-start-a 不补跑。
  149. await openHooksSettings();
  150. await clickTrustButton(E2E_HOOK_TRUST_LABELS.promptSubmit);
  151. await waitForHookTrustStoreRecords(
  152. (items) => items.length === 2,
  153. "Trusting prompt-submit did not persist a second store record",
  154. );
  155. await closeHooksSettings();
  156. await sendV4Prompt("E2E_HOOK_TRUST second prompt: reply with ok");
  157. await waitForHookTrustExecution(
  158. E2E_HOOK_TRUST_LABELS.promptSubmit,
  159. "Trusted UserPromptSubmit hook did not run on next natural prompt",
  160. );
  161. await waitForIdle("Second turn did not return to idle");
  162. const inTaskExecutions = await readHookTrustExecutions();
  163. expect(inTaskExecutions.filter((item) => item.event === "SessionStart")).toHaveLength(0);
  164. expect(inTaskExecutions.some((item) => item.label === E2E_HOOK_TRUST_LABELS.promptSubmit)).toBe(
  165. true,
  166. );
  167. // 第二段(新 task):catalog HK07 字面语义——新 task 的自然 SessionStart
  168. // 按 Trust 执行。该路径与 UserPromptSubmit 不同:覆盖新 session 冷启动时
  169. // 的配置发现、trust store 读取与 admission 评估全链路,不以"语义等价"省略。
  170. // 全局新建会分配虚拟目录;Hook、Skill 与会话候选必须继续使用夹具所属项目。
  171. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  172. await sendV4Prompt("E2E_HOOK_TRUST new task: reply with ok");
  173. await waitForHookTrustExecution(
  174. E2E_HOOK_TRUST_LABELS.sessionStartA,
  175. "Trusted SessionStart hook did not run on the next natural session start",
  176. );
  177. await waitForIdle("New-task turn did not return to idle");
  178. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_UNREAD)).waitForDisplayed();
  179. const executions = await readHookTrustExecutions();
  180. // 已信任的 a 在新 task 自然 SessionStart 执行且仅执行一次;
  181. // 未信任的 b 仍被软门禁跳过。
  182. expect(
  183. executions.filter((item) => item.label === E2E_HOOK_TRUST_LABELS.sessionStartA),
  184. ).toHaveLength(1);
  185. expect(executions.some((item) => item.label === E2E_HOOK_TRUST_LABELS.sessionStartB)).toBe(
  186. false,
  187. );
  188. // 响应式验收放在项目导航之后,避免窄视口影响后续侧栏操作。
  189. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER)).click();
  190. await verifyHookReminderLayouts();
  191. await browser.keys("Escape");
  192. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER)).waitForDisplayed({ reverse: true });
  193. });
  194. });
  195. async function verifyHookReminderLayouts(): Promise<void> {
  196. const original = await browser.execute(() => {
  197. const actions = (
  198. window as typeof window & {
  199. __testActions: { getTheme(): string; getLocale(): string };
  200. }
  201. ).__testActions;
  202. return { theme: actions.getTheme(), locale: actions.getLocale() };
  203. });
  204. try {
  205. for (const width of [1200, 390]) {
  206. await browser.electron.execute(async (electron, width) => {
  207. const target = electron.BrowserWindow.getAllWindows().find(
  208. (w) => w.isVisible() && !w.isDestroyed(),
  209. )!;
  210. if (!target.webContents.debugger.isAttached()) target.webContents.debugger.attach("1.3");
  211. await target.webContents.debugger.sendCommand("Emulation.setDeviceMetricsOverride", {
  212. width,
  213. height: 844,
  214. deviceScaleFactor: 1,
  215. mobile: false,
  216. });
  217. }, width);
  218. for (const theme of ["zai-light", "zai-dark"]) {
  219. for (const locale of ["zh-CN", "en-US"]) {
  220. await browser.execute(
  221. ({ theme, locale }) => {
  222. const actions = (
  223. window as typeof window & {
  224. __testActions: { setTheme(value: string): void; setLocale(value: string): void };
  225. }
  226. ).__testActions;
  227. actions.setTheme(theme);
  228. actions.setLocale(locale);
  229. },
  230. { theme, locale },
  231. );
  232. const popover = $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER));
  233. await expect(popover).toHaveText(
  234. expect.stringContaining(
  235. locale === "zh-CN" ? "工作区 Hook 待审核" : "workspace hook(s) pending review",
  236. ),
  237. );
  238. await browser.waitUntil(() =>
  239. browser.execute((id) => {
  240. const rect = document.querySelector(`[data-testid="${id}"]`)!.getBoundingClientRect();
  241. return (
  242. rect.left >= 0 &&
  243. rect.right <= innerWidth &&
  244. rect.top >= 0 &&
  245. rect.bottom <= innerHeight
  246. );
  247. }, TID_V4_WORKSPACE_HOOK_PENDING_POPOVER),
  248. );
  249. await browser.saveScreenshot(
  250. `.e2e-artifacts/hook-reminder-${width}-${theme}-${locale}.png`,
  251. );
  252. }
  253. }
  254. }
  255. } finally {
  256. await browser.electron.execute(async (electron) => {
  257. const target = electron.BrowserWindow.getAllWindows().find(
  258. (w) => w.isVisible() && !w.isDestroyed(),
  259. )!;
  260. await target.webContents.debugger.sendCommand("Emulation.clearDeviceMetricsOverride");
  261. });
  262. await browser.execute(({ theme, locale }) => {
  263. const actions = (
  264. window as typeof window & {
  265. __testActions: { setTheme(value: string): void; setLocale(value: string): void };
  266. }
  267. ).__testActions;
  268. actions.setTheme(theme);
  269. actions.setLocale(locale);
  270. }, original);
  271. }
  272. }
  273. async function waitForIdle(timeoutMsg: string): Promise<void> {
  274. await waitForV4Pane(
  275. (snapshot) =>
  276. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  277. timeoutMsg,
  278. 60000,
  279. );
  280. }
  281. async function openHooksSettings(): Promise<void> {
  282. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  283. timeout: 15000,
  284. timeoutMsg: "Hook trust E2E could not open Settings",
  285. });
  286. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15000 });
  287. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "hooks"), {
  288. timeout: 15000,
  289. });
  290. await $(HOOKS_SECTION_SELECTOR).waitForDisplayed({ timeout: 15000 });
  291. }
  292. async function closeHooksSettings(): Promise<void> {
  293. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  294. timeout: 15000,
  295. timeoutMsg: "Hook trust E2E could not leave Settings",
  296. });
  297. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30000);
  298. }
  299. async function waitForHookTrustRowCount(count: number): Promise<void> {
  300. await browser.waitUntil(
  301. () =>
  302. browser.execute(
  303. (expected: number) =>
  304. Array.from(
  305. document.querySelectorAll<HTMLElement>('[data-testid="configured-hook-row"]'),
  306. ).filter((row) => row.innerText.includes("hook-trust-")).length === expected,
  307. count,
  308. ),
  309. {
  310. timeout: 15000,
  311. timeoutMsg: `Hooks settings did not render ${count} workspace hook rows`,
  312. },
  313. );
  314. }
  315. function hookRowSelector(label: string): string {
  316. return `${HOOK_ROW_SELECTOR}[contains(., "${label}")]`;
  317. }
  318. async function findTrustButton(label: string) {
  319. const row = await $(hookRowSelector(label));
  320. await row.waitForDisplayed({ timeout: 15000 });
  321. return await row.$(TRUST_BUTTON_IN_ROW);
  322. }
  323. async function clickTrustButton(label: string): Promise<void> {
  324. await (await findTrustButton(label)).click();
  325. }
  326. async function assertNoTrustButton(label: string): Promise<void> {
  327. const row = await $(hookRowSelector(label));
  328. await row.waitForDisplayed({ timeout: 15000 });
  329. await (
  330. await row.$(TRUST_BUTTON_IN_ROW)
  331. ).waitForExist({
  332. timeout: 15000,
  333. reverse: true,
  334. });
  335. }
  336. async function assertUntrustedHookRow(label: string): Promise<void> {
  337. const row = await $(hookRowSelector(label));
  338. await row.waitForDisplayed({ timeout: 15000 });
  339. const buttons = await row.$$("button");
  340. // 行内动作只有“信任”按钮和 Switch 两个 button;不存在任何额外审核动作或徽章入口。
  341. expect(buttons).toHaveLength(2);
  342. const trustButton = await row.$(TRUST_BUTTON_IN_ROW);
  343. await trustButton.waitForDisplayed({ timeout: 15000 });
  344. expect(await trustButton.isEnabled()).toBe(true);
  345. // 未信任行 Switch 强制关闭并锁定。
  346. const switchControl = await row.$('button[role="switch"]');
  347. await switchControl.waitForDisplayed({ timeout: 15000 });
  348. expect(await switchControl.getAttribute("aria-checked")).toBe("false");
  349. expect(await switchControl.getAttribute("disabled")).not.toBeNull();
  350. }