conversationShareContract.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. conversationShareArtifactUploadDataSchema,
  4. conversationShareCapabilitiesDataSchema,
  5. conversationShareCapabilitiesWireSchema,
  6. narrowConversationShareCapabilities,
  7. conversationShareConfirmDataSchema,
  8. conversationShareConfirmRequestSchema,
  9. conversationShareContinuationDataSchema,
  10. conversationShareContinuationRequestSchema,
  11. conversationShareErrorEnvelopeSchema,
  12. classifyConversationShareError,
  13. conversationSharePreparationDataSchema,
  14. conversationSharePreparationRequestSchema,
  15. conversationSharePreviewDataSchema,
  16. conversationSharePreviewArtifactSchema,
  17. conversationShareContinuationArtifactSchema,
  18. createConversationShareSuccessEnvelopeSchema,
  19. decodeConversationShareRows,
  20. isConversationShareSchemaVersionSupported,
  21. localizeConversationShareUrl,
  22. parseConversationSharePathname,
  23. } from "../src/conversation-share.js";
  24. import { sharedContextImportStateSchema } from "../src/zcode-protocol-v4/shared-context-import.js";
  25. const SHA_256 = "a".repeat(64);
  26. const completedRows = [
  27. {
  28. rowId: 1,
  29. turnId: "turn-1",
  30. productTurnId: "product-turn-1",
  31. createdAt: 1_788_415_000_000,
  32. createdAtSeq: 1,
  33. kind: "turnHeader",
  34. origin: "userInput",
  35. state: "completedSuccess",
  36. startedAt: 1_788_415_000_000,
  37. endedAt: 1_788_415_001_000,
  38. },
  39. {
  40. rowId: 2,
  41. turnId: "turn-1",
  42. productTurnId: "product-turn-1",
  43. createdAt: 1_788_415_000_100,
  44. createdAtSeq: 2,
  45. kind: "assistantText",
  46. text: "已完成",
  47. state: "complete",
  48. },
  49. ] as const;
  50. const artifactDescriptor = {
  51. artifact_id: "artifact-public-id",
  52. logical_artifact_key: "report",
  53. producer_product_turn_id: "product-turn-1",
  54. artifact_version: 1,
  55. state: "current",
  56. ref: "zcode-artifact://share/artifact-public-id",
  57. artifact_type: "pptx",
  58. display_name: "季度报告.pptx",
  59. original_path: "/workspace/output/季度报告.pptx",
  60. extension: "pptx",
  61. mime_type: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  62. size_bytes: 102_400,
  63. sha256: SHA_256,
  64. } as const;
  65. describe("conversation share API revision 23 contract", () => {
  66. it("按语言前缀解析分享路径,只认已知形状", () => {
  67. expect(parseConversationSharePathname("/cn/share/abc")).toEqual({
  68. rawCode: "abc",
  69. locale: "zh-CN",
  70. });
  71. expect(parseConversationSharePathname("/share/abc")).toEqual({
  72. rawCode: "abc",
  73. locale: "en-US",
  74. });
  75. expect(parseConversationSharePathname("/share/abc/extra")).toBeNull();
  76. expect(parseConversationSharePathname("/cn/shared/abc")).toBeNull();
  77. expect(parseConversationSharePathname("/share")).toBeNull();
  78. });
  79. it("把分享链接改写到目标语言站点,且不改动 code 段", () => {
  80. expect(localizeConversationShareUrl("https://zcode.z.ai/cn/share/abc", "en-US")).toBe(
  81. "https://zcode.z.ai/share/abc",
  82. );
  83. expect(localizeConversationShareUrl("https://zcode.z.ai/share/abc", "zh-CN")).toBe(
  84. "https://zcode.z.ai/cn/share/abc",
  85. );
  86. // 已经是目标语言时保持原样,端口与 query 不受影响。
  87. expect(
  88. localizeConversationShareUrl("https://zcode.z.ai:8443/cn/share/a.b~c?x=1", "zh-CN"),
  89. ).toBe("https://zcode.z.ai:8443/cn/share/a.b~c?x=1");
  90. });
  91. it("形状不认识的链接原样返回,绝不猜着改", () => {
  92. // 服务端将来若换 URL 形状或独立域名,这里必须安静地不作为而不是改错。
  93. for (const url of [
  94. "https://zcode.z.ai/s/abc",
  95. "https://zcode.z.ai/cn/share/abc/extra",
  96. "https://zcode.z.ai/cn/share",
  97. "not-a-url",
  98. "",
  99. ]) {
  100. expect(localizeConversationShareUrl(url, "en-US")).toBe(url);
  101. }
  102. });
  103. it("sharedContextImport 只接受规范 /cn/share/ 回链", () => {
  104. // 回归守卫:导入时若把回链按界面语言本地化成 /share/<code>,这里会直接拒掉,
  105. // 英文界面的导入就会挂。所以持久化必须存规范路径,本地化只在展示时做。
  106. const base = {
  107. contextId: "shared-context-1",
  108. title: "来自分享:Shared Research",
  109. status: "pending" as const,
  110. };
  111. expect(
  112. sharedContextImportStateSchema.safeParse({
  113. ...base,
  114. shareUrl: "https://zcode.z.ai/cn/share/abc",
  115. }).success,
  116. ).toBe(true);
  117. const localized = sharedContextImportStateSchema.safeParse({
  118. ...base,
  119. shareUrl: "https://zcode.z.ai/share/abc",
  120. });
  121. // 英文站路径只能作为 legacy { title } 形状通过,v2 形状(带 contextId/status)会被拒。
  122. expect(localized.success && "contextId" in localized.data).toBe(false);
  123. });
  124. it("parses capabilities with all three access modes", () => {
  125. const parsed = conversationShareCapabilitiesDataSchema.parse({
  126. schema_version: 1,
  127. ttl_ms: 604_800_000,
  128. access_modes: ["private", "public_readonly", "public_importable"],
  129. max_rows: 500,
  130. max_payload_bytes: 4_194_304,
  131. max_artifact_count: 20,
  132. max_artifact_bytes: 20_971_520,
  133. max_total_artifact_bytes: 104_857_600,
  134. allowed_artifacts: [
  135. {
  136. type: "image",
  137. extensions: ["png", "jpg", "jpeg", "webp"],
  138. mime_types: ["image/png", "image/jpeg", "image/webp"],
  139. },
  140. ],
  141. });
  142. expect(parsed.access_modes).toEqual(["private", "public_readonly", "public_importable"]);
  143. });
  144. it("tolerates artifact types the client does not know yet", () => {
  145. // 线上故障:后端在 allowed_artifacts 里新增类型后,严格枚举让整份 capabilities 解析
  146. // 失败,发布在 collecting 阶段就抛 invalid_contract。能力发现列表必须向前兼容。
  147. const wire = conversationShareCapabilitiesWireSchema.parse({
  148. schema_version: 1,
  149. ttl_ms: 604_800_000,
  150. access_modes: ["private"],
  151. max_rows: 500,
  152. max_payload_bytes: 4_194_304,
  153. max_artifact_count: 20,
  154. max_artifact_bytes: 20_971_520,
  155. max_total_artifact_bytes: 104_857_600,
  156. allowed_artifacts: [
  157. { type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] },
  158. { type: "some-future-type", extensions: ["fut"], mime_types: ["application/x-future"] },
  159. ],
  160. });
  161. const { capabilities, unsupportedArtifactTypes } = narrowConversationShareCapabilities(wire);
  162. expect(capabilities.allowed_artifacts.map((entry) => entry.type)).toEqual(["pdf"]);
  163. expect(unsupportedArtifactTypes).toEqual(["some-future-type"]);
  164. });
  165. it("保留服务端的 md 结果物类型,不再把它当未知类型削掉", () => {
  166. // Bug 根因:本地枚举缺 md → 服务端允许的 md 被丢弃 → 又拿被削过的白名单
  167. // 告诉用户「.md 不支持,请取消该轮」。本地能抽出 .md 候选,就必须认这个类型。
  168. const wire = conversationShareCapabilitiesWireSchema.parse({
  169. schema_version: 1,
  170. ttl_ms: 604_800_000,
  171. access_modes: ["private"],
  172. max_rows: 500,
  173. max_payload_bytes: 4_194_304,
  174. max_artifact_count: 20,
  175. max_artifact_bytes: 20_971_520,
  176. max_total_artifact_bytes: 104_857_600,
  177. allowed_artifacts: [
  178. { type: "md", extensions: ["md"], mime_types: ["text/markdown"] },
  179. { type: "html", extensions: ["html", "htm"], mime_types: ["text/html"] },
  180. { type: "text", extensions: ["txt"], mime_types: ["text/plain"] },
  181. ],
  182. });
  183. const { capabilities, unsupportedArtifactTypes } = narrowConversationShareCapabilities(wire);
  184. expect(capabilities.allowed_artifacts.map((entry) => entry.type)).toEqual([
  185. "md",
  186. "html",
  187. "text",
  188. ]);
  189. expect(unsupportedArtifactTypes).toEqual([]);
  190. });
  191. it("parses preparation request and confirmed idempotency response", () => {
  192. expect(
  193. conversationSharePreparationRequestSchema.parse({
  194. client_request_id: "request-uuid",
  195. title: "分享标题",
  196. schema_version: 1,
  197. access_mode: "public_readonly",
  198. payload_sha256: SHA_256,
  199. artifact_count: 0,
  200. }),
  201. ).toMatchObject({ artifact_count: 0, access_mode: "public_readonly" });
  202. const parsed = conversationSharePreparationDataSchema.parse({
  203. preparation_id: "preparation-id",
  204. status: "confirmed",
  205. access_mode: "public_readonly",
  206. expires_at: 1_789_020_800_000,
  207. share: {
  208. share_code: "base64url-hmac-code",
  209. share_url: "https://example.com/share/base64url-hmac-code",
  210. access_mode: "public_readonly",
  211. expires_at: 1_789_020_800_000,
  212. },
  213. });
  214. expect(parsed.status).toBe("confirmed");
  215. });
  216. it("parses artifact upload response", () => {
  217. expect(
  218. conversationShareArtifactUploadDataSchema.parse({
  219. artifact_id: artifactDescriptor.artifact_id,
  220. size_bytes: artifactDescriptor.size_bytes,
  221. sha256: SHA_256,
  222. status: "uploaded",
  223. safety_status: "pending",
  224. }),
  225. ).toEqual({
  226. artifact_id: "artifact-public-id",
  227. size_bytes: 102_400,
  228. sha256: SHA_256,
  229. status: "uploaded",
  230. safety_status: "pending",
  231. });
  232. });
  233. it.each([undefined, "", " "])(
  234. "rejects missing or empty artifact safety status: %j",
  235. (safetyStatus) => {
  236. expect(() =>
  237. conversationShareArtifactUploadDataSchema.parse({
  238. artifact_id: artifactDescriptor.artifact_id,
  239. size_bytes: artifactDescriptor.size_bytes,
  240. sha256: SHA_256,
  241. status: "uploaded",
  242. ...(safetyStatus === undefined ? {} : { safety_status: safetyStatus }),
  243. }),
  244. ).toThrow();
  245. },
  246. );
  247. it("parses confirm request with formal ConversationRow values", () => {
  248. const parsed = conversationShareConfirmRequestSchema.parse({
  249. selected_product_turn_ids: ["product-turn-1"],
  250. projection: { rows: completedRows },
  251. integrity: {
  252. projection_sha256: SHA_256,
  253. artifact_set_sha256: SHA_256,
  254. },
  255. disclosure_confirmation: {
  256. version: 1,
  257. accepted_at: 1_788_415_002_000,
  258. acknowledged_no_secret_detection: true,
  259. },
  260. });
  261. expect(Object.keys(parsed)).toEqual([
  262. "selected_product_turn_ids",
  263. "projection",
  264. "integrity",
  265. "disclosure_confirmation",
  266. ]);
  267. expect(parsed.projection.rows[0]?.kind).toBe("turnHeader");
  268. expect(
  269. conversationShareConfirmDataSchema.parse({
  270. share_code: "base64url-hmac-code",
  271. share_url: "https://example.com/share/base64url-hmac-code",
  272. access_mode: "private",
  273. expires_at: 1_789_020_800_000,
  274. }).share_code,
  275. ).toBe("base64url-hmac-code");
  276. });
  277. it("keeps preview URLs and continuation download URLs as distinct fields", () => {
  278. const preview = conversationSharePreviewDataSchema.parse({
  279. schema_version: 1,
  280. share: {
  281. title: "分享标题",
  282. access_mode: "public_importable",
  283. created_at: 1_788_415_002_000,
  284. expires_at: 1_789_020_800_000,
  285. },
  286. rows: completedRows,
  287. artifacts: [
  288. {
  289. ...artifactDescriptor,
  290. url: "https://signed.example.com/preview",
  291. url_expires_at: 1_788_415_600_000,
  292. },
  293. ],
  294. integrity: {
  295. projection_sha256: SHA_256,
  296. artifact_set_sha256: SHA_256,
  297. },
  298. });
  299. const continuationRequest = conversationShareContinuationRequestSchema.parse({
  300. schema_version: 1,
  301. client_request_id: "import-request-uuid",
  302. });
  303. const continuation = conversationShareContinuationDataSchema.parse({
  304. schema_version: 1,
  305. import_grant_id: "deterministic-grant-id",
  306. import_grant_expires_at: 1_788_415_600_000,
  307. share: {
  308. share_id: "internal-share-id",
  309. title: "分享标题",
  310. access_mode: "public_importable",
  311. created_at: 1_788_415_002_000,
  312. expires_at: 1_789_020_800_000,
  313. },
  314. rows: completedRows,
  315. artifacts: [
  316. {
  317. ...artifactDescriptor,
  318. download_url: "https://signed.example.com/download",
  319. download_url_expires_at: 1_788_415_600_000,
  320. },
  321. ],
  322. integrity: {
  323. projection_sha256: SHA_256,
  324. artifact_set_sha256: SHA_256,
  325. },
  326. });
  327. expect(preview.artifacts[0]?.url).toContain("/preview");
  328. expect(continuation.artifacts[0]?.download_url).toContain("/download");
  329. expect(continuationRequest.schema_version).toBe(1);
  330. });
  331. it("rejects the legacy payload hash in confirm integrity", () => {
  332. expect(() =>
  333. conversationShareConfirmRequestSchema.parse({
  334. selected_product_turn_ids: ["product-turn-1"],
  335. projection: { rows: completedRows },
  336. integrity: {
  337. projection_sha256: SHA_256,
  338. artifact_set_sha256: SHA_256,
  339. payload_sha256: SHA_256,
  340. },
  341. disclosure_confirmation: {
  342. version: 1,
  343. accepted_at: 1_788_415_002_000,
  344. acknowledged_no_secret_detection: true,
  345. },
  346. }),
  347. ).toThrow();
  348. });
  349. it("accepts formal artifact rows and rejects incomplete ones", () => {
  350. const artifactRow = {
  351. rowId: 3,
  352. turnId: "turn-1",
  353. productTurnId: "product-turn-1",
  354. createdAt: 1_788_415_000_200,
  355. createdAtSeq: 3,
  356. kind: "artifact",
  357. artifactVersionId: "artifact-public-id",
  358. logicalArtifactKey: "report",
  359. displayName: "季度报告.pdf",
  360. artifactType: "pdf",
  361. mimeType: "application/pdf",
  362. sizeBytes: 102_400,
  363. sha256: SHA_256,
  364. ref: "zcode-artifact://share/artifact-public-id",
  365. state: "current",
  366. } as const;
  367. expect(
  368. conversationShareConfirmRequestSchema
  369. .parse({
  370. selected_product_turn_ids: ["product-turn-1"],
  371. projection: { rows: [...completedRows, artifactRow] },
  372. integrity: { projection_sha256: SHA_256, artifact_set_sha256: SHA_256 },
  373. disclosure_confirmation: {
  374. version: 1,
  375. accepted_at: 1_788_415_002_000,
  376. acknowledged_no_secret_detection: true,
  377. },
  378. })
  379. .projection.rows.at(-1),
  380. ).toEqual(artifactRow);
  381. expect(() =>
  382. conversationShareCapabilitiesDataSchema.parse({
  383. schema_version: 1,
  384. ttl_ms: 1,
  385. access_modes: ["private"],
  386. max_rows: 1,
  387. max_payload_bytes: 1,
  388. max_artifact_count: 0,
  389. max_artifact_bytes: 1,
  390. max_total_artifact_bytes: 1,
  391. allowed_artifacts: [],
  392. unexpected: true,
  393. }),
  394. ).toThrow();
  395. // 入站 preview 的 rows 是 unknown[]:残缺行不再打死整份分享,而是由
  396. // decodeConversationShareRows 单独跳过(见「跨版本前向兼容」一节的用例)。
  397. const previewWithBrokenRow = conversationSharePreviewDataSchema.parse({
  398. schema_version: 1,
  399. share: {
  400. title: "分享标题",
  401. access_mode: "public_readonly",
  402. created_at: 1,
  403. expires_at: 2,
  404. },
  405. rows: [
  406. {
  407. rowId: 1,
  408. turnId: "turn-1",
  409. productTurnId: "product-turn-1",
  410. createdAt: 1,
  411. createdAtSeq: 1,
  412. kind: "artifact",
  413. artifactVersionId: "artifact-public-id",
  414. },
  415. ],
  416. artifacts: [],
  417. integrity: {
  418. projection_sha256: SHA_256,
  419. artifact_set_sha256: SHA_256,
  420. },
  421. });
  422. const decodedBrokenRow = decodeConversationShareRows(previewWithBrokenRow.rows);
  423. expect(decodedBrokenRow.rows).toHaveLength(0);
  424. expect(decodedBrokenRow.unsupportedCount).toBe(1);
  425. expect(decodedBrokenRow.unsupportedKinds).toEqual(["artifact"]);
  426. });
  427. });
  428. /**
  429. * 跨版本前向兼容。
  430. *
  431. * 分享内容在 4 个可独立升级/回滚的部件之间流动(发布端 Desktop、Share API 后端、
  432. * 独立部署的落地页镜像、导入端 Desktop),它们不可能同版本。这一节把「什么样的演进
  433. * 不许打死老消费端」钉成回归,避免以后每次改分享内容都要重新推演一遍兼容性。
  434. */
  435. describe("conversation share cross-version forward compatibility", () => {
  436. const share = {
  437. title: "分享标题",
  438. access_mode: "public_readonly",
  439. created_at: 1,
  440. expires_at: 2,
  441. } as const;
  442. const integrity = { projection_sha256: SHA_256, artifact_set_sha256: SHA_256 } as const;
  443. const assistantRow = {
  444. rowId: 10,
  445. turnId: "turn-1",
  446. createdAt: 1,
  447. createdAtSeq: 1,
  448. kind: "assistantText",
  449. text: "hi",
  450. state: "complete",
  451. } as const;
  452. const previewOf = (overrides: Record<string, unknown> = {}) => ({
  453. schema_version: 1,
  454. share,
  455. rows: [assistantRow],
  456. artifacts: [],
  457. integrity,
  458. ...overrides,
  459. });
  460. it("后端给响应加顶层字段时仍然可解析", () => {
  461. expect(() =>
  462. conversationSharePreviewDataSchema.parse(previewOf({ view_count: 3 })),
  463. ).not.toThrow();
  464. });
  465. it("后端给 share 元数据加字段时仍然可解析", () => {
  466. expect(() =>
  467. conversationSharePreviewDataSchema.parse(
  468. previewOf({ share: { ...share, owner_display_name: "someone" } }),
  469. ),
  470. ).not.toThrow();
  471. });
  472. it("后端给 artifact descriptor 加字段时仍然可解析", () => {
  473. const artifact = {
  474. artifact_id: "artifact-1",
  475. logical_artifact_key: "report",
  476. producer_product_turn_id: "product-turn-1",
  477. artifact_version: 1,
  478. state: "current",
  479. ref: "zcode-artifact://share/artifact-1",
  480. artifact_type: "md",
  481. display_name: "report.md",
  482. extension: "md",
  483. mime_type: "text/markdown",
  484. size_bytes: 1,
  485. sha256: SHA_256,
  486. url: "https://example.com/a",
  487. url_expires_at: 3,
  488. // 后端将来新增的安全扫描字段
  489. virus_scan: "clean",
  490. };
  491. expect(() =>
  492. conversationSharePreviewDataSchema.parse(previewOf({ artifacts: [artifact] })),
  493. ).not.toThrow();
  494. });
  495. it("后端上线新业务错误码时保留服务端 msg,不退化成无上下文的 HTTP 错误", () => {
  496. const parsed = conversationShareErrorEnvelopeSchema.parse({ code: 3299, msg: "新错误" });
  497. expect(parsed).toEqual({ code: 3299, msg: "新错误" });
  498. });
  499. it("后端给成功信封写非空 msg 时不判成契约错误", () => {
  500. expect(() =>
  501. createConversationShareSuccessEnvelopeSchema(conversationSharePreviewDataSchema).parse({
  502. code: 0,
  503. msg: "ok",
  504. data: previewOf(),
  505. }),
  506. ).not.toThrow();
  507. });
  508. it("后端给 capabilities 加限额字段或新 access mode 时,能力发现不被打死", () => {
  509. const wire = conversationShareCapabilitiesWireSchema.parse({
  510. schema_version: 1,
  511. ttl_ms: 1,
  512. access_modes: ["private", "public_readonly", "public_importable", "public_team"],
  513. max_rows: 1,
  514. max_payload_bytes: 1,
  515. max_artifact_count: 0,
  516. max_artifact_bytes: 1,
  517. max_total_artifact_bytes: 1,
  518. allowed_artifacts: [],
  519. // 后端将来新增的限额
  520. max_title_length: 100,
  521. });
  522. const narrowed = narrowConversationShareCapabilities(wire);
  523. expect(narrowed.capabilities.access_modes).toEqual([
  524. "private",
  525. "public_readonly",
  526. "public_importable",
  527. ]);
  528. expect(narrowed.unsupportedAccessModes).toEqual(["public_team"]);
  529. });
  530. // 这是本次加固的核心回归:additive 的 row 演进曾经会让所有老导入端算出不同的
  531. // projection_sha256,把「加一个 optional 字段」误报成「分享文件校验失败」。
  532. it("row 多一个未知 optional 字段时,原始值原样保留(哈希才能对得上)", () => {
  533. const futureRow = { ...assistantRow, futureField: "x" };
  534. const parsed = conversationSharePreviewDataSchema.parse(previewOf({ rows: [futureRow] }));
  535. expect(parsed.rows[0]).toEqual(futureRow);
  536. const decoded = decodeConversationShareRows(parsed.rows);
  537. expect(decoded.unsupportedCount).toBe(0);
  538. expect(decoded.rows).toHaveLength(1);
  539. });
  540. it.each([
  541. ["新增 row kind", { ...assistantRow, kind: "videoClip" }, "videoClip"],
  542. ["已有 kind 的新 enum 值", { ...assistantRow, state: "aborted" }, "assistantText"],
  543. [
  544. "新增 timelineMarker type",
  545. {
  546. rowId: 11,
  547. turnId: "turn-1",
  548. createdAt: 1,
  549. createdAtSeq: 2,
  550. kind: "timelineMarker",
  551. marker: { type: "brandNewMarker", detail: "x" },
  552. },
  553. "timelineMarker",
  554. ],
  555. [
  556. "新增 artifact type",
  557. {
  558. rowId: 12,
  559. turnId: "turn-1",
  560. createdAt: 1,
  561. createdAtSeq: 3,
  562. kind: "artifact",
  563. artifactVersionId: "a",
  564. logicalArtifactKey: "k",
  565. displayName: "data.csv",
  566. artifactType: "csv",
  567. mimeType: "text/csv",
  568. sizeBytes: 1,
  569. sha256: SHA_256,
  570. ref: "zcode-artifact://share/a",
  571. state: "current",
  572. },
  573. "artifact",
  574. ],
  575. ])("%s 只丢该行,其余内容照常呈现", (_label, futureRow, expectedKind) => {
  576. const parsed = conversationSharePreviewDataSchema.parse(
  577. previewOf({ rows: [assistantRow, futureRow] }),
  578. );
  579. const decoded = decodeConversationShareRows(parsed.rows);
  580. expect(decoded.rows).toHaveLength(1);
  581. expect(decoded.rows[0]?.rowId).toBe(assistantRow.rowId);
  582. expect(decoded.unsupportedCount).toBe(1);
  583. expect(decoded.unsupportedKinds).toEqual([expectedKind]);
  584. });
  585. it("schema_version 比本端新时收得下,由调用方转成「请升级」而不是「格式无效」", () => {
  586. const parsed = conversationSharePreviewDataSchema.parse(previewOf({ schema_version: 2 }));
  587. expect(parsed.schema_version).toBe(2);
  588. expect(isConversationShareSchemaVersionSupported(parsed.schema_version)).toBe(false);
  589. expect(isConversationShareSchemaVersionSupported(1)).toBe(true);
  590. });
  591. it("出站请求仍然严格:多带字段是本端 bug,必须当场炸掉", () => {
  592. expect(() =>
  593. conversationShareContinuationRequestSchema.parse({
  594. schema_version: 1,
  595. client_request_id: "request-1",
  596. unexpected: true,
  597. }),
  598. ).toThrow();
  599. });
  600. });
  601. describe("share error contract", () => {
  602. it.each([
  603. [3200, "feature_disabled"],
  604. [3201, "authentication_required"],
  605. [3203, "unsupported_schema_version"],
  606. [3204, "invalid_contract"],
  607. [3205, "invalid_conversation"],
  608. [3206, "disclosure_required"],
  609. [3207, "unsafe_structure"],
  610. [3208, "artifact_not_allowed"],
  611. [3209, "limit_exceeded"],
  612. [3210, "upload_incomplete"],
  613. [3211, "not_found"],
  614. [3212, "expired"],
  615. [3213, "authentication_required"],
  616. [3214, "import_not_allowed"],
  617. [3215, "safety_check_pending"],
  618. [3216, "safety_check_rejected"],
  619. [3217, "safety_check_unavailable"],
  620. ])("shares code %s semantics across clients", (code, kind) => {
  621. expect(classifyConversationShareError(400, code as number)).toBe(kind);
  622. });
  623. it("keeps a failure even when its optional diagnostic fields are invalid", () => {
  624. const error = conversationShareErrorEnvelopeSchema.parse({
  625. code: 3205,
  626. msg: "invalid",
  627. logid: "https://secret",
  628. data: {
  629. rule: "field_type",
  630. row_index: -1,
  631. field: "a".repeat(1000),
  632. path: "/private/file",
  633. row_kind: "assistantText",
  634. contents: "secret",
  635. },
  636. });
  637. expect(error).toMatchObject({
  638. code: 3205,
  639. data: { rule: "field_type", row_kind: "assistantText" },
  640. });
  641. expect(error.data?.path).toBeUndefined();
  642. expect(error.data?.field).toBeUndefined();
  643. expect(error.data?.row_index).toBeUndefined();
  644. expect(error.logid).toBeUndefined();
  645. expect(JSON.stringify(error)).not.toContain("secret");
  646. });
  647. });
  648. it.each([
  649. "javascript:alert(1)",
  650. "data:text/html,test",
  651. "file:///workspace/report.pdf",
  652. "custom://host/file",
  653. ])("公开产物拒绝非 HTTP(S) URL %s", (url) => {
  654. expect(
  655. conversationSharePreviewArtifactSchema.safeParse({
  656. ...artifactDescriptor,
  657. url,
  658. url_expires_at: 2000,
  659. }).success,
  660. ).toBe(false);
  661. });
  662. it.each(["https://files.example.com/report.pdf", "http://localhost:8080/report.pdf"])(
  663. "公开产物保留 HTTP(S) URL %s",
  664. (url) => {
  665. expect(
  666. conversationSharePreviewArtifactSchema.safeParse({
  667. ...artifactDescriptor,
  668. url,
  669. url_expires_at: 2000,
  670. }).success,
  671. ).toBe(true);
  672. },
  673. );
  674. it("导入附件复用公开 URL 协议边界,非法 URL 返回校验失败而不抛出", () => {
  675. for (const download_url of ["javascript:alert(1)", "file:///workspace/report.pdf", "not a url"])
  676. expect(
  677. conversationShareContinuationArtifactSchema.safeParse({
  678. ...artifactDescriptor,
  679. download_url,
  680. download_url_expires_at: 2000,
  681. }).success,
  682. ).toBe(false);
  683. });