subagent-session-query.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. SessionEventType,
  4. STREAM_RECOVERY_DISCARDED_ERROR_NAME,
  5. STREAM_RECOVERY_DISCARDED_FINISH,
  6. type MessageWithParts,
  7. type SessionEvent,
  8. type SessionInfo,
  9. type SessionProjection,
  10. type ToolPart,
  11. } from "@zcode/contracts";
  12. import {
  13. paginateEndedSubagents,
  14. projectSessionSubagents,
  15. } from "../src/zcode-protocol/subagent-session-query.js";
  16. function session(id: string, taskType: SessionInfo["taskType"] = "subagent_child"): SessionInfo {
  17. return {
  18. id: id as SessionInfo["id"],
  19. projectID: "project" as SessionInfo["projectID"],
  20. taskType,
  21. slug: id,
  22. directory: "/workspace",
  23. title: id,
  24. version: "test",
  25. time: { created: 1, updated: 100 },
  26. };
  27. }
  28. function toolMessage(input: {
  29. childSessionId?: string;
  30. id: string;
  31. output?: Record<string, unknown> | string;
  32. runInBackground?: boolean;
  33. state?: "completed" | "error" | "running";
  34. tool?: string;
  35. }): MessageWithParts {
  36. const state = input.state ?? "completed";
  37. const common = {
  38. input: {
  39. description: `Description ${input.id}`,
  40. subagent_type: "Explore",
  41. ...(input.runInBackground ? { run_in_background: true } : {}),
  42. },
  43. metadata: input.childSessionId ? { childSessionId: input.childSessionId } : {},
  44. time: state === "running" ? { start: 10 } : { start: 10, end: 20 },
  45. };
  46. const part: ToolPart = {
  47. id: `part-${input.id}` as ToolPart["id"],
  48. sessionID: "parent" as ToolPart["sessionID"],
  49. messageID: input.id as ToolPart["messageID"],
  50. type: "tool",
  51. callID: `call-${input.id}`,
  52. tool: input.tool ?? "Agent",
  53. state:
  54. state === "running"
  55. ? { ...common, status: "running" }
  56. : state === "error"
  57. ? { ...common, status: "error", error: "Provider failed" }
  58. : {
  59. ...common,
  60. status: "completed",
  61. output:
  62. typeof input.output === "string"
  63. ? input.output
  64. : JSON.stringify(input.output ?? { result: `Summary ${input.id}` }),
  65. title: `Description ${input.id}`,
  66. },
  67. };
  68. return {
  69. info: {
  70. id: input.id as never,
  71. sessionID: "parent" as never,
  72. role: "assistant",
  73. time: { created: 10, completed: 20 },
  74. parentID: "user" as never,
  75. modelID: "model" as never,
  76. providerID: "provider" as never,
  77. mode: "build",
  78. agent: "zcode",
  79. path: { cwd: "/workspace", root: "/workspace" },
  80. cost: 0,
  81. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  82. },
  83. parts: [part],
  84. };
  85. }
  86. function projection(status: SessionProjection["status"]): SessionProjection {
  87. return {
  88. id: "child" as never,
  89. createdAt: new Date(1),
  90. updatedAt: new Date(2),
  91. mode: "build",
  92. status,
  93. turnCount: 1,
  94. totalTokenCount: 0,
  95. contextUsed: 0,
  96. contextWindow: 1,
  97. pendingPermissions: [],
  98. pendingSteerInputs: [],
  99. activeToolCalls: [],
  100. streamingToolLedger: [],
  101. backgroundTasks: [],
  102. targetCompletionVerifications: [],
  103. targetCompletionVerificationTimeline: [],
  104. };
  105. }
  106. function subagentEvent(
  107. type: typeof SessionEventType.SubagentSpawned | typeof SessionEventType.SubagentStopped,
  108. payload: Record<string, unknown>,
  109. ): SessionEvent {
  110. return {
  111. id: "event" as never,
  112. sessionId: "parent" as never,
  113. type,
  114. timestamp: new Date(15),
  115. traceId: "trace" as never,
  116. sequenceNumber: 1,
  117. payload,
  118. };
  119. }
  120. describe("subagent session query", () => {
  121. it("projects Agent and legacy Task refs but omits non-persisted children", () => {
  122. const result = projectSessionSubagents({
  123. revision: 3,
  124. parentSession: session("parent", "interactive"),
  125. messages: [
  126. toolMessage({ childSessionId: "child-agent", id: "m1" }),
  127. toolMessage({ childSessionId: "child-task", id: "m2", tool: "Task" }),
  128. toolMessage({ childSessionId: "missing", id: "m3" }),
  129. ],
  130. childSessionsById: new Map([
  131. ["child-agent", session("child-agent")],
  132. ["child-task", session("child-task")],
  133. ]),
  134. childMessagesById: new Map(),
  135. childProjectionsById: new Map(),
  136. });
  137. expect(result.running).toEqual([]);
  138. expect(result.ended.map((item) => item.childSessionId)).toEqual(["child-task", "child-agent"]);
  139. expect(result.ended[0]).toMatchObject({
  140. status: "success",
  141. subagentType: "Explore",
  142. summary: "Summary m2",
  143. });
  144. });
  145. it("uses live child and background state without duplicating the persisted ref", () => {
  146. const parentProjection = projection("running");
  147. parentProjection.backgroundTasks = [
  148. {
  149. taskId: "agent-1",
  150. taskKind: "subagent",
  151. childSessionId: "child-1",
  152. blocked: true,
  153. status: "running",
  154. startedAt: new Date(10),
  155. },
  156. ];
  157. const result = projectSessionSubagents({
  158. revision: 4,
  159. parentSession: session("parent", "interactive"),
  160. messages: [toolMessage({ childSessionId: "child-1", id: "m1", state: "running" })],
  161. childSessionsById: new Map([["child-1", session("child-1")]]),
  162. childMessagesById: new Map(),
  163. childProjectionsById: new Map([["child-1", projection("waiting")]]),
  164. parentProjection,
  165. });
  166. expect(result.ended).toEqual([]);
  167. expect(result.running).toEqual([
  168. expect.objectContaining({ childSessionId: "child-1", status: "blocked" }),
  169. ]);
  170. });
  171. it("uses live spawn events for foreground children before the Agent result is persisted", () => {
  172. const parentProjection = projection("running");
  173. parentProjection.backgroundTasks = [
  174. {
  175. taskId: "agent-live",
  176. taskKind: "subagent",
  177. childSessionId: "child-live",
  178. status: "running",
  179. startedAt: new Date(10),
  180. },
  181. ];
  182. const result = projectSessionSubagents({
  183. revision: 5,
  184. parentSession: session("parent", "interactive"),
  185. messages: [toolMessage({ id: "m1", state: "running" })],
  186. childSessionsById: new Map([["child-live", session("child-live")]]),
  187. childMessagesById: new Map(),
  188. childProjectionsById: new Map(),
  189. parentEvents: [
  190. subagentEvent(SessionEventType.SubagentSpawned, {
  191. agentId: "agent-live",
  192. agentType: "Explore",
  193. childSessionId: "child-live",
  194. parentToolCallId: "call-m1",
  195. description: "Live foreground Agent",
  196. }),
  197. ],
  198. parentProjection,
  199. });
  200. expect(result.running).toEqual([
  201. expect.objectContaining({ childSessionId: "child-live", status: "running" }),
  202. ]);
  203. });
  204. it("keeps a launched background child running when a partial projection omits its task", () => {
  205. const childSessionId = "sess_subagent_agent-keepalive";
  206. const result = projectSessionSubagents({
  207. revision: 6,
  208. parentSession: session("parent", "interactive"),
  209. messages: [
  210. toolMessage({
  211. childSessionId,
  212. id: "m1",
  213. output:
  214. "Async agent launched successfully.\nagentId: agent-keepalive\nThe agent is working in the background.",
  215. runInBackground: true,
  216. }),
  217. ],
  218. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  219. childMessagesById: new Map([[childSessionId, []]]),
  220. childProjectionsById: new Map(),
  221. });
  222. expect(result.ended).toEqual([]);
  223. expect(result.running).toEqual([
  224. expect.objectContaining({ childSessionId, status: "running" }),
  225. ]);
  226. });
  227. it("does not treat a completed child tool-call model step as a terminal child outcome", () => {
  228. const childSessionId = "sess_subagent_agent-child-tool";
  229. const childToolStep = toolMessage({
  230. id: "child-tool-step",
  231. state: "running",
  232. tool: "Bash",
  233. });
  234. childToolStep.info.time.completed = 30;
  235. childToolStep.info.finish = "tool-calls";
  236. const result = projectSessionSubagents({
  237. revision: 7,
  238. parentSession: session("parent", "interactive"),
  239. messages: [
  240. toolMessage({
  241. childSessionId,
  242. id: "m1",
  243. output:
  244. "Async agent launched successfully.\nagentId: agent-child-tool\nThe agent is working in the background.",
  245. runInBackground: true,
  246. }),
  247. ],
  248. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  249. childMessagesById: new Map([[childSessionId, [childToolStep]]]),
  250. childProjectionsById: new Map(),
  251. parentEvents: [
  252. subagentEvent(SessionEventType.SubagentSpawned, {
  253. agentId: "agent-child-tool",
  254. childSessionId,
  255. parentToolCallId: "call-m1",
  256. description: "Child tool Agent",
  257. }),
  258. ],
  259. });
  260. expect(result.ended).toEqual([]);
  261. expect(result.running).toEqual([
  262. expect.objectContaining({ childSessionId, status: "running" }),
  263. ]);
  264. });
  265. it("does not treat a stream recovery discarded child step as a failed child outcome", () => {
  266. const childSessionId = "sess_subagent_agent-child-discarded";
  267. const discardedStep = toolMessage({ id: "child-discarded", state: "running", tool: "Bash" });
  268. discardedStep.parts = [];
  269. discardedStep.info.time.completed = 30;
  270. discardedStep.info.finish = STREAM_RECOVERY_DISCARDED_FINISH;
  271. discardedStep.info.error = {
  272. name: STREAM_RECOVERY_DISCARDED_ERROR_NAME,
  273. data: { message: "Partial assistant output was discarded before a streaming retry." },
  274. };
  275. const result = projectSessionSubagents({
  276. revision: 8,
  277. parentSession: session("parent", "interactive"),
  278. messages: [
  279. toolMessage({
  280. childSessionId,
  281. id: "m1",
  282. output:
  283. "Async agent launched successfully.\nagentId: agent-child-discarded\nThe agent is working in the background.",
  284. runInBackground: true,
  285. }),
  286. ],
  287. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  288. childMessagesById: new Map([[childSessionId, [discardedStep]]]),
  289. childProjectionsById: new Map(),
  290. parentEvents: [
  291. subagentEvent(SessionEventType.SubagentSpawned, {
  292. agentId: "agent-child-discarded",
  293. childSessionId,
  294. parentToolCallId: "call-m1",
  295. description: "Child discarded Agent",
  296. }),
  297. ],
  298. });
  299. expect(result.ended).toEqual([]);
  300. expect(result.running).toEqual([
  301. expect.objectContaining({ childSessionId, status: "running" }),
  302. ]);
  303. });
  304. it("derives the persisted foreground child id from the completed Agent output agentId", () => {
  305. const result = projectSessionSubagents({
  306. revision: 6,
  307. parentSession: session("parent", "interactive"),
  308. messages: [
  309. toolMessage({
  310. id: "m1",
  311. output: { agentId: "agent-foreground", result: "Finished foreground work" },
  312. }),
  313. ],
  314. childSessionsById: new Map([
  315. ["sess_subagent_agent-foreground", session("sess_subagent_agent-foreground")],
  316. ]),
  317. childMessagesById: new Map(),
  318. childProjectionsById: new Map(),
  319. });
  320. expect(result.ended).toEqual([
  321. expect.objectContaining({
  322. childSessionId: "sess_subagent_agent-foreground",
  323. summary: "Finished foreground work",
  324. status: "success",
  325. }),
  326. ]);
  327. });
  328. it("paginates ended children newest-first with an opaque cursor", () => {
  329. const ended = Array.from({ length: 25 }, (_, index) => ({
  330. childSessionId: `child-${index}`,
  331. subagentType: "Explore",
  332. title: `Child ${index}`,
  333. status: "success" as const,
  334. endedAt: 100 - index,
  335. }));
  336. const first = paginateEndedSubagents(ended, { limit: 20 });
  337. const second = paginateEndedSubagents(ended, { cursor: first.nextCursor, limit: 20 });
  338. expect(first.items).toHaveLength(20);
  339. expect(first.nextCursor).toBeTruthy();
  340. expect(second.items.map((item) => item.childSessionId)).toEqual([
  341. "child-20",
  342. "child-21",
  343. "child-22",
  344. "child-23",
  345. "child-24",
  346. ]);
  347. expect(second.nextCursor).toBeUndefined();
  348. });
  349. });