share-input-images.mjs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. // SHARE-IMG01:本地网络 fixture,验证匿名分享页的输入图片及加载失败回退。
  2. import assert from "node:assert/strict";
  3. import { mkdir } from "node:fs/promises";
  4. import { chromium } from "playwright-core";
  5. const baseUrl = process.env.SHARE_E2E_BASE_URL || "http://127.0.0.1:5186";
  6. const output = process.env.SHARE_E2E_ARTIFACTS || "/tmp/share-input-images-e2e";
  7. await mkdir(output, { recursive: true });
  8. const png = Buffer.from(
  9. "iVBORw0KGgoAAAANSUhEUgAAAKAAAABQCAIAAAARP+ljAAAA3UlEQVR4nO3RMQ3AMBDAwMDp3LlwCrZzEQVGJP9JRuBb//2M6nq/Ua3jxwEDBgwYMGDAIzp+HDBgwIABAwY8IsDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMcDHA9wPMDxAMfbNAF3wYemXYoAAAAASUVORK5CYII=",
  10. "base64",
  11. );
  12. const base = { turnId: "turn-1", productTurnId: "product-1", createdAt: 1 };
  13. const input = [
  14. ["image-1", "photo.png", "image/png"],
  15. ["broken-1", "broken.png", "image/png"],
  16. ["missing-1", "unavailable.png", "image/png"],
  17. ["text-1", "notes-with-a-long-name.txt", "text/plain"],
  18. ];
  19. const artifacts = [
  20. ...input.filter(([id]) => id !== "missing-1"),
  21. ["thumb-1", "thumb.png", "image/png"],
  22. ].map(([id, name, mime]) => ({
  23. artifact_id: id,
  24. logical_artifact_key: id,
  25. producer_product_turn_id: base.productTurnId,
  26. artifact_version: 1,
  27. state: "current",
  28. ref: `zcode-artifact://share/${id}`,
  29. artifact_type: mime.startsWith("image/") ? "image" : "text",
  30. display_name: name,
  31. extension: name.split(".").at(-1),
  32. mime_type: mime,
  33. size_bytes: png.length,
  34. sha256: "a".repeat(64),
  35. url: `https://resources.example.com/${id}`,
  36. url_expires_at: 9999999999999,
  37. }));
  38. const preview = {
  39. schema_version: 1,
  40. share: {
  41. title: "Input image preview",
  42. access_mode: "public_readonly",
  43. created_at: 1,
  44. expires_at: 9999999999999,
  45. },
  46. rows: [
  47. {
  48. ...base,
  49. rowId: 1,
  50. createdAtSeq: 1,
  51. kind: "turnHeader",
  52. origin: "userInput",
  53. state: "completedSuccess",
  54. startedAt: 1,
  55. },
  56. {
  57. ...base,
  58. rowId: 2,
  59. createdAtSeq: 2,
  60. kind: "userInput",
  61. origin: "realUser",
  62. text: "这个图里面是啥内容",
  63. attachments: input.map(([id, fileName, mime]) => ({
  64. ref: `zcode-artifact://share/${id}`,
  65. fileName,
  66. mime,
  67. bytes: png.length,
  68. ...(id === "image-1" ? { previewRef: "zcode-artifact://share/thumb-1" } : {}),
  69. })),
  70. },
  71. {
  72. ...base,
  73. rowId: 3,
  74. createdAtSeq: 3,
  75. kind: "assistantText",
  76. state: "complete",
  77. text: "SHARE_IMG01_RESPONSE",
  78. },
  79. ],
  80. artifacts,
  81. integrity: { projection_sha256: "a".repeat(64), artifact_set_sha256: "b".repeat(64) },
  82. };
  83. const browser = await chromium.launch({ channel: "chrome", headless: true });
  84. try {
  85. for (const locale of ["cn/share", "share"])
  86. for (const width of [375, 1280])
  87. for (const theme of ["zai-light", "zai-dark"]) {
  88. const context = await browser.newContext({
  89. viewport: { width, height: 900 },
  90. reducedMotion: "reduce",
  91. });
  92. await context.addInitScript((theme) => localStorage.setItem("zcode-theme", theme), theme);
  93. const page = await context.newPage();
  94. const errors = [],
  95. requests = [],
  96. diagnostics = [];
  97. page.on("pageerror", (e) => errors.length < 5 && errors.push(e.stack ?? e.message));
  98. page.on("console", (msg) => {
  99. if (msg.text().includes("share-input-image")) diagnostics.push(msg.text());
  100. });
  101. await context.route("**/*", async (route) => {
  102. const url = new URL(route.request().url());
  103. if (url.pathname.endsWith("/shares/input-images/preview"))
  104. return route.fulfill({
  105. contentType: "application/json",
  106. body: JSON.stringify({ code: 0, msg: "", data: preview }),
  107. });
  108. if (url.hostname === "resources.example.com") {
  109. requests.push(url.pathname);
  110. if (url.pathname === "/broken-1")
  111. return route.fulfill({ status: 404, body: "Missing image" });
  112. return route.fulfill({ contentType: "image/png", body: png });
  113. }
  114. if (
  115. url.origin === new URL(baseUrl).origin &&
  116. url.pathname.startsWith("/share/") &&
  117. route.request().isNavigationRequest()
  118. ) {
  119. const response = await route.fetch({ url: `${baseUrl}/cn${url.pathname}` });
  120. return route.fulfill({ response });
  121. }
  122. if (url.origin === new URL(baseUrl).origin) return route.continue();
  123. return route.abort();
  124. });
  125. await page.goto(`${baseUrl}/${locale}/input-images`);
  126. const attachments = page.locator('[data-v4-user-input-attachments="true"]');
  127. await attachments.waitFor();
  128. const image = attachments.getByRole("img", { name: "photo.png", exact: true });
  129. assert.equal(
  130. await image.count(),
  131. 1,
  132. "Input image must render a thumbnail, not only a file pill",
  133. );
  134. await image.scrollIntoViewIfNeeded();
  135. await page.waitForFunction(() => {
  136. const img = document.querySelector('img[alt="photo.png"]');
  137. return img?.complete && img.naturalWidth > 0;
  138. });
  139. assert.equal(await image.getAttribute("src"), "https://resources.example.com/thumb-1");
  140. const link = attachments.getByRole("link", { name: "photo.png", exact: true });
  141. assert.equal(await link.getAttribute("href"), "https://resources.example.com/image-1");
  142. const popupPromise = page.waitForEvent("popup");
  143. await link.click();
  144. const popup = await popupPromise;
  145. await popup.waitForLoadState();
  146. assert.equal(popup.url(), "https://resources.example.com/image-1");
  147. await popup.close();
  148. await attachments
  149. .locator('[data-v4-user-input-attachment-pill="true"]')
  150. .filter({ hasText: "broken.png" })
  151. .waitFor();
  152. assert.equal(await attachments.getByRole("img", { name: "broken.png" }).count(), 0);
  153. assert.equal(
  154. await attachments.getByRole("link", { name: /broken.png/u }).getAttribute("href"),
  155. "https://resources.example.com/broken-1",
  156. );
  157. assert.equal(await attachments.locator('[aria-disabled="true"]').count(), 1);
  158. assert.equal(
  159. await attachments.locator('[data-v4-user-input-attachment-pill="true"]').count(),
  160. 3,
  161. );
  162. assert.ok(requests.includes("/thumb-1"), "Thumbnail bytes must be requested");
  163. if (process.env.SHARE_E2E_EXPECT_DIAGNOSTICS === "true") {
  164. assert.ok(
  165. diagnostics.some((line) => line.includes("preview failed")),
  166. "Failed image must produce a diagnostic without signed URLs",
  167. );
  168. }
  169. assert.equal(
  170. await page.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1),
  171. false,
  172. `${locale}/${width}/${theme} overflow`,
  173. );
  174. const pill = await attachments
  175. .locator('[data-v4-user-input-attachment-pill="true"]')
  176. .first()
  177. .boundingBox();
  178. assert.ok(pill && pill.height < 48, "File pills must not stretch to thumbnail height");
  179. const box = await image.boundingBox();
  180. assert.ok(box?.width > 0 && box.width <= 96 && box.height <= 96);
  181. assert.deepEqual(errors, []);
  182. await page.screenshot({
  183. path: `${output}/${locale.replaceAll("/", "-")}-${width}-${theme}.png`,
  184. fullPage: true,
  185. });
  186. await context.close();
  187. }
  188. console.log(
  189. "SHARE-IMG01: 8 browser variants passed (thumbnail bytes, original link, failed/missing images, files, locale, themes, overflow)",
  190. );
  191. } finally {
  192. await browser.close();
  193. }