conversationShareHttpClient.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. import type { ApiClient } from "@zcode/shared";
  2. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  3. const { debugLog, warnLog } = vi.hoisted(() => ({ debugLog: vi.fn(), warnLog: vi.fn() }));
  4. vi.mock("#src/logger/serviceLogger.js", () => ({
  5. createServiceLogger: () => ({
  6. debug: debugLog,
  7. info: vi.fn(),
  8. warn: warnLog,
  9. error: vi.fn(),
  10. }),
  11. }));
  12. import {
  13. ConversationShareClientError,
  14. ConversationShareHttpClient,
  15. } from "../src/conversation-share/conversationShareHttpClient.js";
  16. import { sha256ConversationShareJson } from "../src/conversation-share/conversationShareIntegrity.js";
  17. const SHA_256 = "a".repeat(64);
  18. /** continuation 的完整性由 client 复核,所以 fixture 必须带真哈希而不是占位串。 */
  19. const EMPTY_PROJECTION_SHA_256 = sha256ConversationShareJson([]);
  20. function success(data: unknown): Response {
  21. return new Response(JSON.stringify({ code: 0, msg: "", data }), {
  22. status: 200,
  23. headers: { "content-type": "application/json" },
  24. });
  25. }
  26. function createClient(
  27. request: ApiClient["request"],
  28. tokenProvider: () => Promise<string | null> = async () => "test-token",
  29. ) {
  30. return new ConversationShareHttpClient({
  31. apiClient: { request },
  32. baseUrl: "https://api.example.com/api/v1",
  33. tokenProvider,
  34. });
  35. }
  36. function makeConfirmRequest() {
  37. return {
  38. selected_product_turn_ids: ["share-product-turn-1"],
  39. projection: {
  40. rows: [
  41. {
  42. rowId: 1,
  43. turnId: "share-turn-1",
  44. productTurnId: "share-product-turn-1",
  45. createdAt: 1_000,
  46. createdAtSeq: 1,
  47. kind: "turnHeader" as const,
  48. origin: "userInput" as const,
  49. state: "completedSuccess" as const,
  50. startedAt: 1_000,
  51. endedAt: 1_100,
  52. },
  53. ],
  54. },
  55. integrity: {
  56. projection_sha256: SHA_256,
  57. artifact_set_sha256: SHA_256,
  58. },
  59. disclosure_confirmation: {
  60. version: 1 as const,
  61. accepted_at: 1_200,
  62. acknowledged_no_secret_detection: true as const,
  63. },
  64. };
  65. }
  66. describe("ConversationShareHttpClient", () => {
  67. it.each([
  68. [3216, 422, "safety_check_rejected"],
  69. [3217, 503, "safety_check_unavailable"],
  70. [2001, 500, "service_unavailable"],
  71. [2005, 500, "service_unavailable"],
  72. [2009, 500, "service_unavailable"],
  73. [9876, 422, "unknown"],
  74. ])("preserves code %s and classifies the failure", async (code, status, kind) => {
  75. const request = vi.fn(
  76. async () =>
  77. new Response(JSON.stringify({ code, msg: "server text", logid: "server-log-id" }), {
  78. status,
  79. }),
  80. );
  81. await expect(createClient(request).getCapabilities()).rejects.toMatchObject({
  82. kind,
  83. code,
  84. status,
  85. requestId: "server-log-id",
  86. details: { code },
  87. });
  88. });
  89. it.each([401, 429, 503])(
  90. "classifies HTTP %s before parsing an HTML error page",
  91. async (status) => {
  92. const request = vi.fn(async () => new Response("<html>gateway</html>", { status }));
  93. await expect(createClient(request).getCapabilities()).rejects.toMatchObject({
  94. kind:
  95. status === 401
  96. ? "authentication_required"
  97. : status === 429
  98. ? "rate_limited"
  99. : "service_unavailable",
  100. status,
  101. });
  102. },
  103. );
  104. it("keeps bounded validation coordinates and strips raw payload fields", async () => {
  105. const request = vi.fn(
  106. async () =>
  107. new Response(
  108. JSON.stringify({
  109. code: 3205,
  110. msg: "invalid",
  111. data: {
  112. rule: "field_type",
  113. path: "projection.rows[0].state",
  114. field: "state",
  115. row_index: 0,
  116. row_kind: "assistantText",
  117. text: "secret-content",
  118. },
  119. }),
  120. { status: 422 },
  121. ),
  122. );
  123. const error = await createClient(request)
  124. .getCapabilities()
  125. .catch((error: unknown) => error);
  126. expect(error).toMatchObject({
  127. kind: "invalid_conversation",
  128. details: {
  129. rejection: {
  130. rule: "field_type",
  131. path: "projection.rows[0].state",
  132. field: "state",
  133. row_index: 0,
  134. row_kind: "assistantText",
  135. },
  136. },
  137. });
  138. expect(JSON.stringify(error)).not.toContain("secret-content");
  139. });
  140. it("prefers millisecond retry advice for pending safety checks", async () => {
  141. const request = vi.fn(
  142. async () =>
  143. new Response(JSON.stringify({ code: 3215, msg: "pending" }), {
  144. status: 409,
  145. headers: { "Retry-After-Ms": "1250", "Retry-After": "2" },
  146. }),
  147. );
  148. await expect(createClient(request).confirm("p1", makeConfirmRequest())).rejects.toMatchObject({
  149. retryAfterMs: 1250,
  150. });
  151. });
  152. beforeEach(() => {
  153. debugLog.mockReset();
  154. warnLog.mockReset();
  155. });
  156. afterEach(() => {
  157. vi.restoreAllMocks();
  158. });
  159. it("sanitizes request ids on client error construction", () => {
  160. const error = new ConversationShareClientError({
  161. kind: "unknown",
  162. message: "bad request id",
  163. requestId: "https://signed.example/token",
  164. });
  165. expect(error.requestId).toBeUndefined();
  166. expect(error.details).toBeUndefined();
  167. });
  168. it("requests capabilities with Bearer authentication", async () => {
  169. const request = vi.fn(async () =>
  170. success({
  171. schema_version: 1,
  172. ttl_ms: 1_000,
  173. access_modes: ["private", "public_readonly", "public_importable"],
  174. max_rows: 500,
  175. max_payload_bytes: 4_194_304,
  176. max_artifact_count: 20,
  177. max_artifact_bytes: 20_971_520,
  178. max_total_artifact_bytes: 104_857_600,
  179. allowed_artifacts: [],
  180. }),
  181. );
  182. const capabilities = await createClient(request).getCapabilities();
  183. expect(capabilities.max_rows).toBe(500);
  184. expect(request.mock.calls[0]?.[0]).toBe("https://api.example.com/api/v1/shares/capabilities");
  185. expect(request.mock.calls[0]?.[1]?.method).toBe("GET");
  186. expect(new Headers(request.mock.calls[0]?.[1]?.headers).get("authorization")).toBe(
  187. "Bearer test-token",
  188. );
  189. });
  190. // 线上故障:后端在 allowed_artifacts 里新增了一种客户端枚举没有的类型,
  191. // 整个 capabilities 响应校验失败并抛 invalid_contract,把发布打死在 collecting 阶段
  192. // ——连不含任何结果物的发布也一起挂掉。未知类型必须丢弃而不是拒绝整份响应。
  193. it("drops unknown allowed artifact types instead of rejecting capabilities", async () => {
  194. const request = vi.fn(async () =>
  195. success({
  196. schema_version: 1,
  197. ttl_ms: 1_000,
  198. access_modes: ["private"],
  199. max_rows: 500,
  200. max_payload_bytes: 4_194_304,
  201. max_artifact_count: 20,
  202. max_artifact_bytes: 20_971_520,
  203. max_total_artifact_bytes: 104_857_600,
  204. allowed_artifacts: [
  205. { type: "pdf", extensions: ["pdf"], mime_types: ["application/pdf"] },
  206. { type: "markdown", extensions: ["md"], mime_types: ["text/markdown"] },
  207. { type: "html", extensions: ["html"], mime_types: ["text/html"] },
  208. ],
  209. }),
  210. );
  211. const capabilities = await createClient(request).getCapabilities();
  212. expect(capabilities.allowed_artifacts.map((entry) => entry.type)).toEqual(["pdf", "html"]);
  213. expect(capabilities.max_rows).toBe(500);
  214. });
  215. it("still rejects capabilities whose allowed artifact shape changed", async () => {
  216. // 形状变化(字段改名/缺字段)仍要响亮失败,否则客户端会误以为「什么都不允许」。
  217. const request = vi.fn(async () =>
  218. success({
  219. schema_version: 1,
  220. ttl_ms: 1_000,
  221. access_modes: ["private"],
  222. max_rows: 500,
  223. max_payload_bytes: 4_194_304,
  224. max_artifact_count: 20,
  225. max_artifact_bytes: 20_971_520,
  226. max_total_artifact_bytes: 104_857_600,
  227. allowed_artifacts: [{ type: "pdf", extension: ["pdf"], mime_types: ["application/pdf"] }],
  228. }),
  229. );
  230. await expect(createClient(request).getCapabilities()).rejects.toMatchObject({
  231. kind: "invalid_contract",
  232. });
  233. });
  234. it("serializes preparation as strict JSON", async () => {
  235. const request = vi.fn(async () =>
  236. success({
  237. preparation_id: "preparation-1",
  238. status: "preparing",
  239. access_mode: "public_readonly",
  240. expires_at: 2_000,
  241. }),
  242. );
  243. await createClient(request).createPreparation({
  244. client_request_id: "request-1",
  245. title: "分享标题",
  246. schema_version: 1,
  247. access_mode: "public_readonly",
  248. payload_sha256: SHA_256,
  249. artifact_count: 0,
  250. });
  251. const init = request.mock.calls[0]?.[1];
  252. expect(request.mock.calls[0]?.[0]).toBe("https://api.example.com/api/v1/shares/preparations");
  253. expect(init?.method).toBe("POST");
  254. expect(new Headers(init?.headers).get("content-type")).toBe("application/json");
  255. expect(JSON.parse(String(init?.body))).toEqual({
  256. client_request_id: "request-1",
  257. title: "分享标题",
  258. schema_version: 1,
  259. access_mode: "public_readonly",
  260. payload_sha256: SHA_256,
  261. artifact_count: 0,
  262. });
  263. });
  264. it("serializes confirm without logging conversation payload", async () => {
  265. const request = vi.fn(async () =>
  266. success({
  267. share_code: "share-1",
  268. share_url: "https://zcode.z.ai/cn/share/share-1",
  269. access_mode: "public_importable",
  270. expires_at: 2_000,
  271. }),
  272. );
  273. const confirmRequest = makeConfirmRequest();
  274. await createClient(request).confirm("preparation-1", confirmRequest);
  275. expect(JSON.parse(String(request.mock.calls[0]?.[1]?.body))).toEqual(confirmRequest);
  276. expect(debugLog).not.toHaveBeenCalled();
  277. });
  278. it("uploads descriptor and binary as multipart fields", async () => {
  279. const request = vi.fn(async () =>
  280. success({
  281. artifact_id: "artifact-1",
  282. size_bytes: 3,
  283. sha256: SHA_256,
  284. status: "uploaded",
  285. safety_status: "pending",
  286. }),
  287. );
  288. const descriptor = {
  289. artifact_id: "artifact-1",
  290. logical_artifact_key: "report",
  291. producer_product_turn_id: "product-turn-1",
  292. artifact_version: 1,
  293. state: "current" as const,
  294. ref: "zcode-artifact://share/artifact-1",
  295. artifact_type: "html" as const,
  296. display_name: "report.html",
  297. extension: "html",
  298. mime_type: "text/html",
  299. size_bytes: 3,
  300. sha256: SHA_256,
  301. };
  302. const upload = await createClient(request).uploadArtifact(
  303. "preparation / 1",
  304. descriptor,
  305. new Blob(["abc"], { type: "text/html" }),
  306. );
  307. expect(upload.safety_status).toBe("pending");
  308. expect(request.mock.calls[0]?.[0]).toBe(
  309. "https://api.example.com/api/v1/shares/preparations/preparation%20%2F%201/artifacts",
  310. );
  311. const body = request.mock.calls[0]?.[1]?.body;
  312. expect(body).toBeInstanceOf(FormData);
  313. const form = body as FormData;
  314. expect(JSON.parse(String(form.get("descriptor")))).toEqual(descriptor);
  315. expect(await (form.get("file") as Blob).text()).toBe("abc");
  316. expect(debugLog).toHaveBeenCalledWith(
  317. undefined,
  318. "conversation share artifact upload prepared",
  319. {
  320. preparationId: "preparation / 1",
  321. artifactId: "artifact-1",
  322. artifactType: "html",
  323. fileSizeBytes: 3,
  324. },
  325. );
  326. expect(JSON.stringify(debugLog.mock.calls)).not.toContain("abc");
  327. });
  328. it("allows anonymous preview without Authorization", async () => {
  329. const request = vi.fn(async () =>
  330. success({
  331. schema_version: 1,
  332. share: {
  333. title: "分享标题",
  334. access_mode: "public_readonly",
  335. created_at: 1,
  336. expires_at: 2,
  337. },
  338. rows: [],
  339. artifacts: [],
  340. integrity: {
  341. projection_sha256: SHA_256,
  342. artifact_set_sha256: SHA_256,
  343. },
  344. }),
  345. );
  346. await createClient(request, async () => null).getPreview("share / 1");
  347. expect(request.mock.calls[0]?.[0]).toBe(
  348. "https://api.example.com/api/v1/shares/share%20%2F%201/preview",
  349. );
  350. expect(new Headers(request.mock.calls[0]?.[1]?.headers).has("authorization")).toBe(false);
  351. });
  352. it("sends continuation without Authorization when the local token is missing", async () => {
  353. const request = vi.fn(async () =>
  354. success({
  355. schema_version: 1,
  356. import_grant_id: "grant-1",
  357. import_grant_expires_at: 2_000,
  358. share: {
  359. share_id: "share-1",
  360. title: "分享标题",
  361. access_mode: "public_importable",
  362. created_at: 1,
  363. expires_at: 2,
  364. },
  365. rows: [],
  366. artifacts: [],
  367. integrity: {
  368. projection_sha256: EMPTY_PROJECTION_SHA_256,
  369. artifact_set_sha256: EMPTY_PROJECTION_SHA_256,
  370. },
  371. }),
  372. );
  373. await createClient(request, async () => null).getContinuation("share / 1", {
  374. schema_version: 1,
  375. client_request_id: "request-1",
  376. });
  377. expect(request.mock.calls[0]?.[0]).toBe(
  378. "https://api.example.com/api/v1/shares/share%20%2F%201/continuation",
  379. );
  380. expect(new Headers(request.mock.calls[0]?.[1]?.headers).has("authorization")).toBe(false);
  381. });
  382. it("rejects authenticated routes before network when token is missing", async () => {
  383. const request = vi.fn<ApiClient["request"]>();
  384. await expect(createClient(request, async () => null).getCapabilities()).rejects.toMatchObject({
  385. kind: "authentication_required",
  386. status: 401,
  387. });
  388. expect(request).not.toHaveBeenCalled();
  389. });
  390. it("normalizes empty-body HTTP 401", async () => {
  391. const request = vi.fn(async () => new Response(null, { status: 401 }));
  392. await expect(createClient(request).getCapabilities()).rejects.toMatchObject({
  393. kind: "authentication_required",
  394. status: 401,
  395. });
  396. });
  397. it("normalizes documented business errors", async () => {
  398. const request = vi.fn(
  399. async () =>
  400. new Response(JSON.stringify({ code: 3209, msg: "share limit exceeded" }), {
  401. status: 413,
  402. }),
  403. );
  404. await expect(createClient(request).getCapabilities()).rejects.toMatchObject({
  405. kind: "limit_exceeded",
  406. status: 413,
  407. code: 3209,
  408. message: "share limit exceeded",
  409. });
  410. });
  411. it("does not expose the client request header when the response has no request id", async () => {
  412. const request = vi.fn(
  413. async () =>
  414. new Response(JSON.stringify({ code: 3209, msg: "share limit exceeded" }), {
  415. status: 413,
  416. }),
  417. );
  418. const error = await createClient(request)
  419. .getCapabilities()
  420. .catch((cause: unknown) => cause);
  421. expect(error).toMatchObject({ kind: "limit_exceeded", status: 413, code: 3209 });
  422. expect((error as { requestId?: string }).requestId).toBeUndefined();
  423. expect(new Headers(request.mock.calls[0]?.[1]?.headers).get("x-request-id")).toMatch(
  424. /^[A-Za-z0-9-]{20,}$/u,
  425. );
  426. });
  427. // Bug 根因:LB/网关返回的 5xx HTML 错误页(502/504)此前因 body 无法按 JSON 解析被归类为
  428. // invalid_contract(语义:服务端违反契约)。这是基础设施故障,归类 network 才能给出正确的
  429. // 用户提示与排障方向;request id 仍需保留用于对账。
  430. it("502 HTML 错误页归类 service_unavailable 且保留 request id", async () => {
  431. const request = vi.fn(
  432. async () =>
  433. new Response("<html>not-json</html>", {
  434. status: 502,
  435. headers: { "X-Request-Id": "server-request-malformed" },
  436. }),
  437. );
  438. await expect(createClient(request).getCapabilities()).rejects.toMatchObject({
  439. kind: "service_unavailable",
  440. status: 502,
  441. requestId: "server-request-malformed",
  442. });
  443. });
  444. it("504 空 body 响应也归类 service_unavailable 而不是 unknown", async () => {
  445. const request = vi.fn(async () => new Response(null, { status: 504 }));
  446. await expect(createClient(request).getCapabilities()).rejects.toMatchObject({
  447. kind: "service_unavailable",
  448. status: 504,
  449. });
  450. });
  451. it.each([400, 405])("HTTP %s 的非 JSON 拒绝不归类为成功响应契约损坏", async (status) => {
  452. const request = vi.fn(async () => new Response("<html>bad-request</html>", { status }));
  453. await expect(createClient(request).getCapabilities()).rejects.toMatchObject({
  454. kind: "unknown",
  455. status,
  456. });
  457. });
  458. // Retry-After 只接受 delay-seconds 和 IMF-fixdate;其余取值一律当作「后端没给建议」,
  459. // 由调用方回落到自己的重试节奏,不能解析成 0 或 NaN 毫秒。
  460. it.each([
  461. { label: "a positive delay-seconds value", header: "7", expected: 7_000 },
  462. {
  463. label: "a future IMF-fixdate",
  464. header: "Thu, 12 Aug 2027 10:00:10 GMT",
  465. expected: 10_000,
  466. nowUtc: Date.UTC(2027, 7, 12, 10, 0, 0),
  467. },
  468. { label: "a zero delay", header: "0", expected: null },
  469. { label: "a non-IMF ISO date", header: "2027-08-12", expected: null },
  470. { label: "an invalid value", header: "invalid", expected: null },
  471. ])("maps safety-check pending with $label", async ({ header, expected, nowUtc }) => {
  472. if (nowUtc !== undefined) vi.spyOn(Date, "now").mockReturnValue(nowUtc);
  473. const request = vi.fn(
  474. async () =>
  475. new Response(JSON.stringify({ code: 3215, msg: "share safety check pending" }), {
  476. status: 409,
  477. headers: { "Content-Type": "application/json", "Retry-After": header },
  478. }),
  479. );
  480. const error = await createClient(request)
  481. .confirm("preparation-1", makeConfirmRequest())
  482. .catch((cause: unknown) => cause);
  483. expect(error).toMatchObject({ kind: "safety_check_pending", status: 409, code: 3215 });
  484. if (expected === null) expect(error).not.toHaveProperty("retryAfterMs");
  485. else expect(error).toMatchObject({ retryAfterMs: expected });
  486. });
  487. it("keeps the response request id for safety-check pending", async () => {
  488. const request = vi.fn(
  489. async () =>
  490. new Response(JSON.stringify({ code: 3215, msg: "share safety check pending" }), {
  491. status: 409,
  492. headers: {
  493. "Content-Type": "application/json",
  494. "X-Request-Id": "server-request-3215",
  495. },
  496. }),
  497. );
  498. await expect(
  499. createClient(request).confirm("preparation-1", makeConfirmRequest()),
  500. ).rejects.toMatchObject({ kind: "safety_check_pending", requestId: "server-request-3215" });
  501. });
  502. it("preserves the server request id on rejected responses and logs it", async () => {
  503. const request = vi.fn(
  504. async () =>
  505. new Response(JSON.stringify({ code: 3209, msg: "share limit exceeded" }), {
  506. status: 413,
  507. headers: {
  508. "Content-Type": "application/json",
  509. "X-Request-Id": "server-request-123",
  510. },
  511. }),
  512. );
  513. const error = await createClient(request)
  514. .confirm("preparation-1", makeConfirmRequest())
  515. .catch((cause: unknown) => cause);
  516. expect(error).toMatchObject({
  517. kind: "limit_exceeded",
  518. code: 3209,
  519. requestId: "server-request-123",
  520. });
  521. expect(warnLog).toHaveBeenCalledWith(
  522. undefined,
  523. "conversation share API request rejected",
  524. expect.objectContaining({
  525. path: "/shares/preparations/preparation-1/confirm",
  526. status: 413,
  527. requestId: "server-request-123",
  528. code: 3209,
  529. }),
  530. );
  531. expect(JSON.stringify(warnLog.mock.calls)).not.toContain("test-token");
  532. });
  533. it("rejects malformed successful envelopes as invalid_contract", async () => {
  534. const request = vi.fn(async () => success({ schema_version: 2 }));
  535. await expect(createClient(request).getCapabilities()).rejects.toBeInstanceOf(
  536. ConversationShareClientError,
  537. );
  538. await expect(createClient(request).getCapabilities()).rejects.toMatchObject({
  539. kind: "invalid_contract",
  540. status: 200,
  541. });
  542. });
  543. it("preserves response request id for malformed successful envelopes", async () => {
  544. const request = vi.fn(
  545. async () =>
  546. new Response(JSON.stringify({ code: 0, msg: "", data: { schema_version: 2 } }), {
  547. status: 200,
  548. headers: { "X-Request-Id": "server-request-contract" },
  549. }),
  550. );
  551. await expect(createClient(request).getCapabilities()).rejects.toMatchObject({
  552. kind: "invalid_contract",
  553. status: 200,
  554. requestId: "server-request-contract",
  555. });
  556. });
  557. it.each([
  558. [
  559. JSON.stringify({
  560. code: 0,
  561. msg: "secret-message",
  562. data: {
  563. preparation_id: "p1",
  564. status: "preparing",
  565. access_mode: "private",
  566. expires_at: "secret-value",
  567. },
  568. }),
  569. "schema_mismatch",
  570. ],
  571. ["<html>secret-value</html>", "invalid_json"],
  572. ])("logs safe diagnostics for invalid successful responses", async (body, responseFormat) => {
  573. const request = vi.fn(
  574. async () =>
  575. new Response(body, {
  576. headers: { "X-Request-Id": "server-contract-id" },
  577. }),
  578. );
  579. await expect(
  580. createClient(request).createPreparation({
  581. client_request_id: "client-contract-id",
  582. title: "secret-title",
  583. schema_version: 1,
  584. access_mode: "private",
  585. payload_sha256: SHA_256,
  586. artifact_count: 0,
  587. }),
  588. ).rejects.toMatchObject({ kind: "invalid_contract", status: 200 });
  589. expect(warnLog).toHaveBeenCalledWith(
  590. undefined,
  591. "conversation share success response parsing failed",
  592. expect.objectContaining({
  593. path: "/shares/preparations",
  594. method: "POST",
  595. status: 200,
  596. requestId: "server-contract-id",
  597. clientRequestId: expect.any(String),
  598. responseFormat,
  599. ...(responseFormat === "schema_mismatch"
  600. ? { issues: [{ path: ["data", "expires_at"], code: "invalid_type" }] }
  601. : {}),
  602. }),
  603. );
  604. expect(JSON.stringify(warnLog.mock.calls)).not.toMatch(/secret-|test-token/);
  605. });
  606. it("does not attach a request id to network errors", async () => {
  607. const request = vi.fn(async () => {
  608. throw new Error("offline");
  609. });
  610. const error = await createClient(request)
  611. .getCapabilities()
  612. .catch((cause: unknown) => cause);
  613. expect(error).toMatchObject({ kind: "network" });
  614. expect((error as { requestId?: string }).requestId).toBeUndefined();
  615. });
  616. it("confirm 用更长的单次超时,其它端点保持 30s", async () => {
  617. // Bug 根因:服务端在 confirm 里同步跑安全检查,请求被挂住 50s+ 撞上 30s 上限被 abort,
  618. // 发布在 checking 阶段以 network 失败。轮询超时管的是「服务端已返回 pending」之后的重试,
  619. // 救不了单次请求本身。
  620. const request = vi.fn(async (_url: string, init?: { timeoutMs?: number }) => {
  621. void init;
  622. return success({
  623. share_code: "share-1",
  624. share_url: "https://zcode.z.ai/cn/share/share-1",
  625. access_mode: "private",
  626. expires_at: 20_000,
  627. });
  628. });
  629. const client = createClient(request as never);
  630. await client.confirm("preparation-1", makeConfirmRequest());
  631. expect((request.mock.calls[0]![1] as { timeoutMs: number }).timeoutMs).toBe(120_000);
  632. request.mockClear();
  633. // 只关心传下去的 timeoutMs;响应体不符合 preview schema 会在请求之后才报错,不影响断言。
  634. await client.getPreview("share-1").catch(() => undefined);
  635. expect((request.mock.calls[0]![1] as { timeoutMs: number }).timeoutMs).toBe(30_000);
  636. });
  637. it("confirmTimeoutMs 可覆盖,便于测试与调优", async () => {
  638. const request = vi.fn(async () =>
  639. success({
  640. share_code: "share-1",
  641. share_url: "https://zcode.z.ai/cn/share/share-1",
  642. access_mode: "private",
  643. expires_at: 20_000,
  644. }),
  645. );
  646. const client = new ConversationShareHttpClient({
  647. apiClient: { request: request as never },
  648. baseUrl: "https://api.example.com/api/v1",
  649. tokenProvider: async () => "test-token",
  650. confirmTimeoutMs: 5_000,
  651. });
  652. await client.confirm("preparation-1", makeConfirmRequest());
  653. expect((request.mock.calls[0]![1] as { timeoutMs: number }).timeoutMs).toBe(5_000);
  654. });
  655. // Bug 根因:uploadArtifact 此前沿用 30s 默认超时——confirm 已实测过单请求被挂 50s+(见上),
  656. // 更大的 artifact 在慢速上行上必然超时且上传无自动重试。超时按体积动态放宽:
  657. // 30s 基础余量 + 保底 128KB/s 上行,下限仍为全局默认超时。
  658. it("uploadArtifact 按文件体积动态放宽超时", async () => {
  659. const request = vi.fn(async () =>
  660. success({
  661. artifact_id: "artifact-1",
  662. size_bytes: 3,
  663. sha256: SHA_256,
  664. status: "uploaded",
  665. safety_status: "pending",
  666. }),
  667. );
  668. const client = createClient(request as never);
  669. const descriptor = {
  670. artifact_id: "artifact-1",
  671. logical_artifact_key: "report",
  672. producer_product_turn_id: "product-turn-1",
  673. artifact_version: 1,
  674. state: "current" as const,
  675. ref: "zcode-artifact://share/artifact-1",
  676. artifact_type: "html" as const,
  677. display_name: "report.html",
  678. extension: "html",
  679. mime_type: "text/html",
  680. size_bytes: 3,
  681. sha256: SHA_256,
  682. };
  683. // 小文件:基础余量 + 1s,仍高于 30s 默认值。
  684. await client.uploadArtifact("preparation-1", descriptor, new Blob(["abc"]));
  685. expect((request.mock.calls[0]![1] as { timeoutMs: number }).timeoutMs).toBe(31_000);
  686. request.mockClear();
  687. // 5 MiB:30s + 40s(5 MiB ÷ 128KB/s 向上取整)= 70s。
  688. const fiveMiB = new Uint8Array(5 * 1024 * 1024);
  689. await client.uploadArtifact("preparation-1", descriptor, new Blob([fiveMiB]));
  690. expect((request.mock.calls[0]![1] as { timeoutMs: number }).timeoutMs).toBe(70_000);
  691. });
  692. it("uploadTimeoutMs 下限仍是全局默认超时,避免小请求被缩短", async () => {
  693. const request = vi.fn(async () =>
  694. success({
  695. artifact_id: "artifact-1",
  696. size_bytes: 3,
  697. sha256: SHA_256,
  698. status: "uploaded",
  699. safety_status: "pending",
  700. }),
  701. );
  702. const client = new ConversationShareHttpClient({
  703. apiClient: { request: request as never },
  704. baseUrl: "https://api.example.com/api/v1",
  705. tokenProvider: async () => "test-token",
  706. timeoutMs: 120_000,
  707. });
  708. const descriptor = {
  709. artifact_id: "artifact-1",
  710. logical_artifact_key: "report",
  711. producer_product_turn_id: "product-turn-1",
  712. artifact_version: 1,
  713. state: "current" as const,
  714. ref: "zcode-artifact://share/artifact-1",
  715. artifact_type: "html" as const,
  716. display_name: "report.html",
  717. extension: "html",
  718. mime_type: "text/html",
  719. size_bytes: 3,
  720. sha256: SHA_256,
  721. };
  722. await client.uploadArtifact("preparation-1", descriptor, new Blob(["abc"]));
  723. expect((request.mock.calls[0]![1] as { timeoutMs: number }).timeoutMs).toBe(120_000);
  724. });
  725. });
  726. describe("分享响应读取失败", () => {
  727. it("响应体中断保留状态及双方请求 ID,并归类网络错误", async () => {
  728. let sentRequestId: string | null = null;
  729. const response = new Response(null, {
  730. status: 200,
  731. headers: { "x-request-id": "server-read-id" },
  732. });
  733. vi.spyOn(response, "text").mockRejectedValue(new TypeError("terminated"));
  734. const client = createClient(async (_url, init) => {
  735. sentRequestId = new Headers(init?.headers).get("x-request-id");
  736. return response;
  737. });
  738. const error = await client
  739. .confirm("preparation-read", makeConfirmRequest())
  740. .catch((error: unknown) => error);
  741. expect(error).toMatchObject({
  742. kind: "network",
  743. status: 200,
  744. requestId: "server-read-id",
  745. });
  746. expect(sentRequestId).toBeTruthy();
  747. expect(error).toMatchObject({
  748. details: {
  749. clientRequestId: sentRequestId,
  750. status: 200,
  751. requestId: "server-read-id",
  752. },
  753. });
  754. });
  755. });
  756. it("非 JSON 错误诊断不记录响应正文或查询参数", async () => {
  757. warnLog.mockClear();
  758. const response = new Response("<html>private-user-data</html>", {
  759. status: 405,
  760. headers: { "content-type": "text/html; charset=utf-8" },
  761. });
  762. const error = await createClient(async () => response)
  763. .confirm("diagnostic-preparation", makeConfirmRequest())
  764. .catch((error: unknown) => error);
  765. expect(error).toMatchObject({
  766. kind: "unknown",
  767. status: 405,
  768. details: { clientRequestId: expect.any(String) },
  769. });
  770. expect(error).not.toHaveProperty("cause");
  771. expect(warnLog).toHaveBeenCalledWith(
  772. undefined,
  773. "conversation share HTTP response diagnostics",
  774. expect.objectContaining({
  775. method: "POST",
  776. status: 405,
  777. responseFormat: "html",
  778. mediaType: "text/html",
  779. clientRequestId: expect.any(String),
  780. }),
  781. );
  782. expect(JSON.stringify(warnLog.mock.calls)).not.toContain("private-user-data");
  783. });