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

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