background-task-control.test.ts 79 KB

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