workflowArtifactTilePreview.test.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. // @vitest-environment jsdom
  2. // 完成卡瓦片的预览区(docs/dynamic-workflow/transcript-and-notifications.md「Artifact tiles」):产物本身的缩略。
  3. // 字节与看板条目走 mock 的会话上下文;这里钉分派(markdown / CSV / 图片 / 看板 / 字形)、
  4. // 「还没到」与「画不了」的区分、以及不该读字节的情形。
  5. import { act, cleanup, render, waitFor } from "@testing-library/react";
  6. import { createElement } from "react";
  7. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  8. vi.mock("@/logger.js", () => ({ logger: { debug: vi.fn(), warn: vi.fn() } }));
  9. const workflowRunArtifactRead = vi.fn();
  10. const workflowRunArtifactData = vi.fn();
  11. vi.mock("@/v4/V4ConversationContext.js", () => ({
  12. useV4Conversation: () => ({ workflowRunArtifactRead, workflowRunArtifactData }),
  13. useHasV4Conversation: () => true,
  14. }));
  15. // eslint-disable-next-line import/first -- 必须在 mock 之后再引入被测组件。
  16. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  17. // eslint-disable-next-line import/first
  18. import {
  19. WorkflowArtifactTilePreview,
  20. csvPreviewRows,
  21. previewModeFor,
  22. } from "@/app-shell/workflow-artifacts/WorkflowArtifactTilePreview.js";
  23. // eslint-disable-next-line import/first
  24. import type { WorkflowCompletionArtifact } from "@/components/workflow-timeline/WorkflowArtifactTile.js";
  25. afterEach(() => {
  26. cleanup();
  27. });
  28. beforeEach(() => {
  29. // MessageResponse 按 matchMedia 选代码块配色;jsdom 没有它。
  30. Object.defineProperty(window, "matchMedia", {
  31. configurable: true,
  32. writable: true,
  33. value: vi.fn(() => ({
  34. matches: false,
  35. addEventListener: vi.fn(),
  36. removeEventListener: vi.fn(),
  37. addListener: vi.fn(),
  38. removeListener: vi.fn(),
  39. })),
  40. });
  41. workflowRunArtifactRead.mockReset();
  42. workflowRunArtifactData.mockReset();
  43. workflowRunArtifactData.mockResolvedValue({ items: [], hasMore: false });
  44. });
  45. function bytesOf(text: string, mediaType: string) {
  46. return {
  47. dataBase64: btoa(unescape(encodeURIComponent(text))),
  48. mediaType,
  49. totalBytes: text.length,
  50. nextOffset: null,
  51. };
  52. }
  53. function renderPreview(artifact: WorkflowCompletionArtifact) {
  54. return render(
  55. createElement(
  56. ZCodeIntlProvider,
  57. { initialLocale: "en-US" },
  58. createElement(
  59. "div",
  60. { style: { position: "relative" } },
  61. createElement(WorkflowArtifactTilePreview, {
  62. artifact,
  63. runId: "run-1",
  64. sessionId: "session-1",
  65. theme: "system",
  66. }),
  67. ),
  68. ),
  69. );
  70. }
  71. describe("previewModeFor / csvPreviewRows", () => {
  72. it("按 kind 与内容类型分派;超上限不读", () => {
  73. expect(previewModeFor({ kind: "markdown" })).toBe("markdown");
  74. expect(previewModeFor({ kind: "file", contentType: "text/markdown; charset=utf-8" })).toBe(
  75. "markdown",
  76. );
  77. expect(previewModeFor({ kind: "file", contentType: "text/csv" })).toBe("csv");
  78. expect(previewModeFor({ kind: "file", contentType: "image/png" })).toBe("image");
  79. expect(previewModeFor({ kind: "file", contentType: "application/json" })).toBe("text");
  80. expect(previewModeFor({ kind: "file", contentType: "application/pdf" })).toBeUndefined();
  81. expect(
  82. previewModeFor({ kind: "file", contentType: "text/csv", bytes: 300 * 1024 }),
  83. ).toBeUndefined();
  84. expect(
  85. previewModeFor({ kind: "file", contentType: "image/png", bytes: 5 * 1024 * 1024 }),
  86. ).toBeUndefined();
  87. });
  88. it("CSV 缩略:至多 6 行 × 5 列,认成对引号,长格截断", () => {
  89. const text = [
  90. 'source,score,used,"a, quoted",e,f',
  91. ...Array.from({ length: 8 }, (_unused, index) => `row${index},0.${index},yes,x,y,z`),
  92. ].join("\n");
  93. const rows = csvPreviewRows(text);
  94. expect(rows).toHaveLength(6);
  95. expect(rows[0]).toEqual(["source", "score", "used", "a, quoted", "e"]);
  96. expect(csvPreviewRows(`${"x".repeat(40)},1`)[0]![0]).toBe(`${"x".repeat(28)}…`);
  97. });
  98. });
  99. describe("WorkflowArtifactTilePreview", () => {
  100. it("markdown:先留白,字节到了画缩放的文档渲染", async () => {
  101. workflowRunArtifactRead.mockResolvedValue(bytesOf("# Pricing\n\nBody text.", "text/markdown"));
  102. const view = renderPreview({ id: "brief", kind: "markdown", version: 1 });
  103. expect(view.getByTestId("workflow-artifact-preview-pending")).toBeTruthy();
  104. await waitFor(() => expect(view.getByTestId("workflow-artifact-preview-body")).toBeTruthy());
  105. const body = view.getByTestId("workflow-artifact-preview-body");
  106. expect(body.getAttribute("data-preview-mode")).toBe("markdown");
  107. expect(body.className).toContain("wf-preview-doc");
  108. expect(body.textContent).toContain("Pricing");
  109. expect(workflowRunArtifactRead).toHaveBeenCalledWith(
  110. expect.objectContaining({ artifactId: "brief", version: 1, runId: "run-1" }),
  111. );
  112. });
  113. it("同一份文档在交付物行的框里与瓦片同一档:按版本读字节,没有更小的档(预览要么读得清,要么不画)", async () => {
  114. workflowRunArtifactRead.mockResolvedValue(bytesOf("# Digest", "text/markdown"));
  115. const view = renderPreview({ id: "brief", kind: "markdown", version: 3 });
  116. await waitFor(() => expect(view.getByTestId("workflow-artifact-preview-body")).toBeTruthy());
  117. expect(view.getByTestId("workflow-artifact-preview-body").className).toBe("wf-preview-doc");
  118. expect(workflowRunArtifactRead).toHaveBeenCalledWith(expect.objectContaining({ version: 3 }));
  119. });
  120. it("CSV:前几行成表,首行是表头", async () => {
  121. workflowRunArtifactRead.mockResolvedValue(
  122. bytesOf("source,score\na16z.com,0.91\ngartner.com,0.84", "text/csv"),
  123. );
  124. const view = renderPreview({
  125. id: "sources",
  126. kind: "file",
  127. version: 1,
  128. contentType: "text/csv",
  129. });
  130. await waitFor(() => expect(view.getByTestId("workflow-artifact-preview-body")).toBeTruthy());
  131. const body = view.getByTestId("workflow-artifact-preview-body");
  132. expect(body.getAttribute("data-preview-mode")).toBe("csv");
  133. expect(body.querySelectorAll("tr")).toHaveLength(3);
  134. expect(body.querySelector("tr")?.textContent).toContain("source");
  135. expect(body.textContent).toContain("a16z.com");
  136. });
  137. it("PDF / 二进制:不读字节,直接画纸页字形 + 扩展名徽字", () => {
  138. const view = renderPreview({
  139. id: "report",
  140. kind: "file",
  141. version: 1,
  142. contentType: "application/pdf",
  143. sourcePath: "out/qa-report.pdf",
  144. });
  145. expect(view.getByTestId("workflow-artifact-sheet")).toBeTruthy();
  146. expect(view.getByTestId("workflow-artifact-sheet-badge").textContent).toBe("PDF");
  147. expect(workflowRunArtifactRead).not.toHaveBeenCalled();
  148. });
  149. it("读失败:字形而不是空白,也不炸", async () => {
  150. workflowRunArtifactRead.mockRejectedValue(new Error("boom"));
  151. const view = renderPreview({ id: "brief", kind: "markdown", version: 1 });
  152. await waitFor(() => expect(view.getByTestId("workflow-artifact-sheet")).toBeTruthy());
  153. expect(view.queryByTestId("workflow-artifact-preview-pending")).toBeNull();
  154. });
  155. it("预置看板:spec 没到留白;spec 到了走 compact 渲染并拉条目", async () => {
  156. const pending = renderPreview({ id: "cov", kind: "chart", version: 1, itemCount: 4 });
  157. expect(pending.getByTestId("workflow-artifact-preview-pending")).toBeTruthy();
  158. expect(workflowRunArtifactRead).not.toHaveBeenCalled();
  159. cleanup();
  160. const view = renderPreview({
  161. id: "cov",
  162. kind: "chart",
  163. version: 1,
  164. itemCount: 1,
  165. spec: { type: "line", x: "round", y: "ms" },
  166. });
  167. await act(async () => {
  168. await Promise.resolve();
  169. });
  170. expect(
  171. view.getByTestId("workflow-artifact-preview-body").getAttribute("data-preview-mode"),
  172. ).toBe("preset");
  173. expect(workflowRunArtifactData).toHaveBeenCalledWith(
  174. expect.objectContaining({ artifactId: "cov", runId: "run-1" }),
  175. );
  176. });
  177. });