conversationSharePreviewClient.test.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. ConversationSharePreviewClient,
  4. buildShareImportDeepLink,
  5. parseConversationShareRoute,
  6. } from "../src/share/conversationSharePreviewClient.js";
  7. const preview = {
  8. schema_version: 1 as const,
  9. share: {
  10. title: "Share",
  11. access_mode: "public_importable" as const,
  12. created_at: 1_000,
  13. expires_at: 2_000,
  14. },
  15. rows: [],
  16. artifacts: [],
  17. integrity: { projection_sha256: "a".repeat(64), artifact_set_sha256: "b".repeat(64) },
  18. };
  19. // 客户端在 wire 形状之外附带逐行降级的结果:认不出的行数交给 UI 出软提示。
  20. const decodedPreview = { ...preview, unsupportedRowCount: 0 };
  21. describe("conversation share preview client", () => {
  22. it.each([
  23. [429, "<html>limit</html>", "rate_limited"],
  24. [403, "", "not_found"],
  25. [403, "<html>forbidden</html>", "not_found"],
  26. [400, "<html>bad request</html>", "unknown"],
  27. [400, JSON.stringify({ message: "bad request" }), "unknown"],
  28. [502, "<html>gateway</html>", "service_unavailable"],
  29. [503, "", "service_unavailable"],
  30. [
  31. 500,
  32. JSON.stringify({ code: 2001, msg: "database error", logid: "web-log-id" }),
  33. "service_unavailable",
  34. ],
  35. [404, JSON.stringify({ code: 3200, msg: "disabled" }), "feature_disabled"],
  36. ])("classifies HTTP %s without blaming the content", async (status, body, kind) => {
  37. const client = new ConversationSharePreviewClient({
  38. baseUrl: "https://api.example.com",
  39. fetchImpl: vi.fn(async () => new Response(body, { status })),
  40. });
  41. await expect(client.getPreview("share-1")).rejects.toMatchObject({ kind, status });
  42. });
  43. afterEach(() => {
  44. vi.unstubAllGlobals();
  45. });
  46. it("parses both /cn/share/<code> (zh) and /share/<code> (en) routes", () => {
  47. expect(parseConversationShareRoute("/cn/share/share-1")).toBe("share-1");
  48. expect(parseConversationShareRoute("/cn/share/share-1/")).toBe("share-1");
  49. expect(parseConversationShareRoute("/share/share-1")).toBe("share-1");
  50. expect(parseConversationShareRoute("/share/share-1/")).toBe("share-1");
  51. expect(parseConversationShareRoute("/cn/share")).toBeNull();
  52. expect(parseConversationShareRoute("/share")).toBeNull();
  53. expect(parseConversationShareRoute("/cn/share/a%2Fb")).toBeNull();
  54. expect(parseConversationShareRoute("/share/a%2Fb")).toBeNull();
  55. expect(parseConversationShareRoute("/remote/v4")).toBeNull();
  56. });
  57. it("builds a Deep Link containing only the share code", () => {
  58. expect(buildShareImportDeepLink("share-1")).toBe("zcode://share/import?code=share-1");
  59. expect(() => buildShareImportDeepLink("share/1")).toThrow();
  60. });
  61. it("does not send Authorization for the anonymous preview request", async () => {
  62. const diagnostics = { info: vi.fn(), warn: vi.fn() };
  63. const fetchImpl = vi.fn(async (input: string | URL, init?: RequestInit) => {
  64. expect(String(input)).toBe("https://zcode.z.ai/api/v1/shares/share-1/preview");
  65. expect(init?.headers).toBeUndefined();
  66. return new Response(JSON.stringify({ code: 0, msg: "", data: preview }), { status: 200 });
  67. });
  68. const client = new ConversationSharePreviewClient({
  69. baseUrl: "https://zcode.z.ai/api/v1",
  70. fetchImpl,
  71. diagnostics,
  72. });
  73. await expect(client.getPreview("share-1")).resolves.toEqual(decodedPreview);
  74. expect(diagnostics.info).toHaveBeenCalledWith(
  75. "preview_request_started",
  76. expect.objectContaining({
  77. requestTarget: "https://zcode.z.ai/api/v1/shares/<redacted>/preview",
  78. authenticated: false,
  79. shareCodeLength: 7,
  80. }),
  81. );
  82. expect(diagnostics.info).toHaveBeenCalledWith(
  83. "preview_response_received",
  84. expect.objectContaining({ status: 200, ok: true }),
  85. );
  86. expect(JSON.stringify(diagnostics.info.mock.calls)).not.toContain("share-1");
  87. });
  88. it("logs a safe diagnostic when fetch rejects before an HTTP response", async () => {
  89. const diagnostics = { info: vi.fn(), warn: vi.fn() };
  90. const client = new ConversationSharePreviewClient({
  91. baseUrl: "https://zcode.z.ai/api/v1",
  92. fetchImpl: vi.fn(async () => {
  93. throw new TypeError("Failed to fetch");
  94. }),
  95. diagnostics,
  96. });
  97. await expect(client.getPreview("share-1")).rejects.toMatchObject({ kind: "network" });
  98. expect(diagnostics.warn).toHaveBeenCalledWith("preview_request_failed", {
  99. requestTarget: "https://zcode.z.ai/api/v1/shares/<redacted>/preview",
  100. authenticated: false,
  101. errorName: "TypeError",
  102. errorMessage: "Failed to fetch",
  103. });
  104. expect(JSON.stringify(diagnostics.warn.mock.calls)).not.toContain("share-1");
  105. });
  106. it("keeps the browser global as this when using the default fetch", async () => {
  107. const diagnostics = { info: vi.fn(), warn: vi.fn() };
  108. const brandCheckedFetch = vi.fn(function (this: unknown) {
  109. if (this !== globalThis) throw new TypeError("Illegal invocation");
  110. return Promise.resolve(
  111. new Response(JSON.stringify({ code: 0, msg: "", data: preview }), { status: 200 }),
  112. );
  113. });
  114. vi.stubGlobal("fetch", brandCheckedFetch);
  115. const client = new ConversationSharePreviewClient({
  116. baseUrl: "https://zcode.z.ai/api/v1",
  117. diagnostics,
  118. });
  119. await expect(client.getPreview("share-1")).resolves.toEqual(decodedPreview);
  120. expect(brandCheckedFetch).toHaveBeenCalledOnce();
  121. });
  122. it("retries private preview with a token and maps hidden shares", async () => {
  123. const fetchImpl = vi
  124. .fn()
  125. .mockResolvedValueOnce(
  126. new Response(JSON.stringify({ code: 3211, msg: "not found" }), { status: 404 }),
  127. )
  128. .mockResolvedValueOnce(
  129. new Response(
  130. JSON.stringify({
  131. code: 0,
  132. msg: "",
  133. data: { ...preview, share: { ...preview.share, access_mode: "private" } },
  134. }),
  135. { status: 200 },
  136. ),
  137. );
  138. const client = new ConversationSharePreviewClient({
  139. baseUrl: "https://zcode.z.ai/api/v1",
  140. fetchImpl,
  141. });
  142. await expect(client.getPreview("share-1")).rejects.toMatchObject({ kind: "not_found" });
  143. await expect(client.getPreview("share-1", "jwt-1")).resolves.toMatchObject({
  144. share: { access_mode: "private" },
  145. });
  146. expect(fetchImpl.mock.calls[1]?.[1]).toMatchObject({
  147. headers: { Authorization: "Bearer jwt-1" },
  148. });
  149. });
  150. it("maps an empty 401 response to authentication_required", async () => {
  151. const client = new ConversationSharePreviewClient({
  152. baseUrl: "https://zcode.z.ai/api/v1",
  153. fetchImpl: vi.fn(async () => new Response("", { status: 401 })),
  154. });
  155. await expect(client.getPreview("share-1")).rejects.toMatchObject({
  156. kind: "authentication_required",
  157. status: 401,
  158. });
  159. });
  160. it("retains unknown server codes and logid for support", async () => {
  161. const client = new ConversationSharePreviewClient({
  162. baseUrl: "https://api.example.com",
  163. fetchImpl: vi.fn(
  164. async () =>
  165. new Response(
  166. JSON.stringify({ code: 9999, msg: "server text", logid: "web-request-id" }),
  167. { status: 500 },
  168. ),
  169. ),
  170. });
  171. await expect(client.getPreview("share-1")).rejects.toMatchObject({
  172. kind: "service_unavailable",
  173. code: 9999,
  174. requestId: "web-request-id",
  175. });
  176. });
  177. // 落地页镜像独立部署、独立回滚,所以随时可能比发布分享的客户端旧。
  178. it("载荷版本比本 build 新时报 unsupported_schema_version,不报「格式无效」", async () => {
  179. const client = new ConversationSharePreviewClient({
  180. baseUrl: "https://zcode.z.ai/api/v1",
  181. fetchImpl: vi.fn(
  182. async () =>
  183. new Response(
  184. JSON.stringify({ code: 0, msg: "", data: { ...preview, schema_version: 2 } }),
  185. { status: 200 },
  186. ),
  187. ),
  188. });
  189. await expect(client.getPreview("share-1")).rejects.toMatchObject({
  190. kind: "unsupported_schema_version",
  191. });
  192. });
  193. it("认不出的行只被跳过并计数,整页照常渲染", async () => {
  194. const knownRow = {
  195. rowId: 1,
  196. turnId: "turn-1",
  197. createdAt: 1,
  198. createdAtSeq: 1,
  199. kind: "assistantText",
  200. text: "hi",
  201. state: "complete",
  202. };
  203. const client = new ConversationSharePreviewClient({
  204. baseUrl: "https://zcode.z.ai/api/v1",
  205. fetchImpl: vi.fn(
  206. async () =>
  207. new Response(
  208. JSON.stringify({
  209. code: 0,
  210. msg: "",
  211. data: {
  212. ...preview,
  213. rows: [knownRow, { ...knownRow, rowId: 2, kind: "videoClipAddedLater" }],
  214. },
  215. }),
  216. { status: 200 },
  217. ),
  218. ),
  219. });
  220. const loaded = await client.getPreview("share-1");
  221. expect(loaded.rows).toHaveLength(1);
  222. expect(loaded.unsupportedRowCount).toBe(1);
  223. });
  224. });