subagent-runtime-refresh.test.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. SessionEventType,
  4. createSessionId,
  5. createTraceId,
  6. type ModelRequest,
  7. } from "@zcode/contracts";
  8. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  9. import { createTestModelFactory } from "./test-runtime-model.js";
  10. import { createTestSessionEventStore } from "./test-event-store.js";
  11. import { createRecordingSubagentSessionStore } from "./subagent-test-store.js";
  12. import { TurnPhase } from "../src/agent/turn-state.js";
  13. import {
  14. createTurnAgentDefinitions,
  15. type AgentDefinitionsSnapshot,
  16. } from "../src/subagent/definitions.js";
  17. const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  18. const snapshot = (version: string): AgentDefinitionsSnapshot => ({
  19. activeAgents: [
  20. {
  21. name: "researcher",
  22. description: "Research",
  23. source: "user",
  24. tools: ["Read"],
  25. systemPrompt: `PROFILE_${version}`,
  26. modelSelection: {
  27. providerId: "custom",
  28. modelId: version,
  29. options: { reasoningLevel: version === "old" ? "low" : "high" },
  30. },
  31. },
  32. ],
  33. });
  34. const call = (id: string) => ({
  35. id,
  36. name: "Agent",
  37. input: { description: "Research", prompt: "Read", subagent_type: "researcher" },
  38. });
  39. describe("subagent turn snapshot", () => {
  40. it("discards a cancelled load and retains independent immutable snapshots", async () => {
  41. const pending = Promise.withResolvers<AgentDefinitionsSnapshot>();
  42. const initial = snapshot("old");
  43. const load = vi.fn().mockReturnValueOnce(pending.promise).mockResolvedValue(snapshot("new"));
  44. const definitions = createTurnAgentDefinitions(() => initial, load);
  45. const other = createTurnAgentDefinitions(
  46. () => snapshot("other"),
  47. async () => snapshot("other"),
  48. );
  49. const controller = new AbortController();
  50. const traceContext = { sessionId: createSessionId(), traceId: createTraceId() };
  51. const cancelled = definitions.prepare({ signal: controller.signal, traceContext });
  52. controller.abort();
  53. pending.resolve(snapshot("cancelled"));
  54. await expect(cancelled).rejects.toThrow();
  55. expect(definitions.get().activeAgents[0]?.modelSelection?.modelId).toBe("old");
  56. await definitions.prepare({ signal: new AbortController().signal, traceContext });
  57. expect(definitions.get().activeAgents[0]?.modelSelection?.modelId).toBe("new");
  58. expect(other.get().activeAgents[0]?.modelSelection?.modelId).toBe("other");
  59. });
  60. it("freezes profile for the entire parent turn and reloads only on the next turn", async () => {
  61. let current = snapshot("old"),
  62. step = 0;
  63. const load = vi.fn(async () => current);
  64. const children: { model: string; reasoning: unknown; request: ModelRequest }[] = [];
  65. const runtime = createTestAgentRuntime(
  66. createSessionId(),
  67. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false } },
  68. {
  69. eventStore: createTestSessionEventStore(),
  70. loadAgentDefinitions: load,
  71. modelFactory: createTestModelFactory({
  72. async generateText(request, observation) {
  73. if (observation.invocationContext?.metadata?.querySource === "subagent") {
  74. children.push({
  75. model: observation.model.modelId,
  76. reasoning: observation.model.options.reasoningLevel,
  77. request,
  78. });
  79. current = snapshot("new");
  80. return { finishReason: "stop", text: "child done", usage };
  81. }
  82. const n = ++step;
  83. return n === 1 || n === 2 || n === 4
  84. ? { finishReason: "tool-calls", text: "", usage, toolCalls: [call(`call_${n}`)] }
  85. : { finishReason: "stop", text: "done", usage };
  86. },
  87. }),
  88. },
  89. );
  90. await runtime.executeTurn("first");
  91. expect(load).toHaveBeenCalledTimes(1);
  92. await runtime.executeTurn("second");
  93. expect(load).toHaveBeenCalledTimes(2);
  94. expect(children.map((x) => x.model)).toEqual(["old", "old", "new"]);
  95. expect(children.map((x) => x.reasoning)).toEqual(["low", "low", "high"]);
  96. expect(JSON.stringify(children[0]?.request)).toContain("PROFILE_old");
  97. expect(JSON.stringify(children[2]?.request)).toContain("PROFILE_new");
  98. });
  99. it("loads queued input only when it starts a new turn", async () => {
  100. let current = snapshot("old"),
  101. parentCalls = 0;
  102. const started = Promise.withResolvers<void>();
  103. const blocked = Promise.withResolvers<void>();
  104. const load = vi.fn(async () => current);
  105. const children: string[] = [];
  106. const runtime = createTestAgentRuntime(
  107. createSessionId(),
  108. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false } },
  109. {
  110. eventStore: createTestSessionEventStore(),
  111. loadAgentDefinitions: load,
  112. modelFactory: createTestModelFactory({
  113. async generateText(_request, observation) {
  114. if (observation.invocationContext?.metadata?.querySource === "subagent") {
  115. children.push(observation.model.modelId);
  116. return { finishReason: "stop", text: "child", usage };
  117. }
  118. const step = ++parentCalls;
  119. if (step === 1) {
  120. started.resolve();
  121. await blocked.promise;
  122. }
  123. return step % 2
  124. ? { finishReason: "tool-calls", text: "", usage, toolCalls: [call(`queued_${step}`)] }
  125. : { finishReason: "stop", text: "done", usage };
  126. },
  127. }),
  128. },
  129. );
  130. const first = runtime.executeTurn("busy");
  131. await started.promise;
  132. const queued = runtime.executeTurn("queued");
  133. await Promise.resolve();
  134. expect(load).toHaveBeenCalledTimes(1);
  135. current = snapshot("new");
  136. blocked.resolve();
  137. await Promise.all([first, queued]);
  138. expect(children).toEqual(["old", "new"]);
  139. expect(load).toHaveBeenCalledTimes(2);
  140. });
  141. it("ends a failed configuration read without model requests and retries the next turn", async () => {
  142. const load = vi
  143. .fn()
  144. .mockRejectedValueOnce(new Error("config unavailable"))
  145. .mockResolvedValue(snapshot("new"));
  146. let calls = 0,
  147. children = 0;
  148. const requests: ModelRequest[] = [];
  149. const events = createTestSessionEventStore();
  150. const sessionStore = createRecordingSubagentSessionStore();
  151. const runtime = createTestAgentRuntime(
  152. createSessionId(),
  153. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: true } },
  154. {
  155. eventStore: events,
  156. sessionStore,
  157. loadAgentDefinitions: load,
  158. modelFactory: createTestModelFactory({
  159. async generateText(request, observation) {
  160. if (observation.invocationContext?.metadata?.querySource === "subagent") {
  161. children++;
  162. return { finishReason: "stop", text: "child", usage };
  163. }
  164. requests.push(request);
  165. return ++calls % 2
  166. ? { finishReason: "tool-calls", text: "", usage, toolCalls: [call(`call_${calls}`)] }
  167. : { finishReason: "stop", text: "done", usage };
  168. },
  169. }),
  170. },
  171. );
  172. await expect(runtime.executeTurn("CONFIG_FAILED_USER_INPUT")).rejects.toMatchObject({
  173. cause: { message: "config unavailable" },
  174. });
  175. expect(children).toBe(0);
  176. expect(requests).toHaveLength(0);
  177. const persisted = await sessionStore.messages({ sessionID: runtime.sessionId });
  178. expect(persisted.filter((message) => message.info.role === "user")).toHaveLength(1);
  179. expect(JSON.stringify(persisted)).toContain("CONFIG_FAILED_USER_INPUT");
  180. expect(
  181. (await events.getEvents(runtime.sessionId))
  182. .filter(
  183. (event) =>
  184. event.type === SessionEventType.TurnStarted ||
  185. event.type === SessionEventType.TurnError,
  186. )
  187. .map((event) => event.type),
  188. ).toEqual([SessionEventType.TurnStarted, SessionEventType.TurnError]);
  189. const failed = (await events.getEvents(runtime.sessionId)).filter(
  190. (event) => event.type === SessionEventType.TurnError,
  191. );
  192. expect(failed).toHaveLength(1);
  193. expect(failed[0]!.payload).toMatchObject({ turnPhase: TurnPhase.ProcessingInput });
  194. expect(JSON.stringify(failed[0]!.payload)).toContain("config unavailable");
  195. await runtime.executeTurn("second");
  196. expect(children).toBe(1);
  197. expect(requests).toHaveLength(2);
  198. expect(JSON.stringify(requests[0]!.messages).match(/CONFIG_FAILED_USER_INPUT/g)).toHaveLength(
  199. 1,
  200. );
  201. expect(load).toHaveBeenCalledTimes(2);
  202. });
  203. });