conversation-session-hooks-lifecycle.test.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. import { mkdir, readFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import {
  4. TID_SETTINGS_BACK_BUTTON,
  5. TID_SETTINGS_PAGE,
  6. TID_SETTINGS_SECTION_NAV,
  7. TID_TASK_SETTINGS_BUTTON,
  8. TID_CHAT_ERROR_BANNER,
  9. TID_CHAT_ERROR_DETAILS_BUTTON,
  10. TID_CHAT_ERROR_HOOK_ICON,
  11. TID_V4_HOOK_DETAILS_CONTENT,
  12. TID_V4_HOOK_DETAILS_TRIGGER,
  13. testId,
  14. } from "@zcode/shared";
  15. import {
  16. clearAppData,
  17. clickTestIdByDom,
  18. DEFAULT_WORKSPACE,
  19. seedSettings,
  20. waitForWorkspaceApp,
  21. } from "../helpers/desktop-app.js";
  22. import {
  23. countUpstreamRequests,
  24. countUpstreamRequestsContaining,
  25. waitForUpstreamRequest,
  26. } from "../helpers/conversation-session-network.js";
  27. import { waitForUpstreamNetworkCapture } from "../helpers/upstream-capture.js";
  28. import { selectUpstreamModel, selectUpstreamThoughtLevel } from "../helpers/upstream-provider.js";
  29. import {
  30. findHookEvent,
  31. hasHookRecord,
  32. HOOKS_CASE_MARKERS,
  33. HOOKS_CONTEXT,
  34. HOOKS_ERROR_DETAIL,
  35. HOOKS_FINAL_MARKERS,
  36. HOOKS_REASON,
  37. HOOKS_RELATIVE_PATHS,
  38. HOOKS_TOOL_CALL_IDS,
  39. installHooksLifecycleFixture,
  40. readHookTraceRecords,
  41. processHookRecords,
  42. restoreHooksLifecycleFixture,
  43. waitForHookScenarioTrace,
  44. type HookTraceRecord,
  45. } from "../helpers/hooks-lifecycle-fixture.js";
  46. import { waitForCompactMarkerStatuses } from "../helpers/conversation-session-compact.js";
  47. import { sel } from "../helpers/selectors.js";
  48. import { skipOccupationOnboardingIfPresent } from "../helpers/occupation-onboarding.js";
  49. import {
  50. getV4ComposerText,
  51. prepareV4ConversationE2E,
  52. sendV4Prompt,
  53. startNewV4Draft as startEmptyV4Draft,
  54. waitForV4AssistantMessageContaining,
  55. waitForV4Pane,
  56. waitForV4TimelineContaining,
  57. } from "../helpers/v4-conversation.js";
  58. const STOP_STEP = (index: number) => `${HOOKS_CASE_MARKERS.stopCap}_STEP_${index}`;
  59. async function startNewV4Draft() {
  60. await startEmptyV4Draft();
  61. // Hook 用例不测试默认模型;每份新草稿显式选择,不能依赖旧 Recent 自动回填。
  62. await selectUpstreamModel();
  63. await selectUpstreamThoughtLevel();
  64. }
  65. const HOOK_BLOCK_SCREENSHOT_DIR = join(
  66. process.env.ZCODE_E2E_ARTIFACT_DIR?.trim() || join(process.cwd(), ".e2e-artifacts"),
  67. "hooks-block-reason",
  68. );
  69. describe("Hooks full-chain E2E", () => {
  70. before(async function () {
  71. this.timeout(120000);
  72. await installHooksLifecycleFixture();
  73. // Hooks 详情断言验证中文 aria-label/摘要文案;locale 属于 case fixture,不能
  74. // 依赖运行机系统语言,否则同一 Hook 证据会在英文环境下变成 "Hooks"。
  75. await seedSettings({ locale: "zh-CN", localePreference: "zh-CN" });
  76. // 新隔离 profile 的三步引导会覆盖工作区;先完成真实 UI,再进入 Hook 验收。
  77. await skipOccupationOnboardingIfPresent();
  78. await prepareV4ConversationE2E();
  79. });
  80. after(async () => {
  81. await restoreHooksLifecycleFixture();
  82. await browser.electron.restoreAllMocks();
  83. await clearAppData();
  84. });
  85. it("HK-LC-01: runs seven events, all executors, compatible stdin, and event effects", async function () {
  86. this.timeout(180000);
  87. const prompt = `${HOOKS_CASE_MARKERS.fullChain}: run the configured modified Write and failing Read chain, then reply with exactly ${HOOKS_FINAL_MARKERS.fullChain}.`;
  88. await assertHooksSettingsPage();
  89. await sendV4Prompt(prompt);
  90. await waitForEmptyV4Composer("Full-chain Hooks prompt did not clear the composer");
  91. await waitForV4TimelineContaining(HOOKS_CASE_MARKERS.fullChain);
  92. // Bug 根因:Hooks 验收误把 V4 虚拟时间线里的折叠 tool card 当作运行时完成
  93. // barrier;card 可能已滑出窗口,但后续 provider request 与 trace 才是本 case
  94. // 的权威证据。避免用无关的 UI 可见性阻塞 Hooks 全链断言。
  95. await waitForV4TimelineContaining(HOOKS_FINAL_MARKERS.fullChain);
  96. await waitForIdle("Full-chain Hooks case did not return to idle");
  97. await waitForUpstreamRequest(
  98. {
  99. includes: [HOOKS_CASE_MARKERS.fullChain, HOOKS_CONTEXT.session, HOOKS_CONTEXT.prompt],
  100. excludes: [HOOKS_CONTEXT.asyncIgnored],
  101. },
  102. "First full-chain request did not receive lifecycle context",
  103. 60000,
  104. );
  105. await waitForUpstreamRequest(
  106. {
  107. includes: [
  108. HOOKS_TOOL_CALL_IDS.fullWrite,
  109. HOOKS_RELATIVE_PATHS.fullFinal,
  110. HOOKS_CONTEXT.preWrite,
  111. HOOKS_CONTEXT.post,
  112. ],
  113. },
  114. "Modified Write result did not expose final input and Hook context",
  115. 60000,
  116. );
  117. await waitForUpstreamRequest(
  118. {
  119. includes: [HOOKS_TOOL_CALL_IDS.fullRead, HOOKS_CONTEXT.preRead, HOOKS_CONTEXT.failure],
  120. },
  121. "Failed Read result did not expose recovery Hook context",
  122. 60000,
  123. );
  124. expect(await readFile(workspacePath(HOOKS_RELATIVE_PATHS.fullFinal), "utf8")).toBe(
  125. "permission modified content\n",
  126. );
  127. await expectMissingPath(HOOKS_RELATIVE_PATHS.fullOriginal);
  128. await expectMissingPath(HOOKS_RELATIVE_PATHS.fullPreModified);
  129. const trace = await waitForHookScenarioTrace(
  130. HOOKS_CASE_MARKERS.fullChain,
  131. (records) =>
  132. hasHookRecord(records, {
  133. executor: "process",
  134. hook_event_name: "Stop",
  135. phase: "completed",
  136. }) &&
  137. hasHookRecord(records, {
  138. executor: "command-async",
  139. hook_event_name: "UserPromptSubmit",
  140. phase: "completed",
  141. }),
  142. "Full-chain Hook trace did not complete",
  143. );
  144. assertFullChainTrace(trace, prompt);
  145. await assertHookTurnDetails(HOOKS_FINAL_MARKERS.fullChain);
  146. });
  147. it("HK-EF-01: preserves additionalContext on every handler-before failure", async function () {
  148. this.timeout(180000);
  149. await startNewV4Draft();
  150. const prompt = `${HOOKS_CASE_MARKERS.earlyFailures}: trigger PreToolUse deny, invalid updatedInput, and PermissionRequest deny, then reply with exactly ${HOOKS_FINAL_MARKERS.earlyFailures}.`;
  151. await sendV4Prompt(prompt);
  152. await waitForEmptyV4Composer("Early-failure Hooks prompt did not clear the composer");
  153. await waitForV4TimelineContaining(HOOKS_CASE_MARKERS.earlyFailures);
  154. // Bug 根因:final marker 同时写在用户 prompt 里,按整条 timeline 查文本会在
  155. // provider 请求尚未开始时误判完成。先用 capture 证明主请求已完成,再只在
  156. // assistant row 中等待最终回复,避免 shard 负载下提前进入 trace 断言。
  157. await waitForUpstreamNetworkCapture(HOOKS_CASE_MARKERS.earlyFailures);
  158. await waitForV4AssistantMessageContaining(HOOKS_FINAL_MARKERS.earlyFailures);
  159. await waitForIdle("Early-failure Hooks case did not return to idle");
  160. for (const [toolCallId, context] of [
  161. [HOOKS_TOOL_CALL_IDS.earlyPreDeny, HOOKS_CONTEXT.preDeny],
  162. [HOOKS_TOOL_CALL_IDS.earlyInvalid, HOOKS_CONTEXT.invalidUpdate],
  163. [HOOKS_TOOL_CALL_IDS.earlyPermissionDeny, HOOKS_CONTEXT.permissionDeny],
  164. ] as const) {
  165. await waitForUpstreamRequest(
  166. { includes: [toolCallId, context] },
  167. `Early failure lost Hook context for ${toolCallId}`,
  168. 60000,
  169. );
  170. }
  171. await waitForUpstreamRequest(
  172. {
  173. includes: [HOOKS_TOOL_CALL_IDS.earlyPermissionDeny, HOOKS_REASON.permissionDeny],
  174. },
  175. "PermissionRequest deny reason did not reach the model",
  176. 60000,
  177. );
  178. for (const path of [
  179. HOOKS_RELATIVE_PATHS.earlyPreDeny,
  180. HOOKS_RELATIVE_PATHS.earlyInvalid,
  181. HOOKS_RELATIVE_PATHS.earlyInvalidTarget,
  182. HOOKS_RELATIVE_PATHS.earlyPermissionDeny,
  183. ]) {
  184. await expectMissingPath(path);
  185. }
  186. const trace = await waitForHookScenarioTrace(
  187. HOOKS_CASE_MARKERS.earlyFailures,
  188. (records) =>
  189. hasHookRecord(records, {
  190. executor: "process",
  191. hook_event_name: "Stop",
  192. }),
  193. "Early-failure Hook trace did not complete",
  194. );
  195. assertEarlyFailureTrace(trace);
  196. });
  197. it("HK-ST-01: caps consecutive Stop continuations at three", async function () {
  198. this.timeout(180000);
  199. await startNewV4Draft();
  200. const prompt = `${HOOKS_CASE_MARKERS.stopCap}: keep revising only when the Stop hook asks.`;
  201. await sendV4Prompt(prompt);
  202. await waitForV4TimelineContaining(HOOKS_CASE_MARKERS.stopCap);
  203. await waitForV4TimelineContaining(STOP_STEP(3));
  204. await waitForIdle("Stop-cap Hooks case did not return to idle");
  205. expect(await countUpstreamRequestsContaining(HOOKS_CASE_MARKERS.stopCap)).toBe(4);
  206. for (const index of [1, 2, 3]) {
  207. await waitForUpstreamRequest(
  208. { includes: [HOOKS_CASE_MARKERS.stopCap, HOOKS_CONTEXT.stop(index)] },
  209. `Stop continuation request ${index} did not receive Hook context`,
  210. 60000,
  211. );
  212. }
  213. expect(
  214. await countUpstreamRequests({
  215. includes: [HOOKS_CASE_MARKERS.stopCap, HOOKS_CONTEXT.stop(4)],
  216. }),
  217. ).toBe(0);
  218. const trace = await waitForHookScenarioTrace(
  219. HOOKS_CASE_MARKERS.stopCap,
  220. (records) =>
  221. processHookRecords(records).filter((record) => record.hook_event_name === "Stop").length ===
  222. 4,
  223. "Stop Hook did not execute four boundary checks",
  224. );
  225. assertStopCapTrace(trace);
  226. });
  227. it("HK-UP-01: blocks UserPromptSubmit before the model and isolates async output", async function () {
  228. this.timeout(120000);
  229. await startNewV4Draft();
  230. const prompt = `${HOOKS_CASE_MARKERS.promptBlock}: this prompt must be blocked before the model.`;
  231. await sendV4Prompt(prompt);
  232. await waitForV4TimelineContaining(HOOKS_CASE_MARKERS.promptBlock);
  233. await waitForIdle("Prompt-block Hooks case did not return to idle");
  234. const trace = await waitForHookScenarioTrace(
  235. HOOKS_CASE_MARKERS.promptBlock,
  236. (records) =>
  237. hasHookRecord(records, {
  238. executor: "command-async",
  239. hook_event_name: "UserPromptSubmit",
  240. phase: "completed",
  241. }),
  242. "Async command Hook did not finish after prompt blocking",
  243. );
  244. expect(await countUpstreamRequestsContaining(HOOKS_CASE_MARKERS.promptBlock)).toBe(0);
  245. expect(await countUpstreamRequests({ includes: [HOOKS_CONTEXT.asyncIgnored] })).toBe(0);
  246. expect(
  247. hasHookRecord(trace, {
  248. executor: "process",
  249. hook_event_name: "UserPromptSubmit",
  250. phase: "completed",
  251. }),
  252. ).toBe(true);
  253. expect(
  254. hasHookRecord(trace, {
  255. executor: "command-async",
  256. hook_event_name: "UserPromptSubmit",
  257. phase: "started",
  258. }),
  259. ).toBe(true);
  260. expect(processHookRecords(trace).some((record) => record.hook_event_name === "Stop")).toBe(
  261. false,
  262. );
  263. const readTriggerTestId = () =>
  264. browser.execute(
  265. (marker: string, triggerPrefix: string) => {
  266. const turn = Array.from(document.querySelectorAll<HTMLElement>("[data-turn-id]")).find(
  267. (candidate) => candidate.textContent?.includes(marker),
  268. );
  269. return (
  270. turn
  271. ?.querySelector<HTMLElement>(`[data-testid^="${triggerPrefix}-"]`)
  272. ?.getAttribute("data-testid") ?? null
  273. );
  274. },
  275. HOOKS_CASE_MARKERS.promptBlock,
  276. TID_V4_HOOK_DETAILS_TRIGGER,
  277. );
  278. await browser.waitUntil(async () => (await readTriggerTestId()) !== null, {
  279. timeout: 15000,
  280. timeoutMsg: "Blocked prompt Hook details trigger did not appear",
  281. });
  282. const detailsTriggerTestId = await readTriggerTestId();
  283. if (!detailsTriggerTestId) throw new Error("Missing blocked prompt Hook details trigger");
  284. const hookActionText = await browser.execute((triggerTestId: string) => {
  285. const trigger = document.querySelector<HTMLElement>(`[data-testid="${triggerTestId}"]`);
  286. return trigger?.parentElement?.textContent ?? "";
  287. }, detailsTriggerTestId);
  288. expect(hookActionText).not.toContain(HOOKS_REASON.promptBlock);
  289. await browser.waitUntil(
  290. async () =>
  291. (
  292. await browser.execute((testId: string) => {
  293. return (
  294. document.querySelector<HTMLElement>(`[data-testid="${testId}"]`)?.textContent ?? ""
  295. );
  296. }, TID_CHAT_ERROR_BANNER)
  297. ).includes(`hooks_prompt_block: ${HOOKS_ERROR_DETAIL.promptBlock}`),
  298. {
  299. timeout: 15000,
  300. timeoutMsg: "Blocked prompt Hook reason did not appear in the chat error banner",
  301. },
  302. );
  303. await browser.waitUntil(
  304. async () =>
  305. await browser.execute(
  306. (detailsTestId: string, hookIconTestId: string) =>
  307. Boolean(
  308. document.querySelector(`[data-testid="${detailsTestId}"]`) &&
  309. document.querySelector(`[data-testid="${hookIconTestId}"]`),
  310. ),
  311. TID_CHAT_ERROR_DETAILS_BUTTON,
  312. TID_CHAT_ERROR_HOOK_ICON,
  313. ),
  314. {
  315. timeout: 15000,
  316. timeoutMsg: "Hook block Chat Error details action or icon did not appear",
  317. },
  318. );
  319. await browser.execute((detailsTestId: string) => {
  320. document.querySelector<HTMLElement>(`[data-testid="${detailsTestId}"]`)?.click();
  321. }, TID_CHAT_ERROR_DETAILS_BUTTON);
  322. await browser.waitUntil(
  323. async () =>
  324. await browser.execute(
  325. (errorDetail: string) =>
  326. document.querySelector('[role="dialog"]')?.textContent?.includes(errorDetail) ?? false,
  327. HOOKS_ERROR_DETAIL.promptBlock,
  328. ),
  329. {
  330. timeout: 15000,
  331. timeoutMsg: "Hook block Chat Error details dialog did not show stderr",
  332. },
  333. );
  334. // 截图只作为人工复盘 artifact;通过判定仍依赖上面的稳定 DOM 文本断言。
  335. await mkdir(HOOK_BLOCK_SCREENSHOT_DIR, { recursive: true });
  336. await browser.saveScreenshot(join(HOOK_BLOCK_SCREENSHOT_DIR, "HK-UP-01-chat-error.png"));
  337. });
  338. it("HK-UP-ERR-01: reports a UserPromptSubmit process failure before the model", async function () {
  339. this.timeout(120000);
  340. await startNewV4Draft();
  341. const prompt = `${HOOKS_CASE_MARKERS.promptError}: the hook must fail before the model.`;
  342. await sendV4Prompt(prompt);
  343. await waitForV4TimelineContaining(HOOKS_CASE_MARKERS.promptError);
  344. await waitForV4AssistantMessageContaining("HOOK_PROCESS_FAILURE_REACHED_MODEL");
  345. await waitForIdle("Prompt-error Hooks case did not return to idle");
  346. expect(await countUpstreamRequestsContaining(HOOKS_CASE_MARKERS.promptError)).toBe(1);
  347. let trace: HookTraceRecord[] = [];
  348. await browser.waitUntil(
  349. async () => {
  350. trace = (await readHookTraceRecords()).filter(
  351. (record) =>
  352. typeof record.prompt === "string" &&
  353. record.prompt.includes(HOOKS_CASE_MARKERS.promptError),
  354. );
  355. return hasHookRecord(trace, {
  356. executor: "process",
  357. hook_event_name: "UserPromptSubmit",
  358. phase: "started",
  359. });
  360. },
  361. {
  362. timeout: 30000,
  363. timeoutMsg: "Failing UserPromptSubmit Hook did not start",
  364. },
  365. );
  366. expect(
  367. hasHookRecord(trace, {
  368. executor: "process",
  369. hook_event_name: "UserPromptSubmit",
  370. phase: "completed",
  371. }),
  372. ).toBe(false);
  373. });
  374. it("HK17: keeps the SessionStart summary off a first-action /compact maintenance turn", async function () {
  375. // Bug 根因:Runtime 的 runSessionStartHooks 先于 /compact 输入解析执行;首条
  376. // 输入即 /compact 时 SessionStart Hook 真实执行且事件携带 compact turnId,投影
  377. // 层把摘要挂到了 model-only 维护 turn 上,UI 因此在 compact marker 轮露出
  378. // Hook 图标。回归断言三层:compact 轮无图标、摘要归位下一条真实 turn、真实
  379. // turn 的详情里能看到 SessionStart。
  380. this.timeout(180000);
  381. await startNewV4Draft();
  382. await sendV4Prompt("/compact");
  383. // 新会话历史为空时 manual compact 走 noop(上下文已是最新,无需压缩);
  384. // 维护 turn 语义不变:TurnStarted 仍为 model-only,SessionStart Hook 仍已执行。
  385. await waitForCompactMarkerStatuses(["completed", "skipped"], "manual");
  386. await waitForIdle("Compact-first Hooks case did not return to idle");
  387. // 维护 turn 不渲染 Hook Anchor:compact marker 所在 turn 内没有任何 Hook 入口。
  388. const compactTurnHasHookTrigger = await browser.execute((triggerPrefix: string) => {
  389. const marker = document.querySelector<HTMLElement>(
  390. '[data-row-kind="timelineMarker"][data-marker-type="compact"]',
  391. );
  392. const turn = marker?.closest<HTMLElement>("[data-turn-id]");
  393. return turn != null && turn.querySelector(`[data-testid^="${triggerPrefix}-"]`) !== null;
  394. }, TID_V4_HOOK_DETAILS_TRIGGER);
  395. expect(compactTurnHasHookTrigger).toBe(false);
  396. // 下一条真实 prompt 才承载 SessionStart 摘要。
  397. const followUpMarker = "E2E_HOOKS_COMPACT_FIRST_FOLLOW_UP_OK";
  398. await sendV4Prompt(`Reply with exactly ${followUpMarker} and nothing else.`);
  399. await waitForV4TimelineContaining(followUpMarker);
  400. await waitForIdle("Follow-up prompt did not return to idle");
  401. // 虚拟时间线下用 Hook 入口自身做锚:存在的 Hook trigger 必须落在含 marker 文本
  402. // 的真实 turn,而不是 compact 维护 turn。
  403. const readHookTriggerOwner = () =>
  404. browser.execute(
  405. (marker: string, triggerPrefix: string) => {
  406. const triggers = Array.from(
  407. document.querySelectorAll<HTMLElement>(`[data-testid^="${triggerPrefix}-"]`),
  408. );
  409. const markerTurn = Array.from(
  410. document.querySelectorAll<HTMLElement>("[data-turn-id]"),
  411. ).find((candidate) => candidate.textContent?.includes(marker));
  412. return {
  413. triggerCount: triggers.length,
  414. markerTurnFound: markerTurn != null,
  415. markerTurnHasTrigger:
  416. markerTurn != null &&
  417. markerTurn.querySelector(`[data-testid^="${triggerPrefix}-"]`) !== null,
  418. };
  419. },
  420. followUpMarker,
  421. TID_V4_HOOK_DETAILS_TRIGGER,
  422. );
  423. await browser.waitUntil(
  424. async () => {
  425. const state = await readHookTriggerOwner();
  426. return state.triggerCount >= 1 && state.markerTurnFound && state.markerTurnHasTrigger;
  427. },
  428. {
  429. timeout: 20000,
  430. timeoutMsg: "Follow-up real turn did not own the SessionStart Hook summary",
  431. },
  432. );
  433. await assertHookTurnDetails(followUpMarker, {
  434. // follow-up 是纯文本回复,没有 tool Hook;SessionStart(compact 前后各一次)
  435. // 与 UserPromptSubmit、Stop 才是本 turn 的权威摘要内容。
  436. expectedEvents: ["SessionStart", "UserPromptSubmit", "Stop"],
  437. expectedRowCount: 5,
  438. expectedCountByEvent: { SessionStart: 2, UserPromptSubmit: 2, Stop: 1 },
  439. skipOverflowAssertions: true,
  440. });
  441. });
  442. });
  443. async function assertHooksSettingsPage(): Promise<void> {
  444. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  445. timeout: 15000,
  446. timeoutMsg: "Hooks E2E could not open Settings",
  447. });
  448. await $(sel(TID_SETTINGS_PAGE)).waitForDisplayed({ timeout: 15000 });
  449. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "hooks"), {
  450. timeout: 15000,
  451. timeoutMsg: "Settings did not expose the Hooks section",
  452. });
  453. await $('[data-testid="hooks-settings-section"]').waitForDisplayed({
  454. timeout: 15000,
  455. });
  456. await browser.waitUntil(
  457. async () =>
  458. browser.execute(
  459. () => document.querySelectorAll('[data-testid="configured-hook-row"]').length === 13,
  460. ),
  461. {
  462. timeout: 15000,
  463. timeoutMsg: "Hooks settings did not render all nine configured hooks",
  464. },
  465. );
  466. const settingsText = await $('[data-testid="hooks-settings-section"]').getText();
  467. for (const event of [
  468. "SessionStart",
  469. "UserPromptSubmit",
  470. "PreToolUse",
  471. "PermissionRequest",
  472. "PostToolUse",
  473. "PostToolUseFailure",
  474. "Stop",
  475. ]) {
  476. expect(settingsText).toContain(event);
  477. }
  478. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  479. timeout: 15000,
  480. timeoutMsg: "Hooks settings did not expose the back button",
  481. });
  482. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30000);
  483. }
  484. async function assertHookTurnDetails(
  485. finalAssistantMarker: string,
  486. options: {
  487. expectedEvents?: readonly string[];
  488. expectedRowCount?: number;
  489. expectedCountByEvent?: Readonly<Record<string, number>>;
  490. skipOverflowAssertions?: boolean;
  491. } = {},
  492. ): Promise<void> {
  493. const expectedEvents = options.expectedEvents ?? [
  494. "SessionStart",
  495. "UserPromptSubmit",
  496. "PreToolUse",
  497. ];
  498. const expectedRowCount = options.expectedRowCount ?? 15;
  499. const expectedCountByEvent = options.expectedCountByEvent ?? {
  500. SessionStart: 2,
  501. UserPromptSubmit: 2,
  502. PreToolUse: 4,
  503. };
  504. const readTriggerTestId = () =>
  505. browser.execute(
  506. (marker: string, triggerPrefix: string) => {
  507. const turn = Array.from(document.querySelectorAll<HTMLElement>("[data-turn-id]")).find(
  508. (candidate) => candidate.textContent?.includes(marker),
  509. );
  510. return (
  511. turn
  512. ?.querySelector<HTMLElement>(`[data-testid^="${triggerPrefix}-"]`)
  513. ?.getAttribute("data-testid") ?? null
  514. );
  515. },
  516. finalAssistantMarker,
  517. TID_V4_HOOK_DETAILS_TRIGGER,
  518. );
  519. await browser.waitUntil(async () => (await readTriggerTestId()) !== null, {
  520. timeout: 15000,
  521. timeoutMsg: "Completed full-chain turn did not expose the Hook action",
  522. });
  523. const triggerTestId = await readTriggerTestId();
  524. if (!triggerTestId) throw new Error("Missing full-chain Hook details trigger");
  525. const triggerSelector = `[data-testid="${triggerTestId}"]`;
  526. // 冲突合并曾同时渲染普通 action bar 与 Hook-only 兜底栏;仅取首个入口会漏掉回归。
  527. expect(await $$(triggerSelector).length).toBe(1);
  528. const trigger = await $(triggerSelector);
  529. await trigger.scrollIntoView({ block: "center", inline: "nearest" });
  530. await trigger.moveTo();
  531. await mkdir(HOOK_BLOCK_SCREENSHOT_DIR, { recursive: true });
  532. await browser.saveScreenshot(
  533. join(HOOK_BLOCK_SCREENSHOT_DIR, `${finalAssistantMarker}-single-hook-action.png`),
  534. );
  535. expect(await trigger.getAttribute("aria-label")).toBe("钩子");
  536. await trigger.click();
  537. const detailsSelector = `[data-testid^="${TID_V4_HOOK_DETAILS_CONTENT}-"]`;
  538. const details = await $(detailsSelector);
  539. await details.waitForDisplayed({
  540. timeout: 15000,
  541. timeoutMsg: "Hook action did not open the details Popover",
  542. });
  543. await browser.saveScreenshot(
  544. join(HOOK_BLOCK_SCREENSHOT_DIR, `${finalAssistantMarker}-hook-details.png`),
  545. );
  546. const text = await details.getText();
  547. expect(text).toContain("钩子");
  548. for (const event of expectedEvents) {
  549. expect(text).toContain(event);
  550. }
  551. expect(text).toContain("用户");
  552. expect(text).not.toContain("node");
  553. expect(text).not.toContain(".mjs");
  554. expect(text).not.toContain("Write");
  555. expect(text).not.toContain("Read");
  556. expect(text).not.toContain("×");
  557. expect(text).not.toContain("已完成");
  558. expect(text).toMatch(/\b\d+(?:\.\d+)?(?:ms|s)\b/);
  559. const detailRows = await details.$$("li");
  560. const detailRowTexts = await detailRows.map((row) => row.getText());
  561. expect(detailRowTexts).toHaveLength(expectedRowCount);
  562. for (const [event, count] of Object.entries(expectedCountByEvent)) {
  563. expect(detailRowTexts.filter((row) => row.includes(event))).toHaveLength(count);
  564. }
  565. const listSelector = `${detailsSelector} ul`;
  566. if (options.skipOverflowAssertions === true) {
  567. // 行数不足以溢出(如 HK17 的 5 行摘要)时跳过 HK15 遗留的滚动视觉断言,
  568. // 只保留视口边界检查。
  569. const bounds = await browser.execute((selector) => {
  570. const content = document.querySelector<HTMLElement>(selector);
  571. if (!content) throw new Error("Missing Hook details content");
  572. const rect = content.getBoundingClientRect();
  573. return {
  574. bottom: rect.bottom,
  575. left: rect.left,
  576. right: rect.right,
  577. top: rect.top,
  578. viewportHeight: window.innerHeight,
  579. viewportWidth: window.innerWidth,
  580. };
  581. }, detailsSelector);
  582. expect(bounds.top).toBeGreaterThanOrEqual(8);
  583. expect(bounds.left).toBeGreaterThanOrEqual(8);
  584. expect(bounds.right).toBeLessThanOrEqual(bounds.viewportWidth - 8);
  585. expect(bounds.bottom).toBeLessThanOrEqual(bounds.viewportHeight - 8);
  586. return;
  587. }
  588. const scrollBefore = await browser.execute((selector) => {
  589. const list = document.querySelector<HTMLElement>(selector);
  590. if (!list) throw new Error("Missing Hook details list");
  591. return {
  592. clientHeight: list.clientHeight,
  593. overflowY: getComputedStyle(list).overflowY,
  594. scrollHeight: list.scrollHeight,
  595. };
  596. }, listSelector);
  597. expect(scrollBefore.scrollHeight).toBeGreaterThan(scrollBefore.clientHeight);
  598. expect(scrollBefore.overflowY).toBe("auto");
  599. await browser.execute((selector) => {
  600. const list = document.querySelector<HTMLElement>(selector);
  601. if (!list) throw new Error("Missing Hook details list");
  602. list.scrollTop = list.scrollHeight;
  603. }, listSelector);
  604. await browser.waitUntil(
  605. async () =>
  606. browser.execute((selector) => {
  607. const list = document.querySelector<HTMLElement>(selector);
  608. const last = list?.querySelector<HTMLElement>("li:last-child");
  609. if (!list || !last) return false;
  610. const listRect = list.getBoundingClientRect();
  611. const lastRect = last.getBoundingClientRect();
  612. return lastRect.top >= listRect.top && lastRect.bottom <= listRect.bottom + 1;
  613. }, listSelector),
  614. { timeout: 5000, timeoutMsg: "Hook details list did not reveal its final row after scroll" },
  615. );
  616. const visibleLastRowText = await browser.execute((selector) => {
  617. const list = document.querySelector<HTMLElement>(selector);
  618. return list?.querySelector<HTMLElement>("li:last-child")?.innerText ?? null;
  619. }, listSelector);
  620. expect(visibleLastRowText).toBe(detailRowTexts.at(-1));
  621. const bounds = await browser.execute((selector) => {
  622. const content = document.querySelector<HTMLElement>(selector);
  623. if (!content) throw new Error("Missing Hook details content");
  624. const rect = content.getBoundingClientRect();
  625. return {
  626. bottom: rect.bottom,
  627. left: rect.left,
  628. right: rect.right,
  629. top: rect.top,
  630. viewportHeight: window.innerHeight,
  631. viewportWidth: window.innerWidth,
  632. };
  633. }, detailsSelector);
  634. expect(bounds.top).toBeGreaterThanOrEqual(8);
  635. expect(bounds.left).toBeGreaterThanOrEqual(8);
  636. expect(bounds.right).toBeLessThanOrEqual(bounds.viewportWidth - 8);
  637. expect(bounds.bottom).toBeLessThanOrEqual(bounds.viewportHeight - 8);
  638. }
  639. function assertFullChainTrace(trace: HookTraceRecord[], prompt: string): void {
  640. const processTrace = processHookRecords(trace);
  641. expect(processTrace.map((record) => record.hook_event_name)).toEqual([
  642. "SessionStart",
  643. "UserPromptSubmit",
  644. "PreToolUse",
  645. "PermissionRequest",
  646. "PostToolUse",
  647. "PreToolUse",
  648. "PostToolUseFailure",
  649. "Stop",
  650. ]);
  651. assertClaudeCompatibleTrace(processTrace);
  652. expect(
  653. hasHookRecord(trace, {
  654. executor: "command-sync",
  655. hook_event_name: "SessionStart",
  656. phase: "completed",
  657. }),
  658. ).toBe(true);
  659. expect(
  660. hasHookRecord(trace, {
  661. executor: "command-async",
  662. hook_event_name: "UserPromptSubmit",
  663. phase: "started",
  664. }),
  665. ).toBe(true);
  666. const session = findHookEvent(processTrace, "SessionStart");
  667. expect(session).toMatchObject({
  668. model: expect.any(String),
  669. source: "startup",
  670. });
  671. const userPrompt = findHookEvent(processTrace, "UserPromptSubmit");
  672. expect(userPrompt).toMatchObject({ prompt });
  673. expect(userPrompt.transcript_text).toContain(prompt);
  674. const preWrite = findToolHook(processTrace, "PreToolUse", HOOKS_TOOL_CALL_IDS.fullWrite);
  675. const permission = findToolHook(processTrace, "PermissionRequest", HOOKS_TOOL_CALL_IDS.fullWrite);
  676. const post = findToolHook(processTrace, "PostToolUse", HOOKS_TOOL_CALL_IDS.fullWrite);
  677. expect(preWrite.tool_input).toMatchObject({
  678. file_path: HOOKS_RELATIVE_PATHS.fullOriginal,
  679. });
  680. expect(permission.tool_input).toMatchObject({
  681. file_path: HOOKS_RELATIVE_PATHS.fullPreModified,
  682. content: "pretool modified content\n",
  683. });
  684. expect(post.tool_input).toMatchObject({
  685. file_path: HOOKS_RELATIVE_PATHS.fullFinal,
  686. content: "permission modified content\n",
  687. });
  688. expect(post.tool_response).toEqual(post.toolResponse);
  689. expect(post.tool_response).toEqual(expect.any(Object));
  690. expect(Object.prototype.hasOwnProperty.call(permission, "permission_suggestions")).toBe(false);
  691. const failure = findToolHook(processTrace, "PostToolUseFailure", HOOKS_TOOL_CALL_IDS.fullRead);
  692. expect(failure.error).toEqual(expect.any(String));
  693. expect(failure.error_details).toEqual(expect.any(Object));
  694. expect(failure.is_interrupt).toBe(false);
  695. const stop = findHookEvent(processTrace, "Stop");
  696. expect(stop).toMatchObject({
  697. last_assistant_message: HOOKS_FINAL_MARKERS.fullChain,
  698. stop_hook_active: false,
  699. });
  700. expect(stop.transcript_text).toContain(HOOKS_FINAL_MARKERS.fullChain);
  701. }
  702. function assertEarlyFailureTrace(trace: HookTraceRecord[]): void {
  703. const processTrace = processHookRecords(trace);
  704. expect(processTrace.map((record) => record.hook_event_name)).toEqual([
  705. "SessionStart",
  706. "UserPromptSubmit",
  707. "PreToolUse",
  708. "PreToolUse",
  709. "PreToolUse",
  710. "PermissionRequest",
  711. "Stop",
  712. ]);
  713. assertClaudeCompatibleTrace(processTrace);
  714. expect(
  715. processTrace.filter((record) => record.hook_event_name === "PermissionRequest"),
  716. ).toHaveLength(1);
  717. expect(
  718. findToolHook(processTrace, "PermissionRequest", HOOKS_TOOL_CALL_IDS.earlyPermissionDeny)
  719. .tool_input,
  720. ).toMatchObject({ file_path: HOOKS_RELATIVE_PATHS.earlyPermissionDeny });
  721. expect(
  722. processTrace.some(
  723. (record) =>
  724. record.hook_event_name === "PostToolUse" || record.hook_event_name === "PostToolUseFailure",
  725. ),
  726. ).toBe(false);
  727. }
  728. function assertStopCapTrace(trace: HookTraceRecord[]): void {
  729. const processTrace = processHookRecords(trace);
  730. assertClaudeCompatibleTrace(processTrace);
  731. const stopRecords = processTrace.filter((record) => record.hook_event_name === "Stop");
  732. expect(stopRecords).toHaveLength(4);
  733. expect(stopRecords.map((record) => record.stop_hook_active)).toEqual([false, true, true, true]);
  734. expect(stopRecords.map((record) => record.last_assistant_message)).toEqual([
  735. STOP_STEP(0),
  736. STOP_STEP(1),
  737. STOP_STEP(2),
  738. STOP_STEP(3),
  739. ]);
  740. for (const [index, record] of stopRecords.entries()) {
  741. expect(record.transcript_text).toContain(STOP_STEP(index));
  742. }
  743. }
  744. function assertClaudeCompatibleTrace(records: HookTraceRecord[]): void {
  745. for (const record of records) {
  746. expect(record).toMatchObject({
  747. cwd: DEFAULT_WORKSPACE,
  748. hookEventName: expect.any(String),
  749. hook_event_name: expect.any(String),
  750. mode: expect.any(String),
  751. permission_mode: expect.any(String),
  752. sessionId: expect.any(String),
  753. session_id: expect.any(String),
  754. transcriptPath: expect.any(String),
  755. transcript_path: expect.any(String),
  756. transcript_readable: true,
  757. transcript_text: expect.any(String),
  758. });
  759. expect(record.hook_event_name).toBe(record.hookEventName);
  760. expect(record.permission_mode).toBe(record.mode);
  761. expect(record.session_id).toBe(record.sessionId);
  762. expect(record.transcript_path).toBe(record.transcriptPath);
  763. if ("toolName" in record) {
  764. expect(record.tool_name).toBe(record.toolName);
  765. expect(record.tool_input).toEqual(record.toolInput);
  766. expect(record.tool_use_id).toBe(record.toolCallId);
  767. }
  768. }
  769. }
  770. function findToolHook(
  771. records: HookTraceRecord[],
  772. event: string,
  773. toolCallId: string,
  774. ): HookTraceRecord {
  775. const record = records.find(
  776. (item) => item.hook_event_name === event && item.tool_use_id === toolCallId,
  777. );
  778. if (!record) throw new Error(`Missing ${event} hook for ${toolCallId}`);
  779. return record;
  780. }
  781. async function waitForIdle(timeoutMsg: string): Promise<void> {
  782. await waitForV4Pane(
  783. (snapshot) =>
  784. snapshot.sessionId !== null && snapshot.sessionId !== "draft" && !snapshot.canStop,
  785. timeoutMsg,
  786. 60000,
  787. );
  788. }
  789. async function waitForEmptyV4Composer(timeoutMsg: string): Promise<void> {
  790. try {
  791. await browser.waitUntil(async () => (await getV4ComposerText()) === "", {
  792. // 该 fixture 的单个 Hook 自身允许 10 秒;不能用同样的总时限判定跨进程 admission 失败。
  793. // 仍等待真实清空,不 sleep,也不在超时后替产品清除文本。
  794. timeout: 60000,
  795. timeoutMsg,
  796. });
  797. } catch (error) {
  798. // 首发失败不是 Hook 失败;附上产品错误详情,避免只记录“草稿未清空”掩盖前置错误。
  799. const details = await $(sel(TID_CHAT_ERROR_DETAILS_BUTTON));
  800. if (await details.isExisting()) {
  801. await details.click();
  802. await browser.waitUntil(async () => Boolean(await $("[role='dialog'] pre").getText()), {
  803. timeout: 3000,
  804. });
  805. const content = await $("[role='dialog'] pre").getText();
  806. throw new Error(`${timeoutMsg}; send error: ${content}`, { cause: error });
  807. }
  808. const text = await getV4ComposerText();
  809. throw new Error(`${timeoutMsg}; composer=${JSON.stringify(text)}`, { cause: error });
  810. }
  811. }
  812. async function expectMissingPath(relativePath: string): Promise<void> {
  813. await expect(readFile(workspacePath(relativePath), "utf8")).rejects.toMatchObject({
  814. code: "ENOENT",
  815. });
  816. }
  817. function workspacePath(relativePath: string): string {
  818. return join(DEFAULT_WORKSPACE, relativePath);
  819. }