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

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