subagent-background.test.ts 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. HookEventName,
  4. SessionEventType,
  5. createSessionId,
  6. createTurnId,
  7. modelMessageContentToText,
  8. type BackgroundResultOriginMeta,
  9. type CreateSessionInput,
  10. type ModelMessageContent,
  11. type MessageInfo,
  12. type MessagePart,
  13. type MessageWithParts,
  14. type PermissionRuleset,
  15. type SessionEvent,
  16. type SessionGoal,
  17. type SessionId,
  18. type SessionInfo,
  19. type SessionStorePort,
  20. type TodoItem,
  21. } from "@zcode/contracts";
  22. import { formatTaskNotification } from "../src/runtime-task/notification.js";
  23. import { formatLocalAgentTaskNotification } from "../src/subagent/completion-notification.js";
  24. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  25. import { createRuntimeCommandId } from "../src/runtime/command-queue.js";
  26. import type { PromptRuntimeCommand } from "../src/runtime/command-queue.js";
  27. import { createTurnFailureError } from "../src/runtime/helpers/turn-errors.js";
  28. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  29. import { createExploreSubagentPort } from "../src/subagent/runner.js";
  30. import { createTestSessionEventStore } from "./test-event-store.js";
  31. import { createTestModelFactory } from "./test-runtime-model.js";
  32. describe("subagent background notifications", () => {
  33. it("formats local_agent task notification as user-role XML", () => {
  34. const notification = formatTaskNotification({
  35. outputFile: "/tmp/zcode-agents/sess/agent/output.txt",
  36. result: "child result",
  37. status: "completed",
  38. summary: 'Agent "Audit tests" completed',
  39. taskId: "agent_123",
  40. taskType: "local_agent",
  41. toolUseId: "toolu_123",
  42. usage: {
  43. durationMs: 42,
  44. toolUseCount: 2,
  45. totalTokens: 9,
  46. },
  47. });
  48. expect(notification).toBe(
  49. [
  50. "<task-notification>",
  51. "<task-id>agent_123</task-id>",
  52. "<tool-use-id>toolu_123</tool-use-id>",
  53. "<output-file>/tmp/zcode-agents/sess/agent/output.txt</output-file>",
  54. "<status>completed</status>",
  55. "<summary>Agent &quot;Audit tests&quot; completed</summary>",
  56. "<result>child result</result>",
  57. "<usage><subagent_tokens>9</subagent_tokens><tool_uses>2</tool_uses><duration_ms>42</duration_ms></usage>",
  58. "</task-notification>",
  59. ].join("\n"),
  60. );
  61. });
  62. it("omits unavailable local_agent usage fields", () => {
  63. const notification = formatTaskNotification({
  64. outputFile: "/tmp/output.txt",
  65. status: "completed",
  66. summary: "Agent completed",
  67. taskId: "agent_456",
  68. taskType: "local_agent",
  69. usage: {
  70. durationMs: 25,
  71. },
  72. });
  73. expect(notification).toContain("<usage><duration_ms>25</duration_ms></usage>");
  74. expect(notification).not.toContain("subagent_tokens");
  75. expect(notification).not.toContain("tool_uses");
  76. });
  77. it("formats completed, failed, and stopped local-agent notifications through one helper", () => {
  78. const base = {
  79. agentId: "agent_helper",
  80. agentType: "custom-reviewer",
  81. description: "Review changes",
  82. outputFile: "/tmp/agent_helper/output.txt",
  83. parentToolCallId: "toolu_helper",
  84. totalDurationMs: 12,
  85. };
  86. const completed = formatLocalAgentTaskNotification({
  87. ...base,
  88. result: "looks good",
  89. status: "completed",
  90. totalTokens: 7,
  91. totalToolUseCount: 1,
  92. });
  93. const failed = formatLocalAgentTaskNotification({
  94. ...base,
  95. error: "child failed",
  96. status: "failed",
  97. });
  98. const stopped = formatLocalAgentTaskNotification({
  99. ...base,
  100. status: "stopped",
  101. });
  102. expect(completed).toContain("<status>completed</status>");
  103. expect(completed).toContain("<result>looks good</result>");
  104. expect(completed).toContain(
  105. "<summary>Agent custom-reviewer task &quot;Review changes&quot; completed.</summary>",
  106. );
  107. expect(completed).not.toContain("<error>");
  108. expect(completed).toContain("<subagent_tokens>7</subagent_tokens>");
  109. expect(failed).toContain("<status>failed</status>");
  110. expect(failed).toContain(
  111. "<summary>Agent custom-reviewer task &quot;Review changes&quot; failed. child failed</summary>",
  112. );
  113. expect(failed).toContain("<error>child failed</error>");
  114. expect(stopped).toContain("<status>stopped</status>");
  115. expect(stopped).toContain(
  116. "<summary>Agent custom-reviewer task &quot;Review changes&quot; stopped.</summary>",
  117. );
  118. expect(stopped).not.toContain("<error>");
  119. expect(stopped).not.toContain("Explore");
  120. });
  121. it("drains pending background notifications as strict snapshot batches", async () => {
  122. const sessionId = createSessionId("background-notification-idle-wake");
  123. const sessionStore = new RecordingSessionStore();
  124. const eventStore = createTestSessionEventStore();
  125. const hookEvents: string[] = [];
  126. const requestMessages: Array<readonly { content: ModelMessageContent; role?: string }[]> = [];
  127. const firstRequestMayFinish = createDeferred<void>();
  128. const secondRequestMayFinish = createDeferred<void>();
  129. let requestCount = 0;
  130. const runtime = createTestAgentRuntime(
  131. sessionId,
  132. {
  133. workingDirectory: "/tmp/zcode-background-notification-idle-wake",
  134. },
  135. {
  136. eventStore,
  137. hookRunner: createInMemoryHookRunner({
  138. hooks: [
  139. {
  140. event: HookEventName.UserPromptSubmit,
  141. callback: async (input) => {
  142. hookEvents.push(input.prompt);
  143. return {
  144. hookSpecificOutput: {
  145. hookEventName: HookEventName.UserPromptSubmit,
  146. },
  147. };
  148. },
  149. },
  150. ],
  151. }),
  152. modelFactory: createTestModelFactory({
  153. async generateText(request: {
  154. messages: readonly { content: ModelMessageContent; role?: string }[];
  155. }) {
  156. requestCount += 1;
  157. requestMessages.push(request.messages);
  158. if (requestCount === 1) await firstRequestMayFinish.promise;
  159. if (requestCount === 2) await secondRequestMayFinish.promise;
  160. return modelTextResult(`processed background notification ${requestCount}`);
  161. },
  162. } as never),
  163. sessionStore: sessionStore as unknown as SessionStorePort,
  164. },
  165. ) as unknown as {
  166. enqueueBackgroundTaskNotification(notification: {
  167. originMeta: {
  168. backgroundSource: "bash" | "subagent";
  169. title: string;
  170. workId: string;
  171. };
  172. taskId?: string;
  173. text: string;
  174. traceContext: {
  175. traceId: string;
  176. spanId: string;
  177. sessionId: SessionId;
  178. };
  179. }): void;
  180. };
  181. const traceContext = {
  182. traceId: "trace_background_idle_wake",
  183. spanId: "span_background_idle_wake",
  184. sessionId,
  185. };
  186. runtime.enqueueBackgroundTaskNotification({
  187. originMeta: {
  188. backgroundSource: "subagent",
  189. title: "Inspect renderer state",
  190. workId: "agent_idle_1",
  191. },
  192. taskId: "agent_idle_1",
  193. text: "<task-notification>\n<task-id>agent_idle_1</task-id>\n</task-notification>",
  194. traceContext,
  195. });
  196. await waitForCondition(() => requestMessages.length === 1);
  197. runtime.enqueueBackgroundTaskNotification({
  198. originMeta: {
  199. backgroundSource: "bash",
  200. title: "pnpm test",
  201. workId: "agent_idle_2",
  202. },
  203. taskId: "agent_idle_2",
  204. text: "<task-notification>\n<task-id>agent_idle_2</task-id>\n</task-notification>",
  205. traceContext,
  206. });
  207. runtime.enqueueBackgroundTaskNotification({
  208. originMeta: {
  209. backgroundSource: "subagent",
  210. title: "Inspect service state",
  211. workId: "agent_idle_3",
  212. },
  213. taskId: "agent_idle_3",
  214. text: "<task-notification>\n<task-id>agent_idle_3</task-id>\n</task-notification>",
  215. traceContext,
  216. });
  217. firstRequestMayFinish.resolve(undefined);
  218. await waitForCondition(() => requestMessages.length === 2);
  219. runtime.enqueueBackgroundTaskNotification({
  220. originMeta: {
  221. backgroundSource: "bash",
  222. title: "pnpm lint",
  223. workId: "agent_idle_4",
  224. },
  225. taskId: "agent_idle_4",
  226. text: "<task-notification>\n<task-id>agent_idle_4</task-id>\n</task-notification>",
  227. traceContext,
  228. });
  229. secondRequestMayFinish.resolve(undefined);
  230. await waitForCondition(() => requestMessages.length === 3);
  231. const notificationInputs = requestMessages.map((messages) =>
  232. [...messages]
  233. .reverse()
  234. .find((message) =>
  235. modelMessageContentToText(message.content).includes("<task-notification>"),
  236. ),
  237. );
  238. const notificationTexts = notificationInputs.map((message) =>
  239. modelMessageContentToText(message?.content),
  240. );
  241. expect(notificationTexts[0]).toContain("<task-id>agent_idle_1</task-id>");
  242. expect(notificationTexts[0]).not.toContain("<task-id>agent_idle_2</task-id>");
  243. expect(notificationTexts[1]).toContain("<task-id>agent_idle_2</task-id>");
  244. expect(notificationTexts[1]).toContain("<task-id>agent_idle_3</task-id>");
  245. expect(notificationTexts[1]).not.toContain("<task-id>agent_idle_4</task-id>");
  246. expect(notificationTexts[2]).toContain("<task-id>agent_idle_4</task-id>");
  247. expect(notificationTexts[2]).not.toContain("<task-id>agent_idle_3</task-id>");
  248. const firstNotificationMessage = notificationInputs[0];
  249. expect(firstNotificationMessage?.role).toBe("user");
  250. expect(modelMessageContentToText(firstNotificationMessage?.content)).toContain(
  251. "<system-reminder>",
  252. );
  253. expect(hookEvents).toEqual([]);
  254. expect(requestCount).toBe(3);
  255. const backgroundMessages = sessionStore.savedMessages.filter(
  256. (message) => message.source === "background_task",
  257. );
  258. expect(
  259. sessionStore.savedParts.filter(
  260. (part) =>
  261. part.type === "text" &&
  262. part.metadata?.source === "background_task" &&
  263. part.metadata?.visibility === "model-only",
  264. ),
  265. ).toHaveLength(3);
  266. expect(backgroundMessages.map((message) => message.metadata?.originMeta)).toEqual([
  267. {
  268. backgroundSource: "subagent",
  269. title: "Inspect renderer state",
  270. workId: "agent_idle_1",
  271. },
  272. {
  273. backgroundSource: "bash",
  274. title: "pnpm test · Inspect service state",
  275. workId: "agent_idle_2",
  276. },
  277. {
  278. backgroundSource: "bash",
  279. title: "pnpm lint",
  280. workId: "agent_idle_4",
  281. },
  282. ]);
  283. const liveBackgroundOriginMetas = (await eventStore.getEvents(sessionId))
  284. .filter((event) => event.type === SessionEventType.TurnStarted)
  285. .map(
  286. (event) =>
  287. event.payload as {
  288. inputSource?: string;
  289. originMeta?: {
  290. backgroundSource: "bash" | "subagent";
  291. title: string;
  292. workId: string;
  293. };
  294. },
  295. )
  296. .filter((payload) => payload.inputSource === "background_task")
  297. .map((payload) => payload.originMeta);
  298. expect(liveBackgroundOriginMetas).toEqual(
  299. backgroundMessages.map((message) => message.metadata?.originMeta),
  300. );
  301. const wakeTurns = (await eventStore.getEvents(sessionId))
  302. .filter((event) => event.type === SessionEventType.TurnStarted)
  303. .map(
  304. (event) => event.payload as { inputSource?: string; inputId?: string; messageId?: string },
  305. )
  306. .filter((payload) => payload.inputSource === "background_task");
  307. expect(wakeTurns).toHaveLength(3);
  308. expect(new Set(wakeTurns.map((turn) => turn.inputId)).size).toBe(3);
  309. for (const turn of wakeTurns) {
  310. expect(turn.inputId).toMatch(
  311. /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
  312. );
  313. expect(turn.inputId).not.toBe(turn.messageId);
  314. expect(backgroundMessages.some((message) => message.id === turn.messageId)).toBe(true);
  315. }
  316. expect(sessionStore.savedSessionInputs).toHaveLength(4);
  317. expect(sessionStore.promotedSessionInputs).toHaveLength(4);
  318. expect(sessionStore.promotedSessionInputs.map((input) => input.id)).toEqual(
  319. sessionStore.savedSessionInputs.map((input) => input.id),
  320. );
  321. expect(sessionStore.promotedSessionInputs[1]?.promotedMessageID).toBe(
  322. sessionStore.promotedSessionInputs[2]?.promotedMessageID,
  323. );
  324. expect(sessionStore.promotedSessionInputs[0]?.promotedMessageID).not.toBe(
  325. sessionStore.promotedSessionInputs[1]?.promotedMessageID,
  326. );
  327. expect(sessionStore.promotedSessionInputs[2]?.promotedMessageID).not.toBe(
  328. sessionStore.promotedSessionInputs[3]?.promotedMessageID,
  329. );
  330. });
  331. it("reuses ordinary origin metadata for a composed title without guessing missing members", async () => {
  332. const scenarios: Array<{
  333. expectedBackgroundSource?: "bash" | "subagent" | "workflow";
  334. expectedOriginMeta?: BackgroundResultOriginMeta;
  335. expectedBackgroundSubagentResultConsumed?: boolean;
  336. /** 批里有 dynamic-workflow run 的通知(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Token telemetry for subagents」)。 */
  337. expectedWorkflowResultConsumed?: boolean;
  338. id: string;
  339. originMetas: Array<BackgroundResultOriginMeta | undefined>;
  340. }> = [
  341. {
  342. // 整批都是 dynamic-workflow run 的通知:backgroundSource 冻结为 workflow,只置 wf 维度。
  343. expectedBackgroundSource: "workflow",
  344. expectedOriginMeta: {
  345. backgroundSource: "workflow",
  346. title: "Nightly report · Weekly digest",
  347. workId: "dwfrun-title-1",
  348. },
  349. expectedWorkflowResultConsumed: true,
  350. id: "all-workflow",
  351. originMetas: [
  352. { backgroundSource: "workflow", title: "Nightly report", workId: "dwfrun-title-1" },
  353. { backgroundSource: "workflow", title: "Weekly digest", workId: "dwfrun-title-2" },
  354. ],
  355. },
  356. {
  357. // 混批:来源不一致时 backgroundSource 不冻结(既有规则),但两个维度各自按成员置位。
  358. expectedOriginMeta: {
  359. backgroundSource: "workflow",
  360. title: "Nightly report · Inspect service",
  361. workId: "dwfrun-title-3",
  362. },
  363. expectedBackgroundSubagentResultConsumed: true,
  364. expectedWorkflowResultConsumed: true,
  365. id: "workflow-and-subagent",
  366. originMetas: [
  367. { backgroundSource: "workflow", title: "Nightly report", workId: "dwfrun-title-3" },
  368. {
  369. backgroundSource: "subagent",
  370. title: "Inspect service",
  371. workId: "agent-title-9",
  372. },
  373. ],
  374. },
  375. {
  376. expectedOriginMeta: {
  377. backgroundSource: "subagent",
  378. title: "Inspect renderer · Run tests · Inspect service · +1",
  379. workId: "agent-title-1",
  380. },
  381. expectedBackgroundSubagentResultConsumed: true,
  382. id: "complete-metadata",
  383. originMetas: [
  384. {
  385. backgroundSource: "subagent",
  386. title: "Inspect renderer",
  387. workId: "agent-title-1",
  388. },
  389. { backgroundSource: "bash", title: "Run tests", workId: "bash-title-2" },
  390. {
  391. backgroundSource: "subagent",
  392. title: "Inspect service",
  393. workId: "agent-title-3",
  394. },
  395. { backgroundSource: "bash", title: "Run lint", workId: "bash-title-4" },
  396. ],
  397. },
  398. {
  399. expectedOriginMeta: {
  400. backgroundSource: "bash",
  401. title: "Run tests · Inspect renderer · Run lint · +1",
  402. workId: "bash-title-1",
  403. },
  404. expectedBackgroundSubagentResultConsumed: true,
  405. id: "complete-metadata-reversed",
  406. originMetas: [
  407. { backgroundSource: "bash", title: "Run tests", workId: "bash-title-1" },
  408. {
  409. backgroundSource: "subagent",
  410. title: "Inspect renderer",
  411. workId: "agent-title-2",
  412. },
  413. { backgroundSource: "bash", title: "Run lint", workId: "bash-title-3" },
  414. {
  415. backgroundSource: "subagent",
  416. title: "Inspect service",
  417. workId: "agent-title-4",
  418. },
  419. ],
  420. },
  421. {
  422. expectedBackgroundSource: "subagent",
  423. expectedOriginMeta: {
  424. backgroundSource: "subagent",
  425. title: "Inspect renderer · Inspect service",
  426. workId: "agent-title-5",
  427. },
  428. expectedBackgroundSubagentResultConsumed: true,
  429. id: "all-subagent",
  430. originMetas: [
  431. {
  432. backgroundSource: "subagent",
  433. title: "Inspect renderer",
  434. workId: "agent-title-5",
  435. },
  436. {
  437. backgroundSource: "subagent",
  438. title: "Inspect service",
  439. workId: "agent-title-6",
  440. },
  441. ],
  442. },
  443. {
  444. expectedBackgroundSource: "bash",
  445. expectedOriginMeta: {
  446. backgroundSource: "bash",
  447. title: "Run tests · Run lint",
  448. workId: "bash-title-7",
  449. },
  450. id: "all-bash",
  451. originMetas: [
  452. { backgroundSource: "bash", title: "Run tests", workId: "bash-title-7" },
  453. { backgroundSource: "bash", title: "Run lint", workId: "bash-title-8" },
  454. ],
  455. },
  456. {
  457. expectedBackgroundSubagentResultConsumed: true,
  458. id: "missing-metadata",
  459. originMetas: [
  460. {
  461. backgroundSource: "subagent",
  462. title: "Inspect renderer",
  463. workId: "agent-title-legacy-1",
  464. },
  465. undefined,
  466. ],
  467. },
  468. ];
  469. for (const scenario of scenarios) {
  470. const sessionId = createSessionId(`background-title-${scenario.id}`);
  471. const sessionStore = new RecordingSessionStore();
  472. const eventStore = createTestSessionEventStore();
  473. let requestCount = 0;
  474. const runtime = createTestAgentRuntime(
  475. sessionId,
  476. { workingDirectory: `/tmp/zcode-background-title-${scenario.id}` },
  477. {
  478. eventStore,
  479. modelFactory: createTestModelFactory({
  480. async generateText() {
  481. requestCount += 1;
  482. return modelTextResult("processed notification metadata batch");
  483. },
  484. } as never),
  485. sessionStore: sessionStore as unknown as SessionStorePort,
  486. },
  487. ) as unknown as AgentRuntime & {
  488. drainRuntimeCommandQueue(): Promise<void>;
  489. enqueueBackgroundTaskNotification(notification: {
  490. originMeta?: BackgroundResultOriginMeta;
  491. taskId: string;
  492. text: string;
  493. traceContext: {
  494. sessionId: SessionId;
  495. spanId: string;
  496. traceId: string;
  497. };
  498. }): void;
  499. runtimeCommandDrainActive: boolean;
  500. };
  501. const traceContext = {
  502. sessionId,
  503. spanId: `span_${scenario.id}`,
  504. traceId: `trace_${scenario.id}`,
  505. };
  506. runtime.runtimeCommandDrainActive = true;
  507. scenario.originMetas.forEach((originMeta, index) => {
  508. const taskId = `${scenario.id}-${index + 1}`;
  509. runtime.enqueueBackgroundTaskNotification({
  510. ...(originMeta ? { originMeta } : {}),
  511. taskId,
  512. text: `<task-notification><task-id>${taskId}</task-id></task-notification>`,
  513. traceContext,
  514. });
  515. });
  516. runtime.runtimeCommandDrainActive = false;
  517. await runtime.drainRuntimeCommandQueue();
  518. expect(requestCount).toBe(1);
  519. const backgroundMessages = sessionStore.savedMessages.filter(
  520. (message) => message.source === "background_task",
  521. );
  522. expect(backgroundMessages).toHaveLength(1);
  523. expect(backgroundMessages[0]?.metadata?.originMeta).toEqual(scenario.expectedOriginMeta);
  524. const turnStarts = (await eventStore.getEvents(sessionId))
  525. .filter((event) => event.type === SessionEventType.TurnStarted)
  526. .map(
  527. (event) =>
  528. event.payload as {
  529. backgroundSource?: "bash" | "subagent" | "workflow";
  530. inputSource?: string;
  531. originMeta?: BackgroundResultOriginMeta;
  532. },
  533. )
  534. .filter((payload) => payload.inputSource === "background_task");
  535. expect(turnStarts).toHaveLength(1);
  536. expect(turnStarts[0]?.originMeta).toEqual(scenario.expectedOriginMeta);
  537. expect(turnStarts[0]?.backgroundSource).toBe(scenario.expectedBackgroundSource);
  538. const turnCompletes = (await eventStore.getEvents(sessionId))
  539. .filter((event) => event.type === SessionEventType.TurnComplete)
  540. .map(
  541. (event) =>
  542. event.payload as {
  543. backgroundSubagentResultConsumed?: boolean;
  544. workflowResultConsumed?: boolean;
  545. },
  546. );
  547. expect(turnCompletes).toHaveLength(1);
  548. expect(turnCompletes[0]?.backgroundSubagentResultConsumed).toBe(
  549. scenario.expectedBackgroundSubagentResultConsumed,
  550. );
  551. expect(turnCompletes[0]?.workflowResultConsumed).toBe(
  552. scenario.expectedWorkflowResultConsumed,
  553. );
  554. }
  555. });
  556. it.each(["provider failure", "stop"] as const)(
  557. "keeps a claimed notification batch durable without command requeue after %s",
  558. async (terminalOutcome) => {
  559. const sessionId = createSessionId(`background-notification-${terminalOutcome}`);
  560. const sessionStore = new RecordingSessionStore();
  561. const firstRequestMayFinish = createDeferred<void>();
  562. const secondRequestStarted = createDeferred<AbortSignal | undefined>();
  563. const requestMessages: Array<readonly { content: ModelMessageContent }[]> = [];
  564. let requestCount = 0;
  565. const runtime = createTestAgentRuntime(
  566. sessionId,
  567. {
  568. workingDirectory: `/tmp/zcode-background-notification-${terminalOutcome}`,
  569. },
  570. {
  571. eventStore: createTestSessionEventStore(),
  572. modelFactory: createTestModelFactory({
  573. async generateText(request: {
  574. abortSignal?: AbortSignal;
  575. messages: readonly { content: ModelMessageContent }[];
  576. }) {
  577. requestCount += 1;
  578. requestMessages.push(request.messages);
  579. if (requestCount === 1) {
  580. await firstRequestMayFinish.promise;
  581. return modelTextResult("processed first background notification");
  582. }
  583. if (requestCount === 2) {
  584. secondRequestStarted.resolve(request.abortSignal);
  585. if (terminalOutcome === "stop") {
  586. await waitForAbort(request.abortSignal);
  587. throw request.abortSignal?.reason ?? new Error("notification batch stopped");
  588. }
  589. throw new Error("notification batch provider failure");
  590. }
  591. return modelTextResult("continued after terminal notification batch");
  592. },
  593. } as never),
  594. sessionStore: sessionStore as unknown as SessionStorePort,
  595. },
  596. ) as AgentRuntime & {
  597. enqueueBackgroundTaskNotification(notification: {
  598. taskId?: string;
  599. text: string;
  600. traceContext: {
  601. traceId: string;
  602. spanId: string;
  603. sessionId: SessionId;
  604. };
  605. }): void;
  606. };
  607. const traceContext = {
  608. traceId: `trace_background_notification_${terminalOutcome}`,
  609. spanId: `span_background_notification_${terminalOutcome}`,
  610. sessionId,
  611. };
  612. runtime.enqueueBackgroundTaskNotification({
  613. taskId: "agent_terminal_1",
  614. text: "<task-notification><task-id>agent_terminal_1</task-id></task-notification>",
  615. traceContext,
  616. });
  617. await waitForCondition(() => requestCount === 1);
  618. runtime.enqueueBackgroundTaskNotification({
  619. taskId: "agent_terminal_2",
  620. text: "<task-notification><task-id>agent_terminal_2</task-id></task-notification>",
  621. traceContext,
  622. });
  623. runtime.enqueueBackgroundTaskNotification({
  624. taskId: "agent_terminal_3",
  625. text: "<task-notification><task-id>agent_terminal_3</task-id></task-notification>",
  626. traceContext,
  627. });
  628. firstRequestMayFinish.resolve(undefined);
  629. await secondRequestStarted.promise;
  630. if (terminalOutcome === "stop") {
  631. expect(
  632. runtime.stopActiveForegroundExecution({ reason: "stop notification batch test" }),
  633. ).toMatchObject({ kind: "stopped" });
  634. }
  635. const continuation = await runtime.executeTurn("continue after terminal notification batch");
  636. expect(continuation.response).toBe("continued after terminal notification batch");
  637. expect(requestCount).toBe(3);
  638. const secondRequestText = providerMessagesToText(requestMessages[1]!);
  639. expect(secondRequestText).toContain("<task-id>agent_terminal_2</task-id>");
  640. expect(secondRequestText).toContain("<task-id>agent_terminal_3</task-id>");
  641. const continuationText = providerMessagesToText(requestMessages[2]!);
  642. expect(continuationText.match(/<task-id>agent_terminal_2<\/task-id>/g) ?? []).toHaveLength(1);
  643. expect(continuationText.match(/<task-id>agent_terminal_3<\/task-id>/g) ?? []).toHaveLength(1);
  644. expect(
  645. sessionStore.savedMessages.filter((message) => message.source === "background_task"),
  646. ).toHaveLength(2);
  647. expect(sessionStore.promotedSessionInputs).toHaveLength(3);
  648. expect(sessionStore.promotedSessionInputs[1]?.promotedMessageID).toBe(
  649. sessionStore.promotedSessionInputs[2]?.promotedMessageID,
  650. );
  651. },
  652. );
  653. it("wakes idle background notifications without scheduling a timeout", async () => {
  654. const sessionId = createSessionId("background-notification-idle-wake-ref");
  655. const sessionStore = new RecordingSessionStore();
  656. const firstRequest = createDeferred<readonly { content: ModelMessageContent }[]>();
  657. const runtime = createTestAgentRuntime(
  658. sessionId,
  659. {
  660. workingDirectory: "/tmp/zcode-background-notification-idle-wake-ref",
  661. },
  662. {
  663. eventStore: createTestSessionEventStore(),
  664. modelFactory: createTestModelFactory({
  665. async generateText(request: { messages: readonly { content: ModelMessageContent }[] }) {
  666. firstRequest.resolve(request.messages);
  667. return modelTextResult("processed referenced background notification");
  668. },
  669. } as never),
  670. sessionStore: sessionStore as unknown as SessionStorePort,
  671. },
  672. ) as unknown as {
  673. enqueueBackgroundTaskNotification(notification: {
  674. text: string;
  675. traceContext: {
  676. traceId: string;
  677. spanId: string;
  678. sessionId: SessionId;
  679. };
  680. }): void;
  681. };
  682. const traceContext = {
  683. traceId: "trace_background_idle_wake_ref",
  684. spanId: "span_background_idle_wake_ref",
  685. sessionId,
  686. };
  687. const timeoutRecorder = recordSetTimeoutCalls();
  688. runtime.enqueueBackgroundTaskNotification({
  689. text: "<task-notification>\n<task-id>agent_idle_ref</task-id>\n</task-notification>",
  690. traceContext,
  691. });
  692. timeoutRecorder.restore();
  693. const requestMessages = await firstRequest.promise;
  694. expect(providerMessagesToText(requestMessages)).toContain("<task-id>agent_idle_ref</task-id>");
  695. expect(timeoutRecorder.calls).toEqual([]);
  696. });
  697. it("保留 loopState 初始化前取消的 background subagent composition 标记", async () => {
  698. const sessionId = createSessionId("background-notification-pre-loop-cancel");
  699. const eventStore = createTestSessionEventStore();
  700. const setupStarted = createDeferred<void>();
  701. const setupMayFinish = createDeferred<void>();
  702. const abortController = new AbortController();
  703. const runtime = createTestAgentRuntime(
  704. sessionId,
  705. { workingDirectory: "/tmp/zcode-background-notification-pre-loop-cancel" },
  706. {
  707. eventStore,
  708. modelAdapter: {
  709. async generateText() {
  710. throw new Error("provider request must not start");
  711. },
  712. } as never,
  713. },
  714. );
  715. (runtime as any).runUserPromptSubmitHooks = async (...args: any[]) => {
  716. setupStarted.resolve();
  717. await setupMayFinish.promise;
  718. throw args[3]?.reason ?? new Error("cancelled before loop state");
  719. };
  720. const turn = (runtime as any).executeTurnCommand("consume background result", undefined, {
  721. abortSignal: abortController.signal,
  722. backgroundSubagentResultConsumed: true,
  723. inputSource: "background_task",
  724. inputVisibility: "model-only",
  725. recordedInputMessageId: "background-result-message",
  726. skipInputRecord: true,
  727. traceContext: {
  728. sessionId,
  729. spanId: "span_background_notification_pre_loop_cancel",
  730. traceId: "trace_background_notification_pre_loop_cancel",
  731. },
  732. });
  733. await setupStarted.promise;
  734. abortController.abort(new Error("user stopped before model loop"));
  735. setupMayFinish.resolve();
  736. await expect(turn).rejects.toBeDefined();
  737. const cancelled = (await eventStore.getEvents(sessionId)).find(
  738. (event) => event.type === SessionEventType.TurnComplete,
  739. );
  740. expect(cancelled?.payload).toMatchObject({
  741. backgroundSubagentResultConsumed: true,
  742. resultType: "cancelled",
  743. });
  744. });
  745. it("drains active-loop background notifications into model-only history without starting a turn", async () => {
  746. const sessionId = createSessionId("background-active-loop-drain");
  747. const sessionStore = new RecordingSessionStore();
  748. const generateText = vi.fn();
  749. const runtime = createTestAgentRuntime(
  750. sessionId,
  751. {
  752. workingDirectory: "/tmp/zcode-background-active-loop-drain",
  753. },
  754. {
  755. eventStore: createTestSessionEventStore(),
  756. modelFactory: createTestModelFactory({ generateText } as never),
  757. sessionStore: sessionStore as unknown as SessionStorePort,
  758. },
  759. ) as unknown as AgentRuntime & {
  760. drainPendingRuntimeCommandsForActiveLoop(): Promise<{
  761. consumedCommandIds: readonly string[];
  762. drained: number;
  763. messageIds: readonly string[];
  764. }>;
  765. messageHistory: {
  766. toRuntimeEntries(): readonly { message: { content: ModelMessageContent } }[];
  767. };
  768. runtimeCommandQueue: {
  769. enqueue(command: {
  770. branchGeneration: number;
  771. createdAt: Date;
  772. id: string;
  773. mode: "task-notification";
  774. priority: "next";
  775. source: "background_task";
  776. text: string;
  777. traceContext: {
  778. sessionId: SessionId;
  779. spanId: string;
  780. traceId: string;
  781. };
  782. }): void;
  783. };
  784. };
  785. const traceContext = {
  786. traceId: "trace_background_active_loop_drain",
  787. spanId: "span_background_active_loop_drain",
  788. sessionId,
  789. };
  790. runtime.runtimeCommandQueue.enqueue({
  791. branchGeneration: 0,
  792. createdAt: new Date(),
  793. id: createRuntimeCommandId(),
  794. mode: "task-notification",
  795. priority: "next",
  796. source: "background_task",
  797. text: "<task-notification><task-id>active-drain-1</task-id></task-notification>",
  798. traceContext,
  799. });
  800. runtime.runtimeCommandQueue.enqueue({
  801. branchGeneration: 0,
  802. createdAt: new Date(),
  803. id: createRuntimeCommandId(),
  804. mode: "task-notification",
  805. priority: "next",
  806. source: "background_task",
  807. text: "<task-notification><task-id>active-drain-2</task-id></task-notification>",
  808. traceContext,
  809. });
  810. const result = await runtime.drainPendingRuntimeCommandsForActiveLoop();
  811. expect(result.drained).toBe(2);
  812. expect(result.messageIds).toHaveLength(2);
  813. expect(result.consumedCommandIds).toHaveLength(2);
  814. expect(generateText).not.toHaveBeenCalled();
  815. const persisted = sessionStore.savedMessages.filter(
  816. (message) => message.source === "background_task",
  817. );
  818. expect(persisted).toHaveLength(2);
  819. expect(persisted.every((message) => message.visibility === "model-only")).toBe(true);
  820. const runtimeText = runtime.messageHistory
  821. .toRuntimeEntries()
  822. .map((entry) => modelMessageContentToText(entry.message.content))
  823. .join("\n");
  824. expect(runtimeText).toContain("<task-id>active-drain-1</task-id>");
  825. expect(runtimeText).toContain("<task-id>active-drain-2</task-id>");
  826. });
  827. it("drops active-loop notifications queued by an older rewind branch generation", async () => {
  828. const sessionId = createSessionId("background-active-loop-stale-branch");
  829. const sessionStore = new RecordingSessionStore();
  830. const runtime = createTestAgentRuntime(
  831. sessionId,
  832. { workingDirectory: "/tmp/zcode-background-active-loop-stale-branch" },
  833. {
  834. eventStore: createTestSessionEventStore(),
  835. modelFactory: createTestModelFactory({ generateText: vi.fn() } as never),
  836. sessionStore: sessionStore as unknown as SessionStorePort,
  837. },
  838. ) as unknown as AgentRuntime & {
  839. branchGeneration: number;
  840. drainPendingRuntimeCommandsForActiveLoop(): Promise<{
  841. consumedCommandIds: readonly string[];
  842. drained: number;
  843. messageIds: readonly string[];
  844. }>;
  845. runtimeCommandQueue: {
  846. enqueue(command: {
  847. branchGeneration: number;
  848. createdAt: Date;
  849. id: string;
  850. mode: "task-notification";
  851. priority: "next";
  852. source: "background_task";
  853. text: string;
  854. traceContext: {
  855. sessionId: SessionId;
  856. spanId: string;
  857. traceId: string;
  858. };
  859. }): void;
  860. };
  861. };
  862. runtime.runtimeCommandQueue.enqueue({
  863. branchGeneration: 0,
  864. createdAt: new Date(),
  865. id: createRuntimeCommandId(),
  866. mode: "task-notification",
  867. priority: "next",
  868. source: "background_task",
  869. text: "<task-notification><task-id>stale-task</task-id></task-notification>",
  870. traceContext: {
  871. traceId: "trace_background_active_loop_stale",
  872. spanId: "span_background_active_loop_stale",
  873. sessionId,
  874. },
  875. });
  876. runtime.branchGeneration = 1;
  877. const result = await runtime.drainPendingRuntimeCommandsForActiveLoop();
  878. expect(result).toMatchObject({ drained: 0, consumedCommandIds: [], messageIds: [] });
  879. expect(sessionStore.savedMessages).toEqual([]);
  880. });
  881. it("leaves commands arriving after the active-loop snapshot for the next drain", async () => {
  882. const sessionId = createSessionId("background-active-loop-continuous-drain");
  883. const firstSaveStarted = createDeferred<void>();
  884. const firstSaveMayFinish = createDeferred<void>();
  885. const sessionStore = new RecordingSessionStore();
  886. const saveMessage = sessionStore.saveMessage.bind(sessionStore);
  887. let saveMessageCallCount = 0;
  888. sessionStore.saveMessage = async (input) => {
  889. saveMessageCallCount++;
  890. if (saveMessageCallCount === 1) {
  891. firstSaveStarted.resolve(undefined);
  892. await firstSaveMayFinish.promise;
  893. }
  894. await saveMessage(input);
  895. };
  896. const runtime = createTestAgentRuntime(
  897. sessionId,
  898. {
  899. workingDirectory: "/tmp/zcode-background-active-loop-continuous-drain",
  900. },
  901. {
  902. eventStore: createTestSessionEventStore(),
  903. modelFactory: createTestModelFactory({ generateText: vi.fn() } as never),
  904. sessionStore: sessionStore as unknown as SessionStorePort,
  905. },
  906. ) as unknown as AgentRuntime & {
  907. drainPendingRuntimeCommandsForActiveLoop(): Promise<{
  908. consumedCommandIds: readonly string[];
  909. drained: number;
  910. messageIds: readonly string[];
  911. }>;
  912. runtimeCommandQueue: {
  913. enqueue(command: {
  914. branchGeneration: number;
  915. createdAt: Date;
  916. id: string;
  917. mode: "task-notification";
  918. priority: "next";
  919. source: "background_task";
  920. text: string;
  921. traceContext: {
  922. sessionId: SessionId;
  923. spanId: string;
  924. traceId: string;
  925. };
  926. }): void;
  927. };
  928. };
  929. const traceContext = {
  930. traceId: "trace_background_active_loop_continuous_drain",
  931. spanId: "span_background_active_loop_continuous_drain",
  932. sessionId,
  933. };
  934. const enqueueNotification = (taskId: string) => {
  935. runtime.runtimeCommandQueue.enqueue({
  936. branchGeneration: 0,
  937. createdAt: new Date(),
  938. id: createRuntimeCommandId(),
  939. mode: "task-notification",
  940. priority: "next",
  941. source: "background_task",
  942. text: `<task-notification><task-id>${taskId}</task-id></task-notification>`,
  943. traceContext,
  944. });
  945. };
  946. enqueueNotification("continuous-drain-1");
  947. const drain = runtime.drainPendingRuntimeCommandsForActiveLoop();
  948. await firstSaveStarted.promise;
  949. enqueueNotification("continuous-drain-2");
  950. firstSaveMayFinish.resolve(undefined);
  951. const result = await drain;
  952. expect(result.drained).toBe(1);
  953. expect(result.messageIds).toHaveLength(1);
  954. expect(result.consumedCommandIds).toHaveLength(1);
  955. expect(sessionStore.savedMessages).toHaveLength(1);
  956. const nextResult = await runtime.drainPendingRuntimeCommandsForActiveLoop();
  957. expect(nextResult.drained).toBe(1);
  958. expect(sessionStore.savedMessages).toHaveLength(2);
  959. });
  960. it("leaves prompt commands queued when draining active-loop runtime commands", async () => {
  961. const sessionId = createSessionId("background-active-loop-prompt-drain");
  962. const sessionStore = new RecordingSessionStore();
  963. const runtime = createTestAgentRuntime(
  964. sessionId,
  965. {
  966. workingDirectory: "/tmp/zcode-background-active-loop-prompt-drain",
  967. },
  968. {
  969. eventStore: createTestSessionEventStore(),
  970. modelFactory: createTestModelFactory({ generateText: vi.fn() } as never),
  971. sessionStore: sessionStore as unknown as SessionStorePort,
  972. },
  973. ) as unknown as AgentRuntime & {
  974. drainPendingRuntimeCommandsForActiveLoop(): Promise<{
  975. consumedCommandIds: readonly string[];
  976. drained: number;
  977. messageIds: readonly string[];
  978. }>;
  979. messageHistory: {
  980. toRuntimeEntries(): readonly { message: { content: ModelMessageContent } }[];
  981. };
  982. runtimeCommandQueue: {
  983. enqueue(command: PromptRuntimeCommand): void;
  984. size(): number;
  985. };
  986. };
  987. const traceContext = {
  988. traceId: "trace_background_active_loop_prompt",
  989. spanId: "span_background_active_loop_prompt",
  990. sessionId,
  991. };
  992. const command: PromptRuntimeCommand = {
  993. createdAt: new Date(),
  994. id: createRuntimeCommandId(),
  995. input: "queued prompt stays in outer queue",
  996. mode: "prompt",
  997. priority: "next",
  998. reject: vi.fn(),
  999. resolve: vi.fn(),
  1000. traceContext,
  1001. };
  1002. runtime.runtimeCommandQueue.enqueue(command);
  1003. const result = await runtime.drainPendingRuntimeCommandsForActiveLoop();
  1004. expect(result.drained).toBe(0);
  1005. expect(result.consumedCommandIds).toEqual([]);
  1006. expect(result.messageIds).toEqual([]);
  1007. expect(runtime.runtimeCommandQueue.size()).toBe(1);
  1008. expect(command.resolve).not.toHaveBeenCalled();
  1009. expect(command.reject).not.toHaveBeenCalled();
  1010. const runtimeText = runtime.messageHistory
  1011. .toRuntimeEntries()
  1012. .map((entry) => modelMessageContentToText(entry.message.content))
  1013. .join("\n");
  1014. expect(runtimeText).not.toContain("queued prompt stays in outer queue");
  1015. });
  1016. it("drops queued child Bash task notifications after the subagent runtime is sealed", async () => {
  1017. const sessionId = createSessionId("background-sealed-child-queued-bash");
  1018. const sessionStore = new RecordingSessionStore();
  1019. const generateText = vi.fn();
  1020. const runtime = createTestAgentRuntime(
  1021. sessionId,
  1022. {
  1023. taskType: "subagent_child",
  1024. workingDirectory: "/tmp/zcode-background-sealed-child-queued-bash",
  1025. },
  1026. {
  1027. eventStore: createTestSessionEventStore(),
  1028. modelFactory: createTestModelFactory({ generateText } as never),
  1029. sessionStore: sessionStore as unknown as SessionStorePort,
  1030. },
  1031. ) as unknown as AgentRuntime & {
  1032. backgroundTaskNotificationsSealed: boolean;
  1033. drainRuntimeCommandQueue(): Promise<void>;
  1034. enqueueBackgroundTaskNotification(notification: {
  1035. taskId?: string;
  1036. text: string;
  1037. toolName?: string;
  1038. traceContext: {
  1039. sessionId: SessionId;
  1040. spanId: string;
  1041. traceId: string;
  1042. };
  1043. }): void;
  1044. runtimeCommandDrainActive: boolean;
  1045. runtimeCommandQueue: {
  1046. size(): number;
  1047. };
  1048. sealBackgroundTaskNotifications(input: {
  1049. reason: string;
  1050. traceContext: {
  1051. sessionId: SessionId;
  1052. spanId: string;
  1053. traceId: string;
  1054. };
  1055. }): void;
  1056. };
  1057. const traceContext = {
  1058. traceId: "trace_background_sealed_child_queued_bash",
  1059. spanId: "span_background_sealed_child_queued_bash",
  1060. sessionId,
  1061. };
  1062. runtime.runtimeCommandDrainActive = true;
  1063. runtime.enqueueBackgroundTaskNotification({
  1064. taskId: "child_bash_queued_before_seal",
  1065. text:
  1066. "<task-notification>\n" +
  1067. "<task-id>child_bash_queued_before_seal</task-id>\n" +
  1068. "<status>completed</status>\n" +
  1069. "</task-notification>",
  1070. toolName: "Bash",
  1071. traceContext,
  1072. });
  1073. expect(runtime.runtimeCommandQueue.size()).toBe(1);
  1074. runtime.sealBackgroundTaskNotifications({
  1075. reason: "subagent_terminal",
  1076. traceContext,
  1077. });
  1078. runtime.runtimeCommandDrainActive = false;
  1079. await runtime.drainRuntimeCommandQueue();
  1080. expect(runtime.runtimeCommandQueue.size()).toBe(0);
  1081. expect(generateText).not.toHaveBeenCalled();
  1082. expect(JSON.stringify(sessionStore.savedMessages)).not.toContain(
  1083. "child_bash_queued_before_seal",
  1084. );
  1085. });
  1086. it("filters stale and suppressed members without dropping a valid notification batch member", async () => {
  1087. const sessionId = createSessionId("background-filtered-batch-members");
  1088. const sessionStore = new RecordingSessionStore();
  1089. const requestMessages: Array<readonly { content: ModelMessageContent }[]> = [];
  1090. const runtime = createTestAgentRuntime(
  1091. sessionId,
  1092. {
  1093. taskType: "subagent_child",
  1094. workingDirectory: "/tmp/zcode-background-filtered-batch-members",
  1095. },
  1096. {
  1097. eventStore: createTestSessionEventStore(),
  1098. modelFactory: createTestModelFactory({
  1099. async generateText(request: { messages: readonly { content: ModelMessageContent }[] }) {
  1100. requestMessages.push(request.messages);
  1101. return modelTextResult("processed valid notification");
  1102. },
  1103. } as never),
  1104. sessionStore: sessionStore as unknown as SessionStorePort,
  1105. },
  1106. ) as unknown as AgentRuntime & {
  1107. branchGeneration: number;
  1108. drainRuntimeCommandQueue(): Promise<void>;
  1109. enqueueBackgroundTaskNotification(notification: {
  1110. taskId?: string;
  1111. text: string;
  1112. toolName?: string;
  1113. traceContext: {
  1114. sessionId: SessionId;
  1115. spanId: string;
  1116. traceId: string;
  1117. };
  1118. }): void;
  1119. runtimeCommandDrainActive: boolean;
  1120. runtimeCommandQueue: {
  1121. enqueue(command: {
  1122. branchGeneration: number;
  1123. createdAt: Date;
  1124. id: string;
  1125. mode: "task-notification";
  1126. priority: "next";
  1127. source: "background_task";
  1128. text: string;
  1129. traceContext: {
  1130. sessionId: SessionId;
  1131. spanId: string;
  1132. traceId: string;
  1133. };
  1134. }): void;
  1135. };
  1136. sealBackgroundTaskNotifications(input: {
  1137. reason: string;
  1138. traceContext: {
  1139. sessionId: SessionId;
  1140. spanId: string;
  1141. traceId: string;
  1142. };
  1143. }): void;
  1144. };
  1145. const traceContext = {
  1146. traceId: "trace_background_filtered_batch_members",
  1147. spanId: "span_background_filtered_batch_members",
  1148. sessionId,
  1149. };
  1150. runtime.branchGeneration = 1;
  1151. runtime.runtimeCommandDrainActive = true;
  1152. runtime.enqueueBackgroundTaskNotification({
  1153. taskId: "suppressed-bash",
  1154. text: "<task-notification><task-id>suppressed-bash</task-id></task-notification>",
  1155. toolName: "Bash",
  1156. traceContext,
  1157. });
  1158. runtime.enqueueBackgroundTaskNotification({
  1159. taskId: "valid-agent",
  1160. text: "<task-notification><task-id>valid-agent</task-id></task-notification>",
  1161. toolName: "Agent",
  1162. traceContext,
  1163. });
  1164. runtime.runtimeCommandQueue.enqueue({
  1165. branchGeneration: 0,
  1166. createdAt: new Date(),
  1167. id: createRuntimeCommandId(),
  1168. mode: "task-notification",
  1169. priority: "next",
  1170. source: "background_task",
  1171. text: "<task-notification><task-id>stale-agent</task-id></task-notification>",
  1172. traceContext,
  1173. });
  1174. runtime.sealBackgroundTaskNotifications({
  1175. reason: "subagent_terminal",
  1176. traceContext,
  1177. });
  1178. runtime.runtimeCommandDrainActive = false;
  1179. await runtime.drainRuntimeCommandQueue();
  1180. expect(requestMessages).toHaveLength(1);
  1181. const requestText = providerMessagesToText(requestMessages[0]!);
  1182. expect(requestText).toContain("<task-id>valid-agent</task-id>");
  1183. expect(requestText).not.toContain("<task-id>suppressed-bash</task-id>");
  1184. expect(requestText).not.toContain("<task-id>stale-agent</task-id>");
  1185. expect(
  1186. sessionStore.savedMessages.filter((message) => message.source === "background_task"),
  1187. ).toHaveLength(1);
  1188. });
  1189. it("queues task-notification commands behind an active prompt command", async () => {
  1190. const sessionId = createSessionId("background-notification-waits-for-prompt");
  1191. const sessionStore = new RecordingSessionStore();
  1192. const firstPromptRequest = createDeferred<readonly { content: ModelMessageContent }[]>();
  1193. const firstPromptCanFinish = createDeferred<void>();
  1194. const notificationRequest = createDeferred<readonly { content: ModelMessageContent }[]>();
  1195. let requestCount = 0;
  1196. const runtime = createTestAgentRuntime(
  1197. sessionId,
  1198. {
  1199. workingDirectory: "/tmp/zcode-background-notification-waits-for-prompt",
  1200. },
  1201. {
  1202. eventStore: createTestSessionEventStore(),
  1203. modelFactory: createTestModelFactory({
  1204. async generateText(request: { messages: readonly { content: ModelMessageContent }[] }) {
  1205. requestCount += 1;
  1206. if (requestCount === 1) {
  1207. firstPromptRequest.resolve(request.messages);
  1208. await firstPromptCanFinish.promise;
  1209. return modelTextResult("prompt done");
  1210. }
  1211. notificationRequest.resolve(request.messages);
  1212. return modelTextResult("notification done");
  1213. },
  1214. } as never),
  1215. sessionStore: sessionStore as unknown as SessionStorePort,
  1216. },
  1217. ) as unknown as AgentRuntime & {
  1218. enqueueBackgroundTaskNotification(notification: {
  1219. text: string;
  1220. traceContext: {
  1221. traceId: string;
  1222. spanId: string;
  1223. sessionId: SessionId;
  1224. };
  1225. }): void;
  1226. };
  1227. const traceContext = {
  1228. traceId: "trace_background_waits_for_prompt",
  1229. spanId: "span_background_waits_for_prompt",
  1230. sessionId,
  1231. };
  1232. const promptTurn = runtime.executeTurn("user prompt");
  1233. await firstPromptRequest.promise;
  1234. runtime.enqueueBackgroundTaskNotification({
  1235. text: "<task-notification>\n<task-id>agent_waits_for_prompt</task-id>\n</task-notification>",
  1236. traceContext,
  1237. });
  1238. await waitForMacrotask();
  1239. expect(requestCount).toBe(1);
  1240. firstPromptCanFinish.resolve();
  1241. await expect(promptTurn).resolves.toMatchObject({ response: "prompt done" });
  1242. const requestMessages = await notificationRequest.promise;
  1243. expect(providerMessagesToText(requestMessages)).toContain(
  1244. "<task-id>agent_waits_for_prompt</task-id>",
  1245. );
  1246. expect(requestCount).toBe(2);
  1247. });
  1248. it("preserves the provider cause across failed background local-agent surfaces", async () => {
  1249. const providerMessage = [
  1250. "Requests are too frequent.",
  1251. ` Provider spacing and full payload must remain unchanged: ${"x".repeat(520)}`,
  1252. "Request id: unit-background-subagent-rate-limit",
  1253. ].join("\n");
  1254. const sessionId = createSessionId("subagent-background-rate-limit");
  1255. const turnId = createTurnId("subagent-background-rate-limit-turn");
  1256. const notifications: string[] = [];
  1257. const emittedEvents: SessionEvent[] = [];
  1258. const providerError = Object.assign(new Error(providerMessage), {
  1259. code: "model_rate_limited",
  1260. context: {
  1261. providerCode: "AccountRateLimitExceeded",
  1262. statusCode: 429,
  1263. },
  1264. name: "AiSdkModelAdapterError",
  1265. });
  1266. const turnError = createTurnFailureError(providerError, undefined, "Turn execution failed");
  1267. const port = createExploreSubagentPort({
  1268. createAgentId: () => "agent_background_rate_limit",
  1269. emitParentEvent: async (event) => {
  1270. emittedEvents.push(event);
  1271. },
  1272. enqueueParentTaskNotification: ({ text }) => {
  1273. notifications.push(text);
  1274. },
  1275. runExploreAgent: async (request) => {
  1276. await request.onSessionReady?.();
  1277. throw turnError;
  1278. },
  1279. });
  1280. await port.start?.(createSubagentRunRequest({ sessionId, turnId }));
  1281. await waitForCondition(() => notifications.length === 1);
  1282. await waitForCondition(() =>
  1283. emittedEvents.some((event) => event.type === SessionEventType.SubagentStopped),
  1284. );
  1285. const notification = notifications[0]!;
  1286. expect(notification).toContain(
  1287. `<summary>Agent general-purpose task &quot;Auto background test&quot; failed. ${providerMessage}</summary>`,
  1288. );
  1289. expect(notification).toContain(`<error>${providerMessage}</error>`);
  1290. expect(notification).not.toContain("Turn execution failed");
  1291. expect(await port.getTask?.("agent_background_rate_limit")).toMatchObject({
  1292. status: "failed",
  1293. error: providerMessage,
  1294. });
  1295. expect(emittedEvents).toContainEqual(
  1296. expect.objectContaining({
  1297. type: SessionEventType.SubagentStopped,
  1298. payload: expect.objectContaining({
  1299. status: "failed",
  1300. error: providerMessage,
  1301. }),
  1302. }),
  1303. );
  1304. });
  1305. it("queues parent notification before emitting background completion", async () => {
  1306. const sessionId = createSessionId("subagent-notification-before-completion-event");
  1307. const turnId = createTurnId("subagent-notification-before-completion-event-turn");
  1308. const childGate = createDeferred<void>();
  1309. const completionEventStarted = createDeferred<void>();
  1310. const completionEventMayFinish = createDeferred<void>();
  1311. const observed: string[] = [];
  1312. let childRuntimeBackground: boolean | undefined;
  1313. const port = createExploreSubagentPort({
  1314. createAgentId: () => "agent_notification_before_completion_event",
  1315. emitParentEvent: async (event) => {
  1316. observed.push(`event:${event.type}`);
  1317. if (event.type === SessionEventType.BackgroundTaskCompleted) {
  1318. completionEventStarted.resolve();
  1319. await completionEventMayFinish.promise;
  1320. }
  1321. },
  1322. enqueueParentTaskNotification: () => {
  1323. observed.push("notification");
  1324. },
  1325. runExploreAgent: async (request) => {
  1326. await request.onSessionReady?.();
  1327. childRuntimeBackground = request.background;
  1328. await childGate.promise;
  1329. return {
  1330. events: [],
  1331. response: "child finished before completion event",
  1332. traceId: "trace_subagent_notification_before_completion_event",
  1333. };
  1334. },
  1335. });
  1336. const output = await port.start?.(createSubagentRunRequest({ sessionId, turnId }));
  1337. expect(output).toMatchObject({
  1338. status: "async_launched",
  1339. agentId: "agent_notification_before_completion_event",
  1340. });
  1341. await waitForCondition(() => childRuntimeBackground === true);
  1342. expect(childRuntimeBackground).toBe(true);
  1343. childGate.resolve();
  1344. await completionEventStarted.promise;
  1345. const completedIndex = observed.indexOf(`event:${SessionEventType.BackgroundTaskCompleted}`);
  1346. const notificationIndex = observed.indexOf("notification");
  1347. expect(notificationIndex).toBeGreaterThan(-1);
  1348. expect(notificationIndex).toBeLessThan(completedIndex);
  1349. completionEventMayFinish.resolve();
  1350. await waitForCondition(() => observed.includes(`event:${SessionEventType.SubagentStopped}`));
  1351. const stoppedIndex = observed.indexOf(`event:${SessionEventType.SubagentStopped}`);
  1352. expect(completedIndex).toBeGreaterThan(-1);
  1353. expect(stoppedIndex).toBeGreaterThan(completedIndex);
  1354. });
  1355. it("auto-backgrounds with a referenced timeout and publishes the child result", async () => {
  1356. const sessionId = createSessionId("subagent-auto-background-timeout-ref");
  1357. const turnId = createTurnId("subagent-auto-background-timeout-ref-turn");
  1358. const childGate = createDeferred<void>();
  1359. const notifications: Array<Record<string, unknown>> = [];
  1360. const port = createExploreSubagentPort({
  1361. autoBackgroundMs: 1,
  1362. createAgentId: () => "agent_auto_background_timeout_ref",
  1363. emitParentEvent: async () => {},
  1364. enqueueParentTaskNotification: (notification) => {
  1365. notifications.push(notification);
  1366. },
  1367. runExploreAgent: async (request) => {
  1368. await request.onSessionReady?.();
  1369. await childGate.promise;
  1370. return {
  1371. events: [],
  1372. response: "auto background timeout ref child finished",
  1373. traceId: "trace_subagent_auto_background_timeout_ref",
  1374. };
  1375. },
  1376. });
  1377. const unrefRecorder = recordSetTimeoutUnrefCalls();
  1378. const outputPromise = port.run(createSubagentRunRequest({ sessionId, turnId }));
  1379. let output: Awaited<typeof outputPromise>;
  1380. try {
  1381. output = await outputPromise;
  1382. } finally {
  1383. unrefRecorder.restore();
  1384. }
  1385. expect(output).toMatchObject({
  1386. status: "async_launched",
  1387. agentId: "agent_auto_background_timeout_ref",
  1388. backgroundTaskId: "agent_auto_background_timeout_ref",
  1389. });
  1390. expect(unrefRecorder.calls).toEqual([]);
  1391. childGate.resolve();
  1392. await waitForCondition(() => notifications.length === 1);
  1393. expect(notifications[0]).toMatchObject({
  1394. originMeta: {
  1395. backgroundSource: "subagent",
  1396. title: "Auto background test",
  1397. workId: "agent_auto_background_timeout_ref",
  1398. },
  1399. taskId: "agent_auto_background_timeout_ref",
  1400. });
  1401. expect(notifications[0]?.text).toContain(
  1402. "<task-id>agent_auto_background_timeout_ref</task-id>",
  1403. );
  1404. expect(notifications[0]?.text).toContain("<status>completed</status>");
  1405. expect(notifications[0]?.text).toContain("auto background timeout ref child finished");
  1406. });
  1407. it("does not mark background local agents notified without a parent notification queue", async () => {
  1408. const sessionId = createSessionId("subagent-notification-queue-missing");
  1409. const turnId = createTurnId("subagent-notification-queue-missing-turn");
  1410. const childGate = createDeferred<void>();
  1411. const port = createExploreSubagentPort({
  1412. createAgentId: () => "agent_notification_queue_missing",
  1413. emitParentEvent: async () => {},
  1414. runExploreAgent: async (request) => {
  1415. await request.onSessionReady?.();
  1416. await childGate.promise;
  1417. return {
  1418. events: [],
  1419. response: "child finished without parent queue",
  1420. traceId: "trace_subagent_notification_queue_missing",
  1421. };
  1422. },
  1423. });
  1424. const output = await port.start?.(createSubagentRunRequest({ sessionId, turnId }));
  1425. expect(output).toMatchObject({
  1426. status: "async_launched",
  1427. agentId: "agent_notification_queue_missing",
  1428. });
  1429. childGate.resolve();
  1430. await waitForCondition(async () => {
  1431. const task = await port.getTask?.("agent_notification_queue_missing");
  1432. return task?.status === "completed";
  1433. });
  1434. const task = await port.getTask?.("agent_notification_queue_missing");
  1435. expect(task).toMatchObject({
  1436. status: "completed",
  1437. agentId: "agent_notification_queue_missing",
  1438. });
  1439. expect(task?.notified).not.toBe(true);
  1440. });
  1441. it("does not fake-notify background local agents when parent notification enqueue fails", async () => {
  1442. const sessionId = createSessionId("subagent-notification-enqueue-fails");
  1443. const turnId = createTurnId("subagent-notification-enqueue-fails-turn");
  1444. const childGate = createDeferred<void>();
  1445. const port = createExploreSubagentPort({
  1446. createAgentId: () => "agent_notification_enqueue_fails",
  1447. emitParentEvent: async () => {},
  1448. enqueueParentTaskNotification: () => {
  1449. throw new Error("parent queue unavailable");
  1450. },
  1451. runExploreAgent: async (request) => {
  1452. await request.onSessionReady?.();
  1453. await childGate.promise;
  1454. return {
  1455. events: [],
  1456. response: "child finished but parent queue failed",
  1457. traceId: "trace_subagent_notification_enqueue_fails",
  1458. };
  1459. },
  1460. });
  1461. const output = await port.start?.(createSubagentRunRequest({ sessionId, turnId }));
  1462. expect(output).toMatchObject({
  1463. status: "async_launched",
  1464. agentId: "agent_notification_enqueue_fails",
  1465. });
  1466. childGate.resolve();
  1467. await waitForCondition(async () => {
  1468. const task = await port.getTask?.("agent_notification_enqueue_fails");
  1469. return task?.status === "completed" || task?.status === "failed";
  1470. });
  1471. const task = await port.getTask?.("agent_notification_enqueue_fails");
  1472. expect(task).toMatchObject({
  1473. status: "completed",
  1474. agentId: "agent_notification_enqueue_fails",
  1475. });
  1476. expect(task?.notified).not.toBe(true);
  1477. });
  1478. it("cancels auto-background timeout when a foreground local agent completes first", async () => {
  1479. const sessionId = createSessionId("subagent-auto-background-cancelled");
  1480. const turnId = createTurnId("subagent-auto-background-cancelled-turn");
  1481. const blockedArtifactWrite = createDeferred<void>();
  1482. let outputWriteStarted = false;
  1483. const notifications: string[] = [];
  1484. const actualFs = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
  1485. vi.resetModules();
  1486. vi.doMock("node:fs/promises", () => ({
  1487. ...actualFs,
  1488. writeFile: vi.fn(async (...args: Parameters<typeof actualFs.writeFile>) => {
  1489. const [path] = args;
  1490. if (String(path).endsWith("/output.txt") && !outputWriteStarted) {
  1491. outputWriteStarted = true;
  1492. await blockedArtifactWrite.promise;
  1493. }
  1494. return actualFs.writeFile(...args);
  1495. }),
  1496. }));
  1497. try {
  1498. const { createExploreSubagentPort: createPortWithBlockedArtifactWrite } =
  1499. await import("../src/subagent/runner.js");
  1500. const port = createPortWithBlockedArtifactWrite({
  1501. autoBackgroundMs: 1,
  1502. createAgentId: () => "agent_auto_background_cancelled",
  1503. emitParentEvent: async () => {},
  1504. enqueueParentTaskNotification: ({ text }) => {
  1505. notifications.push(text);
  1506. },
  1507. runExploreAgent: async (request) => {
  1508. await request.onSessionReady?.();
  1509. return {
  1510. events: [],
  1511. response: "foreground child beat timeout",
  1512. traceId: "trace_subagent_auto_background_cancelled",
  1513. };
  1514. },
  1515. });
  1516. const outputPromise = port.run(createSubagentRunRequest({ sessionId, turnId }));
  1517. await waitForCondition(() => outputWriteStarted);
  1518. await new Promise((resolve) => setTimeout(resolve, 10));
  1519. const taskWhileArtifactWriteIsPending = await port.getTask?.(
  1520. "agent_auto_background_cancelled",
  1521. );
  1522. blockedArtifactWrite.resolve();
  1523. const output = await outputPromise;
  1524. expect(output).toMatchObject({
  1525. status: "completed",
  1526. agentId: "agent_auto_background_cancelled",
  1527. });
  1528. expect(taskWhileArtifactWriteIsPending).toMatchObject({
  1529. status: "running",
  1530. isBackgrounded: false,
  1531. });
  1532. const task = await port.getTask?.("agent_auto_background_cancelled");
  1533. expect(task).toMatchObject({
  1534. status: "completed",
  1535. isBackgrounded: false,
  1536. });
  1537. expect(notifications).toEqual([]);
  1538. } finally {
  1539. blockedArtifactWrite.resolve();
  1540. vi.doUnmock("node:fs/promises");
  1541. vi.resetModules();
  1542. }
  1543. });
  1544. it("keeps foreground local agents inline when auto-background timeout is not configured", async () => {
  1545. const sessionId = createSessionId("subagent-no-auto-background");
  1546. const turnId = createTurnId("subagent-no-auto-background-turn");
  1547. const notifications: string[] = [];
  1548. const port = createExploreSubagentPort({
  1549. createAgentId: () => "agent_no_auto_background",
  1550. emitParentEvent: async () => {},
  1551. enqueueParentTaskNotification: ({ text }) => {
  1552. notifications.push(text);
  1553. },
  1554. runExploreAgent: async (request) => {
  1555. await request.onSessionReady?.();
  1556. return {
  1557. events: [],
  1558. response: "foreground child finished",
  1559. traceId: "trace_subagent_no_auto_background",
  1560. };
  1561. },
  1562. });
  1563. const output = await port.run(createSubagentRunRequest({ sessionId, turnId }));
  1564. expect(output).toMatchObject({
  1565. status: "completed",
  1566. agentId: "agent_no_auto_background",
  1567. });
  1568. expect(notifications).toEqual([]);
  1569. });
  1570. it.each(["explicit", "profile", "timeout"])(
  1571. "supports off-peak background model overrides: %s",
  1572. async (kind) => {
  1573. const gate = createDeferred<void>();
  1574. const calls: unknown[] = [];
  1575. const port = createExploreSubagentPort({
  1576. createAgentId: () => "idle-background",
  1577. ...(kind === "timeout" ? { autoBackgroundMs: 1 } : {}),
  1578. emitParentEvent: async () => {},
  1579. profiles: [
  1580. {
  1581. name: "Idle Reviewer",
  1582. description: "Review",
  1583. source: "user",
  1584. systemPrompt: "Review",
  1585. tools: ["Read"],
  1586. background: kind === "profile",
  1587. },
  1588. ],
  1589. runExploreAgent: async (request, options) => {
  1590. calls.push(options);
  1591. await request.onSessionReady?.();
  1592. await gate.promise;
  1593. return { events: [], response: "done", traceId: "idle-background-trace" };
  1594. },
  1595. });
  1596. const modelOverride = {
  1597. selection: { providerId: "idle", modelId: "model" },
  1598. background: "allow" as const,
  1599. };
  1600. try {
  1601. const output = await port.launch(
  1602. {
  1603. ...createSubagentRunRequest({
  1604. sessionId: createSessionId("idle-parent"),
  1605. turnId: createTurnId("idle-turn"),
  1606. }),
  1607. agentType: "Idle Reviewer",
  1608. runInBackground: kind === "explicit",
  1609. },
  1610. { modelOverride },
  1611. );
  1612. expect(output.status).toBe("async_launched");
  1613. expect(calls).toEqual([expect.objectContaining({ modelOverride })]);
  1614. } finally {
  1615. gate.resolve();
  1616. }
  1617. },
  1618. );
  1619. it("rejects background launch when an execution model override is present", async () => {
  1620. const sessionId = createSessionId("subagent-background-turn-execution-model");
  1621. const turnId = createTurnId("subagent-background-turn-execution-model-turn");
  1622. const port = createExploreSubagentPort({
  1623. createAgentId: () => "agent_background_turn_execution_model",
  1624. emitParentEvent: async () => {},
  1625. runExploreAgent: async () => {
  1626. throw new Error("background child must not start");
  1627. },
  1628. });
  1629. await expect(
  1630. port.launch(
  1631. {
  1632. ...createSubagentRunRequest({ sessionId, turnId }),
  1633. runInBackground: true,
  1634. },
  1635. {
  1636. signal: new AbortController().signal,
  1637. modelOverride: {
  1638. selection: { providerId: "account:zai-offpeak-idle-plan", modelId: "GLM-5.2" },
  1639. background: "deny",
  1640. },
  1641. },
  1642. ),
  1643. ).rejects.toThrow("Idle-time tasks do not support background agents");
  1644. expect(await port.getTask?.("agent_background_turn_execution_model")).toBeUndefined();
  1645. });
  1646. it("rejects a profile-configured background agent when an execution model override is present", async () => {
  1647. const sessionId = createSessionId("subagent-profile-background-turn-execution-model");
  1648. const turnId = createTurnId("subagent-profile-background-turn-execution-model-turn");
  1649. const port = createExploreSubagentPort({
  1650. createAgentId: () => "agent_profile_background_turn_execution_model",
  1651. emitParentEvent: async () => {},
  1652. profiles: [
  1653. {
  1654. background: true,
  1655. description: "Background reviewer",
  1656. name: "Background Reviewer",
  1657. source: "user",
  1658. systemPrompt: "Review in background.",
  1659. tools: ["Read"],
  1660. },
  1661. ],
  1662. runExploreAgent: async () => {
  1663. throw new Error("profile background child must not start");
  1664. },
  1665. });
  1666. await expect(
  1667. port.launch(
  1668. {
  1669. ...createSubagentRunRequest({ sessionId, turnId }),
  1670. agentType: "Background Reviewer",
  1671. },
  1672. {
  1673. modelOverride: {
  1674. selection: { providerId: "account:zai-offpeak-idle-plan", modelId: "GLM-5.2" },
  1675. background: "deny",
  1676. },
  1677. },
  1678. ),
  1679. ).rejects.toThrow("Idle-time tasks do not support background agents");
  1680. expect(await port.getTask?.("agent_profile_background_turn_execution_model")).toBeUndefined();
  1681. });
  1682. });
  1683. function createDeferred<T>(): {
  1684. promise: Promise<T>;
  1685. resolve: (value: T) => void;
  1686. } {
  1687. let resolve!: (value: T) => void;
  1688. const promise = new Promise<T>((innerResolve) => {
  1689. resolve = innerResolve;
  1690. });
  1691. return { promise, resolve };
  1692. }
  1693. function modelTextResult(text: string) {
  1694. return {
  1695. finishReason: "stop",
  1696. model: "test",
  1697. providerMetadata: undefined,
  1698. text,
  1699. usage: {
  1700. inputTokens: 1,
  1701. outputTokens: 1,
  1702. totalTokens: 2,
  1703. },
  1704. };
  1705. }
  1706. function providerMessagesToText(messages: readonly { content: ModelMessageContent }[]): string {
  1707. return messages.map((message) => modelMessageContentToText(message.content)).join("\n");
  1708. }
  1709. async function waitForMacrotask(): Promise<void> {
  1710. await new Promise<void>((resolve) => {
  1711. setTimeout(resolve, 0);
  1712. });
  1713. }
  1714. async function waitForCondition(predicate: () => boolean | Promise<boolean>): Promise<void> {
  1715. const startedAt = Date.now();
  1716. while (Date.now() - startedAt < 1000) {
  1717. if (await predicate()) return;
  1718. await new Promise((resolve) => setTimeout(resolve, 5));
  1719. }
  1720. throw new Error("Timed out waiting for condition");
  1721. }
  1722. async function waitForAbort(signal?: AbortSignal): Promise<void> {
  1723. if (!signal || signal.aborted) return;
  1724. await new Promise<void>((resolve) => {
  1725. signal.addEventListener("abort", () => resolve(), { once: true });
  1726. });
  1727. }
  1728. function recordSetTimeoutUnrefCalls(): { calls: number[]; restore: () => void } {
  1729. const calls: number[] = [];
  1730. const originalSetTimeout = globalThis.setTimeout;
  1731. const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout").mockImplementation(((
  1732. handler: Parameters<typeof setTimeout>[0],
  1733. timeout?: Parameters<typeof setTimeout>[1],
  1734. ...args: any[]
  1735. ) => {
  1736. const timer = originalSetTimeout(handler, timeout, ...args);
  1737. if (
  1738. typeof timer === "object" &&
  1739. timer !== null &&
  1740. "unref" in timer &&
  1741. typeof timer.unref === "function"
  1742. ) {
  1743. const originalUnref = timer.unref.bind(timer);
  1744. timer.unref = () => {
  1745. calls.push(typeof timeout === "number" ? timeout : Number(timeout ?? 0));
  1746. return originalUnref();
  1747. };
  1748. }
  1749. return timer;
  1750. }) as typeof setTimeout);
  1751. return {
  1752. calls,
  1753. restore: () => {
  1754. setTimeoutSpy.mockRestore();
  1755. },
  1756. };
  1757. }
  1758. function recordSetTimeoutCalls(): {
  1759. calls: number[];
  1760. restore: () => void;
  1761. } {
  1762. const calls: number[] = [];
  1763. const originalSetTimeout = globalThis.setTimeout;
  1764. const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout").mockImplementation(((
  1765. handler: Parameters<typeof setTimeout>[0],
  1766. timeout?: Parameters<typeof setTimeout>[1],
  1767. ...args: any[]
  1768. ) => {
  1769. calls.push(typeof timeout === "number" ? timeout : Number(timeout ?? 0));
  1770. const timer = originalSetTimeout(handler, timeout, ...args);
  1771. return timer;
  1772. }) as typeof setTimeout);
  1773. return {
  1774. calls,
  1775. restore: () => {
  1776. setTimeoutSpy.mockRestore();
  1777. },
  1778. };
  1779. }
  1780. function createSubagentRunRequest(input: {
  1781. sessionId: SessionId;
  1782. turnId: ReturnType<typeof createTurnId>;
  1783. }) {
  1784. return {
  1785. agentType: "general-purpose",
  1786. description: "Auto background test",
  1787. parentToolCallId: "call_auto_background",
  1788. prompt: "Run slowly",
  1789. sessionId: input.sessionId,
  1790. trace: {
  1791. traceId: "trace_subagent_auto_background_parent",
  1792. spanId: "span_subagent_auto_background_parent",
  1793. sessionId: input.sessionId,
  1794. turnId: input.turnId,
  1795. },
  1796. turnId: input.turnId,
  1797. workingDirectory: "/tmp/zcode-subagent-auto-background",
  1798. workspaceRoot: "/tmp/zcode-subagent-auto-background",
  1799. };
  1800. }
  1801. class RecordingSessionStore {
  1802. readonly createdSessions: CreateSessionInput[] = [];
  1803. readonly projectPermissions = new Map<string, PermissionRuleset>();
  1804. readonly savedMessages: MessageInfo[] = [];
  1805. readonly savedParts: MessagePart[] = [];
  1806. readonly savedSessionInputs: Array<
  1807. Parameters<NonNullable<SessionStorePort["saveSessionInput"]>>[0]
  1808. > = [];
  1809. readonly promotedSessionInputs: Array<
  1810. Parameters<NonNullable<SessionStorePort["markSessionInputPromoted"]>>[0]
  1811. > = [];
  1812. readonly sessions = new Map<string, SessionInfo>();
  1813. readonly targets = new Map<string, SessionGoal>();
  1814. readonly todos = new Map<string, TodoItem[]>();
  1815. async createSession(input: CreateSessionInput): Promise<SessionInfo> {
  1816. this.createdSessions.push(input);
  1817. const now = Date.now();
  1818. const session: SessionInfo = {
  1819. ...input,
  1820. taskType: input.taskType ?? "interactive",
  1821. time: {
  1822. created: input.time?.created ?? now,
  1823. updated: input.time?.updated ?? now,
  1824. },
  1825. };
  1826. this.sessions.set(input.id, session);
  1827. return session;
  1828. }
  1829. async updateSession(
  1830. input: Parameters<SessionStorePort["updateSession"]>[0],
  1831. ): Promise<SessionInfo> {
  1832. const session = this.sessions.get(input.id);
  1833. if (!session) throw new Error(`missing session: ${input.id}`);
  1834. const next: SessionInfo = {
  1835. ...session,
  1836. title: input.title ?? session.title,
  1837. shareURL: input.shareURL === null ? undefined : (input.shareURL ?? session.shareURL),
  1838. summaryAdditions:
  1839. input.summary === null ? undefined : (input.summary?.additions ?? session.summaryAdditions),
  1840. summaryDeletions:
  1841. input.summary === null ? undefined : (input.summary?.deletions ?? session.summaryDeletions),
  1842. summaryFiles:
  1843. input.summary === null ? undefined : (input.summary?.files ?? session.summaryFiles),
  1844. summaryDiffs:
  1845. input.summary === null ? undefined : (input.summary?.diffs ?? session.summaryDiffs),
  1846. permission: input.permission === null ? undefined : (input.permission ?? session.permission),
  1847. time: {
  1848. ...session.time,
  1849. updated: Date.now(),
  1850. compacting:
  1851. input.timeCompacting === null
  1852. ? undefined
  1853. : (input.timeCompacting ?? session.time.compacting),
  1854. },
  1855. };
  1856. this.sessions.set(input.id, next);
  1857. return next;
  1858. }
  1859. async getSession(sessionID: SessionId): Promise<SessionInfo | null> {
  1860. return this.sessions.get(sessionID) ?? null;
  1861. }
  1862. async listSessions(): Promise<SessionInfo[]> {
  1863. return Array.from(this.sessions.values());
  1864. }
  1865. async saveMessage(input: MessageInfo): Promise<void> {
  1866. this.savedMessages.push(input);
  1867. }
  1868. async removeMessage(input: {
  1869. messageID: MessageInfo["id"];
  1870. sessionID: SessionId;
  1871. }): Promise<void> {
  1872. removeWhere(
  1873. this.savedMessages,
  1874. (message) => message.sessionID === input.sessionID && message.id === input.messageID,
  1875. );
  1876. }
  1877. async savePart(input: MessagePart): Promise<void> {
  1878. this.savedParts.push(input);
  1879. }
  1880. async saveSessionInput(
  1881. input: Parameters<NonNullable<SessionStorePort["saveSessionInput"]>>[0],
  1882. ): Promise<void> {
  1883. this.savedSessionInputs.push(input);
  1884. }
  1885. async markSessionInputPromoted(
  1886. input: Parameters<NonNullable<SessionStorePort["markSessionInputPromoted"]>>[0],
  1887. ): Promise<void> {
  1888. this.promotedSessionInputs.push(input);
  1889. }
  1890. async removePart(input: {
  1891. messageID: MessageInfo["id"];
  1892. partID: MessagePart["id"];
  1893. sessionID: SessionId;
  1894. }): Promise<void> {
  1895. removeWhere(
  1896. this.savedParts,
  1897. (part) =>
  1898. part.sessionID === input.sessionID &&
  1899. part.messageID === input.messageID &&
  1900. part.id === input.partID,
  1901. );
  1902. }
  1903. async messages(input: { sessionID: SessionId }): Promise<MessageWithParts[]> {
  1904. return this.savedMessages
  1905. .filter((message) => message.sessionID === input.sessionID)
  1906. .map((info) => ({
  1907. info,
  1908. parts: this.savedParts.filter(
  1909. (part) => part.sessionID === input.sessionID && part.messageID === info.id,
  1910. ),
  1911. }));
  1912. }
  1913. async readTodos(input: { sessionID: SessionId }): Promise<TodoItem[]> {
  1914. return [...(this.todos.get(input.sessionID) ?? [])];
  1915. }
  1916. async updateTodos(input: { sessionID: SessionId; todos: TodoItem[] }): Promise<void> {
  1917. this.todos.set(input.sessionID, [...input.todos]);
  1918. }
  1919. async readTarget(input: { sessionID: SessionId }): Promise<SessionGoal | null> {
  1920. return this.targets.get(input.sessionID) ?? null;
  1921. }
  1922. async updateTarget(input: { sessionID: SessionId; target: SessionGoal | null }): Promise<void> {
  1923. if (input.target === null) {
  1924. this.targets.delete(input.sessionID);
  1925. return;
  1926. }
  1927. this.targets.set(input.sessionID, input.target);
  1928. }
  1929. async readProjectPermissions(input: { projectID: string }): Promise<PermissionRuleset | null> {
  1930. return this.projectPermissions.get(input.projectID) ?? null;
  1931. }
  1932. async updateProjectPermissions(input: {
  1933. projectID: string;
  1934. permission: PermissionRuleset | null;
  1935. }): Promise<void> {
  1936. if (input.permission === null) {
  1937. this.projectPermissions.delete(input.projectID);
  1938. return;
  1939. }
  1940. this.projectPermissions.set(input.projectID, input.permission);
  1941. }
  1942. }
  1943. function removeWhere<T>(items: T[], predicate: (item: T) => boolean): void {
  1944. for (let index = items.length - 1; index >= 0; index--) {
  1945. if (predicate(items[index]!)) items.splice(index, 1);
  1946. }
  1947. }