guarded-user-interaction.test.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createSessionId,
  4. createToolCallId,
  5. SessionEventType,
  6. type CollaborationMode,
  7. type PermissionBrokerRequest,
  8. type PermissionBrokerResult,
  9. type SessionEvent,
  10. } from "@zcode/contracts";
  11. import { createToolExecutor } from "../src/tool/executor.js";
  12. import { askUserQuestionToolEntry } from "../src/tool/handlers/ask-user-question.js";
  13. import { createToolRegistry } from "../src/tool/registry.js";
  14. import { PermissionService } from "../src/permission/service.js";
  15. const QUESTION = "Which color should we use?";
  16. const INPUT = {
  17. questions: [
  18. {
  19. header: "Color",
  20. question: QUESTION,
  21. options: [
  22. { label: "Blue", description: "Use blue" },
  23. { label: "Red", description: "Use red" },
  24. ],
  25. },
  26. ],
  27. };
  28. async function runQuestion(options: {
  29. mode?: CollaborationMode;
  30. answers?: unknown;
  31. deny?: boolean;
  32. hookAnswers?: boolean;
  33. }) {
  34. const registry = createToolRegistry();
  35. const handler = vi.fn(askUserQuestionToolEntry.handler);
  36. registry.register({ ...askUserQuestionToolEntry, handler });
  37. const requests: PermissionBrokerRequest[] = [];
  38. const events: SessionEvent[] = [];
  39. let permissionHookCalls = 0;
  40. const executor = createToolExecutor({
  41. mode: options.mode ?? "guarded",
  42. sessionId: createSessionId("guarded-question"),
  43. registry,
  44. permissionService: new PermissionService(),
  45. emitEvent: async (event) => {
  46. events.push(event);
  47. },
  48. permissionBroker: {
  49. async requestPermission(request, requestOptions): Promise<PermissionBrokerResult> {
  50. requests.push(request);
  51. // 有界失败:回归时立即报错,不让重复问答把测试挂死。
  52. if (requests.length > (options.hookAnswers ? 2 : 1)) {
  53. throw new Error("User answer must not reopen the interaction");
  54. }
  55. if (options.hookAnswers && requests.length === 1) {
  56. return new Promise((_, reject) => {
  57. requestOptions!.signal!.addEventListener("abort", () => reject(new Error("Hook won")), {
  58. once: true,
  59. });
  60. });
  61. }
  62. return options.deny
  63. ? { decision: "deny", reason: "No answer" }
  64. : { decision: "modify", modifiedInput: { ...INPUT, answers: options.answers } };
  65. },
  66. },
  67. ...(options.hookAnswers
  68. ? {
  69. hookRunner: {
  70. run: async ({ hookEventName }) => {
  71. if (hookEventName === "PermissionRequest") permissionHookCalls++;
  72. return {
  73. additionalContexts: [],
  74. ...(hookEventName === "PermissionRequest" && requests.length === 1
  75. ? {
  76. permissionRequestResult: {
  77. behavior: "allow" as const,
  78. updatedInput: { ...INPUT, answers: { [QUESTION]: "Hook answer" } },
  79. },
  80. }
  81. : {}),
  82. };
  83. },
  84. },
  85. }
  86. : {}),
  87. });
  88. const result = await executor.execute({
  89. id: createToolCallId("guarded-question"),
  90. name: "AskUserQuestion",
  91. input: INPUT,
  92. });
  93. return { result, requests, events, handler, permissionHookCalls };
  94. }
  95. describe.each(["yolo", "guarded"] as const)("%s user interaction completion", (mode) => {
  96. it.each(["Blue", "Custom teal", undefined])(
  97. "returns %s without reopening the question",
  98. async (answer) => {
  99. const answers = answer === undefined ? {} : { [QUESTION]: answer };
  100. const { result, requests, events, handler } = await runQuestion({ mode, answers });
  101. expect(result.success).toBe(true);
  102. expect(result.output).toMatchObject({ answers });
  103. expect(result.modelContent).toContain(answer ?? "The user did not provide answers");
  104. expect(requests).toHaveLength(1);
  105. expect(handler).toHaveBeenCalledTimes(1);
  106. expect(events.map((event) => event.type)).toEqual([
  107. SessionEventType.PermissionRequested,
  108. SessionEventType.PermissionResolved,
  109. SessionEventType.ToolCallStarted,
  110. SessionEventType.ToolCallResult,
  111. ]);
  112. },
  113. );
  114. it("still rejects invalid answers before the handler", async () => {
  115. const { result, requests, handler } = await runQuestion({ mode, answers: 42 });
  116. expect(result.success).toBe(false);
  117. expect(requests).toHaveLength(1);
  118. expect(handler).not.toHaveBeenCalled();
  119. });
  120. it("still respects user denial", async () => {
  121. const { result, requests, handler } = await runQuestion({ mode, deny: true });
  122. expect(result.success).toBe(false);
  123. expect(result.error?.message).toContain("No answer");
  124. expect(requests).toHaveLength(1);
  125. expect(handler).not.toHaveBeenCalled();
  126. });
  127. });
  128. it("rechecks Hook changes instead of treating them as a user's answer", async () => {
  129. const answers = { [QUESTION]: "Real user answer" };
  130. const { result, requests, handler, permissionHookCalls } = await runQuestion({
  131. answers,
  132. hookAnswers: true,
  133. });
  134. expect(result.success).toBe(true);
  135. expect(requests).toHaveLength(2);
  136. expect(requests[1]!.requestId).not.toBe(requests[0]!.requestId);
  137. expect(result.output).toMatchObject({ answers });
  138. expect(handler).toHaveBeenCalledTimes(1);
  139. expect(permissionHookCalls).toBe(1);
  140. });