conversationShareWorkflowSnapshot.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. import { describe, expect, it, vi } from "vitest";
  2. import { readFile } from "node:fs/promises";
  3. import { conversationRowSchema } from "@zcode/shared/zcode-protocol-v4";
  4. import {
  5. collectConversationShareWorkflowSnapshot,
  6. type ShareWorkflowReader,
  7. } from "../src/conversation-share/conversationShareWorkflowSnapshot.js";
  8. import { buildConversationSharePublicProjection } from "../src/conversation-share/conversationSharePublicProjection.js";
  9. import {
  10. buildConversationShareConfirmRequest,
  11. verifyConversationShareIntegrity,
  12. } from "../src/conversation-share/conversationShareIntegrity.js";
  13. import type { ConversationShareCapabilities } from "@zcode/shared";
  14. import type { ConversationRow } from "@zcode/shared/zcode-protocol-v4";
  15. const capabilities: ConversationShareCapabilities = {
  16. schema_version: 1,
  17. ttl_ms: 10000,
  18. access_modes: ["public_readonly"],
  19. max_rows: 200,
  20. max_payload_bytes: 1000000,
  21. max_artifact_count: 20,
  22. max_artifact_bytes: 10000,
  23. max_total_artifact_bytes: 100000,
  24. allowed_artifacts: [{ type: "text", extensions: ["md"], mime_types: ["text/markdown"] }],
  25. content_block_versions: { workflow: 1 },
  26. };
  27. const rows: ConversationRow[] = [
  28. {
  29. rowId: 1,
  30. turnId: "t1",
  31. productTurnId: "p1",
  32. createdAt: 1,
  33. createdAtSeq: 1,
  34. kind: "turnHeader",
  35. origin: "backgroundResult",
  36. state: "completedSuccess",
  37. startedAt: 1,
  38. originMeta: {
  39. backgroundSource: "workflow",
  40. workId: "private-run",
  41. title: "军棋",
  42. workflowNotification: { kind: "terminal", status: "completed", summary: "done" },
  43. },
  44. },
  45. {
  46. rowId: 2,
  47. turnId: "t1",
  48. productTurnId: "p1",
  49. createdAt: 1,
  50. createdAtSeq: 2,
  51. kind: "assistantText",
  52. state: "complete",
  53. text: "原始最终正文",
  54. },
  55. ];
  56. function reader(): ShareWorkflowReader {
  57. return {
  58. conversationWorkflowRunsV4: vi.fn().mockResolvedValue({ runs: [] }),
  59. conversationWorkflowRunEventsV4: vi.fn().mockResolvedValue({
  60. hasMore: false,
  61. events: [
  62. { sequence: 1, type: "run-started", payload: {} },
  63. {
  64. sequence: 2,
  65. type: "artifact-published",
  66. payload: { artifact: { id: "board", kind: "board", version: 1, title: "进度看板" } },
  67. },
  68. {
  69. sequence: 3,
  70. type: "artifact-published",
  71. payload: { artifact: { id: "report", kind: "markdown", version: 1, title: "交付报告" } },
  72. },
  73. { sequence: 4, type: "run-settled", payload: { status: "completed" } },
  74. ],
  75. }),
  76. conversationWorkflowRunArtifactsV4: vi.fn().mockResolvedValue({
  77. artifacts: [
  78. {
  79. id: "board",
  80. kind: "board",
  81. versions: [
  82. {
  83. version: 1,
  84. title: "进度看板",
  85. spec: { key: "id", status: "status", columns: ["done"] },
  86. },
  87. ],
  88. },
  89. {
  90. id: "report",
  91. kind: "markdown",
  92. versions: [
  93. { version: 1, title: "交付报告", contentType: "text/markdown" },
  94. { version: 2, title: "后续版本" },
  95. ],
  96. },
  97. ],
  98. }),
  99. conversationWorkflowRunArtifactDataV4: vi.fn().mockResolvedValue({
  100. hasMore: false,
  101. items: [
  102. { sequence: 3, siteId: "report", ordinal: 1, item: { id: "one", status: "done" } },
  103. { sequence: 5, siteId: "report", ordinal: 2, item: { id: "later", status: "done" } },
  104. ],
  105. }),
  106. conversationWorkflowRunArtifactReadV4: vi.fn().mockResolvedValue({
  107. dataBase64: Buffer.from("# Report").toString("base64"),
  108. totalBytes: 8,
  109. nextOffset: null,
  110. mediaType: "text/markdown",
  111. }),
  112. };
  113. }
  114. const input = {
  115. workspacePath: "/workspace",
  116. workspaceIdentity: "remote-a",
  117. remoteSessionId: "attachment-a",
  118. sessionId: "s1",
  119. };
  120. describe("workflow 分享冻结快照", () => {
  121. it("真实会话中的失败编译不生成空 run,完成轮保留统计和文档正文", async () => {
  122. const raw = JSON.parse(
  123. await readFile(
  124. new URL("./fixtures/share-workflow-parity-rows.json", import.meta.url),
  125. "utf8",
  126. ),
  127. );
  128. const actualRows = raw.map((row: unknown) => conversationRowSchema.parse(row));
  129. const agent = reader();
  130. vi.mocked(agent.conversationWorkflowRunsV4).mockResolvedValue({
  131. runs: [
  132. {
  133. runId: "run-completed",
  134. toolCallId: "create-completed",
  135. status: "completed",
  136. resumable: false,
  137. },
  138. ],
  139. });
  140. const snapshot = await collectConversationShareWorkflowSnapshot({
  141. agent,
  142. input,
  143. rows: actualRows,
  144. allRows: actualRows,
  145. capabilities: { ...capabilities, content_block_versions: { workflow: 2 } },
  146. capturedAt: 99,
  147. });
  148. expect(snapshot.drafts).toHaveLength(2);
  149. expect(snapshot.drafts.map((draft) => draft.payload.completion)).toEqual([false, true]);
  150. expect(snapshot.drafts[1]?.payload.duration_ms).toBe(2525893);
  151. expect(snapshot.drafts[1]?.payload.artifacts.find((a) => a.id === "report")).toMatchObject({
  152. preview_text: "# Report",
  153. });
  154. expect(agent.conversationWorkflowRunEventsV4).toHaveBeenCalledTimes(1);
  155. });
  156. it("在物化字节前执行总资源预算,不把超限文件留在上传集合", async () => {
  157. const snapshot = await collectConversationShareWorkflowSnapshot({
  158. agent: reader(),
  159. input,
  160. rows,
  161. allRows: rows,
  162. capabilities: { ...capabilities, max_total_artifact_bytes: 4 },
  163. capturedAt: 99,
  164. });
  165. expect(snapshot.bytes.size).toBe(0);
  166. expect(
  167. snapshot.drafts[0]?.payload.artifacts.find((artifact) => artifact.id === "report"),
  168. ).toMatchObject({ unavailable: "limit_exceeded" });
  169. });
  170. it("完成轮独立关联 journal,固定版本和看板水位,公开 ID 闭包", async () => {
  171. const agent = reader();
  172. const snapshot = await collectConversationShareWorkflowSnapshot({
  173. agent,
  174. input,
  175. rows,
  176. allRows: rows,
  177. capabilities,
  178. capturedAt: 99,
  179. });
  180. expect(snapshot.drafts[0]?.payload.run?.status).toBe("completed");
  181. expect(snapshot.drafts[0]?.payload.artifacts[0]).toMatchObject({
  182. kind: "board",
  183. items: [{ item: { id: "one" } }],
  184. });
  185. expect(agent.conversationWorkflowRunArtifactReadV4).toHaveBeenCalledWith(
  186. expect.objectContaining({ ...input, version: 1 }),
  187. );
  188. const projection = buildConversationSharePublicProjection({
  189. rows: snapshot.rows,
  190. selectedProductTurnIds: ["p1"],
  191. contentDrafts: snapshot.drafts,
  192. });
  193. expect(projection.contentBlocks?.[0]?.resource_ids).toEqual(["share-artifact-1"]);
  194. expect(JSON.stringify(projection)).not.toContain("private-run");
  195. const request = buildConversationShareConfirmRequest({
  196. selected_product_turn_ids: projection.selectedProductTurnIds,
  197. projection: { rows: projection.rows, content_blocks: projection.contentBlocks },
  198. artifacts: projection.artifacts.map((a) => a.descriptor),
  199. disclosure_confirmation: {
  200. version: 1,
  201. accepted_at: 1,
  202. acknowledged_no_secret_detection: true,
  203. },
  204. });
  205. expect(
  206. verifyConversationShareIntegrity({
  207. rawRows: projection.rows,
  208. rawArtifacts: projection.artifacts.map((a) => a.descriptor),
  209. rawContentBlocks: projection.contentBlocks,
  210. integrity: request.integrity,
  211. }),
  212. ).toBe(true);
  213. expect(
  214. verifyConversationShareIntegrity({
  215. rawRows: projection.rows,
  216. rawArtifacts: projection.artifacts.map((a) => a.descriptor),
  217. rawContentBlocks: [],
  218. integrity: request.integrity,
  219. }),
  220. ).toBe(false);
  221. });
  222. it("源读取失败保留摘要和原正文,不伪造已完成状态", async () => {
  223. const agent = reader();
  224. vi.mocked(agent.conversationWorkflowRunEventsV4).mockRejectedValue(new Error("offline"));
  225. const result = await collectConversationShareWorkflowSnapshot({
  226. agent,
  227. input,
  228. rows,
  229. allRows: rows,
  230. capabilities,
  231. capturedAt: 99,
  232. });
  233. expect(result.drafts[0]?.payload.unavailable).toBe("source_unavailable");
  234. expect(result.drafts[0]?.payload.run).toBeUndefined();
  235. expect(result.rows).toContain(rows[1]);
  236. expect(result.rows.at(-1)).toMatchObject({
  237. kind: "assistantText",
  238. text: expect.stringContaining("快照不可用"),
  239. });
  240. });
  241. });
  242. describe("workflow 分享边界回归", () => {
  243. const collect = (agent: ShareWorkflowReader, limits = capabilities) =>
  244. collectConversationShareWorkflowSnapshot({
  245. agent,
  246. input,
  247. rows,
  248. allRows: rows,
  249. capabilities: { ...limits, content_block_versions: { workflow: 2 } },
  250. capturedAt: 99,
  251. });
  252. it("按游标读取多页 journal,最后一页决定产物版本和看板水位", async () => {
  253. const agent = reader();
  254. const complete = await agent.conversationWorkflowRunEventsV4({
  255. ...input,
  256. runId: "private-run",
  257. });
  258. vi.mocked(agent.conversationWorkflowRunEventsV4)
  259. .mockClear()
  260. .mockResolvedValueOnce({ events: complete.events.slice(0, 2), hasMore: true })
  261. .mockResolvedValueOnce({ events: complete.events.slice(2), hasMore: false });
  262. const snapshot = await collect(agent);
  263. expect(snapshot.drafts[0]?.payload.unavailable).toBeUndefined();
  264. expect(snapshot.drafts[0]?.payload.run?.status).toBe("completed");
  265. expect(snapshot.bytes.size).toBe(1);
  266. expect(agent.conversationWorkflowRunEventsV4).toHaveBeenNthCalledWith(
  267. 2,
  268. expect.objectContaining({ ...input, runId: "private-run", afterSequence: 2 }),
  269. );
  270. expect(snapshot.drafts[0]?.payload.artifacts[0]?.items).toHaveLength(1);
  271. });
  272. it.each(["empty", "duplicate", "limit"])("拒绝 %s 分页且不留下上传资源", async (failure) => {
  273. const agent = reader();
  274. const page = { events: [{ sequence: 1, type: "run-started", payload: {} }], hasMore: true };
  275. vi.mocked(agent.conversationWorkflowRunEventsV4)
  276. .mockResolvedValueOnce(page)
  277. .mockResolvedValue(
  278. failure === "empty"
  279. ? { events: [], hasMore: true }
  280. : failure === "duplicate"
  281. ? page
  282. : {
  283. events: Array.from({ length: 20000 }, (_, index) => ({
  284. sequence: index + 2,
  285. type: "run-started",
  286. payload: {},
  287. })),
  288. hasMore: false,
  289. },
  290. );
  291. const snapshot = await collect(agent);
  292. expect(agent.conversationWorkflowRunEventsV4).toHaveBeenCalledTimes(2);
  293. expect(snapshot.drafts[0]?.payload.unavailable).toBe("source_unavailable");
  294. expect(snapshot.bytes.size).toBe(0);
  295. });
  296. it.each(["Report 2026.10", "v1.2 notes", "report.md"])(
  297. "标题 %s 不改变下载扩展名",
  298. async (title) => {
  299. const agent = reader();
  300. const metadata = await agent.conversationWorkflowRunArtifactsV4({
  301. ...input,
  302. runId: "private-run",
  303. });
  304. metadata.artifacts.find((artifact) => artifact.id === "report")!.versions[0]!.title = title;
  305. vi.mocked(agent.conversationWorkflowRunArtifactsV4).mockResolvedValue(metadata);
  306. const snapshot = await collect(agent);
  307. const projection = buildConversationSharePublicProjection({
  308. rows: snapshot.rows,
  309. selectedProductTurnIds: ["p1"],
  310. contentDrafts: snapshot.drafts,
  311. });
  312. expect(projection.artifacts[0]?.descriptor.extension).toBe("md");
  313. expect(projection.artifacts[0]?.descriptor.display_name).toBe(
  314. title.endsWith(".md") ? title : `${title}.md`,
  315. );
  316. },
  317. );
  318. it("文本解码失败不登记字节、行和预算,后续有效产物仍能分享", async () => {
  319. const agent = reader();
  320. const events = await agent.conversationWorkflowRunEventsV4({ ...input, runId: "private-run" });
  321. events.events.splice(3, 0, {
  322. sequence: 4,
  323. type: "artifact-published",
  324. payload: { artifact: { id: "valid", kind: "markdown", version: 1, title: "有效文档" } },
  325. });
  326. events.events.at(-1)!.sequence = 5;
  327. vi.mocked(agent.conversationWorkflowRunEventsV4).mockResolvedValue(events);
  328. const metadata = await agent.conversationWorkflowRunArtifactsV4({
  329. ...input,
  330. runId: "private-run",
  331. });
  332. metadata.artifacts.push({
  333. id: "valid",
  334. kind: "markdown",
  335. versions: [{ version: 1, title: "有效文档", contentType: "text/markdown" }],
  336. } as (typeof metadata.artifacts)[number]);
  337. vi.mocked(agent.conversationWorkflowRunArtifactsV4).mockResolvedValue(metadata);
  338. vi.mocked(agent.conversationWorkflowRunArtifactReadV4).mockResolvedValueOnce({
  339. dataBase64: Buffer.from([0xff]).toString("base64"),
  340. totalBytes: 1,
  341. nextOffset: null,
  342. mediaType: "text/markdown",
  343. });
  344. const snapshot = await collect(agent, {
  345. ...capabilities,
  346. max_artifact_count: 1,
  347. max_total_artifact_bytes: 8,
  348. });
  349. expect(
  350. snapshot.drafts[0]?.payload.artifacts.find((artifact) => artifact.id === "report"),
  351. ).toMatchObject({ unavailable: "source_unavailable" });
  352. expect(
  353. snapshot.drafts[0]?.payload.artifacts.find((artifact) => artifact.id === "valid"),
  354. ).toMatchObject({ resource_id: "workflow-resource-1", preview_text: "# Report" });
  355. expect(snapshot.bytes.size).toBe(1);
  356. expect(snapshot.rows.filter((row) => row.kind === "artifact")).toHaveLength(1);
  357. expect([...snapshot.bytes.values()][0]).toEqual(Buffer.from("# Report"));
  358. });
  359. });
  360. describe("workflow preflight metadata budget", () => {
  361. it.each([8, 10001, 100001])(
  362. "checks declared bytes %s without reading artifact content",
  363. async (declaredBytes) => {
  364. const agent = reader();
  365. const metadata = await agent.conversationWorkflowRunArtifactsV4({
  366. ...input,
  367. runId: "private-run",
  368. });
  369. metadata.artifacts.find((artifact) => artifact.id === "report")!.versions[0]!.bytes =
  370. declaredBytes;
  371. const snapshot = await collectConversationShareWorkflowSnapshot({
  372. agent,
  373. input,
  374. rows,
  375. allRows: rows,
  376. capabilities,
  377. capturedAt: 99,
  378. preflight: true,
  379. });
  380. expect(agent.conversationWorkflowRunArtifactReadV4).not.toHaveBeenCalled();
  381. expect(snapshot.bytes.size).toBe(0);
  382. expect(
  383. snapshot.drafts[0]?.payload.artifacts.find((artifact) => artifact.id === "report"),
  384. ).toMatchObject(
  385. declaredBytes > capabilities.max_artifact_bytes
  386. ? { unavailable: "limit_exceeded" }
  387. : { bytes: declaredBytes },
  388. );
  389. if (declaredBytes === 8) {
  390. await collectConversationShareWorkflowSnapshot({
  391. agent,
  392. input,
  393. rows,
  394. allRows: rows,
  395. capabilities,
  396. capturedAt: 99,
  397. });
  398. expect(agent.conversationWorkflowRunArtifactReadV4).toHaveBeenCalledTimes(1);
  399. }
  400. },
  401. );
  402. });