subagent-execution-boundaries.test.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import { describe, expect, it, vi } from "vitest";
  2. import { SessionEventType, createSessionId } from "@zcode/contracts";
  3. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  4. import { createTestModelFactory } from "./test-runtime-model.js";
  5. import { createTestSessionEventStore } from "./test-event-store.js";
  6. import { setup, initial, done, spawn, send, assertProfile } from "./subagent-profile-scenario.js";
  7. const next = () => ({ ...initial(), systemPrompt: "PROFILE_CHANGED", tools: ["Grep"] });
  8. describe("subagent definitions at execution boundaries", () => {
  9. it("fails the parent before model requests while preserving listing and the running child", async () => {
  10. const blocked = Promise.withResolvers<void>(),
  11. started = Promise.withResolvers<void>();
  12. let runningRequests = 0;
  13. const scenario = setup(async (record) => {
  14. if (
  15. JSON.stringify(record.request.messages).includes("RUNNING_SEED") &&
  16. ++runningRequests === 1
  17. ) {
  18. started.resolve();
  19. await blocked.promise;
  20. return {
  21. finishReason: "tool-calls",
  22. text: "",
  23. usage: {},
  24. toolCalls: [
  25. { id: "read_failure_delivery", name: "Read", input: { file_path: "/missing-fixture" } },
  26. ],
  27. };
  28. }
  29. return done();
  30. });
  31. try {
  32. await scenario.turn([spawn("TERMINAL_SEED")]);
  33. const terminal = (await scenario.spawned())[0]!;
  34. await scenario.waitCompleted(terminal.agentId, 1);
  35. await scenario.turn([spawn("RUNNING_SEED", true)]);
  36. await started.promise;
  37. const running = (await scenario.spawned())[1]!;
  38. const listing = (request: (typeof scenario.parents)[number]) =>
  39. request.messages.filter((message) =>
  40. JSON.stringify(message).includes("Available agent types for the Agent tool:"),
  41. );
  42. const before = listing(scenario.parents.at(-1)!);
  43. expect(before).toHaveLength(1);
  44. const count = scenario.children.length;
  45. const parentCount = scenario.parents.length;
  46. scenario.update(next());
  47. scenario.load.mockRejectedValueOnce(new Error("CONFIG_READ_FAILED"));
  48. await expect(
  49. scenario.turn([
  50. spawn("REJECTED_SPAWN"),
  51. send(terminal.agentId, "REJECTED_RESUME"),
  52. send(running.agentId, "DELIVER_DURING_FAILURE"),
  53. ]),
  54. ).rejects.toMatchObject({ cause: { message: "CONFIG_READ_FAILED" } });
  55. const failure = scenario.parents.at(-1)!;
  56. expect(listing(failure)).toEqual(before);
  57. expect(JSON.stringify(failure.messages)).not.toContain("no longer available");
  58. expect(scenario.parents).toHaveLength(parentCount);
  59. expect(scenario.children).toHaveLength(count);
  60. // 父轮失败不执行 SendMessage;恢复读取后投递,仍在运行的 child 保持原 profile。
  61. await scenario.turn([send(running.agentId, "DELIVER_AFTER_FAILURE")]);
  62. blocked.resolve();
  63. await scenario.waitCompleted(running.agentId, 1);
  64. assertProfile(scenario.children.at(-1)!, initial());
  65. expect(JSON.stringify(scenario.children.at(-1)!.request)).toContain("DELIVER_AFTER_FAILURE");
  66. expect(JSON.stringify(scenario.children.at(-1)!.request)).not.toContain(
  67. "DELIVER_DURING_FAILURE",
  68. );
  69. await scenario.turn([send(terminal.agentId, "RECOVERED_RESUME")]);
  70. await scenario.waitCompleted(terminal.agentId, 2);
  71. assertProfile(scenario.children.at(-1)!, next());
  72. expect(scenario.children.at(-1)!.sessionId).toBe(terminal.childSessionId);
  73. expect(listing(scenario.parents.at(-1)!)).toEqual(before);
  74. } finally {
  75. blocked.resolve();
  76. scenario.runtime.beginShutdown();
  77. }
  78. });
  79. it("keeps the turn definitions when Guide is drained and reloads for the next ordinary turn", async () => {
  80. let profile = initial(),
  81. parentCalls = 0;
  82. const load = vi.fn(async () => ({ activeAgents: [profile] }));
  83. const children: string[] = [];
  84. const runtime = createTestAgentRuntime(
  85. createSessionId(),
  86. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false } },
  87. {
  88. eventStore: createTestSessionEventStore(),
  89. loadAgentDefinitions: load,
  90. modelFactory: createTestModelFactory({
  91. async generateText(request, observation) {
  92. if (observation.invocationContext?.metadata?.querySource === "subagent") {
  93. children.push(JSON.stringify(request.messages));
  94. return done();
  95. }
  96. if (++parentCalls === 1) {
  97. profile = next();
  98. const guide = await runtime.steerTurn({
  99. expectedTurnId: runtime.getActiveTurnInfo()?.turnId,
  100. input: "GUIDE_INPUT",
  101. delivery: "guide",
  102. });
  103. expect(guide.kind).toBe("queued");
  104. return done();
  105. }
  106. return parentCalls === 2 || parentCalls === 4
  107. ? {
  108. finishReason: "tool-calls",
  109. text: "",
  110. usage: {},
  111. toolCalls: [spawn(`GUIDE_CHILD_${parentCalls}`)],
  112. }
  113. : done();
  114. },
  115. }),
  116. },
  117. );
  118. try {
  119. await runtime.executeTurn("START_GUIDE");
  120. expect(load).toHaveBeenCalledTimes(1);
  121. expect(children).toHaveLength(1);
  122. expect(children[0]).toContain(initial().systemPrompt);
  123. expect(children[0]).not.toContain(next().systemPrompt);
  124. await runtime.executeTurn("NEXT_ORDINARY");
  125. expect(load).toHaveBeenCalledTimes(2);
  126. expect(children[1]).toContain(next().systemPrompt);
  127. } finally {
  128. runtime.beginShutdown();
  129. }
  130. });
  131. it("cancels a real runtime during definitions loading and discards the late result before queued work", async () => {
  132. const started = Promise.withResolvers<void>(),
  133. blocked = Promise.withResolvers<void>();
  134. const controller = new AbortController();
  135. const events = createTestSessionEventStore();
  136. const calls: string[] = [];
  137. const load = vi
  138. .fn()
  139. .mockImplementationOnce(async () => {
  140. started.resolve();
  141. await blocked.promise;
  142. return { activeAgents: [{ ...initial(), systemPrompt: "CANCELLED_PROFILE" }] };
  143. })
  144. .mockResolvedValue({ activeAgents: [next()] });
  145. const runtime = createTestAgentRuntime(
  146. createSessionId(),
  147. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false } },
  148. {
  149. eventStore: events,
  150. loadAgentDefinitions: load,
  151. modelFactory: createTestModelFactory({
  152. async generateText(request, observation) {
  153. calls.push(JSON.stringify(request.messages));
  154. return observation.invocationContext?.metadata?.querySource === "subagent" ||
  155. calls.length > 1
  156. ? done()
  157. : {
  158. finishReason: "tool-calls",
  159. text: "",
  160. usage: {},
  161. toolCalls: [spawn("AFTER_STOP")],
  162. };
  163. },
  164. }),
  165. },
  166. );
  167. try {
  168. const cancelled = runtime.executeTurn("CANCELLED_INPUT", undefined, {
  169. abortSignal: controller.signal,
  170. });
  171. const rejected = expect(cancelled).rejects.toMatchObject({ cause: { message: "user stop" } });
  172. await started.promise;
  173. controller.abort(new Error("user stop"));
  174. const queued = runtime.executeTurn("AFTER_STOP_INPUT");
  175. expect(load).toHaveBeenCalledTimes(1);
  176. expect(calls).toHaveLength(0);
  177. blocked.resolve();
  178. await rejected;
  179. await queued;
  180. expect(load).toHaveBeenCalledTimes(2);
  181. expect(calls).toHaveLength(3);
  182. expect(calls.join()).not.toContain("CANCELLED_PROFILE");
  183. expect(calls[1]).toContain(next().systemPrompt);
  184. const completions = (await events.getEvents(runtime.sessionId)).filter(
  185. (e) => e.type === SessionEventType.TurnComplete,
  186. );
  187. // 已开始的输入在 definitions 加载取消后仍保留;终态不启动模型请求。
  188. expect(completions.map((e) => (e.payload as { resultType: string }).resultType)).toEqual([
  189. "cancelled",
  190. "success",
  191. ]);
  192. expect(
  193. (await events.getEvents(runtime.sessionId)).filter(
  194. (e) => e.type === SessionEventType.TurnStarted,
  195. ),
  196. ).toHaveLength(2);
  197. expect(calls[0]!.match(/CANCELLED_INPUT/g)).toHaveLength(1);
  198. } finally {
  199. blocked.resolve();
  200. runtime.beginShutdown();
  201. }
  202. });
  203. });