hook-runner-lifecycle.test.ts 13 KB

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