conversationShareHttpClient.test.ts 24 KB

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