previous-runtime-agent-reconciliation.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. modelMessageContentToText,
  8. type ModelInputMessage,
  9. type SessionStorePort,
  10. } from "@zcode/contracts";
  11. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  12. import { createTestSessionEventStore } from "./test-event-store.js";
  13. import { createTestModelFactory } from "./test-runtime-model.js";
  14. import { createRecordingMessageStore } from "./runtime-output-token-continuation-test-helpers.js";
  15. import { InMemoryRuntimeTaskRegistry } from "../src/runtime-task/index.js";
  16. import type { SubagentRunMetadataStatus } from "../src/subagent/runner.js";
  17. // 上一代 runtime 进程(如因系统内存耗尽)崩溃后,恢复父会话时对账仍在后台运行的 Agent。
  18. // 样本时间都远早于本测试进程的 performance.timeOrigin,即「上一代进程」留下的记录。
  19. const PARENT_ID = createSessionId("previous-runtime-parent");
  20. const OLD = { created: 1_000, launched: 1_500, childUpdated: 1_600 };
  21. // 每个用例一个临时 Agent 输出根目录,metadata.json 按 runner 的布局放在 <root>/<父会话>/<agentId>/ 下。
  22. let outputRoot = "";
  23. beforeEach(async () => {
  24. outputRoot = await mkdtemp(join(tmpdir(), "zcode-previous-runtime-"));
  25. });
  26. afterEach(async () => {
  27. await rm(outputRoot, { recursive: true, force: true });
  28. });
  29. const agentOutputDir = (agentId: string) => join(outputRoot, PARENT_ID, agentId);
  30. function launchAck(agentId: string, outputDir: string | undefined): string {
  31. return [
  32. "Async agent launched successfully. (This tool result is internal metadata — never quote or paste any part of it, including the agentId below, into a user-facing reply.)",
  33. `agentId: ${agentId} (internal ID - do not mention to user. Use SendMessage with to: '${agentId}', summary: '<5-10 word recap>' to continue this agent.)`,
  34. "The agent is working in the background. You will be notified automatically when it completes.",
  35. ...(outputDir ? [`output_file: ${join(outputDir, "output.txt")}`] : []),
  36. ].join("\n");
  37. }
  38. interface AgentSeed {
  39. agentId: string;
  40. description: string;
  41. /** child 最后一条 assistant:tool 停在工具调用(崩溃时的样子),text 不含工具的完成回复,error 带错误。 */
  42. child: "tool" | "text" | "error";
  43. /** 输出目录 metadata.json 的 status;缺省不写这个文件(旧版本或目录被清理)。 */
  44. metadata?: SubagentRunMetadataStatus;
  45. /** metadata.json 的 resumedAt(毫秒):SendMessage 恢复同一个 agentId 的时间。 */
  46. resumedAt?: number;
  47. /** launch ACK 是否带 output_file;不带时按 runtime 配置的输出根目录找 metadata.json。 */
  48. ackOutputFile?: boolean;
  49. /** 输出目录(ACK 的 output_file 与 metadata.json 所在处);缺省按 runner 布局放在输出根目录下。 */
  50. outputDir?: string;
  51. launchedAt?: number;
  52. childUpdatedAt?: number;
  53. /**
  54. * 新 part:part.metadata 带 Agent 工具结算写下的结构化字段(agentId、childSessionId、outputFile、background)。
  55. * 缺省是升级前写下的旧 part,只有启动回执文本。
  56. */
  57. structured?: boolean;
  58. /** 直接写进 part.metadata 的字段,覆盖 structured 生成的值(如去掉 background、只记 childSessionId)。 */
  59. partMetadata?: Record<string, unknown>;
  60. /** child session id;缺省按 runner 的命名 `sess_subagent_<agentId>`。 */
  61. childSessionId?: string;
  62. /** 启动回执 output_file 行指向的目录;缺省与 outputDir 相同。 */
  63. ackOutputDir?: string;
  64. /** 写进 part.state.metadata 的字段(旧版本可能把 childSessionId 记在这里)。 */
  65. stateMetadata?: Record<string, unknown>;
  66. }
  67. const DEFAULT_AGENTS: AgentSeed[] = [
  68. { agentId: "agent_interrupted", description: "Run the long simulation", child: "tool" },
  69. { agentId: "agent_finished", description: "Collect the results", child: "text" },
  70. { agentId: "agent_notified", description: "Lint the project", child: "tool" },
  71. ];
  72. function assistantInfo(id: string, sessionID: string, completed?: number) {
  73. return {
  74. id,
  75. sessionID,
  76. role: "assistant",
  77. time: { created: OLD.launched, ...(completed ? { completed } : {}) },
  78. parentID: "user-1",
  79. modelID: "model",
  80. providerID: "provider",
  81. mode: "build",
  82. agent: "zcode",
  83. path: { cwd: "/workspace", root: "/workspace" },
  84. cost: 0,
  85. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  86. };
  87. }
  88. async function seedStore(agents: readonly AgentSeed[] = DEFAULT_AGENTS) {
  89. const base = createRecordingMessageStore();
  90. const store = {
  91. ...base,
  92. // 父会话与 child 共用一个内存 store:按 sessionID 取各自的消息。
  93. async messages(input?: { sessionID?: string }) {
  94. const all = await base.messages();
  95. return input?.sessionID ? all.filter((m) => m.info.sessionID === input.sessionID) : all;
  96. },
  97. };
  98. await store.createSession({
  99. id: PARENT_ID,
  100. projectID: "project",
  101. directory: "/workspace",
  102. title: "parent",
  103. version: "test",
  104. time: { created: OLD.created, updated: OLD.childUpdated },
  105. });
  106. await store.saveMessage({
  107. id: "user-1",
  108. sessionID: PARENT_ID,
  109. role: "user",
  110. time: { created: OLD.created },
  111. agent: "zcode",
  112. });
  113. await store.savePart({
  114. id: "user-1-text",
  115. sessionID: PARENT_ID,
  116. messageID: "user-1",
  117. type: "text",
  118. text: "Run the three checks in the background.",
  119. });
  120. await store.saveMessage(assistantInfo("assistant-1", PARENT_ID, OLD.launched));
  121. for (const seed of agents) {
  122. const { agentId, description } = seed;
  123. const launchedAt = seed.launchedAt ?? OLD.launched;
  124. const outputDir = seed.outputDir ?? agentOutputDir(agentId);
  125. const childId = seed.childSessionId ?? createSessionId(`subagent_${agentId}`);
  126. const partMetadata = {
  127. ...(seed.structured
  128. ? {
  129. agentId,
  130. childSessionId: childId,
  131. background: true,
  132. outputFile: join(outputDir, "output.txt"),
  133. }
  134. : {}),
  135. ...seed.partMetadata,
  136. };
  137. await store.savePart({
  138. id: `part-${agentId}`,
  139. sessionID: PARENT_ID,
  140. messageID: "assistant-1",
  141. type: "tool",
  142. callID: `call-${agentId}`,
  143. tool: "Agent",
  144. ...(Object.keys(partMetadata).length > 0 ? { metadata: partMetadata } : {}),
  145. state: {
  146. status: "completed",
  147. input: { description, prompt: description, run_in_background: true },
  148. output: launchAck(
  149. agentId,
  150. (seed.ackOutputFile ?? true) ? (seed.ackOutputDir ?? outputDir) : undefined,
  151. ),
  152. title: description,
  153. metadata: { ...seed.stateMetadata },
  154. time: { start: launchedAt, end: launchedAt + 1 },
  155. },
  156. });
  157. await store.createSession({
  158. id: childId,
  159. projectID: "project",
  160. directory: "/workspace",
  161. title: description,
  162. version: "test",
  163. taskType: "subagent_child",
  164. parentID: PARENT_ID,
  165. time: { created: launchedAt, updated: seed.childUpdatedAt ?? OLD.childUpdated },
  166. });
  167. if (seed.metadata) {
  168. await mkdir(outputDir, { recursive: true });
  169. await writeFile(
  170. join(outputDir, "metadata.json"),
  171. JSON.stringify({
  172. agentId,
  173. status: seed.metadata,
  174. description,
  175. ...(seed.resumedAt !== undefined
  176. ? { resumedAt: new Date(seed.resumedAt).toISOString() }
  177. : {}),
  178. }),
  179. );
  180. }
  181. await store.saveMessage({
  182. ...assistantInfo(`${agentId}-last`, childId, OLD.childUpdated),
  183. ...(seed.child === "error"
  184. ? { error: { name: "APIError", data: { message: "provider returned 500" } } }
  185. : {}),
  186. });
  187. await store.savePart(
  188. seed.child === "text"
  189. ? {
  190. id: `${agentId}-last-text`,
  191. sessionID: childId,
  192. messageID: `${agentId}-last`,
  193. type: "text",
  194. text: "All results collected.",
  195. }
  196. : {
  197. id: `${agentId}-last-tool`,
  198. sessionID: childId,
  199. messageID: `${agentId}-last`,
  200. type: "tool",
  201. callID: `${agentId}-bash`,
  202. tool: "Bash",
  203. state: { status: "running", input: { command: "sleep 590" }, time: { start: 1_550 } },
  204. },
  205. );
  206. }
  207. // agent_notified 的终态通知已经送到父会话(例如崩溃前就完成了)。
  208. await store.saveMessage({
  209. id: "user-2",
  210. sessionID: PARENT_ID,
  211. role: "user",
  212. time: { created: OLD.childUpdated },
  213. agent: "zcode",
  214. });
  215. await store.savePart({
  216. id: "user-2-text",
  217. sessionID: PARENT_ID,
  218. messageID: "user-2",
  219. type: "text",
  220. text: "<task-notification>\n<task-id>agent_notified</task-id>\n<status>completed</status>\n</task-notification>",
  221. });
  222. return store;
  223. }
  224. function buildRuntime(
  225. store: Awaited<ReturnType<typeof seedStore>>,
  226. requests: ModelInputMessage[][],
  227. runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry(),
  228. ) {
  229. return createTestAgentRuntime(
  230. PARENT_ID,
  231. { titleGeneration: { enabled: false }, subagents: { outputRootDir: outputRoot } },
  232. {
  233. eventStore: createTestSessionEventStore(),
  234. runtimeTaskRegistry,
  235. sessionStore: store as unknown as SessionStorePort,
  236. modelFactory: createTestModelFactory({
  237. async generateText(request: { messages: ModelInputMessage[] }) {
  238. requests.push(structuredClone(request.messages));
  239. return {
  240. text: "ok",
  241. finishReason: "stop",
  242. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  243. };
  244. },
  245. } as never),
  246. },
  247. );
  248. }
  249. const requestText = (messages: readonly ModelInputMessage[]) =>
  250. messages.map((message) => modelMessageContentToText(message.content)).join("\n");
  251. const NOTICE_HEADLINE = "The previous ZCode runtime process for this workspace exited unexpectedly";
  252. const RUNTIME_EXIT_REASON = "the ZCode runtime process exited before it finished";
  253. /** 恢复后跑一轮,返回这一轮发给模型的文本。 */
  254. async function firstTurnAfterResume(
  255. agents: readonly AgentSeed[],
  256. registry?: InMemoryRuntimeTaskRegistry,
  257. ): Promise<string> {
  258. const store = await seedStore(agents);
  259. const requests: ModelInputMessage[][] = [];
  260. const runtime = buildRuntime(store, requests, registry);
  261. await runtime.resumeFromStore();
  262. await runtime.executeTurn("What happened to the checks?");
  263. return requestText(requests[0]!);
  264. }
  265. describe("previous runtime background agent reconciliation", () => {
  266. it("tells the model on the next turn which background agents the crashed runtime interrupted", async () => {
  267. const store = await seedStore();
  268. const requests: ModelInputMessage[][] = [];
  269. const runtime = buildRuntime(store, requests);
  270. await runtime.resumeFromStore();
  271. // 恢复本身不开新轮:打开会话不消耗 token,也不在内存仍紧张时立刻重新派发。
  272. expect(requests).toHaveLength(0);
  273. await runtime.executeTurn("What happened to the checks?");
  274. const text = requestText(requests[0]!);
  275. expect(text).toContain(
  276. "The previous ZCode runtime process for this workspace exited unexpectedly",
  277. );
  278. expect(text).toContain("<task-id>agent_interrupted</task-id>");
  279. expect(text).toContain("<tool-use-id>call-agent_interrupted</tool-use-id>");
  280. expect(text).toContain("<status>failed</status>");
  281. expect(text).toContain(
  282. 'Agent "Run the long simulation" failed: the ZCode runtime process exited before it finished',
  283. );
  284. // 成功结束的 child 与已收到通知的 child 不报。
  285. expect(text).not.toContain("<task-id>agent_finished</task-id>");
  286. expect(text.match(/<task-id>agent_notified<\/task-id>/g)).toHaveLength(1);
  287. // 提醒按隐藏提醒落盘,作为下次恢复时的去重依据。
  288. const reminderPart = store.savedParts.find(
  289. (part) =>
  290. part.metadata?.runtimeMessage?.source === "task_status" &&
  291. String(part.text).includes("<task-id>agent_interrupted</task-id>"),
  292. );
  293. expect(reminderPart).toBeDefined();
  294. expect(store.savedMessages.find((m) => m.id === reminderPart?.messageID)).toMatchObject({
  295. semantics: { kind: "system_reminder", uiVisibility: "hidden" },
  296. });
  297. });
  298. it("does not repeat the notice after the next resume", async () => {
  299. const store = await seedStore();
  300. const requests: ModelInputMessage[][] = [];
  301. const first = buildRuntime(store, requests);
  302. await first.resumeFromStore();
  303. await first.executeTurn("first turn after crash");
  304. const second = buildRuntime(store, requests);
  305. await second.resumeFromStore();
  306. await second.executeTurn("second turn");
  307. const text = requestText(requests.at(-1)!);
  308. expect(text.match(/<task-id>agent_interrupted<\/task-id>/g)).toHaveLength(1);
  309. });
  310. // 下面每条只放一个 Agent,除被测条件外都满足「被中断」,断言不发提醒(!3562 评审 CR-01、SG-02)。
  311. const interrupted = (overrides: Partial<AgentSeed>): AgentSeed => ({
  312. agentId: "agent_under_test",
  313. description: "Run the long simulation",
  314. child: "tool",
  315. metadata: "running",
  316. ...overrides,
  317. });
  318. it("still reports an agent whose metadata.json was left at running", async () => {
  319. const text = await firstTurnAfterResume([interrupted({})]);
  320. expect(text).toContain(NOTICE_HEADLINE);
  321. expect(text).toContain("<task-id>agent_under_test</task-id>");
  322. });
  323. it("finds metadata.json under the configured output root when the ACK has no output_file", async () => {
  324. // ACK 不带 output_file(父代理没有 Read/Bash)时按 <outputRootDir>/<父会话>/<agentId> 找。
  325. const stopped = await firstTurnAfterResume([
  326. interrupted({ ackOutputFile: false, metadata: "stopped" }),
  327. ]);
  328. expect(stopped).not.toContain(NOTICE_HEADLINE);
  329. const running = await firstTurnAfterResume([interrupted({ ackOutputFile: false })]);
  330. expect(running).toContain("<task-id>agent_under_test</task-id>");
  331. });
  332. it("reads metadata.json from an output_file path that contains spaces", async () => {
  333. // Windows 的用户目录可能带空格;output_file 要取到行尾,且不在默认输出根目录下也要找得到。
  334. const outputDir = join(outputRoot, "User With Space", "agents", "agent_under_test");
  335. const text = await firstTurnAfterResume([interrupted({ outputDir, metadata: "stopped" })]);
  336. expect(text).not.toContain(NOTICE_HEADLINE);
  337. });
  338. it("does not report agents the previous runtime stopped on a normal shutdown", async () => {
  339. // 正常关闭:owner close() 统一 stopTask,metadata.json 改写为 stopped,通知因 shuttingDown 被丢弃。
  340. const text = await firstTurnAfterResume([interrupted({ metadata: "stopped" })]);
  341. expect(text).not.toContain(NOTICE_HEADLINE);
  342. expect(text).not.toContain("<task-id>agent_under_test</task-id>");
  343. });
  344. it("does not relabel an agent that already failed as interrupted by the runtime exit", async () => {
  345. // 已因 provider 错误失败、通知还在内存队列里时进程退出:不能把错误原因改写成 runtime 退出。
  346. const text = await firstTurnAfterResume([interrupted({ metadata: "failed", child: "error" })]);
  347. expect(text).not.toContain(RUNTIME_EXIT_REASON);
  348. expect(text).not.toContain("<task-id>agent_under_test</task-id>");
  349. });
  350. it("does not report an agent whose metadata.json says it completed", async () => {
  351. const text = await firstTurnAfterResume([interrupted({ metadata: "completed" })]);
  352. expect(text).not.toContain(NOTICE_HEADLINE);
  353. });
  354. it("falls back to the child session when metadata.json is missing", async () => {
  355. // 没有 metadata.json(旧版本、目录被清理):child 停在工具调用就报,child 已有终态(失败、完成)就不报。
  356. const text = await firstTurnAfterResume([
  357. interrupted({ agentId: "agent_no_metadata_tool", metadata: undefined }),
  358. interrupted({ agentId: "agent_no_metadata_error", metadata: undefined, child: "error" }),
  359. interrupted({ agentId: "agent_no_metadata_text", metadata: undefined, child: "text" }),
  360. ]);
  361. expect(text).toContain("<task-id>agent_no_metadata_tool</task-id>");
  362. expect(text).not.toContain("<task-id>agent_no_metadata_error</task-id>");
  363. expect(text).not.toContain("<task-id>agent_no_metadata_text</task-id>");
  364. });
  365. // agent_notified 的完成通知写在 OLD.childUpdated(seedStore 里的 user-2)。
  366. it("reports a crash of a SendMessage-resumed run despite the earlier run's notification", async () => {
  367. // 先完成并通知,之后被 SendMessage 恢复(同一个 agentId,metadata.json 改回 running),
  368. // 恢复的运行在进程崩溃时中断:旧通知不能把这次中断挡掉(!3562 评审第二轮 CR-02)。
  369. const text = await firstTurnAfterResume([
  370. interrupted({ agentId: "agent_notified", resumedAt: OLD.childUpdated + 50 }),
  371. ]);
  372. expect(text).toContain(NOTICE_HEADLINE);
  373. expect(text.match(/<task-id>agent_notified<\/task-id>/g)).toHaveLength(2);
  374. expect(text).toContain(RUNTIME_EXIT_REASON);
  375. });
  376. it("still reports an agent that only received a no-progress report before the crash", async () => {
  377. // 无进展提醒(<background-agent-stall>)也带 <task-id>,但它不是终态通知:崩溃前卡住、收到过
  378. // 提醒的 Agent,恢复后仍要报中断(与 !3563 的停滞提醒同时存在时)。
  379. const store = await seedStore([interrupted({})]);
  380. await store.saveMessage({
  381. id: "user-stall",
  382. sessionID: PARENT_ID,
  383. role: "user",
  384. time: { created: OLD.childUpdated },
  385. agent: "zcode",
  386. });
  387. await store.savePart({
  388. id: "user-stall-text",
  389. sessionID: PARENT_ID,
  390. messageID: "user-stall",
  391. type: "text",
  392. text: [
  393. "[SYSTEM NOTIFICATION - NOT USER INPUT]",
  394. "<background-agent-stall>",
  395. " <task-id>agent_under_test</task-id>",
  396. " <no-progress-for-ms>900000</no-progress-for-ms>",
  397. "</background-agent-stall>",
  398. ].join("\n"),
  399. });
  400. const requests: ModelInputMessage[][] = [];
  401. const runtime = buildRuntime(store, requests);
  402. await runtime.resumeFromStore();
  403. await runtime.executeTurn("What happened to the checks?");
  404. const text = requestText(requests[0]!);
  405. expect(text).toContain(NOTICE_HEADLINE);
  406. expect(text).toContain(RUNTIME_EXIT_REASON);
  407. });
  408. it("still treats a notification written after the latest resume as delivered", async () => {
  409. const text = await firstTurnAfterResume([
  410. interrupted({ agentId: "agent_notified", resumedAt: OLD.childUpdated - 50 }),
  411. ]);
  412. expect(text).not.toContain(NOTICE_HEADLINE);
  413. });
  414. it("does not report an agent that this runtime's registry still tracks", async () => {
  415. // 例如在本进程里被 SendMessage 恢复、正在运行。
  416. const registry = new InMemoryRuntimeTaskRegistry();
  417. registry.register({
  418. agentId: "agent_under_test",
  419. agentType: "general-purpose",
  420. description: "Run the long simulation",
  421. isBackgrounded: true,
  422. startedAt: new Date(),
  423. status: "running",
  424. taskId: "agent_under_test",
  425. type: "local_agent",
  426. } as never);
  427. const text = await firstTurnAfterResume([interrupted({})], registry);
  428. expect(text).not.toContain(NOTICE_HEADLINE);
  429. });
  430. it("does not report an agent whose child session was updated after this runtime started", async () => {
  431. // 另一个进程(如终端 TUI)正在运行同一会话,child 持续落盘。
  432. const text = await firstTurnAfterResume([interrupted({ childUpdatedAt: Date.now() })]);
  433. expect(text).not.toContain(NOTICE_HEADLINE);
  434. });
  435. it("does not report an agent launched by this runtime", async () => {
  436. const now = Date.now();
  437. const text = await firstTurnAfterResume([
  438. interrupted({ launchedAt: now, childUpdatedAt: now }),
  439. ]);
  440. expect(text).not.toContain(NOTICE_HEADLINE);
  441. });
  442. it("finds an old part's child through the childSessionId recorded in its state metadata", async () => {
  443. // 原来的逻辑合并 part.metadata 与 part.state.metadata 取 childSessionId,都没有才按 runner 的命名。
  444. const childSessionId = createSessionId("child_recorded_in_state_metadata");
  445. const text = await firstTurnAfterResume([
  446. interrupted({ childSessionId, stateMetadata: { childSessionId } }),
  447. ]);
  448. expect(text).toContain(NOTICE_HEADLINE);
  449. expect(text).toContain("<task-id>agent_under_test</task-id>");
  450. });
  451. });
  452. // 回归 2026-11-11(!3624):对账按 part.metadata 判断新旧 part。上面的用例都是升级前的旧 part(只有启动回执
  453. // 文本),按原来的逻辑对账;下面是 Agent 工具结算写下结构化字段的新 part:身份、child、输出文件、后台启动都读
  454. // part.metadata,不解析回执文本。样本的回执没有 output_file 行,输出目录不在默认根目录下,child 也不按 runner
  455. // 的命名:只有按 part 上记下的事实才找得到 metadata.json 与 child,走旧逻辑时这里的区分用例会失败。
  456. describe("previous runtime reconciliation of Agent parts with structured launch facts", () => {
  457. const recorded = (overrides: Partial<AgentSeed>): AgentSeed => {
  458. const agentId = overrides.agentId ?? "agent_under_test";
  459. return {
  460. agentId,
  461. description: "Run the long simulation",
  462. child: "tool",
  463. metadata: "running",
  464. structured: true,
  465. ackOutputFile: false,
  466. outputDir: join(outputRoot, "moved storage", agentId),
  467. childSessionId: createSessionId(`recorded_child_${agentId}`),
  468. ...overrides,
  469. };
  470. };
  471. it("reports an interrupted agent from the identity, child and outputFile recorded on the part", async () => {
  472. const text = await firstTurnAfterResume([recorded({})]);
  473. expect(text).toContain(NOTICE_HEADLINE);
  474. expect(text).toContain("<task-id>agent_under_test</task-id>");
  475. expect(text).toContain("<tool-use-id>call-agent_under_test</tool-use-id>");
  476. expect(text).toContain(RUNTIME_EXIT_REASON);
  477. // 提醒里的输出文件是 part 上记下的路径,回执文本里没有这一行。
  478. const outputFile = join(outputRoot, "moved storage", "agent_under_test", "output.txt");
  479. expect(text).toContain(`<output-file>${outputFile}</output-file>`);
  480. });
  481. it.each<[string, Partial<AgentSeed>]>([
  482. ["metadata.json next to the recorded outputFile says stopped", { metadata: "stopped" }],
  483. ["metadata.json next to the recorded outputFile says completed", { metadata: "completed" }],
  484. ["the agent already failed", { metadata: "failed", child: "error" }],
  485. // 前台 Agent 的报告正好以启动回执开头(例如 child 转述了它派出的后台 Agent):后台启动只看 background。
  486. [
  487. "the part has no background flag although its text starts with the launch receipt",
  488. { partMetadata: { background: undefined } },
  489. ],
  490. ["its child session was updated after this runtime started", { childUpdatedAt: Date.now() }],
  491. ["this runtime launched it", { launchedAt: Date.now(), childUpdatedAt: Date.now() }],
  492. ])("does not report a recorded agent when %s", async (_condition, overrides) => {
  493. const text = await firstTurnAfterResume([recorded(overrides)]);
  494. expect(text).not.toContain(NOTICE_HEADLINE);
  495. expect(text).not.toContain("<task-id>agent_under_test</task-id>");
  496. });
  497. it("falls back to the recorded child session when metadata.json is missing", async () => {
  498. const text = await firstTurnAfterResume([
  499. recorded({ agentId: "agent_no_metadata_tool", metadata: undefined }),
  500. recorded({ agentId: "agent_no_metadata_error", metadata: undefined, child: "error" }),
  501. recorded({ agentId: "agent_no_metadata_text", metadata: undefined, child: "text" }),
  502. ]);
  503. expect(text).toContain("<task-id>agent_no_metadata_tool</task-id>");
  504. expect(text).not.toContain("<task-id>agent_no_metadata_error</task-id>");
  505. expect(text).not.toContain("<task-id>agent_no_metadata_text</task-id>");
  506. });
  507. it("dedupes a recorded agent by its latest run", async () => {
  508. // agent_notified 的完成通知写在 OLD.childUpdated:恢复晚于它时,这次运行的中断仍要报;早于它时算已通知。
  509. const resumedAfter = await firstTurnAfterResume([
  510. recorded({ agentId: "agent_notified", resumedAt: OLD.childUpdated + 50 }),
  511. ]);
  512. expect(resumedAfter.match(/<task-id>agent_notified<\/task-id>/g)).toHaveLength(2);
  513. const resumedBefore = await firstTurnAfterResume([
  514. recorded({ agentId: "agent_notified", resumedAt: OLD.childUpdated - 50 }),
  515. ]);
  516. expect(resumedBefore).not.toContain(NOTICE_HEADLINE);
  517. });
  518. it("does not report a recorded agent that this runtime's registry still tracks", async () => {
  519. const registry = new InMemoryRuntimeTaskRegistry();
  520. registry.register({
  521. agentId: "agent_under_test",
  522. agentType: "general-purpose",
  523. description: "Run the long simulation",
  524. isBackgrounded: true,
  525. startedAt: new Date(),
  526. status: "running",
  527. taskId: "agent_under_test",
  528. type: "local_agent",
  529. } as never);
  530. const text = await firstTurnAfterResume([recorded({})], registry);
  531. expect(text).not.toContain(NOTICE_HEADLINE);
  532. });
  533. it("treats a part without the recorded outputFile as an old part and reads its receipt", async () => {
  534. // 判据与子会话目录查询相同:agentId、childSessionId、outputFile 三项都在才是新 part。缺一项就按原来的逻辑
  535. // 读回执(output_file 行、默认输出根目录),child 仍取 part 上记下的 childSessionId。
  536. const childSessionId = createSessionId("recorded_child_without_output_file");
  537. const text = await firstTurnAfterResume([
  538. {
  539. agentId: "agent_under_test",
  540. description: "Run the long simulation",
  541. child: "tool",
  542. metadata: "running",
  543. childSessionId,
  544. partMetadata: { agentId: "agent_under_test", childSessionId, background: true },
  545. },
  546. ]);
  547. expect(text).toContain("<task-id>agent_under_test</task-id>");
  548. const outputFile = join(agentOutputDir("agent_under_test"), "output.txt");
  549. expect(text).toContain(`<output-file>${outputFile}</output-file>`);
  550. });
  551. it("reads metadata.json next to the recorded outputFile, not the receipt's output_file line", async () => {
  552. // 回执的 output_file 行指向另一个目录,那里的 metadata.json 还停在 running;part 上记下的目录里是 stopped。
  553. // 新 part 只读记下的 outputFile,按 stopped 不报;走旧逻辑会先读回执的目录,误报中断。
  554. const ackOutputDir = join(outputRoot, "receipt dir", "agent_under_test");
  555. await mkdir(ackOutputDir, { recursive: true });
  556. await writeFile(
  557. join(ackOutputDir, "metadata.json"),
  558. JSON.stringify({ agentId: "agent_under_test", status: "running" }),
  559. );
  560. const text = await firstTurnAfterResume([
  561. recorded({ metadata: "stopped", ackOutputFile: true, ackOutputDir }),
  562. ]);
  563. expect(text).not.toContain(NOTICE_HEADLINE);
  564. expect(text).not.toContain("<task-id>agent_under_test</task-id>");
  565. });
  566. it("reports an old part and a new part interrupted by the same crash", async () => {
  567. // 升级后第一次打开的会话里,升级前与升级后派出的后台 Agent 可以同时在:各按各的事实对账,提醒都在同一条里。
  568. const text = await firstTurnAfterResume([
  569. {
  570. agentId: "agent_old_part",
  571. description: "Run the old check",
  572. child: "tool",
  573. metadata: "running",
  574. },
  575. recorded({ agentId: "agent_new_part" }),
  576. ]);
  577. expect(text.match(new RegExp(NOTICE_HEADLINE, "g"))).toHaveLength(1);
  578. const oldOutputFile = join(agentOutputDir("agent_old_part"), "output.txt");
  579. const newOutputFile = join(outputRoot, "moved storage", "agent_new_part", "output.txt");
  580. expect(text).toContain("<task-id>agent_old_part</task-id>");
  581. expect(text).toContain("<tool-use-id>call-agent_old_part</tool-use-id>");
  582. expect(text).toContain(`<output-file>${oldOutputFile}</output-file>`);
  583. expect(text).toContain("<task-id>agent_new_part</task-id>");
  584. expect(text).toContain(`<output-file>${newOutputFile}</output-file>`);
  585. });
  586. });