subagent-session-query.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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 { listSessionSubagents } from "../src/zcode-protocol/server-operations.js";
  19. import {
  20. loadPreviousRuntimeRunMetadata,
  21. paginateEndedSubagents,
  22. projectSessionSubagents,
  23. } from "../src/zcode-protocol/subagent-session-query.js";
  24. function session(id: string, taskType: SessionInfo["taskType"] = "subagent_child"): SessionInfo {
  25. return {
  26. id: id as SessionInfo["id"],
  27. projectID: "project" as SessionInfo["projectID"],
  28. taskType,
  29. slug: id,
  30. directory: "/workspace",
  31. title: id,
  32. version: "test",
  33. time: { created: 1, updated: 100 },
  34. };
  35. }
  36. function toolMessage(input: {
  37. childSessionId?: string;
  38. id: string;
  39. output?: Record<string, unknown> | string;
  40. runInBackground?: boolean;
  41. state?: "completed" | "error" | "running";
  42. tool?: string;
  43. }): MessageWithParts {
  44. const state = input.state ?? "completed";
  45. const common = {
  46. input: {
  47. description: `Description ${input.id}`,
  48. subagent_type: "Explore",
  49. ...(input.runInBackground ? { run_in_background: true } : {}),
  50. },
  51. metadata: input.childSessionId ? { childSessionId: input.childSessionId } : {},
  52. time: state === "running" ? { start: 10 } : { start: 10, end: 20 },
  53. };
  54. const part: ToolPart = {
  55. id: `part-${input.id}` as ToolPart["id"],
  56. sessionID: "parent" as ToolPart["sessionID"],
  57. messageID: input.id as ToolPart["messageID"],
  58. type: "tool",
  59. callID: `call-${input.id}`,
  60. tool: input.tool ?? "Agent",
  61. state:
  62. state === "running"
  63. ? { ...common, status: "running" }
  64. : state === "error"
  65. ? { ...common, status: "error", error: "Provider failed" }
  66. : {
  67. ...common,
  68. status: "completed",
  69. output:
  70. typeof input.output === "string"
  71. ? input.output
  72. : JSON.stringify(input.output ?? { result: `Summary ${input.id}` }),
  73. title: `Description ${input.id}`,
  74. },
  75. };
  76. return {
  77. info: {
  78. id: input.id as never,
  79. sessionID: "parent" as never,
  80. role: "assistant",
  81. time: { created: 10, completed: 20 },
  82. parentID: "user" as never,
  83. modelID: "model" as never,
  84. providerID: "provider" as never,
  85. mode: "build",
  86. agent: "zcode",
  87. path: { cwd: "/workspace", root: "/workspace" },
  88. cost: 0,
  89. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  90. },
  91. parts: [part],
  92. };
  93. }
  94. function projection(status: SessionProjection["status"]): SessionProjection {
  95. return {
  96. id: "child" as never,
  97. createdAt: new Date(1),
  98. updatedAt: new Date(2),
  99. mode: "build",
  100. status,
  101. turnCount: 1,
  102. totalTokenCount: 0,
  103. contextUsed: 0,
  104. contextWindow: 1,
  105. pendingPermissions: [],
  106. pendingSteerInputs: [],
  107. activeToolCalls: [],
  108. streamingToolLedger: [],
  109. backgroundTasks: [],
  110. targetCompletionVerifications: [],
  111. targetCompletionVerificationTimeline: [],
  112. };
  113. }
  114. function subagentEvent(
  115. type: typeof SessionEventType.SubagentSpawned | typeof SessionEventType.SubagentStopped,
  116. payload: Record<string, unknown>,
  117. ): SessionEvent {
  118. return {
  119. id: "event" as never,
  120. sessionId: "parent" as never,
  121. type,
  122. timestamp: new Date(15),
  123. traceId: "trace" as never,
  124. sequenceNumber: 1,
  125. payload,
  126. };
  127. }
  128. describe("subagent session query", () => {
  129. it("projects Agent and legacy Task refs but omits non-persisted children", () => {
  130. const result = projectSessionSubagents({
  131. revision: 3,
  132. parentSession: session("parent", "interactive"),
  133. messages: [
  134. toolMessage({ childSessionId: "child-agent", id: "m1" }),
  135. toolMessage({ childSessionId: "child-task", id: "m2", tool: "Task" }),
  136. toolMessage({ childSessionId: "missing", id: "m3" }),
  137. ],
  138. childSessionsById: new Map([
  139. ["child-agent", session("child-agent")],
  140. ["child-task", session("child-task")],
  141. ]),
  142. childMessagesById: new Map(),
  143. childProjectionsById: new Map(),
  144. });
  145. expect(result.running).toEqual([]);
  146. expect(result.ended.map((item) => item.childSessionId)).toEqual(["child-task", "child-agent"]);
  147. expect(result.ended[0]).toMatchObject({
  148. status: "success",
  149. subagentType: "Explore",
  150. summary: "Summary m2",
  151. });
  152. });
  153. it("uses live child and background state without duplicating the persisted ref", () => {
  154. const parentProjection = projection("running");
  155. parentProjection.backgroundTasks = [
  156. {
  157. taskId: "agent-1",
  158. taskKind: "subagent",
  159. childSessionId: "child-1",
  160. blocked: true,
  161. status: "running",
  162. startedAt: new Date(10),
  163. },
  164. ];
  165. const result = projectSessionSubagents({
  166. revision: 4,
  167. parentSession: session("parent", "interactive"),
  168. messages: [toolMessage({ childSessionId: "child-1", id: "m1", state: "running" })],
  169. childSessionsById: new Map([["child-1", session("child-1")]]),
  170. childMessagesById: new Map(),
  171. childProjectionsById: new Map([["child-1", projection("waiting")]]),
  172. parentProjection,
  173. });
  174. expect(result.ended).toEqual([]);
  175. expect(result.running).toEqual([
  176. expect.objectContaining({ childSessionId: "child-1", status: "blocked" }),
  177. ]);
  178. });
  179. it("uses live spawn events for foreground children before the Agent result is persisted", () => {
  180. const parentProjection = projection("running");
  181. parentProjection.backgroundTasks = [
  182. {
  183. taskId: "agent-live",
  184. taskKind: "subagent",
  185. childSessionId: "child-live",
  186. status: "running",
  187. startedAt: new Date(10),
  188. },
  189. ];
  190. const result = projectSessionSubagents({
  191. revision: 5,
  192. parentSession: session("parent", "interactive"),
  193. messages: [toolMessage({ id: "m1", state: "running" })],
  194. childSessionsById: new Map([["child-live", session("child-live")]]),
  195. childMessagesById: new Map(),
  196. childProjectionsById: new Map(),
  197. parentEvents: [
  198. subagentEvent(SessionEventType.SubagentSpawned, {
  199. agentId: "agent-live",
  200. agentType: "Explore",
  201. childSessionId: "child-live",
  202. parentToolCallId: "call-m1",
  203. description: "Live foreground Agent",
  204. }),
  205. ],
  206. parentProjection,
  207. });
  208. expect(result.running).toEqual([
  209. expect.objectContaining({ childSessionId: "child-live", status: "running" }),
  210. ]);
  211. });
  212. it("keeps a launched background child running when a partial projection omits its task", () => {
  213. const childSessionId = "sess_subagent_agent-keepalive";
  214. const result = projectSessionSubagents({
  215. revision: 6,
  216. parentSession: session("parent", "interactive"),
  217. messages: [
  218. toolMessage({
  219. childSessionId,
  220. id: "m1",
  221. output:
  222. "Async agent launched successfully.\nagentId: agent-keepalive\nThe agent is working in the background.",
  223. runInBackground: true,
  224. }),
  225. ],
  226. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  227. childMessagesById: new Map([[childSessionId, []]]),
  228. childProjectionsById: new Map(),
  229. });
  230. expect(result.ended).toEqual([]);
  231. expect(result.running).toEqual([
  232. expect.objectContaining({ childSessionId, status: "running" }),
  233. ]);
  234. });
  235. it("does not treat a completed child tool-call model step as a terminal child outcome", () => {
  236. const childSessionId = "sess_subagent_agent-child-tool";
  237. const childToolStep = toolMessage({
  238. id: "child-tool-step",
  239. state: "running",
  240. tool: "Bash",
  241. });
  242. childToolStep.info.time.completed = 30;
  243. childToolStep.info.finish = "tool-calls";
  244. const result = projectSessionSubagents({
  245. revision: 7,
  246. parentSession: session("parent", "interactive"),
  247. messages: [
  248. toolMessage({
  249. childSessionId,
  250. id: "m1",
  251. output:
  252. "Async agent launched successfully.\nagentId: agent-child-tool\nThe agent is working in the background.",
  253. runInBackground: true,
  254. }),
  255. ],
  256. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  257. childMessagesById: new Map([[childSessionId, [childToolStep]]]),
  258. childProjectionsById: new Map(),
  259. parentEvents: [
  260. subagentEvent(SessionEventType.SubagentSpawned, {
  261. agentId: "agent-child-tool",
  262. childSessionId,
  263. parentToolCallId: "call-m1",
  264. description: "Child tool Agent",
  265. }),
  266. ],
  267. });
  268. expect(result.ended).toEqual([]);
  269. expect(result.running).toEqual([
  270. expect.objectContaining({ childSessionId, status: "running" }),
  271. ]);
  272. });
  273. it("does not treat a stream recovery discarded child step as a failed child outcome", () => {
  274. const childSessionId = "sess_subagent_agent-child-discarded";
  275. const discardedStep = toolMessage({ id: "child-discarded", state: "running", tool: "Bash" });
  276. discardedStep.parts = [];
  277. discardedStep.info.time.completed = 30;
  278. discardedStep.info.finish = STREAM_RECOVERY_DISCARDED_FINISH;
  279. discardedStep.info.error = {
  280. name: STREAM_RECOVERY_DISCARDED_ERROR_NAME,
  281. data: { message: "Partial assistant output was discarded before a streaming retry." },
  282. };
  283. const result = projectSessionSubagents({
  284. revision: 8,
  285. parentSession: session("parent", "interactive"),
  286. messages: [
  287. toolMessage({
  288. childSessionId,
  289. id: "m1",
  290. output:
  291. "Async agent launched successfully.\nagentId: agent-child-discarded\nThe agent is working in the background.",
  292. runInBackground: true,
  293. }),
  294. ],
  295. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  296. childMessagesById: new Map([[childSessionId, [discardedStep]]]),
  297. childProjectionsById: new Map(),
  298. parentEvents: [
  299. subagentEvent(SessionEventType.SubagentSpawned, {
  300. agentId: "agent-child-discarded",
  301. childSessionId,
  302. parentToolCallId: "call-m1",
  303. description: "Child discarded Agent",
  304. }),
  305. ],
  306. });
  307. expect(result.ended).toEqual([]);
  308. expect(result.running).toEqual([
  309. expect.objectContaining({ childSessionId, status: "running" }),
  310. ]);
  311. });
  312. describe("leftovers of a previous runtime process", () => {
  313. // 样本时间:父会话里的 Agent 在 t=10 启动,child 最后一步在 t=30、会话最后更新在 t=100,
  314. // 新进程在 t=1000 启动。
  315. const RUNTIME_STARTED_AT = 1_000;
  316. const launchAck = (agentId: string) =>
  317. `Async agent launched successfully.\nagentId: ${agentId}\nThe agent is working in the background.`;
  318. it("ends a background child launched before this process with no live fact as lost", () => {
  319. const childSessionId = "sess_subagent_agent-orphan";
  320. const childToolStep = toolMessage({ id: "child-step", state: "running", tool: "Bash" });
  321. childToolStep.info.time.completed = 30;
  322. childToolStep.info.finish = "tool-calls";
  323. const result = projectSessionSubagents({
  324. revision: 9,
  325. parentSession: session("parent", "interactive"),
  326. messages: [
  327. toolMessage({
  328. childSessionId,
  329. id: "m1",
  330. output: launchAck("agent-orphan"),
  331. runInBackground: true,
  332. }),
  333. ],
  334. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  335. childMessagesById: new Map([[childSessionId, [childToolStep]]]),
  336. childProjectionsById: new Map(),
  337. parentProjection: projection("idle"),
  338. runtimeStartedAt: RUNTIME_STARTED_AT,
  339. });
  340. expect(result.running).toEqual([]);
  341. expect(result.ended).toEqual([
  342. expect.objectContaining({ childSessionId, status: "lost", endedAt: 30 }),
  343. ]);
  344. });
  345. it("ends a foreground Agent part left running by the previous process as lost", () => {
  346. const result = projectSessionSubagents({
  347. revision: 10,
  348. parentSession: session("parent", "interactive"),
  349. messages: [toolMessage({ childSessionId: "child-fg", id: "m1", state: "running" })],
  350. childSessionsById: new Map([["child-fg", session("child-fg")]]),
  351. childMessagesById: new Map(),
  352. childProjectionsById: new Map(),
  353. parentProjection: projection("idle"),
  354. runtimeStartedAt: RUNTIME_STARTED_AT,
  355. });
  356. expect(result.running).toEqual([]);
  357. expect(result.ended).toEqual([
  358. expect.objectContaining({ childSessionId: "child-fg", status: "lost" }),
  359. ]);
  360. });
  361. it("keeps a child running when its session was updated after this process started", () => {
  362. // 另一个进程(例如终端 TUI)仍在运行它:本进程没有活事实,但 child 仍在落盘。
  363. const childSessionId = "sess_subagent_agent-elsewhere";
  364. const child = session(childSessionId);
  365. child.time.updated = RUNTIME_STARTED_AT + 5;
  366. const result = projectSessionSubagents({
  367. revision: 11,
  368. parentSession: session("parent", "interactive"),
  369. messages: [
  370. toolMessage({
  371. childSessionId,
  372. id: "m1",
  373. output: launchAck("agent-elsewhere"),
  374. runInBackground: true,
  375. }),
  376. ],
  377. childSessionsById: new Map([[childSessionId, child]]),
  378. childMessagesById: new Map([[childSessionId, []]]),
  379. childProjectionsById: new Map(),
  380. runtimeStartedAt: RUNTIME_STARTED_AT,
  381. });
  382. expect(result.ended).toEqual([]);
  383. expect(result.running).toEqual([
  384. expect.objectContaining({ childSessionId, status: "running" }),
  385. ]);
  386. });
  387. it("keeps a child resumed in this process running", () => {
  388. const childSessionId = "sess_subagent_agent-resumed";
  389. const resumed = subagentEvent(SessionEventType.SubagentSpawned, {
  390. agentId: "agent-resumed",
  391. childSessionId,
  392. parentToolCallId: "call-m1",
  393. description: "Resumed Agent",
  394. });
  395. resumed.timestamp = new Date(RUNTIME_STARTED_AT + 10);
  396. const result = projectSessionSubagents({
  397. revision: 12,
  398. parentSession: session("parent", "interactive"),
  399. messages: [
  400. toolMessage({
  401. childSessionId,
  402. id: "m1",
  403. output: launchAck("agent-resumed"),
  404. runInBackground: true,
  405. }),
  406. ],
  407. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  408. childMessagesById: new Map([[childSessionId, []]]),
  409. childProjectionsById: new Map(),
  410. parentEvents: [resumed],
  411. runtimeStartedAt: RUNTIME_STARTED_AT,
  412. });
  413. expect(result.ended).toEqual([]);
  414. expect(result.running).toEqual([
  415. expect.objectContaining({ childSessionId, status: "running" }),
  416. ]);
  417. });
  418. it("keeps a known stop of a previous-process Agent instead of relabeling it lost", () => {
  419. // 旧进程正常关闭时停止了它(SubagentStopped(stopped)),child 停在工具调用、没有错误:
  420. // 已知终态优先,不能被「上一代遗留」改写成 lost,结束时间也取 stoppedAt(!3562 评审 SG-01)。
  421. const childSessionId = "sess_subagent_agent-stopped";
  422. const childToolStep = toolMessage({ id: "child-step", state: "running", tool: "Bash" });
  423. childToolStep.info.time.completed = 30;
  424. childToolStep.info.finish = "tool-calls";
  425. const spawned = subagentEvent(SessionEventType.SubagentSpawned, {
  426. agentId: "agent-stopped",
  427. childSessionId,
  428. parentToolCallId: "call-m1",
  429. description: "Stopped Agent",
  430. });
  431. spawned.timestamp = new Date(12);
  432. const stopped = subagentEvent(SessionEventType.SubagentStopped, {
  433. agentId: "agent-stopped",
  434. childSessionId,
  435. parentToolCallId: "call-m1",
  436. status: "stopped",
  437. });
  438. stopped.timestamp = new Date(40);
  439. const result = projectSessionSubagents({
  440. revision: 13,
  441. parentSession: session("parent", "interactive"),
  442. messages: [
  443. toolMessage({
  444. childSessionId,
  445. id: "m1",
  446. output: launchAck("agent-stopped"),
  447. runInBackground: true,
  448. }),
  449. ],
  450. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  451. childMessagesById: new Map([[childSessionId, [childToolStep]]]),
  452. childProjectionsById: new Map(),
  453. parentEvents: [spawned, stopped],
  454. parentProjection: projection("idle"),
  455. runtimeStartedAt: RUNTIME_STARTED_AT,
  456. });
  457. expect(result.running).toEqual([]);
  458. expect(result.ended).toEqual([
  459. expect.objectContaining({ childSessionId, status: "cancelled", endedAt: 40 }),
  460. ]);
  461. });
  462. });
  463. it("derives the persisted foreground child id from the completed Agent output agentId", () => {
  464. const result = projectSessionSubagents({
  465. revision: 6,
  466. parentSession: session("parent", "interactive"),
  467. messages: [
  468. toolMessage({
  469. id: "m1",
  470. output: { agentId: "agent-foreground", result: "Finished foreground work" },
  471. }),
  472. ],
  473. childSessionsById: new Map([
  474. ["sess_subagent_agent-foreground", session("sess_subagent_agent-foreground")],
  475. ]),
  476. childMessagesById: new Map(),
  477. childProjectionsById: new Map(),
  478. });
  479. expect(result.ended).toEqual([
  480. expect.objectContaining({
  481. childSessionId: "sess_subagent_agent-foreground",
  482. summary: "Finished foreground work",
  483. status: "success",
  484. }),
  485. ]);
  486. });
  487. it("paginates ended children newest-first with an opaque cursor", () => {
  488. const ended = Array.from({ length: 25 }, (_, index) => ({
  489. childSessionId: `child-${index}`,
  490. subagentType: "Explore",
  491. title: `Child ${index}`,
  492. status: "success" as const,
  493. endedAt: 100 - index,
  494. }));
  495. const first = paginateEndedSubagents(ended, { limit: 20 });
  496. const second = paginateEndedSubagents(ended, { cursor: first.nextCursor, limit: 20 });
  497. expect(first.items).toHaveLength(20);
  498. expect(first.nextCursor).toBeTruthy();
  499. expect(second.items.map((item) => item.childSessionId)).toEqual([
  500. "child-20",
  501. "child-21",
  502. "child-22",
  503. "child-23",
  504. "child-24",
  505. ]);
  506. expect(second.nextCursor).toBeUndefined();
  507. });
  508. });
  509. // 上一代 runtime 写下的终态只在子代理输出目录的 metadata.json 里跨进程保留;冷查询读不到旧进程内存里的
  510. // SubagentStopped(!3562 评审第二轮 CR-01)。样本时间:Agent 在 t=10 启动、child 最后一步 t=30、
  511. // 会话最后更新 t=100;新进程在 t=1000 启动。
  512. describe("previous runtime terminal facts from metadata.json", () => {
  513. const RUNTIME_STARTED_AT = 1_000;
  514. const PARENT_ID = "parent";
  515. let outputRoot = "";
  516. beforeEach(async () => {
  517. outputRoot = await mkdtemp(join(tmpdir(), "zcode-subagent-metadata-"));
  518. });
  519. afterEach(async () => {
  520. await rm(outputRoot, { recursive: true, force: true });
  521. });
  522. const launchAck = (agentId: string, outputDir?: string) =>
  523. [
  524. "Async agent launched successfully. (This tool result is internal metadata.)",
  525. `agentId: ${agentId} (internal ID - do not mention to user.)`,
  526. "The agent is working in the background.",
  527. ...(outputDir ? [`output_file: ${join(outputDir, "output.txt")}`] : []),
  528. ].join("\n");
  529. function childStuckInTool(): MessageWithParts {
  530. const step = toolMessage({ id: "child-step", state: "running", tool: "Bash" });
  531. step.info.time.completed = 30;
  532. step.info.finish = "tool-calls";
  533. return step;
  534. }
  535. function childFailed(): MessageWithParts {
  536. const step = toolMessage({ id: "child-failed", state: "running", tool: "Bash" });
  537. step.parts = [];
  538. step.info.error = { name: "APIError", data: { message: "provider returned 500" } };
  539. return step;
  540. }
  541. function coldInput(agentId: string, runMetadata?: SubagentRunMetadata) {
  542. const childSessionId = createSessionId(`subagent_${agentId}`);
  543. return {
  544. childSessionId,
  545. input: {
  546. revision: 20,
  547. parentSession: session(PARENT_ID, "interactive"),
  548. messages: [
  549. toolMessage({
  550. childSessionId,
  551. id: "m1",
  552. output: launchAck(agentId),
  553. runInBackground: true,
  554. }),
  555. ],
  556. childSessionsById: new Map([[childSessionId, session(childSessionId)]]),
  557. childMessagesById: new Map([[childSessionId, [childStuckInTool()]]]),
  558. childProjectionsById: new Map(),
  559. runtimeStartedAt: RUNTIME_STARTED_AT,
  560. ...(runMetadata
  561. ? { previousRuntimeRunMetadata: new Map([[childSessionId, runMetadata]]) }
  562. : {}),
  563. },
  564. };
  565. }
  566. it.each([
  567. ["stopped", "cancelled"],
  568. ["failed", "failed"],
  569. ["completed", "success"],
  570. ] as const)(
  571. "projects metadata.json %s of a previous-process Agent without parent events as %s",
  572. (metadataStatus, status) => {
  573. // 正常关闭时 owner 统一 stopTask:metadata.json 写 stopped,child 停在工具调用、没有错误。
  574. const { childSessionId, input } = coldInput("agent-meta", {
  575. status: metadataStatus,
  576. completedAt: 50,
  577. });
  578. const result = projectSessionSubagents(input);
  579. expect(result.running).toEqual([]);
  580. expect(result.ended).toEqual([
  581. expect.objectContaining({ childSessionId, status, endedAt: 50 }),
  582. ]);
  583. },
  584. );
  585. it("keeps lost when metadata.json is still running or missing", () => {
  586. for (const runMetadata of [{ status: "running" } as const, undefined]) {
  587. const { childSessionId, input } = coldInput("agent-meta", runMetadata);
  588. expect(projectSessionSubagents(input).ended).toEqual([
  589. expect.objectContaining({ childSessionId, status: "lost", endedAt: 30 }),
  590. ]);
  591. }
  592. });
  593. it("ends a cold background Agent whose child failed as failed, not success", () => {
  594. // 修复前按 launch ACK 的 completed 判 success(与是否上一代无关的原有问题)。
  595. const { childSessionId, input } = coldInput("agent-child-failed");
  596. const result = projectSessionSubagents({
  597. ...input,
  598. childMessagesById: new Map([[childSessionId, [childFailed()]]]),
  599. runtimeStartedAt: undefined,
  600. });
  601. expect(result.ended).toEqual([expect.objectContaining({ childSessionId, status: "failed" })]);
  602. });
  603. async function writeMetadata(outputDir: string, agentId: string, status: string) {
  604. await mkdir(outputDir, { recursive: true });
  605. await writeFile(
  606. join(outputDir, "metadata.json"),
  607. JSON.stringify({ agentId, status, completedAt: new Date(50).toISOString() }),
  608. );
  609. }
  610. it("preloads metadata.json from output_file or the configured output root", async () => {
  611. const fromAck = join(outputRoot, "User With Space", "agent-ack");
  612. await writeMetadata(fromAck, "agent-ack", "stopped");
  613. await writeMetadata(join(outputRoot, PARENT_ID, "agent-root"), "agent-root", "failed");
  614. await writeMetadata(join(outputRoot, PARENT_ID, "agent-new"), "agent-new", "stopped");
  615. const launchedNow = toolMessage({
  616. childSessionId: createSessionId("subagent_agent-new"),
  617. id: "m3",
  618. output: launchAck("agent-new"),
  619. runInBackground: true,
  620. });
  621. const newPart = launchedNow.parts[0] as ToolPart;
  622. if ("time" in newPart.state) newPart.state.time.start = RUNTIME_STARTED_AT + 5;
  623. let rootResolutions = 0;
  624. const metadata = await loadPreviousRuntimeRunMetadata({
  625. parentSession: session(PARENT_ID, "interactive"),
  626. messages: [
  627. toolMessage({ id: "m1", output: launchAck("agent-ack", fromAck), runInBackground: true }),
  628. toolMessage({ id: "m2", output: launchAck("agent-root"), runInBackground: true }),
  629. launchedNow,
  630. ],
  631. runtimeStartedAt: RUNTIME_STARTED_AT,
  632. resolveOutputRootDir: () => {
  633. rootResolutions += 1;
  634. return outputRoot;
  635. },
  636. });
  637. expect(metadata.get(createSessionId("subagent_agent-ack"))).toMatchObject({
  638. status: "stopped",
  639. });
  640. expect(metadata.get(createSessionId("subagent_agent-root"))).toMatchObject({
  641. status: "failed",
  642. completedAt: 50,
  643. });
  644. // 本进程启动的 Agent 不是遗留候选,不读。
  645. expect(metadata.has(createSessionId("subagent_agent-new"))).toBe(false);
  646. expect(rootResolutions).toBe(1);
  647. });
  648. function coldStore(agentId: string, outputDir: string | undefined) {
  649. const childSessionId = createSessionId(`subagent_${agentId}`);
  650. const parent = session(PARENT_ID, "interactive");
  651. const child = { ...session(childSessionId), parentID: PARENT_ID as SessionInfo["id"] };
  652. const messages = new Map<string, MessageWithParts[]>([
  653. [
  654. PARENT_ID,
  655. [
  656. toolMessage({
  657. childSessionId,
  658. id: "m1",
  659. output: launchAck(agentId, outputDir),
  660. runInBackground: true,
  661. }),
  662. ],
  663. ],
  664. [childSessionId, [childStuckInTool()]],
  665. ]);
  666. const sessions = new Map<string, SessionInfo>([
  667. [PARENT_ID, parent],
  668. [childSessionId, child],
  669. ]);
  670. return {
  671. childSessionId,
  672. store: {
  673. async getSession(id: string) {
  674. return sessions.get(id);
  675. },
  676. async messages(input: { sessionID: string }) {
  677. return messages.get(input.sessionID) ?? [];
  678. },
  679. },
  680. };
  681. }
  682. it("projects a normally stopped previous-process Agent as cancelled in the V4 cold query", async () => {
  683. // 真实冷查询:没有 live parent,parentEvents 为空,终态只能从 metadata.json 读。
  684. const outputDir = join(outputRoot, PARENT_ID, "agent-cold");
  685. await writeMetadata(outputDir, "agent-cold", "stopped");
  686. const { childSessionId, store } = coldStore("agent-cold", outputDir);
  687. const result = await listSessionSubagents(
  688. { deps: { sessionStore: store }, sessions: new Map() } as never,
  689. { sessionId: PARENT_ID },
  690. );
  691. expect(result.running).toEqual([]);
  692. expect(result.ended.items).toEqual([
  693. expect.objectContaining({ childSessionId, status: "cancelled", endedAt: 50 }),
  694. ]);
  695. });
  696. it("projects a normally stopped previous-process Agent as cancelled in the TUI observation", async () => {
  697. // launch ACK 不带 output_file:按配置的存储目录 <storage>/cli/agents/<父会话>/<agentId> 找。
  698. const cliRoot = join(outputRoot, "cli");
  699. await writeMetadata(join(cliRoot, "agents", PARENT_ID, "agent-tui"), "agent-tui", "stopped");
  700. const { childSessionId, store } = coldStore("agent-tui", undefined);
  701. const observation = createSubagentObservation({
  702. sessionId: PARENT_ID as never,
  703. sessionStore: store as never,
  704. runtime: {
  705. getSessionEventStore: () => ({
  706. getEvents: async () => [],
  707. getLatestSequenceNumber: async () => 0,
  708. }),
  709. getProjection: async () => undefined,
  710. } as never,
  711. configResult: { config: { storage: { dir: cliRoot } } } as never,
  712. });
  713. const result = await observation.readSubagents();
  714. expect(result.running).toEqual([]);
  715. expect(result.ended.items).toEqual([
  716. expect.objectContaining({ childSessionId, status: "cancelled", endedAt: 50 }),
  717. ]);
  718. });
  719. });