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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  2. import { chromium, type Browser, type Page } from "playwright-core";
  3. import { join } from "node:path";
  4. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  5. import { obtainUnreadPairingUrl, showMobileTaskHome } from "#e2e/helpers/web-remote-unread";
  6. /**
  7. * 正式 E2E —— Workspace Hook Trust 软门禁与逐条持久信任(HK05–HK07、HK18–HK19)。
  8. * 已通过人工 review 并由 e2e:promote 从 manual-review/pending 晋级,
  9. * 随默认 spec 发现进入常规回归门禁;fixture 走 case-local provider replay。
  10. *
  11. * 证据分层:
  12. * - UI/交互:composer Hook 图标浮层、Settings 钩子行内“信任”按钮、锁定 Switch
  13. * - Runtime:`.hook-trust-e2e/executions.jsonl` 执行证据(未信任零执行、不补跑、
  14. * 信任后自然事件执行)
  15. * - 持久化:`<E2E_HOME>/.zcode/security/workspace-hook-trust-v1.json` 精确落盘
  16. *
  17. * fixture 由 wdio.conf.ts 在 beforeSession 阶段(resetE2EHome 内)落盘,
  18. * 首个 agent 进程冷启动即加载 workspace hooks;spec 内不重复安装。
  19. */
  20. import {
  21. TID_CHAT_MODE_SELECT_TRIGGER,
  22. TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER,
  23. TID_V4_WORKSPACE_HOOK_PENDING_UNREAD,
  24. TID_SETTINGS_BACK_BUTTON,
  25. TID_SETTINGS_PAGE,
  26. TID_SETTINGS_SECTION_NAV,
  27. TID_TASK_SETTINGS_BUTTON,
  28. TID_TASK_ITEM,
  29. TID_V4_WORKSPACE_HOOK_PENDING_POPOVER,
  30. TID_V4_WORKSPACE_HOOK_PENDING_DISMISS,
  31. TID_V4_WORKSPACE_HOOK_PENDING_REVIEW,
  32. testId,
  33. } from "@zcode/shared/test-ids";
  34. import {
  35. DEFAULT_WORKSPACE,
  36. clearAppData,
  37. clickTestIdByDom,
  38. waitForWorkspaceApp,
  39. } from "#e2e/helpers/desktop-app";
  40. import { sel } from "#e2e/helpers/selectors";
  41. import {
  42. E2E_HOOK_TRUST_LABELS,
  43. E2E_HOOK_TRUST_SCRIPT_MISSING_LABEL,
  44. readHookTrustExecutions,
  45. readHookTrustStore,
  46. waitForHookTrustExecution,
  47. waitForHookTrustStoreRecords,
  48. } from "#e2e/helpers/hook-trust-fixture";
  49. import {
  50. getV4ConversationState,
  51. prepareV4ConversationE2E,
  52. sendV4Prompt,
  53. waitForV4Pane,
  54. } from "#e2e/helpers/v4-conversation";
  55. const HOOKS_SECTION_SELECTOR = '[data-testid="hooks-settings-section"]';
  56. const HOOK_ROW_SELECTOR = '//div[@data-testid="configured-hook-row"]';
  57. // 信任按钮通过 ShieldCheck 图标定位(lucide class),不依赖 locale 文案。
  58. const TRUST_BUTTON_IN_ROW = './/button[.//*[contains(@class, "lucide-shield-check")]]';
  59. describe("Workspace Hook Trust (HK05–HK07, HK18–HK19)", () => {
  60. before(async function () {
  61. this.timeout(120000);
  62. await prepareV4ConversationE2E();
  63. });
  64. after(async () => {
  65. await browser.electron.restoreAllMocks();
  66. await clearAppData();
  67. });
  68. it("HK05: 未信任 Hook 被软门禁跳过,图标浮层引导进设置,行内只提供信任与锁定开关", async function () {
  69. this.timeout(180000);
  70. expect(await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER)).isExisting()).toBe(false);
  71. await sendV4Prompt("E2E_HOOK_TRUST: reply with ok");
  72. await waitForIdle("Soft-gated turn did not return to idle");
  73. // 软门禁不阻塞对话,且未信任 Hook 零执行。
  74. const trigger = $(sel(TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER));
  75. await trigger.waitForDisplayed({ timeout: 30000 });
  76. expect(await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_UNREAD)).isDisplayed()).toBe(true);
  77. expect(await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER)).isExisting()).toBe(false);
  78. expect(await $('[data-testid="v4-workspace-hook-pending-banner"]').isExisting()).toBe(false);
  79. const adjacent = await browser.execute(
  80. (modeId, hookId) => {
  81. const mode = document.querySelector(`[data-testid="${modeId}"]`)!;
  82. const hook = document.querySelector(`[data-testid="${hookId}"]`)!;
  83. const a = mode.getBoundingClientRect();
  84. const b = hook.getBoundingClientRect();
  85. return b.left >= a.right && b.left - a.right <= 12 && Math.abs(a.top - b.top) <= 2;
  86. },
  87. TID_CHAT_MODE_SELECT_TRIGGER,
  88. TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER,
  89. );
  90. expect(adjacent).toBe(true);
  91. await trigger.click();
  92. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER)).waitForDisplayed();
  93. expect(await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_UNREAD)).isExisting()).toBe(false);
  94. await browser.keys("Escape");
  95. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER)).waitForDisplayed({ reverse: true });
  96. expect(await trigger.isFocused()).toBe(true);
  97. await browser.keys("Enter");
  98. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER)).waitForDisplayed();
  99. expect(await readHookTrustExecutions()).toHaveLength(0);
  100. // 从 composer Hook 图标浮层 进入 设置 → 钩子。
  101. await clickTestIdByDom(TID_V4_WORKSPACE_HOOK_PENDING_REVIEW, {
  102. timeout: 15000,
  103. });
  104. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15000 });
  105. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "hooks"), {
  106. timeout: 15000,
  107. });
  108. await $(HOOKS_SECTION_SELECTOR).waitForDisplayed({ timeout: 15000 });
  109. // 三条可审核的 workspace Hook 声明全部未信任:只有“信任”按钮 + 锁定关闭的开关,
  110. // 没有其他审核动作(Allow once / Trust all / Keep blocked 均不存在)。
  111. // 第四行是 HK18 的入口脚本缺失声明,单独断言。
  112. await waitForHookTrustRowCount(4);
  113. for (const label of Object.values(E2E_HOOK_TRUST_LABELS)) {
  114. await assertUntrustedHookRow(label);
  115. }
  116. // 忽略图标 是 renderer 本地行为,不产生 Trust mutation。
  117. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  118. timeout: 15000,
  119. });
  120. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30000);
  121. expect(await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_UNREAD)).isExisting()).toBe(false);
  122. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER)).click();
  123. await clickTestIdByDom(TID_V4_WORKSPACE_HOOK_PENDING_DISMISS, {
  124. timeout: 15000,
  125. });
  126. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER)).waitForDisplayed({
  127. timeout: 15000,
  128. reverse: true,
  129. });
  130. expect(await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER)).isExisting()).toBe(false);
  131. expect(await readHookTrustStore()).toBeNull();
  132. });
  133. it("HK06: 行内信任单条声明,只对该条精确持久落盘,其余行保持可审核", async function () {
  134. this.timeout(180000);
  135. await openHooksSettings();
  136. const trustButton = await findTrustButton(E2E_HOOK_TRUST_LABELS.sessionStartA);
  137. await trustButton.waitForDisplayed({ timeout: 15000 });
  138. await trustButton.click();
  139. const records = await waitForHookTrustStoreRecords(
  140. (items) => items.length === 1,
  141. "Trusting session-start-a did not persist exactly one store record",
  142. );
  143. expect(records[0]!.decision).toBe("trusted");
  144. expect(records[0]!.eventAtGrant).toBe("SessionStart");
  145. // 被信任的行按钮消失;其余两条仍显示“信任”。
  146. await assertNoTrustButton(E2E_HOOK_TRUST_LABELS.sessionStartA);
  147. for (const label of [E2E_HOOK_TRUST_LABELS.sessionStartB, E2E_HOOK_TRUST_LABELS.promptSubmit]) {
  148. await (await findTrustButton(label)).waitForDisplayed({ timeout: 15000 });
  149. }
  150. await closeHooksSettings();
  151. });
  152. it("HK07: 信任不补跑已跳过的 SessionStart,只作用于未来自然事件", async function () {
  153. this.timeout(240000);
  154. // 第一段(同 task):信任 UserPromptSubmit 后再发一条 prompt,
  155. // 出现 prompt-submit 记录 = 信任只作用于未来自然事件;
  156. // 全程无 SessionStart 记录 = 已信任的 session-start-a 不补跑。
  157. await openHooksSettings();
  158. await clickTrustButton(E2E_HOOK_TRUST_LABELS.promptSubmit);
  159. await waitForHookTrustStoreRecords(
  160. (items) => items.length === 2,
  161. "Trusting prompt-submit did not persist a second store record",
  162. );
  163. await closeHooksSettings();
  164. await sendV4Prompt("E2E_HOOK_TRUST second prompt: reply with ok");
  165. await waitForHookTrustExecution(
  166. E2E_HOOK_TRUST_LABELS.promptSubmit,
  167. "Trusted UserPromptSubmit hook did not run on next natural prompt",
  168. );
  169. await waitForIdle("Second turn did not return to idle");
  170. const inTaskExecutions = await readHookTrustExecutions();
  171. expect(inTaskExecutions.filter((item) => item.event === "SessionStart")).toHaveLength(0);
  172. expect(inTaskExecutions.some((item) => item.label === E2E_HOOK_TRUST_LABELS.promptSubmit)).toBe(
  173. true,
  174. );
  175. // 第二段(新 task):catalog HK07 字面语义——新 task 的自然 SessionStart
  176. // 按 Trust 执行。该路径与 UserPromptSubmit 不同:覆盖新 session 冷启动时
  177. // 的配置发现、trust store 读取与 admission 评估全链路,不以"语义等价"省略。
  178. // 全局新建会分配虚拟目录;Hook、Skill 与会话候选必须继续使用夹具所属项目。
  179. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  180. await sendV4Prompt("E2E_HOOK_TRUST new task: reply with ok");
  181. await waitForHookTrustExecution(
  182. E2E_HOOK_TRUST_LABELS.sessionStartA,
  183. "Trusted SessionStart hook did not run on the next natural session start",
  184. );
  185. await waitForIdle("New-task turn did not return to idle");
  186. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_UNREAD)).waitForDisplayed();
  187. const executions = await readHookTrustExecutions();
  188. // 已信任的 a 在新 task 自然 SessionStart 执行且仅执行一次;
  189. // 未信任的 b 仍被软门禁跳过。
  190. expect(
  191. executions.filter((item) => item.label === E2E_HOOK_TRUST_LABELS.sessionStartA),
  192. ).toHaveLength(1);
  193. expect(executions.some((item) => item.label === E2E_HOOK_TRUST_LABELS.sessionStartB)).toBe(
  194. false,
  195. );
  196. // 响应式验收放在项目导航之后,避免窄视口影响后续侧栏操作。
  197. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER)).click();
  198. await verifyHookReminderLayouts();
  199. await browser.keys("Escape");
  200. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER)).waitForDisplayed({ reverse: true });
  201. });
  202. // 放在最后:窄视口验收会改变侧栏状态,影响 HK07 的项目导航。
  203. it("HK18: 入口脚本不存在的声明不提供信任,开关锁定,各视口与主题下原因可见", async function () {
  204. this.timeout(180000);
  205. // 新 task 的设置页默认是用户作用域;与 HK05 相同,经 Hook 图标浮层进入工作区作用域。
  206. await $(sel(TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER)).click();
  207. await clickTestIdByDom(TID_V4_WORKSPACE_HOOK_PENDING_REVIEW, { timeout: 15000 });
  208. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15000 });
  209. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "hooks"), { timeout: 15000 });
  210. await $(HOOKS_SECTION_SELECTOR).waitForDisplayed({ timeout: 15000 });
  211. const row = await $(hookRowSelector(E2E_HOOK_TRUST_SCRIPT_MISSING_LABEL));
  212. await row.waitForDisplayed({ timeout: 15000 });
  213. // 没有可审核的内容:只有锁定关闭的 Switch,没有“信任”按钮。
  214. expect(await row.$$("button")).toHaveLength(1);
  215. expect(await (await row.$(TRUST_BUTTON_IN_ROW)).isExisting()).toBe(false);
  216. const switchControl = await row.$('button[role="switch"]');
  217. expect(await switchControl.getAttribute("aria-checked")).toBe("false");
  218. expect(await switchControl.getAttribute("disabled")).not.toBeNull();
  219. await verifyScriptUnavailableRowLayouts();
  220. await closeHooksSettings();
  221. expect(
  222. (await readHookTrustExecutions()).some(
  223. (item) => item.label === E2E_HOOK_TRUST_SCRIPT_MISSING_LABEL,
  224. ),
  225. ).toBe(false);
  226. // HK06/HK07 已信任其他行;入口缺失的 Stop 声明不得出现在 store 中。
  227. expect((await readHookTrustStore())?.some((record) => record.eventAtGrant === "Stop")).toBe(
  228. false,
  229. );
  230. });
  231. // 手机 Web 远控与桌面共用同一 Host 设置数据:入口脚本缺失的行同样只显示原因,开关锁定,无信任按钮。
  232. it("HK19: 手机 Web 远控设置页对入口脚本缺失的 Hook 显示原因、锁定开关、无信任按钮", async function () {
  233. this.timeout(180000);
  234. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts";
  235. const { taskId } = await getV4ConversationState();
  236. expect(taskId).toBeTruthy();
  237. // 前序用例的窄视口验收会让侧栏折叠;配对入口在侧栏底部,先展开。
  238. if (await sidebarCollapsed()) {
  239. await browser.execute(() => {
  240. document
  241. .querySelector<HTMLButtonElement>(
  242. 'button[aria-label="切换侧边栏"], button[aria-label="Toggle sidebar"]',
  243. )
  244. ?.click();
  245. });
  246. await browser.waitUntil(async () => !(await sidebarCollapsed()), {
  247. timeout: 15000,
  248. timeoutMsg: "HK19 could not expand the sidebar before pairing",
  249. });
  250. }
  251. // 远控 fixture(web-remote-control-auth-gate-fixture 登记本 spec)提供本地 relay 与测试登录态,
  252. // 否则桌面端的远控弹窗会停在登录门禁,拿不到配对链接。
  253. const endpoint = process.env.ZCODE_WEB_REMOTE_CONTROL_URL;
  254. if (!endpoint) throw new Error("HK19 requires the web remote control fixture");
  255. const pairingUrl = await obtainUnreadPairingUrl(new URL(endpoint).origin);
  256. const executablePath =
  257. process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE || process.env.R3_MOBILE_CHROME;
  258. let chrome: Browser | undefined;
  259. let page: Page | undefined;
  260. try {
  261. chrome = await chromium.launch({
  262. ...(executablePath ? { executablePath } : { channel: "chrome" }),
  263. headless: true,
  264. });
  265. const context = await chrome.newContext({
  266. viewport: { width: 390, height: 844 },
  267. isMobile: true,
  268. hasTouch: true,
  269. locale: "zh-CN",
  270. });
  271. await seedMobileFixtureLogin(context);
  272. page = await context.newPage();
  273. await openMobilePairingPage(page, pairingUrl, {
  274. artifactDir,
  275. caseMarker: "HK19",
  276. phase: "mobile",
  277. readySelector: '[data-testid="sidebar"], [data-mobile-page="chat"]',
  278. });
  279. await showMobileTaskHome(page);
  280. await page.getByTestId(testId(TID_TASK_ITEM, taskId!)).click();
  281. await page.getByTestId(TID_V4_WORKSPACE_HOOK_PENDING_TRIGGER).click();
  282. await page.getByTestId(TID_V4_WORKSPACE_HOOK_PENDING_REVIEW).click();
  283. await page.getByTestId(TID_SETTINGS_PAGE).waitFor({ state: "visible" });
  284. const hooksNav = page.getByTestId(testId(TID_SETTINGS_SECTION_NAV, "hooks"));
  285. if (await hooksNav.isVisible()) await hooksNav.click();
  286. const row = page
  287. .locator('[data-testid="configured-hook-row"]')
  288. .filter({ hasText: E2E_HOOK_TRUST_SCRIPT_MISSING_LABEL });
  289. await row.waitFor({ state: "visible" });
  290. await row.scrollIntoViewIfNeeded();
  291. expect(await row.innerText()).toContain(SCRIPT_UNAVAILABLE_TEXT["zh-CN"]!);
  292. expect(await row.locator("button").count()).toBe(1);
  293. expect(await row.locator(".lucide-shield-check").count()).toBe(0);
  294. const switchControl = row.locator('button[role="switch"]');
  295. expect(await switchControl.getAttribute("aria-checked")).toBe("false");
  296. expect(await switchControl.isDisabled()).toBe(true);
  297. const box = await row.boundingBox();
  298. expect(box).not.toBeNull();
  299. expect(box!.x).toBeGreaterThanOrEqual(0);
  300. expect(box!.x + box!.width).toBeLessThanOrEqual(390);
  301. for (const theme of ["zai-light", "zai-dark"]) {
  302. await page.evaluate((value) => {
  303. (
  304. window as typeof window & { __testActions: { setTheme(value: string): void } }
  305. ).__testActions.setTheme(value);
  306. }, theme);
  307. await page.screenshot({
  308. path: join(artifactDir, `hook-script-unavailable-mobile-${theme}.png`),
  309. });
  310. }
  311. } catch (error) {
  312. if (page && !page.isClosed()) {
  313. await page.screenshot({ path: join(artifactDir, "HK19-mobile-failure.png") });
  314. }
  315. throw error;
  316. } finally {
  317. await chrome?.close();
  318. }
  319. });
  320. });
  321. async function sidebarCollapsed(): Promise<boolean> {
  322. return browser.execute(
  323. () =>
  324. (document.querySelector('[data-testid="sidebar"]')?.getBoundingClientRect().width ?? 0) < 100,
  325. );
  326. }
  327. const SCRIPT_UNAVAILABLE_TEXT: Record<string, string> = {
  328. "zh-CN": "入口脚本不存在或无法读取",
  329. "en-US": "Script missing or unreadable",
  330. };
  331. /** HK18 视觉验收:1200/390 × 深浅主题 × 中英文,原因标签可见、不溢出行。 */
  332. async function verifyScriptUnavailableRowLayouts(): Promise<void> {
  333. await withLayoutMatrix(async ({ width, theme, locale }) => {
  334. const row = $(hookRowSelector(E2E_HOOK_TRUST_SCRIPT_MISSING_LABEL));
  335. await row.scrollIntoView({ block: "center" });
  336. await expect(row).toHaveText(expect.stringContaining(SCRIPT_UNAVAILABLE_TEXT[locale]!));
  337. const fits = await browser.execute((label: string) => {
  338. const element = Array.from(
  339. document.querySelectorAll<HTMLElement>('[data-testid="configured-hook-row"]'),
  340. ).find((candidate) => candidate.innerText.includes(label))!;
  341. const rowRect = element.getBoundingClientRect();
  342. return Array.from(element.querySelectorAll("*")).every((child) => {
  343. const rect = child.getBoundingClientRect();
  344. return (
  345. rect.width === 0 || (rect.left >= rowRect.left - 1 && rect.right <= rowRect.right + 1)
  346. );
  347. });
  348. }, E2E_HOOK_TRUST_SCRIPT_MISSING_LABEL);
  349. expect(fits).toBe(true);
  350. await browser.saveScreenshot(
  351. `.e2e-artifacts/hook-script-unavailable-${width}-${theme}-${locale}.png`,
  352. );
  353. });
  354. }
  355. async function verifyHookReminderLayouts(): Promise<void> {
  356. await withLayoutMatrix(async ({ width, theme, locale }) => {
  357. const popover = $(sel(TID_V4_WORKSPACE_HOOK_PENDING_POPOVER));
  358. await expect(popover).toHaveText(
  359. expect.stringContaining(
  360. locale === "zh-CN" ? "工作区 Hook 待审核" : "workspace hook(s) pending review",
  361. ),
  362. );
  363. await browser.waitUntil(() =>
  364. browser.execute((id) => {
  365. const rect = document.querySelector(`[data-testid="${id}"]`)!.getBoundingClientRect();
  366. return (
  367. rect.left >= 0 && rect.right <= innerWidth && rect.top >= 0 && rect.bottom <= innerHeight
  368. );
  369. }, TID_V4_WORKSPACE_HOOK_PENDING_POPOVER),
  370. );
  371. await browser.saveScreenshot(`.e2e-artifacts/hook-reminder-${width}-${theme}-${locale}.png`);
  372. });
  373. }
  374. /** 1200/390 视口 × Zai 深浅主题 × 中英文逐一回调;结束后恢复视口、主题与语言。 */
  375. async function withLayoutMatrix(
  376. check: (layout: { width: number; theme: string; locale: string }) => Promise<void>,
  377. ): Promise<void> {
  378. const original = await browser.execute(() => {
  379. const actions = (
  380. window as typeof window & {
  381. __testActions: { getTheme(): string; getLocale(): string };
  382. }
  383. ).__testActions;
  384. return { theme: actions.getTheme(), locale: actions.getLocale() };
  385. });
  386. try {
  387. for (const width of [1200, 390]) {
  388. await browser.electron.execute(async (electron, width) => {
  389. const target = electron.BrowserWindow.getAllWindows().find(
  390. (w) => w.isVisible() && !w.isDestroyed(),
  391. )!;
  392. if (!target.webContents.debugger.isAttached()) target.webContents.debugger.attach("1.3");
  393. await target.webContents.debugger.sendCommand("Emulation.setDeviceMetricsOverride", {
  394. width,
  395. height: 844,
  396. deviceScaleFactor: 1,
  397. mobile: false,
  398. });
  399. }, width);
  400. for (const theme of ["zai-light", "zai-dark"]) {
  401. for (const locale of ["zh-CN", "en-US"]) {
  402. await browser.execute(
  403. ({ theme, locale }) => {
  404. const actions = (
  405. window as typeof window & {
  406. __testActions: { setTheme(value: string): void; setLocale(value: string): void };
  407. }
  408. ).__testActions;
  409. actions.setTheme(theme);
  410. actions.setLocale(locale);
  411. },
  412. { theme, locale },
  413. );
  414. await check({ width, theme, locale });
  415. }
  416. }
  417. }
  418. } finally {
  419. await browser.electron.execute(async (electron) => {
  420. const target = electron.BrowserWindow.getAllWindows().find(
  421. (w) => w.isVisible() && !w.isDestroyed(),
  422. )!;
  423. await target.webContents.debugger.sendCommand("Emulation.clearDeviceMetricsOverride");
  424. });
  425. await browser.execute(({ theme, locale }) => {
  426. const actions = (
  427. window as typeof window & {
  428. __testActions: { setTheme(value: string): void; setLocale(value: string): void };
  429. }
  430. ).__testActions;
  431. actions.setTheme(theme);
  432. actions.setLocale(locale);
  433. }, original);
  434. }
  435. }
  436. async function waitForIdle(timeoutMsg: string): Promise<void> {
  437. await waitForV4Pane(
  438. (snapshot) =>
  439. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  440. timeoutMsg,
  441. 60000,
  442. );
  443. }
  444. async function openHooksSettings(): Promise<void> {
  445. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  446. timeout: 15000,
  447. timeoutMsg: "Hook trust E2E could not open Settings",
  448. });
  449. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15000 });
  450. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "hooks"), {
  451. timeout: 15000,
  452. });
  453. await $(HOOKS_SECTION_SELECTOR).waitForDisplayed({ timeout: 15000 });
  454. }
  455. async function closeHooksSettings(): Promise<void> {
  456. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  457. timeout: 15000,
  458. timeoutMsg: "Hook trust E2E could not leave Settings",
  459. });
  460. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30000);
  461. }
  462. async function waitForHookTrustRowCount(count: number): Promise<void> {
  463. await browser.waitUntil(
  464. () =>
  465. browser.execute(
  466. (expected: number) =>
  467. Array.from(
  468. document.querySelectorAll<HTMLElement>('[data-testid="configured-hook-row"]'),
  469. ).filter((row) => row.innerText.includes("hook-trust-")).length === expected,
  470. count,
  471. ),
  472. {
  473. timeout: 15000,
  474. timeoutMsg: `Hooks settings did not render ${count} workspace hook rows`,
  475. },
  476. );
  477. }
  478. function hookRowSelector(label: string): string {
  479. return `${HOOK_ROW_SELECTOR}[contains(., "${label}")]`;
  480. }
  481. async function findTrustButton(label: string) {
  482. const row = await $(hookRowSelector(label));
  483. await row.waitForDisplayed({ timeout: 15000 });
  484. return await row.$(TRUST_BUTTON_IN_ROW);
  485. }
  486. async function clickTrustButton(label: string): Promise<void> {
  487. await (await findTrustButton(label)).click();
  488. }
  489. async function assertNoTrustButton(label: string): Promise<void> {
  490. const row = await $(hookRowSelector(label));
  491. await row.waitForDisplayed({ timeout: 15000 });
  492. await (
  493. await row.$(TRUST_BUTTON_IN_ROW)
  494. ).waitForExist({
  495. timeout: 15000,
  496. reverse: true,
  497. });
  498. }
  499. async function assertUntrustedHookRow(label: string): Promise<void> {
  500. const row = await $(hookRowSelector(label));
  501. await row.waitForDisplayed({ timeout: 15000 });
  502. const buttons = await row.$$("button");
  503. // 行内动作只有“信任”按钮和 Switch 两个 button;不存在任何额外审核动作或徽章入口。
  504. expect(buttons).toHaveLength(2);
  505. const trustButton = await row.$(TRUST_BUTTON_IN_ROW);
  506. await trustButton.waitForDisplayed({ timeout: 15000 });
  507. expect(await trustButton.isEnabled()).toBe(true);
  508. // 未信任行 Switch 强制关闭并锁定。
  509. const switchControl = await row.$('button[role="switch"]');
  510. await switchControl.waitForDisplayed({ timeout: 15000 });
  511. expect(await switchControl.getAttribute("aria-checked")).toBe("false");
  512. expect(await switchControl.getAttribute("disabled")).not.toBeNull();
  513. }