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

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