zcodeProtocolV4WorkflowRuns.test.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. // workflowRuns 状态键 + 事件日志 query 的协议面。
  2. // 见 docs/dynamic-workflow/presentation.md「The run state the pane draws」「事件日志」「v4 线上版本偏斜」。
  3. import { describe, expect, it } from "vitest";
  4. import {
  5. V4_METHODS,
  6. WORKFLOW_RUNS_LIMITS,
  7. workflowRunPhaseSchema,
  8. workflowRunActorSchema,
  9. workflowRunNodeSchema,
  10. workflowRunNodeLastToolSchema,
  11. backgroundWorkSummarySchema,
  12. conversationSnapshotSchema,
  13. statePatchSchema,
  14. v4ConversationWorkflowRunEventsParamsSchema,
  15. v4ConversationWorkflowRunEventsResultSchema,
  16. v4ConversationWorkflowRunSummarySchema,
  17. v4ConversationWorkflowRunsResultSchema,
  18. workflowRunsStateSchema,
  19. PROTOCOL_V4_LIMITS,
  20. WORKFLOW_ARTIFACT_LIMITS,
  21. v4ConversationWorkflowRunArtifactDataParamsSchema,
  22. v4ConversationWorkflowRunArtifactDataResultSchema,
  23. v4ConversationWorkflowRunArtifactReadParamsSchema,
  24. v4ConversationWorkflowRunArtifactReadResultSchema,
  25. v4ConversationWorkflowRunArtifactsParamsSchema,
  26. v4ConversationWorkflowRunArtifactsResultSchema,
  27. workflowRunArtifactSchema,
  28. workflowRunArtifactSummarySchema,
  29. } from "../src/zcode-protocol-v4/index.js";
  30. function run(overrides: Record<string, unknown> = {}) {
  31. return {
  32. runId: "dwfrun-1",
  33. toolCallId: "tc-1",
  34. status: "running" as const,
  35. usage: { spentTokens: 1_200, nodesUsed: 3 },
  36. actors: [
  37. {
  38. siteId: "actor#1",
  39. ordinal: 1,
  40. name: "planner",
  41. sessionId: "sess_dwf-1",
  42. status: "running" as const,
  43. },
  44. ],
  45. nodes: [
  46. {
  47. siteId: "ask#1",
  48. ordinal: 1,
  49. kind: "ask" as const,
  50. phase: "settled" as const,
  51. outcome: "ok" as const,
  52. },
  53. ],
  54. lastEventSequence: 9,
  55. ...overrides,
  56. };
  57. }
  58. describe("workflowRuns 状态键", () => {
  59. it("接受完整的运行态条目并原样回出", () => {
  60. const state = { revision: 3, runs: [run()] };
  61. expect(workflowRunsStateSchema.parse(state)).toEqual(state);
  62. });
  63. it("用量只记已花 token 与步数:没有上限、没有剩余量、没有 budget 键", () => {
  64. // docs/dynamic-workflow/authoring.md:预算构造整体移除,用量是观察面。
  65. const usage = run({ usage: { spentTokens: 42, nodesUsed: 1 } });
  66. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [usage] })).toEqual({
  67. revision: 1,
  68. runs: [usage],
  69. });
  70. // 旧形状的上限键被剥掉(zod 非 strict:旧桌面端与新 agent 之间的偏斜靠剥离而不是整帧丢弃)。
  71. const stale = run({ usage: { spentTokens: 1, nodesUsed: 1, maxNodes: 100, budgetTotal: 10 } });
  72. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [stale] }).runs[0]?.usage).toEqual({
  73. spentTokens: 1,
  74. nodesUsed: 1,
  75. });
  76. // 只有剩余量、没有已花值的形状不成立;`budget` 也不再是一个可替代 `usage` 的键。
  77. for (const invalid of [
  78. run({ usage: { remainingTokens: 1, remainingNodes: 1 } }),
  79. { ...run(), usage: undefined, budget: { spentTokens: 1, nodesUsed: 1 } },
  80. ]) {
  81. expect(() => workflowRunsStateSchema.parse({ revision: 1, runs: [invalid] })).toThrow();
  82. }
  83. });
  84. it("actors 与 nodes 同界:每个节点都属于某个 actor,压低 actors 只会让平常的 fan-out 静默丢子代理", () => {
  85. // 曾是 32:一个 50 路 fan-out 在检视器里少 18 个子代理,而节点表、引擎、图三层都装得下。
  86. expect(WORKFLOW_RUNS_LIMITS.maxActors).toBe(WORKFLOW_RUNS_LIMITS.maxNodes);
  87. });
  88. it("四个数组各有上限,超界即拒(生产侧在超界前置 truncated)", () => {
  89. const many = (count: number, make: (index: number) => unknown) =>
  90. Array.from({ length: count }, (_, index) => make(index));
  91. expect(() =>
  92. workflowRunsStateSchema.parse({
  93. revision: 1,
  94. runs: many(WORKFLOW_RUNS_LIMITS.maxRuns + 1, (index) => run({ runId: `dwfrun-${index}` })),
  95. }),
  96. ).toThrow();
  97. expect(() =>
  98. workflowRunsStateSchema.parse({
  99. revision: 1,
  100. runs: [
  101. run({
  102. actors: many(WORKFLOW_RUNS_LIMITS.maxActors + 1, (index) => ({
  103. siteId: "actor#1",
  104. ordinal: index,
  105. status: "waiting",
  106. })),
  107. }),
  108. ],
  109. }),
  110. ).toThrow();
  111. expect(() =>
  112. workflowRunsStateSchema.parse({
  113. revision: 1,
  114. runs: [
  115. run({
  116. nodes: many(WORKFLOW_RUNS_LIMITS.maxNodes + 1, (index) => ({
  117. siteId: "ask#1",
  118. ordinal: index,
  119. phase: "queued",
  120. })),
  121. }),
  122. ],
  123. }),
  124. ).toThrow();
  125. expect(() =>
  126. workflowRunsStateSchema.parse({
  127. revision: 1,
  128. runs: [
  129. run({
  130. reports: many(WORKFLOW_RUNS_LIMITS.maxReports + 1, (index) => ({
  131. siteId: "report#1",
  132. ordinal: index,
  133. preview: "finding",
  134. })),
  135. }),
  136. ],
  137. }),
  138. ).toThrow();
  139. });
  140. // ── Results 区的数据面(docs/dynamic-workflow/presentation.md「The run pane」)──
  141. it("reports 是渐进产物的有序列表,每条带身份与有界预览", () => {
  142. const withReports = run({
  143. reports: [
  144. { siteId: "report#1", ordinal: 1, preview: "found 3 stale imports" },
  145. { siteId: "report#2", ordinal: 1, preview: '{\n "file": "a.ts"\n}' },
  146. ],
  147. });
  148. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [withReports] })).toEqual({
  149. revision: 1,
  150. runs: [withReports],
  151. });
  152. });
  153. it("reports 零条时整个键缺席,而不是空数组(Results 区据此整区不渲染)", () => {
  154. // 键缺席是合法形状:optional 也正是偏斜安全的那一半——不发 reports 的旧 CLI
  155. // 不会让整个 state.updated patch 在一个已知键上解析失败(偏斜第三档)。
  156. expect(workflowRunsStateSchema.safeParse({ revision: 1, runs: [run()] }).success).toBe(true);
  157. expect(
  158. workflowRunsStateSchema.parse({ revision: 1, runs: [run()] }).runs[0],
  159. ).not.toHaveProperty("reports");
  160. });
  161. it("单条 report 的预览有界(展示预算,不是引擎契约)", () => {
  162. // 引擎的 run 级 report 上限(REPORT_CAPS)是契约;协议线上的 64 条 / 2KB 是**展示**预算。
  163. // 两者不必相等:超出展示界的条目仍在 journal 的 kind="report" 行上。
  164. expect(WORKFLOW_RUNS_LIMITS.maxReports).toBe(64);
  165. expect(
  166. workflowRunsStateSchema.safeParse({
  167. revision: 1,
  168. runs: [
  169. run({
  170. reports: [
  171. {
  172. siteId: "report#1",
  173. ordinal: 1,
  174. preview: "x".repeat(WORKFLOW_RUNS_LIMITS.maxReportPreviewLength + 1),
  175. },
  176. ],
  177. }),
  178. ],
  179. }).success,
  180. ).toBe(false);
  181. });
  182. it("node.kind 可缺省:resume 的 cached 命中只发 node-settled,从不发 node-queued", () => {
  183. // engine.ts:228/232 —— 完结命中短路直接 settled,kind 因此不可观察。
  184. const cached = run({
  185. nodes: [{ siteId: "ask#1", ordinal: 1, phase: "settled", outcome: "ok", cached: true }],
  186. });
  187. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [cached] })).toEqual({
  188. revision: 1,
  189. runs: [cached],
  190. });
  191. });
  192. it("phase 词汇表就是引擎实际发出的七个(executing / waiting 自 v2 起可观察,throttled 已删)", () => {
  193. for (const phase of [
  194. "queued",
  195. "dispatched",
  196. "executing",
  197. "waiting",
  198. "repairing",
  199. "nudged",
  200. "settled",
  201. ]) {
  202. expect(
  203. workflowRunsStateSchema.safeParse({
  204. revision: 1,
  205. runs: [run({ nodes: [{ siteId: "ask#1", ordinal: 1, phase }] })],
  206. }).success,
  207. ).toBe(true);
  208. }
  209. // v1 的 throttled 相位已由 waiting 取代(docs/dynamic-workflow/concurrency.md「Protocol state」)。
  210. expect(
  211. workflowRunsStateSchema.safeParse({
  212. revision: 1,
  213. runs: [run({ nodes: [{ siteId: "ask#1", ordinal: 1, phase: "throttled" }] })],
  214. }).success,
  215. ).toBe(false);
  216. });
  217. it("resultPreview 有界", () => {
  218. expect(
  219. workflowRunsStateSchema.safeParse({
  220. revision: 1,
  221. runs: [
  222. run({
  223. status: "completed",
  224. resultPreview: "x".repeat(WORKFLOW_RUNS_LIMITS.maxResultPreviewLength + 1),
  225. }),
  226. ],
  227. }).success,
  228. ).toBe(false);
  229. });
  230. it("进 statePatch 与 cold snapshot 两处(漏一处即静默丢运行态)", () => {
  231. const patch = statePatchSchema.parse({
  232. revision: 5,
  233. workflowRuns: { revision: 2, runs: [run()] },
  234. });
  235. expect(patch.workflowRuns?.runs[0]?.runId).toBe("dwfrun-1");
  236. expect(conversationSnapshotSchema.shape.workflowRuns).toBeDefined();
  237. });
  238. });
  239. describe("v4 版本偏斜:状态键 vs 行内枚举的不对称", () => {
  240. it("旧桌面的 non-strict statePatch 容器只丢掉未知键,保住其余键", () => {
  241. // 这条是先例记录:workflowRuns 之所以不需要偏斜防御,正因为容器不 strict。
  242. const parsed = statePatchSchema.parse({ revision: 7, unknownFutureKey: { a: 1 } });
  243. expect(parsed.revision).toBe(7);
  244. expect(parsed).not.toHaveProperty("unknownFutureKey");
  245. });
  246. it("backgroundWorks.kind 加宽到 workflow(闭集,旧桌面会整帧拒收——见 spec 偏斜行)", () => {
  247. const work = {
  248. workId: "dwfrun-1",
  249. kind: "workflow" as const,
  250. title: "workflow run",
  251. status: "running" as const,
  252. startedAt: 1_700_000_000_000,
  253. anchorRowId: null,
  254. };
  255. expect(backgroundWorkSummarySchema.parse(work)).toEqual(work);
  256. });
  257. });
  258. describe("v4 conversation workflowRunEvents query", () => {
  259. it("声明一个只读、无状态、超时重发安全的分页 query", () => {
  260. expect(V4_METHODS.conversationWorkflowRunEvents).toBe("v4/conversation/workflowRunEvents");
  261. expect(
  262. v4ConversationWorkflowRunEventsParamsSchema.parse({
  263. sessionId: "session-1",
  264. runId: "dwfrun-1",
  265. afterSequence: 4,
  266. limit: 50,
  267. }),
  268. ).toEqual({ sessionId: "session-1", runId: "dwfrun-1", afterSequence: 4, limit: 50 });
  269. // cursor 是可选的(缺省从头取),但未知字段一律拒收。
  270. expect(
  271. v4ConversationWorkflowRunEventsParamsSchema.parse({ sessionId: "s", runId: "r" }),
  272. ).toEqual({ sessionId: "s", runId: "r" });
  273. expect(() =>
  274. v4ConversationWorkflowRunEventsParamsSchema.parse({
  275. sessionId: "s",
  276. runId: "r",
  277. cwd: "/repo",
  278. }),
  279. ).toThrow();
  280. });
  281. it("**刻意不带** atSeq / atLogEpoch —— journal cursor 永不失效,没有陈旧可防", () => {
  282. // 同族的 rows/range 与 plans 带这两个字段做陈旧读防护,因为它们读 conversation projection,
  283. // 而 rowId 只在一个 log epoch 内有意义。本 query 读 journal:sequence 只追加、跨 resume
  284. // 从既有最大值继续、编号不变(journal 契约测证明),所以 (runId, sequence) cursor 永远有效。
  285. // 带上它反而有害:一次与 run 无关的会话 rewind 会让详情页丢掉合法的 journal 页。
  286. expect(Object.keys(v4ConversationWorkflowRunEventsResultSchema.shape).sort()).toEqual([
  287. "events",
  288. "hasMore",
  289. ]);
  290. // strict:多带一个字段直接拒收,所以"以后顺手加上 atLogEpoch"会先在这里红。
  291. expect(
  292. v4ConversationWorkflowRunEventsResultSchema.safeParse({
  293. events: [],
  294. hasMore: false,
  295. atLogEpoch: "epoch-1",
  296. }).success,
  297. ).toBe(false);
  298. });
  299. it("结果携带事件页与 hasMore(cursor 语义在 journal 契约测里证明)", () => {
  300. const result = {
  301. events: [{ sequence: 5, type: "node-settled", payload: { outcome: "ok" } }],
  302. hasMore: false,
  303. };
  304. expect(v4ConversationWorkflowRunEventsResultSchema.parse(result)).toEqual(result);
  305. expect(() =>
  306. v4ConversationWorkflowRunEventsResultSchema.parse({ ...result, events: undefined }),
  307. ).toThrow();
  308. });
  309. });
  310. // ── dwf run 枚举 query 的摘要形状(docs/dynamic-workflow/launch.md「`/dwf`」)──
  311. // 新增的 label / updatedAt 是 additive optional:老 CLI 不发这两个键,读侧回落 runId 与
  312. // 「不显示时间」。这里钉住的正是那个偏斜姿态——schema 两侧同一个模块(服务端
  313. // v4-gateway.parse 与桌面 zcodeAgentService.parse 共用),加可选键不破任何一侧。
  314. describe("v4 conversation workflowRuns query 的 run 摘要", () => {
  315. function summary(overrides: Record<string, unknown> = {}) {
  316. return {
  317. runId: "dwfrun-1",
  318. status: "running" as const,
  319. resumable: false,
  320. ...overrides,
  321. };
  322. }
  323. it("最小摘要(无 label / updatedAt)照旧通过——老服务端的形状", () => {
  324. const minimal = summary();
  325. expect(v4ConversationWorkflowRunSummarySchema.parse(minimal)).toEqual(minimal);
  326. });
  327. it("label 与 updatedAt 可选且原样透传", () => {
  328. const full = summary({
  329. toolCallId: "tc-1",
  330. label: "nightly audit",
  331. updatedAt: 1_755_000_000_000,
  332. status: "stopped" as const,
  333. stopReason: "interrupted" as const,
  334. failureCode: "Interrupted",
  335. failureMessage: "owning process exited",
  336. resumable: true,
  337. });
  338. expect(v4ConversationWorkflowRunSummarySchema.parse(full)).toEqual(full);
  339. });
  340. it("lineage 两键可选:修订出来的 run 带 resumedFrom,被替代的 run 带 supersededBy(docs/dynamic-workflow/presentation.md「The run card」)", () => {
  341. // 2026-09-14 实测:这份 strict schema 少了这两个键 + superseded 一词,桌面端整页 run 目录被拒
  342. // (「读取 run 摘要失败」),任务岛的已结束计数随之空白。钉住:成功者与被替代者都能过。
  343. const successor = summary({ resumedFrom: "dwfrun-predecessor" });
  344. expect(v4ConversationWorkflowRunSummarySchema.parse(successor)).toEqual(successor);
  345. const predecessor = summary({
  346. status: "stopped",
  347. stopReason: "superseded",
  348. supersededBy: "dwfrun-successor",
  349. resumable: false,
  350. });
  351. expect(v4ConversationWorkflowRunSummarySchema.parse(predecessor)).toEqual(predecessor);
  352. expect(
  353. v4ConversationWorkflowRunSummarySchema.safeParse(summary({ resumedFrom: "" })).success,
  354. ).toBe(false);
  355. });
  356. it("status 是三终态词汇;stopReason 五值可选(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md)", () => {
  357. for (const status of ["completed", "errored", "pending", "running", "stopped"] as const) {
  358. expect(v4ConversationWorkflowRunSummarySchema.safeParse(summary({ status })).success).toBe(
  359. true,
  360. );
  361. }
  362. for (const status of ["failed", "cancelled"]) {
  363. expect(v4ConversationWorkflowRunSummarySchema.safeParse(summary({ status })).success).toBe(
  364. false,
  365. );
  366. }
  367. for (const stopReason of ["user", "model", "provider", "interrupted", "superseded"]) {
  368. expect(
  369. v4ConversationWorkflowRunSummarySchema.safeParse(summary({ status: "stopped", stopReason }))
  370. .success,
  371. ).toBe(true);
  372. }
  373. expect(
  374. v4ConversationWorkflowRunSummarySchema.safeParse(
  375. summary({ status: "stopped", stopReason: "crash" }),
  376. ).success,
  377. ).toBe(false);
  378. });
  379. it("label 拒空串、updatedAt 拒负数与小数(时间是 epoch 毫秒整数)", () => {
  380. expect(v4ConversationWorkflowRunSummarySchema.safeParse(summary({ label: "" })).success).toBe(
  381. false,
  382. );
  383. expect(
  384. v4ConversationWorkflowRunSummarySchema.safeParse(summary({ updatedAt: -1 })).success,
  385. ).toBe(false);
  386. expect(
  387. v4ConversationWorkflowRunSummarySchema.safeParse(summary({ updatedAt: 1.5 })).success,
  388. ).toBe(false);
  389. });
  390. it("schema 是 strict:未知键仍然拒绝(加字段必须走 schema,不能靠透传)", () => {
  391. expect(
  392. v4ConversationWorkflowRunSummarySchema.safeParse(summary({ notAField: 1 })).success,
  393. ).toBe(false);
  394. });
  395. it("结果包裹 runs 数组,最近更新在前由存储层负责", () => {
  396. const result = {
  397. runs: [summary({ label: "a", updatedAt: 2 }), summary({ runId: "dwfrun-2" })],
  398. };
  399. expect(v4ConversationWorkflowRunsResultSchema.parse(result)).toEqual(result);
  400. });
  401. });
  402. // ── 用户面产物(docs/dynamic-workflow/authoring.md「How the user sees them」)─────────────────
  403. // ⚠ 术语:本节的 artifact 是脚本经 `artifact.*` 发布给**用户**看的产出,与
  404. // `serializeWorkflowArtifact`(引擎内部对「脚本顶层返回值」的叫法,给模型看)无关。
  405. describe("workflowRuns[].artifacts 状态键", () => {
  406. const summary = (overrides: Record<string, unknown> = {}) => ({
  407. id: "book",
  408. kind: "file" as const,
  409. title: "注意力之书",
  410. version: 2,
  411. contentType: "application/pdf",
  412. bytes: 4_194_304,
  413. itemCount: 0,
  414. ...overrides,
  415. });
  416. it("摘要元素只带最新版元数据:spec / versions / uri / sourcePath 一律拒收", () => {
  417. expect(workflowRunArtifactSummarySchema.parse(summary())).toEqual(summary());
  418. // strict:把全量元数据顺手塞进高频状态键会先在这里红。
  419. for (const extra of [
  420. { spec: { x: { field: "round" } } },
  421. { versions: [{ version: 1, publishedAt: 1 }] },
  422. { uri: "zcode-artifact://s/a" },
  423. { sourcePath: "out/book.pdf" },
  424. { description: "一本书" },
  425. ]) {
  426. expect(workflowRunArtifactSummarySchema.safeParse({ ...summary(), ...extra }).success).toBe(
  427. false,
  428. );
  429. }
  430. });
  431. it("kind 是六成员闭集;title / contentType / bytes / itemCount 全可缺席", () => {
  432. for (const kind of ["file", "markdown", "chart", "table", "metrics", "board"]) {
  433. expect(workflowRunArtifactSummarySchema.parse({ id: "x", kind, version: 1 })).toEqual({
  434. id: "x",
  435. kind,
  436. version: 1,
  437. });
  438. }
  439. expect(
  440. workflowRunArtifactSummarySchema.safeParse({ id: "x", kind: "spreadsheet", version: 1 })
  441. .success,
  442. ).toBe(false);
  443. });
  444. it("primary 是可选的字面量 true(交付物;docs/dynamic-workflow/authoring.md「Ids, tags and versions」)", () => {
  445. expect(workflowRunArtifactSummarySchema.parse(summary({ primary: true }))).toEqual(
  446. summary({ primary: true }),
  447. );
  448. // 不是交付物 = 键缺席,不是 false:三处 schema 同一约定,UI 只判 `=== true`。
  449. expect(workflowRunArtifactSummarySchema.safeParse(summary({ primary: false })).success).toBe(
  450. false,
  451. );
  452. expect(workflowRunArtifactSummarySchema.safeParse(summary({ primary: "yes" })).success).toBe(
  453. false,
  454. );
  455. });
  456. it("artifacts 是 optional(老 CLI 不发这个键的整帧仍可解析——偏斜第三档)", () => {
  457. // 这是这个字段 optional 的全部理由:往已有状态键上加必填字段,会让任何一个不发它的旧
  458. // CLI 的 state.updated patch 整帧被丢,而不是少一个键。
  459. const { artifacts: _omitted, ...withoutKey } = { ...run(), artifacts: [summary()] };
  460. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [withoutKey] })).toEqual({
  461. revision: 1,
  462. runs: [withoutKey],
  463. });
  464. const withKey = { ...run(), artifacts: [summary()] };
  465. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [withKey] })).toEqual({
  466. revision: 1,
  467. runs: [withKey],
  468. });
  469. });
  470. it("artifacts 有界 32(= 引擎的 ARTIFACT_CAPS.maxArtifactsPerRun,不另设更低的展示预算)", () => {
  471. expect(WORKFLOW_RUNS_LIMITS.maxArtifacts).toBe(32);
  472. const many = Array.from({ length: WORKFLOW_RUNS_LIMITS.maxArtifacts + 1 }, (_value, index) =>
  473. summary({ id: `a${index}` }),
  474. );
  475. expect(
  476. workflowRunsStateSchema.safeParse({ revision: 1, runs: [{ ...run(), artifacts: many }] })
  477. .success,
  478. ).toBe(false);
  479. });
  480. it("reports 元素长出可选的 artifactId(打标签的条目仍进 reports——一条通道一套上限)", () => {
  481. const tagged = {
  482. ...run(),
  483. reports: [{ siteId: "report#1", ordinal: 1, preview: "{}", artifactId: "perf" }],
  484. };
  485. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [tagged] })).toEqual({
  486. revision: 1,
  487. runs: [tagged],
  488. });
  489. const untagged = { ...run(), reports: [{ siteId: "report#1", ordinal: 1, preview: "{}" }] };
  490. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [untagged] })).toEqual({
  491. revision: 1,
  492. runs: [untagged],
  493. });
  494. });
  495. });
  496. describe("v4 conversation workflowRunArtifacts query", () => {
  497. const version = (overrides: Record<string, unknown> = {}) => ({
  498. version: 1,
  499. title: "注意力之书",
  500. contentType: "application/pdf",
  501. bytes: 4_194_304,
  502. uri: "zcode-artifact://session-1/tool-result-abc",
  503. sourcePath: "out/book.pdf",
  504. publishedAt: 1_756_100_000_000,
  505. ...overrides,
  506. });
  507. it("声明一个只读、无状态、超时重发安全的清单 query", () => {
  508. expect(V4_METHODS.conversationWorkflowRunArtifacts).toBe(
  509. "v4/conversation/workflowRunArtifacts",
  510. );
  511. expect(
  512. v4ConversationWorkflowRunArtifactsParamsSchema.parse({ sessionId: "s", runId: "r" }),
  513. ).toEqual({
  514. sessionId: "s",
  515. runId: "r",
  516. });
  517. expect(
  518. v4ConversationWorkflowRunArtifactsParamsSchema.safeParse({
  519. sessionId: "s",
  520. runId: "r",
  521. limit: 5,
  522. }).success,
  523. ).toBe(false);
  524. });
  525. it("元素带全部版本(升序)与 itemCount——这是冷恢复与中枢详情的 durable 读法", () => {
  526. const artifact = {
  527. id: "book",
  528. kind: "file" as const,
  529. title: "注意力之书",
  530. description: "59 页",
  531. contentType: "application/pdf",
  532. sourcePath: "out/book.pdf",
  533. version: 2,
  534. versions: [version(), version({ version: 2, bytes: 5_000_000 })],
  535. itemCount: 0,
  536. };
  537. expect(workflowRunArtifactSchema.parse(artifact)).toEqual(artifact);
  538. expect(v4ConversationWorkflowRunArtifactsResultSchema.parse({ artifacts: [artifact] })).toEqual(
  539. { artifacts: [artifact] },
  540. );
  541. // strict 两层:结果与元素都拒收未知字段。
  542. expect(
  543. v4ConversationWorkflowRunArtifactsResultSchema.safeParse({
  544. artifacts: [artifact],
  545. hasMore: false,
  546. }).success,
  547. ).toBe(false);
  548. });
  549. it("primary 在版本项与顶层都可带(引擎按 id 粘着盖章;投影抬到顶层),且只能是 true", () => {
  550. const artifact = {
  551. id: "report",
  552. kind: "markdown" as const,
  553. version: 2,
  554. versions: [version({ primary: true }), version({ version: 2, primary: true })],
  555. itemCount: 0,
  556. primary: true as const,
  557. };
  558. expect(workflowRunArtifactSchema.parse(artifact)).toEqual(artifact);
  559. expect(workflowRunArtifactSchema.safeParse({ ...artifact, primary: false }).success).toBe(false);
  560. expect(
  561. workflowRunArtifactSchema.safeParse({ ...artifact, versions: [version({ primary: false })] })
  562. .success,
  563. ).toBe(false);
  564. });
  565. it("publishedAt 必填:driver 恒写入,缺席即让「版本没有时刻」在协议边界上就红", () => {
  566. const { publishedAt: _dropped, ...withoutTime } = version();
  567. expect(
  568. workflowRunArtifactSchema.safeParse({
  569. id: "book",
  570. kind: "file",
  571. version: 1,
  572. versions: [withoutTime],
  573. itemCount: 0,
  574. }).success,
  575. ).toBe(false);
  576. });
  577. it("预置看板带 spec、不带字节;版本数与 id 长度按 ARTIFACT_CAPS 有界", () => {
  578. const board = {
  579. id: "perf",
  580. kind: "chart" as const,
  581. spec: { x: { field: "round" }, y: { field: "queryMs" } },
  582. version: 1,
  583. versions: [{ version: 1, spec: { x: { field: "round" } }, publishedAt: 1 }],
  584. itemCount: 12,
  585. };
  586. expect(workflowRunArtifactSchema.parse(board)).toEqual(board);
  587. expect(WORKFLOW_ARTIFACT_LIMITS.maxVersions).toBe(16);
  588. expect(
  589. workflowRunArtifactSchema.safeParse({
  590. ...board,
  591. versions: Array.from({ length: 17 }, (_v, index) => ({
  592. version: index + 1,
  593. publishedAt: 1,
  594. })),
  595. }).success,
  596. ).toBe(false);
  597. expect(workflowRunArtifactSchema.safeParse({ ...board, id: "x".repeat(65) }).success).toBe(
  598. false,
  599. );
  600. });
  601. });
  602. describe("v4 conversation workflowRunArtifactData query", () => {
  603. it("声明看板的取数面:cursor = journal sequence,limit 钳在 500", () => {
  604. expect(V4_METHODS.conversationWorkflowRunArtifactData).toBe(
  605. "v4/conversation/workflowRunArtifactData",
  606. );
  607. const params = {
  608. sessionId: "s",
  609. runId: "r",
  610. artifactId: "perf",
  611. afterSequence: 12,
  612. limit: 200,
  613. };
  614. expect(v4ConversationWorkflowRunArtifactDataParamsSchema.parse(params)).toEqual(params);
  615. expect(
  616. v4ConversationWorkflowRunArtifactDataParamsSchema.parse({
  617. sessionId: "s",
  618. runId: "r",
  619. artifactId: "perf",
  620. }),
  621. ).toEqual({
  622. sessionId: "s",
  623. runId: "r",
  624. artifactId: "perf",
  625. });
  626. expect(WORKFLOW_ARTIFACT_LIMITS.defaultItemsPerPage).toBe(200);
  627. expect(WORKFLOW_ARTIFACT_LIMITS.maxItemsPerPage).toBe(500);
  628. expect(
  629. v4ConversationWorkflowRunArtifactDataParamsSchema.safeParse({ ...params, limit: 501 })
  630. .success,
  631. ).toBe(false);
  632. expect(
  633. v4ConversationWorkflowRunArtifactDataParamsSchema.safeParse({ ...params, limit: 0 }).success,
  634. ).toBe(false);
  635. });
  636. it("条目带**原值**而不是预览文本:看板的纯函数要按字段路径取数", () => {
  637. // preview 化(string 原样、其余 pretty JSON)是 Results 区那一行的契约。看板要读
  638. // spec.x.field 形如 "timing.after" 的路径,拿到一段 JSON 文本就取不出来了。
  639. const result = {
  640. items: [
  641. { sequence: 12, siteId: "report#1", ordinal: 3, item: { round: 3, timing: { after: 41 } } },
  642. { sequence: 15, siteId: "report#1", ordinal: 4, item: null },
  643. ],
  644. hasMore: true,
  645. };
  646. expect(v4ConversationWorkflowRunArtifactDataResultSchema.parse(result)).toEqual(result);
  647. expect(
  648. v4ConversationWorkflowRunArtifactDataResultSchema.safeParse({
  649. items: [],
  650. hasMore: false,
  651. nextSequence: 3,
  652. }).success,
  653. ).toBe(false);
  654. expect(
  655. v4ConversationWorkflowRunArtifactDataResultSchema.safeParse({
  656. items: [{ sequence: 1, siteId: "report#1", ordinal: 0, item: 1, extra: true }],
  657. hasMore: false,
  658. }).success,
  659. ).toBe(false);
  660. });
  661. });
  662. describe("v4 conversation workflowRunArtifactRead query", () => {
  663. it("逐字照 attachmentRead:≤ 512 KiB 一块,复用同一个常量而不另铸", () => {
  664. expect(V4_METHODS.conversationWorkflowRunArtifactRead).toBe(
  665. "v4/conversation/workflowRunArtifactRead",
  666. );
  667. const params = {
  668. sessionId: "s",
  669. runId: "r",
  670. artifactId: "book",
  671. version: 1,
  672. offset: 0,
  673. limit: PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes,
  674. };
  675. expect(v4ConversationWorkflowRunArtifactReadParamsSchema.parse(params)).toEqual(params);
  676. expect(
  677. v4ConversationWorkflowRunArtifactReadParamsSchema.safeParse({
  678. ...params,
  679. limit: PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes + 1,
  680. }).success,
  681. ).toBe(false);
  682. // version 必填且为正整数:授权链按 (artifactId, version) 在 journal 找 completed 行。
  683. expect(
  684. v4ConversationWorkflowRunArtifactReadParamsSchema.safeParse({ ...params, version: 0 })
  685. .success,
  686. ).toBe(false);
  687. const { version: _dropped, ...withoutVersion } = params;
  688. expect(
  689. v4ConversationWorkflowRunArtifactReadParamsSchema.safeParse(withoutVersion).success,
  690. ).toBe(false);
  691. });
  692. it("结果按块携带 base64 与总字节;解码超块界、nextOffset 越界都拒收", () => {
  693. const result = {
  694. dataBase64: "aGVsbG8=",
  695. mediaType: "application/pdf",
  696. totalBytes: 5,
  697. nextOffset: null,
  698. };
  699. expect(v4ConversationWorkflowRunArtifactReadResultSchema.parse(result)).toEqual(result);
  700. expect(
  701. v4ConversationWorkflowRunArtifactReadResultSchema.safeParse({
  702. ...result,
  703. dataBase64: "not base64!",
  704. }).success,
  705. ).toBe(false);
  706. expect(
  707. v4ConversationWorkflowRunArtifactReadResultSchema.safeParse({ ...result, nextOffset: 9 })
  708. .success,
  709. ).toBe(false);
  710. expect(
  711. v4ConversationWorkflowRunArtifactReadResultSchema.safeParse({
  712. ...result,
  713. totalBytes: PROTOCOL_V4_LIMITS.attachmentMaxBytes + 1,
  714. }).success,
  715. ).toBe(false);
  716. });
  717. it("mediaType **不**限死在 image/video/pdf——限死会让 markdown 与 office 文件整条读不出来", () => {
  718. // attachmentRead 那条 refine 是为已发送消息的预览面写的;产物的合法类型是 driver 那张
  719. // 17 项扩展名表加 application/octet-stream。
  720. for (const mediaType of [
  721. "text/markdown",
  722. "text/html",
  723. "text/csv",
  724. "application/octet-stream",
  725. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  726. ]) {
  727. expect(
  728. v4ConversationWorkflowRunArtifactReadResultSchema.safeParse({
  729. dataBase64: "aGVsbG8=",
  730. mediaType,
  731. totalBytes: 5,
  732. nextOffset: null,
  733. }).success,
  734. ).toBe(true);
  735. }
  736. });
  737. });
  738. // ── 阶段进入记录(docs/dynamic-workflow/presentation.md)──────────
  739. describe("workflowRuns[].phases / currentPhase 状态键", () => {
  740. it("phases 与 currentPhase 都是 optional(老 CLI 不发它们的整帧仍可解析)", () => {
  741. const bare = run();
  742. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [bare] })).toEqual({
  743. revision: 1,
  744. runs: [bare],
  745. });
  746. const withKeys = { ...run(), phases: [{ name: "plan", rounds: 2 }], currentPhase: "plan" };
  747. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [withKeys] })).toEqual({
  748. revision: 1,
  749. runs: [withKeys],
  750. });
  751. });
  752. it("名字非空且 ≤ 128;rounds 是正整数;条数 ≤ 32", () => {
  753. const ok = { name: "x".repeat(WORKFLOW_RUNS_LIMITS.maxPhaseNameLength), rounds: 1 };
  754. expect(workflowRunPhaseSchema.parse(ok)).toEqual(ok);
  755. expect(workflowRunPhaseSchema.safeParse({ name: "", rounds: 1 }).success).toBe(false);
  756. expect(workflowRunPhaseSchema.safeParse({ name: "x".repeat(129), rounds: 1 }).success).toBe(
  757. false,
  758. );
  759. expect(workflowRunPhaseSchema.safeParse({ name: "x", rounds: 0 }).success).toBe(false);
  760. const tooMany = Array.from({ length: WORKFLOW_RUNS_LIMITS.maxPhases + 1 }, (_, i) => ({
  761. name: `p${i}`,
  762. rounds: 1,
  763. }));
  764. expect(
  765. workflowRunsStateSchema.safeParse({ revision: 1, runs: [{ ...run(), phases: tooMany }] })
  766. .success,
  767. ).toBe(false);
  768. });
  769. });
  770. // ── 实例的出生阶段坐标(docs/dynamic-workflow/presentation.md)──────
  771. describe("workflowRuns[].actors/nodes 的 phaseName 状态键", () => {
  772. it("actor 与 node 上都是 optional(不发它的旧 CLI 整帧仍可解析)", () => {
  773. const bare = run();
  774. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [bare] })).toEqual({
  775. revision: 1,
  776. runs: [bare],
  777. });
  778. const stamped = {
  779. ...run(),
  780. actors: [{ ...run().actors[0], phaseName: "调查" }],
  781. nodes: [{ ...run().nodes[0], phaseName: "调查" }],
  782. };
  783. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [stamped] })).toEqual({
  784. revision: 1,
  785. runs: [stamped],
  786. });
  787. });
  788. it("名字非空且 ≤ 128:与 phases[].name 同一条界(UI 按名字关联两边)", () => {
  789. const limit = WORKFLOW_RUNS_LIMITS.maxPhaseNameLength;
  790. const actor = { siteId: "actor#1", ordinal: 1, status: "running" as const };
  791. const node = { siteId: "ask#1", ordinal: 1, phase: "settled" as const };
  792. expect(
  793. workflowRunActorSchema.safeParse({ ...actor, phaseName: "x".repeat(limit) }).success,
  794. ).toBe(true);
  795. expect(
  796. workflowRunActorSchema.safeParse({ ...actor, phaseName: "x".repeat(limit + 1) }).success,
  797. ).toBe(false);
  798. expect(workflowRunActorSchema.safeParse({ ...actor, phaseName: "" }).success).toBe(false);
  799. expect(
  800. workflowRunNodeSchema.safeParse({ ...node, phaseName: "x".repeat(limit) }).success,
  801. ).toBe(true);
  802. expect(
  803. workflowRunNodeSchema.safeParse({ ...node, phaseName: "x".repeat(limit + 1) }).success,
  804. ).toBe(false);
  805. expect(workflowRunNodeSchema.safeParse({ ...node, phaseName: "" }).success).toBe(false);
  806. });
  807. it("phaseName 与节点生命周期 phase 是两个键,可以同时在场", () => {
  808. const parsed = workflowRunNodeSchema.parse({
  809. siteId: "ask#1",
  810. ordinal: 37,
  811. phase: "settled",
  812. phaseName: "第三阶段",
  813. });
  814. expect(parsed.phase).toBe("settled");
  815. expect(parsed.phaseName).toBe("第三阶段");
  816. });
  817. });
  818. // ── 一次 ask 的任务与进度读数(docs/dynamic-workflow/presentation.md)──────
  819. describe("workflowRuns[].nodes 的 instructionsHead / turn / toolCalls / lastTool", () => {
  820. const node = { siteId: "ask#1", ordinal: 1, phase: "executing" as const };
  821. it("四个键都是 optional:不发它们的旧 CLI 整帧仍可解析,原样回出", () => {
  822. const bare = run();
  823. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [bare] })).toEqual({
  824. revision: 1,
  825. runs: [bare],
  826. });
  827. const reported = {
  828. ...run(),
  829. nodes: [
  830. {
  831. ...node,
  832. kind: "ask" as const,
  833. instructionsHead: "读一遍 docs/dynamic-workflow 并列出过时的段落",
  834. turn: 3,
  835. toolCalls: 12,
  836. lastTool: { name: "Read", target: "docs/dynamic-workflow/presentation.md" },
  837. },
  838. ],
  839. };
  840. expect(workflowRunsStateSchema.parse({ revision: 1, runs: [reported] })).toEqual({
  841. revision: 1,
  842. runs: [reported],
  843. });
  844. });
  845. it("instructionsHead 非空且 ≤ 240(与引擎侧 INSTRUCTIONS_HEAD_MAX_CHARS 同值)", () => {
  846. const limit = WORKFLOW_RUNS_LIMITS.maxInstructionsHeadLength;
  847. expect(limit).toBe(240);
  848. expect(
  849. workflowRunNodeSchema.safeParse({ ...node, instructionsHead: "x".repeat(limit) }).success,
  850. ).toBe(true);
  851. expect(
  852. workflowRunNodeSchema.safeParse({ ...node, instructionsHead: "x".repeat(limit + 1) }).success,
  853. ).toBe(false);
  854. expect(workflowRunNodeSchema.safeParse({ ...node, instructionsHead: "" }).success).toBe(false);
  855. });
  856. it("turn 是正整数、toolCalls 是非负整数:0 轮次不存在,0 次工具调用是事实", () => {
  857. expect(workflowRunNodeSchema.safeParse({ ...node, turn: 1, toolCalls: 0 }).success).toBe(true);
  858. expect(workflowRunNodeSchema.safeParse({ ...node, turn: 0 }).success).toBe(false);
  859. expect(workflowRunNodeSchema.safeParse({ ...node, turn: 1.5 }).success).toBe(false);
  860. expect(workflowRunNodeSchema.safeParse({ ...node, toolCalls: -1 }).success).toBe(false);
  861. expect(workflowRunNodeSchema.safeParse({ ...node, toolCalls: 2.5 }).success).toBe(false);
  862. });
  863. it("lastTool:工具名必填 ≤ 64,target 可缺席 ≤ 120(放得下路径或命令头,放不下参数全文)", () => {
  864. const names = WORKFLOW_RUNS_LIMITS.maxLastToolNameLength;
  865. const targets = WORKFLOW_RUNS_LIMITS.maxLastToolTargetLength;
  866. expect([names, targets]).toEqual([64, 120]);
  867. expect(workflowRunNodeLastToolSchema.parse({ name: "Bash" })).toEqual({ name: "Bash" });
  868. expect(
  869. workflowRunNodeLastToolSchema.safeParse({
  870. name: "x".repeat(names),
  871. target: "y".repeat(targets),
  872. }).success,
  873. ).toBe(true);
  874. expect(workflowRunNodeLastToolSchema.safeParse({ name: "x".repeat(names + 1) }).success).toBe(
  875. false,
  876. );
  877. expect(
  878. workflowRunNodeLastToolSchema.safeParse({ name: "Bash", target: "y".repeat(targets + 1) })
  879. .success,
  880. ).toBe(false);
  881. expect(workflowRunNodeLastToolSchema.safeParse({ name: "" }).success).toBe(false);
  882. expect(workflowRunNodeLastToolSchema.safeParse({ target: "a.ts" }).success).toBe(false);
  883. });
  884. it("生命周期 phase 与这些读数可以同时在场:settled 的节点也留着它跑完时的读数", () => {
  885. const parsed = workflowRunNodeSchema.parse({
  886. siteId: "ask#1",
  887. ordinal: 4,
  888. phase: "settled",
  889. outcome: "ok",
  890. instructionsHead: "写一份回归测试",
  891. turn: 6,
  892. toolCalls: 21,
  893. lastTool: { name: "Edit", target: "packages/shared/test/x.test.ts" },
  894. });
  895. expect(parsed.phase).toBe("settled");
  896. expect(parsed.turn).toBe(6);
  897. });
  898. });