hook-runner-lifecycle.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. HookEventName,
  4. HookOutcome,
  5. SessionEventType,
  6. createSessionId,
  7. createTraceId,
  8. createTurnId,
  9. type ExecutionPort,
  10. type HookExecutionDescriptor,
  11. type HookRunLifecyclePayload,
  12. type SessionEvent,
  13. } from "@zcode/contracts";
  14. import {
  15. createConfiguredHookRunner,
  16. createInMemoryHookRunner,
  17. sanitizeHookDisplayText,
  18. } from "../src/hooks/index.js";
  19. import { resolveHookTimeoutMs } from "../src/hooks/configured-runner-input.js";
  20. const visibleDescriptor: HookExecutionDescriptor = {
  21. clientVisible: true,
  22. commandDisplay: "hook-command",
  23. executionMode: "foreground",
  24. executionType: "process",
  25. sourceKind: "user",
  26. sourcePath: "/Users/example/.zcode/cli/config.json",
  27. timeoutMs: 60_000,
  28. };
  29. function promptInput() {
  30. return {
  31. cwd: "/workspace",
  32. hookEventName: HookEventName.UserPromptSubmit,
  33. mode: "build" as const,
  34. prompt: "hello",
  35. sessionId: createSessionId("hook-lifecycle"),
  36. timestamp: new Date().toISOString(),
  37. traceId: createTraceId(),
  38. turnId: createTurnId("turn-1"),
  39. };
  40. }
  41. function lifecyclePayload(event: SessionEvent | undefined): HookRunLifecyclePayload | undefined {
  42. return event?.payload as HookRunLifecyclePayload | undefined;
  43. }
  44. describe("Hook runner lifecycle", () => {
  45. it("groups visible hooks under one invocation with one terminal event per execution", async () => {
  46. const events: SessionEvent[] = [];
  47. const runner = createInMemoryHookRunner({
  48. emitEvent: async (event) => {
  49. events.push(event);
  50. },
  51. hooks: [
  52. {
  53. callback: async () => undefined,
  54. descriptor: visibleDescriptor,
  55. event: HookEventName.UserPromptSubmit,
  56. },
  57. {
  58. callback: async () => ({ continue: false, reason: "blocked" }),
  59. descriptor: visibleDescriptor,
  60. event: HookEventName.UserPromptSubmit,
  61. },
  62. ],
  63. });
  64. await runner.run(promptInput());
  65. expect(events.map((event) => event.type)).toEqual([
  66. SessionEventType.HookRunStarted,
  67. SessionEventType.HookRunCompleted,
  68. SessionEventType.HookRunStarted,
  69. SessionEventType.HookRunBlocked,
  70. ]);
  71. expect(new Set(events.map((event) => lifecyclePayload(event)?.hookInvocationId)).size).toBe(1);
  72. expect(events.map((event) => lifecyclePayload(event)?.hookCount)).toEqual([2, 2, 2, 2]);
  73. expect(events.map((event) => lifecyclePayload(event)?.hookIndex)).toEqual([0, 0, 1, 1]);
  74. expect(events.filter((event) => event.type === SessionEventType.HookRunBlocked)).toHaveLength(
  75. 1,
  76. );
  77. expect(
  78. lifecyclePayload(events.find((event) => event.type === SessionEventType.HookRunBlocked))
  79. ?.blockReason,
  80. ).toBe("blocked");
  81. });
  82. it("distinguishes timeout and cancellation and continues after a failed hook", async () => {
  83. const events: SessionEvent[] = [];
  84. let laterHookRan = false;
  85. const runner = createInMemoryHookRunner({
  86. emitEvent: async (event) => {
  87. events.push(event);
  88. },
  89. hooks: [
  90. {
  91. callback: () => new Promise<never>(() => {}),
  92. descriptor: { ...visibleDescriptor, timeoutMs: 1 },
  93. event: HookEventName.UserPromptSubmit,
  94. timeoutMs: 1,
  95. },
  96. {
  97. callback: async () => {
  98. laterHookRan = true;
  99. },
  100. descriptor: visibleDescriptor,
  101. event: HookEventName.UserPromptSubmit,
  102. },
  103. ],
  104. });
  105. await runner.run(promptInput());
  106. expect(laterHookRan).toBe(true);
  107. const timedOut = events.find(
  108. (event) =>
  109. event.type === SessionEventType.HookRunFailed && lifecyclePayload(event)?.hookIndex === 0,
  110. );
  111. expect(lifecyclePayload(timedOut)?.outcome).toBe(HookOutcome.TimedOut);
  112. expect(
  113. events.filter(
  114. (event) =>
  115. lifecyclePayload(event)?.hookIndex === 0 &&
  116. (event.type === SessionEventType.HookRunCompleted ||
  117. event.type === SessionEventType.HookRunFailed ||
  118. event.type === SessionEventType.HookRunBlocked),
  119. ),
  120. ).toHaveLength(1);
  121. const cancelledEvents: SessionEvent[] = [];
  122. const controller = new AbortController();
  123. controller.abort("user cancelled");
  124. const cancelledRunner = createInMemoryHookRunner({
  125. emitEvent: async (event) => {
  126. cancelledEvents.push(event);
  127. },
  128. hooks: [
  129. {
  130. callback: async () => undefined,
  131. descriptor: visibleDescriptor,
  132. event: HookEventName.UserPromptSubmit,
  133. },
  134. ],
  135. });
  136. await cancelledRunner.run(promptInput(), { signal: controller.signal });
  137. expect(
  138. lifecyclePayload(
  139. cancelledEvents.find((event) => event.type === SessionEventType.HookRunFailed),
  140. )?.outcome,
  141. ).toBe(HookOutcome.Cancelled);
  142. });
  143. it("returns immediately for async hooks and emits their terminal lifecycle later", async () => {
  144. const events: SessionEvent[] = [];
  145. let release: (() => void) | undefined;
  146. const runner = createInMemoryHookRunner({
  147. emitEvent: async (event) => {
  148. events.push(event);
  149. },
  150. hooks: [
  151. {
  152. async: true,
  153. callback: () =>
  154. new Promise<void>((resolve) => {
  155. release = resolve;
  156. }),
  157. descriptor: { ...visibleDescriptor, executionMode: "background" },
  158. event: HookEventName.UserPromptSubmit,
  159. },
  160. ],
  161. });
  162. await runner.run(promptInput());
  163. expect(events.map((event) => event.type)).toEqual([SessionEventType.HookRunStarted]);
  164. release?.();
  165. await vi.waitFor(() => {
  166. expect(events.map((event) => event.type)).toEqual([
  167. SessionEventType.HookRunStarted,
  168. SessionEventType.HookRunCompleted,
  169. ]);
  170. });
  171. });
  172. it.each([
  173. {
  174. label: "per-hook timeoutMs",
  175. hook: { type: "process" as const, command: "hook", timeoutMs: 1_000.6 },
  176. defaultTimeoutMs: 60_000,
  177. expected: 1_001,
  178. },
  179. {
  180. label: "command timeout seconds",
  181. hook: { type: "command" as const, command: "hook", timeout: 1.0006 },
  182. defaultTimeoutMs: 60_000,
  183. expected: 1_001,
  184. },
  185. {
  186. label: "default timeoutMs",
  187. hook: { type: "process" as const, command: "hook" },
  188. defaultTimeoutMs: 60_000.6,
  189. expected: 60_001,
  190. },
  191. {
  192. label: "sub-millisecond timeout",
  193. hook: { type: "process" as const, command: "hook", timeoutMs: 0.4 },
  194. defaultTimeoutMs: 60_000,
  195. expected: 1,
  196. },
  197. ])(
  198. "normalizes fractional $label to positive integer milliseconds",
  199. ({ hook, defaultTimeoutMs, expected }) => {
  200. expect(resolveHookTimeoutMs(hook, defaultTimeoutMs)).toBe(expected);
  201. },
  202. );
  203. it("emits actual configured path, protocol, timeout, and redacted full command", async () => {
  204. const events: SessionEvent[] = [];
  205. const now = new Date();
  206. const executionPort: ExecutionPort = {
  207. async run() {
  208. return {
  209. status: "completed",
  210. exitCode: 0,
  211. stdout: { text: "", bytes: 0, truncated: false },
  212. stderr: { text: "", bytes: 0, truncated: false },
  213. durationMs: 2,
  214. timedOut: false,
  215. cancelled: false,
  216. startedAt: now,
  217. completedAt: now,
  218. };
  219. },
  220. };
  221. const runner = createConfiguredHookRunner({
  222. config: {
  223. enabled: true,
  224. events: {
  225. UserPromptSubmit: [
  226. {
  227. hooks: [
  228. {
  229. type: "process",
  230. command: "${ZCODE_PLUGIN_ROOT}/hooks/check.mjs",
  231. args: ["--token", "secret-value"],
  232. timeoutMs: 5_000,
  233. statusMessage: "Checking policy",
  234. plugin: {
  235. dataPath: "/tmp/plugin-data",
  236. id: "policy@example",
  237. name: "Policy",
  238. rootPath: "/tmp/policy-plugin",
  239. sourcePath: "/tmp/policy-plugin/hooks/hooks.json",
  240. },
  241. },
  242. ],
  243. },
  244. ],
  245. },
  246. maxOutputBytes: 1_024,
  247. timeoutMs: 60_000,
  248. },
  249. emitEvent: async (event) => {
  250. events.push(event);
  251. },
  252. executionPort,
  253. getWorkingDirectory: () => "/workspace",
  254. });
  255. await runner?.run(promptInput());
  256. expect(lifecyclePayload(events[0])?.descriptor).toMatchObject({
  257. clientVisible: true,
  258. commandDisplay: "/tmp/policy-plugin/hooks/check.mjs --token ••••",
  259. executionType: "process",
  260. pluginId: "policy@example",
  261. pluginName: "Policy",
  262. sourceKind: "plugin",
  263. sourcePath: "/tmp/policy-plugin/hooks/hooks.json",
  264. statusMessage: "Checking policy",
  265. timeoutMs: 5_000,
  266. });
  267. });
  268. it("carries stderr diagnostics when a configured hook returns a generic block reason", async () => {
  269. const events: SessionEvent[] = [];
  270. const now = new Date();
  271. const stderr =
  272. "python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory";
  273. const executionPort: ExecutionPort = {
  274. async run() {
  275. return {
  276. status: "completed",
  277. exitCode: 0,
  278. stdout: {
  279. text: JSON.stringify({
  280. continue: false,
  281. reason: "hooks_prompt_block",
  282. hookSpecificOutput: { hookEventName: "UserPromptSubmit" },
  283. }),
  284. bytes: 100,
  285. truncated: false,
  286. },
  287. stderr: { text: stderr, bytes: stderr.length, truncated: false },
  288. durationMs: 2,
  289. timedOut: false,
  290. cancelled: false,
  291. startedAt: now,
  292. completedAt: now,
  293. };
  294. },
  295. };
  296. const runner = createConfiguredHookRunner({
  297. config: {
  298. enabled: true,
  299. events: {
  300. UserPromptSubmit: [{ hooks: [{ type: "process", command: "python3" }] }],
  301. },
  302. maxOutputBytes: 1_024,
  303. timeoutMs: 5_000,
  304. },
  305. emitEvent: async (event) => {
  306. events.push(event);
  307. },
  308. executionPort,
  309. getWorkingDirectory: () => "/workspace",
  310. });
  311. const result = await runner?.run(promptInput());
  312. const blocked = events.find((event) => event.type === SessionEventType.HookRunBlocked);
  313. expect(result?.stopReason).toBe("hooks_prompt_block");
  314. expect(lifecyclePayload(blocked)).toMatchObject({
  315. blockReason: "hooks_prompt_block",
  316. errorMessage: stderr,
  317. stderrPreview: stderr,
  318. });
  319. });
  320. it("redacts common credential forms before persistence", () => {
  321. expect(
  322. sanitizeHookDisplayText(
  323. "curl https://kevin:secret@example.com?api_key=abc --token xyz password=hunter2",
  324. ),
  325. ).toBe("curl https://••••:••••@example.com?api_key=•••• --token •••• password=••••");
  326. expect(sanitizeHookDisplayText("Authorization: Bearer secret-token")).toBe(
  327. "Authorization: Bearer ••••",
  328. );
  329. expect(
  330. sanitizeHookDisplayText(
  331. 'curl -H "Authorization: Bearer secret-token" "https://example.com?api_key=abc" "password=hunter2"',
  332. ),
  333. ).toBe(
  334. 'curl -H "Authorization: Bearer ••••" "https://example.com?api_key=••••" "password=••••"',
  335. );
  336. expect(sanitizeHookDisplayText("GITHUB_TOKEN=abc FOO_GITHUB_TOKEN=def")).toBe(
  337. "GITHUB_TOKEN=•••• FOO_GITHUB_TOKEN=••••",
  338. );
  339. expect(sanitizeHookDisplayText("postgres://user:pass@host/db")).toBe(
  340. "postgres://••••:••••@host/db",
  341. );
  342. expect(sanitizeHookDisplayText('{"password":"secret","api_key":"abc"}')).toBe(
  343. '{"password":••••,"api_key":••••}',
  344. );
  345. });
  346. // Bug 修复回归(H1):admission 返回 skipLifecycle 的 hook 不发任何事件,
  347. // 但 clientVisibleHookCount 之前包含了它们 → 投影层 executions.length < hookCount
  348. // 永远为 true → hookInvocation row 卡在 running,UI 计时器永不停止。
  349. // 修复:先解析全部 matchingHooks 的 admission,把 skipLifecycle 的从参与列表
  350. // 剔除后再计算 clientVisibleHookCount。
  351. it("excludes skipLifecycle admission hooks from hookCount and emits no events for them", async () => {
  352. const events: SessionEvent[] = [];
  353. const runner = createInMemoryHookRunner({
  354. emitEvent: async (event) => {
  355. events.push(event);
  356. },
  357. hooks: [
  358. {
  359. // configured-disabled → admission skipLifecycle → 完全不可见
  360. admission: () => ({
  361. allowed: false,
  362. reasonCode: "workspace_hooks_feature_disabled",
  363. skipLifecycle: true,
  364. }),
  365. callback: async () => undefined,
  366. descriptor: visibleDescriptor,
  367. event: HookEventName.UserPromptSubmit,
  368. },
  369. {
  370. // pending → admission blocked 但参与生命周期
  371. admission: () => ({
  372. allowed: false,
  373. reasonCode: "workspace_hooks_pending_trust",
  374. }),
  375. callback: async () => undefined,
  376. descriptor: visibleDescriptor,
  377. event: HookEventName.UserPromptSubmit,
  378. },
  379. ],
  380. });
  381. await runner.run(promptInput());
  382. // skipLifecycle hook 不发任何事件
  383. expect(events.map((event) => event.type)).toEqual([SessionEventType.HookRunBlocked]);
  384. // hookCount 必须是 1(不是 2),否则投影层会等一个永远不来的 execution
  385. expect(lifecyclePayload(events[0])?.hookCount).toBe(1);
  386. expect(lifecyclePayload(events[0])?.hookIndex).toBe(0);
  387. expect(lifecyclePayload(events[0])?.errorCode).toBe("workspace_hooks_pending_trust");
  388. });
  389. });