permission-full-access.test.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  3. import { applyRuntimeExecutionState } from "../src/runtime/execution-state.js";
  4. import { grantPermissionMode } from "../src/runtime/permission-full-access.js";
  5. function fixture() {
  6. const inputs = [
  7. {
  8. pendingInputId: "a",
  9. intent: { mode: "build", planEnabled: true, modelSelection: { modelId: "one" } },
  10. },
  11. { pendingInputId: "b", intent: { mode: "edit", planEnabled: false } },
  12. ];
  13. let receipt: unknown;
  14. const runtime = {
  15. sessionId: "session",
  16. sessionPersisted: true,
  17. config: { mode: "edit", planEnabled: true },
  18. rootTraceContext: {},
  19. pendingInputReservations: new Map(),
  20. activeTurn: {
  21. pendingInputs: inputs.map((item) => ({ id: item.pendingInputId, intent: item.intent })),
  22. },
  23. rebuildProjection: vi.fn(async () => ({ pendingSteerInputs: inputs })),
  24. sessionStore: {
  25. sessionEntries: vi.fn(async () =>
  26. receipt ? [{ id: "session:permission-full-access:permission-1", data: receipt }] : [],
  27. ),
  28. commitPermissionFullAccess: vi.fn(async (input) => {
  29. receipt = input.receipt.data;
  30. }),
  31. },
  32. createEvent: vi.fn((type, payload) => ({
  33. id: "grant-event",
  34. type,
  35. payload,
  36. sessionId: "session",
  37. traceId: "trace",
  38. timestamp: new Date(),
  39. sequenceNumber: 0,
  40. })),
  41. appendEvent: vi.fn(async () => {}),
  42. eventStore: { getEvents: vi.fn(async () => []) },
  43. notifyEventSinks: vi.fn(async () => {}),
  44. };
  45. return {
  46. runtime,
  47. grant: (mode: "guarded" | "yolo" = "yolo") =>
  48. grantPermissionMode.call(runtime as unknown as AgentRuntimeInternal, "permission-1", mode),
  49. };
  50. }
  51. describe("审批框完全访问", () => {
  52. it("草稿只授权内存,发布失败重试复用原事件,不覆盖后来的模式", async () => {
  53. const { runtime, grant } = fixture();
  54. runtime.sessionPersisted = false;
  55. runtime.rebuildProjection.mockResolvedValue({ pendingSteerInputs: [] });
  56. runtime.activeTurn.pendingInputs = [];
  57. const published: unknown[] = [];
  58. runtime.createEvent.mockImplementation((type, payload) => ({
  59. id: `event-${runtime.createEvent.mock.calls.length}`,
  60. type,
  61. payload,
  62. sessionId: "session",
  63. traceId: "trace",
  64. timestamp: new Date(),
  65. sequenceNumber: 0,
  66. }));
  67. runtime.appendEvent.mockRejectedValueOnce(new Error("event failed"));
  68. await expect(grant()).rejects.toThrow("event failed");
  69. expect(runtime.config.mode).toBe("yolo");
  70. runtime.appendEvent.mockImplementation(async (event) => {
  71. published.push(event);
  72. });
  73. runtime.eventStore.getEvents.mockImplementation(async () => published);
  74. await applyRuntimeExecutionState(
  75. runtime as unknown as AgentRuntimeInternal,
  76. { mode: "build", planEnabled: false },
  77. { source: "command" },
  78. );
  79. await grant();
  80. expect(runtime.sessionStore.commitPermissionFullAccess).not.toHaveBeenCalled();
  81. expect(runtime.createEvent).toHaveBeenCalledTimes(2);
  82. expect(runtime.appendEvent.mock.calls[0]?.[0]).toBe(runtime.appendEvent.mock.calls[1]?.[0]);
  83. expect(published).toHaveLength(2);
  84. expect(runtime.config).toEqual({ mode: "build", planEnabled: false });
  85. });
  86. it.each(["guarded", "yolo"] as const)(
  87. "保留 Runtime 和每项 Plan,只更新本次目标为 %s",
  88. async (mode) => {
  89. const { runtime, grant } = fixture();
  90. await grant(mode);
  91. expect(runtime.config).toEqual({ mode, planEnabled: true });
  92. expect(runtime.activeTurn.pendingInputs.map((item) => item.intent)).toEqual([
  93. { mode, planEnabled: true, modelSelection: { modelId: "one" } },
  94. { mode, planEnabled: false },
  95. ]);
  96. expect(runtime.sessionStore.commitPermissionFullAccess).toHaveBeenCalledOnce();
  97. expect(runtime.appendEvent).toHaveBeenCalledOnce();
  98. },
  99. );
  100. it("重试同一请求不能把已保存的自主授权升级为完全访问", async () => {
  101. const { runtime, grant } = fixture();
  102. runtime.appendEvent.mockRejectedValueOnce(new Error("event failed"));
  103. await expect(grant("guarded")).rejects.toThrow("event failed");
  104. await expect(grant("yolo")).rejects.toMatchObject({
  105. reasonCode: "fault.permissionGrant.committed.guarded",
  106. });
  107. await grant("guarded");
  108. expect(runtime.sessionStore.commitPermissionFullAccess).toHaveBeenCalledOnce();
  109. expect(runtime.config.mode).toBe("guarded");
  110. });
  111. it("授权重试仍严格拒绝损坏 receipt,不重新抓取队列或提交权限", async () => {
  112. const { runtime, grant } = fixture();
  113. runtime.sessionStore.sessionEntries.mockResolvedValueOnce([
  114. {
  115. id: "session:permission-full-access:permission-1",
  116. data: { interactionId: "permission-1", event: null },
  117. },
  118. ]);
  119. await expect(grant()).rejects.toThrow();
  120. expect(runtime.sessionStore.commitPermissionFullAccess).not.toHaveBeenCalled();
  121. expect(runtime.rebuildProjection).not.toHaveBeenCalled();
  122. expect(runtime.appendEvent).not.toHaveBeenCalled();
  123. expect(runtime.config.mode).toBe("edit");
  124. });
  125. it("事务失败不改内存,不发布成功", async () => {
  126. const { runtime, grant } = fixture();
  127. runtime.sessionStore.commitPermissionFullAccess.mockRejectedValueOnce(new Error("disk full"));
  128. await expect(grant()).rejects.toThrow("disk full");
  129. expect(runtime.config.mode).toBe("edit");
  130. expect(runtime.activeTurn.pendingInputs[0]?.intent.mode).toBe("build");
  131. expect(runtime.appendEvent).not.toHaveBeenCalled();
  132. });
  133. it("提交后事件失败可重试,固定目标不覆盖后来入队消息", async () => {
  134. const { runtime, grant } = fixture();
  135. runtime.appendEvent.mockRejectedValueOnce(new Error("event failed"));
  136. await expect(grant()).rejects.toThrow("event failed");
  137. runtime.activeTurn.pendingInputs.push({
  138. id: "later",
  139. intent: { mode: "edit", planEnabled: false },
  140. });
  141. await grant();
  142. expect(runtime.sessionStore.commitPermissionFullAccess).toHaveBeenCalledOnce();
  143. expect(runtime.activeTurn.pendingInputs.at(-1)?.intent.mode).toBe("edit");
  144. });
  145. it("Guide 正在消费或队列已 reserve 时拒绝提权,稍后可重试", async () => {
  146. const { runtime, grant } = fixture();
  147. Object.assign(runtime, { pendingInputDrains: 1 });
  148. await expect(grant()).rejects.toThrow("busy");
  149. Object.assign(runtime, { pendingInputDrains: 0 });
  150. runtime.pendingInputReservations.set("a", "reservation");
  151. await expect(grant()).rejects.toThrow("busy");
  152. runtime.pendingInputReservations.clear();
  153. await grant();
  154. expect(runtime.sessionStore.commitPermissionFullAccess).toHaveBeenCalledOnce();
  155. });
  156. it("发布失败后改权限,先补旧事件;迟到审批重试不覆盖较新的选择", async () => {
  157. const { runtime, grant } = fixture();
  158. const published: unknown[] = [];
  159. runtime.appendEvent.mockRejectedValueOnce(new Error("event failed"));
  160. await expect(grant()).rejects.toThrow("event failed");
  161. runtime.appendEvent.mockImplementation(async (event) => {
  162. published.push(event);
  163. });
  164. runtime.eventStore.getEvents.mockImplementation(async () => published);
  165. await applyRuntimeExecutionState(
  166. runtime as unknown as AgentRuntimeInternal,
  167. { mode: "build", planEnabled: false },
  168. { source: "command" },
  169. );
  170. expect(published.map((event: any) => event.payload.mode)).toEqual(["yolo", "build"]);
  171. await grant();
  172. expect(runtime.config).toEqual({ mode: "build", planEnabled: false });
  173. expect(published).toHaveLength(2);
  174. });
  175. });