conversationSharePreviewClient.test.ts 7.4 KB

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