tool-result-metadata.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. import {
  2. createWorkflowToolResultDisplayPayloadSchema,
  3. parseCompletedToolPartMetadata,
  4. parseToolResultDisplayPayload,
  5. respondToCoordinatorToolResultDisplayPayloadSchema,
  6. taskOutputToolResultDisplayPayloadSchema,
  7. toolResultDisplayPayloadSchema,
  8. } from "../src/tools/tool-result-metadata.js";
  9. import { CreateWorkflowCausalityGraphSchema } from "../src/tools/create-workflow.js";
  10. import {
  11. getWorkflowRunToolResultDisplayPayloadSchema,
  12. resumeWorkflowRunToolResultDisplayPayloadSchema,
  13. } from "../src/tools/workflow-observation-display.js";
  14. import { describe, expect, it } from "vitest";
  15. describe("tool result display metadata", () => {
  16. it("accepts the bounded TaskOutput UI projection", () => {
  17. const display = {
  18. kind: "task_output",
  19. retrievalStatus: "not_ready",
  20. taskStatus: "running",
  21. output: "partial output",
  22. truncated: true,
  23. } as const;
  24. expect(taskOutputToolResultDisplayPayloadSchema.parse(display)).toEqual(display);
  25. expect(parseToolResultDisplayPayload(display)).toEqual(display);
  26. });
  27. it("rejects oversized or extra TaskOutput display fields", () => {
  28. expect(
  29. taskOutputToolResultDisplayPayloadSchema.safeParse({
  30. kind: "task_output",
  31. retrievalStatus: "success",
  32. taskStatus: "x".repeat(65),
  33. }).success,
  34. ).toBe(false);
  35. expect(
  36. taskOutputToolResultDisplayPayloadSchema.safeParse({
  37. kind: "task_output",
  38. retrievalStatus: "success",
  39. output: "x".repeat(2_001),
  40. }).success,
  41. ).toBe(false);
  42. expect(
  43. taskOutputToolResultDisplayPayloadSchema.safeParse({
  44. kind: "task_output",
  45. retrievalStatus: "success",
  46. description: "must not cross the UI display boundary",
  47. }).success,
  48. ).toBe(false);
  49. });
  50. it.each(["success", "failed"] as const)(
  51. "accepts RespondToCoordinator %s without response content",
  52. (status) => {
  53. const display = {
  54. kind: "respond_to_coordinator",
  55. status,
  56. } as const;
  57. expect(respondToCoordinatorToolResultDisplayPayloadSchema.parse(display)).toEqual(display);
  58. expect(parseToolResultDisplayPayload(display)).toEqual(display);
  59. },
  60. );
  61. it("rejects RespondToCoordinator delivery details", () => {
  62. expect(
  63. respondToCoordinatorToolResultDisplayPayloadSchema.safeParse({
  64. kind: "respond_to_coordinator",
  65. status: "success",
  66. responseId: "response-1",
  67. }).success,
  68. ).toBe(false);
  69. });
  70. it("accepts bounded authoritative CUA target-app display metadata", () => {
  71. const display = {
  72. kind: "cua",
  73. schemaVersion: 1,
  74. toolName: "key",
  75. status: "success",
  76. targetApp: {
  77. schemaVersion: 1,
  78. displayName: "Calculator",
  79. iconLocators: [{ kind: "darwin-bundle-id", value: "com.apple.calculator" }],
  80. },
  81. } as const;
  82. expect(parseToolResultDisplayPayload(display)).toEqual(display);
  83. expect(
  84. parseToolResultDisplayPayload({
  85. ...display,
  86. targetApp: {
  87. ...display.targetApp,
  88. iconLocators: [{ kind: "unsupported", value: "forged" }],
  89. },
  90. }),
  91. ).toBeUndefined();
  92. });
  93. it("accepts strict request_access permission status and rejects unknown fields", () => {
  94. const display = {
  95. kind: "cua",
  96. schemaVersion: 1,
  97. toolName: "request_access",
  98. status: "success",
  99. permissionStatus: {
  100. schemaVersion: 1,
  101. platform: "darwin",
  102. grantOwner: "dev.zcode.cua-helper.dev",
  103. accessibility: "denied",
  104. screenRecording: "unknown",
  105. },
  106. } as const;
  107. expect(parseToolResultDisplayPayload(display)).toEqual(display);
  108. expect(
  109. parseToolResultDisplayPayload({
  110. ...display,
  111. permissionStatus: { ...display.permissionStatus, promptUser: true },
  112. }),
  113. ).toBeUndefined();
  114. });
  115. it("accepts a bounded CreateWorkflow display with a causality graph", () => {
  116. const display = {
  117. kind: "create_workflow",
  118. ok: true,
  119. errorCount: 0,
  120. diagnostics: [],
  121. causalityGraph: {
  122. steps: [
  123. {
  124. id: "ask#1",
  125. kind: "ask",
  126. label: "planner",
  127. line: 2,
  128. column: 24,
  129. lane: "actor#1",
  130. },
  131. {
  132. id: "ask#2",
  133. kind: "ask",
  134. label: "reviewer",
  135. line: 3,
  136. column: 24,
  137. lane: "actor#2",
  138. lanes: ["actor#2", "actor#3"],
  139. repeat: "stack",
  140. },
  141. ],
  142. lanes: [
  143. { id: "workspace" },
  144. { id: "actor#1", name: "planner", line: 2, column: 17 },
  145. { id: "actor#2", name: "reviewer", line: 3, column: 17 },
  146. ],
  147. // 第二层是子代理导向(docs/dynamic-workflow/presentation.md):每阶段一张参与者
  148. // 卡,无阶段词汇时 phase 恒为 `unphased`;家族基数未知时一张 `many` 卡。
  149. participants: [
  150. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  151. {
  152. id: "unphased:actor#2",
  153. phase: "unphased",
  154. lane: "actor#2",
  155. steps: ["ask#2"],
  156. many: true,
  157. },
  158. ],
  159. // 一种箭头:runs after;`back: true` 只标循环回边;`types` 是跨越它的产物类型(检视器用)。
  160. handoffs: [
  161. { from: "unphased:actor#1", to: "unphased:actor#2", types: ["Plan"] },
  162. { from: "unphased:actor#2", to: "unphased:actor#1", back: true },
  163. ],
  164. sink: ["ask#1", "ask#2"],
  165. truncated: true,
  166. },
  167. } as const;
  168. expect(createWorkflowToolResultDisplayPayloadSchema.parse(display)).toEqual(display);
  169. expect(parseToolResultDisplayPayload(display)).toEqual(display);
  170. });
  171. // docs/dynamic-workflow/presentation.md:模型精炼撤回后,四层 schema
  172. // 里不再有 `refinedName` / `refinedLabel`,而库里仍躺着带它们的旧 part。两个解析入口在
  173. // 严格解析之前把这三个位置的字段剥掉;不剥的后果是整个 display(连同图)从旧会话里消失。
  174. describe("withdrawn refined display names on persisted CreateWorkflow displays", () => {
  175. const plain = {
  176. kind: "create_workflow",
  177. ok: true,
  178. errorCount: 0,
  179. diagnostics: [],
  180. causalityGraph: {
  181. steps: [{ id: "ask#1", kind: "ask", label: "planner", lane: "actor#1", phase: "phase#1" }],
  182. lanes: [{ id: "actor#1", name: "planner" }],
  183. participants: [
  184. { id: "phase#1:actor#1", phase: "phase#1", lane: "actor#1", steps: ["ask#1"] },
  185. ],
  186. handoffs: [],
  187. phases: [{ id: "phase#1", name: "plan" }],
  188. },
  189. } as const;
  190. const refined = {
  191. ...plain,
  192. causalityGraph: {
  193. ...plain.causalityGraph,
  194. steps: [{ ...plain.causalityGraph.steps[0], refinedLabel: "拟定计划" }],
  195. lanes: [{ ...plain.causalityGraph.lanes[0], refinedName: "规划者" }],
  196. phases: [{ ...plain.causalityGraph.phases[0], refinedName: "规划" }],
  197. },
  198. };
  199. it("the schema itself knows nothing about the withdrawn fields", () => {
  200. expect(createWorkflowToolResultDisplayPayloadSchema.parse(plain)).toEqual(plain);
  201. expect(createWorkflowToolResultDisplayPayloadSchema.safeParse(refined).success).toBe(false);
  202. });
  203. it("both parse entry points strip the fields before the strict parse", () => {
  204. expect(parseToolResultDisplayPayload(refined)).toEqual(plain);
  205. expect(
  206. parseCompletedToolPartMetadata({ schemaVersion: 1, display: refined })?.display,
  207. ).toEqual(plain);
  208. });
  209. it("leaves other display kinds alone", () => {
  210. // 剥离只认 create_workflow:别的 kind 上多出来的同名键仍然是陌生字段,照常拒绝。
  211. expect(
  212. parseToolResultDisplayPayload({
  213. kind: "task_output",
  214. retrievalStatus: "success",
  215. refinedName: "x",
  216. }),
  217. ).toBeUndefined();
  218. });
  219. });
  220. // docs/dynamic-workflow/launch.md「Their cards」:工具卡的 error 只有 code/message。
  221. // 2026-09-14 起的 CLI 把工具输出的 `error.providerStop` 一并写进了 display 并落库,
  222. // 而渲染端的镜像 schema 从来只认 {code, message}:那些帧一律被拒,一个会话因此停在
  223. // fault.subscription.recoveryFailed。构造侧已经改完,库里躺着的那批只能在解析之前剥。
  224. describe("provider stop details on persisted GetWorkflowRun displays", () => {
  225. const plain = {
  226. kind: "get_workflow_run",
  227. runId: "dwfrun_stopped",
  228. label: "nightly-sync",
  229. status: "stopped",
  230. stopReason: "provider",
  231. usage: {
  232. spentTokens: 12_345,
  233. nodesObserved: 7,
  234. nodesRunning: 0,
  235. nodesCompleted: 4,
  236. nodesFailed: 1,
  237. },
  238. actors: [{ siteId: "agent#1", ordinal: 1, name: "scout" }],
  239. logTail: [{ sequence: 1, message: "started" }],
  240. error: { code: "ProviderStop", message: "The provider stopped the run: rate limited." },
  241. } as const;
  242. const persisted = {
  243. ...plain,
  244. error: {
  245. ...plain.error,
  246. providerStop: {
  247. kind: "quota",
  248. reason: "rate_limited",
  249. providerId: "bigmodel",
  250. providerCode: "1308",
  251. },
  252. },
  253. };
  254. it("the display schema itself knows nothing about providerStop", () => {
  255. expect(getWorkflowRunToolResultDisplayPayloadSchema.parse(plain)).toEqual(plain);
  256. expect(getWorkflowRunToolResultDisplayPayloadSchema.safeParse(persisted).success).toBe(false);
  257. });
  258. it("both parse entry points strip it before the strict parse", () => {
  259. // code / message 完整幸存,只掉 providerStop。
  260. expect(parseToolResultDisplayPayload(persisted)).toEqual(plain);
  261. expect(
  262. parseCompletedToolPartMetadata({
  263. schemaVersion: 1,
  264. display: persisted,
  265. serialization: {
  266. truncated: false,
  267. originalBytes: 128,
  268. returnedBytes: 128,
  269. budgetStrategy: "inline",
  270. },
  271. })?.display,
  272. ).toEqual(plain);
  273. });
  274. it("leaves a card without an error untouched", () => {
  275. // 只改在场的键:缺席的 error 不能被凭空添成一个 undefined。
  276. const { error: _error, ...withoutError } = plain;
  277. expect(parseToolResultDisplayPayload(withoutError)).toEqual(withoutError);
  278. expect(Object.keys(parseToolResultDisplayPayload(withoutError) ?? {})).not.toContain("error");
  279. });
  280. it("leaves other display kinds alone", () => {
  281. // 剥离按 kind 分派:别的卡上多出来的 providerStop 仍然是陌生字段。
  282. expect(
  283. parseToolResultDisplayPayload({
  284. kind: "list_workflow_runs",
  285. runs: [],
  286. error: { code: "ProviderStop", message: "x", providerStop: { kind: "quota" } },
  287. }),
  288. ).toBeUndefined();
  289. });
  290. });
  291. it("bounds the CreateWorkflow causality graph strictly", () => {
  292. const step = {
  293. id: "ask#1",
  294. kind: "ask",
  295. label: "a",
  296. lane: "actor#1",
  297. } as const;
  298. const participant = {
  299. id: "unphased:actor#1",
  300. phase: "unphased",
  301. lane: "actor#1",
  302. steps: ["ask#1"],
  303. };
  304. const base = {
  305. steps: [step],
  306. lanes: [{ id: "actor#1" }],
  307. participants: [participant],
  308. handoffs: [],
  309. };
  310. expect(CreateWorkflowCausalityGraphSchema.safeParse(base).success).toBe(true);
  311. // 65 steps exceed the 64-step bound.
  312. expect(
  313. CreateWorkflowCausalityGraphSchema.safeParse({
  314. ...base,
  315. steps: Array.from({ length: 65 }, (_, index) => ({ ...step, id: `ask#${index}` })),
  316. }).success,
  317. ).toBe(false);
  318. // 33 lanes exceed the 32-lane bound.
  319. expect(
  320. CreateWorkflowCausalityGraphSchema.safeParse({
  321. ...base,
  322. lanes: Array.from({ length: 33 }, (_, index) => ({ id: `actor#${index}` })),
  323. }).success,
  324. ).toBe(false);
  325. // Step label above the 128-char bound.
  326. expect(
  327. CreateWorkflowCausalityGraphSchema.safeParse({
  328. ...base,
  329. steps: [{ ...step, label: "n".repeat(129) }],
  330. }).success,
  331. ).toBe(false);
  332. // The nested `loc` shape stays inside the analyzer: the payload is flat line/column.
  333. expect(
  334. CreateWorkflowCausalityGraphSchema.safeParse({
  335. ...base,
  336. steps: [{ ...step, loc: { line: 1, column: 1 } }],
  337. }).success,
  338. ).toBe(false);
  339. // Every step needs a lane — the renderer has no default.
  340. const partial: Record<string, unknown> = { ...step };
  341. delete partial.lane;
  342. expect(
  343. CreateWorkflowCausalityGraphSchema.safeParse({ ...base, steps: [partial] }).success,
  344. ).toBe(false);
  345. // step 级边与车道多重性已退出载荷(docs/dynamic-workflow/presentation.md):`edges`
  346. // 连空数组都是多出来的键,`Lane.nesting` 同理。
  347. expect(CreateWorkflowCausalityGraphSchema.safeParse({ ...base, edges: [] }).success).toBe(
  348. false,
  349. );
  350. expect(
  351. CreateWorkflowCausalityGraphSchema.safeParse({
  352. ...base,
  353. lanes: [{ id: "actor#1", nesting: 1 }],
  354. }).success,
  355. ).toBe(false);
  356. // 参与者与交接都是必填——零参与者是空数组,不是缺席。
  357. const { participants: _p, ...noParticipants } = base;
  358. const { handoffs: _h, ...noHandoffs } = base;
  359. expect(CreateWorkflowCausalityGraphSchema.safeParse(noParticipants).success).toBe(false);
  360. expect(CreateWorkflowCausalityGraphSchema.safeParse(noHandoffs).success).toBe(false);
  361. // 65 participants exceed the 64-participant bound.
  362. expect(
  363. CreateWorkflowCausalityGraphSchema.safeParse({
  364. ...base,
  365. participants: Array.from({ length: 65 }, (_, index) => ({
  366. ...participant,
  367. id: `unphased:actor#1[${index}]`,
  368. member: { index, of: 65 },
  369. })),
  370. }).success,
  371. ).toBe(false);
  372. // A participant with no step is not a card.
  373. expect(
  374. CreateWorkflowCausalityGraphSchema.safeParse({
  375. ...base,
  376. participants: [{ ...participant, steps: [] }],
  377. }).success,
  378. ).toBe(false);
  379. // member = {index ≥ 0, of ≥ 1},strict;many 只接受字面量 true。
  380. expect(
  381. CreateWorkflowCausalityGraphSchema.safeParse({
  382. ...base,
  383. participants: [{ ...participant, id: "unphased:actor#1[2]", member: { index: 2, of: 3 } }],
  384. }).success,
  385. ).toBe(true);
  386. for (const member of [{ index: -1, of: 3 }, { index: 0, of: 0 }, { index: 0 }, { of: 3 }]) {
  387. expect(
  388. CreateWorkflowCausalityGraphSchema.safeParse({
  389. ...base,
  390. participants: [{ ...participant, member }],
  391. }).success,
  392. ).toBe(false);
  393. }
  394. expect(
  395. CreateWorkflowCausalityGraphSchema.safeParse({
  396. ...base,
  397. participants: [{ ...participant, many: false }],
  398. }).success,
  399. ).toBe(false);
  400. // 一种箭头:交接边只有 {from, to, back?, types?}。分析器的种类 / certainty 与折叠计数
  401. // 都不进展示通道,strict schema 对每个多出来的键都必须拒绝。
  402. const handoff = { from: "unphased:actor#1", to: "unphased:actor#1" };
  403. for (const extra of [
  404. { kind: "data" },
  405. { kind: "message" },
  406. { certainty: "always" },
  407. { exact: true },
  408. { count: 2 },
  409. ]) {
  410. expect(
  411. CreateWorkflowCausalityGraphSchema.safeParse({
  412. ...base,
  413. handoffs: [{ ...handoff, ...extra }],
  414. }).success,
  415. ).toBe(false);
  416. }
  417. // 257 handoffs exceed the 256-handoff bound.
  418. expect(
  419. CreateWorkflowCausalityGraphSchema.safeParse({
  420. ...base,
  421. handoffs: Array.from({ length: 257 }, () => handoff),
  422. }).success,
  423. ).toBe(false);
  424. // `types` 在场就是 1..8 个名字,每个 ≤ 128 字符。
  425. expect(
  426. CreateWorkflowCausalityGraphSchema.safeParse({
  427. ...base,
  428. handoffs: [{ ...handoff, types: ["Flaky"] }],
  429. }).success,
  430. ).toBe(true);
  431. for (const types of [
  432. [],
  433. Array.from({ length: 9 }, (_, i) => `T${i}`),
  434. [""],
  435. ["t".repeat(129)],
  436. ]) {
  437. expect(
  438. CreateWorkflowCausalityGraphSchema.safeParse({
  439. ...base,
  440. handoffs: [{ ...handoff, types }],
  441. }).success,
  442. ).toBe(false);
  443. }
  444. // `back` 只接受字面量 true。
  445. expect(
  446. CreateWorkflowCausalityGraphSchema.safeParse({
  447. ...base,
  448. handoffs: [{ ...handoff, back: true }],
  449. }).success,
  450. ).toBe(true);
  451. expect(
  452. CreateWorkflowCausalityGraphSchema.safeParse({
  453. ...base,
  454. handoffs: [{ ...handoff, back: false }],
  455. }).success,
  456. ).toBe(false);
  457. });
  458. });
  459. /**
  460. * 版本偏斜 tripwire(docs/dynamic-workflow/launch.md「Other clients」)。
  461. *
  462. * 这条断言的读者是**未来那个想给 create_workflow display 加字段的人**。既有 kind 上多出来
  463. * 的键不是「旧客户端少读一个字段」,而是整块 display 校验不过:`packages/ui` 的
  464. * create-workflow renderer 用 safeParse,legacy v3 按 kind 查表,两处都是 strict。
  465. * 可复用工作流的 saved 来源因此把全部新内容放进了**工具入参**通道——那一侧对所有版本
  466. * 都是无 schema 的透传。要加字段先回去读那一节,然后连同 packages/shared 的两份镜像
  467. * 一起改。
  468. */
  469. describe("create_workflow display field set (skew tripwire)", () => {
  470. it("carries exactly the frozen field set", () => {
  471. expect(Object.keys(createWorkflowToolResultDisplayPayloadSchema.shape).sort()).toEqual([
  472. "causalityGraph",
  473. "diagnostics",
  474. "errorCount",
  475. "kind",
  476. "ok",
  477. "truncated",
  478. ]);
  479. });
  480. it("rejects an extra key outright rather than dropping it", () => {
  481. const base = { kind: "create_workflow" as const, ok: true, errorCount: 0, diagnostics: [] };
  482. expect(createWorkflowToolResultDisplayPayloadSchema.safeParse(base).success).toBe(true);
  483. expect(
  484. createWorkflowToolResultDisplayPayloadSchema.safeParse({ ...base, script: "return 1;" })
  485. .success,
  486. ).toBe(false);
  487. });
  488. // v1 刻意不加 save_workflow kind:保存确认块按 toolName 读归一化入参渲染。
  489. // (未知 kind 在两侧都干净降级,所以将来要加是纯增量——见 spec 的 Follow-ups。)
  490. it("has no save_workflow member in the union", () => {
  491. expect(
  492. toolResultDisplayPayloadSchema.safeParse({ kind: "save_workflow", name: "x" }).success,
  493. ).toBe(false);
  494. });
  495. });
  496. // spec:docs/dynamic-workflow/presentation.md「The run card」——
  497. // 载荷刻意最小 {runId},字段表钉死(多字段 = 两侧 strict schema 同步债,见上tripwire 注释)。
  498. describe("resume_workflow_run display payload", () => {
  499. it("parses the minimal payload and rejects extras", () => {
  500. expect(
  501. toolResultDisplayPayloadSchema.safeParse({ kind: "resume_workflow_run", runId: "dwfrun_x" })
  502. .success,
  503. ).toBe(true);
  504. expect(
  505. toolResultDisplayPayloadSchema.safeParse({
  506. kind: "resume_workflow_run",
  507. runId: "dwfrun_x",
  508. response: "extra",
  509. }).success,
  510. ).toBe(false);
  511. });
  512. it("carries exactly the frozen field set", () => {
  513. const schema = resumeWorkflowRunToolResultDisplayPayloadSchema;
  514. expect(Object.keys(schema.shape).sort()).toEqual(["kind", "runId"]);
  515. });
  516. });