subagent-runtime-refresh.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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.each(
  41. (["config", "reader", "loader"] as const).flatMap((source) =>
  42. (["enabled", "disabled", "use-off", "deny-edit"] as const).map((mode) => ({ source, mode })),
  43. ),
  44. )(
  45. "projects Memory tools from $source definitions ($mode) into child requests",
  46. async ({ source, mode }) => {
  47. const profile = {
  48. ...snapshot("old").activeAgents[0]!,
  49. tools: ["Grep"],
  50. memory: "project" as const,
  51. ...(mode === "deny-edit" ? { disallowedTools: ["Edit"] } : {}),
  52. };
  53. const definitions = { activeAgents: [profile] };
  54. const children: ModelRequest[] = [];
  55. let parentCalls = 0;
  56. const runtime = createTestAgentRuntime(
  57. createSessionId(),
  58. {
  59. mode: "yolo",
  60. compact: { enabled: false },
  61. titleGeneration: { enabled: false },
  62. memory: {
  63. enabled: mode !== "disabled",
  64. use: mode !== "use-off",
  65. storageRoot: "/storage",
  66. },
  67. ...(source === "config" ? { subagents: { profiles: [profile] } } : {}),
  68. },
  69. {
  70. eventStore: createTestSessionEventStore(),
  71. ...(source === "reader" ? { getAgentDefinitions: () => definitions } : {}),
  72. ...(source === "loader" ? { loadAgentDefinitions: async () => definitions } : {}),
  73. modelFactory: createTestModelFactory({
  74. async generateText(request, observation) {
  75. if (observation.invocationContext?.metadata?.querySource === "subagent") {
  76. children.push(request);
  77. return { finishReason: "stop", text: "child", usage };
  78. }
  79. return ++parentCalls % 2
  80. ? {
  81. finishReason: "tool-calls",
  82. text: "",
  83. usage,
  84. toolCalls: [call(`memory_${parentCalls}`)],
  85. }
  86. : { finishReason: "stop", text: "done", usage };
  87. },
  88. }),
  89. },
  90. );
  91. try {
  92. await runtime.executeTurn("first");
  93. await runtime.executeTurn("second");
  94. expect(children).toHaveLength(2);
  95. for (const request of children) {
  96. const tools = request.tools?.map((tool) => tool.name);
  97. expect(tools).toContain("Grep");
  98. expect(tools).not.toContain("Read");
  99. expect(tools?.includes("Write")).toBe(mode === "enabled" || mode === "deny-edit");
  100. expect(tools?.includes("Edit")).toBe(mode === "enabled");
  101. }
  102. // 有效工具是 Runtime 的派生视图,不能回写 Host 配置或跨会话污染快照。
  103. expect(profile.tools).toEqual(["Grep"]);
  104. } finally {
  105. runtime.beginShutdown();
  106. }
  107. },
  108. );
  109. it("discards a cancelled load and retains independent immutable snapshots", async () => {
  110. const pending = Promise.withResolvers<AgentDefinitionsSnapshot>();
  111. const initial = snapshot("old");
  112. const load = vi.fn().mockReturnValueOnce(pending.promise).mockResolvedValue(snapshot("new"));
  113. const definitions = createTurnAgentDefinitions(() => initial, load);
  114. const other = createTurnAgentDefinitions(
  115. () => snapshot("other"),
  116. async () => snapshot("other"),
  117. );
  118. const controller = new AbortController();
  119. const traceContext = { sessionId: createSessionId(), traceId: createTraceId() };
  120. const cancelled = definitions.prepare({ signal: controller.signal, traceContext });
  121. controller.abort();
  122. pending.resolve(snapshot("cancelled"));
  123. await expect(cancelled).rejects.toThrow();
  124. expect(definitions.get().activeAgents[0]?.modelSelection?.modelId).toBe("old");
  125. await definitions.prepare({ signal: new AbortController().signal, traceContext });
  126. expect(definitions.get().activeAgents[0]?.modelSelection?.modelId).toBe("new");
  127. expect(other.get().activeAgents[0]?.modelSelection?.modelId).toBe("other");
  128. });
  129. it("freezes profile for the entire parent turn and reloads only on the next turn", async () => {
  130. let current = snapshot("old"),
  131. step = 0;
  132. const load = vi.fn(async () => current);
  133. const children: { model: string; reasoning: unknown; request: ModelRequest }[] = [];
  134. const runtime = createTestAgentRuntime(
  135. createSessionId(),
  136. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false } },
  137. {
  138. eventStore: createTestSessionEventStore(),
  139. loadAgentDefinitions: load,
  140. modelFactory: createTestModelFactory({
  141. async generateText(request, observation) {
  142. if (observation.invocationContext?.metadata?.querySource === "subagent") {
  143. children.push({
  144. model: observation.model.modelId,
  145. reasoning: observation.model.options.reasoningLevel,
  146. request,
  147. });
  148. current = snapshot("new");
  149. return { finishReason: "stop", text: "child done", usage };
  150. }
  151. const n = ++step;
  152. return n === 1 || n === 2 || n === 4
  153. ? { finishReason: "tool-calls", text: "", usage, toolCalls: [call(`call_${n}`)] }
  154. : { finishReason: "stop", text: "done", usage };
  155. },
  156. }),
  157. },
  158. );
  159. await runtime.executeTurn("first");
  160. expect(load).toHaveBeenCalledTimes(1);
  161. await runtime.executeTurn("second");
  162. expect(load).toHaveBeenCalledTimes(2);
  163. expect(children.map((x) => x.model)).toEqual(["old", "old", "new"]);
  164. expect(children.map((x) => x.reasoning)).toEqual(["low", "low", "high"]);
  165. expect(JSON.stringify(children[0]?.request)).toContain("PROFILE_old");
  166. expect(JSON.stringify(children[2]?.request)).toContain("PROFILE_new");
  167. });
  168. it("loads queued input only when it starts a new turn", async () => {
  169. let current = snapshot("old"),
  170. parentCalls = 0;
  171. const started = Promise.withResolvers<void>();
  172. const blocked = Promise.withResolvers<void>();
  173. const load = vi.fn(async () => current);
  174. const children: string[] = [];
  175. const runtime = createTestAgentRuntime(
  176. createSessionId(),
  177. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false } },
  178. {
  179. eventStore: createTestSessionEventStore(),
  180. loadAgentDefinitions: load,
  181. modelFactory: createTestModelFactory({
  182. async generateText(_request, observation) {
  183. if (observation.invocationContext?.metadata?.querySource === "subagent") {
  184. children.push(observation.model.modelId);
  185. return { finishReason: "stop", text: "child", usage };
  186. }
  187. const step = ++parentCalls;
  188. if (step === 1) {
  189. started.resolve();
  190. await blocked.promise;
  191. }
  192. return step % 2
  193. ? { finishReason: "tool-calls", text: "", usage, toolCalls: [call(`queued_${step}`)] }
  194. : { finishReason: "stop", text: "done", usage };
  195. },
  196. }),
  197. },
  198. );
  199. const first = runtime.executeTurn("busy");
  200. await started.promise;
  201. const queued = runtime.executeTurn("queued");
  202. await Promise.resolve();
  203. expect(load).toHaveBeenCalledTimes(1);
  204. current = snapshot("new");
  205. blocked.resolve();
  206. await Promise.all([first, queued]);
  207. expect(children).toEqual(["old", "new"]);
  208. expect(load).toHaveBeenCalledTimes(2);
  209. });
  210. it("ends a failed configuration read without model requests and retries the next turn", async () => {
  211. const load = vi
  212. .fn()
  213. .mockRejectedValueOnce(new Error("config unavailable"))
  214. .mockResolvedValue(snapshot("new"));
  215. let calls = 0,
  216. children = 0;
  217. const requests: ModelRequest[] = [];
  218. const events = createTestSessionEventStore();
  219. const sessionStore = createRecordingSubagentSessionStore();
  220. const runtime = createTestAgentRuntime(
  221. createSessionId(),
  222. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: true } },
  223. {
  224. eventStore: events,
  225. sessionStore,
  226. loadAgentDefinitions: load,
  227. modelFactory: createTestModelFactory({
  228. async generateText(request, observation) {
  229. if (observation.invocationContext?.metadata?.querySource === "subagent") {
  230. children++;
  231. return { finishReason: "stop", text: "child", usage };
  232. }
  233. requests.push(request);
  234. return ++calls % 2
  235. ? { finishReason: "tool-calls", text: "", usage, toolCalls: [call(`call_${calls}`)] }
  236. : { finishReason: "stop", text: "done", usage };
  237. },
  238. }),
  239. },
  240. );
  241. await expect(runtime.executeTurn("CONFIG_FAILED_USER_INPUT")).rejects.toMatchObject({
  242. cause: { message: "config unavailable" },
  243. });
  244. expect(children).toBe(0);
  245. expect(requests).toHaveLength(0);
  246. const persisted = await sessionStore.messages({ sessionID: runtime.sessionId });
  247. expect(persisted.filter((message) => message.info.role === "user")).toHaveLength(1);
  248. expect(JSON.stringify(persisted)).toContain("CONFIG_FAILED_USER_INPUT");
  249. expect(
  250. (await events.getEvents(runtime.sessionId))
  251. .filter(
  252. (event) =>
  253. event.type === SessionEventType.TurnStarted ||
  254. event.type === SessionEventType.TurnError,
  255. )
  256. .map((event) => event.type),
  257. ).toEqual([SessionEventType.TurnStarted, SessionEventType.TurnError]);
  258. const failed = (await events.getEvents(runtime.sessionId)).filter(
  259. (event) => event.type === SessionEventType.TurnError,
  260. );
  261. expect(failed).toHaveLength(1);
  262. expect(failed[0]!.payload).toMatchObject({ turnPhase: TurnPhase.ProcessingInput });
  263. expect(JSON.stringify(failed[0]!.payload)).toContain("config unavailable");
  264. await runtime.executeTurn("second");
  265. expect(children).toBe(1);
  266. expect(requests).toHaveLength(2);
  267. expect(JSON.stringify(requests[0]!.messages).match(/CONFIG_FAILED_USER_INPUT/g)).toHaveLength(
  268. 1,
  269. );
  270. expect(load).toHaveBeenCalledTimes(2);
  271. });
  272. });