subagent-session-query.test.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  5. import {
  6. createSessionId,
  7. SessionEventType,
  8. STREAM_RECOVERY_DISCARDED_ERROR_NAME,
  9. STREAM_RECOVERY_DISCARDED_FINISH,
  10. type MessageWithParts,
  11. type SessionEvent,
  12. type SessionInfo,
  13. type SessionProjection,
  14. type ToolPart,
  15. } from "@zcode/contracts";
  16. import type { SubagentRunMetadata } from "@zcode/core";
  17. import { createSubagentObservation } from "../src/app/subagent-observation.js";
  18. import { ProductProjection } from "../src/zcode-protocol-v4/product-projection.js";
  19. import { listSessionSubagents } from "../src/zcode-protocol/server-operations.js";
  20. import {
  21. collectSubagentParentMessageIds,
  22. loadPreviousRuntimeRunMetadata,
  23. paginateEndedSubagents,
  24. projectSessionSubagents,
  25. } from "../src/zcode-protocol/subagent-session-query.js";
  26. function session(id: string, taskType: SessionInfo["taskType"] = "subagent_child"): SessionInfo {
  27. return {
  28. id: id as SessionInfo["id"],
  29. projectID: "project" as SessionInfo["projectID"],
  30. taskType,
  31. slug: id,
  32. directory: "/workspace",
  33. title: id,
  34. version: "test",
  35. time: { created: 1, updated: 100 },
  36. };
  37. }
  38. function toolMessage(input: {
  39. childSessionId?: string;
  40. /** 结算写进 part.metadata 的结构化事实(与 Agent 工具结算一致);不给时是只有回执文本的旧 part。 */
  41. facts?: { agentId: string; background?: true; outputFile: string };
  42. id: string;
  43. output?: Record<string, unknown> | string;
  44. runInBackground?: boolean;
  45. state?: "completed" | "error" | "running";
  46. tool?: string;
  47. }): MessageWithParts {
  48. const state = input.state ?? "completed";
  49. const common = {
  50. input: {
  51. description: `Description ${input.id}`,
  52. subagent_type: "Explore",
  53. ...(input.runInBackground ? { run_in_background: true } : {}),
  54. },
  55. metadata: input.childSessionId ? { childSessionId: input.childSessionId } : {},
  56. time: state === "running" ? { start: 10 } : { start: 10, end: 20 },
  57. };
  58. const part: ToolPart = {
  59. id: `part-${input.id}` as ToolPart["id"],
  60. sessionID: "parent" as ToolPart["sessionID"],
  61. messageID: input.id as ToolPart["messageID"],
  62. type: "tool",
  63. callID: `call-${input.id}`,
  64. tool: input.tool ?? "Agent",
  65. ...(input.facts
  66. ? {
  67. metadata: {
  68. agentId: input.facts.agentId,
  69. childSessionId: createSessionId(`subagent_${input.facts.agentId}`),
  70. outputFile: input.facts.outputFile,
  71. ...(input.facts.background ? { background: true } : {}),
  72. },
  73. }
  74. : {}),
  75. state:
  76. state === "running"
  77. ? { ...common, status: "running" }
  78. : state === "error"
  79. ? { ...common, status: "error", error: "Provider failed" }
  80. : {
  81. ...common,
  82. status: "completed",
  83. output:
  84. typeof input.output === "string"
  85. ? input.output
  86. : JSON.stringify(input.output ?? { result: `Summary ${input.id}` }),
  87. title: `Description ${input.id}`,
  88. },
  89. };
  90. return {
  91. info: {
  92. id: input.id as never,
  93. sessionID: "parent" as never,
  94. role: "assistant",
  95. time: { created: 10, completed: 20 },
  96. parentID: "user" as never,
  97. modelID: "model" as never,
  98. providerID: "provider" as never,
  99. mode: "build",
  100. agent: "zcode",
  101. path: { cwd: "/workspace", root: "/workspace" },
  102. cost: 0,
  103. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  104. },
  105. parts: [part],
  106. };
  107. }
  108. function projection(status: SessionProjection["status"]): SessionProjection {
  109. return {
  110. id: "child" as never,
  111. createdAt: new Date(1),
  112. updatedAt: new Date(2),
  113. mode: "build",
  114. status,
  115. turnCount: 1,
  116. totalTokenCount: 0,
  117. contextUsed: 0,
  118. contextWindow: 1,
  119. pendingPermissions: [],
  120. pendingSteerInputs: [],
  121. activeToolCalls: [],
  122. streamingToolLedger: [],
  123. backgroundTasks: [],
  124. targetCompletionVerifications: [],
  125. targetCompletionVerificationTimeline: [],
  126. };
  127. }
  128. function subagentEvent(
  129. type: typeof SessionEventType.SubagentSpawned | typeof SessionEventType.SubagentStopped,
  130. payload: Record<string, unknown>,
  131. ): SessionEvent {
  132. return {
  133. id: "event" as never,
  134. sessionId: "parent" as never,
  135. type,
  136. timestamp: new Date(15),
  137. traceId: "trace" as never,
  138. sequenceNumber: 1,
  139. payload,
  140. };
  141. }
  142. describe("subagent session query", () => {
  143. it("真实冷查询来源驱动无行 child 回退,与重新读取活动分支一致", async () => {
  144. const parent = session("parent", "interactive");
  145. const messages = [
  146. toolMessage({ id: "old", childSessionId: "old-child" }),
  147. toolMessage({ id: "new", childSessionId: "new-child" }),
  148. ];
  149. const store = {
  150. getSession: async (id: string) => (id === "parent" ? parent : session(id)),
  151. messages: async ({ sessionID }: { sessionID: string }) =>
  152. sessionID === "parent" ? messages : [{ ...toolMessage({ id: "child-result" }), parts: [] }],
  153. };
  154. const context = { deps: { sessionStore: store }, sessions: new Map() };
  155. const load = async () => {
  156. const result = await listSessionSubagents(
  157. context as never,
  158. { sessionId: "parent" },
  159. undefined,
  160. true,
  161. );
  162. return {
  163. ...result,
  164. ended: result.ended.items.flatMap((item) =>
  165. item.status === "lost" ? [] : [{ ...item, status: item.status }],
  166. ),
  167. };
  168. };
  169. const live = new ProductProjection("parent", "live");
  170. live.seedSubagents(await load());
  171. expect(live.getSnapshot().rows.window).toEqual([]);
  172. expect(live.getSnapshot().completedActivityCount).toBe(2);
  173. parent.revert = {
  174. messageID: "old" as never,
  175. targetMessageID: "new" as never,
  176. keptMessageIDs: ["old" as never],
  177. branchCutAfterMessageID: "new" as never,
  178. branchGeneration: 1,
  179. };
  180. live.applyEventAtomically(
  181. {
  182. id: "rewind" as never,
  183. sessionId: "parent" as never,
  184. traceId: "trace" as never,
  185. sequenceNumber: 1,
  186. timestamp: new Date(100),
  187. type: SessionEventType.RewindTriggered,
  188. payload: {
  189. rewindId: "rewind",
  190. strategy: "active_chain",
  191. scope: "conversation",
  192. targetMessageId: "new" as never,
  193. branchCutAfterMessageId: "new" as never,
  194. branchGeneration: 1,
  195. removedMessageIds: ["new"],
  196. },
  197. },
  198. () => true,
  199. );
  200. const cold = new ProductProjection("parent", "cold");
  201. cold.seedSubagents(await load());
  202. expect(live.getSnapshot().completedActivityCount).toBe(1);
  203. expect(live.getSnapshot().completedActivityCount).toBe(
  204. cold.getSnapshot().completedActivityCount,
  205. );
  206. expect(live.getSnapshot().subagents?.childSessionIds).toEqual(
  207. cold.getSnapshot().subagents?.childSessionIds,
  208. );
  209. });
  210. it("冷种子来源复用候选解析,保留同 child 的全部活动分支消息", () => {
  211. const parent = session("parent", "interactive");
  212. const messages = [
  213. toolMessage({ id: "old", childSessionId: "shared" }),
  214. toolMessage({ id: "new", childSessionId: "shared" }),
  215. toolMessage({ id: "other", childSessionId: "other" }),
  216. ];
  217. expect(collectSubagentParentMessageIds(parent, messages)).toEqual({
  218. shared: ["old", "new"],
  219. other: ["other"],
  220. });
  221. parent.revert = {
  222. messageID: "old" as never,
  223. targetMessageID: "new" as never,
  224. keptMessageIDs: ["old" as never],
  225. branchCutAfterMessageID: "other" as never,
  226. branchGeneration: 1,
  227. };
  228. expect(collectSubagentParentMessageIds(parent, messages)).toEqual({ shared: ["old"] });
  229. });
  230. it("projects Agent and legacy Task refs but omits non-persisted children", () => {
  231. const result = projectSessionSubagents({
  232. revision: 3,
  233. parentSession: session("parent", "interactive"),
  234. messages: [
  235. toolMessage({ childSessionId: "child-agent", id: "m1" }),
  236. toolMessage({ childSessionId: "child-task", id: "m2", tool: "Task" }),
  237. toolMessage({ childSessionId: "missing", id: "m3" }),
  238. ],
  239. childSessionsById: new Map([
  240. ["child-agent", session("child-agent")],
  241. ["child-task", session("child-task")],
  242. ]),
  243. childMessagesById: new Map(),
  244. childProjectionsById: new Map(),
  245. });
  246. expect(result.running).toEqual([]);
  247. expect(result.ended.map((item) => item.childSessionId)).toEqual(["child-task", "child-agent"]);
  248. expect(result.ended[0]).toMatchObject({
  249. status: "success",
  250. subagentType: "Explore",
  251. summary: "Summary m2",
  252. });
  253. });
  254. it("uses live child and background state without duplicating the persisted ref", () => {
  255. const parentProjection = projection("running");
  256. parentProjection.backgroundTasks = [
  257. {
  258. taskId: "agent-1",
  259. taskKind: "subagent",
  260. childSessionId: "child-1",
  261. blocked: true,
  262. status: "running",
  263. startedAt: new Date(10),
  264. },
  265. ];
  266. const result = projectSessionSubagents({
  267. revision: 4,
  268. parentSession: session("parent", "interactive"),
  269. messages: [toolMessage({ childSessionId: "child-1", id: "m1", state: "running" })],
  270. childSessionsById: new Map([["child-1", session("child-1")]]),
  271. childMessagesById: new Map(),
  272. childProjectionsById: new Map([["child-1", projection("waiting")]]),
  273. parentProjection,
  274. });
  275. expect(result.ended).toEqual([]);
  276. expect(result.running).toEqual([
  277. expect.objectContaining({ childSessionId: "child-1", status: "blocked" }),
  278. ]);
  279. });
  280. it("uses live spawn events for foreground children before the Agent result is persisted", () => {
  281. const parentProjection = projection("running");
  282. parentProjection.backgroundTasks = [
  283. {
  284. taskId: "agent-live",
  285. taskKind: "subagent",
  286. childSessionId: "child-live",
  287. status: "running",
  288. startedAt: new Date(10),
  289. },
  290. ];
  291. const result = projectSessionSubagents({
  292. revision: 5,
  293. parentSession: session("parent", "interactive"),
  294. messages: [toolMessage({ id: "m1", state: "running" })],
  295. childSessionsById: new Map([["child-live", session("child-live")]]),
  296. childMessagesById: new Map(),
  297. childProjectionsById: new Map(),
  298. parentEvents: [
  299. subagentEvent(SessionEventType.SubagentSpawned, {
  300. agentId: "agent-live",
  301. agentType: "Explore",
  302. childSessionId: "child-live",
  303. parentToolCallId: "call-m1",
  304. description: "Live foreground Agent",
  305. }),
  306. ],
  307. parentProjection,
  308. });
  309. expect(result.running).toEqual([
  310. expect.objectContaining({ childSessionId: "child-live", status: "running" }),
  311. ]);
  312. });
  313. it("keeps a launched background child running when a partial projection omits its task", () => {
  314. const childSessionId = "sess_subagent_agent-keepalive";
  315. const result = projectSessionSubagents({
  316. revision: 6,
  317. parentSession: session("parent", "interactive"),
  318. messages: [
  319. toolMessage({
  320. childSessionId,
  321. id: "m1",
  322. output:
  323. "Async agent launched successfully.\nagentId: agent-keepalive\nThe agent is working in the background.",
  324. runInBackground: true,
  325. }),
  326. ],
  327. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  328. childMessagesById: new Map([[childSessionId, []]]),
  329. childProjectionsById: new Map(),
  330. });
  331. expect(result.ended).toEqual([]);
  332. expect(result.running).toEqual([
  333. expect.objectContaining({ childSessionId, status: "running" }),
  334. ]);
  335. });
  336. // 修复回归:running 推断原来读原始输入的 run_in_background === true。Agent 总在后台运行后
  337. // 输入里没有这个字段,冷启动 seed 时运行中的后台子代理被判为已结束;现在读结构化的后台启动事实。
  338. it("keeps a launched background child running when its Agent input has no run_in_background", () => {
  339. const childSessionId = "sess_subagent_agent-no-flag";
  340. const result = projectSessionSubagents({
  341. revision: 6,
  342. parentSession: session("parent", "interactive"),
  343. messages: [
  344. toolMessage({
  345. facts: {
  346. agentId: "agent-no-flag",
  347. background: true,
  348. outputFile: "/workspace/.zcode/agents/agent-no-flag/output.txt",
  349. },
  350. id: "m1",
  351. output: { status: "async_launched", agentId: "agent-no-flag" },
  352. }),
  353. ],
  354. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  355. childMessagesById: new Map([[childSessionId, []]]),
  356. childProjectionsById: new Map(),
  357. });
  358. expect(result.ended).toEqual([]);
  359. expect(result.running).toEqual([
  360. expect.objectContaining({ childSessionId, status: "running" }),
  361. ]);
  362. });
  363. it("does not treat a completed child tool-call model step as a terminal child outcome", () => {
  364. const childSessionId = "sess_subagent_agent-child-tool";
  365. const childToolStep = toolMessage({
  366. id: "child-tool-step",
  367. state: "running",
  368. tool: "Bash",
  369. });
  370. childToolStep.info.time.completed = 30;
  371. childToolStep.info.finish = "tool-calls";
  372. const result = projectSessionSubagents({
  373. revision: 7,
  374. parentSession: session("parent", "interactive"),
  375. messages: [
  376. toolMessage({
  377. childSessionId,
  378. id: "m1",
  379. output:
  380. "Async agent launched successfully.\nagentId: agent-child-tool\nThe agent is working in the background.",
  381. runInBackground: true,
  382. }),
  383. ],
  384. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  385. childMessagesById: new Map([[childSessionId, [childToolStep]]]),
  386. childProjectionsById: new Map(),
  387. parentEvents: [
  388. subagentEvent(SessionEventType.SubagentSpawned, {
  389. agentId: "agent-child-tool",
  390. childSessionId,
  391. parentToolCallId: "call-m1",
  392. description: "Child tool Agent",
  393. }),
  394. ],
  395. });
  396. expect(result.ended).toEqual([]);
  397. expect(result.running).toEqual([
  398. expect.objectContaining({ childSessionId, status: "running" }),
  399. ]);
  400. });
  401. it("does not treat a stream recovery discarded child step as a failed child outcome", () => {
  402. const childSessionId = "sess_subagent_agent-child-discarded";
  403. const discardedStep = toolMessage({ id: "child-discarded", state: "running", tool: "Bash" });
  404. discardedStep.parts = [];
  405. discardedStep.info.time.completed = 30;
  406. discardedStep.info.finish = STREAM_RECOVERY_DISCARDED_FINISH;
  407. discardedStep.info.error = {
  408. name: STREAM_RECOVERY_DISCARDED_ERROR_NAME,
  409. data: { message: "Partial assistant output was discarded before a streaming retry." },
  410. };
  411. const result = projectSessionSubagents({
  412. revision: 8,
  413. parentSession: session("parent", "interactive"),
  414. messages: [
  415. toolMessage({
  416. childSessionId,
  417. id: "m1",
  418. output:
  419. "Async agent launched successfully.\nagentId: agent-child-discarded\nThe agent is working in the background.",
  420. runInBackground: true,
  421. }),
  422. ],
  423. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  424. childMessagesById: new Map([[childSessionId, [discardedStep]]]),
  425. childProjectionsById: new Map(),
  426. parentEvents: [
  427. subagentEvent(SessionEventType.SubagentSpawned, {
  428. agentId: "agent-child-discarded",
  429. childSessionId,
  430. parentToolCallId: "call-m1",
  431. description: "Child discarded Agent",
  432. }),
  433. ],
  434. });
  435. expect(result.ended).toEqual([]);
  436. expect(result.running).toEqual([
  437. expect.objectContaining({ childSessionId, status: "running" }),
  438. ]);
  439. });
  440. describe("leftovers of a previous runtime process", () => {
  441. // 样本时间:父会话里的 Agent 在 t=10 启动,child 最后一步在 t=30、会话最后更新在 t=100,
  442. // 新进程在 t=1000 启动。
  443. const RUNTIME_STARTED_AT = 1_000;
  444. const launchAck = (agentId: string) =>
  445. `Async agent launched successfully.\nagentId: ${agentId}\nThe agent is working in the background.`;
  446. it("ends a background child launched before this process with no live fact as lost", () => {
  447. const childSessionId = "sess_subagent_agent-orphan";
  448. const childToolStep = toolMessage({ id: "child-step", state: "running", tool: "Bash" });
  449. childToolStep.info.time.completed = 30;
  450. childToolStep.info.finish = "tool-calls";
  451. const result = projectSessionSubagents({
  452. revision: 9,
  453. parentSession: session("parent", "interactive"),
  454. messages: [
  455. toolMessage({
  456. childSessionId,
  457. id: "m1",
  458. output: launchAck("agent-orphan"),
  459. runInBackground: true,
  460. }),
  461. ],
  462. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  463. childMessagesById: new Map([[childSessionId, [childToolStep]]]),
  464. childProjectionsById: new Map(),
  465. parentProjection: projection("idle"),
  466. runtimeStartedAt: RUNTIME_STARTED_AT,
  467. });
  468. expect(result.running).toEqual([]);
  469. expect(result.ended).toEqual([
  470. expect.objectContaining({ childSessionId, status: "lost", endedAt: 30 }),
  471. ]);
  472. });
  473. it("ends a foreground Agent part left running by the previous process as lost", () => {
  474. const result = projectSessionSubagents({
  475. revision: 10,
  476. parentSession: session("parent", "interactive"),
  477. messages: [toolMessage({ childSessionId: "child-fg", id: "m1", state: "running" })],
  478. childSessionsById: new Map([["child-fg", session("child-fg")]]),
  479. childMessagesById: new Map(),
  480. childProjectionsById: new Map(),
  481. parentProjection: projection("idle"),
  482. runtimeStartedAt: RUNTIME_STARTED_AT,
  483. });
  484. expect(result.running).toEqual([]);
  485. expect(result.ended).toEqual([
  486. expect.objectContaining({ childSessionId: "child-fg", status: "lost" }),
  487. ]);
  488. });
  489. it("keeps a child running when its session was updated after this process started", () => {
  490. // 另一个进程(例如终端 TUI)仍在运行它:本进程没有活事实,但 child 仍在落盘。
  491. const childSessionId = "sess_subagent_agent-elsewhere";
  492. const child = session(childSessionId);
  493. child.time.updated = RUNTIME_STARTED_AT + 5;
  494. const result = projectSessionSubagents({
  495. revision: 11,
  496. parentSession: session("parent", "interactive"),
  497. messages: [
  498. toolMessage({
  499. childSessionId,
  500. id: "m1",
  501. output: launchAck("agent-elsewhere"),
  502. runInBackground: true,
  503. }),
  504. ],
  505. childSessionsById: new Map([[childSessionId, child]]),
  506. childMessagesById: new Map([[childSessionId, []]]),
  507. childProjectionsById: new Map(),
  508. runtimeStartedAt: RUNTIME_STARTED_AT,
  509. });
  510. expect(result.ended).toEqual([]);
  511. expect(result.running).toEqual([
  512. expect.objectContaining({ childSessionId, status: "running" }),
  513. ]);
  514. });
  515. it("keeps a child resumed in this process running", () => {
  516. const childSessionId = "sess_subagent_agent-resumed";
  517. const resumed = subagentEvent(SessionEventType.SubagentSpawned, {
  518. agentId: "agent-resumed",
  519. childSessionId,
  520. parentToolCallId: "call-m1",
  521. description: "Resumed Agent",
  522. });
  523. resumed.timestamp = new Date(RUNTIME_STARTED_AT + 10);
  524. const result = projectSessionSubagents({
  525. revision: 12,
  526. parentSession: session("parent", "interactive"),
  527. messages: [
  528. toolMessage({
  529. childSessionId,
  530. id: "m1",
  531. output: launchAck("agent-resumed"),
  532. runInBackground: true,
  533. }),
  534. ],
  535. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  536. childMessagesById: new Map([[childSessionId, []]]),
  537. childProjectionsById: new Map(),
  538. parentEvents: [resumed],
  539. runtimeStartedAt: RUNTIME_STARTED_AT,
  540. });
  541. expect(result.ended).toEqual([]);
  542. expect(result.running).toEqual([
  543. expect.objectContaining({ childSessionId, status: "running" }),
  544. ]);
  545. });
  546. it("keeps a known stop of a previous-process Agent instead of relabeling it lost", () => {
  547. // 旧进程正常关闭时停止了它(SubagentStopped(stopped)),child 停在工具调用、没有错误:
  548. // 已知终态优先,不能被「上一代遗留」改写成 lost,结束时间也取 stoppedAt(!3562 评审 SG-01)。
  549. const childSessionId = "sess_subagent_agent-stopped";
  550. const childToolStep = toolMessage({ id: "child-step", state: "running", tool: "Bash" });
  551. childToolStep.info.time.completed = 30;
  552. childToolStep.info.finish = "tool-calls";
  553. const spawned = subagentEvent(SessionEventType.SubagentSpawned, {
  554. agentId: "agent-stopped",
  555. childSessionId,
  556. parentToolCallId: "call-m1",
  557. description: "Stopped Agent",
  558. });
  559. spawned.timestamp = new Date(12);
  560. const stopped = subagentEvent(SessionEventType.SubagentStopped, {
  561. agentId: "agent-stopped",
  562. childSessionId,
  563. parentToolCallId: "call-m1",
  564. status: "stopped",
  565. });
  566. stopped.timestamp = new Date(40);
  567. const result = projectSessionSubagents({
  568. revision: 13,
  569. parentSession: session("parent", "interactive"),
  570. messages: [
  571. toolMessage({
  572. childSessionId,
  573. id: "m1",
  574. output: launchAck("agent-stopped"),
  575. runInBackground: true,
  576. }),
  577. ],
  578. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  579. childMessagesById: new Map([[childSessionId, [childToolStep]]]),
  580. childProjectionsById: new Map(),
  581. parentEvents: [spawned, stopped],
  582. parentProjection: projection("idle"),
  583. runtimeStartedAt: RUNTIME_STARTED_AT,
  584. });
  585. expect(result.running).toEqual([]);
  586. expect(result.ended).toEqual([
  587. expect.objectContaining({ childSessionId, status: "cancelled", endedAt: 40 }),
  588. ]);
  589. });
  590. });
  591. it("lists a sync Agent that failed after its child was ready by its structured identity", () => {
  592. // 读取契约(2026-11-10):error 状态的 part 没有 output,身份只能来自结算写进 part.metadata 的字段;
  593. // 读不到时没有 childSessionId,这条失败的子代理不会出现在子会话目录里。
  594. const childSessionId = createSessionId("subagent_agent-failed");
  595. const result = projectSessionSubagents({
  596. revision: 14,
  597. parentSession: session("parent", "interactive"),
  598. messages: [
  599. toolMessage({
  600. facts: {
  601. agentId: "agent-failed",
  602. outputFile: "/tmp/agents/parent/agent-failed/output.txt",
  603. },
  604. id: "m1",
  605. state: "error",
  606. }),
  607. ],
  608. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  609. childMessagesById: new Map(),
  610. childProjectionsById: new Map(),
  611. });
  612. expect(result.running).toEqual([]);
  613. expect(result.ended).toEqual([expect.objectContaining({ childSessionId, status: "failed" })]);
  614. });
  615. it("does not read the agentId line of a new part's report when the part records its identity", () => {
  616. // 有结构化事实的新 part 不解析文本:旧格式的报告顶格写在 agentId 行之前,报告里自己的 agentId 行
  617. // 排在前面,按文本读会拿到报告里的 id。
  618. const childSessionId = createSessionId("subagent_agent-real");
  619. const result = projectSessionSubagents({
  620. revision: 15,
  621. parentSession: session("parent", "interactive"),
  622. messages: [
  623. toolMessage({
  624. facts: { agentId: "agent-real", outputFile: "/tmp/agents/parent/agent-real/output.txt" },
  625. id: "m1",
  626. output: [
  627. "Report: the module calls an earlier helper.",
  628. "agentId: agent-in-report",
  629. "agentId: agent-real (use SendMessage with to: 'agent-real' to continue this agent)",
  630. ].join("\n"),
  631. }),
  632. ],
  633. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  634. childMessagesById: new Map(),
  635. childProjectionsById: new Map(),
  636. });
  637. expect(result.ended).toEqual([
  638. expect.objectContaining({ agentId: "agent-real", childSessionId }),
  639. ]);
  640. });
  641. it("derives the persisted foreground child id from the completed Agent output agentId", () => {
  642. const result = projectSessionSubagents({
  643. revision: 6,
  644. parentSession: session("parent", "interactive"),
  645. messages: [
  646. toolMessage({
  647. id: "m1",
  648. output: { agentId: "agent-foreground", result: "Finished foreground work" },
  649. }),
  650. ],
  651. childSessionsById: new Map([
  652. ["sess_subagent_agent-foreground", session("sess_subagent_agent-foreground")],
  653. ]),
  654. childMessagesById: new Map(),
  655. childProjectionsById: new Map(),
  656. });
  657. expect(result.ended).toEqual([
  658. expect.objectContaining({
  659. childSessionId: "sess_subagent_agent-foreground",
  660. summary: "Finished foreground work",
  661. status: "success",
  662. }),
  663. ]);
  664. });
  665. it("paginates ended children newest-first with an opaque cursor", () => {
  666. const ended = Array.from({ length: 25 }, (_, index) => ({
  667. childSessionId: `child-${index}`,
  668. subagentType: "Explore",
  669. title: `Child ${index}`,
  670. status: "success" as const,
  671. endedAt: 100 - index,
  672. }));
  673. const first = paginateEndedSubagents(ended, { limit: 20 });
  674. const second = paginateEndedSubagents(ended, { cursor: first.nextCursor, limit: 20 });
  675. expect(first.items).toHaveLength(20);
  676. expect(first.nextCursor).toBeTruthy();
  677. expect(second.items.map((item) => item.childSessionId)).toEqual([
  678. "child-20",
  679. "child-21",
  680. "child-22",
  681. "child-23",
  682. "child-24",
  683. ]);
  684. expect(second.nextCursor).toBeUndefined();
  685. });
  686. });
  687. // 上一代 runtime 写下的终态只在子代理输出目录的 metadata.json 里跨进程保留;冷查询读不到旧进程内存里的
  688. // SubagentStopped(!3562 评审第二轮 CR-01)。样本时间:Agent 在 t=10 启动、child 最后一步 t=30、
  689. // 会话最后更新 t=100;新进程在 t=1000 启动。
  690. describe("previous runtime terminal facts from metadata.json", () => {
  691. const RUNTIME_STARTED_AT = 1_000;
  692. const PARENT_ID = "parent";
  693. let outputRoot = "";
  694. beforeEach(async () => {
  695. outputRoot = await mkdtemp(join(tmpdir(), "zcode-subagent-metadata-"));
  696. });
  697. afterEach(async () => {
  698. await rm(outputRoot, { recursive: true, force: true });
  699. });
  700. const launchAck = (agentId: string, outputDir?: string) =>
  701. [
  702. "Async agent launched successfully. (This tool result is internal metadata.)",
  703. `agentId: ${agentId} (internal ID - do not mention to user.)`,
  704. "The agent is working in the background.",
  705. ...(outputDir ? [`output_file: ${join(outputDir, "output.txt")}`] : []),
  706. ].join("\n");
  707. function childStuckInTool(): MessageWithParts {
  708. const step = toolMessage({ id: "child-step", state: "running", tool: "Bash" });
  709. step.info.time.completed = 30;
  710. step.info.finish = "tool-calls";
  711. return step;
  712. }
  713. function childFailed(): MessageWithParts {
  714. const step = toolMessage({ id: "child-failed", state: "running", tool: "Bash" });
  715. step.parts = [];
  716. step.info.error = { name: "APIError", data: { message: "provider returned 500" } };
  717. return step;
  718. }
  719. function coldInput(agentId: string, runMetadata?: SubagentRunMetadata) {
  720. const childSessionId = createSessionId(`subagent_${agentId}`);
  721. return {
  722. childSessionId,
  723. input: {
  724. revision: 20,
  725. parentSession: session(PARENT_ID, "interactive"),
  726. messages: [
  727. toolMessage({
  728. childSessionId,
  729. id: "m1",
  730. output: launchAck(agentId),
  731. runInBackground: true,
  732. }),
  733. ],
  734. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  735. childMessagesById: new Map([[childSessionId, [childStuckInTool()]]]),
  736. childProjectionsById: new Map(),
  737. runtimeStartedAt: RUNTIME_STARTED_AT,
  738. ...(runMetadata
  739. ? { previousRuntimeRunMetadata: new Map([[childSessionId, runMetadata]]) }
  740. : {}),
  741. },
  742. };
  743. }
  744. it.each([
  745. ["stopped", "cancelled"],
  746. ["failed", "failed"],
  747. ["completed", "success"],
  748. ] as const)(
  749. "projects metadata.json %s of a previous-process Agent without parent events as %s",
  750. (metadataStatus, status) => {
  751. // 正常关闭时 owner 统一 stopTask:metadata.json 写 stopped,child 停在工具调用、没有错误。
  752. const { childSessionId, input } = coldInput("agent-meta", {
  753. status: metadataStatus,
  754. completedAt: 50,
  755. });
  756. const result = projectSessionSubagents(input);
  757. expect(result.running).toEqual([]);
  758. expect(result.ended).toEqual([
  759. expect.objectContaining({ childSessionId, status, endedAt: 50 }),
  760. ]);
  761. },
  762. );
  763. it("keeps lost when metadata.json is still running or missing", () => {
  764. for (const runMetadata of [{ status: "running" } as const, undefined]) {
  765. const { childSessionId, input } = coldInput("agent-meta", runMetadata);
  766. expect(projectSessionSubagents(input).ended).toEqual([
  767. expect.objectContaining({ childSessionId, status: "lost", endedAt: 30 }),
  768. ]);
  769. }
  770. });
  771. it("ends a cold background Agent whose child failed as failed, not success", () => {
  772. // 修复前按 launch ACK 的 completed 判 success(与是否上一代无关的原有问题)。
  773. const { childSessionId, input } = coldInput("agent-child-failed");
  774. const result = projectSessionSubagents({
  775. ...input,
  776. childMessagesById: new Map([[childSessionId, [childFailed()]]]),
  777. runtimeStartedAt: undefined,
  778. });
  779. expect(result.ended).toEqual([expect.objectContaining({ childSessionId, status: "failed" })]);
  780. });
  781. it("ends a background Agent recorded with structured facts by its child, not by the receipt text", () => {
  782. // 新 part 有结构化事实时不解析回执文本:「completed 只表示已启动」取 part.metadata.background。
  783. // 这里的结果文本不是启动回执;按文本判断会把 completed 当成功,child 已失败却显示 success。
  784. const childSessionId = createSessionId("subagent_agent-structured");
  785. const result = projectSessionSubagents({
  786. revision: 20,
  787. parentSession: session(PARENT_ID, "interactive"),
  788. messages: [
  789. toolMessage({
  790. facts: {
  791. agentId: "agent-structured",
  792. background: true,
  793. outputFile: join(outputRoot, PARENT_ID, "agent-structured", "output.txt"),
  794. },
  795. id: "m1",
  796. output: "Launched in the background.",
  797. runInBackground: true,
  798. }),
  799. ],
  800. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  801. childMessagesById: new Map([[childSessionId, [childFailed()]]]),
  802. childProjectionsById: new Map(),
  803. });
  804. expect(result.ended).toEqual([expect.objectContaining({ childSessionId, status: "failed" })]);
  805. });
  806. async function writeMetadata(outputDir: string, agentId: string, status: string) {
  807. await mkdir(outputDir, { recursive: true });
  808. await writeFile(
  809. join(outputDir, "metadata.json"),
  810. JSON.stringify({ agentId, status, completedAt: new Date(50).toISOString() }),
  811. );
  812. }
  813. it("preloads metadata.json from output_file or the configured output root", async () => {
  814. const fromAck = join(outputRoot, "User With Space", "agent-ack");
  815. await writeMetadata(fromAck, "agent-ack", "stopped");
  816. await writeMetadata(join(outputRoot, PARENT_ID, "agent-root"), "agent-root", "failed");
  817. await writeMetadata(join(outputRoot, PARENT_ID, "agent-new"), "agent-new", "stopped");
  818. const launchedNow = toolMessage({
  819. childSessionId: createSessionId("subagent_agent-new"),
  820. id: "m3",
  821. output: launchAck("agent-new"),
  822. runInBackground: true,
  823. });
  824. const newPart = launchedNow.parts[0] as ToolPart;
  825. if ("time" in newPart.state) newPart.state.time.start = RUNTIME_STARTED_AT + 5;
  826. let rootResolutions = 0;
  827. const metadata = await loadPreviousRuntimeRunMetadata({
  828. parentSession: session(PARENT_ID, "interactive"),
  829. messages: [
  830. toolMessage({ id: "m1", output: launchAck("agent-ack", fromAck), runInBackground: true }),
  831. toolMessage({ id: "m2", output: launchAck("agent-root"), runInBackground: true }),
  832. launchedNow,
  833. ],
  834. runtimeStartedAt: RUNTIME_STARTED_AT,
  835. resolveOutputRootDir: () => {
  836. rootResolutions += 1;
  837. return outputRoot;
  838. },
  839. });
  840. expect(metadata.get(createSessionId("subagent_agent-ack"))).toMatchObject({
  841. status: "stopped",
  842. });
  843. expect(metadata.get(createSessionId("subagent_agent-root"))).toMatchObject({
  844. status: "failed",
  845. completedAt: 50,
  846. });
  847. // 本进程启动的 Agent 不是遗留候选,不读。
  848. expect(metadata.has(createSessionId("subagent_agent-new"))).toBe(false);
  849. expect(rootResolutions).toBe(1);
  850. });
  851. it("preloads metadata.json next to the outputFile recorded on the launch part", async () => {
  852. // 新 part 只按结算时记下的 outputFile 找:它可以不在当前配置的输出根目录下(之后改过存储配置、用户目录
  853. // 带空格);回执文本里的 output_file 行与按配置推算的目录都不用。
  854. const recordedDir = join(outputRoot, "User With Space", "agent-recorded");
  855. const receiptDir = join(outputRoot, "receipt", "agent-recorded");
  856. await writeMetadata(recordedDir, "agent-recorded", "stopped");
  857. await writeMetadata(receiptDir, "agent-recorded", "failed");
  858. await writeMetadata(join(outputRoot, PARENT_ID, "agent-recorded"), "agent-recorded", "failed");
  859. let rootResolutions = 0;
  860. const metadata = await loadPreviousRuntimeRunMetadata({
  861. parentSession: session(PARENT_ID, "interactive"),
  862. messages: [
  863. toolMessage({
  864. facts: {
  865. agentId: "agent-recorded",
  866. background: true,
  867. outputFile: join(recordedDir, "output.txt"),
  868. },
  869. id: "m1",
  870. output: launchAck("agent-recorded", receiptDir),
  871. runInBackground: true,
  872. }),
  873. ],
  874. runtimeStartedAt: RUNTIME_STARTED_AT,
  875. resolveOutputRootDir: () => {
  876. rootResolutions += 1;
  877. return outputRoot;
  878. },
  879. });
  880. expect(metadata.get(createSessionId("subagent_agent-recorded"))).toMatchObject({
  881. status: "stopped",
  882. });
  883. expect(rootResolutions).toBe(0);
  884. });
  885. function coldStore(agentId: string, outputDir: string | undefined) {
  886. const childSessionId = createSessionId(`subagent_${agentId}`);
  887. const parent = session(PARENT_ID, "interactive");
  888. const child = { ...session(childSessionId), parentID: PARENT_ID as SessionInfo["id"] };
  889. const messages = new Map<string, MessageWithParts[]>([
  890. [
  891. PARENT_ID,
  892. [
  893. toolMessage({
  894. childSessionId,
  895. id: "m1",
  896. output: launchAck(agentId, outputDir),
  897. runInBackground: true,
  898. }),
  899. ],
  900. ],
  901. [childSessionId, [childStuckInTool()]],
  902. ]);
  903. const sessions = new Map<string, SessionInfo>([
  904. [PARENT_ID, parent],
  905. [childSessionId, child],
  906. ]);
  907. return {
  908. childSessionId,
  909. store: {
  910. async getSession(id: string) {
  911. return sessions.get(id);
  912. },
  913. async messages(input: { sessionID: string }) {
  914. return messages.get(input.sessionID) ?? [];
  915. },
  916. },
  917. };
  918. }
  919. it("projects a normally stopped previous-process Agent as cancelled in the V4 cold query", async () => {
  920. // 真实冷查询:没有 live parent,parentEvents 为空,终态只能从 metadata.json 读。
  921. const outputDir = join(outputRoot, PARENT_ID, "agent-cold");
  922. await writeMetadata(outputDir, "agent-cold", "stopped");
  923. const { childSessionId, store } = coldStore("agent-cold", outputDir);
  924. const result = await listSessionSubagents(
  925. { deps: { sessionStore: store }, sessions: new Map() } as never,
  926. { sessionId: PARENT_ID },
  927. );
  928. expect(result.running).toEqual([]);
  929. expect(result.ended.items).toEqual([
  930. expect.objectContaining({ childSessionId, status: "cancelled", endedAt: 50 }),
  931. ]);
  932. });
  933. it("projects a normally stopped previous-process Agent as cancelled in the TUI observation", async () => {
  934. // launch ACK 不带 output_file:按配置的存储目录 <storage>/cli/agents/<父会话>/<agentId> 找。
  935. const cliRoot = join(outputRoot, "cli");
  936. await writeMetadata(join(cliRoot, "agents", PARENT_ID, "agent-tui"), "agent-tui", "stopped");
  937. const { childSessionId, store } = coldStore("agent-tui", undefined);
  938. const observation = createSubagentObservation({
  939. sessionId: PARENT_ID as never,
  940. sessionStore: store as never,
  941. runtime: {
  942. getSessionEventStore: () => ({
  943. getEvents: async () => [],
  944. getLatestSequenceNumber: async () => 0,
  945. }),
  946. getProjection: async () => undefined,
  947. } as never,
  948. configResult: { config: { storage: { dir: cliRoot } } } as never,
  949. });
  950. const result = await observation.readSubagents();
  951. expect(result.running).toEqual([]);
  952. expect(result.ended.items).toEqual([
  953. expect.objectContaining({ childSessionId, status: "cancelled", endedAt: 50 }),
  954. ]);
  955. });
  956. });
  957. it("cold foreground child uses its newer resumed outcome instead of the original tool end", () => {
  958. const child = toolMessage({ id: "resumed" });
  959. child.parts = [];
  960. child.info.time.completed = 300;
  961. child.info.error = { name: "APIError", data: { message: "new failure" } };
  962. const result = projectSessionSubagents({
  963. revision: 1,
  964. parentSession: session("parent", "interactive"),
  965. messages: [toolMessage({ id: "original", childSessionId: "child" })],
  966. childSessionsById: new Map([["child", session("child")]]),
  967. childMessagesById: new Map([["child", [child]]]),
  968. childProjectionsById: new Map(),
  969. runtimeStartedAt: 1000,
  970. });
  971. expect(result.ended).toEqual([
  972. expect.objectContaining({
  973. childSessionId: "child",
  974. endedAt: 300,
  975. status: "failed",
  976. summary: "new failure",
  977. }),
  978. ]);
  979. });