conversationSharePublicProjection.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import { readFile } from "node:fs/promises";
  2. import { decodeConversationShareRows } from "@zcode/shared";
  3. import { toolCallDisplaySchema } from "@zcode/shared/zcode-protocol-v4";
  4. import type { ConversationRow } from "@zcode/shared";
  5. import { describe, expect, it } from "vitest";
  6. import {
  7. assertConversationSharePublicProjection,
  8. buildConversationSharePublicProjection,
  9. } from "../src/conversation-share/conversationSharePublicProjection.js";
  10. function rowsWithCompletedSubagent(): ConversationRow[] {
  11. return [
  12. {
  13. rowId: 101,
  14. turnId: "local-turn-a",
  15. entityId: "local-entity-header",
  16. productTurnId: "local-product-turn-a",
  17. createdAt: 1_000,
  18. createdAtSeq: 10,
  19. actions: { canFork: true },
  20. kind: "turnHeader",
  21. origin: "userInput",
  22. executionKind: "agent",
  23. state: "completedSuccess",
  24. startedAt: 1_000,
  25. endedAt: 1_900,
  26. activeMs: 700,
  27. workSegments: [
  28. {
  29. segmentId: "segment-1",
  30. triggerEntityId: "local-entity-tool",
  31. startedAt: 1_100,
  32. endedAt: 1_800,
  33. activeMs: 700,
  34. },
  35. ],
  36. originMeta: {
  37. backgroundSource: "subagent",
  38. workId: "local-work-header",
  39. title: "后台结果",
  40. },
  41. fileChanges: { additions: 3, deletions: 1, files: 1 },
  42. },
  43. {
  44. rowId: 102,
  45. turnId: "local-turn-a",
  46. entityId: "local-entity-user",
  47. productTurnId: "local-product-turn-a",
  48. createdAt: 1_010,
  49. createdAtSeq: 11,
  50. actions: { canEdit: true },
  51. kind: "userInput",
  52. text: "请分析并生成报告",
  53. origin: "backgroundResult",
  54. originMeta: {
  55. backgroundSource: "subagent",
  56. workId: "local-work-user",
  57. senderSessionId: "local-child-session",
  58. senderLabel: "研究助手",
  59. },
  60. sourceCommandId: "source-command",
  61. rootSourceCommandId: "root-source-command",
  62. clientId: "client-desktop",
  63. },
  64. {
  65. rowId: 103,
  66. turnId: "local-turn-a",
  67. entityId: "local-entity-tool",
  68. productTurnId: "local-product-turn-a",
  69. createdAt: 1_020,
  70. createdAtSeq: 12,
  71. actions: { canRetry: true },
  72. kind: "toolCall",
  73. toolCallId: "local-tool-call",
  74. toolName: "Agent",
  75. status: "success",
  76. inputText: '{"description":"研究"}',
  77. input: { description: "研究" },
  78. output: { text: "子任务已完成" },
  79. progress: { bytes: 12, previewLine: "running", updatedAt: 1_500 },
  80. approvalInteractionId: "approval-1",
  81. backgrounded: true,
  82. workId: "local-work-tool",
  83. startedAt: 1_100,
  84. endedAt: 1_700,
  85. },
  86. {
  87. rowId: 104,
  88. turnId: "local-turn-a",
  89. entityId: "local-entity-subagent",
  90. productTurnId: "local-product-turn-a",
  91. createdAt: 1_030,
  92. createdAtSeq: 13,
  93. kind: "subagent",
  94. parentToolCallId: "local-tool-call",
  95. subagentType: "research",
  96. status: "success",
  97. summaryText: "研究完成",
  98. childSessionId: "local-child-session",
  99. startedAt: 1_100,
  100. endedAt: 1_700,
  101. },
  102. {
  103. rowId: 105,
  104. turnId: "local-turn-a",
  105. entityId: "local-entity-assistant",
  106. productTurnId: "local-product-turn-a",
  107. createdAt: 1_040,
  108. createdAtSeq: 14,
  109. actions: { canFork: true },
  110. kind: "assistantText",
  111. text: "报告已经生成",
  112. state: "complete",
  113. model: "glm",
  114. feedback: "like",
  115. },
  116. ];
  117. }
  118. function build(rows = rowsWithCompletedSubagent()) {
  119. return buildConversationSharePublicProjection({
  120. rows,
  121. selectedProductTurnIds: ["local-product-turn-a"],
  122. });
  123. }
  124. function expectBuildFailure(rows: ConversationRow[], kind: string): void {
  125. try {
  126. build(rows);
  127. throw new Error("Expected public projection construction to fail");
  128. } catch (error) {
  129. expect(error).toMatchObject({ kind });
  130. }
  131. }
  132. describe("conversation share public projection", () => {
  133. it("SHARE02:重建 artifact 公开身份并保留本地读取引用在 sidecar", () => {
  134. const rows = rowsWithCompletedSubagent();
  135. rows.push({
  136. rowId: 106,
  137. turnId: "local-turn-a",
  138. entityId: "local-artifact-entity",
  139. productTurnId: "local-product-turn-a",
  140. createdAt: 1_050,
  141. createdAtSeq: 15,
  142. kind: "artifact",
  143. artifactVersionId: "local-artifact-version",
  144. logicalArtifactKey: "local-report-key",
  145. displayName: "report.pdf",
  146. artifactType: "pdf",
  147. mimeType: "application/pdf",
  148. sizeBytes: 4,
  149. sha256: "a".repeat(64),
  150. ref: "/workspace/report.pdf",
  151. state: "current",
  152. });
  153. const result = build(rows);
  154. expect(result.rows.at(-1)).toMatchObject({
  155. kind: "artifact",
  156. artifactVersionId: "share-artifact-1",
  157. logicalArtifactKey: "share-artifact-key-1",
  158. ref: "zcode-artifact://share/share-artifact-1",
  159. productTurnId: "share-product-turn-1",
  160. });
  161. expect(result.artifacts).toEqual([
  162. {
  163. sourceRef: "/workspace/report.pdf",
  164. descriptor: {
  165. artifact_id: "share-artifact-1",
  166. logical_artifact_key: "share-artifact-key-1",
  167. producer_product_turn_id: "share-product-turn-1",
  168. artifact_version: 1,
  169. state: "current",
  170. ref: "zcode-artifact://share/share-artifact-1",
  171. artifact_type: "pdf",
  172. display_name: "report.pdf",
  173. extension: "pdf",
  174. mime_type: "application/pdf",
  175. size_bytes: 4,
  176. sha256: "a".repeat(64),
  177. },
  178. },
  179. ]);
  180. expect(JSON.stringify(result.rows)).not.toContain("/workspace/report.pdf");
  181. });
  182. it("filters completed subagent details while preserving Agent toolCall and public content", () => {
  183. const result = build();
  184. expect(result.selectedProductTurnIds).toEqual(["share-product-turn-1"]);
  185. expect(result.rows.map((row) => row.kind)).toEqual([
  186. "turnHeader",
  187. "userInput",
  188. "toolCall",
  189. "assistantText",
  190. ]);
  191. expect(result.rows.map((row) => row.rowId)).toEqual([1, 2, 3, 4]);
  192. expect(result.rows.map((row) => row.entityId)).toEqual([
  193. "share-entity-1",
  194. "share-entity-2",
  195. "share-entity-3",
  196. "share-entity-4",
  197. ]);
  198. expect(result.rows.every((row) => row.productTurnId === "share-product-turn-1")).toBe(true);
  199. expect(result.rows[0]).toMatchObject({
  200. kind: "turnHeader",
  201. turnId: "share-turn-1",
  202. workSegments: [expect.objectContaining({ triggerEntityId: "share-entity-3" })],
  203. });
  204. expect(result.rows[0]).not.toHaveProperty("originMeta");
  205. expect(result.rows[1]).toMatchObject({
  206. kind: "userInput",
  207. originMeta: {
  208. backgroundSource: "subagent",
  209. senderLabel: "研究助手",
  210. },
  211. });
  212. expect(result.rows[2]).toMatchObject({
  213. kind: "toolCall",
  214. toolName: "Agent",
  215. toolCallId: "share-tool-call-1",
  216. status: "success",
  217. output: { text: "子任务已完成" },
  218. });
  219. expect(result.rows[2]).not.toHaveProperty("progress");
  220. expect(result.rows[2]).not.toHaveProperty("approvalInteractionId");
  221. expect(result.rows[2]).not.toHaveProperty("workId");
  222. expect(result.rows[3]).not.toHaveProperty("feedback");
  223. expect(JSON.stringify(result.rows)).not.toMatch(
  224. /local-product-turn-a|local-turn-a|local-entity|local-tool-call|source-command|client-desktop|approval-1|local-work/u,
  225. );
  226. });
  227. it("allows rows to share one persistent entity identity", () => {
  228. const rows = rowsWithCompletedSubagent();
  229. rows[1] = { ...rows[1]!, entityId: rows[0]!.entityId } as ConversationRow;
  230. const result = build(rows);
  231. expect(result.rows[0]?.entityId).toBe("share-entity-1");
  232. expect(result.rows[1]?.entityId).toBe("share-entity-1");
  233. });
  234. it("is deterministic and rejects a dangling retained entity reference", () => {
  235. const first = build();
  236. const second = build();
  237. expect(second).toEqual(first);
  238. const header = first.rows[0];
  239. if (header?.kind !== "turnHeader" || !header.workSegments?.[0]) {
  240. throw new Error("Expected projected turn header work segment");
  241. }
  242. header.workSegments[0].triggerEntityId = "share-entity-999";
  243. expect(() =>
  244. assertConversationSharePublicProjection({
  245. rows: first.rows,
  246. selectedProductTurnIds: first.selectedProductTurnIds,
  247. }),
  248. ).toThrowError(expect.objectContaining({ kind: "invalid_conversation" }));
  249. });
  250. it("rejects active rows before preparing a share", () => {
  251. const rows = rowsWithCompletedSubagent();
  252. rows[0] = { ...rows[0]!, kind: "turnHeader", state: "running" };
  253. expectBuildFailure(rows, "invalid_conversation");
  254. });
  255. it("drops local attachment refs until the publication stage rewrites them", () => {
  256. const rows = rowsWithCompletedSubagent();
  257. rows[1] = {
  258. ...rows[1]!,
  259. kind: "userInput",
  260. attachments: [
  261. {
  262. ref: "attachment/local-file",
  263. fileName: "report.pdf",
  264. mime: "application/pdf",
  265. bytes: 10,
  266. },
  267. ],
  268. };
  269. const result = build(rows);
  270. expect(result.rows.find((row) => row.kind === "userInput")).not.toHaveProperty("attachments");
  271. });
  272. it("preserves share attachment refs in the public projection", () => {
  273. const rows = rowsWithCompletedSubagent();
  274. rows[1] = {
  275. ...rows[1]!,
  276. kind: "userInput",
  277. attachments: [
  278. {
  279. ref: "zcode-artifact://share/share-input-artifact-1",
  280. previewRef: "zcode-artifact://share/share-input-artifact-1",
  281. fileName: "pasted-text.txt",
  282. mime: "text/plain",
  283. bytes: 10,
  284. },
  285. ],
  286. };
  287. const result = build(rows);
  288. expect(result.rows.find((row) => row.kind === "userInput")).toMatchObject({
  289. attachments: [
  290. expect.objectContaining({ ref: "zcode-artifact://share/share-input-artifact-1" }),
  291. ],
  292. });
  293. });
  294. it.each([
  295. ["data:text/plain;base64,YQ==", "unsafe_structure"],
  296. ["file:///tmp/report.html", "unsafe_structure"],
  297. ["zcode-artifact://share/report", "artifact_protocol_not_ready"],
  298. ] as const)("rejects unsupported local reference %s", (text, kind) => {
  299. const rows = rowsWithCompletedSubagent();
  300. rows[4] = {
  301. ...rows[4]!,
  302. kind: "assistantText",
  303. text,
  304. state: "complete",
  305. };
  306. expectBuildFailure(rows, kind);
  307. });
  308. it("SHARE02:移除本地 truncated 引用但保留可公开的工具输出预览", () => {
  309. const rows = rowsWithCompletedSubagent();
  310. rows[2] = {
  311. ...rows[2]!,
  312. kind: "toolCall",
  313. output: {
  314. text: "head...tail",
  315. truncated: { totalBytes: 100_000, ref: "tool-output/local-tool-call" },
  316. },
  317. };
  318. const projection = build(rows);
  319. expect(projection.rows.find((row) => row.kind === "toolCall")?.output).toEqual({
  320. text: "head...tail",
  321. });
  322. });
  323. });
  324. // 与 zcode-server 的 testdata/workflow-displays.json 同步,覆盖跨语言分享契约。
  325. const workflowDisplays: unknown[] = JSON.parse(
  326. await readFile(new URL("./fixtures/workflow-displays.json", import.meta.url), "utf8"),
  327. );
  328. describe("workflow display public projection", () => {
  329. it.each(workflowDisplays)("保留完整展示并可在落地页/导入端解码:%j", (fixture) => {
  330. const display = toolCallDisplaySchema.parse(fixture);
  331. const rows = rowsWithCompletedSubagent();
  332. const tool = rows.find((row) => row.kind === "toolCall")!;
  333. tool.display = display;
  334. const projection = build(rows);
  335. const published = projection.rows.find((row) => row.kind === "toolCall")!;
  336. expect(published.display).toEqual(display);
  337. expect(published.output).toEqual(tool.output);
  338. const decoded = decodeConversationShareRows(projection.rows);
  339. expect(decoded.unsupportedCount).toBe(0);
  340. expect(decoded.rows.find((row) => row.kind === "toolCall")).toEqual(published);
  341. // 公开快照不能继续引用源 session 的嵌套可变展示。
  342. expect(published.display).not.toBe(display);
  343. if (display.kind === "create_workflow" && published.display?.kind === "create_workflow") {
  344. expect(published.display.causalityGraph).not.toBe(display.causalityGraph);
  345. }
  346. });
  347. it("未知嵌套 display 字段在预检投影阶段拒绝", () => {
  348. const rows = rowsWithCompletedSubagent();
  349. const tool = rows.find((row) => row.kind === "toolCall")!;
  350. tool.display = {
  351. kind: "create_workflow",
  352. ok: true,
  353. errorCount: 0,
  354. diagnostics: [{ line: 0, column: 0, code: 1, message: "test", secret: "private" }],
  355. } as unknown as typeof tool.display;
  356. expectBuildFailure(rows, "invalid_conversation");
  357. });
  358. });