subagent-background.test.ts 78 KB

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