zcodeProtocolV4WorkflowRuns.test.ts 34 KB

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