subagent-send-now-background.test.ts 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. import { describe, expect, it, onTestFinished } from "vitest";
  2. import {
  3. CoreErrorType,
  4. InMemorySessionEventStore,
  5. SessionEventType,
  6. createInputPreemptionAbortReason,
  7. createModelId,
  8. createModelProviderId,
  9. createSessionId,
  10. createTurnId,
  11. isInputPreemptionAbortReason,
  12. type InputPreemptionControl,
  13. type InputPreemptionHandling,
  14. type SessionEvent,
  15. type SessionEventStorePort,
  16. type SessionId,
  17. } from "@zcode/contracts";
  18. import { createExploreSubagentPort } from "../src/subagent/runner.js";
  19. import {
  20. InMemoryRuntimeTaskRegistry,
  21. isTerminalRuntimeTask,
  22. type RuntimeTaskSnapshot,
  23. } from "../src/runtime-task/registry.js";
  24. import {
  25. ToolDeadline,
  26. createInputPreemptionSlot,
  27. executeWithTimeout,
  28. } from "../src/tool/executor/timeout.js";
  29. import type { ToolEntry, ToolExecutionContext } from "../src/tool/types.js";
  30. import type { OffPeakLifecycleEvent } from "../src/runtime/off-peak/lifecycle.js";
  31. import { USER_STOPPED_TOOL_RESULT_CONTENT } from "../src/runtime/methods/interrupt-marker.js";
  32. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  33. import { createTestSessionEventStore } from "./test-event-store.js";
  34. import { createTestModelSelection } from "./test-model-selection.js";
  35. import { createTestModelFactory } from "./test-runtime-model.js";
  36. // 立即发送抢占前台 Agent:只有前台等待中(child 运行中)才转后台,结果经 task-notification 送回;
  37. // 启动阶段、收尾阶段(child 已出结果)、禁止后台、任务已结束和其他停止照旧取消。
  38. // 闲时运行允许后台,同样转后台。每个用例结束都关闭它建的 port / runtime。
  39. // 规格见 apps/zcode-cli/docs/design/v2/loop/turn-steering.md「前台子代理转后台」。
  40. const SEND_NOW_REASON = "v4 sendQueuedNow preempts active turn";
  41. const ASYNC_LAUNCHED_TEXT = "Async agent launched successfully";
  42. const AGENT_CANCELLED_TEXT = "Agent was cancelled before the subagent returned findings";
  43. const INTERRUPT_MARKER_PREFIX = "[Request interrupted by user";
  44. const FINISHED_CHILD_RESULT = "child result finished before send-now";
  45. const INACTIVITY_TIMEOUT_MS = 50;
  46. describe("send-now preemption of foreground subagents", () => {
  47. describe("subagent runner", () => {
  48. it("moves a ready foreground agent to background and keeps the child running", async () => {
  49. const sessionId = createSessionId("send-now-background-runner");
  50. const turnId = createTurnId("send-now-background-runner-turn");
  51. const parent = new AbortController();
  52. const preemption = createExecutorPreemption(parent.signal);
  53. const childReady = createDeferred<void>();
  54. const childGate = createDeferred<void>();
  55. const notifications: Array<{ text: string }> = [];
  56. let childSignal: AbortSignal | undefined;
  57. const port = createExploreSubagentPort({
  58. createAgentId: () => "agent_send_now_background",
  59. emitParentEvent: async () => {},
  60. enqueueParentTaskNotification: (notification) => {
  61. notifications.push(notification);
  62. },
  63. runExploreAgent: async (request, options) => {
  64. childSignal = options?.signal;
  65. await request.onSessionReady?.();
  66. childReady.resolve();
  67. await childGate.promise;
  68. return { events: [], response: "child finished after send-now", traceId: "trace_child" };
  69. },
  70. });
  71. onTestFinished(async () => {
  72. childGate.resolve();
  73. await port.close?.();
  74. });
  75. const run = port.run(createRunRequest(sessionId, turnId), {
  76. signal: parent.signal,
  77. inputPreemption: preemption.control,
  78. });
  79. await childReady.promise;
  80. parent.abort(createInputPreemptionAbortReason(SEND_NOW_REASON));
  81. // executor 先调用判断函数(转后台),runner 在同一次 abort 里读到同一个结果。
  82. expect(preemption.decision()).toBe("wait");
  83. await expect(run).resolves.toMatchObject({
  84. status: "async_launched",
  85. agentId: "agent_send_now_background",
  86. });
  87. expect(childSignal?.aborted).toBe(false);
  88. expect(await port.getTask?.("agent_send_now_background")).toMatchObject({
  89. isBackgrounded: true,
  90. status: "running",
  91. });
  92. childGate.resolve();
  93. await waitForCondition(() => notifications.length === 1);
  94. expect(notifications[0]?.text).toContain("<status>completed</status>");
  95. expect(notifications[0]?.text).toContain("<result>child finished after send-now</result>");
  96. });
  97. it("cancels as before when the caller passes no preemption control", async () => {
  98. const parent = new AbortController();
  99. const { port, childReady, childSignal } = createGatedPort("agent_without_control");
  100. const run = port.run(
  101. createRunRequest(createSessionId("no-control"), createTurnId("no-control-turn")),
  102. { signal: parent.signal },
  103. );
  104. await childReady.promise;
  105. parent.abort(createInputPreemptionAbortReason(SEND_NOW_REASON));
  106. await expect(run).rejects.toMatchObject({ type: CoreErrorType.ToolCancelled });
  107. expect(childSignal()?.aborted).toBe(true);
  108. expect(await port.getTask?.("agent_without_control")).toMatchObject({
  109. isBackgrounded: false,
  110. });
  111. });
  112. it("cancels a ready foreground agent when the parent stops for another reason", async () => {
  113. const parent = new AbortController();
  114. const preemption = createExecutorPreemption(parent.signal);
  115. const { port, childReady, childSignal } = createGatedPort("agent_plain_stop");
  116. const run = port.run(
  117. createRunRequest(createSessionId("plain-stop"), createTurnId("plain-stop-turn")),
  118. { signal: parent.signal, inputPreemption: preemption.control },
  119. );
  120. await childReady.promise;
  121. parent.abort(new Error("v4 session stopped"));
  122. await expect(run).rejects.toMatchObject({ type: CoreErrorType.ToolCancelled });
  123. expect(childSignal()?.aborted).toBe(true);
  124. });
  125. it("cancels a foreground agent preempted before its child session is ready", async () => {
  126. const parent = new AbortController();
  127. const preemption = createExecutorPreemption(parent.signal);
  128. const childStarted = createDeferred<void>();
  129. let childSignal: AbortSignal | undefined;
  130. const port = createExploreSubagentPort({
  131. createAgentId: () => "agent_preempted_during_startup",
  132. emitParentEvent: async () => {},
  133. runExploreAgent: async (_request, options) => {
  134. childSignal = options?.signal;
  135. childStarted.resolve();
  136. // 启动阶段永不就绪:只有取消才能结束这次 Agent 调用。
  137. await new Promise<void>((resolve) => {
  138. options?.signal?.addEventListener("abort", () => resolve(), { once: true });
  139. });
  140. throw options?.signal?.reason ?? new Error("child aborted");
  141. },
  142. });
  143. onTestFinished(() => port.close?.());
  144. const run = port.run(
  145. createRunRequest(createSessionId("startup-preempt"), createTurnId("startup-preempt-turn")),
  146. { signal: parent.signal, inputPreemption: preemption.control },
  147. );
  148. await childStarted.promise;
  149. parent.abort(createInputPreemptionAbortReason(SEND_NOW_REASON));
  150. // 启动阶段的判断是 cancel:executor 立即判取消,不等 runner。
  151. expect(preemption.decision()).toBe("cancel");
  152. await expect(run).rejects.toMatchObject({ type: CoreErrorType.ToolCancelled });
  153. expect(childSignal?.aborted).toBe(true);
  154. });
  155. it("cancels a foreground agent whose run does not allow background", async () => {
  156. const parent = new AbortController();
  157. const preemption = createExecutorPreemption(parent.signal);
  158. const { port, childReady, childSignal } = createGatedPort("agent_background_denied");
  159. const run = port.run(
  160. createRunRequest(createSessionId("deny-preempt"), createTurnId("deny-preempt-turn")),
  161. {
  162. signal: parent.signal,
  163. modelOverride: { background: "deny" } as never,
  164. inputPreemption: preemption.control,
  165. },
  166. );
  167. await childReady.promise;
  168. parent.abort(createInputPreemptionAbortReason(SEND_NOW_REASON));
  169. await expect(run).rejects.toMatchObject({ type: CoreErrorType.ToolCancelled });
  170. expect(preemption.decision()).toBe("cancel");
  171. expect(childSignal()?.aborted).toBe(true);
  172. });
  173. it.each([
  174. { outcome: "completed", fail: false },
  175. { outcome: "failed", fail: true },
  176. ])(
  177. "does not claim a foreground agent whose child already $outcome",
  178. async ({ outcome, fail }) => {
  179. const parent = new AbortController();
  180. const preemption = createExecutorPreemption(parent.signal);
  181. const notifications: Array<{ text: string }> = [];
  182. const agentId = `agent_${outcome}_before_send_now`;
  183. // child 已完成或失败,runner 已写完结果文件、正要把任务改成终态:前台等待已结束,registry
  184. // 仍是 running,requestBackground 仍会成功,只有认领开关能拒绝。
  185. const registry = new BeforeTerminalRegistry(() => {
  186. parent.abort(createInputPreemptionAbortReason(SEND_NOW_REASON));
  187. });
  188. const port = createExploreSubagentPort({
  189. createAgentId: () => agentId,
  190. emitParentEvent: async () => {},
  191. enqueueParentTaskNotification: (notification) => {
  192. notifications.push(notification);
  193. },
  194. runtimeTaskRegistry: registry,
  195. runExploreAgent: async (request) => {
  196. await request.onSessionReady?.();
  197. if (fail) throw new Error("provider failed before send-now");
  198. return { events: [], response: "finished before send-now", traceId: "trace_child" };
  199. },
  200. });
  201. onTestFinished(() => port.close?.());
  202. const run = port.run(
  203. createRunRequest(createSessionId(`settle-${outcome}`), createTurnId(`settle-${outcome}`)),
  204. { signal: parent.signal, inputPreemption: preemption.control },
  205. );
  206. // executor 按 cancel 立即判取消;runner 照常在前台写完收尾,不转后台、不发通知。
  207. await (fail ? expect(run).rejects.toBeDefined() : expect(run).resolves.toBeDefined());
  208. expect(preemption.decision()).toBe("cancel");
  209. expect(await port.getTask?.(agentId)).toMatchObject({
  210. isBackgrounded: false,
  211. status: outcome,
  212. });
  213. expect(notifications).toHaveLength(0);
  214. },
  215. );
  216. it("cancels a foreground agent whose task was already stopped", async () => {
  217. const parent = new AbortController();
  218. const preemption = createExecutorPreemption(parent.signal);
  219. const childReady = createDeferred<void>();
  220. const port = createExploreSubagentPort({
  221. createAgentId: () => "agent_stopped_before_send_now",
  222. emitParentEvent: async () => {},
  223. enqueueParentTaskNotification: () => {},
  224. runExploreAgent: async (request, options) => {
  225. await request.onSessionReady?.();
  226. childReady.resolve();
  227. await new Promise<void>((resolve) => {
  228. options?.signal?.addEventListener("abort", () => resolve(), { once: true });
  229. });
  230. throw options?.signal?.reason ?? new Error("child aborted");
  231. },
  232. });
  233. onTestFinished(() => port.close?.());
  234. const run = port.run(
  235. createRunRequest(createSessionId("stopped-preempt"), createTurnId("stopped-preempt-turn")),
  236. { signal: parent.signal, inputPreemption: preemption.control },
  237. );
  238. await childReady.promise;
  239. // 单项停止同步提交 killed 后,同一段代码里立即发送到达:前台等待还在,但任务已结束,不能再转后台。
  240. const stopping = port.stopTask?.("agent_stopped_before_send_now");
  241. parent.abort(createInputPreemptionAbortReason(SEND_NOW_REASON));
  242. expect(preemption.decision()).toBe("cancel");
  243. await stopping;
  244. // 取消结果来自单项停止:与就绪后的单项停止相同,不是转后台。
  245. await expect(run).rejects.toMatchObject({
  246. type: CoreErrorType.ToolCancelled,
  247. message: "Subagent was stopped by user",
  248. });
  249. expect(await port.getTask?.("agent_stopped_before_send_now")).toMatchObject({
  250. isBackgrounded: false,
  251. });
  252. });
  253. it.each([
  254. {
  255. outcome: "completed",
  256. fail: false,
  257. expected: "<result>finished right after the move</result>",
  258. },
  259. { outcome: "failed", fail: true, expected: "failed: provider failed right after the move" },
  260. ])(
  261. "keeps the background branch when the child $outcome right after the move",
  262. async ({ outcome, fail, expected }) => {
  263. const parent = new AbortController();
  264. const preemption = createExecutorPreemption(parent.signal);
  265. const childReady = createDeferred<void>();
  266. const childGate = createDeferred<void>();
  267. const notifications: Array<{ text: string }> = [];
  268. const agentId = `agent_moved_then_${outcome}`;
  269. const registry = new CompletionFirstRegistry();
  270. const port = createExploreSubagentPort({
  271. createAgentId: () => agentId,
  272. emitParentEvent: async () => {},
  273. enqueueParentTaskNotification: (notification) => {
  274. notifications.push(notification);
  275. },
  276. // 模拟同一轮微任务里 child 的结果先被 race 选中:转后台请求的等待永不先返回。
  277. runtimeTaskRegistry: registry,
  278. runExploreAgent: async (request) => {
  279. await request.onSessionReady?.();
  280. childReady.resolve();
  281. await childGate.promise;
  282. if (fail) throw new Error("provider failed right after the move");
  283. return {
  284. events: [],
  285. response: "finished right after the move",
  286. traceId: "trace_child",
  287. };
  288. },
  289. });
  290. onTestFinished(async () => {
  291. childGate.resolve();
  292. await port.close?.();
  293. });
  294. const run = port.run(
  295. createRunRequest(createSessionId(`moved-then-${outcome}`), createTurnId("moved-turn")),
  296. { signal: parent.signal, inputPreemption: preemption.control },
  297. );
  298. await childReady.promise;
  299. parent.abort(createInputPreemptionAbortReason(SEND_NOW_REASON));
  300. expect(preemption.decision()).toBe("wait");
  301. childGate.resolve();
  302. // registry 已标为后台:完成和失败都走后台分支,结果经 task-notification 送回,不在前台返回。
  303. await expect(run).resolves.toMatchObject({ status: "async_launched" });
  304. await waitForCondition(() => notifications.length === 1);
  305. expect(notifications[0]?.text).toContain(`<status>${outcome}</status>`);
  306. expect(notifications[0]?.text).toContain(expected);
  307. expect(registry.get(agentId)).toMatchObject({ isBackgrounded: true, status: outcome });
  308. },
  309. );
  310. it("finishes a moved agent with the known error when the wait ends by inactivity timeout", async () => {
  311. const parent = new AbortController();
  312. const preemption = createExecutorPreemption(parent.signal);
  313. const childReady = createDeferred<void>();
  314. const childRelease = createDeferred<void>();
  315. const notifications: Array<{ text: string }> = [];
  316. const agentId = "agent_moved_then_timed_out";
  317. const registry = new CompletionFirstRegistry();
  318. const port = createExploreSubagentPort({
  319. createAgentId: () => agentId,
  320. emitParentEvent: async () => {},
  321. enqueueParentTaskNotification: (notification) => {
  322. notifications.push(notification);
  323. },
  324. inactivityTimeoutMs: INACTIVITY_TIMEOUT_MS,
  325. runtimeTaskRegistry: registry,
  326. runExploreAgent: async (request) => {
  327. await request.onSessionReady?.();
  328. childReady.resolve();
  329. // child 不响应取消,用例结束前一直不返回:只有按已知错误收尾才会有通知。
  330. await childRelease.promise;
  331. throw new Error("child released after the test");
  332. },
  333. });
  334. onTestFinished(async () => {
  335. childRelease.resolve();
  336. await port.close?.();
  337. });
  338. const run = port.run(
  339. createRunRequest(createSessionId("moved-then-timed-out"), createTurnId("timed-out-turn")),
  340. { signal: parent.signal, inputPreemption: preemption.control },
  341. );
  342. await childReady.promise;
  343. parent.abort(createInputPreemptionAbortReason(SEND_NOW_REASON));
  344. expect(preemption.decision()).toBe("wait");
  345. // 等待随后因闲置超时以异常结束;registry 已标为后台,按超时错误直接在后台收尾。
  346. await expect(run).resolves.toMatchObject({ status: "async_launched" });
  347. await waitForCondition(() => notifications.length === 1);
  348. expect(notifications[0]?.text).toContain("<status>failed</status>");
  349. expect(notifications[0]?.text).toContain(
  350. `Subagent was inactive for ${INACTIVITY_TIMEOUT_MS}ms`,
  351. );
  352. expect(registry.get(agentId)).toMatchObject({ isBackgrounded: true, status: "failed" });
  353. });
  354. });
  355. describe("tool executor", () => {
  356. const entry = {
  357. metadata: { name: "Agent" },
  358. cancellation: {
  359. supported: true,
  360. cleanup: "bestEffort",
  361. userVisibleMessage: "Agent was cancelled",
  362. },
  363. } as unknown as ToolEntry;
  364. // 与 call-runner 一致:context 上只放接管点的 register,带 decide 的接管点单独交给 executeWithTimeout。
  365. const createCall = (controller: AbortController, decide?: () => InputPreemptionHandling) => {
  366. const inputPreemption = createInputPreemptionSlot();
  367. if (decide) inputPreemption.register(decide);
  368. const context = {
  369. abortSignal: controller.signal,
  370. inputPreemption,
  371. } as unknown as ToolExecutionContext;
  372. return { context, inputPreemption };
  373. };
  374. const execute = (
  375. call: ReturnType<typeof createCall>,
  376. controller: AbortController,
  377. output: unknown,
  378. ) =>
  379. executeWithTimeout(
  380. async () => output,
  381. {},
  382. call.context,
  383. new ToolDeadline(undefined),
  384. controller,
  385. entry,
  386. call.inputPreemption,
  387. );
  388. it("waits for the handler when the registered decision is wait", async () => {
  389. const controller = new AbortController();
  390. const handlerOutput = createDeferred<unknown>();
  391. const result = execute(
  392. createCall(controller, () => "wait"),
  393. controller,
  394. handlerOutput.promise,
  395. );
  396. controller.abort(createInputPreemptionAbortReason(SEND_NOW_REASON));
  397. handlerOutput.resolve({ status: "async_launched" });
  398. await expect(result).resolves.toEqual({ status: "async_launched" });
  399. });
  400. it("cancels at once when the decision is cancel, when none is registered, or for other stops", async () => {
  401. const declined = new AbortController();
  402. const declinedResult = execute(
  403. createCall(declined, () => "cancel"),
  404. declined,
  405. new Promise(() => {}),
  406. );
  407. declined.abort(createInputPreemptionAbortReason(SEND_NOW_REASON));
  408. await expect(declinedResult).rejects.toMatchObject({ type: CoreErrorType.ToolCancelled });
  409. const unregistered = new AbortController();
  410. const unregisteredResult = execute(
  411. createCall(unregistered),
  412. unregistered,
  413. new Promise(() => {}),
  414. );
  415. unregistered.abort(createInputPreemptionAbortReason(SEND_NOW_REASON));
  416. await expect(unregisteredResult).rejects.toMatchObject({
  417. type: CoreErrorType.ToolCancelled,
  418. });
  419. let decideCalls = 0;
  420. const plainStop = new AbortController();
  421. const plainResult = execute(
  422. createCall(plainStop, () => {
  423. decideCalls += 1;
  424. return "wait";
  425. }),
  426. plainStop,
  427. new Promise(() => {}),
  428. );
  429. plainStop.abort(new Error("v4 session stopped"));
  430. await expect(plainResult).rejects.toMatchObject({ type: CoreErrorType.ToolCancelled });
  431. expect(decideCalls).toBe(0);
  432. });
  433. it("does not start a tool after the preemption", async () => {
  434. const controller = new AbortController();
  435. controller.abort(createInputPreemptionAbortReason(SEND_NOW_REASON));
  436. let started = false;
  437. const call = createCall(controller, () => "wait");
  438. const result = executeWithTimeout(
  439. async () => {
  440. started = true;
  441. return {};
  442. },
  443. {},
  444. call.context,
  445. new ToolDeadline(undefined),
  446. controller,
  447. entry,
  448. call.inputPreemption,
  449. );
  450. await expect(result).rejects.toMatchObject({ type: CoreErrorType.ToolCancelled });
  451. expect(started).toBe(false);
  452. });
  453. });
  454. describe("agent runtime", () => {
  455. it("send-now keeps both foreground agents running and records async launch results", async () => {
  456. const harness = createRuntimeHarness({ agentCount: 2 });
  457. const pendingTurn = harness.runtime.executeTurn("Launch two slow foreground agents.");
  458. await waitForCondition(() => harness.childStarts.length === 2);
  459. expect(
  460. harness.runtime.stopActiveForegroundExecution({
  461. preserveQueueAutoDrainOnCancel: true,
  462. reason: SEND_NOW_REASON,
  463. }),
  464. ).toMatchObject({ kind: "stopped" });
  465. await expect(pendingTurn).rejects.toMatchObject({ type: CoreErrorType.TurnCancelled });
  466. expect(harness.childStarts.every((start) => start.signal?.aborted === false)).toBe(true);
  467. await harness.runtime.executeTurn("send this now");
  468. const sendNowRequest = JSON.stringify(harness.parentRequests[1]);
  469. expect(countOccurrences(sendNowRequest, ASYNC_LAUNCHED_TEXT)).toBe(2);
  470. expect(sendNowRequest).not.toContain(USER_STOPPED_TOOL_RESULT_CONTENT);
  471. expect(sendNowRequest).not.toContain(INTERRUPT_MARKER_PREFIX);
  472. expect(sendNowRequest).toContain("send this now");
  473. harness.childGate.resolve();
  474. await waitForCondition(
  475. () =>
  476. harness.parentRequests.some((request) =>
  477. JSON.stringify(request).includes("<status>completed</status>"),
  478. ),
  479. 3000,
  480. );
  481. const notificationRequest = JSON.stringify(harness.parentRequests.at(-1));
  482. expect(notificationRequest).toContain("<task-notification>");
  483. expect(notificationRequest).toContain("child result after send-now");
  484. // 两个 Agent 都收口后再结束:清理时关闭 runtime,不能和还在收尾的后台 Agent 同时发生。
  485. await waitForCondition(
  486. () =>
  487. harness.liveEvents.filter(
  488. (event) =>
  489. event.sessionId === harness.sessionId &&
  490. event.type === SessionEventType.SubagentStopped,
  491. ).length === 2,
  492. 3000,
  493. );
  494. });
  495. it("send-now during a finished agent's settle cancels it as before without waiting", async () => {
  496. const stoppedAppending = createDeferred<void>();
  497. const releaseStopped = createDeferred<void>();
  498. const harness = createRuntimeHarness({
  499. agentCount: 1,
  500. childResult: FINISHED_CHILD_RESULT,
  501. childWaits: false,
  502. eventStore: new BlockingSubagentStoppedEventStore(stoppedAppending, releaseStopped.promise),
  503. });
  504. const pendingTurn = harness.runtime.executeTurn("Launch one fast foreground agent.");
  505. // child 已出结果,runner 正在写完成事件,这次写入一直卡住。
  506. await stoppedAppending.promise;
  507. harness.runtime.stopActiveForegroundExecution({
  508. preserveQueueAutoDrainOnCancel: true,
  509. reason: SEND_NOW_REASON,
  510. });
  511. // 写入还卡着,旧轮照样立即结束:收尾阶段不认领,executor 立即取消。
  512. await expect(pendingTurn).rejects.toMatchObject({ type: CoreErrorType.TurnCancelled });
  513. releaseStopped.resolve();
  514. await harness.runtime.executeTurn("send this now");
  515. const sendNowRequest = JSON.stringify(harness.parentRequests[1]);
  516. expect(sendNowRequest).toContain(AGENT_CANCELLED_TEXT);
  517. expect(sendNowRequest).not.toContain(ASYNC_LAUNCHED_TEXT);
  518. expect(sendNowRequest).not.toContain(FINISHED_CHILD_RESULT);
  519. expect(sendNowRequest).toContain("send this now");
  520. });
  521. it("a child that finishes right after the move leaves the background work finished, not running", async () => {
  522. let releaseChild = () => {};
  523. const eventStore = new ResultAfterSettleEventStore("call_send_now_agent_0", () =>
  524. releaseChild(),
  525. );
  526. const harness = createRuntimeHarness({ agentCount: 1, eventStore });
  527. releaseChild = () => harness.childGate.resolve();
  528. const pendingTurn = harness.runtime.executeTurn("Launch one slow foreground agent.");
  529. await waitForCondition(() => harness.childStarts.length === 1);
  530. harness.runtime.stopActiveForegroundExecution({
  531. preserveQueueAutoDrainOnCancel: true,
  532. reason: SEND_NOW_REASON,
  533. });
  534. await expect(pendingTurn).rejects.toMatchObject({ type: CoreErrorType.TurnCancelled });
  535. await waitForCondition(
  536. () =>
  537. harness.parentRequests.some((request) =>
  538. JSON.stringify(request).includes("<status>completed</status>"),
  539. ),
  540. 3000,
  541. );
  542. // runner 先收口并写了 BackgroundTaskCompleted;tracker 随后不再写 BackgroundTaskStarted,
  543. // 后台工作的最后一条生命周期事件是完成,面板不会停在运行中。
  544. const lifecycle = harness.liveEvents
  545. .filter(
  546. (event) =>
  547. event.sessionId === harness.sessionId &&
  548. (event.type === SessionEventType.BackgroundTaskStarted ||
  549. event.type === SessionEventType.BackgroundTaskCompleted),
  550. )
  551. .map((event) => event.type);
  552. expect(lifecycle).toEqual([SessionEventType.BackgroundTaskCompleted]);
  553. const notificationRequests = harness.parentRequests.filter((request) =>
  554. JSON.stringify(request).includes("<task-notification>"),
  555. );
  556. expect(notificationRequests.length).toBeGreaterThan(0);
  557. expect(JSON.stringify(notificationRequests.at(-1))).toContain("child result after send-now");
  558. });
  559. it("manual stop still cancels the foreground agent", async () => {
  560. const harness = createRuntimeHarness({ agentCount: 1 });
  561. const pendingTurn = harness.runtime.executeTurn("Launch one slow foreground agent.");
  562. await waitForCondition(() => harness.childStarts.length === 1);
  563. harness.runtime.stopActiveForegroundExecution({ reason: "v4 session stopped" });
  564. await expect(pendingTurn).rejects.toMatchObject({ type: CoreErrorType.TurnCancelled });
  565. await waitForCondition(() => harness.childStarts[0]?.signal?.aborted === true);
  566. await harness.runtime.executeTurn("next prompt");
  567. const nextRequest = JSON.stringify(harness.parentRequests[1]);
  568. expect(nextRequest).toContain(USER_STOPPED_TOOL_RESULT_CONTENT);
  569. expect(nextRequest).not.toContain(ASYNC_LAUNCHED_TEXT);
  570. harness.childGate.resolve();
  571. });
  572. it("a child waiting for approval moves to background with its request kept open", async () => {
  573. const userAnswered = createDeferred<void>();
  574. const permissionSignals: Array<AbortSignal | undefined> = [];
  575. const harness = createRuntimeHarness({
  576. agentCount: 1,
  577. childAsksUser: true,
  578. permissionBroker: {
  579. requestPermission(request: { input: unknown }, options?: { signal?: AbortSignal }) {
  580. permissionSignals.push(options?.signal);
  581. return userAnswered.promise.then(() => ({
  582. decision: "modify",
  583. modifiedInput: {
  584. ...(request.input as Record<string, unknown>),
  585. answers: { "Which path?": "A" },
  586. },
  587. reason: "answered in parent task",
  588. }));
  589. },
  590. },
  591. });
  592. // 先于 harness 的清理执行:用例中途失败时也让审批返回,child 才能结束。
  593. onTestFinished(() => userAnswered.resolve());
  594. const pendingTurn = harness.runtime.executeTurn("Launch an agent that asks the user.");
  595. await waitForCondition(() => permissionSignals.length === 1);
  596. harness.runtime.stopActiveForegroundExecution({
  597. preserveQueueAutoDrainOnCancel: true,
  598. reason: SEND_NOW_REASON,
  599. });
  600. await expect(pendingTurn).rejects.toMatchObject({ type: CoreErrorType.TurnCancelled });
  601. expect(permissionSignals[0]?.aborted).toBe(false);
  602. // 用户在审批框里作答后,后台 child 继续执行并完成。
  603. userAnswered.resolve();
  604. harness.childGate.resolve();
  605. await waitForCondition(
  606. () =>
  607. harness.liveEvents.some(
  608. (event) =>
  609. event.sessionId === harness.sessionId &&
  610. event.type === SessionEventType.BackgroundTaskCompleted,
  611. ),
  612. 3000,
  613. );
  614. expect(harness.childCallCount()).toBe(2);
  615. });
  616. it("send-now in an off-peak run moves the foreground agent, and the off-peak run ends after it", async () => {
  617. const lifecycleEvents: OffPeakLifecycleEvent[] = [];
  618. const registry = new InMemoryRuntimeTaskRegistry();
  619. const childGate = createDeferred<void>();
  620. const childStarts: Array<{ providerId: string; signal?: AbortSignal }> = [];
  621. const mainRequests: Array<{ providerId: string; messages: string }> = [];
  622. const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  623. const runtime = createTestAgentRuntime(
  624. createSessionId("send-now-off-peak"),
  625. {
  626. mode: "yolo",
  627. modelSelection: createTestModelSelection("user/normal"),
  628. titleGeneration: { enabled: false },
  629. workingDirectory: "/workspace/project",
  630. // 这些用例按前台 Agent 写成,关闭「Agent 总在后台」开关(07-subagent.md「ZCode 当前实现」)。
  631. subagents: { alwaysBackground: false },
  632. },
  633. {
  634. runtimeTaskRegistry: registry,
  635. eventStore: createTestSessionEventStore(),
  636. onOffPeakLifecycleEvent: (event) => lifecycleEvents.push(event),
  637. modelFactory: createTestModelFactory({
  638. async generateText(request, observation) {
  639. const providerId = String(observation.model.providerId);
  640. if (observation.invocationContext?.metadata?.querySource === "subagent") {
  641. childStarts.push({ providerId, signal: request.abortSignal });
  642. await childGate.promise;
  643. return { text: "off-peak child result", finishReason: "stop", usage };
  644. }
  645. mainRequests.push({ providerId, messages: JSON.stringify(request.messages) });
  646. if (mainRequests.length > 1)
  647. return { text: "parent reply", finishReason: "stop", usage };
  648. return {
  649. text: "",
  650. finishReason: "tool-calls",
  651. usage,
  652. toolCalls: [
  653. {
  654. id: "call_off_peak_agent",
  655. name: "Agent",
  656. input: {
  657. description: "Off-peak child",
  658. prompt: "Work slowly.",
  659. subagent_type: "general-purpose",
  660. },
  661. },
  662. ],
  663. };
  664. },
  665. }),
  666. },
  667. );
  668. onTestFinished(async () => {
  669. childGate.resolve();
  670. await runtime.close();
  671. });
  672. const offPeakTurn = runtime.executeTurn("idle work", undefined, {
  673. offPeakTaskId: "idle-task",
  674. intent: {
  675. sourceCommandId: "idle-input",
  676. kind: "sendText",
  677. modelSelection: createTestModelSelection("idle/model"),
  678. } as never,
  679. modelExecution: {
  680. selectionScope: "execution",
  681. offPeak: { executionId: "off-peak-run", ticketId: "one", providerErrorCode: "3102" },
  682. requestDependencies: {
  683. requestAuth: { source: { resolve: async () => ({ headers: { ticket: "one" } }) } },
  684. },
  685. },
  686. });
  687. await waitForCondition(() => childStarts.length === 1);
  688. runtime.stopActiveForegroundExecution({
  689. preserveQueueAutoDrainOnCancel: true,
  690. reason: SEND_NOW_REASON,
  691. });
  692. await expect(offPeakTurn).rejects.toMatchObject({ type: CoreErrorType.TurnCancelled });
  693. // 闲时运行允许后台:Agent 转后台,child 继续用闲时模型运行,算作这次闲时运行的后台工作。
  694. expect(childStarts[0]?.providerId).toBe("idle");
  695. expect(childStarts[0]?.signal?.aborted).toBe(false);
  696. expect(Object.values(registry.all())).toEqual([
  697. expect.objectContaining({
  698. isBackgrounded: true,
  699. offPeakExecutionId: "off-peak-run",
  700. status: "running",
  701. }),
  702. ]);
  703. // 立即发送的消息由用户接管,改用用户模型;child 还在运行,闲时运行不结束。
  704. await runtime.executeTurn("send this now", undefined, {
  705. intent: {
  706. sourceCommandId: "user-input",
  707. kind: "sendText",
  708. admissionSeq: 2,
  709. modelSelection: createTestModelSelection("paid/new"),
  710. } as never,
  711. });
  712. expect(mainRequests[1]?.providerId).toBe("paid");
  713. expect(mainRequests[1]?.messages).toContain(ASYNC_LAUNCHED_TEXT);
  714. expect(lifecycleEvents.some((event) => event.type === "completed")).toBe(false);
  715. // child 跑完:结果经 task-notification 回到父模型,闲时运行随后只结束一次。
  716. childGate.resolve();
  717. await waitForCondition(
  718. () => lifecycleEvents.some((event) => event.type === "completed"),
  719. 3000,
  720. );
  721. expect(lifecycleEvents.filter((event) => event.type === "completed")).toHaveLength(1);
  722. expect(
  723. mainRequests.some(
  724. (request) =>
  725. request.messages.includes("<task-notification>") &&
  726. request.messages.includes("off-peak child result"),
  727. ),
  728. ).toBe(true);
  729. });
  730. });
  731. it("marks only send-now stops with the input preemption reason", () => {
  732. const reason = createInputPreemptionAbortReason(SEND_NOW_REASON);
  733. expect(reason).toBeInstanceOf(Error);
  734. expect(reason.message).toBe(SEND_NOW_REASON);
  735. expect(isInputPreemptionAbortReason(reason)).toBe(true);
  736. expect(isInputPreemptionAbortReason(new Error(SEND_NOW_REASON))).toBe(false);
  737. expect(isInputPreemptionAbortReason({ kind: "input_preemption" })).toBe(false);
  738. expect(isInputPreemptionAbortReason(undefined)).toBe(false);
  739. });
  740. });
  741. /** 转后台请求的等待永不先返回,让 race 只能选中 child 的结果。 */
  742. class CompletionFirstRegistry extends InMemoryRuntimeTaskRegistry {
  743. override waitForBackgroundRequest(): Promise<RuntimeTaskSnapshot | undefined> {
  744. return new Promise(() => {});
  745. }
  746. }
  747. /** 任务第一次要变为终态时,先调用 beforeTerminal 再写入:用来停在 runner 收尾、registry 仍是 running 的窗口。 */
  748. class BeforeTerminalRegistry extends InMemoryRuntimeTaskRegistry {
  749. constructor(private beforeTerminal: (() => void) | undefined) {
  750. super();
  751. }
  752. override update(
  753. id: string,
  754. updater: (task: RuntimeTaskSnapshot) => RuntimeTaskSnapshot,
  755. ): RuntimeTaskSnapshot | undefined {
  756. const current = this.get(id);
  757. if (current && !isTerminalRuntimeTask(current) && isTerminalRuntimeTask(updater(current))) {
  758. const beforeTerminal = this.beforeTerminal;
  759. this.beforeTerminal = undefined;
  760. beforeTerminal?.();
  761. }
  762. // 回调可能已改动任务(例如标为后台),按写入时的最新值重新计算。
  763. return super.update(id, updater);
  764. }
  765. }
  766. /**
  767. * 父会话 Agent 的 ToolCallResult 写入要等 runner 写完 BackgroundTaskCompleted 才返回:复现转后台与
  768. * child 结束几乎同时发生时,executor 的 tracker 晚于 runner 收口。
  769. */
  770. class ResultAfterSettleEventStore extends InMemorySessionEventStore {
  771. private readonly settled = createDeferred<void>();
  772. constructor(
  773. private readonly toolCallId: string,
  774. private readonly onResultAppended: () => void,
  775. ) {
  776. super({ retention: "unbounded" });
  777. }
  778. override async append(event: SessionEvent): Promise<SessionEvent> {
  779. const stored = await super.append(event);
  780. if (event.type === SessionEventType.BackgroundTaskCompleted) this.settled.resolve();
  781. if (
  782. event.type === SessionEventType.ToolCallResult &&
  783. (event.payload as { toolCallId?: string }).toolCallId === this.toolCallId
  784. ) {
  785. this.onResultAppended();
  786. await this.settled.promise;
  787. }
  788. return stored;
  789. }
  790. }
  791. /** 父会话的 SubagentStopped 写入卡住,直到测试放行;用来停在 runner 收尾阶段。 */
  792. class BlockingSubagentStoppedEventStore extends InMemorySessionEventStore {
  793. constructor(
  794. private readonly appending: { resolve: (value: void) => void },
  795. private readonly release: Promise<void>,
  796. ) {
  797. super({ retention: "unbounded" });
  798. }
  799. override async append(event: SessionEvent): Promise<SessionEvent> {
  800. if (event.type === SessionEventType.SubagentStopped) {
  801. this.appending.resolve();
  802. await this.release;
  803. }
  804. return super.append(event);
  805. }
  806. }
  807. /**
  808. * 按生产顺序模拟 executor:用生产的接管点,并在 runner 之前挂上父 signal 的 abort 监听
  809. * (executeWithTimeout 先于 handler 注册监听),立即发送到达时先由它调用判断函数,记录结果。
  810. */
  811. function createExecutorPreemption(parent: AbortSignal): {
  812. control: InputPreemptionControl;
  813. decision: () => InputPreemptionHandling | undefined;
  814. } {
  815. const slot = createInputPreemptionSlot();
  816. let decision: InputPreemptionHandling | undefined;
  817. parent.addEventListener(
  818. "abort",
  819. () => {
  820. if (isInputPreemptionAbortReason(parent.reason)) decision = slot.decide();
  821. },
  822. { once: true },
  823. );
  824. return { control: slot, decision: () => decision };
  825. }
  826. let harnessIndex = 0;
  827. interface RuntimeHarnessOptions {
  828. agentCount: number;
  829. childAsksUser?: boolean;
  830. /** child 的最终回复;缺省为短文本。 */
  831. childResult?: string;
  832. /** child 回复前是否等 childGate;缺省等待。 */
  833. childWaits?: boolean;
  834. eventStore?: SessionEventStorePort;
  835. permissionBroker?: unknown;
  836. }
  837. function createRuntimeHarness(options: RuntimeHarnessOptions) {
  838. harnessIndex += 1;
  839. const sessionId: SessionId = createSessionId(`send-now-agent-runtime-${harnessIndex}`);
  840. const childGate = createDeferred<void>();
  841. const childStarts: Array<{ signal?: AbortSignal }> = [];
  842. const parentRequests: unknown[] = [];
  843. const liveEvents: SessionEvent[] = [];
  844. const childCalls = new Map<string, number>();
  845. const runtime = createTestAgentRuntime(
  846. sessionId,
  847. {
  848. mode: "yolo",
  849. modelSelection: {
  850. providerId: createModelProviderId("provider-test"),
  851. modelId: createModelId("parent-model"),
  852. },
  853. titleGeneration: { enabled: false },
  854. workingDirectory: "/workspace/project",
  855. // 这些用例按前台 Agent 写成,关闭「Agent 总在后台」开关(07-subagent.md「ZCode 当前实现」)。
  856. subagents: { alwaysBackground: false },
  857. },
  858. {
  859. eventStore: options.eventStore ?? createTestSessionEventStore(),
  860. ...(options.permissionBroker ? { permissionBroker: options.permissionBroker as never } : {}),
  861. modelFactory: createTestModelFactory({
  862. async generateText(request: any) {
  863. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  864. if (toolNames.includes("Agent")) {
  865. parentRequests.push(structuredClone(request.messages));
  866. if (parentRequests.length === 1) {
  867. return {
  868. finishReason: "tool-calls",
  869. providerMetadata: undefined,
  870. text: "",
  871. toolCalls: Array.from({ length: options.agentCount }, (_, index) => ({
  872. id: `call_send_now_agent_${index}`,
  873. name: "Agent",
  874. input: {
  875. description: `Slow child ${index}`,
  876. prompt: `CHILD_${index}: work slowly.`,
  877. subagent_type: "general-purpose",
  878. },
  879. })),
  880. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  881. };
  882. }
  883. return {
  884. finishReason: "stop",
  885. providerMetadata: undefined,
  886. text: `parent reply ${parentRequests.length}`,
  887. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  888. };
  889. }
  890. const childKey = JSON.stringify(request.messages).match(/CHILD_\d+/)?.[0] ?? "CHILD";
  891. const call = (childCalls.get(childKey) ?? 0) + 1;
  892. childCalls.set(childKey, call);
  893. if (call === 1) {
  894. childStarts.push({ signal: request.abortSignal });
  895. if (options.childAsksUser) {
  896. return {
  897. finishReason: "tool-calls",
  898. providerMetadata: undefined,
  899. text: "",
  900. toolCalls: [
  901. {
  902. id: `call_child_ask_${childKey}`,
  903. name: "AskUserQuestion",
  904. input: {
  905. questions: [
  906. {
  907. header: "Path",
  908. multiSelect: false,
  909. options: [
  910. { description: "Use path A", label: "A" },
  911. { description: "Use path B", label: "B" },
  912. ],
  913. question: "Which path?",
  914. },
  915. ],
  916. },
  917. },
  918. ],
  919. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  920. };
  921. }
  922. }
  923. if (options.childWaits !== false) await childGate.promise;
  924. return {
  925. finishReason: "stop",
  926. providerMetadata: undefined,
  927. text: options.childResult ?? "child result after send-now",
  928. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  929. };
  930. },
  931. } as never),
  932. },
  933. );
  934. runtime.subscribeEvents({
  935. onSessionEvent: (event) => {
  936. liveEvents.push(event);
  937. },
  938. });
  939. onTestFinished(async () => {
  940. childGate.resolve();
  941. await runtime.close();
  942. });
  943. const childCallCount = () =>
  944. Array.from(childCalls.values()).reduce((total, count) => total + count, 0);
  945. return { runtime, sessionId, childGate, childStarts, childCallCount, parentRequests, liveEvents };
  946. }
  947. function createGatedPort(agentId: string) {
  948. const childReady = createDeferred<void>();
  949. let signal: AbortSignal | undefined;
  950. const port = createExploreSubagentPort({
  951. createAgentId: () => agentId,
  952. emitParentEvent: async () => {},
  953. runExploreAgent: async (request, options) => {
  954. signal = options?.signal;
  955. await request.onSessionReady?.();
  956. childReady.resolve();
  957. await new Promise<void>((resolve) => {
  958. signal?.addEventListener("abort", () => resolve(), { once: true });
  959. });
  960. throw signal?.reason ?? new Error("child aborted");
  961. },
  962. });
  963. onTestFinished(() => port.close?.());
  964. return { port, childReady, childSignal: () => signal };
  965. }
  966. function createRunRequest(sessionId: SessionId, turnId: ReturnType<typeof createTurnId>) {
  967. return {
  968. agentType: "general-purpose",
  969. description: "Send-now background test",
  970. parentToolCallId: "call_send_now_background",
  971. prompt: "Run slowly",
  972. sessionId,
  973. trace: {
  974. traceId: "trace_send_now_background_parent",
  975. spanId: "span_send_now_background_parent",
  976. sessionId,
  977. turnId,
  978. },
  979. turnId,
  980. workingDirectory: "/tmp/zcode-subagent-send-now-background",
  981. workspaceRoot: "/tmp/zcode-subagent-send-now-background",
  982. };
  983. }
  984. function createDeferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
  985. let resolve!: (value: T) => void;
  986. const promise = new Promise<T>((innerResolve) => {
  987. resolve = innerResolve;
  988. });
  989. return { promise, resolve };
  990. }
  991. function countOccurrences(text: string, needle: string): number {
  992. return text.split(needle).length - 1;
  993. }
  994. async function waitForCondition(
  995. predicate: () => boolean | Promise<boolean>,
  996. timeoutMs = 1000,
  997. ): Promise<void> {
  998. const startedAt = Date.now();
  999. while (Date.now() - startedAt < timeoutMs) {
  1000. if (await predicate()) return;
  1001. await new Promise((resolve) => setTimeout(resolve, 5));
  1002. }
  1003. throw new Error("Timed out waiting for condition");
  1004. }