background-task-control.test.ts 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744
  1. import { existsSync, readFileSync } from "node:fs";
  2. import { mkdir, mkdtemp, rm } from "node:fs/promises";
  3. import { dirname, join } from "node:path";
  4. import { tmpdir } from "node:os";
  5. import { describe, expect, it } from "vitest";
  6. import {
  7. SessionEventType,
  8. CoreErrorType,
  9. createModelId,
  10. createModelProviderId,
  11. createSessionEvent,
  12. createSessionId,
  13. createTurnId,
  14. type ExecutionPort,
  15. type SessionEvent,
  16. } from "@zcode/contracts";
  17. import type { AgentRuntime } from "../src/runtime.js";
  18. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  19. import {
  20. InMemoryRuntimeTaskRegistry,
  21. hasRunningBackgroundRuntimeTask,
  22. } from "../src/runtime-task/registry.js";
  23. import { BackgroundTaskTracker } from "../src/tool/executor/background-tasks.js";
  24. import { updateRuntimeBackgroundTask } from "../src/tool/executor/background-task-registry.js";
  25. import { createExploreSubagentPort } from "../src/subagent/runner.js";
  26. import { taskStopToolEntry } from "../src/tool/handlers/task-stop.js";
  27. import { createTestSessionEventStore } from "./test-event-store.js";
  28. import { createTestModelFactory } from "./test-runtime-model.js";
  29. function deferred<T = void>(): {
  30. promise: Promise<T>;
  31. reject: (error: unknown) => void;
  32. resolve: (value: T) => void;
  33. } {
  34. let resolve!: (value: T) => void;
  35. let reject!: (error: unknown) => void;
  36. const promise = new Promise<T>((innerResolve, innerReject) => {
  37. resolve = innerResolve;
  38. reject = innerReject;
  39. });
  40. return { promise, reject, resolve };
  41. }
  42. async function waitForCondition(predicate: () => boolean | Promise<boolean>): Promise<void> {
  43. const startedAt = Date.now();
  44. while (Date.now() - startedAt < 1_000) {
  45. if (await predicate()) return;
  46. await new Promise((resolve) => setTimeout(resolve, 5));
  47. }
  48. throw new Error("Timed out waiting for condition");
  49. }
  50. describe("background task control", () => {
  51. it("stops running local Bash tasks through the runtime registry dispatcher", async () => {
  52. const sessionId = createSessionId("background-control-bash");
  53. const eventStore = createTestSessionEventStore();
  54. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  55. const startedAt = new Date(0);
  56. const completedAt = new Date(1);
  57. const cancelledTaskIds: string[] = [];
  58. const executionPort: ExecutionPort = {
  59. async run() {
  60. throw new Error("run should not be called");
  61. },
  62. async cancelBackgroundTask(taskId) {
  63. cancelledTaskIds.push(taskId);
  64. return {
  65. taskId,
  66. status: "cancelled",
  67. startedAt,
  68. completedAt,
  69. stdoutTail: "cancelled",
  70. };
  71. },
  72. };
  73. runtimeTaskRegistry.register({
  74. agentId: "bash_bg",
  75. agentType: "local_bash",
  76. command: "npm run dev",
  77. description: "npm run dev",
  78. isBackgrounded: true,
  79. startedAt,
  80. status: "running",
  81. taskId: "bash_bg",
  82. taskType: "local_bash",
  83. type: "local_bash",
  84. } as never);
  85. await eventStore.append(
  86. createSessionEvent(SessionEventType.BackgroundTaskStarted, sessionId, {
  87. cancellable: true,
  88. command: "npm run dev",
  89. startedAt,
  90. status: "running",
  91. taskId: "bash_bg",
  92. terminalId: "bash_bg",
  93. toolCallId: "tool_bash",
  94. toolName: "Bash",
  95. }),
  96. );
  97. const runtime = createTestAgentRuntime(
  98. sessionId,
  99. { mode: "build" },
  100. { eventStore, executionPort, runtimeTaskRegistry },
  101. );
  102. const result = await runtime.cancelBackgroundTask("bash_bg");
  103. const events = await eventStore.getEvents(sessionId);
  104. expect(cancelledTaskIds).toEqual(["bash_bg"]);
  105. expect(result).toMatchObject({
  106. cancelled: true,
  107. status: "cancelled",
  108. taskId: "bash_bg",
  109. });
  110. expect(
  111. events.filter((event) => event.type === SessionEventType.BackgroundTaskUpdated),
  112. ).toHaveLength(1);
  113. expect(
  114. events.filter((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  115. ).toHaveLength(0);
  116. });
  117. it("does not ask the execution port to stop an unknown UI-control task", async () => {
  118. const sessionId = createSessionId("background-control-missing-ui");
  119. const eventStore = createTestSessionEventStore();
  120. let cancelCalled = false;
  121. const runtime = createTestAgentRuntime(
  122. sessionId,
  123. { mode: "build" },
  124. {
  125. eventStore,
  126. executionPort: {
  127. async run() {
  128. throw new Error("run should not be called");
  129. },
  130. async cancelBackgroundTask() {
  131. cancelCalled = true;
  132. return undefined;
  133. },
  134. },
  135. },
  136. );
  137. const result = await runtime.cancelBackgroundTask("missing_bg");
  138. expect(cancelCalled).toBe(false);
  139. expect(result).toMatchObject({
  140. cancelled: false,
  141. reason: "background_task_not_found",
  142. status: "lost",
  143. taskId: "missing_bg",
  144. });
  145. });
  146. it("marks a registry-backed local Bash task lost when the execution adapter no longer has it", async () => {
  147. const sessionId = createSessionId("background-control-bash-lost-adapter");
  148. const eventStore = createTestSessionEventStore();
  149. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  150. const startedAt = new Date(0);
  151. const executionPort: ExecutionPort = {
  152. async run() {
  153. throw new Error("run should not be called");
  154. },
  155. async cancelBackgroundTask() {
  156. return undefined;
  157. },
  158. };
  159. runtimeTaskRegistry.register({
  160. agentId: "bash_lost_adapter",
  161. agentType: "local_bash",
  162. command: "sleep 999",
  163. description: "sleep 999",
  164. isBackgrounded: true,
  165. startedAt,
  166. status: "running",
  167. taskId: "bash_lost_adapter",
  168. taskType: "local_bash",
  169. type: "local_bash",
  170. } as never);
  171. const runtime = createTestAgentRuntime(
  172. sessionId,
  173. { mode: "build" },
  174. { eventStore, executionPort, runtimeTaskRegistry },
  175. );
  176. const result = await runtime.cancelBackgroundTask("bash_lost_adapter");
  177. const events = await eventStore.getEvents(sessionId);
  178. expect(result).toMatchObject({
  179. cancelled: false,
  180. reason: "background_task_not_found",
  181. status: "lost",
  182. taskId: "bash_lost_adapter",
  183. });
  184. expect(runtimeTaskRegistry.get("bash_lost_adapter")).toMatchObject({
  185. status: "lost",
  186. });
  187. expect(
  188. events.filter((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  189. ).toHaveLength(1);
  190. });
  191. it("returns strict not-found and not-running results for model-tool callers", async () => {
  192. const sessionId = createSessionId("background-control-strict");
  193. const eventStore = createTestSessionEventStore();
  194. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  195. runtimeTaskRegistry.register({
  196. agentId: "terminal_bg",
  197. agentType: "local_bash",
  198. description: "finished",
  199. isBackgrounded: true,
  200. startedAt: new Date(0),
  201. status: "completed",
  202. taskId: "terminal_bg",
  203. taskType: "local_bash",
  204. type: "local_bash",
  205. } as never);
  206. const runtime = createTestAgentRuntime(
  207. sessionId,
  208. { mode: "build" },
  209. {
  210. eventStore,
  211. runtimeTaskRegistry,
  212. executionPort: {
  213. async run() {
  214. throw new Error("run should not be called");
  215. },
  216. },
  217. },
  218. );
  219. await expect(
  220. (runtime as any).stopBackgroundTask("missing_bg", {
  221. strict: true,
  222. }),
  223. ).resolves.toMatchObject({
  224. ok: false,
  225. reason: "background_task_not_found",
  226. taskId: "missing_bg",
  227. });
  228. await expect(
  229. (runtime as any).stopBackgroundTask("terminal_bg", {
  230. strict: true,
  231. }),
  232. ).resolves.toMatchObject({
  233. ok: false,
  234. reason: "background_task_not_running",
  235. status: "completed",
  236. taskId: "terminal_bg",
  237. type: "local_bash",
  238. });
  239. });
  240. it("treats stopped runtime task results as successful cancellation", async () => {
  241. const sessionId = createSessionId("background-control-stopped-status");
  242. const eventStore = createTestSessionEventStore();
  243. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  244. runtimeTaskRegistry.register({
  245. agentId: "agent_stopped",
  246. agentType: "general-purpose",
  247. description: "stoppable agent",
  248. isBackgrounded: true,
  249. outputFile: "/tmp/agent_stopped/output.txt",
  250. parentToolCallId: "tool_agent_stopped",
  251. startedAt: new Date(0),
  252. status: "running",
  253. taskId: "agent_stopped",
  254. taskType: "local_agent",
  255. type: "local_agent",
  256. } as never);
  257. const runtime = createTestAgentRuntime(
  258. sessionId,
  259. { mode: "build" },
  260. {
  261. eventStore,
  262. runtimeTaskRegistry,
  263. subagentPort: {
  264. async launch() {
  265. throw new Error("launch should not be called");
  266. },
  267. async run() {
  268. throw new Error("run should not be called");
  269. },
  270. async stopTask(taskId) {
  271. return {
  272. agentId: taskId,
  273. agentType: "general-purpose",
  274. childSessionId: "child_stopped" as never,
  275. description: "stoppable agent",
  276. isBackgrounded: true,
  277. outputFile: "/tmp/agent_stopped/output.txt",
  278. parentToolCallId: "tool_agent_stopped",
  279. parentSessionId: sessionId,
  280. prompt: "stop",
  281. startedAt: new Date(0),
  282. status: "stopped",
  283. taskId,
  284. taskType: "local_agent",
  285. type: "local_agent",
  286. } as never;
  287. },
  288. },
  289. },
  290. );
  291. await expect(runtime.cancelBackgroundTask("agent_stopped")).resolves.toMatchObject({
  292. cancelled: true,
  293. status: "cancelled",
  294. taskId: "agent_stopped",
  295. });
  296. });
  297. it("returns unsupported for runtime task types without a stop handler", async () => {
  298. const sessionId = createSessionId("background-control-unsupported");
  299. const eventStore = createTestSessionEventStore();
  300. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  301. runtimeTaskRegistry.register({
  302. agentId: "workflow_bg",
  303. agentType: "local_workflow",
  304. description: "workflow",
  305. isBackgrounded: true,
  306. startedAt: new Date(0),
  307. status: "running",
  308. taskId: "workflow_bg",
  309. taskType: "local_workflow",
  310. type: "local_workflow",
  311. } as never);
  312. const runtime = createTestAgentRuntime(
  313. sessionId,
  314. { mode: "build" },
  315. { eventStore, runtimeTaskRegistry },
  316. );
  317. await expect((runtime as any).stopBackgroundTask("workflow_bg", {})).resolves.toMatchObject({
  318. ok: false,
  319. reason: "background_task_cancel_not_supported",
  320. taskId: "workflow_bg",
  321. type: "local_workflow",
  322. });
  323. });
  324. it("stops running local Agent tasks through the subagent port", async () => {
  325. const sessionId = createSessionId("background-control-agent");
  326. const eventStore = createTestSessionEventStore();
  327. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  328. const stoppedTaskIds: string[] = [];
  329. runtimeTaskRegistry.register({
  330. agentId: "agent_bg",
  331. agentType: "general-purpose",
  332. description: "research",
  333. isBackgrounded: true,
  334. outputFile: "/tmp/agent_bg/output.txt",
  335. parentToolCallId: "tool_agent",
  336. startedAt: new Date(0),
  337. status: "running",
  338. taskId: "agent_bg",
  339. taskType: "local_agent",
  340. type: "local_agent",
  341. } as never);
  342. const runtime = createTestAgentRuntime(
  343. sessionId,
  344. { mode: "build" },
  345. {
  346. eventStore,
  347. runtimeTaskRegistry,
  348. subagentPort: {
  349. async launch() {
  350. throw new Error("launch should not be called");
  351. },
  352. async run() {
  353. throw new Error("run should not be called");
  354. },
  355. async stopTask(taskId, options) {
  356. stoppedTaskIds.push(`${taskId}:${options?.initiator}`);
  357. return {
  358. agentId: taskId,
  359. agentType: "general-purpose",
  360. description: "research",
  361. outputFile: "/tmp/agent_bg/output.txt",
  362. startedAt: new Date(0),
  363. status: "killed",
  364. taskId,
  365. };
  366. },
  367. },
  368. },
  369. );
  370. const result = await runtime.cancelBackgroundTask("agent_bg");
  371. // GUI 入口是用户的停止:停止者随 stopTask 传给 subagent,终态通知据此写 "was stopped by user"。
  372. expect(stoppedTaskIds).toEqual(["agent_bg:user"]);
  373. expect(result).toMatchObject({
  374. cancelled: true,
  375. status: "cancelled",
  376. taskId: "agent_bg",
  377. });
  378. });
  379. it("uses the local Agent description as the TaskStop command", async () => {
  380. const sessionId = createSessionId("background-control-agent-command");
  381. const eventStore = createTestSessionEventStore();
  382. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  383. const prompt = "Read every source and return a complete multi-section report.";
  384. runtimeTaskRegistry.register({
  385. agentId: "agent_command",
  386. agentType: "general-purpose",
  387. description: "Research the current odds",
  388. isBackgrounded: true,
  389. prompt,
  390. startedAt: new Date(0),
  391. status: "running",
  392. taskId: "agent_command",
  393. taskType: "local_agent",
  394. type: "local_agent",
  395. } as never);
  396. await eventStore.append(
  397. createSessionEvent(SessionEventType.BackgroundTaskStarted, sessionId, {
  398. cancellable: true,
  399. command: prompt,
  400. description: "Research the current odds",
  401. startedAt: new Date(0),
  402. status: "running",
  403. taskId: "agent_command",
  404. terminalId: "agent_command",
  405. toolCallId: "tool_agent_command",
  406. toolName: "Agent",
  407. }),
  408. );
  409. const runtime = createTestAgentRuntime(
  410. sessionId,
  411. { mode: "build" },
  412. {
  413. eventStore,
  414. runtimeTaskRegistry,
  415. subagentPort: {
  416. async launch() {
  417. throw new Error("launch should not be called");
  418. },
  419. async run() {
  420. throw new Error("run should not be called");
  421. },
  422. async stopTask(taskId) {
  423. return {
  424. agentId: taskId,
  425. agentType: "general-purpose",
  426. description: "Research the current odds",
  427. startedAt: new Date(0),
  428. status: "killed",
  429. taskId,
  430. };
  431. },
  432. },
  433. },
  434. );
  435. await expect(
  436. (runtime as any).stopBackgroundTask("agent_command", { strict: true }),
  437. ).resolves.toMatchObject({
  438. command: "Research the current odds",
  439. ok: true,
  440. status: "killed",
  441. taskId: "agent_command",
  442. type: "local_agent",
  443. });
  444. });
  445. it("aborts a running background subagent and enqueues one stopped notification", async () => {
  446. const sessionId = createSessionId("background-control-agent-port");
  447. const turnId = createTurnId("turn_background_control_agent_port");
  448. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-background-control-agent-port-"));
  449. const aborted = deferred();
  450. let abortObserved = false;
  451. const notifications: string[] = [];
  452. const notificationOriginMetas: unknown[] = [];
  453. const notificationArtifactStates: Array<{ exists: boolean; content: string }> = [];
  454. const emittedEvents: Array<{ type: SessionEventType; payload: unknown }> = [];
  455. const backgroundCompletedAbortStates: boolean[] = [];
  456. const registry = new InMemoryRuntimeTaskRegistry();
  457. const port = createExploreSubagentPort({
  458. createAgentId: () => "agent_stop",
  459. emitParentEvent: async (event) => {
  460. if (event.type === SessionEventType.BackgroundTaskCompleted) {
  461. backgroundCompletedAbortStates.push(abortObserved);
  462. }
  463. emittedEvents.push({ type: event.type, payload: event.payload });
  464. },
  465. enqueueParentTaskNotification: (notification) => {
  466. const outputFile = notification.text.match(/<output-file>([^<]+)<\/output-file>/u)?.[1];
  467. notificationArtifactStates.push({
  468. exists: outputFile ? existsSync(outputFile) : false,
  469. content: outputFile && existsSync(outputFile) ? readFileSync(outputFile, "utf8") : "",
  470. });
  471. notifications.push(notification.text);
  472. notificationOriginMetas.push(notification.originMeta);
  473. },
  474. outputRootDir,
  475. runtimeTaskRegistry: registry,
  476. async runExploreAgent(request, options) {
  477. await request.onSessionReady?.();
  478. return await new Promise((_, reject) => {
  479. options?.signal?.addEventListener(
  480. "abort",
  481. () => {
  482. abortObserved = true;
  483. aborted.resolve();
  484. reject(options.signal?.reason ?? new Error("aborted"));
  485. },
  486. { once: true },
  487. );
  488. });
  489. },
  490. });
  491. try {
  492. await port.start?.({
  493. agentType: "general-purpose",
  494. description: "Stop me",
  495. parentToolCallId: "tool_agent_stop",
  496. prompt: "Wait until stopped",
  497. sessionId,
  498. trace: {
  499. traceId: "trace_background_control_agent_port",
  500. spanId: "span_background_control_agent_port",
  501. sessionId,
  502. turnId,
  503. },
  504. turnId,
  505. workingDirectory: outputRootDir,
  506. workspaceRoot: outputRootDir,
  507. });
  508. const stopped = await port.stopTask?.("agent_stop", { initiator: "model" });
  509. await aborted.promise;
  510. expect(stopped).toMatchObject({
  511. status: "killed",
  512. taskId: "agent_stop",
  513. });
  514. expect(registry.get("agent_stop")).toMatchObject({
  515. notified: true,
  516. status: "killed",
  517. });
  518. expect(notifications).toHaveLength(1);
  519. expect(notifications[0]).toContain("<status>killed</status>");
  520. // TaskStop 传入的停止者进入通知;killed 通知不带 usage。
  521. expect(notifications[0]).toContain('<summary>Agent "Stop me" was stopped by ZCode</summary>');
  522. expect(notifications[0]).not.toContain("<usage>");
  523. // 终态随 originMeta 结构化下发;killed 不带 error。
  524. expect(notificationOriginMetas).toEqual([
  525. {
  526. backgroundSource: "subagent",
  527. title: "Stop me",
  528. workId: "agent_stop",
  529. subagentResult: { status: "killed" },
  530. },
  531. ]);
  532. expect(notificationArtifactStates).toEqual([
  533. expect.objectContaining({
  534. exists: true,
  535. content: expect.stringContaining("Background agent task stopped."),
  536. }),
  537. ]);
  538. expect(backgroundCompletedAbortStates).toEqual([true]);
  539. expect(
  540. emittedEvents.filter((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  541. ).toHaveLength(1);
  542. } finally {
  543. await rm(outputRootDir, { force: true, recursive: true });
  544. }
  545. });
  546. // 停止者全链路:停止入口 → runtime.stopBackgroundTask → subagent stopTask → killed 通知 summary。
  547. it.each([
  548. { initiator: "model", summary: "was stopped by ZCode" },
  549. { initiator: "user", summary: "was stopped by user" },
  550. ])(
  551. "carries the $initiator stop initiator from the stop entry into the killed notification",
  552. async ({ initiator, summary }) => {
  553. const sessionId = createSessionId(`background-control-agent-initiator-${initiator}`);
  554. const turnId = createTurnId(`turn_background_control_agent_initiator_${initiator}`);
  555. const outputRootDir = await mkdtemp(
  556. join(tmpdir(), "zcode-background-control-agent-initiator-"),
  557. );
  558. const aborted = deferred();
  559. const notifications: string[] = [];
  560. const registry = new InMemoryRuntimeTaskRegistry();
  561. const port = createExploreSubagentPort({
  562. createAgentId: () => "agent_initiator",
  563. emitParentEvent: async () => {},
  564. enqueueParentTaskNotification: (notification) => {
  565. notifications.push(notification.text);
  566. },
  567. outputRootDir,
  568. runtimeTaskRegistry: registry,
  569. async runExploreAgent(request, options) {
  570. await request.onSessionReady?.();
  571. return await new Promise((_, reject) => {
  572. options?.signal?.addEventListener(
  573. "abort",
  574. () => {
  575. aborted.resolve();
  576. reject(options.signal?.reason ?? new Error("aborted"));
  577. },
  578. { once: true },
  579. );
  580. });
  581. },
  582. });
  583. const runtime = createTestAgentRuntime(
  584. sessionId,
  585. { mode: "build" },
  586. {
  587. eventStore: createTestSessionEventStore(),
  588. runtimeTaskRegistry: registry,
  589. subagentPort: port,
  590. },
  591. );
  592. try {
  593. await port.start?.({
  594. agentType: "general-purpose",
  595. description: "Stop me",
  596. parentToolCallId: "tool_agent_initiator",
  597. prompt: "Wait until stopped",
  598. sessionId,
  599. trace: {
  600. traceId: "trace_background_control_agent_initiator",
  601. spanId: "span_background_control_agent_initiator",
  602. sessionId,
  603. turnId,
  604. },
  605. turnId,
  606. workingDirectory: outputRootDir,
  607. workspaceRoot: outputRootDir,
  608. });
  609. if (initiator === "model") {
  610. // 模型入口:TaskStop 用 runtime 交给工具执行上下文的同一个绑定。
  611. await taskStopToolEntry.handler({ task_id: "agent_initiator" }, {
  612. backgroundTaskControlPort: {
  613. stopBackgroundTask: runtime.stopBackgroundTask.bind(runtime),
  614. },
  615. toolCallId: "tool_task_stop",
  616. } as never);
  617. } else {
  618. // App 入口:v4 cancelBackgroundWork 调 cancelBackgroundTask。
  619. await runtime.cancelBackgroundTask("agent_initiator");
  620. }
  621. await aborted.promise;
  622. expect(registry.get("agent_initiator")).toMatchObject({ status: "killed" });
  623. expect(notifications).toHaveLength(1);
  624. expect(notifications[0]).toContain(`<summary>Agent "Stop me" ${summary}</summary>`);
  625. } finally {
  626. await rm(outputRootDir, { force: true, recursive: true });
  627. }
  628. },
  629. );
  630. it("cleans up a background subagent when startup event emission fails before run starts", async () => {
  631. const sessionId = createSessionId("background-control-agent-startup-failure");
  632. const turnId = createTurnId("turn_background_control_agent_startup_failure");
  633. const outputRootDir = await mkdtemp(
  634. join(tmpdir(), "zcode-background-control-agent-startup-failure-"),
  635. );
  636. const registry = new InMemoryRuntimeTaskRegistry();
  637. let runCalled = false;
  638. const port = createExploreSubagentPort({
  639. createAgentId: () => "agent_startup_fail",
  640. emitParentEvent: async (event) => {
  641. if (event.type === SessionEventType.SubagentSpawned) {
  642. throw new Error("spawn event failed");
  643. }
  644. },
  645. enqueueParentTaskNotification: () => {},
  646. outputRootDir,
  647. runtimeTaskRegistry: registry,
  648. async runExploreAgent(request) {
  649. runCalled = true;
  650. await request.onSessionReady?.();
  651. throw new Error("run should not be called");
  652. },
  653. });
  654. try {
  655. await expect(
  656. port.start?.({
  657. agentType: "general-purpose",
  658. description: "Fail before run",
  659. parentToolCallId: "tool_agent_startup_fail",
  660. prompt: "This should not start",
  661. sessionId,
  662. trace: {
  663. traceId: "trace_background_control_agent_startup_failure",
  664. spanId: "span_background_control_agent_startup_failure",
  665. sessionId,
  666. turnId,
  667. },
  668. turnId,
  669. workingDirectory: outputRootDir,
  670. workspaceRoot: outputRootDir,
  671. }),
  672. ).rejects.toThrow("spawn event failed");
  673. expect(runCalled).toBe(true);
  674. expect(registry.get("agent_startup_fail")).toBeUndefined();
  675. } finally {
  676. await rm(outputRootDir, { force: true, recursive: true });
  677. }
  678. });
  679. it("keeps a stopped background subagent terminal even when notification enqueue fails", async () => {
  680. const sessionId = createSessionId("background-control-agent-stop-finalize-failure");
  681. const turnId = createTurnId("turn_background_control_agent_stop_final_failure");
  682. const outputRootDir = await mkdtemp(
  683. join(tmpdir(), "zcode-background-control-agent-stop-finalize-failure-"),
  684. );
  685. const aborted = deferred();
  686. let abortObserved = false;
  687. const registry = new InMemoryRuntimeTaskRegistry();
  688. const events: SessionEvent[] = [];
  689. const port = createExploreSubagentPort({
  690. createAgentId: () => "agent_stop_finalize_fail",
  691. emitParentEvent: async (event) => {
  692. events.push(event);
  693. },
  694. enqueueParentTaskNotification: () => {
  695. throw new Error("enqueue failed");
  696. },
  697. outputRootDir,
  698. runtimeTaskRegistry: registry,
  699. async runExploreAgent(request, options) {
  700. await request.onSessionReady?.();
  701. return await new Promise((_, reject) => {
  702. options?.signal?.addEventListener(
  703. "abort",
  704. () => {
  705. abortObserved = true;
  706. aborted.resolve();
  707. reject(options.signal?.reason ?? new Error("aborted"));
  708. },
  709. { once: true },
  710. );
  711. });
  712. },
  713. });
  714. try {
  715. await port.start?.({
  716. agentType: "general-purpose",
  717. description: "Stop finalize failure",
  718. parentToolCallId: "tool_agent_stop_finalize_fail",
  719. prompt: "Wait until stopped",
  720. sessionId,
  721. trace: {
  722. traceId: "trace_background_control_agent_stop_final_failure",
  723. spanId: "span_background_control_agent_stop_final_failure",
  724. sessionId,
  725. turnId,
  726. },
  727. turnId,
  728. workingDirectory: outputRootDir,
  729. workspaceRoot: outputRootDir,
  730. });
  731. await expect(port.stopTask?.("agent_stop_finalize_fail")).rejects.toThrow(
  732. "stopped notification was not enqueued",
  733. );
  734. expect(abortObserved).toBe(true);
  735. expect(registry.get("agent_stop_finalize_fail")).toMatchObject({
  736. status: "killed",
  737. });
  738. expect(
  739. events.filter((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  740. ).toHaveLength(1);
  741. expect(events.filter((event) => event.type === SessionEventType.SubagentStopped)).toEqual([
  742. expect.objectContaining({
  743. payload: expect.objectContaining({
  744. executionId: registry.get("agent_stop_finalize_fail")?.executionId,
  745. status: "stopped",
  746. }),
  747. }),
  748. ]);
  749. } finally {
  750. await rm(outputRootDir, { force: true, recursive: true });
  751. }
  752. });
  753. it.each([
  754. { background: false, blockedArtifact: "output.txt" },
  755. { background: false, blockedArtifact: "metadata.json" },
  756. { background: true, blockedArtifact: "output.txt" },
  757. { background: true, blockedArtifact: "metadata.json" },
  758. ])(
  759. "publishes stopped lifecycle after $blockedArtifact write failure (background=$background)",
  760. async ({ background, blockedArtifact }) => {
  761. const sessionId = createSessionId("agent-stop-artifact-failure");
  762. const turnId = createTurnId("turn_agent_stop_artifact_failure");
  763. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-agent-stop-artifact-failure-"));
  764. const registry = new InMemoryRuntimeTaskRegistry();
  765. const events: SessionEvent[] = [];
  766. const notifications: string[] = [];
  767. let abortObserved = false;
  768. const port = createExploreSubagentPort({
  769. createAgentId: () => "agent_stop_artifact_failure",
  770. emitParentEvent: async (event) => {
  771. events.push(event);
  772. },
  773. enqueueParentTaskNotification: (notification) => {
  774. notifications.push(notification.text);
  775. },
  776. outputRootDir,
  777. runtimeTaskRegistry: registry,
  778. async runExploreAgent(request, options) {
  779. await request.onSessionReady?.();
  780. return await new Promise((_, reject) => {
  781. const onAbort = () => {
  782. abortObserved = true;
  783. reject(options?.signal?.reason);
  784. };
  785. if (options?.signal?.aborted) onAbort();
  786. else options?.signal?.addEventListener("abort", onAbort, { once: true });
  787. });
  788. },
  789. });
  790. try {
  791. const request = {
  792. agentType: "general-purpose",
  793. description: "Stop with failed artifact write",
  794. parentToolCallId: "tool_stop_artifact_failure",
  795. prompt: "Wait until stopped",
  796. sessionId,
  797. trace: {
  798. traceId: "trace_stop_artifact_failure",
  799. spanId: "span_stop_artifact_failure",
  800. sessionId,
  801. turnId,
  802. },
  803. turnId,
  804. workingDirectory: outputRootDir,
  805. workspaceRoot: outputRootDir,
  806. };
  807. const running = background ? undefined : port.run(request);
  808. const foregroundResult = running?.catch((error: unknown) => error);
  809. if (background) await port.start?.(request);
  810. else
  811. await waitForCondition(() =>
  812. events.some((event) => event.type === SessionEventType.SubagentSpawned),
  813. );
  814. const task = registry.get("agent_stop_artifact_failure")!;
  815. const blockedPath = join(dirname(task.outputFile!), blockedArtifact);
  816. await rm(blockedPath, { force: true });
  817. await mkdir(blockedPath);
  818. await expect(
  819. port.stopTask?.(task.taskId, {
  820. expectedExecutionId: task.executionId,
  821. initiator: "user",
  822. }),
  823. ).rejects.toMatchObject({ path: blockedPath });
  824. expect(abortObserved).toBe(true);
  825. expect(registry.get(task.taskId)?.status).toBe("killed");
  826. expect(events.filter((event) => event.type === SessionEventType.SubagentStopped)).toEqual([
  827. expect.objectContaining({
  828. payload: expect.objectContaining({
  829. childSessionId: task.childSessionId,
  830. executionId: task.executionId,
  831. status: "stopped",
  832. }),
  833. }),
  834. ]);
  835. expect(
  836. events.filter((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  837. ).toHaveLength(background ? 1 : 0);
  838. expect(notifications).toHaveLength(background ? 1 : 0);
  839. if (foregroundResult)
  840. expect(await foregroundResult).toMatchObject({ type: CoreErrorType.ToolCancelled });
  841. const eventCount = events.length;
  842. await expect(
  843. port.stopTask?.(task.taskId, { expectedExecutionId: task.executionId }),
  844. ).resolves.toBeUndefined();
  845. expect(events).toHaveLength(eventCount);
  846. } finally {
  847. await port.close?.();
  848. await rm(outputRootDir, { force: true, recursive: true });
  849. }
  850. },
  851. );
  852. it("aborts a SendMessage-resumed background subagent when it is stopped", async () => {
  853. const sessionId = createSessionId("background-control-agent-resume");
  854. const turnId = createTurnId("turn_background_control_agent_resume");
  855. const childSessionId = createSessionId("subagent_agent_resume");
  856. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-background-control-agent-resume-"));
  857. const agentOutputDir = join(outputRootDir, sessionId, "agent_resume");
  858. const aborted = deferred();
  859. const parentEvents: SessionEvent[] = [];
  860. const registry = new InMemoryRuntimeTaskRegistry();
  861. registry.register({
  862. agentId: "agent_resume",
  863. agentType: "general-purpose",
  864. childSessionId,
  865. description: "Resume me",
  866. isBackgrounded: true,
  867. parentSessionId: sessionId,
  868. parentToolCallId: "tool_agent_resume",
  869. prompt: "Original prompt",
  870. startedAt: new Date(0),
  871. status: "completed",
  872. taskId: "agent_resume",
  873. taskType: "local_agent",
  874. traceContext: {
  875. traceId: "trace_background_control_agent_resume",
  876. spanId: "span_background_control_agent_resume",
  877. sessionId,
  878. turnId,
  879. },
  880. turnId,
  881. type: "local_agent",
  882. } as never);
  883. const port = createExploreSubagentPort({
  884. createAgentId: () => "unused_agent_id",
  885. emitParentEvent: async (event) => {
  886. parentEvents.push(event);
  887. },
  888. enqueueParentTaskNotification: () => {},
  889. outputRootDir,
  890. runtimeTaskRegistry: registry,
  891. async runExploreAgent(request, options) {
  892. await request.onSessionReady?.();
  893. return await new Promise((_, reject) => {
  894. options?.signal?.addEventListener(
  895. "abort",
  896. () => {
  897. aborted.resolve();
  898. reject(options.signal?.reason ?? new Error("aborted"));
  899. },
  900. { once: true },
  901. );
  902. });
  903. },
  904. });
  905. try {
  906. const result = await port.sendMessage?.({
  907. message: "Continue in background",
  908. parentToolCallId: "tool_agent_resume_send",
  909. sessionId,
  910. summary: "Continue resumed work",
  911. to: "agent_resume",
  912. trace: {
  913. traceId: "trace_background_control_agent_resume_send",
  914. spanId: "span_background_control_agent_resume_send",
  915. sessionId,
  916. turnId,
  917. },
  918. turnId,
  919. workingDirectory: outputRootDir,
  920. workspaceRoot: outputRootDir,
  921. });
  922. expect(result).toMatchObject({
  923. agentId: "agent_resume",
  924. delivery: "resumed_background",
  925. message: `Agent "agent_resume" was stopped (completed); resumed it in the background with your message. You'll be notified when it finishes. Output: ${join(agentOutputDir, "output.txt")}`,
  926. outputFile: join(agentOutputDir, "output.txt"),
  927. status: "success",
  928. taskId: "agent_resume",
  929. });
  930. const resumedStartEvents = parentEvents.filter(
  931. (event) =>
  932. event.type === SessionEventType.SubagentSpawned ||
  933. event.type === SessionEventType.BackgroundTaskStarted,
  934. );
  935. expect(resumedStartEvents.map((event) => event.type)).toEqual([
  936. SessionEventType.SubagentSpawned,
  937. ]);
  938. expect(resumedStartEvents[0]?.payload).toMatchObject({
  939. agentId: "agent_resume",
  940. background: true,
  941. childSessionId,
  942. resumed: true,
  943. status: "running",
  944. });
  945. const stopped = await port.stopTask?.("agent_resume");
  946. await Promise.race([
  947. aborted.promise,
  948. new Promise((_, reject) =>
  949. setTimeout(() => reject(new Error("resumed subagent was not aborted")), 100),
  950. ),
  951. ]);
  952. expect(stopped).toMatchObject({
  953. status: "killed",
  954. taskId: "agent_resume",
  955. });
  956. expect(registry.get("agent_resume")).toMatchObject({
  957. status: "killed",
  958. });
  959. } finally {
  960. await rm(outputRootDir, { force: true, recursive: true });
  961. }
  962. });
  963. it("rejects a stale execution token after SendMessage resumes the same taskId", async () => {
  964. const sessionId = createSessionId("background-control-agent-stale-stop");
  965. const turnId = createTurnId("turn_background_control_agent_stale_stop");
  966. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-agent-stale-stop-"));
  967. const registry = new InMemoryRuntimeTaskRegistry();
  968. const notifications: string[] = [];
  969. const events: SessionEvent[] = [];
  970. const port = createExploreSubagentPort({
  971. createAgentId: () => "agent_stale_stop",
  972. emitParentEvent: async (event) => {
  973. events.push(event);
  974. },
  975. enqueueParentTaskNotification: (notification) => {
  976. notifications.push(notification.text);
  977. },
  978. outputRootDir,
  979. runtimeTaskRegistry: registry,
  980. async runExploreAgent(request, options) {
  981. await request.onSessionReady?.();
  982. return await new Promise((_, reject) => {
  983. options?.signal?.addEventListener("abort", () => reject(options.signal?.reason), {
  984. once: true,
  985. });
  986. });
  987. },
  988. });
  989. const trace = {
  990. traceId: "trace_agent_stale_stop",
  991. spanId: "span_agent_stale_stop",
  992. sessionId,
  993. turnId,
  994. };
  995. try {
  996. await port.start?.({
  997. agentType: "general-purpose",
  998. description: "Stop old generation",
  999. parentToolCallId: "tool_stale",
  1000. prompt: "Wait",
  1001. sessionId,
  1002. trace,
  1003. turnId,
  1004. workingDirectory: outputRootDir,
  1005. workspaceRoot: outputRootDir,
  1006. });
  1007. const firstExecutionId = (
  1008. registry.get("agent_stale_stop") as { executionId?: string } | undefined
  1009. )?.executionId;
  1010. expect(firstExecutionId).toBeTruthy();
  1011. await port.stopTask?.("agent_stale_stop", { expectedExecutionId: firstExecutionId });
  1012. await waitForCondition(() => registry.get("agent_stale_stop")?.status === "killed");
  1013. const sent = await port.sendMessage?.({
  1014. to: "agent_stale_stop",
  1015. message: "Continue",
  1016. parentToolCallId: "tool_resume",
  1017. sessionId,
  1018. trace,
  1019. turnId,
  1020. workingDirectory: outputRootDir,
  1021. workspaceRoot: outputRootDir,
  1022. });
  1023. expect(sent?.delivery).toBe("resumed_background");
  1024. const secondExecutionId = (
  1025. registry.get("agent_stale_stop") as { executionId?: string } | undefined
  1026. )?.executionId;
  1027. expect(secondExecutionId).toBeTruthy();
  1028. expect(secondExecutionId).not.toBe(firstExecutionId);
  1029. const oldStop = await port.stopTask?.("agent_stale_stop", {
  1030. expectedExecutionId: firstExecutionId,
  1031. });
  1032. expect(oldStop).toBeUndefined();
  1033. expect(registry.get("agent_stale_stop")?.status).toBe("running");
  1034. expect(notifications).toHaveLength(1);
  1035. await port.stopTask?.("agent_stale_stop", { expectedExecutionId: secondExecutionId });
  1036. await waitForCondition(() => registry.get("agent_stale_stop")?.status === "killed");
  1037. expect(notifications).toHaveLength(2);
  1038. expect(
  1039. events.filter((event) => event.type === SessionEventType.SubagentSpawned),
  1040. ).toHaveLength(2);
  1041. } finally {
  1042. await port.close?.();
  1043. await rm(outputRootDir, { force: true, recursive: true });
  1044. }
  1045. });
  1046. it("stops a foreground child without a background notification or failed overwrite", async () => {
  1047. const sessionId = createSessionId("foreground-control-agent-stop");
  1048. const turnId = createTurnId("turn_foreground_control_agent_stop");
  1049. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-foreground-control-agent-"));
  1050. const registry = new InMemoryRuntimeTaskRegistry();
  1051. const notifications: string[] = [];
  1052. const events: SessionEvent[] = [];
  1053. const port = createExploreSubagentPort({
  1054. createAgentId: () => "agent_foreground_stop",
  1055. emitParentEvent: async (event) => {
  1056. events.push(event);
  1057. },
  1058. enqueueParentTaskNotification: (notification) => {
  1059. notifications.push(notification.text);
  1060. },
  1061. outputRootDir,
  1062. runtimeTaskRegistry: registry,
  1063. async runExploreAgent(request, options) {
  1064. await request.onSessionReady?.();
  1065. return await new Promise((_, reject) => {
  1066. options?.signal?.addEventListener("abort", () => reject(options.signal?.reason), {
  1067. once: true,
  1068. });
  1069. });
  1070. },
  1071. });
  1072. const trace = {
  1073. traceId: "trace_foreground_stop",
  1074. spanId: "span_foreground_stop",
  1075. sessionId,
  1076. turnId,
  1077. };
  1078. try {
  1079. const running = port.run({
  1080. agentType: "general-purpose",
  1081. description: "Stop foreground",
  1082. parentToolCallId: "tool_foreground",
  1083. prompt: "Wait",
  1084. sessionId,
  1085. trace,
  1086. turnId,
  1087. workingDirectory: outputRootDir,
  1088. workspaceRoot: outputRootDir,
  1089. });
  1090. await waitForCondition(() =>
  1091. events.some((event) => event.type === SessionEventType.SubagentSpawned),
  1092. );
  1093. const executionId = (
  1094. registry.get("agent_foreground_stop") as { executionId?: string } | undefined
  1095. )?.executionId;
  1096. expect(executionId).toBeTruthy();
  1097. await port.stopTask?.("agent_foreground_stop", { expectedExecutionId: executionId });
  1098. await expect(running).rejects.toMatchObject({ type: CoreErrorType.ToolCancelled });
  1099. expect(registry.get("agent_foreground_stop")?.status).toBe("killed");
  1100. expect(notifications).toEqual([]);
  1101. expect(
  1102. events.filter((event) => event.type === SessionEventType.SubagentStopped),
  1103. ).toHaveLength(1);
  1104. } finally {
  1105. await port.close?.();
  1106. await rm(outputRootDir, { force: true, recursive: true });
  1107. }
  1108. });
  1109. it("lets the parent turn continue after a foreground Agent tool is stopped", async () => {
  1110. const sessionId = createSessionId("foreground-stop-parent-continues");
  1111. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-foreground-stop-turn-"));
  1112. const registry = new InMemoryRuntimeTaskRegistry();
  1113. const events: SessionEvent[] = [];
  1114. let parentRequests = 0;
  1115. const port = createExploreSubagentPort({
  1116. createAgentId: () => "agent_parent_continues",
  1117. emitParentEvent: async (event) => {
  1118. events.push(event);
  1119. },
  1120. outputRootDir,
  1121. runtimeTaskRegistry: registry,
  1122. async runExploreAgent(request, options) {
  1123. await request.onSessionReady?.();
  1124. return await new Promise((_, reject) => {
  1125. options?.signal?.addEventListener("abort", () => reject(options.signal?.reason), {
  1126. once: true,
  1127. });
  1128. });
  1129. },
  1130. });
  1131. const runtime = createTestAgentRuntime(
  1132. sessionId,
  1133. {
  1134. mode: "yolo",
  1135. modelSelection: {
  1136. providerId: createModelProviderId("provider-test"),
  1137. modelId: createModelId("parent-model"),
  1138. },
  1139. workingDirectory: outputRootDir,
  1140. },
  1141. {
  1142. eventStore: createTestSessionEventStore(),
  1143. runtimeTaskRegistry: registry,
  1144. subagentPort: port,
  1145. modelFactory: createTestModelFactory({
  1146. async generateText() {
  1147. parentRequests++;
  1148. return parentRequests === 1
  1149. ? {
  1150. finishReason: "tool-calls",
  1151. text: "",
  1152. toolCalls: [
  1153. {
  1154. id: "call_parent_agent_stop",
  1155. name: "Agent",
  1156. input: {
  1157. description: "Stop child only",
  1158. prompt: "Wait for stop",
  1159. subagent_type: "general-purpose",
  1160. },
  1161. },
  1162. ],
  1163. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1164. }
  1165. : {
  1166. finishReason: "stop",
  1167. text: "Parent continued",
  1168. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1169. };
  1170. },
  1171. } as never),
  1172. },
  1173. );
  1174. try {
  1175. const turn = runtime.executeTurn("Stop this child, then continue");
  1176. await waitForCondition(() =>
  1177. events.some((event) => event.type === SessionEventType.SubagentSpawned),
  1178. );
  1179. const executionId = registry.get("agent_parent_continues")?.executionId;
  1180. expect(executionId).toBeTruthy();
  1181. await runtime.stopBackgroundTask("agent_parent_continues", {
  1182. expectedExecutionId: executionId,
  1183. initiator: "user",
  1184. strict: true,
  1185. });
  1186. const result = await turn;
  1187. expect(result).toMatchObject({ response: "Parent continued" });
  1188. expect(parentRequests).toBe(2);
  1189. expect(registry.get("agent_parent_continues")?.status).toBe("killed");
  1190. expect(
  1191. events.filter((event) => event.type === SessionEventType.SubagentStopped),
  1192. ).toHaveLength(1);
  1193. } finally {
  1194. await port.close?.();
  1195. await rm(outputRootDir, { force: true, recursive: true });
  1196. }
  1197. });
  1198. it("keeps the first terminal decision when background completion races with stop", async () => {
  1199. const sessionId = createSessionId("background-stop-completion-race");
  1200. const turnId = createTurnId("turn_background_stop_completion_race");
  1201. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-stop-completion-race-"));
  1202. const releaseCompletion = deferred<{
  1203. response: string;
  1204. traceId: string;
  1205. events: SessionEvent[];
  1206. }>();
  1207. const registry = new InMemoryRuntimeTaskRegistry();
  1208. const notifications: string[] = [];
  1209. const events: SessionEvent[] = [];
  1210. const port = createExploreSubagentPort({
  1211. createAgentId: () => "agent_completion_race",
  1212. emitParentEvent: async (event) => {
  1213. events.push(event);
  1214. },
  1215. enqueueParentTaskNotification: (notification) => {
  1216. notifications.push(notification.text);
  1217. },
  1218. outputRootDir,
  1219. runtimeTaskRegistry: registry,
  1220. async runExploreAgent(request) {
  1221. await request.onSessionReady?.();
  1222. return releaseCompletion.promise;
  1223. },
  1224. });
  1225. try {
  1226. await port.start?.({
  1227. agentType: "general-purpose",
  1228. description: "Stop completion race",
  1229. parentToolCallId: "tool_completion_race",
  1230. prompt: "Wait",
  1231. sessionId,
  1232. trace: {
  1233. traceId: "trace_completion_race",
  1234. spanId: "span_completion_race",
  1235. sessionId,
  1236. turnId,
  1237. },
  1238. turnId,
  1239. workingDirectory: outputRootDir,
  1240. workspaceRoot: outputRootDir,
  1241. });
  1242. const executionId = registry.get("agent_completion_race")?.executionId;
  1243. await port.stopTask?.("agent_completion_race", { expectedExecutionId: executionId });
  1244. releaseCompletion.resolve({
  1245. response: "late success",
  1246. traceId: "trace_completion_race",
  1247. events: [],
  1248. });
  1249. await port.close?.();
  1250. expect(registry.get("agent_completion_race")?.status).toBe("killed");
  1251. expect(notifications).toHaveLength(1);
  1252. expect(
  1253. events.filter((event) => event.type === SessionEventType.SubagentStopped),
  1254. ).toHaveLength(1);
  1255. } finally {
  1256. releaseCompletion.resolve({
  1257. response: "late success",
  1258. traceId: "trace_completion_race",
  1259. events: [],
  1260. });
  1261. await port.close?.();
  1262. await rm(outputRootDir, { force: true, recursive: true });
  1263. }
  1264. });
  1265. it("does not overwrite a terminal runtime task when a late tracker snapshot arrives", () => {
  1266. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  1267. runtimeTaskRegistry.register({
  1268. agentId: "bash_race",
  1269. agentType: "local_bash",
  1270. description: "sleep 30",
  1271. isBackgrounded: true,
  1272. startedAt: new Date(0),
  1273. status: "killed",
  1274. taskId: "bash_race",
  1275. taskType: "local_bash",
  1276. type: "local_bash",
  1277. } as never);
  1278. updateRuntimeBackgroundTask(
  1279. { runtimeTaskRegistry } as never,
  1280. {
  1281. id: "tool_bash_race",
  1282. input: { command: "sleep 30" },
  1283. name: "Bash",
  1284. } as never,
  1285. "bash_race",
  1286. "completed",
  1287. {
  1288. taskId: "bash_race",
  1289. status: "completed",
  1290. startedAt: new Date(0),
  1291. completedAt: new Date(1),
  1292. stdoutTail: "done",
  1293. },
  1294. );
  1295. expect(runtimeTaskRegistry.get("bash_race")).toMatchObject({
  1296. status: "killed",
  1297. });
  1298. expect(runtimeTaskRegistry.get("bash_race")).not.toHaveProperty("stdoutTail");
  1299. });
  1300. /**
  1301. * TaskOutput 的投影只读得到 registry 条目(dwf 从不写 outputFile),所以产物必须在终态
  1302. * 更新时就落到条目上。以下几条钉住「存什么、什么时候存、绝不用 undefined 清掉已有值」。
  1303. */
  1304. describe("dwf run 产物落到 registry 条目上", () => {
  1305. const CREATE_WORKFLOW_CALL = {
  1306. id: "tool_dwf_result",
  1307. input: { script: "return 1;" },
  1308. name: "CreateWorkflow",
  1309. };
  1310. function registryWithDwfRun(): InMemoryRuntimeTaskRegistry {
  1311. const registry = new InMemoryRuntimeTaskRegistry();
  1312. registry.register({
  1313. agentId: "dwfrun-result",
  1314. agentType: "local_dynamic_workflow",
  1315. description: "Dynamic workflow run",
  1316. isBackgrounded: true,
  1317. startedAt: new Date(0),
  1318. status: "running",
  1319. taskId: "dwfrun-result",
  1320. taskType: "local_dynamic_workflow",
  1321. type: "local_dynamic_workflow",
  1322. } as never);
  1323. return registry;
  1324. }
  1325. function update(
  1326. registry: InMemoryRuntimeTaskRegistry,
  1327. status: string,
  1328. snapshot: Record<string, unknown>,
  1329. ): void {
  1330. updateRuntimeBackgroundTask(
  1331. { runtimeTaskRegistry: registry } as never,
  1332. CREATE_WORKFLOW_CALL as never,
  1333. "dwfrun-result",
  1334. status,
  1335. snapshot as never,
  1336. );
  1337. }
  1338. it("终态的字符串产物原样存为 resultText", () => {
  1339. const registry = registryWithDwfRun();
  1340. update(registry, "completed", {
  1341. taskId: "dwfrun-result",
  1342. status: "completed",
  1343. output: "the final answer",
  1344. });
  1345. expect(registry.get("dwfrun-result")?.resultText).toBe("the final answer");
  1346. });
  1347. it("终态的对象产物存为 pretty JSON", () => {
  1348. const registry = registryWithDwfRun();
  1349. update(registry, "completed", {
  1350. taskId: "dwfrun-result",
  1351. status: "completed",
  1352. output: { report: "done" },
  1353. });
  1354. expect(registry.get("dwfrun-result")?.resultText).toBe(
  1355. JSON.stringify({ report: "done" }, null, 2),
  1356. );
  1357. });
  1358. it("running 的中途快照不写 resultText", () => {
  1359. const registry = registryWithDwfRun();
  1360. update(registry, "running", {
  1361. taskId: "dwfrun-result",
  1362. status: "running",
  1363. output: "not settled yet",
  1364. });
  1365. expect(registry.get("dwfrun-result")?.resultText).toBeUndefined();
  1366. });
  1367. it("产物缺席的终态不写 resultText", () => {
  1368. const registry = registryWithDwfRun();
  1369. update(registry, "completed", { taskId: "dwfrun-result", status: "completed" });
  1370. expect(registry.get("dwfrun-result")?.resultText).toBeUndefined();
  1371. });
  1372. // undefined 绝不清掉已有值:一次产物缺席的更新不该把先前存下的产物抹掉。
  1373. it("已有的 resultText 不被产物缺席的更新清掉", () => {
  1374. const registry = registryWithDwfRun();
  1375. registry.update("dwfrun-result", (current) => ({
  1376. ...current,
  1377. resultText: "already captured",
  1378. }));
  1379. update(registry, "running", { taskId: "dwfrun-result", status: "running" });
  1380. expect(registry.get("dwfrun-result")?.resultText).toBe("already captured");
  1381. });
  1382. it("legacy Workflow 的终态不写 resultText(不改它的契约)", () => {
  1383. const registry = new InMemoryRuntimeTaskRegistry();
  1384. registry.register({
  1385. agentId: "wfrun-legacy",
  1386. agentType: "local_workflow",
  1387. description: "Workflow background task",
  1388. isBackgrounded: true,
  1389. startedAt: new Date(0),
  1390. status: "running",
  1391. taskId: "wfrun-legacy",
  1392. taskType: "local_workflow",
  1393. type: "local_workflow",
  1394. } as never);
  1395. updateRuntimeBackgroundTask(
  1396. { runtimeTaskRegistry: registry } as never,
  1397. { id: "tool_wf_legacy", input: { scriptPath: "w.ts" }, name: "Workflow" } as never,
  1398. "wfrun-legacy",
  1399. "completed",
  1400. { runId: "wfrun-legacy", status: "completed", output: { response: "legacy" } } as never,
  1401. );
  1402. expect(registry.get("wfrun-legacy")?.resultText).toBeUndefined();
  1403. });
  1404. });
  1405. it("emits non-cancellable terminal background task events", async () => {
  1406. const sessionId = createSessionId("background-control-terminal-cancellable");
  1407. const turnId = createTurnId("turn_background_control_terminal_cancellable");
  1408. const events: Array<{ type: SessionEventType; payload: unknown }> = [];
  1409. const tracker = new BackgroundTaskTracker({
  1410. emitEvent: async (event) => {
  1411. events.push({ type: event.type, payload: event.payload });
  1412. },
  1413. executionPort: {
  1414. async run() {
  1415. throw new Error("run should not be called");
  1416. },
  1417. async cancelBackgroundTask() {
  1418. throw new Error("cancelBackgroundTask should not be called");
  1419. },
  1420. async waitForBackgroundTask() {
  1421. return {
  1422. taskId: "bash_terminal_cancellable",
  1423. status: "completed",
  1424. startedAt: new Date(0),
  1425. completedAt: new Date(1),
  1426. stdoutTail: "done",
  1427. };
  1428. },
  1429. },
  1430. getWorkingDirectory: () => "/tmp",
  1431. getWorkspaceRoot: () => "/tmp",
  1432. readFileState: new Map(),
  1433. runtimeScope: "main",
  1434. sessionId,
  1435. } as never);
  1436. await tracker.trackBackgroundTask(
  1437. {
  1438. id: "tool_bash_terminal_cancellable",
  1439. input: { command: "echo done" },
  1440. name: "Bash",
  1441. } as never,
  1442. {
  1443. backgroundTaskId: "bash_terminal_cancellable",
  1444. status: "backgrounded",
  1445. },
  1446. {
  1447. traceId: "trace_background_control_terminal_cancellable",
  1448. spanId: "span_background_control_terminal_cancellable",
  1449. sessionId,
  1450. turnId,
  1451. },
  1452. turnId,
  1453. );
  1454. await waitForCondition(() =>
  1455. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1456. );
  1457. const completed = events.find(
  1458. (event) => event.type === SessionEventType.BackgroundTaskCompleted,
  1459. );
  1460. expect(completed?.payload).toMatchObject({
  1461. cancellable: false,
  1462. status: "completed",
  1463. taskId: "bash_terminal_cancellable",
  1464. });
  1465. });
  1466. it("logs pid, exit code and duration of a background Bash process with its toolCallId", async () => {
  1467. const sessionId = createSessionId("background-control-terminal-log");
  1468. const turnId = createTurnId("turn_background_control_terminal_log");
  1469. const logs: Array<{ message: string; context: Record<string, unknown> }> = [];
  1470. const tracker = new BackgroundTaskTracker({
  1471. emitEvent: async () => {},
  1472. executionPort: {
  1473. async run() {
  1474. throw new Error("run should not be called");
  1475. },
  1476. async waitForBackgroundTask() {
  1477. return {
  1478. taskId: "bash_terminal_log",
  1479. status: "failed",
  1480. startedAt: new Date(0),
  1481. completedAt: new Date(2_000),
  1482. pid: 5824,
  1483. result: {
  1484. status: "failed",
  1485. exitCode: 137,
  1486. signal: "SIGKILL",
  1487. durationMs: 2_000,
  1488. pid: 5824,
  1489. },
  1490. };
  1491. },
  1492. },
  1493. getWorkingDirectory: () => "/tmp",
  1494. getWorkspaceRoot: () => "/tmp",
  1495. logger: {
  1496. info: (message: string, context?: Record<string, unknown>) =>
  1497. logs.push({ message, context: context ?? {} }),
  1498. },
  1499. readFileState: new Map(),
  1500. runtimeScope: "main",
  1501. sessionId,
  1502. } as never);
  1503. await tracker.trackBackgroundTask(
  1504. { id: "tool_bash_terminal_log", input: { command: "python big.py" }, name: "Bash" } as never,
  1505. { backgroundTaskId: "bash_terminal_log", status: "backgrounded" },
  1506. { traceId: "trace_terminal_log", spanId: "span_terminal_log", sessionId, turnId },
  1507. turnId,
  1508. );
  1509. await waitForCondition(() =>
  1510. logs.some((entry) => entry.context.event === "background_task.tracking.terminal"),
  1511. );
  1512. expect(
  1513. logs.find((entry) => entry.context.event === "background_task.tracking.terminal")?.context,
  1514. ).toMatchObject({
  1515. durationMs: 2_000,
  1516. exitCode: 137,
  1517. pid: 5824,
  1518. signal: "SIGKILL",
  1519. taskId: "bash_terminal_log",
  1520. toolCallId: "tool_bash_terminal_log",
  1521. });
  1522. });
  1523. });
  1524. /**
  1525. * 后台生命周期的按工具名硬分派已改成按工具查表(见 docs/dynamic-workflow/presentation.md 的
  1526. * 「后台生命周期泛化」)。这一组测两件事:CreateWorkflow 经 dynamicWorkflowRunPort 拿到
  1527. * 完整的快照/等待/取消能力,以及既有工具的语义逐字未变。
  1528. */
  1529. describe("background task per-tool provider lookup", () => {
  1530. interface TrackedRun {
  1531. events: { payload: Record<string, unknown>; type: string }[];
  1532. notifications: { taskId?: string; text: string; toolName?: string; originMeta?: unknown }[];
  1533. }
  1534. async function trackDynamicWorkflowRun(options: {
  1535. getTask?: () => Promise<unknown>;
  1536. input?: Record<string, unknown>;
  1537. launchOutput?: Record<string, unknown>;
  1538. name?: string;
  1539. port?: Record<string, unknown>;
  1540. waitForTask?: () => Promise<unknown>;
  1541. }): Promise<TrackedRun> {
  1542. const sessionId = createSessionId(options.name ?? "dwf-tracker");
  1543. const turnId = createTurnId(options.name ?? "dwf-tracker");
  1544. const events: TrackedRun["events"] = [];
  1545. const notifications: TrackedRun["notifications"] = [];
  1546. const tracker = new BackgroundTaskTracker({
  1547. emitEvent: async (event) => {
  1548. events.push({ payload: event.payload as Record<string, unknown>, type: event.type });
  1549. },
  1550. enqueueBackgroundTaskNotification: (notification) => {
  1551. notifications.push(notification);
  1552. return undefined;
  1553. },
  1554. dynamicWorkflowRunPort:
  1555. options.port ??
  1556. ({
  1557. async submit() {
  1558. throw new Error("submit should not be called by the tracker");
  1559. },
  1560. getTask: options.getTask ?? (async () => ({ status: "running", taskId: "dwfrun-1" })),
  1561. waitForTask:
  1562. options.waitForTask ??
  1563. (async () => ({
  1564. status: "completed",
  1565. taskId: "dwfrun-1",
  1566. output: { response: "workflow answer" },
  1567. })),
  1568. async cancel() {
  1569. return true;
  1570. },
  1571. async listEvents() {
  1572. return [];
  1573. },
  1574. } as never),
  1575. getWorkingDirectory: () => "/tmp",
  1576. getWorkspaceRoot: () => "/tmp",
  1577. readFileState: new Map(),
  1578. runtimeScope: "main",
  1579. sessionId,
  1580. } as never);
  1581. await tracker.trackBackgroundTask(
  1582. {
  1583. id: "tool_create_workflow_1",
  1584. input: options.input ?? { script: 'const r = await agent("a").ask("x");' },
  1585. name: "CreateWorkflow",
  1586. } as never,
  1587. { backgroundTaskId: "dwfrun-1", status: "backgrounded", ...options.launchOutput },
  1588. {
  1589. traceId: `trace_${options.name ?? "dwf-tracker"}`,
  1590. spanId: `span_${options.name ?? "dwf-tracker"}`,
  1591. sessionId,
  1592. turnId,
  1593. },
  1594. turnId,
  1595. );
  1596. return { events, notifications };
  1597. }
  1598. // 第五处分派(canCancelBackgroundTask):它决定 started payload 的 cancellable。
  1599. // 不修它,详情页与后台面板的 Cancel 按钮点不动——整条取消路径不可达。
  1600. it("CreateWorkflow 的 started payload 可取消", async () => {
  1601. const { events } = await trackDynamicWorkflowRun({ name: "dwf-cancellable" });
  1602. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  1603. expect(started?.payload).toMatchObject({
  1604. cancellable: true,
  1605. status: "running",
  1606. taskId: "dwfrun-1",
  1607. toolName: "CreateWorkflow",
  1608. });
  1609. });
  1610. // taskKind 是展示类别(面板分组与图标)。dwf run 此前落进 "bash"——一个我们知情的错标。
  1611. // 生命周期语义不受它影响(已由 per-tool lifecycleProvider 分派),但面板据它分组,
  1612. // 而一个能点开详情页、能取消的 run 与一条后台 shell 命令不是同一种东西。
  1613. it("CreateWorkflow 的 taskKind 是 workflow,不再错标成 bash", async () => {
  1614. const { events } = await trackDynamicWorkflowRun({ name: "dwf-task-kind" });
  1615. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  1616. expect((started?.payload as { taskKind?: string }).taskKind).toBe("workflow");
  1617. });
  1618. /**
  1619. * payload 的 `description` 是任务岛 Workflows 分区那一行的题名(经 backgroundWorks.title)。
  1620. * 原实现只认 `input.description`,而 CreateWorkflow 的输入 schema 里根本没有这个键
  1621. * (只有 `{name?, script}`,contracts/src/tools/create-workflow.ts),于是面板行退到 toolName
  1622. * 显示成 "CreateWorkflow"——每个 run 都同名。改走既有的 workflowTaskSubject 兜底链。
  1623. */
  1624. it("CreateWorkflow 的展示名取 input.name", async () => {
  1625. const { events } = await trackDynamicWorkflowRun({
  1626. input: { name: "Nightly release audit", script: "" },
  1627. name: "dwf-description-name",
  1628. });
  1629. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  1630. expect(started?.payload).toMatchObject({ description: "Nightly release audit" });
  1631. });
  1632. // 名字缺席时兜底链走到最后一环 taskId:不是 undefined,也不是 toolName。
  1633. // 投影对这两者的处理本就一致(都会落到 UI 侧的 fallbackName),所以 taskId 可接受。
  1634. it("CreateWorkflow 无 name 时展示名兜底到 taskId 而不是工具名", async () => {
  1635. const { events } = await trackDynamicWorkflowRun({ name: "dwf-description-fallback" });
  1636. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  1637. expect((started?.payload as { description?: string }).description).toBe("dwfrun-1");
  1638. });
  1639. // 快照提供者与直接等待者都来自同一个端口:终态经 waitForTask 到达并收口成 completed。
  1640. it("经端口的快照提供者与等待者把 run 结算成终态", async () => {
  1641. const { events } = await trackDynamicWorkflowRun({ name: "dwf-terminal" });
  1642. await waitForCondition(() =>
  1643. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1644. );
  1645. const completed = events.find(
  1646. (event) => event.type === SessionEventType.BackgroundTaskCompleted,
  1647. );
  1648. expect(completed?.payload).toMatchObject({ status: "completed", taskId: "dwfrun-1" });
  1649. });
  1650. // 完成通知复用 formatWorkflowTaskNotification,并带 backgroundSource "workflow",
  1651. // 这样主 agent 的新回合渲染成后台结果头而不是退化成裸 model-only 消息。
  1652. it("终态通知走 workflow 通知格式并标记 backgroundSource", async () => {
  1653. const { events, notifications } = await trackDynamicWorkflowRun({ name: "dwf-notify" });
  1654. await waitForCondition(() =>
  1655. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1656. );
  1657. expect(notifications).toHaveLength(1);
  1658. const notification = notifications[0]!;
  1659. expect(notification.taskId).toBe("dwfrun-1");
  1660. expect(notification.toolName).toBe("CreateWorkflow");
  1661. // formatWorkflowTaskNotification 的形状(不是 Bash 的那套):workflow 措辞的 summary
  1662. // 加上截断后的结果。
  1663. expect(notification.text).toContain('<summary>Workflow &quot;dwfrun-1&quot; completed.</summary>');
  1664. expect(notification.text).toContain("workflow answer");
  1665. expect(notification.originMeta).toMatchObject({
  1666. backgroundSource: "workflow",
  1667. workId: "dwfrun-1",
  1668. });
  1669. });
  1670. /**
  1671. * run 产物的回投(桌面实测 bug)。原实现按 legacy `Workflow` 的输出形状取 `output.response`:
  1672. * dwf 产物是脚本的任意顶层返回值,record 时没有 `response` 键 → `<result>` 整个缺席;
  1673. * 非 record 时 `isRecord` 门把 output 退到 **launch output**,其 `response` 是「run 已在后台
  1674. * 启动」的陈旧散文——比缺席更糟。以下几条把序列化规则与「绝不回退散文」钉住。
  1675. *
  1676. * launchOutput 只在 `lost` 那两条路径上到得了通知(终态路径根本不传它),所以「不回退散文」
  1677. * 唯一能真正失败的地方是 lost 用例。
  1678. */
  1679. const LAUNCH_PROSE =
  1680. "The workflow script compiled cleanly and the run started in the background with ID: dwfrun-1.";
  1681. async function notificationFor(name: string, artifact: unknown): Promise<string> {
  1682. const { events, notifications } = await trackDynamicWorkflowRun({
  1683. name,
  1684. waitForTask: async () => ({
  1685. status: "completed",
  1686. taskId: "dwfrun-1",
  1687. ...(artifact === undefined ? {} : { output: artifact }),
  1688. }),
  1689. });
  1690. await waitForCondition(() =>
  1691. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1692. );
  1693. return notifications[0]!.text;
  1694. }
  1695. it("字符串产物原样进 <result>(不加 JSON 引号)", async () => {
  1696. const text = await notificationFor("dwf-artifact-string", "the final answer");
  1697. expect(text).toContain("<result>the final answer</result>");
  1698. expect(text).not.toContain('"the final answer"');
  1699. });
  1700. it("对象产物按 pretty JSON 进 <result>", async () => {
  1701. const text = await notificationFor("dwf-artifact-object", {
  1702. report: "done",
  1703. steps: [1, 2],
  1704. });
  1705. // JSON.stringify(v, null, 2),随后经 escapeXml(引号变 &quot;)。
  1706. expect(text).toContain("&quot;report&quot;: &quot;done&quot;");
  1707. expect(text).toContain("&quot;steps&quot;");
  1708. expect(text).toContain("<result>{\n");
  1709. });
  1710. it("非 record 的数组产物也走 pretty JSON", async () => {
  1711. const text = await notificationFor("dwf-artifact-array", ["one", "two"]);
  1712. expect(text).toContain("&quot;one&quot;");
  1713. expect(text).toContain("<result>[\n");
  1714. });
  1715. // 产物缺席时 `<result>` 整字段缺席。
  1716. it("undefined 产物没有 <result>", async () => {
  1717. const text = await notificationFor("dwf-artifact-absent", undefined);
  1718. expect(text).not.toContain("<result>");
  1719. });
  1720. it("失败的 run 带 <error> 不带 <result>", async () => {
  1721. const { events, notifications } = await trackDynamicWorkflowRun({
  1722. name: "dwf-artifact-failed",
  1723. waitForTask: async () => ({
  1724. status: "failed",
  1725. taskId: "dwfrun-1",
  1726. error: "script threw TypeError",
  1727. }),
  1728. });
  1729. await waitForCondition(() =>
  1730. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1731. );
  1732. const text = notifications[0]!.text;
  1733. expect(text).toContain("<error>script threw TypeError</error>");
  1734. expect(text).not.toContain("<result>");
  1735. });
  1736. // 这条是「比缺席更糟」的那一种:lost 路径把 launch output 递进通知,原实现于是把
  1737. // 「run 已在后台启动」的陈旧散文当成 run 的结果回给模型。dwf 必须整字段缺席。
  1738. it("lost 的 dwf run 绝不把 launch 散文当结果回投", async () => {
  1739. const { events, notifications } = await trackDynamicWorkflowRun({
  1740. launchOutput: { response: LAUNCH_PROSE },
  1741. name: "dwf-artifact-lost",
  1742. waitForTask: async () => undefined,
  1743. });
  1744. await waitForCondition(() =>
  1745. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1746. );
  1747. const text = notifications[0]!.text;
  1748. expect(text).toContain("its in-process state was lost");
  1749. expect(text).not.toContain("<result>");
  1750. expect(text).not.toContain(LAUNCH_PROSE);
  1751. });
  1752. // ── 渐进产物(report)随完成通知回投(docs/dynamic-workflow/transcript-and-notifications.md「Notifications」)──
  1753. //
  1754. // 三个终态一律携带,因为一个死在半途的 run 仍然做完了前面那些活——捞回它正是 report 存在
  1755. // 的理由,而一句「失败」把它全扔了。条目来自 journal 的 kind="report" 行(run service 把它
  1756. // 们放在快照的 `reports` 上),不是 memory-only 的 workflowRuns 投影。
  1757. async function notificationWithReports(
  1758. name: string,
  1759. snapshot: Record<string, unknown>,
  1760. ): Promise<string> {
  1761. const { events, notifications } = await trackDynamicWorkflowRun({
  1762. name,
  1763. waitForTask: async () => ({ taskId: "dwfrun-1", ...snapshot }),
  1764. });
  1765. await waitForCondition(() =>
  1766. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1767. );
  1768. return notifications[0]!.text;
  1769. }
  1770. it("completed 的通知带 <reports>:真实总数 + 逐条预览(string 原样 / object pretty JSON)", async () => {
  1771. const text = await notificationWithReports("dwf-reports-completed", {
  1772. status: "completed",
  1773. output: "final answer",
  1774. reports: ["3 stale imports", { file: "a.ts", severity: "warn" }],
  1775. });
  1776. expect(text).toContain('<reports count="2">');
  1777. expect(text).toContain("[1] 3 stale imports");
  1778. // 序列化规则与 <result> 同源:object 走 pretty JSON(经 escapeXml,引号变 &quot;)。
  1779. expect(text).toContain("[2] {");
  1780. expect(text).toContain("&quot;file&quot;: &quot;a.ts&quot;");
  1781. // 全部条目都进了预览,所以不带 shown 属性(shown 的存在本身就意味着"预览是局部的")。
  1782. expect(text).not.toContain("shown=");
  1783. // 产物与 run 结果是两件事,两者同时在场。
  1784. expect(text).toContain("<result>final answer</result>");
  1785. });
  1786. it("failed 与 cancelled 的通知一样带 reports(这条是 report 特性的目的)", async () => {
  1787. const failed = await notificationWithReports("dwf-reports-failed", {
  1788. status: "failed",
  1789. error: "script threw TypeError",
  1790. reports: ["finding before the crash"],
  1791. });
  1792. expect(failed).toContain('<reports count="1">');
  1793. expect(failed).toContain("[1] finding before the crash");
  1794. expect(failed).toContain("<error>script threw TypeError</error>");
  1795. // 失败的 run 没有产物,但有报告——两者必须能分辨。
  1796. expect(failed).not.toContain("<result>");
  1797. const cancelled = await notificationWithReports("dwf-reports-cancelled", {
  1798. status: "cancelled",
  1799. reports: ["finding before the cancel"],
  1800. });
  1801. expect(cancelled).toContain('<reports count="1">');
  1802. expect(cancelled).toContain("[1] finding before the cancel");
  1803. });
  1804. // ── 呈现指引(docs/dynamic-workflow/authoring.md「What the main agent is told when a run ends」)──
  1805. //
  1806. // XML 之后追加一段散文,告诉主代理把 run 的结果当交付物呈现。completed 与非 completed 各一段;
  1807. // 散文排在 reports 之后,所以总截断先斩它。
  1808. it("completed 的通知在 XML 之后带交付物呈现指引", async () => {
  1809. const text = await notificationWithReports("dwf-guidance-completed", {
  1810. status: "completed",
  1811. output: "final answer",
  1812. reports: ["one finding"],
  1813. });
  1814. const close = text.indexOf("</task-notification>");
  1815. const guidance = text.indexOf("Present its outcome to the user as a deliverable");
  1816. expect(close).toBeGreaterThanOrEqual(0);
  1817. expect(guidance).toBeGreaterThan(close);
  1818. expect(text).toContain("which findings were confirmed by a deterministic check or an independent subagent");
  1819. expect(text).toContain("Do not restate the phase graph or the script.");
  1820. expect(text).not.toContain("Present what it salvaged first");
  1821. });
  1822. it("failed / cancelled 的通知带抢救优先的指引", async () => {
  1823. const failed = await notificationWithReports("dwf-guidance-failed", {
  1824. status: "failed",
  1825. error: "script threw TypeError",
  1826. reports: ["finding before the crash"],
  1827. });
  1828. expect(failed.indexOf("Present what it salvaged first")).toBeGreaterThan(
  1829. failed.indexOf("</task-notification>"),
  1830. );
  1831. expect(failed).toContain("AmendWorkflow");
  1832. expect(failed).not.toContain("Present its outcome to the user as a deliverable");
  1833. const cancelled = await notificationWithReports("dwf-guidance-cancelled", {
  1834. status: "cancelled",
  1835. reports: ["finding before the cancel"],
  1836. });
  1837. expect(cancelled).toContain("Present what it salvaged first");
  1838. });
  1839. it("零条 report 时整节缺席,不发一节空的 <reports>", async () => {
  1840. const noKey = await notificationWithReports("dwf-reports-absent", {
  1841. status: "completed",
  1842. output: "done",
  1843. });
  1844. expect(noKey).not.toContain("<reports");
  1845. const emptyList = await notificationWithReports("dwf-reports-empty", {
  1846. status: "completed",
  1847. output: "done",
  1848. reports: [],
  1849. });
  1850. expect(emptyList).not.toContain("<reports");
  1851. });
  1852. /**
  1853. * 截断与计数**两者都重要**:计数才是让主 agent 知道「预览是局部的、全量可经 run id 取回」
  1854. * 的那个信号。只给预览会让模型以为它看到了全部。
  1855. */
  1856. it("预览按预算截断,但 count 是真实总数且 shown 说明预览有多少条", async () => {
  1857. const reports = Array.from({ length: 300 }, (_, index) => `finding ${index + 1} `.repeat(20));
  1858. const text = await notificationWithReports("dwf-reports-truncated", {
  1859. status: "completed",
  1860. reports,
  1861. });
  1862. expect(text).toContain('count="300"');
  1863. const shown = /shown="(\d+)"/u.exec(text);
  1864. expect(shown).not.toBeNull();
  1865. const shownCount = Number(shown![1]);
  1866. expect(shownCount).toBeGreaterThan(0);
  1867. expect(shownCount).toBeLessThan(300);
  1868. // 预览从第一条开始给(最早的发现最可能是别的条目的前提)。
  1869. expect(text).toContain("[1] finding 1");
  1870. });
  1871. // 快照只带前 256 条 item,真实总数在 `reportCount`(docs/execution-engine.md「Reading the
  1872. // journal」):count 必须说 run 的总数,而不是快照里的条数——否则一个报了 65,536 条的 run
  1873. // 会在通知里自称只报了 256 条,模型就不会去取剩下的。
  1874. it("count 读快照的 reportCount:快照截在 256 条时仍报真实总数", async () => {
  1875. const reports = Array.from({ length: 256 }, (_, index) => `f${index + 1}`);
  1876. const text = await notificationWithReports("dwf-reports-count-from-snapshot", {
  1877. status: "completed",
  1878. reports,
  1879. reportCount: 65_536,
  1880. });
  1881. expect(text).toContain('count="65536"');
  1882. const shown = /shown="(\d+)"/u.exec(text);
  1883. expect(Number(shown?.[1])).toBeLessThanOrEqual(256);
  1884. expect(text).toContain("[1] f1");
  1885. });
  1886. it("没有 reportCount 的老快照退回条目数", async () => {
  1887. const text = await notificationWithReports("dwf-reports-count-legacy", {
  1888. status: "completed",
  1889. reports: ["a", "b", "c"],
  1890. });
  1891. expect(text).toContain('<reports count="3">');
  1892. });
  1893. // ── run 的脚本文件(docs/dynamic-workflow/launch.md「Script files」)──
  1894. //
  1895. // 端口在快照上给绝对路径(run 身份的一部分),追踪器交给指引的是**工作区相对**写法:
  1896. // 主代理接下来要 Edit 这个文件,而那是它在别处读写文件时用的那一种路径。
  1897. it("errored 的指引带上快照里的脚本文件,写成工作区相对路径", async () => {
  1898. const text = await notificationWithReports("dwf-script-path-errored", {
  1899. status: "failed",
  1900. runStatus: "errored",
  1901. error: "script threw TypeError",
  1902. scriptPath: "/tmp/.zcode/workflow-drafts/audit.dwf.ts",
  1903. });
  1904. expect(text).toContain(
  1905. 'The run\'s script is at .zcode/workflow-drafts/audit.dwf.ts. Edit that file in place, then call AmendWorkflow (run_id="dwfrun-1", path=".zcode/workflow-drafts/audit.dwf.ts")',
  1906. );
  1907. expect(text).not.toContain("Fix the script and submit it with AmendWorkflow");
  1908. // 路径只进指引,不进 XML 块:用户面一概不显示它(spec 的「What the user sees」)。
  1909. expect(text.indexOf(".zcode/workflow-drafts")).toBeGreaterThan(
  1910. text.indexOf("</task-notification>"),
  1911. );
  1912. });
  1913. it("工作目录之外的脚本文件原样给绝对路径", async () => {
  1914. const text = await notificationWithReports("dwf-script-path-outside", {
  1915. status: "failed",
  1916. runStatus: "errored",
  1917. error: "script threw TypeError",
  1918. scriptPath: "/elsewhere/shared/audit.dwf.ts",
  1919. });
  1920. expect(text).toContain("The run's script is at /elsewhere/shared/audit.dwf.ts.");
  1921. });
  1922. it("stopped(model) 的指引在快照有文件时多一句「编辑它、传 path」", async () => {
  1923. const text = await notificationWithReports("dwf-script-path-stopped", {
  1924. status: "cancelled",
  1925. runStatus: "stopped",
  1926. stopReason: "model",
  1927. scriptPath: "/tmp/.zcode/workflow-drafts/audit.dwf.ts",
  1928. });
  1929. expect(text).toContain(
  1930. "Its script is at .zcode/workflow-drafts/audit.dwf.ts: edit that file and pass `path`.",
  1931. );
  1932. });
  1933. it("快照没有脚本文件时指引逐字节退回旧话(老端口 / 草稿写不下去的项目)", async () => {
  1934. const text = await notificationWithReports("dwf-script-path-absent", {
  1935. status: "failed",
  1936. runStatus: "errored",
  1937. error: "script threw TypeError",
  1938. });
  1939. expect(text).toContain(
  1940. 'Fix the script and submit it with AmendWorkflow (run_id="dwfrun-1") so finished work is reused.',
  1941. );
  1942. expect(text).not.toContain("Edit that file in place");
  1943. });
  1944. // ── 用户面产物(docs/dynamic-workflow/authoring.md「How the user sees them」)──
  1945. //
  1946. // ⚠ 术语:本 describe 里的 artifact 有两个义。`<result>` 那一族是脚本的**顶层返回值**
  1947. // (引擎内部的 `RunSettlement.artifact`),`<artifacts>` 这一节是脚本经 `artifact.*`
  1948. // **发布给用户看的产出**。两者在同一条通知里并列出现,措辞必须可区分。
  1949. it("completed 的通知带 <artifacts>,排在 <reports> 之后,一行一件", async () => {
  1950. const text = await notificationWithReports("dwf-artifacts-completed", {
  1951. status: "completed",
  1952. output: "final answer",
  1953. reports: ["a finding"],
  1954. artifacts: [
  1955. {
  1956. id: "audit",
  1957. kind: "file",
  1958. title: "审计报告",
  1959. version: 2,
  1960. contentType: "application/pdf",
  1961. itemCount: 0,
  1962. versions: [{ version: 1, publishedAt: 1, bytes: 10 }, { version: 2, publishedAt: 2, bytes: 4096 }],
  1963. },
  1964. {
  1965. id: "perf",
  1966. kind: "chart",
  1967. version: 1,
  1968. itemCount: 12,
  1969. versions: [{ version: 1, publishedAt: 3 }],
  1970. },
  1971. ],
  1972. });
  1973. expect(text).toContain('<artifacts count="2">');
  1974. // 内容产物:contentType + 最新版的字节数。
  1975. expect(text).toContain("- audit (file, v2, application/pdf, 4096 bytes): 审计报告");
  1976. // 预置看板:没有字节,数据量是标签 report 的条数;无 title 时不带冒号。
  1977. expect(text).toContain("- perf (chart, v1, 12 items)");
  1978. expect(text).not.toContain("- perf (chart, v1, 12 items):");
  1979. // 顺序:<reports> 在前、<artifacts> 在后(120k 总截断先斩后者)。
  1980. expect(text.indexOf("<reports")).toBeGreaterThan(-1);
  1981. expect(text.indexOf("<artifacts")).toBeGreaterThan(text.indexOf("</reports>"));
  1982. // 呈现指引追加句只在产物在场时出现。
  1983. expect(text).toContain("already in front of the user as cards");
  1984. });
  1985. it("failed 与 cancelled 的通知一样带 <artifacts>,并给一句更短的指引", async () => {
  1986. const artifacts = [
  1987. { id: "notes", kind: "markdown", version: 1, contentType: "text/markdown", itemCount: 0, versions: [{ version: 1, publishedAt: 1, bytes: 128 }] },
  1988. ];
  1989. const failed = await notificationWithReports("dwf-artifacts-failed", {
  1990. status: "failed",
  1991. error: "ask #12 threw",
  1992. artifacts,
  1993. });
  1994. expect(failed).toContain('<artifacts count="1">');
  1995. expect(failed).toContain("- notes (markdown, v1, text/markdown, 128 bytes)");
  1996. expect(failed).toContain("Artifacts listed above are already in front of the user.");
  1997. expect(failed).not.toContain("already in front of the user as cards");
  1998. const cancelled = await notificationWithReports("dwf-artifacts-cancelled", {
  1999. status: "cancelled",
  2000. artifacts,
  2001. });
  2002. expect(cancelled).toContain('<artifacts count="1">');
  2003. });
  2004. it("零件时整节缺席,指引也不长出那一句(没有清单可引用)", async () => {
  2005. const noKey = await notificationWithReports("dwf-artifacts-absent", { status: "completed" });
  2006. expect(noKey).not.toContain("<artifacts");
  2007. expect(noKey).not.toContain("already in front of the user");
  2008. const emptyList = await notificationWithReports("dwf-artifacts-empty", {
  2009. status: "completed",
  2010. artifacts: [],
  2011. });
  2012. expect(emptyList).not.toContain("<artifacts");
  2013. });
  2014. it("超过 8 件时 shown 在场且 count 仍是真实总数", async () => {
  2015. const artifacts = Array.from({ length: 11 }, (_, index) => ({
  2016. id: `a${index + 1}`,
  2017. kind: "markdown",
  2018. version: 1,
  2019. itemCount: 0,
  2020. versions: [{ version: 1, publishedAt: 1, bytes: 8 }],
  2021. }));
  2022. const text = await notificationWithReports("dwf-artifacts-truncated", {
  2023. status: "completed",
  2024. artifacts,
  2025. });
  2026. expect(text).toContain('<artifacts count="11" shown="8">');
  2027. expect(text).toContain("- a1 (markdown, v1, 8 bytes)");
  2028. expect(text).toContain("- a8 (markdown, v1, 8 bytes)");
  2029. expect(text).not.toContain("- a9 (");
  2030. });
  2031. it("形状不合的条目被跳过而不是让整节消失", async () => {
  2032. const text = await notificationWithReports("dwf-artifacts-malformed", {
  2033. status: "completed",
  2034. artifacts: [
  2035. null,
  2036. "not an object",
  2037. { id: "ok", kind: "file", version: 1, itemCount: 0, versions: [] },
  2038. // version 缺席 ⇒ 无法定位版本,整条丢。
  2039. { id: "broken", kind: "file", itemCount: 0, versions: [] },
  2040. ],
  2041. });
  2042. expect(text).toContain('<artifacts count="1">');
  2043. expect(text).toContain("- ok (file, v1)");
  2044. expect(text).not.toContain("broken");
  2045. });
  2046. // legacy `Workflow` 的通知逐字节不变:它的 `output.response` 真实存在,lost 路径上的
  2047. // launchOutput 回退是它自己的契约。dwf 的修订不得溢出到这条路径上。
  2048. it("legacy Workflow 的通知仍取 output.response 并保留 launchOutput 回退", async () => {
  2049. async function legacyNotification(getTask?: () => Promise<unknown>): Promise<string> {
  2050. const sessionId = createSessionId("legacy-workflow-result");
  2051. const turnId = createTurnId("legacy-workflow-result");
  2052. const events: { payload: Record<string, unknown>; type: string }[] = [];
  2053. const notifications: { text: string }[] = [];
  2054. const tracker = new BackgroundTaskTracker({
  2055. emitEvent: async (event) => {
  2056. events.push({ payload: event.payload as Record<string, unknown>, type: event.type });
  2057. },
  2058. enqueueBackgroundTaskNotification: (notification) => {
  2059. notifications.push(notification);
  2060. return undefined;
  2061. },
  2062. ...(getTask ? { workflowPort: { getTask } } : {}),
  2063. getWorkingDirectory: () => "/tmp",
  2064. getWorkspaceRoot: () => "/tmp",
  2065. readFileState: new Map(),
  2066. runtimeScope: "main",
  2067. sessionId,
  2068. } as never);
  2069. await tracker.trackBackgroundTask(
  2070. { id: "tool_workflow_result", input: { scriptPath: "w.ts" }, name: "Workflow" } as never,
  2071. { backgroundTaskId: "wfrun-1", response: "legacy launch prose", status: "backgrounded" },
  2072. { traceId: "trace_legacy_result", spanId: "span_legacy_result", sessionId, turnId },
  2073. turnId,
  2074. );
  2075. await waitForCondition(() =>
  2076. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  2077. );
  2078. return notifications[0]!.text;
  2079. }
  2080. const withResponse = await legacyNotification(async () => ({
  2081. status: "completed",
  2082. runId: "wfrun-1",
  2083. output: { response: "legacy workflow answer" },
  2084. // 即便端口硬塞一个 reports 字段,legacy 通知也不长出 <reports> 这一节:渐进产物是
  2085. // dwf 独有的概念,两套 workflow 机制不共用通知形状。
  2086. reports: ["should not surface"],
  2087. // 用户面产物同理(docs/dynamic-workflow/authoring.md:legacy `Workflow` 通知逐字节不变)。
  2088. artifacts: [
  2089. {
  2090. id: "should-not-surface",
  2091. kind: "file",
  2092. version: 1,
  2093. itemCount: 0,
  2094. versions: [{ version: 1, publishedAt: 1, bytes: 4 }],
  2095. },
  2096. ],
  2097. }));
  2098. expect(withResponse).toContain("<result>legacy workflow answer</result>");
  2099. expect(withResponse).not.toContain("<reports");
  2100. expect(withResponse).not.toContain("should not surface");
  2101. expect(withResponse).not.toContain("<artifacts");
  2102. expect(withResponse).not.toContain("should-not-surface");
  2103. // 呈现指引整块也不属于 legacy:它的通知没有这一段。
  2104. expect(withResponse).not.toContain("already in front of the user");
  2105. // 端口缺席(lost)时回退到 launch output 的 response——legacy 的既有契约,逐字保留。
  2106. const fallback = await legacyNotification();
  2107. expect(fallback).toContain("<result>legacy launch prose</result>");
  2108. });
  2109. // 端口缺席的 CreateWorkflow:没有快照源就按既有语义标 lost,而不是永远挂着轮询。
  2110. it("端口缺席时 CreateWorkflow 立即标记 lost", async () => {
  2111. const sessionId = createSessionId("dwf-no-port");
  2112. const turnId = createTurnId("dwf-no-port");
  2113. const events: { payload: Record<string, unknown>; type: string }[] = [];
  2114. const tracker = new BackgroundTaskTracker({
  2115. emitEvent: async (event) => {
  2116. events.push({ payload: event.payload as Record<string, unknown>, type: event.type });
  2117. },
  2118. getWorkingDirectory: () => "/tmp",
  2119. getWorkspaceRoot: () => "/tmp",
  2120. readFileState: new Map(),
  2121. runtimeScope: "main",
  2122. sessionId,
  2123. } as never);
  2124. await tracker.trackBackgroundTask(
  2125. { id: "tool_cw_lost", input: { script: "" }, name: "CreateWorkflow" } as never,
  2126. { backgroundTaskId: "dwfrun-lost", status: "backgrounded" },
  2127. { traceId: "trace_dwf_lost", spanId: "span_dwf_lost", sessionId, turnId },
  2128. turnId,
  2129. );
  2130. const completed = events.find(
  2131. (event) => event.type === SessionEventType.BackgroundTaskCompleted,
  2132. );
  2133. expect(completed?.payload).toMatchObject({ status: "lost", taskId: "dwfrun-lost" });
  2134. });
  2135. // 回归护栏:legacy Workflow 的四处语义不能被泛化改写——它没有快照提供者以外的取消能力,
  2136. // started payload 的 cancellable 必须仍为 false。
  2137. it("legacy Workflow 的 cancellable 仍为 false", async () => {
  2138. const sessionId = createSessionId("legacy-workflow-cancellable");
  2139. const turnId = createTurnId("legacy-workflow-cancellable");
  2140. const events: { payload: Record<string, unknown>; type: string }[] = [];
  2141. const tracker = new BackgroundTaskTracker({
  2142. emitEvent: async (event) => {
  2143. events.push({ payload: event.payload as Record<string, unknown>, type: event.type });
  2144. },
  2145. workflowPort: {
  2146. async getTask() {
  2147. return { status: "running", runId: "wfrun-1" };
  2148. },
  2149. },
  2150. getWorkingDirectory: () => "/tmp",
  2151. getWorkspaceRoot: () => "/tmp",
  2152. readFileState: new Map(),
  2153. runtimeScope: "main",
  2154. sessionId,
  2155. } as never);
  2156. await tracker.trackBackgroundTask(
  2157. { id: "tool_workflow_1", input: { scriptPath: "w.ts" }, name: "Workflow" } as never,
  2158. { backgroundTaskId: "wfrun-1", status: "backgrounded" },
  2159. { traceId: "trace_legacy_wf", spanId: "span_legacy_wf", sessionId, turnId },
  2160. turnId,
  2161. );
  2162. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  2163. expect(started?.payload).toMatchObject({ cancellable: false, taskId: "wfrun-1" });
  2164. });
  2165. /**
  2166. * 回归护栏:展示名的修订只对 CreateWorkflow 生效,其他工具的 `description` 逐字节不变。
  2167. * Bash 的既有优先级是 `input.description` 先于 `snapshot.description`,两者都缺则整字段缺席
  2168. * (面板据此退到命令行文本)——三种情形一次钉住。
  2169. */
  2170. it("Bash 的展示名仍是 input.description 优先于快照,缺席时为 undefined", async () => {
  2171. async function trackBash(input: Record<string, unknown>): Promise<
  2172. { payload: Record<string, unknown>; type: string }[]
  2173. > {
  2174. const sessionId = createSessionId("bash-description-pin");
  2175. const turnId = createTurnId("bash-description-pin");
  2176. const events: { payload: Record<string, unknown>; type: string }[] = [];
  2177. const tracker = new BackgroundTaskTracker({
  2178. emitEvent: async (event) => {
  2179. events.push({ payload: event.payload as Record<string, unknown>, type: event.type });
  2180. },
  2181. executionPort: {
  2182. async run() {
  2183. throw new Error("run should not be called");
  2184. },
  2185. async waitForBackgroundTask() {
  2186. return {
  2187. taskId: "bash_description",
  2188. status: "completed",
  2189. description: "snapshot description",
  2190. startedAt: new Date(0),
  2191. completedAt: new Date(1),
  2192. stdoutTail: "done",
  2193. };
  2194. },
  2195. },
  2196. getWorkingDirectory: () => "/tmp",
  2197. getWorkspaceRoot: () => "/tmp",
  2198. readFileState: new Map(),
  2199. runtimeScope: "main",
  2200. sessionId,
  2201. } as never);
  2202. await tracker.trackBackgroundTask(
  2203. { id: "tool_bash_description", input, name: "Bash" } as never,
  2204. { backgroundTaskId: "bash_description", status: "backgrounded" },
  2205. { traceId: "trace_bash_description", spanId: "span_bash_description", sessionId, turnId },
  2206. turnId,
  2207. );
  2208. await waitForCondition(() =>
  2209. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  2210. );
  2211. return events;
  2212. }
  2213. const withDescription = await trackBash({ command: "npm run dev", description: "dev server" });
  2214. // started 没有快照,只能来自 input;completed 有快照,input 仍然优先。
  2215. expect(
  2216. withDescription.find((event) => event.type === SessionEventType.BackgroundTaskStarted)
  2217. ?.payload.description,
  2218. ).toBe("dev server");
  2219. expect(
  2220. withDescription.find((event) => event.type === SessionEventType.BackgroundTaskCompleted)
  2221. ?.payload.description,
  2222. ).toBe("dev server");
  2223. const withoutDescription = await trackBash({ command: "npm run dev" });
  2224. expect(
  2225. withoutDescription.find((event) => event.type === SessionEventType.BackgroundTaskStarted)
  2226. ?.payload.description,
  2227. ).toBeUndefined();
  2228. expect(
  2229. withoutDescription.find((event) => event.type === SessionEventType.BackgroundTaskCompleted)
  2230. ?.payload.description,
  2231. ).toBe("snapshot description");
  2232. });
  2233. });
  2234. /**
  2235. * 取消的唯一路径:`cancelBackgroundWork {workId}` → `app.cancelBackgroundTask` →
  2236. * `runtime.cancelBackgroundTask` → `runtime.stopBackgroundTask` → 端口的 `cancel(runId)`。
  2237. *
  2238. * 这条链按 RuntimeTaskType 分派(runtime/methods/background.ts),与追踪器的按工具名查表
  2239. * 是两处独立的分派。spec 只点了追踪器那五处;这一组测的是链路后半段——不接它,
  2240. * `cancellable: true` 只会给出一个点下去毫无反应的按钮。
  2241. */
  2242. describe("dynamic workflow run cancellation", () => {
  2243. it("cancelBackgroundTask 经运行时分派打到端口的 cancel", async () => {
  2244. const sessionId = createSessionId("dwf-cancel-dispatch");
  2245. const eventStore = createTestSessionEventStore();
  2246. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  2247. const cancelled: string[] = [];
  2248. const startedAt = new Date(0);
  2249. runtimeTaskRegistry.register({
  2250. agentId: "dwfrun-cancel",
  2251. agentType: "local_dynamic_workflow",
  2252. description: "workflow run",
  2253. isBackgrounded: true,
  2254. startedAt,
  2255. status: "running",
  2256. taskId: "dwfrun-cancel",
  2257. taskType: "local_dynamic_workflow",
  2258. type: "local_dynamic_workflow",
  2259. } as never);
  2260. await eventStore.append(
  2261. createSessionEvent(SessionEventType.BackgroundTaskStarted, sessionId, {
  2262. cancellable: true,
  2263. startedAt,
  2264. status: "running",
  2265. taskId: "dwfrun-cancel",
  2266. terminalId: "dwfrun-cancel",
  2267. toolCallId: "tool_create_workflow",
  2268. toolName: "CreateWorkflow",
  2269. }),
  2270. );
  2271. const runtime = createTestAgentRuntime(
  2272. sessionId,
  2273. { mode: "build" },
  2274. {
  2275. dynamicWorkflowRunPort: {
  2276. async submit() {
  2277. throw new Error("submit should not be called");
  2278. },
  2279. async getTask(taskId: string) {
  2280. return { taskId, status: cancelled.includes(taskId) ? "cancelled" : "running" };
  2281. },
  2282. async waitForTask(taskId: string) {
  2283. return { taskId, status: "cancelled" };
  2284. },
  2285. async cancel(runId: string) {
  2286. cancelled.push(runId);
  2287. return true;
  2288. },
  2289. async listEvents() {
  2290. return [];
  2291. },
  2292. },
  2293. eventStore,
  2294. runtimeTaskRegistry,
  2295. } as never,
  2296. );
  2297. const result = await runtime.cancelBackgroundTask("dwfrun-cancel");
  2298. // 端口收到了 runId(workId ≡ taskId ≡ runId,无身份映射表)。
  2299. expect(cancelled).toEqual(["dwfrun-cancel"]);
  2300. expect(result).toMatchObject({ cancelled: true, status: "cancelled", taskId: "dwfrun-cancel" });
  2301. });
  2302. it("端口对未知 run 返回 false 时归一成 not_found 而不是静默成功", async () => {
  2303. const sessionId = createSessionId("dwf-cancel-unknown");
  2304. const eventStore = createTestSessionEventStore();
  2305. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  2306. runtimeTaskRegistry.register({
  2307. agentId: "dwfrun-gone",
  2308. agentType: "local_dynamic_workflow",
  2309. description: "workflow run",
  2310. isBackgrounded: true,
  2311. startedAt: new Date(0),
  2312. status: "running",
  2313. taskId: "dwfrun-gone",
  2314. taskType: "local_dynamic_workflow",
  2315. type: "local_dynamic_workflow",
  2316. } as never);
  2317. const runtime = createTestAgentRuntime(
  2318. sessionId,
  2319. { mode: "build" },
  2320. {
  2321. dynamicWorkflowRunPort: {
  2322. async submit() {
  2323. throw new Error("submit should not be called");
  2324. },
  2325. async getTask() {
  2326. return undefined;
  2327. },
  2328. async waitForTask() {
  2329. return undefined;
  2330. },
  2331. async cancel() {
  2332. return false;
  2333. },
  2334. async listEvents() {
  2335. return [];
  2336. },
  2337. },
  2338. eventStore,
  2339. runtimeTaskRegistry,
  2340. } as never,
  2341. );
  2342. const result = await runtime.cancelBackgroundTask("dwfrun-gone");
  2343. expect(result.cancelled).toBe(false);
  2344. expect(result.reason).toBe("background_task_not_found");
  2345. });
  2346. // 端口整个缺席(未接线的宿主):得结构化的"能力不支持",不能假装取消成功。
  2347. it("端口缺席时报能力不支持", async () => {
  2348. const sessionId = createSessionId("dwf-cancel-no-port");
  2349. const eventStore = createTestSessionEventStore();
  2350. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  2351. runtimeTaskRegistry.register({
  2352. agentId: "dwfrun-noport",
  2353. agentType: "local_dynamic_workflow",
  2354. description: "workflow run",
  2355. isBackgrounded: true,
  2356. startedAt: new Date(0),
  2357. status: "running",
  2358. taskId: "dwfrun-noport",
  2359. taskType: "local_dynamic_workflow",
  2360. type: "local_dynamic_workflow",
  2361. } as never);
  2362. const runtime = createTestAgentRuntime(
  2363. sessionId,
  2364. { mode: "build" },
  2365. { eventStore, runtimeTaskRegistry } as never,
  2366. );
  2367. const result = await runtime.cancelBackgroundTask("dwfrun-noport");
  2368. expect(result.cancelled).toBe(false);
  2369. expect(result.reason).toBe("background_task_cancel_not_supported");
  2370. });
  2371. });
  2372. /**
  2373. * FORK-1 的两个后果,各自钉一条测试。
  2374. *
  2375. * 1. **回收护栏**:runtime task registry 是 `hasRunningBackgroundRuntimeTask` 的数据源,
  2376. * 而那个谓词决定常驻 session 会不会被回收。CreateWorkflow 此前在
  2377. * `runtimeTaskTypeForToolCall` 里没有映射,registerRuntimeBackgroundTask 因此整个早退——
  2378. * 一个在飞的 run 会让 session 看起来空闲,被回收掉之后完成通知无处投递。这比"取消按钮
  2379. * 点不动"更难查,所以单独成测。
  2380. * 2. **两个入口一个实现**:GUI 的 cancelBackgroundWork 与模型的 TaskStop 都落到
  2381. * runtime.stopBackgroundTask(后者经 backgroundTaskControlPort,runtime-tools.ts:144
  2382. * 绑定的正是同一个方法),只在 strict 上不同。
  2383. */
  2384. describe("dynamic workflow background task registration", () => {
  2385. async function trackWithRegistry(runtimeTaskRegistry: InMemoryRuntimeTaskRegistry) {
  2386. const sessionId = createSessionId("dwf-registry");
  2387. const turnId = createTurnId("dwf-registry");
  2388. const tracker = new BackgroundTaskTracker({
  2389. emitEvent: async () => {},
  2390. dynamicWorkflowRunPort: {
  2391. async submit() {
  2392. throw new Error("submit should not be called");
  2393. },
  2394. async getTask(taskId: string) {
  2395. return { taskId, runId: taskId, startedAt: new Date(0), status: "running" };
  2396. },
  2397. // 永不结算:run 在测试期间保持在飞。
  2398. waitForTask: () => new Promise(() => {}),
  2399. async cancel() {
  2400. return true;
  2401. },
  2402. async listEvents() {
  2403. return [];
  2404. },
  2405. },
  2406. getWorkingDirectory: () => "/tmp",
  2407. getWorkspaceRoot: () => "/tmp",
  2408. readFileState: new Map(),
  2409. runtimeScope: "main",
  2410. runtimeTaskRegistry,
  2411. sessionId,
  2412. } as never);
  2413. await tracker.trackBackgroundTask(
  2414. { id: "tool_cw_registry", input: { script: "" }, name: "CreateWorkflow" } as never,
  2415. { backgroundTaskId: "dwfrun-live", status: "backgrounded" },
  2416. { traceId: "trace_dwf_registry", spanId: "span_dwf_registry", sessionId, turnId },
  2417. turnId,
  2418. );
  2419. }
  2420. it("在飞的 run 登记进 registry,回收护栏因此为真", async () => {
  2421. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  2422. // 前提:没有任何在飞后台任务时护栏为假。
  2423. expect(hasRunningBackgroundRuntimeTask(runtimeTaskRegistry)).toBe(false);
  2424. await trackWithRegistry(runtimeTaskRegistry);
  2425. // 登记发生了,且类型是 dwf 专属的那个(不是 legacy local_workflow,也不是 undefined)。
  2426. expect(runtimeTaskRegistry.get("dwfrun-live")).toMatchObject({
  2427. isBackgrounded: true,
  2428. status: "running",
  2429. taskId: "dwfrun-live",
  2430. type: "local_dynamic_workflow",
  2431. });
  2432. // 护栏为真 → 有在飞 run 的 session 不会被当作空闲回收。
  2433. expect(hasRunningBackgroundRuntimeTask(runtimeTaskRegistry)).toBe(true);
  2434. });
  2435. it("模型侧 TaskStop 与 GUI 侧取消共用 runtime.stopBackgroundTask,同样打到 port.cancel", async () => {
  2436. const sessionId = createSessionId("dwf-taskstop");
  2437. const eventStore = createTestSessionEventStore();
  2438. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  2439. const cancelled: string[] = [];
  2440. runtimeTaskRegistry.register({
  2441. agentId: "dwfrun-taskstop",
  2442. agentType: "local_dynamic_workflow",
  2443. description: "workflow run",
  2444. isBackgrounded: true,
  2445. startedAt: new Date(0),
  2446. status: "running",
  2447. taskId: "dwfrun-taskstop",
  2448. taskType: "local_dynamic_workflow",
  2449. type: "local_dynamic_workflow",
  2450. } as never);
  2451. const runtime = createTestAgentRuntime(
  2452. sessionId,
  2453. { mode: "build" },
  2454. {
  2455. dynamicWorkflowRunPort: {
  2456. async submit() {
  2457. throw new Error("submit should not be called");
  2458. },
  2459. async getTask(taskId: string) {
  2460. return { taskId, runId: taskId, startedAt: new Date(0), status: "running" };
  2461. },
  2462. async waitForTask(taskId: string) {
  2463. return { taskId, runId: taskId, startedAt: new Date(0), status: "cancelled" };
  2464. },
  2465. async cancel(runId: string) {
  2466. cancelled.push(runId);
  2467. return true;
  2468. },
  2469. async listEvents() {
  2470. return [];
  2471. },
  2472. },
  2473. eventStore,
  2474. runtimeTaskRegistry,
  2475. } as never,
  2476. );
  2477. // 这就是 runtime-tools.ts:144 交给工具执行上下文的那个绑定。
  2478. const backgroundTaskControlPort = {
  2479. stopBackgroundTask: runtime.stopBackgroundTask.bind(runtime),
  2480. };
  2481. const output = (await taskStopToolEntry.handler(
  2482. { task_id: "dwfrun-taskstop" },
  2483. { backgroundTaskControlPort, toolCallId: "tool_task_stop" } as never,
  2484. )) as { task_id?: string; task_type?: string };
  2485. // 关键断言:模型侧入口也把 runId 直送到了端口的 cancel。
  2486. expect(cancelled).toEqual(["dwfrun-taskstop"]);
  2487. // 并且工具向模型报告的是 dwf 专属类型,不是被归成 bash/legacy workflow。
  2488. expect(output.task_id).toBe("dwfrun-taskstop");
  2489. expect(output.task_type).toBe("local_dynamic_workflow");
  2490. });
  2491. });
  2492. // 停止分支记「谁停的」(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Cancel and resume」 2026-09-09):只在 dwf 分支、
  2493. // 只在调用方给了 initiator 时写;写在 port.cancel 之前。
  2494. describe("dwf 停止分支记录 stopInitiator", () => {
  2495. function dwfRuntime(
  2496. name: string,
  2497. cancelled: string[],
  2498. ): {
  2499. runtime: AgentRuntime;
  2500. registry: InMemoryRuntimeTaskRegistry;
  2501. } {
  2502. const registry = new InMemoryRuntimeTaskRegistry();
  2503. registry.register({
  2504. agentId: "dwfrun-stop",
  2505. agentType: "local_dynamic_workflow",
  2506. description: "Dynamic workflow run",
  2507. isBackgrounded: true,
  2508. startedAt: new Date(0),
  2509. status: "running",
  2510. taskId: "dwfrun-stop",
  2511. taskType: "local_dynamic_workflow",
  2512. type: "local_dynamic_workflow",
  2513. } as never);
  2514. const runtime = createTestAgentRuntime(
  2515. createSessionId(name),
  2516. { mode: "build" },
  2517. {
  2518. eventStore: createTestSessionEventStore(),
  2519. runtimeTaskRegistry: registry,
  2520. dynamicWorkflowRunPort: {
  2521. async submit() {
  2522. throw new Error("submit should not be called");
  2523. },
  2524. async getTask() {
  2525. return {
  2526. runId: "dwfrun-stop",
  2527. taskId: "dwfrun-stop",
  2528. startedAt: new Date(),
  2529. status: "running",
  2530. };
  2531. },
  2532. async waitForTask() {
  2533. return new Promise(() => undefined);
  2534. },
  2535. async cancel(runId: string) {
  2536. // 断言顺序:abort 时 initiator 已经在条目上。
  2537. cancelled.push(`${runId}:${registry.get(runId)?.stopInitiator ?? "none"}`);
  2538. return true;
  2539. },
  2540. async listEvents() {
  2541. return [];
  2542. },
  2543. } as never,
  2544. },
  2545. );
  2546. return { runtime, registry };
  2547. }
  2548. it("stopBackgroundTask({initiator}) 在 abort 之前把 initiator 写进条目", async () => {
  2549. const cancelled: string[] = [];
  2550. const { runtime, registry } = dwfRuntime("dwf-stop-model", cancelled);
  2551. await expect(
  2552. (runtime as any).stopBackgroundTask("dwfrun-stop", { initiator: "model", strict: true }),
  2553. ).resolves.toMatchObject({ ok: true, status: "cancelled", type: "local_dynamic_workflow" });
  2554. expect(cancelled).toEqual(["dwfrun-stop:model"]);
  2555. expect(registry.get("dwfrun-stop")?.stopInitiator).toBe("model");
  2556. });
  2557. it("cancelBackgroundTask(GUI 入口)写 user;不带 initiator 的停止不写", async () => {
  2558. const viaGui: string[] = [];
  2559. const gui = dwfRuntime("dwf-stop-user", viaGui);
  2560. await gui.runtime.cancelBackgroundTask("dwfrun-stop");
  2561. expect(viaGui).toEqual(["dwfrun-stop:user"]);
  2562. expect(gui.registry.get("dwfrun-stop")?.stopInitiator).toBe("user");
  2563. const plain: string[] = [];
  2564. const system = dwfRuntime("dwf-stop-system", plain);
  2565. await (system.runtime as any).stopBackgroundTask("dwfrun-stop", {});
  2566. expect(plain).toEqual(["dwfrun-stop:none"]);
  2567. expect(system.registry.get("dwfrun-stop")?.stopInitiator).toBeUndefined();
  2568. });
  2569. });