background-task-control.test.ts 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905
  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. // 这个用例停的是前台 Agent,关闭「Agent 总在后台」开关(07-subagent.md「ZCode 当前实现」)。
  1141. subagents: { alwaysBackground: false },
  1142. },
  1143. {
  1144. eventStore: createTestSessionEventStore(),
  1145. runtimeTaskRegistry: registry,
  1146. subagentPort: port,
  1147. modelFactory: createTestModelFactory({
  1148. async generateText() {
  1149. parentRequests++;
  1150. return parentRequests === 1
  1151. ? {
  1152. finishReason: "tool-calls",
  1153. text: "",
  1154. toolCalls: [
  1155. {
  1156. id: "call_parent_agent_stop",
  1157. name: "Agent",
  1158. input: {
  1159. description: "Stop child only",
  1160. prompt: "Wait for stop",
  1161. subagent_type: "general-purpose",
  1162. },
  1163. },
  1164. ],
  1165. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1166. }
  1167. : {
  1168. finishReason: "stop",
  1169. text: "Parent continued",
  1170. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1171. };
  1172. },
  1173. } as never),
  1174. },
  1175. );
  1176. try {
  1177. const turn = runtime.executeTurn("Stop this child, then continue");
  1178. await waitForCondition(() =>
  1179. events.some((event) => event.type === SessionEventType.SubagentSpawned),
  1180. );
  1181. const executionId = registry.get("agent_parent_continues")?.executionId;
  1182. expect(executionId).toBeTruthy();
  1183. await runtime.stopBackgroundTask("agent_parent_continues", {
  1184. expectedExecutionId: executionId,
  1185. initiator: "user",
  1186. strict: true,
  1187. });
  1188. const result = await turn;
  1189. expect(result).toMatchObject({ response: "Parent continued" });
  1190. expect(parentRequests).toBe(2);
  1191. expect(registry.get("agent_parent_continues")?.status).toBe("killed");
  1192. expect(
  1193. events.filter((event) => event.type === SessionEventType.SubagentStopped),
  1194. ).toHaveLength(1);
  1195. } finally {
  1196. await port.close?.();
  1197. await rm(outputRootDir, { force: true, recursive: true });
  1198. }
  1199. });
  1200. it("keeps the first terminal decision when background completion races with stop", async () => {
  1201. const sessionId = createSessionId("background-stop-completion-race");
  1202. const turnId = createTurnId("turn_background_stop_completion_race");
  1203. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-stop-completion-race-"));
  1204. const releaseCompletion = deferred<{
  1205. response: string;
  1206. traceId: string;
  1207. events: SessionEvent[];
  1208. }>();
  1209. const registry = new InMemoryRuntimeTaskRegistry();
  1210. const notifications: string[] = [];
  1211. const events: SessionEvent[] = [];
  1212. const port = createExploreSubagentPort({
  1213. createAgentId: () => "agent_completion_race",
  1214. emitParentEvent: async (event) => {
  1215. events.push(event);
  1216. },
  1217. enqueueParentTaskNotification: (notification) => {
  1218. notifications.push(notification.text);
  1219. },
  1220. outputRootDir,
  1221. runtimeTaskRegistry: registry,
  1222. async runExploreAgent(request) {
  1223. await request.onSessionReady?.();
  1224. return releaseCompletion.promise;
  1225. },
  1226. });
  1227. try {
  1228. await port.start?.({
  1229. agentType: "general-purpose",
  1230. description: "Stop completion race",
  1231. parentToolCallId: "tool_completion_race",
  1232. prompt: "Wait",
  1233. sessionId,
  1234. trace: {
  1235. traceId: "trace_completion_race",
  1236. spanId: "span_completion_race",
  1237. sessionId,
  1238. turnId,
  1239. },
  1240. turnId,
  1241. workingDirectory: outputRootDir,
  1242. workspaceRoot: outputRootDir,
  1243. });
  1244. const executionId = registry.get("agent_completion_race")?.executionId;
  1245. await port.stopTask?.("agent_completion_race", { expectedExecutionId: executionId });
  1246. releaseCompletion.resolve({
  1247. response: "late success",
  1248. traceId: "trace_completion_race",
  1249. events: [],
  1250. });
  1251. await port.close?.();
  1252. expect(registry.get("agent_completion_race")?.status).toBe("killed");
  1253. expect(notifications).toHaveLength(1);
  1254. expect(
  1255. events.filter((event) => event.type === SessionEventType.SubagentStopped),
  1256. ).toHaveLength(1);
  1257. } finally {
  1258. releaseCompletion.resolve({
  1259. response: "late success",
  1260. traceId: "trace_completion_race",
  1261. events: [],
  1262. });
  1263. await port.close?.();
  1264. await rm(outputRootDir, { force: true, recursive: true });
  1265. }
  1266. });
  1267. it("does not overwrite a terminal runtime task when a late tracker snapshot arrives", () => {
  1268. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  1269. runtimeTaskRegistry.register({
  1270. agentId: "bash_race",
  1271. agentType: "local_bash",
  1272. description: "sleep 30",
  1273. isBackgrounded: true,
  1274. startedAt: new Date(0),
  1275. status: "killed",
  1276. taskId: "bash_race",
  1277. taskType: "local_bash",
  1278. type: "local_bash",
  1279. } as never);
  1280. updateRuntimeBackgroundTask(
  1281. { runtimeTaskRegistry } as never,
  1282. {
  1283. id: "tool_bash_race",
  1284. input: { command: "sleep 30" },
  1285. name: "Bash",
  1286. } as never,
  1287. "bash_race",
  1288. "completed",
  1289. {
  1290. taskId: "bash_race",
  1291. status: "completed",
  1292. startedAt: new Date(0),
  1293. completedAt: new Date(1),
  1294. stdoutTail: "done",
  1295. },
  1296. );
  1297. expect(runtimeTaskRegistry.get("bash_race")).toMatchObject({
  1298. status: "killed",
  1299. });
  1300. expect(runtimeTaskRegistry.get("bash_race")).not.toHaveProperty("stdoutTail");
  1301. });
  1302. /**
  1303. * TaskOutput 的投影只读得到 registry 条目(dwf 从不写 outputFile),所以产物必须在终态
  1304. * 更新时就落到条目上。以下几条钉住「存什么、什么时候存、绝不用 undefined 清掉已有值」。
  1305. */
  1306. describe("dwf run 产物落到 registry 条目上", () => {
  1307. const CREATE_WORKFLOW_CALL = {
  1308. id: "tool_dwf_result",
  1309. input: { script: "return 1;" },
  1310. name: "CreateWorkflow",
  1311. };
  1312. function registryWithDwfRun(): InMemoryRuntimeTaskRegistry {
  1313. const registry = new InMemoryRuntimeTaskRegistry();
  1314. registry.register({
  1315. agentId: "dwfrun-result",
  1316. agentType: "local_dynamic_workflow",
  1317. description: "Dynamic workflow run",
  1318. isBackgrounded: true,
  1319. startedAt: new Date(0),
  1320. status: "running",
  1321. taskId: "dwfrun-result",
  1322. taskType: "local_dynamic_workflow",
  1323. type: "local_dynamic_workflow",
  1324. } as never);
  1325. return registry;
  1326. }
  1327. function update(
  1328. registry: InMemoryRuntimeTaskRegistry,
  1329. status: string,
  1330. snapshot: Record<string, unknown>,
  1331. ): void {
  1332. updateRuntimeBackgroundTask(
  1333. { runtimeTaskRegistry: registry } as never,
  1334. CREATE_WORKFLOW_CALL as never,
  1335. "dwfrun-result",
  1336. status,
  1337. snapshot as never,
  1338. );
  1339. }
  1340. it("终态的字符串产物原样存为 resultText", () => {
  1341. const registry = registryWithDwfRun();
  1342. update(registry, "completed", {
  1343. taskId: "dwfrun-result",
  1344. status: "completed",
  1345. output: "the final answer",
  1346. });
  1347. expect(registry.get("dwfrun-result")?.resultText).toBe("the final answer");
  1348. });
  1349. it("终态的对象产物存为 pretty JSON", () => {
  1350. const registry = registryWithDwfRun();
  1351. update(registry, "completed", {
  1352. taskId: "dwfrun-result",
  1353. status: "completed",
  1354. output: { report: "done" },
  1355. });
  1356. expect(registry.get("dwfrun-result")?.resultText).toBe(
  1357. JSON.stringify({ report: "done" }, null, 2),
  1358. );
  1359. });
  1360. it("running 的中途快照不写 resultText", () => {
  1361. const registry = registryWithDwfRun();
  1362. update(registry, "running", {
  1363. taskId: "dwfrun-result",
  1364. status: "running",
  1365. output: "not settled yet",
  1366. });
  1367. expect(registry.get("dwfrun-result")?.resultText).toBeUndefined();
  1368. });
  1369. it("产物缺席的终态不写 resultText", () => {
  1370. const registry = registryWithDwfRun();
  1371. update(registry, "completed", { taskId: "dwfrun-result", status: "completed" });
  1372. expect(registry.get("dwfrun-result")?.resultText).toBeUndefined();
  1373. });
  1374. // undefined 绝不清掉已有值:一次产物缺席的更新不该把先前存下的产物抹掉。
  1375. it("已有的 resultText 不被产物缺席的更新清掉", () => {
  1376. const registry = registryWithDwfRun();
  1377. registry.update("dwfrun-result", (current) => ({
  1378. ...current,
  1379. resultText: "already captured",
  1380. }));
  1381. update(registry, "running", { taskId: "dwfrun-result", status: "running" });
  1382. expect(registry.get("dwfrun-result")?.resultText).toBe("already captured");
  1383. });
  1384. it("legacy Workflow 的终态不写 resultText(不改它的契约)", () => {
  1385. const registry = new InMemoryRuntimeTaskRegistry();
  1386. registry.register({
  1387. agentId: "wfrun-legacy",
  1388. agentType: "local_workflow",
  1389. description: "Workflow background task",
  1390. isBackgrounded: true,
  1391. startedAt: new Date(0),
  1392. status: "running",
  1393. taskId: "wfrun-legacy",
  1394. taskType: "local_workflow",
  1395. type: "local_workflow",
  1396. } as never);
  1397. updateRuntimeBackgroundTask(
  1398. { runtimeTaskRegistry: registry } as never,
  1399. { id: "tool_wf_legacy", input: { scriptPath: "w.ts" }, name: "Workflow" } as never,
  1400. "wfrun-legacy",
  1401. "completed",
  1402. { runId: "wfrun-legacy", status: "completed", output: { response: "legacy" } } as never,
  1403. );
  1404. expect(registry.get("wfrun-legacy")?.resultText).toBeUndefined();
  1405. });
  1406. });
  1407. it("emits non-cancellable terminal background task events", async () => {
  1408. const sessionId = createSessionId("background-control-terminal-cancellable");
  1409. const turnId = createTurnId("turn_background_control_terminal_cancellable");
  1410. const events: Array<{ type: SessionEventType; payload: unknown }> = [];
  1411. const tracker = new BackgroundTaskTracker({
  1412. emitEvent: async (event) => {
  1413. events.push({ type: event.type, payload: event.payload });
  1414. },
  1415. executionPort: {
  1416. async run() {
  1417. throw new Error("run should not be called");
  1418. },
  1419. async cancelBackgroundTask() {
  1420. throw new Error("cancelBackgroundTask should not be called");
  1421. },
  1422. async waitForBackgroundTask() {
  1423. return {
  1424. taskId: "bash_terminal_cancellable",
  1425. status: "completed",
  1426. startedAt: new Date(0),
  1427. completedAt: new Date(1),
  1428. stdoutTail: "done",
  1429. };
  1430. },
  1431. },
  1432. getWorkingDirectory: () => "/tmp",
  1433. getWorkspaceRoot: () => "/tmp",
  1434. readFileState: new Map(),
  1435. runtimeScope: "main",
  1436. sessionId,
  1437. } as never);
  1438. await tracker.trackBackgroundTask(
  1439. {
  1440. id: "tool_bash_terminal_cancellable",
  1441. input: { command: "echo done" },
  1442. name: "Bash",
  1443. } as never,
  1444. {
  1445. backgroundTaskId: "bash_terminal_cancellable",
  1446. status: "backgrounded",
  1447. },
  1448. {
  1449. traceId: "trace_background_control_terminal_cancellable",
  1450. spanId: "span_background_control_terminal_cancellable",
  1451. sessionId,
  1452. turnId,
  1453. },
  1454. turnId,
  1455. );
  1456. await waitForCondition(() =>
  1457. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1458. );
  1459. const completed = events.find(
  1460. (event) => event.type === SessionEventType.BackgroundTaskCompleted,
  1461. );
  1462. expect(completed?.payload).toMatchObject({
  1463. cancellable: false,
  1464. status: "completed",
  1465. taskId: "bash_terminal_cancellable",
  1466. });
  1467. });
  1468. it("logs pid, exit code and duration of a background Bash process with its toolCallId", async () => {
  1469. const sessionId = createSessionId("background-control-terminal-log");
  1470. const turnId = createTurnId("turn_background_control_terminal_log");
  1471. const logs: Array<{ message: string; context: Record<string, unknown> }> = [];
  1472. const tracker = new BackgroundTaskTracker({
  1473. emitEvent: async () => {},
  1474. executionPort: {
  1475. async run() {
  1476. throw new Error("run should not be called");
  1477. },
  1478. async waitForBackgroundTask() {
  1479. return {
  1480. taskId: "bash_terminal_log",
  1481. status: "failed",
  1482. startedAt: new Date(0),
  1483. completedAt: new Date(2_000),
  1484. pid: 5824,
  1485. result: {
  1486. status: "failed",
  1487. exitCode: 137,
  1488. signal: "SIGKILL",
  1489. durationMs: 2_000,
  1490. pid: 5824,
  1491. },
  1492. };
  1493. },
  1494. },
  1495. getWorkingDirectory: () => "/tmp",
  1496. getWorkspaceRoot: () => "/tmp",
  1497. logger: {
  1498. info: (message: string, context?: Record<string, unknown>) =>
  1499. logs.push({ message, context: context ?? {} }),
  1500. },
  1501. readFileState: new Map(),
  1502. runtimeScope: "main",
  1503. sessionId,
  1504. } as never);
  1505. await tracker.trackBackgroundTask(
  1506. { id: "tool_bash_terminal_log", input: { command: "python big.py" }, name: "Bash" } as never,
  1507. { backgroundTaskId: "bash_terminal_log", status: "backgrounded" },
  1508. { traceId: "trace_terminal_log", spanId: "span_terminal_log", sessionId, turnId },
  1509. turnId,
  1510. );
  1511. await waitForCondition(() =>
  1512. logs.some((entry) => entry.context.event === "background_task.tracking.terminal"),
  1513. );
  1514. expect(
  1515. logs.find((entry) => entry.context.event === "background_task.tracking.terminal")?.context,
  1516. ).toMatchObject({
  1517. durationMs: 2_000,
  1518. exitCode: 137,
  1519. pid: 5824,
  1520. signal: "SIGKILL",
  1521. taskId: "bash_terminal_log",
  1522. toolCallId: "tool_bash_terminal_log",
  1523. });
  1524. });
  1525. it.each([
  1526. { settledBeforeTracking: true, expected: [] },
  1527. { settledBeforeTracking: false, expected: [SessionEventType.BackgroundTaskStarted] },
  1528. ])(
  1529. "writes BackgroundTaskStarted for an Agent launch only while the runner has not settled it (settled first: $settledBeforeTracking)",
  1530. async ({ settledBeforeTracking, expected }) => {
  1531. const sessionId = createSessionId(
  1532. `background-control-agent-settled-${settledBeforeTracking}`,
  1533. );
  1534. const turnId = createTurnId(`turn_background_control_agent_settled_${settledBeforeTracking}`);
  1535. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  1536. runtimeTaskRegistry.register({
  1537. agentId: "agent_settled",
  1538. agentType: "general-purpose",
  1539. description: "research",
  1540. isBackgrounded: true,
  1541. outputFile: "/tmp/agent_settled/output.txt",
  1542. parentToolCallId: "tool_agent_settled",
  1543. startedAt: new Date(0),
  1544. status: "running",
  1545. taskId: "agent_settled",
  1546. taskType: "local_agent",
  1547. type: "local_agent",
  1548. } as never);
  1549. // runner 收口:改成终态并发出通知(它自己的 BackgroundTaskCompleted 不经 tracker)。
  1550. const settle = () =>
  1551. runtimeTaskRegistry.update("agent_settled", (task) => ({
  1552. ...task,
  1553. completedAt: new Date(1),
  1554. notified: true,
  1555. status: "completed",
  1556. }));
  1557. // 转后台与 child 结束几乎同时发生:tracker 开始追踪前 runner 已收口。
  1558. if (settledBeforeTracking) settle();
  1559. const events: SessionEventType[] = [];
  1560. const tracker = new BackgroundTaskTracker({
  1561. emitEvent: async (event) => {
  1562. events.push(event.type);
  1563. // 正常顺序:Started 写入之后 runner 才收口。
  1564. if (event.type === SessionEventType.BackgroundTaskStarted) settle();
  1565. },
  1566. getWorkingDirectory: () => "/tmp",
  1567. getWorkspaceRoot: () => "/tmp",
  1568. readFileState: new Map(),
  1569. runtimeScope: "main",
  1570. runtimeTaskRegistry,
  1571. sessionId,
  1572. subagentPort: {
  1573. getTask: async (taskId: string) => runtimeTaskRegistry.get(taskId),
  1574. },
  1575. } as never);
  1576. await tracker.trackBackgroundTask(
  1577. {
  1578. id: "tool_agent_settled",
  1579. input: { description: "research", prompt: "research" },
  1580. name: "Agent",
  1581. } as never,
  1582. { agentId: "agent_settled", status: "async_launched" },
  1583. {
  1584. traceId: "trace_background_control_agent_settled",
  1585. spanId: "span_background_control_agent_settled",
  1586. sessionId,
  1587. turnId,
  1588. },
  1589. turnId,
  1590. );
  1591. // 两种顺序下完成事件与通知都只由 runner 发;tracker 读到已通知的终态即停止,不补写任何事件。
  1592. expect(events).toEqual(expected);
  1593. },
  1594. );
  1595. it("does not write BackgroundTaskStarted after a run_in_background Agent whose child already finished", async () => {
  1596. const sessionId = createSessionId("background-control-agent-finished-before-tracking");
  1597. const eventStore = createTestSessionEventStore();
  1598. const settled = deferred();
  1599. // Agent 的 ToolCallResult 写入等到 runner 写完 BackgroundTaskCompleted 才返回:child 在 tracker 开始追踪前结束。
  1600. const gatedEventStore = new Proxy(eventStore, {
  1601. get(target, property, receiver) {
  1602. if (property === "append") {
  1603. return async (event: SessionEvent) => {
  1604. const stored = await target.append(event);
  1605. if (event.type === SessionEventType.BackgroundTaskCompleted) settled.resolve();
  1606. if (
  1607. event.type === SessionEventType.ToolCallResult &&
  1608. (event.payload as { toolCallId?: string }).toolCallId === "call_background_agent"
  1609. )
  1610. await settled.promise;
  1611. return stored;
  1612. };
  1613. }
  1614. const value = Reflect.get(target, property, receiver);
  1615. return typeof value === "function" ? value.bind(target) : value;
  1616. },
  1617. }) as typeof eventStore;
  1618. let parentCalls = 0;
  1619. const runtime = createTestAgentRuntime(
  1620. sessionId,
  1621. {
  1622. mode: "yolo",
  1623. modelSelection: {
  1624. providerId: createModelProviderId("provider-test"),
  1625. modelId: createModelId("parent-model"),
  1626. },
  1627. titleGeneration: { enabled: false },
  1628. workingDirectory: "/workspace/project",
  1629. },
  1630. {
  1631. eventStore: gatedEventStore,
  1632. modelFactory: createTestModelFactory({
  1633. async generateText(request: any) {
  1634. const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  1635. if (!(request.tools ?? []).some((tool: any) => tool.name === "Agent"))
  1636. return { finishReason: "stop", text: "child finished fast", usage };
  1637. parentCalls += 1;
  1638. if (parentCalls > 1) return { finishReason: "stop", text: "parent reply", usage };
  1639. return {
  1640. finishReason: "tool-calls",
  1641. text: "",
  1642. toolCalls: [
  1643. {
  1644. id: "call_background_agent",
  1645. name: "Agent",
  1646. input: {
  1647. description: "Fast background child",
  1648. prompt: "Finish at once.",
  1649. run_in_background: true,
  1650. subagent_type: "general-purpose",
  1651. },
  1652. },
  1653. ],
  1654. usage,
  1655. };
  1656. },
  1657. } as never),
  1658. },
  1659. );
  1660. try {
  1661. await runtime.executeTurn("Launch one background agent.");
  1662. await waitForCondition(async () =>
  1663. (await eventStore.getEvents(sessionId)).some(
  1664. (event) => event.type === SessionEventType.BackgroundTaskCompleted,
  1665. ),
  1666. );
  1667. const lifecycle = (await eventStore.getEvents(sessionId))
  1668. .filter(
  1669. (event) =>
  1670. event.type === SessionEventType.BackgroundTaskStarted ||
  1671. event.type === SessionEventType.BackgroundTaskCompleted,
  1672. )
  1673. .map((event) => event.type);
  1674. // 后台工作的最后一条生命周期事件是完成,面板不会停在运行中。
  1675. expect(lifecycle).toEqual([SessionEventType.BackgroundTaskCompleted]);
  1676. } finally {
  1677. await runtime.close();
  1678. }
  1679. });
  1680. });
  1681. /**
  1682. * 后台生命周期的按工具名硬分派已改成按工具查表(见 docs/dynamic-workflow/presentation.md 的
  1683. * 「后台生命周期泛化」)。这一组测两件事:CreateWorkflow 经 dynamicWorkflowRunPort 拿到
  1684. * 完整的快照/等待/取消能力,以及既有工具的语义逐字未变。
  1685. */
  1686. describe("background task per-tool provider lookup", () => {
  1687. interface TrackedRun {
  1688. events: { payload: Record<string, unknown>; type: string }[];
  1689. notifications: { taskId?: string; text: string; toolName?: string; originMeta?: unknown }[];
  1690. }
  1691. async function trackDynamicWorkflowRun(options: {
  1692. getTask?: () => Promise<unknown>;
  1693. input?: Record<string, unknown>;
  1694. launchOutput?: Record<string, unknown>;
  1695. name?: string;
  1696. port?: Record<string, unknown>;
  1697. waitForTask?: () => Promise<unknown>;
  1698. }): Promise<TrackedRun> {
  1699. const sessionId = createSessionId(options.name ?? "dwf-tracker");
  1700. const turnId = createTurnId(options.name ?? "dwf-tracker");
  1701. const events: TrackedRun["events"] = [];
  1702. const notifications: TrackedRun["notifications"] = [];
  1703. const tracker = new BackgroundTaskTracker({
  1704. emitEvent: async (event) => {
  1705. events.push({ payload: event.payload as Record<string, unknown>, type: event.type });
  1706. },
  1707. enqueueBackgroundTaskNotification: (notification) => {
  1708. notifications.push(notification);
  1709. return undefined;
  1710. },
  1711. dynamicWorkflowRunPort:
  1712. options.port ??
  1713. ({
  1714. async submit() {
  1715. throw new Error("submit should not be called by the tracker");
  1716. },
  1717. getTask: options.getTask ?? (async () => ({ status: "running", taskId: "dwfrun-1" })),
  1718. waitForTask:
  1719. options.waitForTask ??
  1720. (async () => ({
  1721. status: "completed",
  1722. taskId: "dwfrun-1",
  1723. output: { response: "workflow answer" },
  1724. })),
  1725. async cancel() {
  1726. return true;
  1727. },
  1728. async listEvents() {
  1729. return [];
  1730. },
  1731. } as never),
  1732. getWorkingDirectory: () => "/tmp",
  1733. getWorkspaceRoot: () => "/tmp",
  1734. readFileState: new Map(),
  1735. runtimeScope: "main",
  1736. sessionId,
  1737. } as never);
  1738. await tracker.trackBackgroundTask(
  1739. {
  1740. id: "tool_create_workflow_1",
  1741. input: options.input ?? { script: 'const r = await agent("a").ask("x");' },
  1742. name: "CreateWorkflow",
  1743. } as never,
  1744. { backgroundTaskId: "dwfrun-1", status: "backgrounded", ...options.launchOutput },
  1745. {
  1746. traceId: `trace_${options.name ?? "dwf-tracker"}`,
  1747. spanId: `span_${options.name ?? "dwf-tracker"}`,
  1748. sessionId,
  1749. turnId,
  1750. },
  1751. turnId,
  1752. );
  1753. return { events, notifications };
  1754. }
  1755. // 第五处分派(canCancelBackgroundTask):它决定 started payload 的 cancellable。
  1756. // 不修它,详情页与后台面板的 Cancel 按钮点不动——整条取消路径不可达。
  1757. it("CreateWorkflow 的 started payload 可取消", async () => {
  1758. const { events } = await trackDynamicWorkflowRun({ name: "dwf-cancellable" });
  1759. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  1760. expect(started?.payload).toMatchObject({
  1761. cancellable: true,
  1762. status: "running",
  1763. taskId: "dwfrun-1",
  1764. toolName: "CreateWorkflow",
  1765. });
  1766. });
  1767. // taskKind 是展示类别(面板分组与图标)。dwf run 此前落进 "bash"——一个我们知情的错标。
  1768. // 生命周期语义不受它影响(已由 per-tool lifecycleProvider 分派),但面板据它分组,
  1769. // 而一个能点开详情页、能取消的 run 与一条后台 shell 命令不是同一种东西。
  1770. it("CreateWorkflow 的 taskKind 是 workflow,不再错标成 bash", async () => {
  1771. const { events } = await trackDynamicWorkflowRun({ name: "dwf-task-kind" });
  1772. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  1773. expect((started?.payload as { taskKind?: string }).taskKind).toBe("workflow");
  1774. });
  1775. /**
  1776. * payload 的 `description` 是任务岛 Workflows 分区那一行的题名(经 backgroundWorks.title)。
  1777. * 原实现只认 `input.description`,而 CreateWorkflow 的输入 schema 里根本没有这个键
  1778. * (只有 `{name?, script}`,contracts/src/tools/create-workflow.ts),于是面板行退到 toolName
  1779. * 显示成 "CreateWorkflow"——每个 run 都同名。改走既有的 workflowTaskSubject 兜底链。
  1780. */
  1781. it("CreateWorkflow 的展示名取 input.name", async () => {
  1782. const { events } = await trackDynamicWorkflowRun({
  1783. input: { name: "Nightly release audit", script: "" },
  1784. name: "dwf-description-name",
  1785. });
  1786. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  1787. expect(started?.payload).toMatchObject({ description: "Nightly release audit" });
  1788. });
  1789. // 名字缺席时兜底链走到最后一环 taskId:不是 undefined,也不是 toolName。
  1790. // 投影对这两者的处理本就一致(都会落到 UI 侧的 fallbackName),所以 taskId 可接受。
  1791. it("CreateWorkflow 无 name 时展示名兜底到 taskId 而不是工具名", async () => {
  1792. const { events } = await trackDynamicWorkflowRun({ name: "dwf-description-fallback" });
  1793. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  1794. expect((started?.payload as { description?: string }).description).toBe("dwfrun-1");
  1795. });
  1796. // 快照提供者与直接等待者都来自同一个端口:终态经 waitForTask 到达并收口成 completed。
  1797. it("经端口的快照提供者与等待者把 run 结算成终态", async () => {
  1798. const { events } = await trackDynamicWorkflowRun({ name: "dwf-terminal" });
  1799. await waitForCondition(() =>
  1800. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1801. );
  1802. const completed = events.find(
  1803. (event) => event.type === SessionEventType.BackgroundTaskCompleted,
  1804. );
  1805. expect(completed?.payload).toMatchObject({ status: "completed", taskId: "dwfrun-1" });
  1806. });
  1807. // 完成通知复用 formatWorkflowTaskNotification,并带 backgroundSource "workflow",
  1808. // 这样主 agent 的新回合渲染成后台结果头而不是退化成裸 model-only 消息。
  1809. it("终态通知走 workflow 通知格式并标记 backgroundSource", async () => {
  1810. const { events, notifications } = await trackDynamicWorkflowRun({ name: "dwf-notify" });
  1811. await waitForCondition(() =>
  1812. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1813. );
  1814. expect(notifications).toHaveLength(1);
  1815. const notification = notifications[0]!;
  1816. expect(notification.taskId).toBe("dwfrun-1");
  1817. expect(notification.toolName).toBe("CreateWorkflow");
  1818. // formatWorkflowTaskNotification 的形状(不是 Bash 的那套):workflow 措辞的 summary
  1819. // 加上截断后的结果。
  1820. expect(notification.text).toContain('<summary>Workflow &quot;dwfrun-1&quot; completed.</summary>');
  1821. expect(notification.text).toContain("workflow answer");
  1822. expect(notification.originMeta).toMatchObject({
  1823. backgroundSource: "workflow",
  1824. workId: "dwfrun-1",
  1825. });
  1826. });
  1827. /**
  1828. * run 产物的回投(桌面实测 bug)。原实现按 legacy `Workflow` 的输出形状取 `output.response`:
  1829. * dwf 产物是脚本的任意顶层返回值,record 时没有 `response` 键 → `<result>` 整个缺席;
  1830. * 非 record 时 `isRecord` 门把 output 退到 **launch output**,其 `response` 是「run 已在后台
  1831. * 启动」的陈旧散文——比缺席更糟。以下几条把序列化规则与「绝不回退散文」钉住。
  1832. *
  1833. * launchOutput 只在 `lost` 那两条路径上到得了通知(终态路径根本不传它),所以「不回退散文」
  1834. * 唯一能真正失败的地方是 lost 用例。
  1835. */
  1836. const LAUNCH_PROSE =
  1837. "The workflow script compiled cleanly and the run started in the background with ID: dwfrun-1.";
  1838. async function notificationFor(name: string, artifact: unknown): Promise<string> {
  1839. const { events, notifications } = await trackDynamicWorkflowRun({
  1840. name,
  1841. waitForTask: async () => ({
  1842. status: "completed",
  1843. taskId: "dwfrun-1",
  1844. ...(artifact === undefined ? {} : { output: artifact }),
  1845. }),
  1846. });
  1847. await waitForCondition(() =>
  1848. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1849. );
  1850. return notifications[0]!.text;
  1851. }
  1852. it("字符串产物原样进 <result>(不加 JSON 引号)", async () => {
  1853. const text = await notificationFor("dwf-artifact-string", "the final answer");
  1854. expect(text).toContain("<result>the final answer</result>");
  1855. expect(text).not.toContain('"the final answer"');
  1856. });
  1857. it("对象产物按 pretty JSON 进 <result>", async () => {
  1858. const text = await notificationFor("dwf-artifact-object", {
  1859. report: "done",
  1860. steps: [1, 2],
  1861. });
  1862. // JSON.stringify(v, null, 2),随后经 escapeXml(引号变 &quot;)。
  1863. expect(text).toContain("&quot;report&quot;: &quot;done&quot;");
  1864. expect(text).toContain("&quot;steps&quot;");
  1865. expect(text).toContain("<result>{\n");
  1866. });
  1867. it("非 record 的数组产物也走 pretty JSON", async () => {
  1868. const text = await notificationFor("dwf-artifact-array", ["one", "two"]);
  1869. expect(text).toContain("&quot;one&quot;");
  1870. expect(text).toContain("<result>[\n");
  1871. });
  1872. // 产物缺席时 `<result>` 整字段缺席。
  1873. it("undefined 产物没有 <result>", async () => {
  1874. const text = await notificationFor("dwf-artifact-absent", undefined);
  1875. expect(text).not.toContain("<result>");
  1876. });
  1877. it("失败的 run 带 <error> 不带 <result>", async () => {
  1878. const { events, notifications } = await trackDynamicWorkflowRun({
  1879. name: "dwf-artifact-failed",
  1880. waitForTask: async () => ({
  1881. status: "failed",
  1882. taskId: "dwfrun-1",
  1883. error: "script threw TypeError",
  1884. }),
  1885. });
  1886. await waitForCondition(() =>
  1887. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1888. );
  1889. const text = notifications[0]!.text;
  1890. expect(text).toContain("<error>script threw TypeError</error>");
  1891. expect(text).not.toContain("<result>");
  1892. });
  1893. // 这条是「比缺席更糟」的那一种:lost 路径把 launch output 递进通知,原实现于是把
  1894. // 「run 已在后台启动」的陈旧散文当成 run 的结果回给模型。dwf 必须整字段缺席。
  1895. it("lost 的 dwf run 绝不把 launch 散文当结果回投", async () => {
  1896. const { events, notifications } = await trackDynamicWorkflowRun({
  1897. launchOutput: { response: LAUNCH_PROSE },
  1898. name: "dwf-artifact-lost",
  1899. waitForTask: async () => undefined,
  1900. });
  1901. await waitForCondition(() =>
  1902. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1903. );
  1904. const text = notifications[0]!.text;
  1905. expect(text).toContain("its in-process state was lost");
  1906. expect(text).not.toContain("<result>");
  1907. expect(text).not.toContain(LAUNCH_PROSE);
  1908. });
  1909. // ── 渐进产物(report)随完成通知回投(docs/dynamic-workflow/transcript-and-notifications.md「Notifications」)──
  1910. //
  1911. // 三个终态一律携带,因为一个死在半途的 run 仍然做完了前面那些活——捞回它正是 report 存在
  1912. // 的理由,而一句「失败」把它全扔了。条目来自 journal 的 kind="report" 行(run service 把它
  1913. // 们放在快照的 `reports` 上),不是 memory-only 的 workflowRuns 投影。
  1914. async function notificationWithReports(
  1915. name: string,
  1916. snapshot: Record<string, unknown>,
  1917. ): Promise<string> {
  1918. const { events, notifications } = await trackDynamicWorkflowRun({
  1919. name,
  1920. waitForTask: async () => ({ taskId: "dwfrun-1", ...snapshot }),
  1921. });
  1922. await waitForCondition(() =>
  1923. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  1924. );
  1925. return notifications[0]!.text;
  1926. }
  1927. it("completed 的通知带 <reports>:真实总数 + 逐条预览(string 原样 / object pretty JSON)", async () => {
  1928. const text = await notificationWithReports("dwf-reports-completed", {
  1929. status: "completed",
  1930. output: "final answer",
  1931. reports: ["3 stale imports", { file: "a.ts", severity: "warn" }],
  1932. });
  1933. expect(text).toContain('<reports count="2">');
  1934. expect(text).toContain("[1] 3 stale imports");
  1935. // 序列化规则与 <result> 同源:object 走 pretty JSON(经 escapeXml,引号变 &quot;)。
  1936. expect(text).toContain("[2] {");
  1937. expect(text).toContain("&quot;file&quot;: &quot;a.ts&quot;");
  1938. // 全部条目都进了预览,所以不带 shown 属性(shown 的存在本身就意味着"预览是局部的")。
  1939. expect(text).not.toContain("shown=");
  1940. // 产物与 run 结果是两件事,两者同时在场。
  1941. expect(text).toContain("<result>final answer</result>");
  1942. });
  1943. it("failed 与 cancelled 的通知一样带 reports(这条是 report 特性的目的)", async () => {
  1944. const failed = await notificationWithReports("dwf-reports-failed", {
  1945. status: "failed",
  1946. error: "script threw TypeError",
  1947. reports: ["finding before the crash"],
  1948. });
  1949. expect(failed).toContain('<reports count="1">');
  1950. expect(failed).toContain("[1] finding before the crash");
  1951. expect(failed).toContain("<error>script threw TypeError</error>");
  1952. // 失败的 run 没有产物,但有报告——两者必须能分辨。
  1953. expect(failed).not.toContain("<result>");
  1954. const cancelled = await notificationWithReports("dwf-reports-cancelled", {
  1955. status: "cancelled",
  1956. reports: ["finding before the cancel"],
  1957. });
  1958. expect(cancelled).toContain('<reports count="1">');
  1959. expect(cancelled).toContain("[1] finding before the cancel");
  1960. });
  1961. // ── 呈现指引(docs/dynamic-workflow/authoring.md「What the main agent is told when a run ends」)──
  1962. //
  1963. // XML 之后追加一段散文,告诉主代理把 run 的结果当交付物呈现。completed 与非 completed 各一段;
  1964. // 散文排在 reports 之后,所以总截断先斩它。
  1965. it("completed 的通知在 XML 之后带交付物呈现指引", async () => {
  1966. const text = await notificationWithReports("dwf-guidance-completed", {
  1967. status: "completed",
  1968. output: "final answer",
  1969. reports: ["one finding"],
  1970. });
  1971. const close = text.indexOf("</task-notification>");
  1972. const guidance = text.indexOf("Present its outcome to the user as a deliverable");
  1973. expect(close).toBeGreaterThanOrEqual(0);
  1974. expect(guidance).toBeGreaterThan(close);
  1975. expect(text).toContain("which findings were confirmed by a deterministic check or an independent subagent");
  1976. expect(text).toContain("Do not restate the phase graph or the script.");
  1977. expect(text).not.toContain("Present what it salvaged first");
  1978. });
  1979. it("failed / cancelled 的通知带抢救优先的指引", async () => {
  1980. const failed = await notificationWithReports("dwf-guidance-failed", {
  1981. status: "failed",
  1982. error: "script threw TypeError",
  1983. reports: ["finding before the crash"],
  1984. });
  1985. expect(failed.indexOf("Present what it salvaged first")).toBeGreaterThan(
  1986. failed.indexOf("</task-notification>"),
  1987. );
  1988. expect(failed).toContain("AmendWorkflow");
  1989. expect(failed).not.toContain("Present its outcome to the user as a deliverable");
  1990. const cancelled = await notificationWithReports("dwf-guidance-cancelled", {
  1991. status: "cancelled",
  1992. reports: ["finding before the cancel"],
  1993. });
  1994. expect(cancelled).toContain("Present what it salvaged first");
  1995. });
  1996. it("零条 report 时整节缺席,不发一节空的 <reports>", async () => {
  1997. const noKey = await notificationWithReports("dwf-reports-absent", {
  1998. status: "completed",
  1999. output: "done",
  2000. });
  2001. expect(noKey).not.toContain("<reports");
  2002. const emptyList = await notificationWithReports("dwf-reports-empty", {
  2003. status: "completed",
  2004. output: "done",
  2005. reports: [],
  2006. });
  2007. expect(emptyList).not.toContain("<reports");
  2008. });
  2009. /**
  2010. * 截断与计数**两者都重要**:计数才是让主 agent 知道「预览是局部的、全量可经 run id 取回」
  2011. * 的那个信号。只给预览会让模型以为它看到了全部。
  2012. */
  2013. it("预览按预算截断,但 count 是真实总数且 shown 说明预览有多少条", async () => {
  2014. const reports = Array.from({ length: 300 }, (_, index) => `finding ${index + 1} `.repeat(20));
  2015. const text = await notificationWithReports("dwf-reports-truncated", {
  2016. status: "completed",
  2017. reports,
  2018. });
  2019. expect(text).toContain('count="300"');
  2020. const shown = /shown="(\d+)"/u.exec(text);
  2021. expect(shown).not.toBeNull();
  2022. const shownCount = Number(shown![1]);
  2023. expect(shownCount).toBeGreaterThan(0);
  2024. expect(shownCount).toBeLessThan(300);
  2025. // 预览从第一条开始给(最早的发现最可能是别的条目的前提)。
  2026. expect(text).toContain("[1] finding 1");
  2027. });
  2028. // 快照只带前 256 条 item,真实总数在 `reportCount`(docs/execution-engine.md「Reading the
  2029. // journal」):count 必须说 run 的总数,而不是快照里的条数——否则一个报了 65,536 条的 run
  2030. // 会在通知里自称只报了 256 条,模型就不会去取剩下的。
  2031. it("count 读快照的 reportCount:快照截在 256 条时仍报真实总数", async () => {
  2032. const reports = Array.from({ length: 256 }, (_, index) => `f${index + 1}`);
  2033. const text = await notificationWithReports("dwf-reports-count-from-snapshot", {
  2034. status: "completed",
  2035. reports,
  2036. reportCount: 65_536,
  2037. });
  2038. expect(text).toContain('count="65536"');
  2039. const shown = /shown="(\d+)"/u.exec(text);
  2040. expect(Number(shown?.[1])).toBeLessThanOrEqual(256);
  2041. expect(text).toContain("[1] f1");
  2042. });
  2043. it("没有 reportCount 的老快照退回条目数", async () => {
  2044. const text = await notificationWithReports("dwf-reports-count-legacy", {
  2045. status: "completed",
  2046. reports: ["a", "b", "c"],
  2047. });
  2048. expect(text).toContain('<reports count="3">');
  2049. });
  2050. // ── run 的脚本文件(docs/dynamic-workflow/launch.md「Script files」)──
  2051. //
  2052. // 端口在快照上给绝对路径(run 身份的一部分),追踪器交给指引的是**工作区相对**写法:
  2053. // 主代理接下来要 Edit 这个文件,而那是它在别处读写文件时用的那一种路径。
  2054. it("errored 的指引带上快照里的脚本文件,写成工作区相对路径", async () => {
  2055. const text = await notificationWithReports("dwf-script-path-errored", {
  2056. status: "failed",
  2057. runStatus: "errored",
  2058. error: "script threw TypeError",
  2059. scriptPath: "/tmp/.zcode/workflow-drafts/audit.dwf.ts",
  2060. });
  2061. expect(text).toContain(
  2062. '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")',
  2063. );
  2064. expect(text).not.toContain("Fix the script and submit it with AmendWorkflow");
  2065. // 路径只进指引,不进 XML 块:用户面一概不显示它(spec 的「What the user sees」)。
  2066. expect(text.indexOf(".zcode/workflow-drafts")).toBeGreaterThan(
  2067. text.indexOf("</task-notification>"),
  2068. );
  2069. });
  2070. it("工作目录之外的脚本文件原样给绝对路径", async () => {
  2071. const text = await notificationWithReports("dwf-script-path-outside", {
  2072. status: "failed",
  2073. runStatus: "errored",
  2074. error: "script threw TypeError",
  2075. scriptPath: "/elsewhere/shared/audit.dwf.ts",
  2076. });
  2077. expect(text).toContain("The run's script is at /elsewhere/shared/audit.dwf.ts.");
  2078. });
  2079. it("stopped(model) 的指引在快照有文件时多一句「编辑它、传 path」", async () => {
  2080. const text = await notificationWithReports("dwf-script-path-stopped", {
  2081. status: "cancelled",
  2082. runStatus: "stopped",
  2083. stopReason: "model",
  2084. scriptPath: "/tmp/.zcode/workflow-drafts/audit.dwf.ts",
  2085. });
  2086. expect(text).toContain(
  2087. "Its script is at .zcode/workflow-drafts/audit.dwf.ts: edit that file and pass `path`.",
  2088. );
  2089. });
  2090. it("快照没有脚本文件时指引逐字节退回旧话(老端口 / 草稿写不下去的项目)", async () => {
  2091. const text = await notificationWithReports("dwf-script-path-absent", {
  2092. status: "failed",
  2093. runStatus: "errored",
  2094. error: "script threw TypeError",
  2095. });
  2096. expect(text).toContain(
  2097. 'Fix the script and submit it with AmendWorkflow (run_id="dwfrun-1") so finished work is reused.',
  2098. );
  2099. expect(text).not.toContain("Edit that file in place");
  2100. });
  2101. // ── 用户面产物(docs/dynamic-workflow/authoring.md「How the user sees them」)──
  2102. //
  2103. // ⚠ 术语:本 describe 里的 artifact 有两个义。`<result>` 那一族是脚本的**顶层返回值**
  2104. // (引擎内部的 `RunSettlement.artifact`),`<artifacts>` 这一节是脚本经 `artifact.*`
  2105. // **发布给用户看的产出**。两者在同一条通知里并列出现,措辞必须可区分。
  2106. it("completed 的通知带 <artifacts>,排在 <reports> 之后,一行一件", async () => {
  2107. const text = await notificationWithReports("dwf-artifacts-completed", {
  2108. status: "completed",
  2109. output: "final answer",
  2110. reports: ["a finding"],
  2111. artifacts: [
  2112. {
  2113. id: "audit",
  2114. kind: "file",
  2115. title: "审计报告",
  2116. version: 2,
  2117. contentType: "application/pdf",
  2118. itemCount: 0,
  2119. versions: [{ version: 1, publishedAt: 1, bytes: 10 }, { version: 2, publishedAt: 2, bytes: 4096 }],
  2120. },
  2121. {
  2122. id: "perf",
  2123. kind: "chart",
  2124. version: 1,
  2125. itemCount: 12,
  2126. versions: [{ version: 1, publishedAt: 3 }],
  2127. },
  2128. ],
  2129. });
  2130. expect(text).toContain('<artifacts count="2">');
  2131. // 内容产物:contentType + 最新版的字节数。
  2132. expect(text).toContain("- audit (file, v2, application/pdf, 4096 bytes): 审计报告");
  2133. // 预置看板:没有字节,数据量是标签 report 的条数;无 title 时不带冒号。
  2134. expect(text).toContain("- perf (chart, v1, 12 items)");
  2135. expect(text).not.toContain("- perf (chart, v1, 12 items):");
  2136. // 顺序:<reports> 在前、<artifacts> 在后(120k 总截断先斩后者)。
  2137. expect(text.indexOf("<reports")).toBeGreaterThan(-1);
  2138. expect(text.indexOf("<artifacts")).toBeGreaterThan(text.indexOf("</reports>"));
  2139. // 呈现指引追加句只在产物在场时出现。
  2140. expect(text).toContain("already in front of the user as cards");
  2141. });
  2142. it("failed 与 cancelled 的通知一样带 <artifacts>,并给一句更短的指引", async () => {
  2143. const artifacts = [
  2144. { id: "notes", kind: "markdown", version: 1, contentType: "text/markdown", itemCount: 0, versions: [{ version: 1, publishedAt: 1, bytes: 128 }] },
  2145. ];
  2146. const failed = await notificationWithReports("dwf-artifacts-failed", {
  2147. status: "failed",
  2148. error: "ask #12 threw",
  2149. artifacts,
  2150. });
  2151. expect(failed).toContain('<artifacts count="1">');
  2152. expect(failed).toContain("- notes (markdown, v1, text/markdown, 128 bytes)");
  2153. expect(failed).toContain("Artifacts listed above are already in front of the user.");
  2154. expect(failed).not.toContain("already in front of the user as cards");
  2155. const cancelled = await notificationWithReports("dwf-artifacts-cancelled", {
  2156. status: "cancelled",
  2157. artifacts,
  2158. });
  2159. expect(cancelled).toContain('<artifacts count="1">');
  2160. });
  2161. it("零件时整节缺席,指引也不长出那一句(没有清单可引用)", async () => {
  2162. const noKey = await notificationWithReports("dwf-artifacts-absent", { status: "completed" });
  2163. expect(noKey).not.toContain("<artifacts");
  2164. expect(noKey).not.toContain("already in front of the user");
  2165. const emptyList = await notificationWithReports("dwf-artifacts-empty", {
  2166. status: "completed",
  2167. artifacts: [],
  2168. });
  2169. expect(emptyList).not.toContain("<artifacts");
  2170. });
  2171. it("超过 8 件时 shown 在场且 count 仍是真实总数", async () => {
  2172. const artifacts = Array.from({ length: 11 }, (_, index) => ({
  2173. id: `a${index + 1}`,
  2174. kind: "markdown",
  2175. version: 1,
  2176. itemCount: 0,
  2177. versions: [{ version: 1, publishedAt: 1, bytes: 8 }],
  2178. }));
  2179. const text = await notificationWithReports("dwf-artifacts-truncated", {
  2180. status: "completed",
  2181. artifacts,
  2182. });
  2183. expect(text).toContain('<artifacts count="11" shown="8">');
  2184. expect(text).toContain("- a1 (markdown, v1, 8 bytes)");
  2185. expect(text).toContain("- a8 (markdown, v1, 8 bytes)");
  2186. expect(text).not.toContain("- a9 (");
  2187. });
  2188. it("形状不合的条目被跳过而不是让整节消失", async () => {
  2189. const text = await notificationWithReports("dwf-artifacts-malformed", {
  2190. status: "completed",
  2191. artifacts: [
  2192. null,
  2193. "not an object",
  2194. { id: "ok", kind: "file", version: 1, itemCount: 0, versions: [] },
  2195. // version 缺席 ⇒ 无法定位版本,整条丢。
  2196. { id: "broken", kind: "file", itemCount: 0, versions: [] },
  2197. ],
  2198. });
  2199. expect(text).toContain('<artifacts count="1">');
  2200. expect(text).toContain("- ok (file, v1)");
  2201. expect(text).not.toContain("broken");
  2202. });
  2203. // legacy `Workflow` 的通知逐字节不变:它的 `output.response` 真实存在,lost 路径上的
  2204. // launchOutput 回退是它自己的契约。dwf 的修订不得溢出到这条路径上。
  2205. it("legacy Workflow 的通知仍取 output.response 并保留 launchOutput 回退", async () => {
  2206. async function legacyNotification(getTask?: () => Promise<unknown>): Promise<string> {
  2207. const sessionId = createSessionId("legacy-workflow-result");
  2208. const turnId = createTurnId("legacy-workflow-result");
  2209. const events: { payload: Record<string, unknown>; type: string }[] = [];
  2210. const notifications: { text: string }[] = [];
  2211. const tracker = new BackgroundTaskTracker({
  2212. emitEvent: async (event) => {
  2213. events.push({ payload: event.payload as Record<string, unknown>, type: event.type });
  2214. },
  2215. enqueueBackgroundTaskNotification: (notification) => {
  2216. notifications.push(notification);
  2217. return undefined;
  2218. },
  2219. ...(getTask ? { workflowPort: { getTask } } : {}),
  2220. getWorkingDirectory: () => "/tmp",
  2221. getWorkspaceRoot: () => "/tmp",
  2222. readFileState: new Map(),
  2223. runtimeScope: "main",
  2224. sessionId,
  2225. } as never);
  2226. await tracker.trackBackgroundTask(
  2227. { id: "tool_workflow_result", input: { scriptPath: "w.ts" }, name: "Workflow" } as never,
  2228. { backgroundTaskId: "wfrun-1", response: "legacy launch prose", status: "backgrounded" },
  2229. { traceId: "trace_legacy_result", spanId: "span_legacy_result", sessionId, turnId },
  2230. turnId,
  2231. );
  2232. await waitForCondition(() =>
  2233. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  2234. );
  2235. return notifications[0]!.text;
  2236. }
  2237. const withResponse = await legacyNotification(async () => ({
  2238. status: "completed",
  2239. runId: "wfrun-1",
  2240. output: { response: "legacy workflow answer" },
  2241. // 即便端口硬塞一个 reports 字段,legacy 通知也不长出 <reports> 这一节:渐进产物是
  2242. // dwf 独有的概念,两套 workflow 机制不共用通知形状。
  2243. reports: ["should not surface"],
  2244. // 用户面产物同理(docs/dynamic-workflow/authoring.md:legacy `Workflow` 通知逐字节不变)。
  2245. artifacts: [
  2246. {
  2247. id: "should-not-surface",
  2248. kind: "file",
  2249. version: 1,
  2250. itemCount: 0,
  2251. versions: [{ version: 1, publishedAt: 1, bytes: 4 }],
  2252. },
  2253. ],
  2254. }));
  2255. expect(withResponse).toContain("<result>legacy workflow answer</result>");
  2256. expect(withResponse).not.toContain("<reports");
  2257. expect(withResponse).not.toContain("should not surface");
  2258. expect(withResponse).not.toContain("<artifacts");
  2259. expect(withResponse).not.toContain("should-not-surface");
  2260. // 呈现指引整块也不属于 legacy:它的通知没有这一段。
  2261. expect(withResponse).not.toContain("already in front of the user");
  2262. // 端口缺席(lost)时回退到 launch output 的 response——legacy 的既有契约,逐字保留。
  2263. const fallback = await legacyNotification();
  2264. expect(fallback).toContain("<result>legacy launch prose</result>");
  2265. });
  2266. // 端口缺席的 CreateWorkflow:没有快照源就按既有语义标 lost,而不是永远挂着轮询。
  2267. it("端口缺席时 CreateWorkflow 立即标记 lost", async () => {
  2268. const sessionId = createSessionId("dwf-no-port");
  2269. const turnId = createTurnId("dwf-no-port");
  2270. const events: { payload: Record<string, unknown>; type: string }[] = [];
  2271. const tracker = new BackgroundTaskTracker({
  2272. emitEvent: async (event) => {
  2273. events.push({ payload: event.payload as Record<string, unknown>, type: event.type });
  2274. },
  2275. getWorkingDirectory: () => "/tmp",
  2276. getWorkspaceRoot: () => "/tmp",
  2277. readFileState: new Map(),
  2278. runtimeScope: "main",
  2279. sessionId,
  2280. } as never);
  2281. await tracker.trackBackgroundTask(
  2282. { id: "tool_cw_lost", input: { script: "" }, name: "CreateWorkflow" } as never,
  2283. { backgroundTaskId: "dwfrun-lost", status: "backgrounded" },
  2284. { traceId: "trace_dwf_lost", spanId: "span_dwf_lost", sessionId, turnId },
  2285. turnId,
  2286. );
  2287. const completed = events.find(
  2288. (event) => event.type === SessionEventType.BackgroundTaskCompleted,
  2289. );
  2290. expect(completed?.payload).toMatchObject({ status: "lost", taskId: "dwfrun-lost" });
  2291. });
  2292. // 回归护栏:legacy Workflow 的四处语义不能被泛化改写——它没有快照提供者以外的取消能力,
  2293. // started payload 的 cancellable 必须仍为 false。
  2294. it("legacy Workflow 的 cancellable 仍为 false", async () => {
  2295. const sessionId = createSessionId("legacy-workflow-cancellable");
  2296. const turnId = createTurnId("legacy-workflow-cancellable");
  2297. const events: { payload: Record<string, unknown>; type: string }[] = [];
  2298. const tracker = new BackgroundTaskTracker({
  2299. emitEvent: async (event) => {
  2300. events.push({ payload: event.payload as Record<string, unknown>, type: event.type });
  2301. },
  2302. workflowPort: {
  2303. async getTask() {
  2304. return { status: "running", runId: "wfrun-1" };
  2305. },
  2306. },
  2307. getWorkingDirectory: () => "/tmp",
  2308. getWorkspaceRoot: () => "/tmp",
  2309. readFileState: new Map(),
  2310. runtimeScope: "main",
  2311. sessionId,
  2312. } as never);
  2313. await tracker.trackBackgroundTask(
  2314. { id: "tool_workflow_1", input: { scriptPath: "w.ts" }, name: "Workflow" } as never,
  2315. { backgroundTaskId: "wfrun-1", status: "backgrounded" },
  2316. { traceId: "trace_legacy_wf", spanId: "span_legacy_wf", sessionId, turnId },
  2317. turnId,
  2318. );
  2319. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  2320. expect(started?.payload).toMatchObject({ cancellable: false, taskId: "wfrun-1" });
  2321. });
  2322. /**
  2323. * 回归护栏:展示名的修订只对 CreateWorkflow 生效,其他工具的 `description` 逐字节不变。
  2324. * Bash 的既有优先级是 `input.description` 先于 `snapshot.description`,两者都缺则整字段缺席
  2325. * (面板据此退到命令行文本)——三种情形一次钉住。
  2326. */
  2327. it("Bash 的展示名仍是 input.description 优先于快照,缺席时为 undefined", async () => {
  2328. async function trackBash(input: Record<string, unknown>): Promise<
  2329. { payload: Record<string, unknown>; type: string }[]
  2330. > {
  2331. const sessionId = createSessionId("bash-description-pin");
  2332. const turnId = createTurnId("bash-description-pin");
  2333. const events: { payload: Record<string, unknown>; type: string }[] = [];
  2334. const tracker = new BackgroundTaskTracker({
  2335. emitEvent: async (event) => {
  2336. events.push({ payload: event.payload as Record<string, unknown>, type: event.type });
  2337. },
  2338. executionPort: {
  2339. async run() {
  2340. throw new Error("run should not be called");
  2341. },
  2342. async waitForBackgroundTask() {
  2343. return {
  2344. taskId: "bash_description",
  2345. status: "completed",
  2346. description: "snapshot description",
  2347. startedAt: new Date(0),
  2348. completedAt: new Date(1),
  2349. stdoutTail: "done",
  2350. };
  2351. },
  2352. },
  2353. getWorkingDirectory: () => "/tmp",
  2354. getWorkspaceRoot: () => "/tmp",
  2355. readFileState: new Map(),
  2356. runtimeScope: "main",
  2357. sessionId,
  2358. } as never);
  2359. await tracker.trackBackgroundTask(
  2360. { id: "tool_bash_description", input, name: "Bash" } as never,
  2361. { backgroundTaskId: "bash_description", status: "backgrounded" },
  2362. { traceId: "trace_bash_description", spanId: "span_bash_description", sessionId, turnId },
  2363. turnId,
  2364. );
  2365. await waitForCondition(() =>
  2366. events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted),
  2367. );
  2368. return events;
  2369. }
  2370. const withDescription = await trackBash({ command: "npm run dev", description: "dev server" });
  2371. // started 没有快照,只能来自 input;completed 有快照,input 仍然优先。
  2372. expect(
  2373. withDescription.find((event) => event.type === SessionEventType.BackgroundTaskStarted)
  2374. ?.payload.description,
  2375. ).toBe("dev server");
  2376. expect(
  2377. withDescription.find((event) => event.type === SessionEventType.BackgroundTaskCompleted)
  2378. ?.payload.description,
  2379. ).toBe("dev server");
  2380. const withoutDescription = await trackBash({ command: "npm run dev" });
  2381. expect(
  2382. withoutDescription.find((event) => event.type === SessionEventType.BackgroundTaskStarted)
  2383. ?.payload.description,
  2384. ).toBeUndefined();
  2385. expect(
  2386. withoutDescription.find((event) => event.type === SessionEventType.BackgroundTaskCompleted)
  2387. ?.payload.description,
  2388. ).toBe("snapshot description");
  2389. });
  2390. });
  2391. /**
  2392. * 取消的唯一路径:`cancelBackgroundWork {workId}` → `app.cancelBackgroundTask` →
  2393. * `runtime.cancelBackgroundTask` → `runtime.stopBackgroundTask` → 端口的 `cancel(runId)`。
  2394. *
  2395. * 这条链按 RuntimeTaskType 分派(runtime/methods/background.ts),与追踪器的按工具名查表
  2396. * 是两处独立的分派。spec 只点了追踪器那五处;这一组测的是链路后半段——不接它,
  2397. * `cancellable: true` 只会给出一个点下去毫无反应的按钮。
  2398. */
  2399. describe("dynamic workflow run cancellation", () => {
  2400. it("cancelBackgroundTask 经运行时分派打到端口的 cancel", async () => {
  2401. const sessionId = createSessionId("dwf-cancel-dispatch");
  2402. const eventStore = createTestSessionEventStore();
  2403. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  2404. const cancelled: string[] = [];
  2405. const startedAt = new Date(0);
  2406. runtimeTaskRegistry.register({
  2407. agentId: "dwfrun-cancel",
  2408. agentType: "local_dynamic_workflow",
  2409. description: "workflow run",
  2410. isBackgrounded: true,
  2411. startedAt,
  2412. status: "running",
  2413. taskId: "dwfrun-cancel",
  2414. taskType: "local_dynamic_workflow",
  2415. type: "local_dynamic_workflow",
  2416. } as never);
  2417. await eventStore.append(
  2418. createSessionEvent(SessionEventType.BackgroundTaskStarted, sessionId, {
  2419. cancellable: true,
  2420. startedAt,
  2421. status: "running",
  2422. taskId: "dwfrun-cancel",
  2423. terminalId: "dwfrun-cancel",
  2424. toolCallId: "tool_create_workflow",
  2425. toolName: "CreateWorkflow",
  2426. }),
  2427. );
  2428. const runtime = createTestAgentRuntime(
  2429. sessionId,
  2430. { mode: "build" },
  2431. {
  2432. dynamicWorkflowRunPort: {
  2433. async submit() {
  2434. throw new Error("submit should not be called");
  2435. },
  2436. async getTask(taskId: string) {
  2437. return { taskId, status: cancelled.includes(taskId) ? "cancelled" : "running" };
  2438. },
  2439. async waitForTask(taskId: string) {
  2440. return { taskId, status: "cancelled" };
  2441. },
  2442. async cancel(runId: string) {
  2443. cancelled.push(runId);
  2444. return true;
  2445. },
  2446. async listEvents() {
  2447. return [];
  2448. },
  2449. },
  2450. eventStore,
  2451. runtimeTaskRegistry,
  2452. } as never,
  2453. );
  2454. const result = await runtime.cancelBackgroundTask("dwfrun-cancel");
  2455. // 端口收到了 runId(workId ≡ taskId ≡ runId,无身份映射表)。
  2456. expect(cancelled).toEqual(["dwfrun-cancel"]);
  2457. expect(result).toMatchObject({ cancelled: true, status: "cancelled", taskId: "dwfrun-cancel" });
  2458. });
  2459. it("端口对未知 run 返回 false 时归一成 not_found 而不是静默成功", async () => {
  2460. const sessionId = createSessionId("dwf-cancel-unknown");
  2461. const eventStore = createTestSessionEventStore();
  2462. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  2463. runtimeTaskRegistry.register({
  2464. agentId: "dwfrun-gone",
  2465. agentType: "local_dynamic_workflow",
  2466. description: "workflow run",
  2467. isBackgrounded: true,
  2468. startedAt: new Date(0),
  2469. status: "running",
  2470. taskId: "dwfrun-gone",
  2471. taskType: "local_dynamic_workflow",
  2472. type: "local_dynamic_workflow",
  2473. } as never);
  2474. const runtime = createTestAgentRuntime(
  2475. sessionId,
  2476. { mode: "build" },
  2477. {
  2478. dynamicWorkflowRunPort: {
  2479. async submit() {
  2480. throw new Error("submit should not be called");
  2481. },
  2482. async getTask() {
  2483. return undefined;
  2484. },
  2485. async waitForTask() {
  2486. return undefined;
  2487. },
  2488. async cancel() {
  2489. return false;
  2490. },
  2491. async listEvents() {
  2492. return [];
  2493. },
  2494. },
  2495. eventStore,
  2496. runtimeTaskRegistry,
  2497. } as never,
  2498. );
  2499. const result = await runtime.cancelBackgroundTask("dwfrun-gone");
  2500. expect(result.cancelled).toBe(false);
  2501. expect(result.reason).toBe("background_task_not_found");
  2502. });
  2503. // 端口整个缺席(未接线的宿主):得结构化的"能力不支持",不能假装取消成功。
  2504. it("端口缺席时报能力不支持", async () => {
  2505. const sessionId = createSessionId("dwf-cancel-no-port");
  2506. const eventStore = createTestSessionEventStore();
  2507. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  2508. runtimeTaskRegistry.register({
  2509. agentId: "dwfrun-noport",
  2510. agentType: "local_dynamic_workflow",
  2511. description: "workflow run",
  2512. isBackgrounded: true,
  2513. startedAt: new Date(0),
  2514. status: "running",
  2515. taskId: "dwfrun-noport",
  2516. taskType: "local_dynamic_workflow",
  2517. type: "local_dynamic_workflow",
  2518. } as never);
  2519. const runtime = createTestAgentRuntime(
  2520. sessionId,
  2521. { mode: "build" },
  2522. { eventStore, runtimeTaskRegistry } as never,
  2523. );
  2524. const result = await runtime.cancelBackgroundTask("dwfrun-noport");
  2525. expect(result.cancelled).toBe(false);
  2526. expect(result.reason).toBe("background_task_cancel_not_supported");
  2527. });
  2528. });
  2529. /**
  2530. * FORK-1 的两个后果,各自钉一条测试。
  2531. *
  2532. * 1. **回收护栏**:runtime task registry 是 `hasRunningBackgroundRuntimeTask` 的数据源,
  2533. * 而那个谓词决定常驻 session 会不会被回收。CreateWorkflow 此前在
  2534. * `runtimeTaskTypeForToolCall` 里没有映射,registerRuntimeBackgroundTask 因此整个早退——
  2535. * 一个在飞的 run 会让 session 看起来空闲,被回收掉之后完成通知无处投递。这比"取消按钮
  2536. * 点不动"更难查,所以单独成测。
  2537. * 2. **两个入口一个实现**:GUI 的 cancelBackgroundWork 与模型的 TaskStop 都落到
  2538. * runtime.stopBackgroundTask(后者经 backgroundTaskControlPort,runtime-tools.ts:144
  2539. * 绑定的正是同一个方法),只在 strict 上不同。
  2540. */
  2541. describe("dynamic workflow background task registration", () => {
  2542. async function trackWithRegistry(runtimeTaskRegistry: InMemoryRuntimeTaskRegistry) {
  2543. const sessionId = createSessionId("dwf-registry");
  2544. const turnId = createTurnId("dwf-registry");
  2545. const tracker = new BackgroundTaskTracker({
  2546. emitEvent: async () => {},
  2547. dynamicWorkflowRunPort: {
  2548. async submit() {
  2549. throw new Error("submit should not be called");
  2550. },
  2551. async getTask(taskId: string) {
  2552. return { taskId, runId: taskId, startedAt: new Date(0), status: "running" };
  2553. },
  2554. // 永不结算:run 在测试期间保持在飞。
  2555. waitForTask: () => new Promise(() => {}),
  2556. async cancel() {
  2557. return true;
  2558. },
  2559. async listEvents() {
  2560. return [];
  2561. },
  2562. },
  2563. getWorkingDirectory: () => "/tmp",
  2564. getWorkspaceRoot: () => "/tmp",
  2565. readFileState: new Map(),
  2566. runtimeScope: "main",
  2567. runtimeTaskRegistry,
  2568. sessionId,
  2569. } as never);
  2570. await tracker.trackBackgroundTask(
  2571. { id: "tool_cw_registry", input: { script: "" }, name: "CreateWorkflow" } as never,
  2572. { backgroundTaskId: "dwfrun-live", status: "backgrounded" },
  2573. { traceId: "trace_dwf_registry", spanId: "span_dwf_registry", sessionId, turnId },
  2574. turnId,
  2575. );
  2576. }
  2577. it("在飞的 run 登记进 registry,回收护栏因此为真", async () => {
  2578. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  2579. // 前提:没有任何在飞后台任务时护栏为假。
  2580. expect(hasRunningBackgroundRuntimeTask(runtimeTaskRegistry)).toBe(false);
  2581. await trackWithRegistry(runtimeTaskRegistry);
  2582. // 登记发生了,且类型是 dwf 专属的那个(不是 legacy local_workflow,也不是 undefined)。
  2583. expect(runtimeTaskRegistry.get("dwfrun-live")).toMatchObject({
  2584. isBackgrounded: true,
  2585. status: "running",
  2586. taskId: "dwfrun-live",
  2587. type: "local_dynamic_workflow",
  2588. });
  2589. // 护栏为真 → 有在飞 run 的 session 不会被当作空闲回收。
  2590. expect(hasRunningBackgroundRuntimeTask(runtimeTaskRegistry)).toBe(true);
  2591. });
  2592. it("模型侧 TaskStop 与 GUI 侧取消共用 runtime.stopBackgroundTask,同样打到 port.cancel", async () => {
  2593. const sessionId = createSessionId("dwf-taskstop");
  2594. const eventStore = createTestSessionEventStore();
  2595. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  2596. const cancelled: string[] = [];
  2597. runtimeTaskRegistry.register({
  2598. agentId: "dwfrun-taskstop",
  2599. agentType: "local_dynamic_workflow",
  2600. description: "workflow run",
  2601. isBackgrounded: true,
  2602. startedAt: new Date(0),
  2603. status: "running",
  2604. taskId: "dwfrun-taskstop",
  2605. taskType: "local_dynamic_workflow",
  2606. type: "local_dynamic_workflow",
  2607. } as never);
  2608. const runtime = createTestAgentRuntime(
  2609. sessionId,
  2610. { mode: "build" },
  2611. {
  2612. dynamicWorkflowRunPort: {
  2613. async submit() {
  2614. throw new Error("submit should not be called");
  2615. },
  2616. async getTask(taskId: string) {
  2617. return { taskId, runId: taskId, startedAt: new Date(0), status: "running" };
  2618. },
  2619. async waitForTask(taskId: string) {
  2620. return { taskId, runId: taskId, startedAt: new Date(0), status: "cancelled" };
  2621. },
  2622. async cancel(runId: string) {
  2623. cancelled.push(runId);
  2624. return true;
  2625. },
  2626. async listEvents() {
  2627. return [];
  2628. },
  2629. },
  2630. eventStore,
  2631. runtimeTaskRegistry,
  2632. } as never,
  2633. );
  2634. // 这就是 runtime-tools.ts:144 交给工具执行上下文的那个绑定。
  2635. const backgroundTaskControlPort = {
  2636. stopBackgroundTask: runtime.stopBackgroundTask.bind(runtime),
  2637. };
  2638. const output = (await taskStopToolEntry.handler(
  2639. { task_id: "dwfrun-taskstop" },
  2640. { backgroundTaskControlPort, toolCallId: "tool_task_stop" } as never,
  2641. )) as { task_id?: string; task_type?: string };
  2642. // 关键断言:模型侧入口也把 runId 直送到了端口的 cancel。
  2643. expect(cancelled).toEqual(["dwfrun-taskstop"]);
  2644. // 并且工具向模型报告的是 dwf 专属类型,不是被归成 bash/legacy workflow。
  2645. expect(output.task_id).toBe("dwfrun-taskstop");
  2646. expect(output.task_type).toBe("local_dynamic_workflow");
  2647. });
  2648. });
  2649. // 停止分支记「谁停的」(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Cancel and resume」 2026-09-09):只在 dwf 分支、
  2650. // 只在调用方给了 initiator 时写;写在 port.cancel 之前。
  2651. describe("dwf 停止分支记录 stopInitiator", () => {
  2652. function dwfRuntime(
  2653. name: string,
  2654. cancelled: string[],
  2655. ): {
  2656. runtime: AgentRuntime;
  2657. registry: InMemoryRuntimeTaskRegistry;
  2658. } {
  2659. const registry = new InMemoryRuntimeTaskRegistry();
  2660. registry.register({
  2661. agentId: "dwfrun-stop",
  2662. agentType: "local_dynamic_workflow",
  2663. description: "Dynamic workflow run",
  2664. isBackgrounded: true,
  2665. startedAt: new Date(0),
  2666. status: "running",
  2667. taskId: "dwfrun-stop",
  2668. taskType: "local_dynamic_workflow",
  2669. type: "local_dynamic_workflow",
  2670. } as never);
  2671. const runtime = createTestAgentRuntime(
  2672. createSessionId(name),
  2673. { mode: "build" },
  2674. {
  2675. eventStore: createTestSessionEventStore(),
  2676. runtimeTaskRegistry: registry,
  2677. dynamicWorkflowRunPort: {
  2678. async submit() {
  2679. throw new Error("submit should not be called");
  2680. },
  2681. async getTask() {
  2682. return {
  2683. runId: "dwfrun-stop",
  2684. taskId: "dwfrun-stop",
  2685. startedAt: new Date(),
  2686. status: "running",
  2687. };
  2688. },
  2689. async waitForTask() {
  2690. return new Promise(() => undefined);
  2691. },
  2692. async cancel(runId: string) {
  2693. // 断言顺序:abort 时 initiator 已经在条目上。
  2694. cancelled.push(`${runId}:${registry.get(runId)?.stopInitiator ?? "none"}`);
  2695. return true;
  2696. },
  2697. async listEvents() {
  2698. return [];
  2699. },
  2700. } as never,
  2701. },
  2702. );
  2703. return { runtime, registry };
  2704. }
  2705. it("stopBackgroundTask({initiator}) 在 abort 之前把 initiator 写进条目", async () => {
  2706. const cancelled: string[] = [];
  2707. const { runtime, registry } = dwfRuntime("dwf-stop-model", cancelled);
  2708. await expect(
  2709. (runtime as any).stopBackgroundTask("dwfrun-stop", { initiator: "model", strict: true }),
  2710. ).resolves.toMatchObject({ ok: true, status: "cancelled", type: "local_dynamic_workflow" });
  2711. expect(cancelled).toEqual(["dwfrun-stop:model"]);
  2712. expect(registry.get("dwfrun-stop")?.stopInitiator).toBe("model");
  2713. });
  2714. it("cancelBackgroundTask(GUI 入口)写 user;不带 initiator 的停止不写", async () => {
  2715. const viaGui: string[] = [];
  2716. const gui = dwfRuntime("dwf-stop-user", viaGui);
  2717. await gui.runtime.cancelBackgroundTask("dwfrun-stop");
  2718. expect(viaGui).toEqual(["dwfrun-stop:user"]);
  2719. expect(gui.registry.get("dwfrun-stop")?.stopInitiator).toBe("user");
  2720. const plain: string[] = [];
  2721. const system = dwfRuntime("dwf-stop-system", plain);
  2722. await (system.runtime as any).stopBackgroundTask("dwfrun-stop", {});
  2723. expect(plain).toEqual(["dwfrun-stop:none"]);
  2724. expect(system.registry.get("dwfrun-stop")?.stopInitiator).toBeUndefined();
  2725. });
  2726. });