background-task-control.test.ts 83 KB

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