hook-runner-lifecycle.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. // 带空格的值:参数先逐个加引号再脱敏,整段遮住,不会只遮第一个词。
  229. args: ["--token", "secret value"],
  230. timeoutMs: 5_000,
  231. statusMessage: "Checking policy",
  232. plugin: {
  233. dataPath: "/tmp/plugin-data",
  234. id: "policy@example",
  235. name: "Policy",
  236. rootPath: "/tmp/policy-plugin",
  237. sourcePath: "/tmp/policy-plugin/hooks/hooks.json",
  238. },
  239. },
  240. ],
  241. },
  242. ],
  243. },
  244. maxOutputBytes: 1_024,
  245. timeoutMs: 60_000,
  246. },
  247. emitEvent: async (event) => {
  248. events.push(event);
  249. },
  250. executionPort,
  251. getWorkingDirectory: () => "/workspace",
  252. });
  253. await runner?.run(promptInput());
  254. expect(lifecyclePayload(events[0])?.descriptor).toMatchObject({
  255. clientVisible: true,
  256. commandDisplay: "/tmp/policy-plugin/hooks/check.mjs --token ••••",
  257. executionType: "process",
  258. pluginId: "policy@example",
  259. pluginName: "Policy",
  260. sourceKind: "plugin",
  261. sourcePath: "/tmp/policy-plugin/hooks/hooks.json",
  262. statusMessage: "Checking policy",
  263. timeoutMs: 5_000,
  264. });
  265. });
  266. it("carries stderr diagnostics when a configured hook returns a generic block reason", async () => {
  267. const events: SessionEvent[] = [];
  268. const now = new Date();
  269. const stderr =
  270. "python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory";
  271. const executionPort: ExecutionPort = {
  272. async run() {
  273. return {
  274. status: "completed",
  275. exitCode: 0,
  276. stdout: {
  277. text: JSON.stringify({
  278. continue: false,
  279. reason: "hooks_prompt_block",
  280. hookSpecificOutput: { hookEventName: "UserPromptSubmit" },
  281. }),
  282. bytes: 100,
  283. truncated: false,
  284. },
  285. stderr: { text: stderr, bytes: stderr.length, truncated: false },
  286. durationMs: 2,
  287. timedOut: false,
  288. cancelled: false,
  289. startedAt: now,
  290. completedAt: now,
  291. };
  292. },
  293. };
  294. const runner = createConfiguredHookRunner({
  295. config: {
  296. enabled: true,
  297. events: {
  298. UserPromptSubmit: [{ hooks: [{ type: "process", command: "python3" }] }],
  299. },
  300. maxOutputBytes: 1_024,
  301. timeoutMs: 5_000,
  302. },
  303. emitEvent: async (event) => {
  304. events.push(event);
  305. },
  306. executionPort,
  307. getWorkingDirectory: () => "/workspace",
  308. });
  309. const result = await runner?.run(promptInput());
  310. const blocked = events.find((event) => event.type === SessionEventType.HookRunBlocked);
  311. expect(result?.stopReason).toBe("hooks_prompt_block");
  312. expect(lifecyclePayload(blocked)).toMatchObject({
  313. blockReason: "hooks_prompt_block",
  314. errorMessage: stderr,
  315. stderrPreview: stderr,
  316. });
  317. });
  318. it("redacts common credential forms before persistence", () => {
  319. expect(
  320. sanitizeHookDisplayText(
  321. "curl https://kevin:secret@example.com?api_key=abc --token xyz password=hunter2",
  322. ),
  323. ).toBe("curl https://••••:••••@example.com?api_key=•••• --token •••• password=••••");
  324. expect(sanitizeHookDisplayText("Authorization: Bearer secret-token")).toBe(
  325. "Authorization: Bearer ••••",
  326. );
  327. expect(
  328. sanitizeHookDisplayText(
  329. 'curl -H "Authorization: Bearer secret-token" "https://example.com?api_key=abc" "password=hunter2"',
  330. ),
  331. ).toBe(
  332. 'curl -H "Authorization: Bearer ••••" "https://example.com?api_key=••••" "password=••••"',
  333. );
  334. expect(sanitizeHookDisplayText("GITHUB_TOKEN=abc FOO_GITHUB_TOKEN=def")).toBe(
  335. "GITHUB_TOKEN=•••• FOO_GITHUB_TOKEN=••••",
  336. );
  337. expect(sanitizeHookDisplayText("postgres://user:pass@host/db")).toBe(
  338. "postgres://••••:••••@host/db",
  339. );
  340. expect(sanitizeHookDisplayText('{"password":"secret","api_key":"abc"}')).toBe(
  341. '{"password":••••,"api_key":••••}',
  342. );
  343. });
  344. // Bug 修复回归(H1):admission 返回 skipLifecycle 的 hook 不发任何事件,
  345. // 但 clientVisibleHookCount 之前包含了它们 → 投影层 executions.length < hookCount
  346. // 永远为 true → hookInvocation row 卡在 running,UI 计时器永不停止。
  347. // 修复:先解析全部 matchingHooks 的 admission,把 skipLifecycle 的从参与列表
  348. // 剔除后再计算 clientVisibleHookCount。
  349. it("excludes skipLifecycle admission hooks from hookCount and emits no events for them", async () => {
  350. const events: SessionEvent[] = [];
  351. const runner = createInMemoryHookRunner({
  352. emitEvent: async (event) => {
  353. events.push(event);
  354. },
  355. hooks: [
  356. {
  357. // configured-disabled → admission skipLifecycle → 完全不可见
  358. admission: () => ({
  359. allowed: false,
  360. reasonCode: "workspace_hooks_feature_disabled",
  361. skipLifecycle: true,
  362. }),
  363. callback: async () => undefined,
  364. descriptor: visibleDescriptor,
  365. event: HookEventName.UserPromptSubmit,
  366. },
  367. {
  368. // pending → admission blocked 但参与生命周期
  369. admission: () => ({
  370. allowed: false,
  371. reasonCode: "workspace_hooks_pending_trust",
  372. }),
  373. callback: async () => undefined,
  374. descriptor: visibleDescriptor,
  375. event: HookEventName.UserPromptSubmit,
  376. },
  377. ],
  378. });
  379. await runner.run(promptInput());
  380. // skipLifecycle hook 不发任何事件
  381. expect(events.map((event) => event.type)).toEqual([SessionEventType.HookRunBlocked]);
  382. // hookCount 必须是 1(不是 2),否则投影层会等一个永远不来的 execution
  383. expect(lifecyclePayload(events[0])?.hookCount).toBe(1);
  384. expect(lifecyclePayload(events[0])?.hookIndex).toBe(0);
  385. expect(lifecyclePayload(events[0])?.errorCode).toBe("workspace_hooks_pending_trust");
  386. });
  387. });