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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. const DEFAULT_AGENTS: AgentSeed[] = [
  55. { agentId: "agent_interrupted", description: "Run the long simulation", child: "tool" },
  56. { agentId: "agent_finished", description: "Collect the results", child: "text" },
  57. { agentId: "agent_notified", description: "Lint the project", child: "tool" },
  58. ];
  59. function assistantInfo(id: string, sessionID: string, completed?: number) {
  60. return {
  61. id,
  62. sessionID,
  63. role: "assistant",
  64. time: { created: OLD.launched, ...(completed ? { completed } : {}) },
  65. parentID: "user-1",
  66. modelID: "model",
  67. providerID: "provider",
  68. mode: "build",
  69. agent: "zcode",
  70. path: { cwd: "/workspace", root: "/workspace" },
  71. cost: 0,
  72. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  73. };
  74. }
  75. async function seedStore(agents: readonly AgentSeed[] = DEFAULT_AGENTS) {
  76. const base = createRecordingMessageStore();
  77. const store = {
  78. ...base,
  79. // 父会话与 child 共用一个内存 store:按 sessionID 取各自的消息。
  80. async messages(input?: { sessionID?: string }) {
  81. const all = await base.messages();
  82. return input?.sessionID ? all.filter((m) => m.info.sessionID === input.sessionID) : all;
  83. },
  84. };
  85. await store.createSession({
  86. id: PARENT_ID,
  87. projectID: "project",
  88. directory: "/workspace",
  89. title: "parent",
  90. version: "test",
  91. time: { created: OLD.created, updated: OLD.childUpdated },
  92. });
  93. await store.saveMessage({
  94. id: "user-1",
  95. sessionID: PARENT_ID,
  96. role: "user",
  97. time: { created: OLD.created },
  98. agent: "zcode",
  99. });
  100. await store.savePart({
  101. id: "user-1-text",
  102. sessionID: PARENT_ID,
  103. messageID: "user-1",
  104. type: "text",
  105. text: "Run the three checks in the background.",
  106. });
  107. await store.saveMessage(assistantInfo("assistant-1", PARENT_ID, OLD.launched));
  108. for (const seed of agents) {
  109. const { agentId, description } = seed;
  110. const launchedAt = seed.launchedAt ?? OLD.launched;
  111. const outputDir = seed.outputDir ?? agentOutputDir(agentId);
  112. await store.savePart({
  113. id: `part-${agentId}`,
  114. sessionID: PARENT_ID,
  115. messageID: "assistant-1",
  116. type: "tool",
  117. callID: `call-${agentId}`,
  118. tool: "Agent",
  119. state: {
  120. status: "completed",
  121. input: { description, prompt: description, run_in_background: true },
  122. output: launchAck(agentId, (seed.ackOutputFile ?? true) ? outputDir : undefined),
  123. title: description,
  124. metadata: {},
  125. time: { start: launchedAt, end: launchedAt + 1 },
  126. },
  127. });
  128. const childId = createSessionId(`subagent_${agentId}`);
  129. await store.createSession({
  130. id: childId,
  131. projectID: "project",
  132. directory: "/workspace",
  133. title: description,
  134. version: "test",
  135. taskType: "subagent_child",
  136. parentID: PARENT_ID,
  137. time: { created: launchedAt, updated: seed.childUpdatedAt ?? OLD.childUpdated },
  138. });
  139. if (seed.metadata) {
  140. await mkdir(outputDir, { recursive: true });
  141. await writeFile(
  142. join(outputDir, "metadata.json"),
  143. JSON.stringify({
  144. agentId,
  145. status: seed.metadata,
  146. description,
  147. ...(seed.resumedAt !== undefined
  148. ? { resumedAt: new Date(seed.resumedAt).toISOString() }
  149. : {}),
  150. }),
  151. );
  152. }
  153. await store.saveMessage({
  154. ...assistantInfo(`${agentId}-last`, childId, OLD.childUpdated),
  155. ...(seed.child === "error"
  156. ? { error: { name: "APIError", data: { message: "provider returned 500" } } }
  157. : {}),
  158. });
  159. await store.savePart(
  160. seed.child === "text"
  161. ? {
  162. id: `${agentId}-last-text`,
  163. sessionID: childId,
  164. messageID: `${agentId}-last`,
  165. type: "text",
  166. text: "All results collected.",
  167. }
  168. : {
  169. id: `${agentId}-last-tool`,
  170. sessionID: childId,
  171. messageID: `${agentId}-last`,
  172. type: "tool",
  173. callID: `${agentId}-bash`,
  174. tool: "Bash",
  175. state: { status: "running", input: { command: "sleep 590" }, time: { start: 1_550 } },
  176. },
  177. );
  178. }
  179. // agent_notified 的终态通知已经送到父会话(例如崩溃前就完成了)。
  180. await store.saveMessage({
  181. id: "user-2",
  182. sessionID: PARENT_ID,
  183. role: "user",
  184. time: { created: OLD.childUpdated },
  185. agent: "zcode",
  186. });
  187. await store.savePart({
  188. id: "user-2-text",
  189. sessionID: PARENT_ID,
  190. messageID: "user-2",
  191. type: "text",
  192. text: "<task-notification>\n<task-id>agent_notified</task-id>\n<status>completed</status>\n</task-notification>",
  193. });
  194. return store;
  195. }
  196. function buildRuntime(
  197. store: Awaited<ReturnType<typeof seedStore>>,
  198. requests: ModelInputMessage[][],
  199. runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry(),
  200. ) {
  201. return createTestAgentRuntime(
  202. PARENT_ID,
  203. { titleGeneration: { enabled: false }, subagents: { outputRootDir: outputRoot } },
  204. {
  205. eventStore: createTestSessionEventStore(),
  206. runtimeTaskRegistry,
  207. sessionStore: store as unknown as SessionStorePort,
  208. modelFactory: createTestModelFactory({
  209. async generateText(request: { messages: ModelInputMessage[] }) {
  210. requests.push(structuredClone(request.messages));
  211. return {
  212. text: "ok",
  213. finishReason: "stop",
  214. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  215. };
  216. },
  217. } as never),
  218. },
  219. );
  220. }
  221. const requestText = (messages: readonly ModelInputMessage[]) =>
  222. messages.map((message) => modelMessageContentToText(message.content)).join("\n");
  223. const NOTICE_HEADLINE = "The previous ZCode runtime process for this workspace exited unexpectedly";
  224. const RUNTIME_EXIT_REASON = "the ZCode runtime process exited before it finished";
  225. /** 恢复后跑一轮,返回这一轮发给模型的文本。 */
  226. async function firstTurnAfterResume(
  227. agents: readonly AgentSeed[],
  228. registry?: InMemoryRuntimeTaskRegistry,
  229. ): Promise<string> {
  230. const store = await seedStore(agents);
  231. const requests: ModelInputMessage[][] = [];
  232. const runtime = buildRuntime(store, requests, registry);
  233. await runtime.resumeFromStore();
  234. await runtime.executeTurn("What happened to the checks?");
  235. return requestText(requests[0]!);
  236. }
  237. describe("previous runtime background agent reconciliation", () => {
  238. it("tells the model on the next turn which background agents the crashed runtime interrupted", async () => {
  239. const store = await seedStore();
  240. const requests: ModelInputMessage[][] = [];
  241. const runtime = buildRuntime(store, requests);
  242. await runtime.resumeFromStore();
  243. // 恢复本身不开新轮:打开会话不消耗 token,也不在内存仍紧张时立刻重新派发。
  244. expect(requests).toHaveLength(0);
  245. await runtime.executeTurn("What happened to the checks?");
  246. const text = requestText(requests[0]!);
  247. expect(text).toContain(
  248. "The previous ZCode runtime process for this workspace exited unexpectedly",
  249. );
  250. expect(text).toContain("<task-id>agent_interrupted</task-id>");
  251. expect(text).toContain("<tool-use-id>call-agent_interrupted</tool-use-id>");
  252. expect(text).toContain("<status>failed</status>");
  253. expect(text).toContain(
  254. 'Agent "Run the long simulation" failed: the ZCode runtime process exited before it finished',
  255. );
  256. // 成功结束的 child 与已收到通知的 child 不报。
  257. expect(text).not.toContain("<task-id>agent_finished</task-id>");
  258. expect(text.match(/<task-id>agent_notified<\/task-id>/g)).toHaveLength(1);
  259. // 提醒按隐藏提醒落盘,作为下次恢复时的去重依据。
  260. const reminderPart = store.savedParts.find(
  261. (part) =>
  262. part.metadata?.runtimeMessage?.source === "task_status" &&
  263. String(part.text).includes("<task-id>agent_interrupted</task-id>"),
  264. );
  265. expect(reminderPart).toBeDefined();
  266. expect(store.savedMessages.find((m) => m.id === reminderPart?.messageID)).toMatchObject({
  267. semantics: { kind: "system_reminder", uiVisibility: "hidden" },
  268. });
  269. });
  270. it("does not repeat the notice after the next resume", async () => {
  271. const store = await seedStore();
  272. const requests: ModelInputMessage[][] = [];
  273. const first = buildRuntime(store, requests);
  274. await first.resumeFromStore();
  275. await first.executeTurn("first turn after crash");
  276. const second = buildRuntime(store, requests);
  277. await second.resumeFromStore();
  278. await second.executeTurn("second turn");
  279. const text = requestText(requests.at(-1)!);
  280. expect(text.match(/<task-id>agent_interrupted<\/task-id>/g)).toHaveLength(1);
  281. });
  282. // 下面每条只放一个 Agent,除被测条件外都满足「被中断」,断言不发提醒(!3562 评审 CR-01、SG-02)。
  283. const interrupted = (overrides: Partial<AgentSeed>): AgentSeed => ({
  284. agentId: "agent_under_test",
  285. description: "Run the long simulation",
  286. child: "tool",
  287. metadata: "running",
  288. ...overrides,
  289. });
  290. it("still reports an agent whose metadata.json was left at running", async () => {
  291. const text = await firstTurnAfterResume([interrupted({})]);
  292. expect(text).toContain(NOTICE_HEADLINE);
  293. expect(text).toContain("<task-id>agent_under_test</task-id>");
  294. });
  295. it("finds metadata.json under the configured output root when the ACK has no output_file", async () => {
  296. // ACK 不带 output_file(父代理没有 Read/Bash)时按 <outputRootDir>/<父会话>/<agentId> 找。
  297. const stopped = await firstTurnAfterResume([
  298. interrupted({ ackOutputFile: false, metadata: "stopped" }),
  299. ]);
  300. expect(stopped).not.toContain(NOTICE_HEADLINE);
  301. const running = await firstTurnAfterResume([interrupted({ ackOutputFile: false })]);
  302. expect(running).toContain("<task-id>agent_under_test</task-id>");
  303. });
  304. it("reads metadata.json from an output_file path that contains spaces", async () => {
  305. // Windows 的用户目录可能带空格;output_file 要取到行尾,且不在默认输出根目录下也要找得到。
  306. const outputDir = join(outputRoot, "User With Space", "agents", "agent_under_test");
  307. const text = await firstTurnAfterResume([interrupted({ outputDir, metadata: "stopped" })]);
  308. expect(text).not.toContain(NOTICE_HEADLINE);
  309. });
  310. it("does not report agents the previous runtime stopped on a normal shutdown", async () => {
  311. // 正常关闭:owner close() 统一 stopTask,metadata.json 改写为 stopped,通知因 shuttingDown 被丢弃。
  312. const text = await firstTurnAfterResume([interrupted({ metadata: "stopped" })]);
  313. expect(text).not.toContain(NOTICE_HEADLINE);
  314. expect(text).not.toContain("<task-id>agent_under_test</task-id>");
  315. });
  316. it("does not relabel an agent that already failed as interrupted by the runtime exit", async () => {
  317. // 已因 provider 错误失败、通知还在内存队列里时进程退出:不能把错误原因改写成 runtime 退出。
  318. const text = await firstTurnAfterResume([interrupted({ metadata: "failed", child: "error" })]);
  319. expect(text).not.toContain(RUNTIME_EXIT_REASON);
  320. expect(text).not.toContain("<task-id>agent_under_test</task-id>");
  321. });
  322. it("does not report an agent whose metadata.json says it completed", async () => {
  323. const text = await firstTurnAfterResume([interrupted({ metadata: "completed" })]);
  324. expect(text).not.toContain(NOTICE_HEADLINE);
  325. });
  326. it("falls back to the child session when metadata.json is missing", async () => {
  327. // 没有 metadata.json(旧版本、目录被清理):child 停在工具调用就报,child 已有终态(失败、完成)就不报。
  328. const text = await firstTurnAfterResume([
  329. interrupted({ agentId: "agent_no_metadata_tool", metadata: undefined }),
  330. interrupted({ agentId: "agent_no_metadata_error", metadata: undefined, child: "error" }),
  331. interrupted({ agentId: "agent_no_metadata_text", metadata: undefined, child: "text" }),
  332. ]);
  333. expect(text).toContain("<task-id>agent_no_metadata_tool</task-id>");
  334. expect(text).not.toContain("<task-id>agent_no_metadata_error</task-id>");
  335. expect(text).not.toContain("<task-id>agent_no_metadata_text</task-id>");
  336. });
  337. // agent_notified 的完成通知写在 OLD.childUpdated(seedStore 里的 user-2)。
  338. it("reports a crash of a SendMessage-resumed run despite the earlier run's notification", async () => {
  339. // 先完成并通知,之后被 SendMessage 恢复(同一个 agentId,metadata.json 改回 running),
  340. // 恢复的运行在进程崩溃时中断:旧通知不能把这次中断挡掉(!3562 评审第二轮 CR-02)。
  341. const text = await firstTurnAfterResume([
  342. interrupted({ agentId: "agent_notified", resumedAt: OLD.childUpdated + 50 }),
  343. ]);
  344. expect(text).toContain(NOTICE_HEADLINE);
  345. expect(text.match(/<task-id>agent_notified<\/task-id>/g)).toHaveLength(2);
  346. expect(text).toContain(RUNTIME_EXIT_REASON);
  347. });
  348. it("still reports an agent that only received a no-progress report before the crash", async () => {
  349. // 无进展提醒(<background-agent-stall>)也带 <task-id>,但它不是终态通知:崩溃前卡住、收到过
  350. // 提醒的 Agent,恢复后仍要报中断(与 !3563 的停滞提醒同时存在时)。
  351. const store = await seedStore([interrupted({})]);
  352. await store.saveMessage({
  353. id: "user-stall",
  354. sessionID: PARENT_ID,
  355. role: "user",
  356. time: { created: OLD.childUpdated },
  357. agent: "zcode",
  358. });
  359. await store.savePart({
  360. id: "user-stall-text",
  361. sessionID: PARENT_ID,
  362. messageID: "user-stall",
  363. type: "text",
  364. text: [
  365. "[SYSTEM NOTIFICATION - NOT USER INPUT]",
  366. "<background-agent-stall>",
  367. " <task-id>agent_under_test</task-id>",
  368. " <no-progress-for-ms>900000</no-progress-for-ms>",
  369. "</background-agent-stall>",
  370. ].join("\n"),
  371. });
  372. const requests: ModelInputMessage[][] = [];
  373. const runtime = buildRuntime(store, requests);
  374. await runtime.resumeFromStore();
  375. await runtime.executeTurn("What happened to the checks?");
  376. const text = requestText(requests[0]!);
  377. expect(text).toContain(NOTICE_HEADLINE);
  378. expect(text).toContain(RUNTIME_EXIT_REASON);
  379. });
  380. it("still treats a notification written after the latest resume as delivered", async () => {
  381. const text = await firstTurnAfterResume([
  382. interrupted({ agentId: "agent_notified", resumedAt: OLD.childUpdated - 50 }),
  383. ]);
  384. expect(text).not.toContain(NOTICE_HEADLINE);
  385. });
  386. it("does not report an agent that this runtime's registry still tracks", async () => {
  387. // 例如在本进程里被 SendMessage 恢复、正在运行。
  388. const registry = new InMemoryRuntimeTaskRegistry();
  389. registry.register({
  390. agentId: "agent_under_test",
  391. agentType: "general-purpose",
  392. description: "Run the long simulation",
  393. isBackgrounded: true,
  394. startedAt: new Date(),
  395. status: "running",
  396. taskId: "agent_under_test",
  397. type: "local_agent",
  398. } as never);
  399. const text = await firstTurnAfterResume([interrupted({})], registry);
  400. expect(text).not.toContain(NOTICE_HEADLINE);
  401. });
  402. it("does not report an agent whose child session was updated after this runtime started", async () => {
  403. // 另一个进程(如终端 TUI)正在运行同一会话,child 持续落盘。
  404. const text = await firstTurnAfterResume([interrupted({ childUpdatedAt: Date.now() })]);
  405. expect(text).not.toContain(NOTICE_HEADLINE);
  406. });
  407. it("does not report an agent launched by this runtime", async () => {
  408. const now = Date.now();
  409. const text = await firstTurnAfterResume([
  410. interrupted({ launchedAt: now, childUpdatedAt: now }),
  411. ]);
  412. expect(text).not.toContain(NOTICE_HEADLINE);
  413. });
  414. });