dynamic-workflow-run-track.test.ts 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359
  1. // 恢复的 dwf run 的追踪重臂(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md)。
  2. //
  3. // submit 路径的追踪由 tool executor 在 CreateWorkflow 返回 backgrounded 时自动完成;resume
  4. // 是一条 v4 命令、没有在飞的工具调用,所以 runtime 需要一个公共方法合成工具描述子、走同一条
  5. // trackBackgroundTask。漏掉它的两个可测后果:恢复的 run 不在 runtime-task registry 里
  6. // (hasRunningBackgroundTasks 为假 → 会话被当空闲回收、完成通知丢失),以及 backgroundWorks
  7. // 面板上没有条目(cancellable 不可达 → 恢复后无法再取消)。
  8. import { describe, expect, it, vi } from "vitest";
  9. import {
  10. CREATE_WORKFLOW_TOOL_NAME,
  11. RESUME_WORKFLOW_RUN_TOOL_NAME,
  12. SessionEventType,
  13. createRootTraceContext,
  14. createSessionId,
  15. type DynamicWorkflowRunSnapshot,
  16. type SessionEvent,
  17. } from "@zcode/contracts";
  18. import { workflowNotificationMetaSchema } from "@zcode/shared/zcode-protocol-v4";
  19. import { AgentRuntime } from "../src/index.js";
  20. import { InMemoryRuntimeTaskRegistry } from "../src/runtime-task/registry.js";
  21. import { BackgroundTaskTracker } from "../src/tool/executor/background-tasks.js";
  22. import type { ToolExecutorDeps } from "../src/tool/executor/types.js";
  23. import type { ExecutableToolCall } from "../src/tool/types.js";
  24. import { createTestSessionEventStore } from "./test-event-store.js";
  25. interface Deferred<T> {
  26. promise: Promise<T>;
  27. resolve: (value: T) => void;
  28. }
  29. function defer<T>(): Deferred<T> {
  30. let resolve!: (value: T) => void;
  31. const promise = new Promise<T>((res) => {
  32. resolve = res;
  33. });
  34. return { promise, resolve };
  35. }
  36. /**
  37. * 可二次 settle 的队列式 waitForTask stub:每次被调用就挂一个新的 deferred,settle 按调用
  38. * 顺序消费最旧的一个。单次 deferred 在「cancel 终态 → 未重启即 resume」场景下只能喂第一轮
  39. * waiter,第二轮重臂挂上的 promise 永远悬置——那正是终态残留缺陷的完整回归路径需要的形状。
  40. */
  41. interface TerminalQueue {
  42. resolve(value: DynamicWorkflowRunSnapshot): void;
  43. }
  44. function makeTerminalQueue(): TerminalQueue & {
  45. waitForTask(): Promise<DynamicWorkflowRunSnapshot>;
  46. } {
  47. const pending: Deferred<DynamicWorkflowRunSnapshot>[] = [];
  48. return {
  49. waitForTask() {
  50. const deferred = defer<DynamicWorkflowRunSnapshot>();
  51. pending.push(deferred);
  52. return deferred.promise;
  53. },
  54. resolve(value) {
  55. pending.shift()?.resolve(value);
  56. },
  57. };
  58. }
  59. function makeRuntime(name: string): {
  60. runtime: AgentRuntime;
  61. events: SessionEvent[];
  62. terminal: TerminalQueue;
  63. } {
  64. const terminal = makeTerminalQueue();
  65. const runtime = new AgentRuntime(
  66. createSessionId(name),
  67. { agentName: "dwf-track-test", workingDirectory: "/tmp/zcode-dwf-track" },
  68. {
  69. eventStore: createTestSessionEventStore(),
  70. modelAdapter: {} as never,
  71. dynamicWorkflowRunPort: {
  72. async submit() {
  73. throw new Error("resume 重臂不应触发 submit");
  74. },
  75. async getTask() {
  76. return {
  77. runId: "dwfrun-1",
  78. taskId: "dwfrun-1",
  79. startedAt: new Date(),
  80. status: "running",
  81. };
  82. },
  83. waitForTask: () => terminal.waitForTask(),
  84. async cancel() {
  85. return true;
  86. },
  87. async listEvents() {
  88. return [];
  89. },
  90. } as never,
  91. },
  92. );
  93. const events: SessionEvent[] = [];
  94. runtime.subscribeEvents({ onSessionEvent: (event) => events.push(event) });
  95. return { runtime, events, terminal };
  96. }
  97. describe("trackResumedDynamicWorkflowRun", () => {
  98. it("登记 registry(回收护栏)并发出可取消的 workflow started 事件", async () => {
  99. const { runtime, events } = makeRuntime("dwf-track-started");
  100. await runtime.trackResumedDynamicWorkflowRun({
  101. runId: "dwfrun-1",
  102. toolCallId: "call-origin",
  103. name: "Nightly audit",
  104. });
  105. // 回收护栏:恢复的 run 在飞期间,会话绝不能显得空闲。
  106. expect(runtime.hasRunningBackgroundTasks()).toBe(true);
  107. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  108. expect(started?.payload).toMatchObject({
  109. cancellable: true,
  110. description: "Nightly audit",
  111. status: "running",
  112. taskId: "dwfrun-1",
  113. taskKind: "workflow",
  114. // 合成描述子的 id 就是原始 toolCallId:工具卡 → 详情页的关联键跨 resume 保持。
  115. toolCallId: "call-origin",
  116. toolName: "CreateWorkflow",
  117. });
  118. // 命令发起、不属于任何模型回合。
  119. expect(started?.turnId).toBeUndefined();
  120. });
  121. it("终态经 waiter 收口:resolve 后发出 completed 事件并退出 registry", async () => {
  122. const { runtime, events, terminal } = makeRuntime("dwf-track-settle");
  123. await runtime.trackResumedDynamicWorkflowRun({ runId: "dwfrun-1" });
  124. terminal.resolve({
  125. runId: "dwfrun-1",
  126. taskId: "dwfrun-1",
  127. startedAt: new Date(),
  128. status: "completed",
  129. output: "revived artifact",
  130. });
  131. await vi.waitFor(() => {
  132. expect(events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted)).toBe(
  133. true,
  134. );
  135. });
  136. expect(runtime.hasRunningBackgroundTasks()).toBe(false);
  137. });
  138. it("同 runId 重复重臂是幂等的(poller 去重,不发第二个 started)", async () => {
  139. const { runtime, events } = makeRuntime("dwf-track-dedupe");
  140. await runtime.trackResumedDynamicWorkflowRun({ runId: "dwfrun-1", toolCallId: "call-1" });
  141. await runtime.trackResumedDynamicWorkflowRun({ runId: "dwfrun-1", toolCallId: "call-1" });
  142. const started = events.filter((event) => event.type === SessionEventType.BackgroundTaskStarted);
  143. expect(started).toHaveLength(1);
  144. });
  145. it("老 run 缺 toolCallId 时合成可观测的 resume 前缀 id,不冒充真实工具行", async () => {
  146. const { runtime, events } = makeRuntime("dwf-track-no-anchor");
  147. await runtime.trackResumedDynamicWorkflowRun({ runId: "dwfrun-old" });
  148. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  149. expect((started?.payload as { toolCallId?: string }).toolCallId).toBe("resume-dwfrun-old");
  150. // 展示名缺席 → 兜底链走到 taskId(与 submit 路径同语义,UI 侧按 fallbackName 处理)。
  151. expect((started?.payload as { description?: string }).description).toBe("dwfrun-old");
  152. });
  153. });
  154. // ————————————————————————————————————————————————
  155. // 终态残留复位(fix 档,apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Cancel and resume」)。
  156. //
  157. // 根因:同进程 cancel 终态 → 未重启即 resume 时,registry 既有条目带上一轮 claim 的
  158. // notified:true,registerRuntimeBackgroundTask 的 {...existing} 重建不复位它,
  159. // claimRuntimeBackgroundTaskNotification 据此拒收——恢复 run 的终态模型通知被吞。
  160. // 缺陷与工具名无关(今天就经 v4 命令路径以 CreateWorkflow 名触达),所以这里也用
  161. // CreateWorkflow 描述子;fix 提交点上 lifecycleProvider 尚不认 ResumeWorkflowRun。
  162. // ————————————————————————————————————————————————
  163. /** 直构 executor deps 的单元级 fixture:registry + 通知 spy + 事件数组 + dwf 端口 stub。 */
  164. function makeUnitFixture(runId = "dwfrun-relive"): {
  165. deps: ToolExecutorDeps;
  166. events: SessionEvent[];
  167. notifications: { text: string; taskId?: string; originMeta?: unknown }[];
  168. registry: InMemoryRuntimeTaskRegistry;
  169. settleTerminal(value: DynamicWorkflowRunSnapshot): void;
  170. } {
  171. const registry = new InMemoryRuntimeTaskRegistry();
  172. const events: SessionEvent[] = [];
  173. const notifications: { text: string; taskId?: string; originMeta?: unknown }[] = [];
  174. const terminal = makeTerminalQueue();
  175. const deps = {
  176. emitEvent: async (event: SessionEvent) => {
  177. events.push(event);
  178. },
  179. enqueueBackgroundTaskNotification: (notification: {
  180. text: string;
  181. taskId?: string;
  182. originMeta?: unknown;
  183. }) => {
  184. notifications.push(notification);
  185. },
  186. runtimeTaskRegistry: registry,
  187. dynamicWorkflowRunPort: {
  188. async getTask() {
  189. return { runId, taskId: runId, startedAt: new Date(), status: "running" };
  190. },
  191. waitForTask: () => terminal.waitForTask(),
  192. async cancel() {
  193. return true;
  194. },
  195. },
  196. sessionId: createSessionId("dwf-relive-unit"),
  197. } as unknown as ToolExecutorDeps;
  198. return {
  199. deps,
  200. events,
  201. notifications,
  202. registry,
  203. settleTerminal: (value) => terminal.resolve(value),
  204. };
  205. }
  206. describe("trackBackgroundTask 终态残留复位(单元级)", () => {
  207. it("重臂终态条目按新生命重盖 branchGeneration(cancel → rewind → resume 不被 stale-branch fencing 拦下)", async () => {
  208. const { deps, registry } = makeUnitFixture();
  209. // 上一段生命周期在分支代 3 登记并被 cancel;随后用户 rewind,active 分支代推进到 7。
  210. registry.setActiveBranchGeneration(3);
  211. registry.register({
  212. taskId: "dwfrun-relive",
  213. agentId: "dwfrun-relive",
  214. agentType: "local_dynamic_workflow",
  215. description: "nightly audit",
  216. startedAt: new Date(0),
  217. status: "killed",
  218. type: "local_dynamic_workflow",
  219. isBackgrounded: true,
  220. notified: true,
  221. });
  222. expect(registry.get("dwfrun-relive")?.branchGeneration).toBe(3);
  223. registry.setActiveBranchGeneration(7);
  224. const tracker = new BackgroundTaskTracker(deps);
  225. await tracker.trackBackgroundTask(
  226. { id: "call-resume-new", name: CREATE_WORKFLOW_TOOL_NAME, input: {} },
  227. { status: "backgrounded", backgroundTaskId: "dwfrun-relive" },
  228. createRootTraceContext({ sessionId: createSessionId("dwf-relive-unit") }),
  229. undefined,
  230. );
  231. // 修复前:update 的 {...existing} 把 3 带进新生命,runtime-command-generation 会把新生命的
  232. // 任务事件当旧分支残留丢弃。新生命必须盖当前 active 分支代。
  233. expect(registry.get("dwfrun-relive")?.branchGeneration).toBe(7);
  234. expect(registry.get("dwfrun-relive")?.status).toBe("running");
  235. });
  236. it("仍在 running 的既有条目重臂保持自己的 branchGeneration(不是新生命)", async () => {
  237. const { deps, registry } = makeUnitFixture();
  238. registry.setActiveBranchGeneration(3);
  239. registry.register({
  240. taskId: "dwfrun-relive",
  241. agentId: "dwfrun-relive",
  242. agentType: "local_dynamic_workflow",
  243. description: "nightly audit",
  244. startedAt: new Date(0),
  245. status: "running",
  246. type: "local_dynamic_workflow",
  247. isBackgrounded: true,
  248. });
  249. registry.setActiveBranchGeneration(7);
  250. const tracker = new BackgroundTaskTracker(deps);
  251. await tracker.trackBackgroundTask(
  252. { id: "call-resume-new", name: CREATE_WORKFLOW_TOOL_NAME, input: {} },
  253. { status: "backgrounded", backgroundTaskId: "dwfrun-relive" },
  254. createRootTraceContext({ sessionId: createSessionId("dwf-relive-unit") }),
  255. undefined,
  256. );
  257. expect(registry.get("dwfrun-relive")?.branchGeneration).toBe(3);
  258. });
  259. it("重臂既有终态条目:结算面复位、身份面保留,二次结算通知不被旧 claim 吞掉", async () => {
  260. const { deps, notifications, registry, settleTerminal } = makeUnitFixture();
  261. const startedAt = new Date(Date.UTC(2026, 7, 1, 8, 0, 0));
  262. // 预置上一轮的终态残留:cancelled 已结算、claim 已消费(notified:true),还挂着旧失败
  263. // 与旧产物。身份面(parentToolCallId/startedAt)是「工具卡 → 详情页链路跨 resume 保持」
  264. // 的锚,修复若被误写成整体重建丢身份,下面的身份面断言必须红。
  265. registry.register({
  266. taskId: "dwfrun-relive",
  267. agentId: "dwfrun-relive",
  268. agentType: "local_dynamic_workflow",
  269. description: "nightly audit",
  270. startedAt,
  271. status: "killed",
  272. type: "local_dynamic_workflow",
  273. isBackgrounded: true,
  274. notified: true,
  275. error: "cancelled by user",
  276. completedAt: new Date(Date.UTC(2026, 7, 1, 9, 0, 0)),
  277. resultText: "旧产物",
  278. parentToolCallId: "call-create-origin",
  279. });
  280. const tracker = new BackgroundTaskTracker(deps);
  281. const toolCall: ExecutableToolCall = {
  282. id: "call-resume-new",
  283. name: CREATE_WORKFLOW_TOOL_NAME,
  284. input: {},
  285. };
  286. await tracker.trackBackgroundTask(
  287. toolCall,
  288. { status: "backgrounded", backgroundTaskId: "dwfrun-relive" },
  289. createRootTraceContext({ sessionId: createSessionId("dwf-relive-unit") }),
  290. undefined,
  291. );
  292. // 结算面复位:running 期的条目不能再挂着上一轮的 notified/error/completedAt/resultText
  293. // (error/completedAt/resultText 残留会让 running 期条目经 update 的 ?? 链挂旧失败)。
  294. const rearmed = registry.get("dwfrun-relive");
  295. expect(rearmed?.status).toBe("running");
  296. expect(rearmed?.notified).toBe(false);
  297. expect(rearmed?.error).toBeUndefined();
  298. expect(rearmed?.completedAt).toBeUndefined();
  299. expect(rearmed?.resultText).toBeUndefined();
  300. // 身份面保留:parentToolCallId/startedAt 维持 existing,不换成本次重臂的描述子。
  301. expect(rearmed?.parentToolCallId).toBe("call-create-origin");
  302. expect(rearmed?.startedAt).toBe(startedAt);
  303. // 二次结算的终态通知必须送达:修复前 notified:true 残留让 claim 拒收、通知被吞。
  304. settleTerminal({
  305. runId: "dwfrun-relive",
  306. taskId: "dwfrun-relive",
  307. startedAt: new Date(),
  308. status: "completed",
  309. output: "revived artifact",
  310. });
  311. await vi.waitFor(() => {
  312. expect(notifications).toHaveLength(1);
  313. });
  314. expect(notifications[0]!.text).toContain("revived artifact");
  315. });
  316. });
  317. // ————————————————————————————————————————————————
  318. // 终态通知的 manifest 载荷(docs/dynamic-workflow/transcript-and-notifications.md「Where the payload is minted」发射点)。
  319. // 载荷发射侧铸造、有界,随 originMeta 走全管线;GUI 据它渲染 manifest 条目。快照缺失(lost)
  320. // 或非终态一律不携带——载荷缺席即退回裸标题行。
  321. // ————————————————————————————————————————————————
  322. interface TerminalNotificationMeta {
  323. kind: "terminal";
  324. status: "completed" | "failed" | "cancelled";
  325. summary: string;
  326. result?: string;
  327. resultForm?: "prose" | "json";
  328. resultTruncated?: true;
  329. error?: string;
  330. reports?: { count: number; shown: number; preview: string[] };
  331. artifacts?: { id: string; kind: string; title?: string; version: number; contentType?: string }[];
  332. artifactsTruncated?: true;
  333. durationMs?: number;
  334. }
  335. /** 取 notifications[0] 的 workflowNotification(terminal 分支),无则 undefined。 */
  336. function terminalMetaOf(
  337. notification: { originMeta?: unknown } | undefined,
  338. ): TerminalNotificationMeta | undefined {
  339. const originMeta = notification?.originMeta as
  340. | { workflowNotification?: TerminalNotificationMeta }
  341. | undefined;
  342. const meta = originMeta?.workflowNotification;
  343. return meta?.kind === "terminal" ? meta : undefined;
  344. }
  345. describe("终态通知的 manifest 载荷", () => {
  346. it("completed:status/summary/result(prose)/reports/durationMs 齐备", async () => {
  347. const { deps, notifications, settleTerminal } = makeUnitFixture("dwfrun-manifest");
  348. const tracker = new BackgroundTaskTracker(deps);
  349. await tracker.trackBackgroundTask(
  350. { id: "call-m1", name: CREATE_WORKFLOW_TOOL_NAME, input: { name: "nightly audit" } },
  351. { status: "backgrounded", backgroundTaskId: "dwfrun-manifest" },
  352. createRootTraceContext({ sessionId: createSessionId("dwf-manifest") }),
  353. undefined,
  354. );
  355. const startedAt = new Date(Date.UTC(2026, 8, 1, 8, 0, 0));
  356. const completedAt = new Date(Date.UTC(2026, 8, 1, 8, 0, 5));
  357. settleTerminal({
  358. runId: "dwfrun-manifest",
  359. taskId: "dwfrun-manifest",
  360. startedAt,
  361. completedAt,
  362. status: "completed",
  363. output: "final prose artifact",
  364. reports: [{ title: "第一步" }, "第二步"],
  365. });
  366. await vi.waitFor(() => {
  367. expect(notifications).toHaveLength(1);
  368. });
  369. const meta = terminalMetaOf(notifications[0]);
  370. // summary 与后台结果头的 title 同源(workflowTaskSubject → input.name)。
  371. expect(notifications[0]!.originMeta).toMatchObject({ title: "nightly audit" });
  372. expect(meta).toMatchObject({
  373. kind: "terminal",
  374. status: "completed",
  375. summary: "nightly audit",
  376. result: "final prose artifact",
  377. resultForm: "prose",
  378. durationMs: 5_000,
  379. });
  380. // string 产物 → prose,绝不截断标志。
  381. expect(meta?.resultTruncated).toBeUndefined();
  382. // reports:count 是真实总条数,preview 逐条序列化(第二条是纯字符串,原样)。
  383. expect(meta?.reports).toEqual({
  384. count: 2,
  385. shown: 2,
  386. preview: [JSON.stringify({ title: "第一步" }, null, 2), "第二步"],
  387. });
  388. });
  389. it("reports.count 读快照的 reportCount(快照只带前 256 条 item)", async () => {
  390. const meta = await terminalMetaAfterSettle("dwfrun-manifest-count", {
  391. startedAt: new Date(Date.UTC(2026, 8, 1, 8, 0, 0)),
  392. completedAt: new Date(Date.UTC(2026, 8, 1, 8, 0, 5)),
  393. status: "completed",
  394. output: "done",
  395. reports: Array.from({ length: 256 }, (_, index) => `f${index + 1}`),
  396. reportCount: 65_536,
  397. });
  398. expect(meta?.reports?.count).toBe(65_536);
  399. expect(meta?.reports?.shown).toBe(8);
  400. expect(meta?.reports?.preview[0]).toBe("f1");
  401. });
  402. // ————————————————————————————————————————————————
  403. // 时长的口径(docs/dynamic-workflow/transcript-and-notifications.md「How long it took」)。
  404. // 回归的缺陷:只报「结算它的这个进程自己的那一世」,于是修订/恢复出来的那一世(大半是缓存
  405. // 重放,秒级)成了整条 lineage 的时长——四小时的活报 12 秒,而同卡的 tokens 是 lineage 总数。
  406. // ————————————————————————————————————————————————
  407. /** 追踪一个 run 并交出它的终态载荷。 */
  408. async function terminalMetaAfterSettle(
  409. runId: string,
  410. snapshot: Omit<DynamicWorkflowRunSnapshot, "runId" | "taskId">,
  411. ): Promise<TerminalNotificationMeta | undefined> {
  412. const { deps, notifications, settleTerminal } = makeUnitFixture(runId);
  413. const tracker = new BackgroundTaskTracker(deps);
  414. await tracker.trackBackgroundTask(
  415. { id: `call-${runId}`, name: CREATE_WORKFLOW_TOOL_NAME, input: {} },
  416. { status: "backgrounded", backgroundTaskId: runId },
  417. createRootTraceContext({ sessionId: createSessionId(runId) }),
  418. undefined,
  419. );
  420. settleTerminal({ runId, taskId: runId, ...snapshot } as DynamicWorkflowRunSnapshot);
  421. await vi.waitFor(() => {
  422. expect(notifications).toHaveLength(1);
  423. });
  424. return terminalMetaOf(notifications[0]);
  425. }
  426. /** 本世 12 秒(修订/恢复出来的那一世),lineage 四小时。 */
  427. const AMENDED_LIFE = {
  428. startedAt: new Date(Date.UTC(2026, 8, 1, 12, 0, 0)),
  429. completedAt: new Date(Date.UTC(2026, 8, 1, 12, 0, 12)),
  430. status: "completed" as const,
  431. };
  432. it("lineage 的活动时长在场时报它,而不是本进程那一世", async () => {
  433. const meta = await terminalMetaAfterSettle("dwfrun-lineage", {
  434. ...AMENDED_LIFE,
  435. activeDurationMs: 4 * 3_600_000,
  436. });
  437. expect(meta?.durationMs).toBe(4 * 3_600_000);
  438. // 跨边界的那道闸:共享 schema 拒收的载荷会让整条 row 落不了库(通知因此永久消失),
  439. // 而这个口径下的数比以往大几个数量级——上界必须真的没有。
  440. expect(workflowNotificationMetaSchema.safeParse(meta).success).toBe(true);
  441. });
  442. it("端口不带 activeDurationMs(老端口 / 内存 journal):退回本世,行为逐字不变", async () => {
  443. const meta = await terminalMetaAfterSettle("dwfrun-own-life", AMENDED_LIFE);
  444. expect(meta?.durationMs).toBe(12_000);
  445. });
  446. it("取大:lineage 值小于本世(老 run 的事件不全)时不少报本进程亲眼所见的那一段", async () => {
  447. const meta = await terminalMetaAfterSettle("dwfrun-floor", {
  448. ...AMENDED_LIFE,
  449. activeDurationMs: 3_000,
  450. });
  451. expect(meta?.durationMs).toBe(12_000);
  452. });
  453. it("只有 lineage 值、没有 completedAt 时也报得出", async () => {
  454. const meta = await terminalMetaAfterSettle("dwfrun-no-completed", {
  455. startedAt: new Date(Date.UTC(2026, 8, 1, 12, 0, 0)),
  456. status: "completed",
  457. activeDurationMs: 90_000,
  458. });
  459. expect(meta?.durationMs).toBe(90_000);
  460. });
  461. it("脏的 lineage 值(负数 / 非有限)读作说不出,不污染时长", async () => {
  462. const negative = await terminalMetaAfterSettle("dwfrun-negative", {
  463. ...AMENDED_LIFE,
  464. activeDurationMs: -1,
  465. });
  466. expect(negative?.durationMs).toBe(12_000);
  467. const notFinite = await terminalMetaAfterSettle("dwfrun-nan", {
  468. ...AMENDED_LIFE,
  469. activeDurationMs: Number.NaN,
  470. });
  471. expect(notFinite?.durationMs).toBe(12_000);
  472. // 两个来源都说不出 → 整字段缺席(卡上 `—`),不写 0。
  473. const neither = await terminalMetaAfterSettle("dwfrun-neither", {
  474. startedAt: new Date(Date.UTC(2026, 8, 1, 12, 0, 0)),
  475. status: "completed",
  476. activeDurationMs: Number.POSITIVE_INFINITY,
  477. });
  478. expect(neither?.durationMs).toBeUndefined();
  479. });
  480. it("非字符串产物 → resultForm=json;>4000 产物截断且置 resultTruncated", async () => {
  481. const { deps, notifications, settleTerminal } = makeUnitFixture("dwfrun-json");
  482. const tracker = new BackgroundTaskTracker(deps);
  483. await tracker.trackBackgroundTask(
  484. { id: "call-m2", name: CREATE_WORKFLOW_TOOL_NAME, input: {} },
  485. { status: "backgrounded", backgroundTaskId: "dwfrun-json" },
  486. createRootTraceContext({ sessionId: createSessionId("dwf-json") }),
  487. undefined,
  488. );
  489. // 一个序列化后 >4000 字符的对象产物。
  490. const big = "x".repeat(5_000);
  491. settleTerminal({
  492. runId: "dwfrun-json",
  493. taskId: "dwfrun-json",
  494. startedAt: new Date(),
  495. status: "completed",
  496. output: { blob: big },
  497. });
  498. await vi.waitFor(() => {
  499. expect(notifications).toHaveLength(1);
  500. });
  501. const meta = terminalMetaOf(notifications[0]);
  502. expect(meta?.resultForm).toBe("json");
  503. expect(meta?.resultTruncated).toBe(true);
  504. expect(meta?.result?.length).toBe(4_000);
  505. });
  506. it("failed:error 落载荷;无产物则无 result/resultForm", async () => {
  507. const { deps, notifications, settleTerminal } = makeUnitFixture("dwfrun-failed");
  508. const tracker = new BackgroundTaskTracker(deps);
  509. await tracker.trackBackgroundTask(
  510. { id: "call-m3", name: CREATE_WORKFLOW_TOOL_NAME, input: {} },
  511. { status: "backgrounded", backgroundTaskId: "dwfrun-failed" },
  512. createRootTraceContext({ sessionId: createSessionId("dwf-failed") }),
  513. undefined,
  514. );
  515. settleTerminal({
  516. runId: "dwfrun-failed",
  517. taskId: "dwfrun-failed",
  518. startedAt: new Date(),
  519. status: "failed",
  520. runStatus: "errored",
  521. error: "ask #12 exhausted budget",
  522. });
  523. await vi.waitFor(() => {
  524. expect(notifications).toHaveLength(1);
  525. });
  526. const meta = terminalMetaOf(notifications[0]);
  527. // 追踪器的 `failed` 在 manifest 上是三终态词 `errored`(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md)。
  528. expect(meta).toMatchObject({
  529. kind: "terminal",
  530. status: "errored",
  531. error: "ask #12 exhausted budget",
  532. });
  533. expect(meta?.result).toBeUndefined();
  534. expect(meta?.resultForm).toBeUndefined();
  535. });
  536. it("lost(快照缺失)→ 无 manifest 载荷,仅保留三基字段", async () => {
  537. // dwf 端口在场时不会落 lost;端口整个缺席时无快照源、无等待者,tracking 直接 lost。
  538. const notifications: { text: string; originMeta?: unknown }[] = [];
  539. const deps = {
  540. emitEvent: async () => {},
  541. enqueueBackgroundTaskNotification: (n: { text: string; originMeta?: unknown }) => {
  542. notifications.push(n);
  543. },
  544. runtimeTaskRegistry: new InMemoryRuntimeTaskRegistry(),
  545. sessionId: createSessionId("dwf-lost-unit"),
  546. } as unknown as ToolExecutorDeps;
  547. const tracker = new BackgroundTaskTracker(deps);
  548. await tracker.trackBackgroundTask(
  549. { id: "call-m4", name: CREATE_WORKFLOW_TOOL_NAME, input: { name: "orphan" } },
  550. { status: "backgrounded", backgroundTaskId: "dwfrun-lost" },
  551. createRootTraceContext({ sessionId: createSessionId("dwf-lost") }),
  552. undefined,
  553. );
  554. expect(notifications).toHaveLength(1);
  555. expect(notifications[0]!.originMeta).toEqual({
  556. backgroundSource: "workflow",
  557. title: "orphan",
  558. workId: "dwfrun-lost",
  559. });
  560. });
  561. // 用户面产物的 chips 载荷(docs/dynamic-workflow/authoring.md「How the user sees them」)。这是通知行 chips
  562. // 的唯一数据源;冷恢复靠 shared 的 zod 原样读回,所以形状必须与那份 schema 逐字对齐。
  563. //
  564. // ⚠ 术语:这里的 artifacts 是脚本经 `artifact.*` 发布给用户看的产出,与同一载荷上的 `result`
  565. // (脚本顶层返回值,引擎内部也叫 artifact)是两件不同的东西。
  566. it("artifacts:只带 chip 画得下的字段,与 result 并列且互不影响", async () => {
  567. const { deps, notifications, settleTerminal } = makeUnitFixture("dwfrun-artifacts");
  568. const tracker = new BackgroundTaskTracker(deps);
  569. await tracker.trackBackgroundTask(
  570. { id: "call-a1", name: CREATE_WORKFLOW_TOOL_NAME, input: { name: "audit" } },
  571. { status: "backgrounded", backgroundTaskId: "dwfrun-artifacts" },
  572. createRootTraceContext({ sessionId: createSessionId("dwf-artifacts") }),
  573. undefined,
  574. );
  575. settleTerminal({
  576. runId: "dwfrun-artifacts",
  577. taskId: "dwfrun-artifacts",
  578. startedAt: new Date(),
  579. status: "completed",
  580. output: "the script's return value",
  581. artifacts: [
  582. {
  583. id: "report",
  584. kind: "file",
  585. title: "审计报告",
  586. contentType: "application/pdf",
  587. sourcePath: "out/report.pdf",
  588. version: 2,
  589. itemCount: 0,
  590. versions: [
  591. { version: 1, publishedAt: 1, bytes: 10 },
  592. { version: 2, publishedAt: 2, bytes: 4096 },
  593. ],
  594. },
  595. {
  596. id: "perf",
  597. kind: "chart",
  598. version: 1,
  599. itemCount: 7,
  600. versions: [{ version: 1, publishedAt: 3 }],
  601. },
  602. ],
  603. });
  604. await vi.waitFor(() => {
  605. expect(notifications).toHaveLength(1);
  606. });
  607. const meta = terminalMetaOf(notifications[0]);
  608. // 字节 / 条目 / 出处 / spec 都刻意不进载荷——chip 上放不下,点开侧板即可。
  609. expect(meta?.artifacts).toEqual([
  610. { id: "report", kind: "file", title: "审计报告", version: 2, contentType: "application/pdf" },
  611. { id: "perf", kind: "chart", version: 1 },
  612. ]);
  613. expect(meta?.artifactsTruncated).toBeUndefined();
  614. // 顶层返回值仍然独立在场:两个 artifact 互不干扰。
  615. expect(meta?.result).toBe("the script's return value");
  616. });
  617. // 交付物(docs/dynamic-workflow/transcript-and-notifications.md「Artifact tiles」):
  618. // 排到清单最前——8 的上界永远砍不到它;只有它带 description(完成卡的那一行要念)。
  619. it("artifacts:primary 带头进清单(第 9 件发布也不会被 8 的上界砍掉),description 只在它身上", async () => {
  620. const { deps, notifications, settleTerminal } = makeUnitFixture("dwfrun-artifacts-primary");
  621. const tracker = new BackgroundTaskTracker(deps);
  622. await tracker.trackBackgroundTask(
  623. { id: "call-a5", name: CREATE_WORKFLOW_TOOL_NAME, input: {} },
  624. { status: "backgrounded", backgroundTaskId: "dwfrun-artifacts-primary" },
  625. createRootTraceContext({ sessionId: createSessionId("dwf-artifacts-primary") }),
  626. undefined,
  627. );
  628. settleTerminal({
  629. runId: "dwfrun-artifacts-primary",
  630. taskId: "dwfrun-artifacts-primary",
  631. startedAt: new Date(),
  632. status: "completed",
  633. artifacts: [
  634. ...Array.from({ length: 8 }, (_, index) => ({
  635. id: `a${index + 1}`,
  636. kind: "markdown",
  637. version: 1,
  638. itemCount: 0,
  639. description: "intermediate note",
  640. versions: [{ version: 1, publishedAt: 1, bytes: 8 }],
  641. })),
  642. {
  643. id: "report",
  644. kind: "markdown",
  645. title: "审计报告",
  646. description: "结论与修复建议",
  647. version: 2,
  648. itemCount: 0,
  649. primary: true,
  650. versions: [
  651. { version: 1, publishedAt: 9, bytes: 8, primary: true },
  652. { version: 2, publishedAt: 10, bytes: 9, primary: true },
  653. ],
  654. },
  655. ],
  656. });
  657. await vi.waitFor(() => {
  658. expect(notifications).toHaveLength(1);
  659. });
  660. const meta = terminalMetaOf(notifications[0]);
  661. expect(meta?.artifacts).toHaveLength(8);
  662. expect(meta?.artifacts?.[0]).toEqual({
  663. id: "report",
  664. kind: "markdown",
  665. title: "审计报告",
  666. version: 2,
  667. primary: true,
  668. description: "结论与修复建议",
  669. });
  670. expect(meta?.artifacts?.slice(1).map((artifact) => artifact.id)).toEqual([
  671. "a1",
  672. "a2",
  673. "a3",
  674. "a4",
  675. "a5",
  676. "a6",
  677. "a7",
  678. ]);
  679. // 非交付物的 description 不进载荷(chip 上放不下,也不需要)。
  680. expect(meta?.artifacts?.slice(1).some((artifact) => "description" in artifact)).toBe(false);
  681. expect(meta?.artifactsTruncated).toBe(true);
  682. // 模型面的清单同样以交付物带头,并在种类后标 primary。
  683. const text = notifications[0]!.text;
  684. const primaryLine = text.indexOf("- report (markdown, primary, v2");
  685. expect(primaryLine).toBeGreaterThan(-1);
  686. expect(primaryLine).toBeLessThan(text.indexOf("- a1 (markdown, v1"));
  687. expect(text).toContain("The one marked primary is the deliverable");
  688. });
  689. it("artifacts:超过 8 件截断并置 artifactsTruncated;零件时两个键一起缺席", async () => {
  690. const { deps, notifications, settleTerminal } = makeUnitFixture("dwfrun-artifacts-many");
  691. const tracker = new BackgroundTaskTracker(deps);
  692. await tracker.trackBackgroundTask(
  693. { id: "call-a2", name: CREATE_WORKFLOW_TOOL_NAME, input: {} },
  694. { status: "backgrounded", backgroundTaskId: "dwfrun-artifacts-many" },
  695. createRootTraceContext({ sessionId: createSessionId("dwf-artifacts-many") }),
  696. undefined,
  697. );
  698. settleTerminal({
  699. runId: "dwfrun-artifacts-many",
  700. taskId: "dwfrun-artifacts-many",
  701. startedAt: new Date(),
  702. status: "completed",
  703. artifacts: Array.from({ length: 10 }, (_, index) => ({
  704. id: `a${index + 1}`,
  705. kind: "markdown",
  706. version: 1,
  707. itemCount: 0,
  708. versions: [{ version: 1, publishedAt: 1, bytes: 8 }],
  709. })),
  710. });
  711. await vi.waitFor(() => {
  712. expect(notifications).toHaveLength(1);
  713. });
  714. const meta = terminalMetaOf(notifications[0]);
  715. expect(meta?.artifacts).toHaveLength(8);
  716. expect(meta?.artifacts?.[7]?.id).toBe("a8");
  717. expect(meta?.artifactsTruncated).toBe(true);
  718. // 零件(快照上没有这个键):两个字段一起缺席,而不是一个空数组。
  719. const empty = makeUnitFixture("dwfrun-artifacts-none");
  720. const emptyTracker = new BackgroundTaskTracker(empty.deps);
  721. await emptyTracker.trackBackgroundTask(
  722. { id: "call-a3", name: CREATE_WORKFLOW_TOOL_NAME, input: {} },
  723. { status: "backgrounded", backgroundTaskId: "dwfrun-artifacts-none" },
  724. createRootTraceContext({ sessionId: createSessionId("dwf-artifacts-none") }),
  725. undefined,
  726. );
  727. empty.settleTerminal({
  728. runId: "dwfrun-artifacts-none",
  729. taskId: "dwfrun-artifacts-none",
  730. startedAt: new Date(),
  731. status: "completed",
  732. });
  733. await vi.waitFor(() => {
  734. expect(empty.notifications).toHaveLength(1);
  735. });
  736. const emptyMeta = terminalMetaOf(empty.notifications[0]);
  737. expect(emptyMeta?.artifacts).toBeUndefined();
  738. expect(emptyMeta?.artifactsTruncated).toBeUndefined();
  739. });
  740. it("artifacts:未知 kind 的条目整条丢弃,其余 chip 不受牵连", async () => {
  741. const { deps, notifications, settleTerminal } = makeUnitFixture("dwfrun-artifacts-kind");
  742. const tracker = new BackgroundTaskTracker(deps);
  743. await tracker.trackBackgroundTask(
  744. { id: "call-a4", name: CREATE_WORKFLOW_TOOL_NAME, input: {} },
  745. { status: "backgrounded", backgroundTaskId: "dwfrun-artifacts-kind" },
  746. createRootTraceContext({ sessionId: createSessionId("dwf-artifacts-kind") }),
  747. undefined,
  748. );
  749. settleTerminal({
  750. runId: "dwfrun-artifacts-kind",
  751. taskId: "dwfrun-artifacts-kind",
  752. startedAt: new Date(),
  753. status: "completed",
  754. artifacts: [
  755. // 未来版本的新种类:放行会让整份载荷被 zod 拒收,连带其余 chip 一起消失。
  756. {
  757. id: "future",
  758. kind: "hologram",
  759. version: 1,
  760. itemCount: 0,
  761. versions: [{ version: 1, publishedAt: 1 }],
  762. },
  763. {
  764. id: "notes",
  765. kind: "markdown",
  766. version: 1,
  767. itemCount: 0,
  768. versions: [{ version: 1, publishedAt: 2 }],
  769. },
  770. ],
  771. });
  772. await vi.waitFor(() => {
  773. expect(notifications).toHaveLength(1);
  774. });
  775. const meta = terminalMetaOf(notifications[0]);
  776. expect(meta?.artifacts).toEqual([{ id: "notes", kind: "markdown", version: 1 }]);
  777. // 丢掉了一条 ⇒ 清单是局部的。
  778. expect(meta?.artifactsTruncated).toBe(true);
  779. });
  780. // 载荷随 turnHeader row 走协议,超界会让整行落库时 zod 拒收——所以每一条界都必须在
  781. // **构造前**兑现。这条把发射侧的产物直接喂给那份 schema,是两边不漂移的唯一硬证据。
  782. it("artifacts:越界的 id / version / contentType 整条或整键丢弃,产物恒可被 shared 的 zod 接受", async () => {
  783. const { deps, notifications, settleTerminal } = makeUnitFixture("dwfrun-artifacts-bounds");
  784. const tracker = new BackgroundTaskTracker(deps);
  785. await tracker.trackBackgroundTask(
  786. { id: "call-a5", name: CREATE_WORKFLOW_TOOL_NAME, input: {} },
  787. { status: "backgrounded", backgroundTaskId: "dwfrun-artifacts-bounds" },
  788. createRootTraceContext({ sessionId: createSessionId("dwf-artifacts-bounds") }),
  789. undefined,
  790. );
  791. settleTerminal({
  792. runId: "dwfrun-artifacts-bounds",
  793. taskId: "dwfrun-artifacts-bounds",
  794. startedAt: new Date(),
  795. status: "completed",
  796. artifacts: [
  797. // id 超 64:截短就是编造一个不存在的产物 ⇒ 整条丢。
  798. { id: "x".repeat(65), kind: "file", version: 1, itemCount: 0, versions: [] },
  799. // 非正整数版本号 ⇒ 整条丢。
  800. { id: "half", kind: "file", version: 1.5, itemCount: 0, versions: [] },
  801. // contentType 超 255 ⇒ 只丢这一个装饰键,条目仍在。
  802. {
  803. id: "ok",
  804. kind: "file",
  805. version: 1,
  806. contentType: "a/".repeat(200),
  807. itemCount: 0,
  808. versions: [],
  809. },
  810. // title 超 120 ⇒ 截断(title 是展示文本,截短仍然有意义)。
  811. {
  812. id: "long",
  813. kind: "markdown",
  814. version: 1,
  815. title: "标".repeat(200),
  816. itemCount: 0,
  817. versions: [],
  818. },
  819. ],
  820. });
  821. await vi.waitFor(() => {
  822. expect(notifications).toHaveLength(1);
  823. });
  824. const meta = terminalMetaOf(notifications[0]);
  825. expect(meta?.artifacts?.map((artifact) => artifact.id)).toEqual(["ok", "long"]);
  826. expect(meta?.artifacts?.[0]).not.toHaveProperty("contentType");
  827. expect(meta?.artifacts?.[1]?.title).toHaveLength(120);
  828. expect(meta?.artifactsTruncated).toBe(true);
  829. // 发射侧产物 → shared 的 zod:两边的界不漂移。
  830. expect(workflowNotificationMetaSchema.safeParse(meta).success).toBe(true);
  831. });
  832. it("Bash 后台通知不带 manifest 载荷(v1 只改 workflow 源)", async () => {
  833. const notifications: { text: string; originMeta?: unknown }[] = [];
  834. let resolveTerminal!: (snapshot: { status: string; result?: { exitCode?: number } }) => void;
  835. const terminalPromise = new Promise<{ status: string; result?: { exitCode?: number } }>(
  836. (resolve) => {
  837. resolveTerminal = resolve;
  838. },
  839. );
  840. const deps = {
  841. emitEvent: async () => {},
  842. enqueueBackgroundTaskNotification: (n: { text: string; originMeta?: unknown }) => {
  843. notifications.push(n);
  844. },
  845. runtimeTaskRegistry: new InMemoryRuntimeTaskRegistry(),
  846. executionPort: {
  847. waitForBackgroundTask: () => terminalPromise,
  848. },
  849. sessionId: createSessionId("dwf-bash-unit"),
  850. } as unknown as ToolExecutorDeps;
  851. const tracker = new BackgroundTaskTracker(deps);
  852. await tracker.trackBackgroundTask(
  853. { id: "call-bash", name: "Bash", input: { command: "sleep 1", description: "wait" } },
  854. { status: "backgrounded", backgroundTaskId: "bash-bg" },
  855. createRootTraceContext({ sessionId: createSessionId("dwf-bash") }),
  856. undefined,
  857. );
  858. resolveTerminal({ status: "completed", result: { exitCode: 0 } });
  859. await vi.waitFor(() => {
  860. expect(notifications).toHaveLength(1);
  861. });
  862. expect(notifications[0]!.originMeta).toEqual({
  863. backgroundSource: "bash",
  864. title: "wait",
  865. workId: "bash-bg",
  866. });
  867. });
  868. });
  869. // v4 路径的完整回归:cancel 终态 → 未重启即 resume → 二次结算。主断言是 spy
  870. // runtime.enqueueBackgroundTaskNotification(经 runtime-tools.ts 默认接线可达);
  871. // BackgroundTaskCompleted 事件无论 claim 与否都发,钉不住「吞通知」这个行为。
  872. describe("trackResumedDynamicWorkflowRun 终态残留复位(v4 路径回归)", () => {
  873. it("cancel 结算后再重臂同 runId:两轮终态各送达一次通知且内容可分辨", async () => {
  874. const { runtime, events, terminal } = makeRuntime("dwf-track-relive");
  875. const recorded: string[] = [];
  876. vi.spyOn(runtime, "enqueueBackgroundTaskNotification").mockImplementation(
  877. (notification: { text: string }) => {
  878. // 只记录不真正入队:入队会经 runtime 命令队列启动模型轮次(task-notification →
  879. // executeTurnCommand),测试没有模型;本用例钉的是「通知是否被 claim 吞掉」。
  880. recorded.push(notification.text);
  881. },
  882. );
  883. await runtime.trackResumedDynamicWorkflowRun({ runId: "dwfrun-1", toolCallId: "call-origin" });
  884. terminal.resolve({
  885. runId: "dwfrun-1",
  886. taskId: "dwfrun-1",
  887. startedAt: new Date(),
  888. status: "cancelled",
  889. });
  890. await vi.waitFor(() => {
  891. expect(recorded).toHaveLength(1);
  892. });
  893. expect(recorded[0]).toMatch(/stopped/i);
  894. // 同进程内 cancel 终态 → 未重启即 resume:重臂同一个 runId 并二次结算。
  895. await runtime.trackResumedDynamicWorkflowRun({ runId: "dwfrun-1", toolCallId: "call-origin" });
  896. terminal.resolve({
  897. runId: "dwfrun-1",
  898. taskId: "dwfrun-1",
  899. startedAt: new Date(),
  900. status: "completed",
  901. output: "second life",
  902. });
  903. await vi.waitFor(() => {
  904. expect(recorded).toHaveLength(2);
  905. });
  906. // 两轮内容可分辨:cancelled vs completed(携新产物)。
  907. expect(recorded[1]).toMatch(/completed/i);
  908. expect(recorded[1]).toContain("second life");
  909. // 辅助断言:两轮各发一次 BackgroundTaskCompleted(它无论 claim 与否都发,钉不住吞通知,
  910. // 只证明两轮结算都走完了)。
  911. const completions = events.filter(
  912. (event) => event.type === SessionEventType.BackgroundTaskCompleted,
  913. );
  914. expect(completions).toHaveLength(2);
  915. });
  916. });
  917. // ————————————————————————————————————————————————
  918. // feat 档(2026-08-29):ResumeWorkflowRun 这个名字本身要被追踪管线认领——
  919. // isDynamicWorkflowRunDispatchToolName 扩名后,恢复入口与新启动入口对 tracker 同构
  920. //(taskType、面板 taskKind、可取消、通知格式、registry 重臂语义全部一致)。
  921. // ————————————————————————————————————————————————
  922. describe("ResumeWorkflowRun 的追踪分派", () => {
  923. /** ResumeWorkflowRun 工具的真实输出形状(executor 据其中的 backgrounded 触发追踪)。 */
  924. function resumeOutput(runId: string): Record<string, unknown> {
  925. return {
  926. ok: true,
  927. runId,
  928. response: "resumed in the background",
  929. status: "backgrounded",
  930. backgroundTaskId: runId,
  931. };
  932. }
  933. it("走 dwf 生命周期:registry 在册、workflow 面板条目可取消、终态通知携产物与 reports", async () => {
  934. const { deps, events, notifications, registry, settleTerminal } =
  935. makeUnitFixture("dwfrun-feat");
  936. const tracker = new BackgroundTaskTracker(deps);
  937. await tracker.trackBackgroundTask(
  938. {
  939. id: "call-resume-1",
  940. name: RESUME_WORKFLOW_RUN_TOOL_NAME,
  941. input: { run_id: "dwfrun-feat" },
  942. },
  943. resumeOutput("dwfrun-feat"),
  944. createRootTraceContext({ sessionId: createSessionId("dwf-feat") }),
  945. undefined,
  946. );
  947. // 回收护栏在册 + taskType 归 dwf(缺席则 registerRuntimeBackgroundTask 直接 return,
  948. // 会话回收护栏与 TaskOutput 可见性全失)。
  949. expect(registry.get("dwfrun-feat")).toMatchObject({
  950. taskType: "local_dynamic_workflow",
  951. type: "local_dynamic_workflow",
  952. status: "running",
  953. parentToolCallId: "call-resume-1",
  954. });
  955. // 面板条目:taskKind "workflow" + 可取消(端口在场 → cancel 可达)。
  956. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  957. expect(started?.payload).toMatchObject({
  958. cancellable: true,
  959. status: "running",
  960. taskId: "dwfrun-feat",
  961. taskKind: "workflow",
  962. toolCallId: "call-resume-1",
  963. toolName: RESUME_WORKFLOW_RUN_TOOL_NAME,
  964. });
  965. // 端口在场 → 有快照提供者 → 绝不落 lost。
  966. expect(
  967. events.some(
  968. (event) =>
  969. event.type === SessionEventType.BackgroundTaskCompleted &&
  970. (event.payload as { status?: string }).status === "lost",
  971. ),
  972. ).toBe(false);
  973. settleTerminal({
  974. runId: "dwfrun-feat",
  975. taskId: "dwfrun-feat",
  976. startedAt: new Date(),
  977. status: "completed",
  978. output: "resumed artifact",
  979. reports: [{ title: "中途产物" }],
  980. });
  981. await vi.waitFor(() => {
  982. expect(notifications).toHaveLength(1);
  983. });
  984. // formatWorkflowTaskNotification:serializeWorkflowArtifact 产物 + reports 节 +
  985. // workflow originMeta(后台结果头,workId ≡ runId)。
  986. expect(notifications[0]!.text).toContain("resumed artifact");
  987. expect(notifications[0]!.text).toContain("中途产物");
  988. expect(notifications[0]!.originMeta).toMatchObject({
  989. backgroundSource: "workflow",
  990. workId: "dwfrun-feat",
  991. });
  992. });
  993. it("parentToolCallId 首次登记为 resume 工具行 id,二次重臂按 existing 合并语义保持", async () => {
  994. const { deps, notifications, registry, settleTerminal } = makeUnitFixture("dwfrun-again");
  995. const tracker = new BackgroundTaskTracker(deps);
  996. await tracker.trackBackgroundTask(
  997. {
  998. id: "call-resume-a",
  999. name: RESUME_WORKFLOW_RUN_TOOL_NAME,
  1000. input: { run_id: "dwfrun-again" },
  1001. },
  1002. resumeOutput("dwfrun-again"),
  1003. createRootTraceContext({ sessionId: createSessionId("dwf-again") }),
  1004. undefined,
  1005. );
  1006. expect(registry.get("dwfrun-again")?.parentToolCallId).toBe("call-resume-a");
  1007. // cancel→resume 循环里的第二次重臂:必须发生在第一轮终态结算**之后**(结算把 poller
  1008. // 摘掉,重臂才会真正重建条目——poller 还在时二次调用被去重挡掉,是既有幂等语义)。
  1009. settleTerminal({
  1010. runId: "dwfrun-again",
  1011. taskId: "dwfrun-again",
  1012. startedAt: new Date(),
  1013. status: "cancelled",
  1014. });
  1015. await vi.waitFor(() => {
  1016. expect(notifications).toHaveLength(1);
  1017. });
  1018. // existing 合并语义保住**首个** resume 工具行 id,不换成新描述子——join 键稳定,
  1019. // 不做「换成新行」的断言。
  1020. await tracker.trackBackgroundTask(
  1021. {
  1022. id: "call-resume-b",
  1023. name: RESUME_WORKFLOW_RUN_TOOL_NAME,
  1024. input: { run_id: "dwfrun-again" },
  1025. },
  1026. resumeOutput("dwfrun-again"),
  1027. createRootTraceContext({ sessionId: createSessionId("dwf-again") }),
  1028. undefined,
  1029. );
  1030. expect(registry.get("dwfrun-again")?.parentToolCallId).toBe("call-resume-a");
  1031. expect(registry.get("dwfrun-again")?.status).toBe("running");
  1032. });
  1033. // 生产首链:CreateWorkflow 启动 → 终态 → ResumeWorkflowRun 恢复。registry 条目经
  1034. // existing 合并语义沿用原始 CreateWorkflow 工具行的 parentToolCallId——详情页 join
  1035. // 跨 resume 不断链(与 v4 路径合成原始 toolCallId 的效果殊途同归)。
  1036. it("混合场景:CreateWorkflow 首链条目被 ResumeWorkflowRun 重臂后 join 键不断链", async () => {
  1037. const { deps, registry } = makeUnitFixture("dwfrun-mixed");
  1038. registry.register({
  1039. taskId: "dwfrun-mixed",
  1040. agentId: "dwfrun-mixed",
  1041. agentType: "local_dynamic_workflow",
  1042. description: "first life",
  1043. startedAt: new Date(),
  1044. status: "killed",
  1045. type: "local_dynamic_workflow",
  1046. isBackgrounded: true,
  1047. notified: true,
  1048. parentToolCallId: "call-create-origin",
  1049. });
  1050. const tracker = new BackgroundTaskTracker(deps);
  1051. await tracker.trackBackgroundTask(
  1052. {
  1053. id: "call-resume-mixed",
  1054. name: RESUME_WORKFLOW_RUN_TOOL_NAME,
  1055. input: { run_id: "dwfrun-mixed" },
  1056. },
  1057. resumeOutput("dwfrun-mixed"),
  1058. createRootTraceContext({ sessionId: createSessionId("dwf-mixed") }),
  1059. undefined,
  1060. );
  1061. expect(registry.get("dwfrun-mixed")?.parentToolCallId).toBe("call-create-origin");
  1062. });
  1063. // fix 档行为的名字面复验:ResumeWorkflowRun 描述子重臂终态残留条目后,二次结算的通知
  1064. // 不被旧 claim 吞掉。
  1065. it("终态结算后再经 ResumeWorkflowRun 重臂同 runId:通知不被吞(fix 档行为的名字面)", async () => {
  1066. const { deps, notifications, registry, settleTerminal } = makeUnitFixture("dwfrun-cycle");
  1067. const tracker = new BackgroundTaskTracker(deps);
  1068. const toolCall = {
  1069. id: "call-resume-cycle",
  1070. name: RESUME_WORKFLOW_RUN_TOOL_NAME,
  1071. input: { run_id: "dwfrun-cycle" },
  1072. };
  1073. const traceContext = createRootTraceContext({ sessionId: createSessionId("dwf-cycle") });
  1074. await tracker.trackBackgroundTask(
  1075. toolCall,
  1076. resumeOutput("dwfrun-cycle"),
  1077. traceContext,
  1078. undefined,
  1079. );
  1080. settleTerminal({
  1081. runId: "dwfrun-cycle",
  1082. taskId: "dwfrun-cycle",
  1083. startedAt: new Date(),
  1084. status: "cancelled",
  1085. });
  1086. await vi.waitFor(() => {
  1087. expect(notifications).toHaveLength(1);
  1088. });
  1089. await tracker.trackBackgroundTask(
  1090. toolCall,
  1091. resumeOutput("dwfrun-cycle"),
  1092. traceContext,
  1093. undefined,
  1094. );
  1095. settleTerminal({
  1096. runId: "dwfrun-cycle",
  1097. taskId: "dwfrun-cycle",
  1098. startedAt: new Date(),
  1099. status: "completed",
  1100. output: "third life",
  1101. });
  1102. await vi.waitFor(() => {
  1103. expect(notifications).toHaveLength(2);
  1104. });
  1105. expect(notifications[1]!.text).toContain("third life");
  1106. expect(registry.get("dwfrun-cycle")?.status).toBe("completed");
  1107. });
  1108. });
  1109. // ————————————————————————————————————————————————
  1110. // feat 档(2026-09-03,docs/dynamic-workflow/launch.md):中枢直接启动合成的 CreateWorkflow
  1111. // 描述子(input = { name, saved: {...} },id = launch-<uuid>)经同一条 trackBackgroundTask,
  1112. // 产出的终态通知 subject / originMeta 与模型工具路径(input = { name })逐字段同形——不变式 1:
  1113. // 两条路径的 run 对通知不可区分(只在 toolCallId 前缀上可辨)。
  1114. // ————————————————————————————————————————————————
  1115. describe("直接启动合成 toolCall 的通知同形", () => {
  1116. it("launch- 描述子(含 saved 袋)与工具路径产出同一 subject / originMeta", async () => {
  1117. // 工具路径:input.name 决定 subject。
  1118. const tool = makeUnitFixture("dwfrun-parity");
  1119. const toolTracker = new BackgroundTaskTracker(tool.deps);
  1120. await toolTracker.trackBackgroundTask(
  1121. { id: "tool_abc", name: CREATE_WORKFLOW_TOOL_NAME, input: { name: "reporter" } },
  1122. { status: "backgrounded", backgroundTaskId: "dwfrun-parity" },
  1123. createRootTraceContext({ sessionId: createSessionId("dwf-parity-tool") }),
  1124. undefined,
  1125. );
  1126. tool.settleTerminal({
  1127. runId: "dwfrun-parity",
  1128. taskId: "dwfrun-parity",
  1129. startedAt: new Date(),
  1130. status: "completed",
  1131. output: "same artifact",
  1132. });
  1133. await vi.waitFor(() => {
  1134. expect(tool.notifications).toHaveLength(1);
  1135. });
  1136. // 直接启动路径:合成 CreateWorkflow 描述子,input 带 saved 袋,id 为 launch- 前缀。
  1137. const launch = makeUnitFixture("dwfrun-parity-2");
  1138. const launchTracker = new BackgroundTaskTracker(launch.deps);
  1139. const launchCall: ExecutableToolCall = {
  1140. id: "launch-uuid-1",
  1141. name: CREATE_WORKFLOW_TOOL_NAME,
  1142. input: {
  1143. name: "reporter",
  1144. saved: { name: "reporter", scope: "project", args: { pr: "42" } },
  1145. },
  1146. };
  1147. await launchTracker.trackBackgroundTask(
  1148. launchCall,
  1149. { status: "backgrounded", backgroundTaskId: "dwfrun-parity-2" },
  1150. createRootTraceContext({ sessionId: createSessionId("dwf-parity-launch") }),
  1151. undefined,
  1152. );
  1153. launch.settleTerminal({
  1154. runId: "dwfrun-parity-2",
  1155. taskId: "dwfrun-parity-2",
  1156. startedAt: new Date(),
  1157. status: "completed",
  1158. output: "same artifact",
  1159. });
  1160. await vi.waitFor(() => {
  1161. expect(launch.notifications).toHaveLength(1);
  1162. });
  1163. // subject(title)同源:两路都从 input.name 取,与 saved 袋无关。
  1164. const toolMeta = tool.notifications[0]!.originMeta as {
  1165. title?: string;
  1166. backgroundSource?: string;
  1167. };
  1168. const launchMeta = launch.notifications[0]!.originMeta as {
  1169. title?: string;
  1170. backgroundSource?: string;
  1171. };
  1172. expect(launchMeta.title).toBe("reporter");
  1173. expect(launchMeta.title).toBe(toolMeta.title);
  1174. expect(launchMeta.backgroundSource).toBe("workflow");
  1175. expect(launchMeta.backgroundSource).toBe(toolMeta.backgroundSource);
  1176. // 终态 manifest 载荷同形:summary 同源、都 completed。
  1177. expect(terminalMetaOf(launch.notifications[0])).toMatchObject({
  1178. kind: "terminal",
  1179. status: "completed",
  1180. summary: "reporter",
  1181. });
  1182. expect(terminalMetaOf(tool.notifications[0])?.summary).toBe(
  1183. terminalMetaOf(launch.notifications[0])?.summary,
  1184. );
  1185. });
  1186. });
  1187. // 用户取消之后主代理不得自行恢复(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Cancel and resume」 2026-09-09):
  1188. // 停止分支把「谁停的」写进 registry,终态通知据此措辞并给出「不要恢复」的指引。
  1189. describe("用户取消的 run:终态通知说清是谁停的", () => {
  1190. function recordNotifications(runtime: AgentRuntime): string[] {
  1191. const recorded: string[] = [];
  1192. vi.spyOn(runtime, "enqueueBackgroundTaskNotification").mockImplementation(
  1193. (notification: { text: string }) => {
  1194. recorded.push(notification.text);
  1195. },
  1196. );
  1197. return recorded;
  1198. }
  1199. it("GUI 取消(cancelBackgroundTask)→ summary「stopped by the user」+ <stop-reason>user</stop-reason> + 不要恢复的指引", async () => {
  1200. const { runtime, terminal } = makeRuntime("dwf-track-user-cancel");
  1201. const recorded = recordNotifications(runtime);
  1202. await runtime.trackResumedDynamicWorkflowRun({ runId: "dwfrun-1", toolCallId: "call-origin" });
  1203. // GUI / 后台面板唯一走的入口:runtime.cancelBackgroundTask(v4 cancelBackgroundWork)。
  1204. await runtime.cancelBackgroundTask("dwfrun-1");
  1205. terminal.resolve({
  1206. runId: "dwfrun-1",
  1207. taskId: "dwfrun-1",
  1208. startedAt: new Date(),
  1209. status: "cancelled",
  1210. runStatus: "stopped",
  1211. stopReason: "user",
  1212. });
  1213. await vi.waitFor(() => {
  1214. expect(recorded).toHaveLength(1);
  1215. });
  1216. const text = recorded[0]!;
  1217. expect(text).toContain("was stopped by the user.");
  1218. expect(text).toContain("<status>stopped</status>");
  1219. expect(text).toContain("<stop-reason>user</stop-reason>");
  1220. expect(text).toContain("The user stopped this workflow on purpose.");
  1221. expect(text).toMatch(/Do not resume it with ResumeWorkflowRun/);
  1222. // 旧指引那句「resumable as-is」绝不能再出现在用户取消的通知里。
  1223. expect(text).not.toContain("resumable as-is");
  1224. });
  1225. it("模型 TaskStop(initiator model)→「stopped by you」;无 initiator 的停止保持中性措辞", async () => {
  1226. const stoppedByModel = makeRuntime("dwf-track-model-stop");
  1227. const recordedModel = recordNotifications(stoppedByModel.runtime);
  1228. await stoppedByModel.runtime.trackResumedDynamicWorkflowRun({ runId: "dwfrun-1" });
  1229. await stoppedByModel.runtime.stopBackgroundTask("dwfrun-1", { initiator: "model" });
  1230. // 快照不带 stopReason(老端口):registry 的 stopInitiator 仍是兜底。
  1231. stoppedByModel.terminal.resolve({
  1232. runId: "dwfrun-1",
  1233. taskId: "dwfrun-1",
  1234. startedAt: new Date(),
  1235. status: "cancelled",
  1236. });
  1237. await vi.waitFor(() => {
  1238. expect(recordedModel).toHaveLength(1);
  1239. });
  1240. expect(recordedModel[0]).toContain("was stopped by you (TaskStop).");
  1241. expect(recordedModel[0]).toContain("<stop-reason>model</stop-reason>");
  1242. // 为改脚本而停的 run 要当场修订(amend-resume 追记 2026-09-14),指引首句必须先说这个。
  1243. expect(recordedModel[0]).toContain("If you stopped it to fix the script");
  1244. expect(recordedModel[0]).not.toContain("resumable as-is");
  1245. const neutral = makeRuntime("dwf-track-neutral-stop");
  1246. const recordedNeutral = recordNotifications(neutral.runtime);
  1247. await neutral.runtime.trackResumedDynamicWorkflowRun({ runId: "dwfrun-1" });
  1248. neutral.terminal.resolve({
  1249. runId: "dwfrun-1",
  1250. taskId: "dwfrun-1",
  1251. startedAt: new Date(),
  1252. status: "cancelled",
  1253. });
  1254. await vi.waitFor(() => {
  1255. expect(recordedNeutral).toHaveLength(1);
  1256. });
  1257. expect(recordedNeutral[0]).toContain("was stopped.");
  1258. expect(recordedNeutral[0]).not.toContain("<stop-reason>");
  1259. });
  1260. it("重臂(resume 新生命)复位 stopInitiator:上一轮是谁停的与新生命无关", async () => {
  1261. const { runtime, terminal } = makeRuntime("dwf-track-rearm-initiator");
  1262. recordNotifications(runtime);
  1263. const registry = (runtime as unknown as { runtimeTaskRegistry: InMemoryRuntimeTaskRegistry })
  1264. .runtimeTaskRegistry;
  1265. await runtime.trackResumedDynamicWorkflowRun({ runId: "dwfrun-1", toolCallId: "call-origin" });
  1266. await runtime.cancelBackgroundTask("dwfrun-1");
  1267. expect(registry.get("dwfrun-1")?.stopInitiator).toBe("user");
  1268. terminal.resolve({
  1269. runId: "dwfrun-1",
  1270. taskId: "dwfrun-1",
  1271. startedAt: new Date(),
  1272. status: "cancelled",
  1273. });
  1274. await vi.waitFor(() => {
  1275. expect(registry.get("dwfrun-1")?.status).toBe("killed");
  1276. });
  1277. await runtime.trackResumedDynamicWorkflowRun({ runId: "dwfrun-1", toolCallId: "call-origin" });
  1278. expect(registry.get("dwfrun-1")?.status).toBe("running");
  1279. expect(registry.get("dwfrun-1")?.stopInitiator).toBeUndefined();
  1280. });
  1281. });