guarded-interaction-lifecycle.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. CoreErrorType,
  4. createSessionId,
  5. createToolCallId,
  6. SessionEventType,
  7. type ExecutionRequest,
  8. type PermissionBrokerResult,
  9. type SessionEvent,
  10. } from "@zcode/contracts";
  11. import { zcodePermissionResponseSchema } from "@zcode/shared";
  12. import {
  13. createToolExecutor,
  14. createToolRegistry,
  15. registerBuiltInTools,
  16. PermissionService,
  17. } from "@zcode/core";
  18. import { ProductProjection } from "../src/zcode-protocol-v4/index.js";
  19. import { V4InteractionRegistry } from "../src/zcode-protocol-v4/interaction-registry.js";
  20. import { V4CommandExecutor } from "../src/zcode-protocol-v4/commands/executor.js";
  21. import { createProtocolInteractionBroker } from "../src/zcode-protocol/interaction-broker.js";
  22. import {
  23. ProtocolRequestError,
  24. type ZCodeProtocolAgentServerContext,
  25. } from "../src/zcode-protocol/server-types.js";
  26. const QUESTION = "Which color?";
  27. const questionInput = {
  28. questions: [
  29. {
  30. header: "Color",
  31. question: QUESTION,
  32. options: [
  33. { label: "Blue", description: "Use blue" },
  34. { label: "Red", description: "Use red" },
  35. ],
  36. },
  37. ],
  38. };
  39. function harness(
  40. options: {
  41. onVisible?: (id: string, registry: V4InteractionRegistry) => void;
  42. clientError?: number;
  43. clientResponse?: () => PermissionBrokerResult;
  44. } = {},
  45. ) {
  46. const sessionId = createSessionId("guarded-wire");
  47. const interactions = new V4InteractionRegistry();
  48. const projection = new ProductProjection(sessionId, "epoch");
  49. const events: SessionEvent[] = [];
  50. const requests: Array<{ requestId: string; toolName: string }> = [];
  51. const execution = vi.fn(async (_request: ExecutionRequest) => ({
  52. status: "completed" as const,
  53. exitCode: 0,
  54. stdout: { text: "controlled execution", bytes: 20, truncated: false },
  55. stderr: { text: "", bytes: 0, truncated: false },
  56. durationMs: 1,
  57. timedOut: false,
  58. cancelled: false,
  59. startedAt: new Date(),
  60. completedAt: new Date(),
  61. }));
  62. const registry = createToolRegistry();
  63. registerBuiltInTools(registry);
  64. const saveProjectPermission = vi.fn();
  65. const context = {
  66. v4Interactions: interactions,
  67. // 真正的 broker 在问答登记前读取持久化元数据;测试保留这个异步边界。
  68. deps: { sessionStore: { sessionEntries: async () => [] } },
  69. requestClient: (
  70. _method: string,
  71. request: { requestId: string; toolName: string },
  72. _schema: unknown,
  73. callOptions: { signal?: AbortSignal },
  74. ) => {
  75. requests.push(request);
  76. if (options.clientError)
  77. return Promise.reject(new ProtocolRequestError(options.clientError, "protocol failure"));
  78. if (options.clientResponse)
  79. return Promise.resolve(zcodePermissionResponseSchema.parse(options.clientResponse()));
  80. return new Promise((_, reject) => {
  81. const abort = () => reject(new ProtocolRequestError(-32021, "client request cancelled"));
  82. if (callOptions.signal?.aborted) abort();
  83. else callOptions.signal?.addEventListener("abort", abort, { once: true });
  84. });
  85. },
  86. } as unknown as ZCodeProtocolAgentServerContext;
  87. const executor = createToolExecutor({
  88. mode: "guarded",
  89. workingDirectory: process.cwd(),
  90. sessionId,
  91. registry,
  92. permissionService: new PermissionService(),
  93. bashShellSelection: { dialect: "posix", source: "auto-detected", display: { name: "bash" } },
  94. executionPort: { run: execution },
  95. permissionBroker: createProtocolInteractionBroker(context),
  96. sessionStore: {
  97. getSession: async () => ({ projectID: "fixture-project" }),
  98. getProjectPermission: async () => ({ allow: [{ toolName: "Bash" }] }),
  99. saveProjectPermission,
  100. } as never,
  101. emitEvent: async (event) => {
  102. events.push(event);
  103. projection.applyEvent({ ...event, sequenceNumber: events.length } as SessionEvent);
  104. if (event.type === SessionEventType.PermissionRequested)
  105. options.onVisible?.(event.payload.requestId!, interactions);
  106. },
  107. });
  108. const commands = new V4CommandExecutor({ getRecord: () => undefined, interactions });
  109. const answer = (
  110. id: string,
  111. value: {
  112. optionId?: string;
  113. freeText?: string;
  114. action?: "accept" | "decline" | "cancel";
  115. content?: Record<string, unknown>;
  116. },
  117. ) =>
  118. commands.execute({
  119. type: "resolveInteraction",
  120. payload: { interactionId: id, answer: value },
  121. sessionId,
  122. commandId: crypto.randomUUID(),
  123. clientId: "client",
  124. issuedAt: Date.now(),
  125. });
  126. const run = (
  127. name = "Bash",
  128. input: unknown = { command: "rm -rf fixture" },
  129. signal?: AbortSignal,
  130. ) => executor.execute({ id: createToolCallId("guarded-wire-tool"), name, input }, { signal });
  131. return {
  132. run,
  133. answer,
  134. interactions,
  135. projection,
  136. events,
  137. requests,
  138. execution,
  139. saveProjectPermission,
  140. };
  141. }
  142. afterEach(() => vi.useRealTimers());
  143. describe("Guarded real executor → protocol broker → V4 command → result", () => {
  144. it.each(["allow", "modify"] as const)(
  145. "a client %s with modified input closes one request and executes the approved command",
  146. async (decision) => {
  147. const command = "git reset --hard";
  148. let responses = 0;
  149. const h = harness({
  150. clientResponse: () =>
  151. ++responses === 1
  152. ? { decision, modifiedInput: { command } }
  153. : { decision: "deny", reason: "Unexpected reapproval" },
  154. });
  155. const result = await h.run();
  156. expect(result.success, JSON.stringify(result)).toBe(true);
  157. expect(result.modelContent).toContain("controlled execution");
  158. expect(h.requests).toHaveLength(1);
  159. expect(h.execution).toHaveBeenCalledTimes(1);
  160. expect(h.execution.mock.calls[0]?.[0]).toMatchObject({ command: { mode: "shell", command } });
  161. expect(
  162. h.events.filter((event) => event.type === SessionEventType.PermissionResolved),
  163. ).toHaveLength(1);
  164. expect(
  165. h.events.filter((event) => event.type === SessionEventType.ToolCallResult),
  166. ).toHaveLength(1);
  167. expect(h.interactions.has(h.requests[0]!.requestId)).toBe(false);
  168. expect(h.projection.getSnapshot().pendingInteractions).toEqual([]);
  169. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  170. },
  171. );
  172. it("cancellation during a broker-approved edit still prevents execution", async () => {
  173. const controller = new AbortController();
  174. const h = harness({
  175. clientResponse: () => {
  176. controller.abort();
  177. return { decision: "modify", modifiedInput: { command: "git reset --hard" } };
  178. },
  179. });
  180. const result = await h.run("Bash", { command: "rm -rf fixture" }, controller.signal);
  181. expect(result.error?.type).toBe(CoreErrorType.ToolCancelled);
  182. expect(h.requests).toHaveLength(1);
  183. expect(h.execution).not.toHaveBeenCalled();
  184. expect(h.interactions.has(h.requests[0]!.requestId)).toBe(false);
  185. expect(h.projection.getSnapshot().pendingInteractions).toEqual([]);
  186. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  187. });
  188. it.each(["Blue", "Custom teal", ""])(
  189. "an immediate AskUserQuestion answer is delivered exactly once: %s",
  190. async (answer) => {
  191. const h = harness({
  192. onVisible: (id, registry) => {
  193. expect(registry.has(id)).toBe(true);
  194. expect(
  195. registry.resolve(id, {
  196. action: "accept",
  197. content: { answers: answer ? { [QUESTION]: answer } : {} },
  198. }),
  199. ).toBe(true);
  200. },
  201. });
  202. const result = await h.run("AskUserQuestion", questionInput);
  203. expect(result.success).toBe(true);
  204. expect(result.modelContent).toContain(answer || "The user did not provide answers");
  205. expect(h.requests).toHaveLength(1);
  206. expect(
  207. h.events.filter((event) => event.type === SessionEventType.ToolCallResult),
  208. ).toHaveLength(1);
  209. expect(h.projection.getSnapshot().pendingInteractions).toEqual([]);
  210. },
  211. );
  212. it.each(["allowOnce", "deny", "allowAlways"])(
  213. "finishes %s through the real command registry, rejecting duplicates",
  214. async (optionId) => {
  215. const h = harness();
  216. const pending = h.run();
  217. await vi.waitFor(() =>
  218. expect(h.projection.getSnapshot().pendingInteractions).toHaveLength(1),
  219. );
  220. const id = h.requests[0]!.requestId;
  221. expect(h.execution).not.toHaveBeenCalled();
  222. await h.answer(id, { optionId, freeText: "Keep files" });
  223. await h.answer(id, { optionId: "allowOnce" });
  224. const result = await pending;
  225. expect(result.success, JSON.stringify(result)).toBe(optionId === "allowOnce");
  226. if (optionId !== "allowOnce")
  227. expect(result.modelContent ?? result.error?.message).toContain("Keep files");
  228. expect(h.execution).toHaveBeenCalledTimes(optionId === "allowOnce" ? 1 : 0);
  229. expect(h.saveProjectPermission).not.toHaveBeenCalled();
  230. expect(h.interactions.has(id)).toBe(false);
  231. expect(h.projection.getSnapshot().pendingInteractions).toEqual([]);
  232. expect(
  233. h.events.filter((event) => event.type === SessionEventType.PermissionResolved),
  234. ).toHaveLength(1);
  235. },
  236. );
  237. it("no human response does not activate the AskUserQuestion automatic-answer timer", async () => {
  238. vi.useFakeTimers();
  239. const h = harness();
  240. const pending = h.run();
  241. await vi.advanceTimersByTimeAsync(600_000);
  242. const id = h.requests[0]!.requestId;
  243. expect(h.interactions.has(id)).toBe(true);
  244. expect(h.projection.getSnapshot().pendingInteractions).toHaveLength(1);
  245. expect(h.execution).not.toHaveBeenCalled();
  246. await h.answer(id, { optionId: "deny" });
  247. expect((await pending).success).toBe(false);
  248. expect(h.interactions.has(id)).toBe(false);
  249. });
  250. it.each([
  251. [-32021, CoreErrorType.ToolCancelled],
  252. [-32022, CoreErrorType.PermissionTimeout],
  253. [-32020, CoreErrorType.ConfigurationError],
  254. ] as const)(
  255. "preserves the failure category for protocol code %s",
  256. async (clientError, errorType) => {
  257. const h = harness({ clientError });
  258. const result = await h.run();
  259. expect(result.error?.type).toBe(errorType);
  260. expect(h.execution).not.toHaveBeenCalled();
  261. expect(h.projection.getSnapshot().pendingInteractions).toEqual([]);
  262. },
  263. );
  264. it("cancellation racing with approval still prevents execution", async () => {
  265. const h = harness();
  266. const controller = new AbortController();
  267. const pending = h.run("Bash", { command: "rm -rf fixture" }, controller.signal);
  268. await vi.waitFor(() => expect(h.requests).toHaveLength(1));
  269. const id = h.requests[0]!.requestId;
  270. const response = h.answer(id, { optionId: "allowOnce" });
  271. controller.abort();
  272. await response;
  273. expect((await pending).error?.type).toBe(CoreErrorType.ToolCancelled);
  274. expect(h.execution).not.toHaveBeenCalled();
  275. expect(h.interactions.has(id)).toBe(false);
  276. });
  277. });