Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): stabilize community image previews (#524)
Gener7f91ef7877bf
diff --git a/src/web/src/components/community/messages/image-lightbox-layout.test.ts b/src/web/src/components/community/messages/image-lightbox-layout.test.tsnew file mode 100644index 000000000..61c4970ba--- /dev/null+++ b/src/web/src/components/community/messages/image-lightbox-layout.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest"+import {+ fallbackPreviewSize,+ fitImageToViewport,+ previewFrameStyle,+ validImageDimensions,+} from "./image-lightbox-layout"++describe("image lightbox layout", () => {+ it.each([+ { name: "landscape within bounds", image: { width: 800, height: 450 }, expected: { width: 800, height: 450 } },+ { name: "portrait within bounds", image: { width: 396, height: 702 }, expected: { width: 396, height: 702 } },+ { name: "small image is not enlarged", image: { width: 80, height: 40 }, expected: { width: 80, height: 40 } },+ { name: "width cap", image: { width: 2000, height: 1000 }, expected: { width: 900, height: 450 } },+ { name: "height cap", image: { width: 1000, height: 2000 }, expected: { width: 382.5, height: 765 } },+ ])("fits $name", ({ image, expected }) => {+ expect(fitImageToViewport(image, { width: 1000, height: 900 })).toEqual(expected)+ })++ it("uses a capped square fallback while legacy dimensions are unknown", () => {+ expect(fallbackPreviewSize({ width: 390, height: 844 })).toEqual({ width: 200, height: 200 })+ expect(fallbackPreviewSize({ width: 120, height: 100 })).toEqual({ width: 85, height: 85 })+ })++ it("uses live viewport CSS without upscaling or a JavaScript viewport snapshot", () => {+ expect(previewFrameStyle({ width: 1200, height: 630 })).toEqual({+ width: "min(1200px, 90vw, 161.904762vh)",+ aspectRatio: "1200 / 630",+ })+ expect(previewFrameStyle({ width: 80, height: 40 })).toEqual({+ width: "min(80px, 90vw, 170vh)",+ aspectRatio: "80 / 40",+ })+ expect(previewFrameStyle()).toEqual({+ width: "min(200px, 90vw, 85vh)",+ aspectRatio: "1 / 1",+ })+ })++ it("rejects incomplete or invalid dimensions", () => {+ expect(validImageDimensions(640, 480)).toEqual({ width: 640, height: 480 })+ expect(validImageDimensions(undefined, 480)).toBeUndefined()+ expect(validImageDimensions(0, 480)).toBeUndefined()+ expect(validImageDimensions(Number.NaN, 480)).toBeUndefined()+ })+})diff --git a/src/web/src/components/community/messages/image-lightbox-layout.ts b/src/web/src/components/community/messages/image-lightbox-layout.tsnew file mode 100644index 000000000..8904f7b88--- /dev/null+++ b/src/web/src/components/community/messages/image-lightbox-layout.ts@@ -0,0 +1,72 @@+export type ImageDimensions = { width: number; height: number }++export type ViewportDimensions = { width: number; height: number }++export type PreviewFrameStyle = {+ width: string+ aspectRatio: string+}++const DEFAULT_PREVIEW_EDGE = 200+const PREVIEW_MAX_WIDTH_RATIO = 0.9+const PREVIEW_MAX_HEIGHT_RATIO = 0.85++function formatCssNumber(value: number): string {+ return Number(value.toFixed(6)).toString()+}++export function validImageDimensions(width?: number, height?: number): ImageDimensions | undefined {+ if (+ width === undefined+ || height === undefined+ || !Number.isFinite(width)+ || !Number.isFinite(height)+ || width <= 0+ || height <= 0+ ) return undefined++ return { width, height }+}++export function fitImageToViewport(+ image: ImageDimensions,+ viewport: ViewportDimensions,+): ImageDimensions {+ const maxWidth = Math.max(1, viewport.width * PREVIEW_MAX_WIDTH_RATIO)+ const maxHeight = Math.max(1, viewport.height * PREVIEW_MAX_HEIGHT_RATIO)+ const scale = Math.min(1, maxWidth / image.width, maxHeight / image.height)++ return {+ width: image.width * scale,+ height: image.height * scale,+ }+}++export function fallbackPreviewSize(viewport: ViewportDimensions): ImageDimensions {+ const edge = Math.min(+ DEFAULT_PREVIEW_EDGE,+ Math.max(1, viewport.width * PREVIEW_MAX_WIDTH_RATIO),+ Math.max(1, viewport.height * PREVIEW_MAX_HEIGHT_RATIO),+ )+ return { width: edge, height: edge }+}++/**+ * CSS owns live viewport fitting so resize and orientation changes do not need+ * client-side viewport snapshots or event listeners. The height-limited width+ * is expressed in vh after applying the image aspect ratio.+ */+export function previewFrameStyle(dimensions?: ImageDimensions): PreviewFrameStyle {+ if (!dimensions) {+ return {+ width: `min(${DEFAULT_PREVIEW_EDGE}px, ${PREVIEW_MAX_WIDTH_RATIO * 100}vw, ${PREVIEW_MAX_HEIGHT_RATIO * 100}vh)`,+ aspectRatio: "1 / 1",+ }+ }++ const heightLimitedWidth = PREVIEW_MAX_HEIGHT_RATIO * 100 * (dimensions.width / dimensions.height)+ return {+ width: `min(${formatCssNumber(dimensions.width)}px, ${PREVIEW_MAX_WIDTH_RATIO * 100}vw, ${formatCssNumber(heightLimitedWidth)}vh)`,+ aspectRatio: `${formatCssNumber(dimensions.width)} / ${formatCssNumber(dimensions.height)}`,+ }+}diff --git a/src/web/src/components/community/messages/image-lightbox.test.ts b/src/web/src/components/community/messages/image-lightbox.test.tsindex c3d58e58f..5346d4607 100644--- a/src/web/src/components/community/messages/image-lightbox.test.ts+++ b/src/web/src/components/community/messages/image-lightbox.test.ts@@ -1,41 +1,258 @@import React from "react"import TestRenderer, { act } from "react-test-renderer"import { describe, expect, it, vi } from "vitest"+import { tid } from "@/lib/community/testids"vi.mock("@/components/ui/dialog", () => ({- Dialog: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),+ Dialog: ({ children, ...props }: { children: React.ReactNode }) => React.createElement("dialog-mock", props, children),DialogContent: ({ children }: { children: React.ReactNode }) => React.createElement("section", null, children),}))import { ImageLightbox } from "./image-lightbox"+function renderLightbox(image: React.ComponentProps<typeof ImageLightbox>["image"], onClose = vi.fn()) {+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(ImageLightbox, { image, onClose }))+ })+ return { renderer: renderer!, onClose }+}++function imageEvent(width: number, height: number, decode: () => Promise<void>) {+ return { currentTarget: { naturalWidth: width, naturalHeight: height, decode } }+}++async function loadThumbnail(renderer: TestRenderer.ReactTestRenderer, width: number, height: number) {+ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.imageLightboxThumbnail }).props.onLoad(+ imageEvent(width, height, () => Promise.resolve()),+ )+ await Promise.resolve()+ })+}+describe("ImageLightbox", () => {- it("keeps the thumbnail painted until the clicked original loads", () => {- let renderer: TestRenderer.ReactTestRenderer- act(() => {- renderer = TestRenderer.create(React.createElement(ImageLightbox, {- image: { originalUrl: "/original", thumbnailUrl: "/thumbnail", name: "photo" },- onClose: vi.fn(),- }))- })- const images = renderer!.root.findAllByType("img")- expect(images.map((image) => image.props.src)).toEqual(["/thumbnail", "/original"])- expect(images[1].props.className).toContain("invisible")- act(() => images[1].props.onLoad())- expect(renderer!.root.findAllByType("img")[1].props.className).not.toContain("invisible")- })-- it("retains the thumbnail when the original fails", () => {- let renderer: TestRenderer.ReactTestRenderer- act(() => {- renderer = TestRenderer.create(React.createElement(ImageLightbox, {- image: { originalUrl: "/original", thumbnailUrl: "/thumbnail", name: "photo" },- onClose: vi.fn(),- }))- })- act(() => renderer!.root.findAllByType("img")[1].props.onError())- const images = renderer!.root.findAllByType("img")- expect(images).toHaveLength(1)- expect(images[0].props.src).toBe("/thumbnail")+ it("reserves the known frame and reveals the original only after decode", async () => {+ let resolveDecode!: () => void+ const decodePromise = new Promise<void>((resolve) => { resolveDecode = resolve })+ const { renderer } = renderLightbox({+ originalUrl: "/original",+ thumbnailUrl: "/thumbnail",+ name: "photo",+ width: 800,+ height: 450,+ })+ const frame = renderer.root.findByProps({ "data-testid": tid.imageLightbox })+ const thumbnail = renderer.root.findByProps({ "data-testid": tid.imageLightboxThumbnail })+ const original = renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal })++ expect(frame.props.style).toEqual({+ width: "min(800px, 90vw, 151.111111vh)",+ aspectRatio: "800 / 450",+ })+ expect(thumbnail.props.className).toContain("absolute inset-0 size-full")+ expect(original.props.className).toContain("absolute inset-0 size-full")+ expect(original.props.className).toContain("opacity-0")+ expect(frame.parent?.props.className).toContain("invisible")++ await loadThumbnail(renderer, 800, 450)+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightbox }).parent?.props.className).toContain("visible")++ act(() => original.props.onLoad(imageEvent(800, 450, () => decodePromise)))+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-0")++ await act(async () => {+ resolveDecode()+ await decodePromise+ })+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-100")+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxThumbnail }).props.className).toContain("opacity-0")+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightbox }).props.style).toEqual({+ width: "min(800px, 90vw, 151.111111vh)",+ aspectRatio: "800 / 450",+ })+ })++ it("keeps the thumbnail and retries only the failed original", async () => {+ const { renderer } = renderLightbox({+ originalUrl: "/original",+ thumbnailUrl: "/thumbnail",+ name: "photo",+ width: 640,+ height: 480,+ })+ await loadThumbnail(renderer, 640, 480)+ act(() => renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.onError())++ expect(renderer.root.findAllByProps({ "data-testid": tid.imageLightboxOriginal })).toHaveLength(0)+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxThumbnail }).props.src).toBe("/thumbnail")+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxError })).toBeDefined()++ act(() => renderer.root.findByProps({ "data-testid": tid.imageLightboxRetry }).props.onClick())+ const retriedOriginal = renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal })+ expect(retriedOriginal.props.src).toBe("/original")+ expect(renderer.root.findAllByProps({ "data-testid": tid.imageLightboxError })).toHaveLength(0)++ await act(async () => {+ retriedOriginal.props.onLoad(imageEvent(640, 480, () => Promise.resolve()))+ await Promise.resolve()+ })+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-100")+ })++ it("commits legacy natural dimensions with the decoded reveal", async () => {+ let resolveDecode!: () => void+ const decodePromise = new Promise<void>((resolve) => { resolveDecode = resolve })+ const { renderer } = renderLightbox({+ originalUrl: "/legacy-original",+ thumbnailUrl: "/legacy-thumbnail",+ name: "legacy",+ })+ const frame = () => renderer.root.findByProps({ "data-testid": tid.imageLightbox })++ expect(frame().props.style).toEqual({ width: "min(200px, 90vw, 85vh)", aspectRatio: "1 / 1" })+ await loadThumbnail(renderer, 200, 100)+ expect(frame().props.style).toEqual({ width: "min(200px, 90vw, 170vh)", aspectRatio: "200 / 100" })++ act(() => renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.onLoad(+ imageEvent(1000, 500, () => decodePromise),+ ))+ expect(frame().props.style).toEqual({ width: "min(200px, 90vw, 170vh)", aspectRatio: "200 / 100" })+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-0")++ await act(async () => {+ resolveDecode()+ await decodePromise+ })+ expect(frame().props.style).toEqual({ width: "min(1000px, 90vw, 170vh)", aspectRatio: "1000 / 500" })+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-100")+ })++ it("treats a decode failure like an original load failure", async () => {+ const { renderer } = renderLightbox({+ originalUrl: "/original",+ thumbnailUrl: "/thumbnail",+ name: "photo",+ })+ await loadThumbnail(renderer, 640, 480)+ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.onLoad(+ imageEvent(640, 480, () => Promise.reject(new Error("decode failed"))),+ )+ await Promise.resolve()+ })+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxError })).toBeDefined()+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxThumbnail }).props.className).toContain("opacity-100")+ })++ it("ignores late load, decode, and error callbacks from a retried attempt", async () => {+ let resolveOldDecode!: () => void+ const oldDecode = new Promise<void>((resolve) => { resolveOldDecode = resolve })+ const { renderer } = renderLightbox({+ originalUrl: "/original",+ thumbnailUrl: "/thumbnail",+ name: "photo",+ width: 640,+ height: 480,+ })+ await loadThumbnail(renderer, 640, 480)+ const oldOriginal = renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal })+ const oldOnLoad = oldOriginal.props.onLoad as (event: ReturnType<typeof imageEvent>) => void+ const oldOnError = oldOriginal.props.onError as () => void++ act(() => oldOnLoad(imageEvent(640, 480, () => oldDecode)))+ act(() => oldOnError())+ act(() => renderer.root.findByProps({ "data-testid": tid.imageLightboxRetry }).props.onClick())+ const retriedOriginal = renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal })++ act(() => oldOnError())+ expect(renderer.root.findAllByProps({ "data-testid": tid.imageLightboxError })).toHaveLength(0)+ expect(retriedOriginal.props.className).toContain("opacity-0")++ await act(async () => {+ resolveOldDecode()+ await oldDecode+ })+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-0")++ await act(async () => {+ retriedOriginal.props.onLoad(imageEvent(640, 480, () => Promise.resolve()))+ await Promise.resolve()+ })+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-100")+ })++ it("shows an explicit original-loading fallback when no thumbnail exists", () => {+ const { renderer } = renderLightbox({ originalUrl: "/original", name: "legacy" })+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxLoading }).children).toEqual(["正在加载原图"])+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightbox }).props.style).toEqual({+ width: "min(200px, 90vw, 85vh)",+ aspectRatio: "1 / 1",+ })+ })++ it("keeps a cold preview hidden until the thumbnail decodes, then paints it before an already-decoded original", async () => {+ let runAnimationFrame: FrameRequestCallback | undefined+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ runAnimationFrame = callback+ return 1+ })+ vi.stubGlobal("cancelAnimationFrame", vi.fn())++ try {+ const { renderer } = renderLightbox({+ originalUrl: "/original",+ thumbnailUrl: "/cold-thumbnail",+ name: "cold",+ width: 1200,+ height: 630,+ })+ const frame = () => renderer.root.findByProps({ "data-testid": tid.imageLightbox })+ const original = renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal })++ expect(frame().parent?.props.className).toContain("invisible")+ await act(async () => {+ original.props.onLoad(imageEvent(1200, 630, () => Promise.resolve()))+ await Promise.resolve()+ })+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-0")++ await loadThumbnail(renderer, 512, 269)+ expect(frame().parent?.props.className).toContain("visible")+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxThumbnail }).props.className).toContain("opacity-100")+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-0")+ expect(runAnimationFrame).toBeTypeOf("function")++ act(() => runAnimationFrame!(0))+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-100")+ } finally {+ vi.unstubAllGlobals()+ }+ })++ it.each([+ { name: "extreme landscape", width: 4000, height: 100 },+ { name: "extreme portrait", width: 100, height: 4000 },+ ])("keeps the error controls outside the clipped image frame for $name", ({ width, height }) => {+ const { renderer } = renderLightbox({ originalUrl: "/original", name: "extreme", width, height })+ act(() => renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.onError())+ const frame = renderer.root.findByProps({ "data-testid": tid.imageLightbox })+ const error = renderer.root.findByProps({ "data-testid": tid.imageLightboxError })+ const retry = renderer.root.findByProps({ "data-testid": tid.imageLightboxRetry })++ expect(frame.findAllByProps({ "data-testid": tid.imageLightboxError })).toHaveLength(0)+ expect(error.parent).toBe(frame.parent)+ expect(error.props.className).toContain("w-max")+ expect(retry.props.className).toContain("h-12")+ expect(retry.props.className).toContain("min-w-12")+ })++ it("preserves the dialog close callback", () => {+ const { renderer, onClose } = renderLightbox({ originalUrl: "/original", name: "photo" })+ const dialog = renderer.root.findByType("dialog-mock")+ act(() => dialog.props.onOpenChange(true))+ expect(onClose).not.toHaveBeenCalled()+ act(() => dialog.props.onOpenChange(false))+ expect(onClose).toHaveBeenCalledOnce()})})diff --git a/src/web/src/components/community/messages/image-lightbox.tsx b/src/web/src/components/community/messages/image-lightbox.tsxindex 91849282d..a61523e81 100644--- a/src/web/src/components/community/messages/image-lightbox.tsx+++ b/src/web/src/components/community/messages/image-lightbox.tsx@@ -1,35 +1,180 @@"use client"-import { useState } from "react"+import { useEffect, useMemo, useState } from "react"import { Dialog, DialogContent } from "@/components/ui/dialog"import type { ImagePreview } from "@/lib/community/models/message"import { tid } from "@/lib/community/testids"+import {+ previewFrameStyle,+ type ImageDimensions,+ validImageDimensions,+} from "./image-lightbox-layout"++type OriginalStatus = "loading" | "decoded" | "ready" | "failed"+type ThumbnailStatus = "loading" | "ready" | "failed" | "absent"++type PreviewState = {+ dimensions?: ImageDimensions+ originalStatus: OriginalStatus+ thumbnailStatus: ThumbnailStatus+ requestKey: number+}++function PreviewFrame({ image }: { image: ImagePreview }) {+ const knownDimensions = useMemo(+ () => validImageDimensions(image.width, image.height),+ [image.height, image.width],+ )+ const [state, setState] = useState<PreviewState>({+ dimensions: knownDimensions,+ originalStatus: "loading",+ thumbnailStatus: image.thumbnailUrl ? "loading" : "absent",+ requestKey: 0,+ })++ const frameStyle = previewFrameStyle(state.dimensions)+ const originalReady = state.originalStatus === "ready"+ const thumbnailReady = state.thumbnailStatus === "ready"+ const previewVisible = state.thumbnailStatus !== "loading"++ useEffect(() => {+ if (state.originalStatus !== "decoded" || !previewVisible) return+ const requestKey = state.requestKey+ const frameId = requestAnimationFrame(() => {+ setState((current) => (+ current.requestKey === requestKey && current.originalStatus === "decoded"+ ? { ...current, originalStatus: "ready" }+ : current+ ))+ })+ return () => cancelAnimationFrame(frameId)+ }, [previewVisible, state.originalStatus, state.requestKey])++ const settleThumbnail = async (element: HTMLImageElement) => {+ try {+ await element.decode()+ } catch {+ setState((current) => ({ ...current, thumbnailStatus: "failed" }))+ return+ }++ const dimensions = validImageDimensions(element.naturalWidth, element.naturalHeight)+ setState((current) => ({+ ...current,+ dimensions: knownDimensions ?? dimensions ?? current.dimensions,+ thumbnailStatus: dimensions ? "ready" : "failed",+ }))+ }++ const failThumbnail = () => {+ setState((current) => ({ ...current, thumbnailStatus: "failed" }))+ }++ const revealDecodedOriginal = async (element: HTMLImageElement, requestKey: number) => {+ try {+ await element.decode()+ } catch {+ setState((current) => current.requestKey === requestKey+ ? { ...current, originalStatus: "failed" }+ : current)+ return+ }++ const naturalDimensions = validImageDimensions(element.naturalWidth, element.naturalHeight)+ setState((current) => {+ if (current.requestKey !== requestKey) return current+ return {+ ...current,+ dimensions: knownDimensions ?? naturalDimensions ?? current.dimensions,+ originalStatus: current.thumbnailStatus === "loading" ? "decoded" : "ready",+ }+ })+ }++ const failOriginal = (requestKey: number) => {+ setState((current) => current.requestKey === requestKey+ ? { ...current, originalStatus: "failed" }+ : current)+ }++ const retryOriginal = () => {+ setState((current) => ({+ ...current,+ originalStatus: "loading",+ requestKey: current.requestKey + 1,+ }))+ }++ return (+ <div className={`relative w-fit ${previewVisible ? "visible" : "invisible"}`}>+ <div+ data-testid={tid.imageLightbox}+ className="relative overflow-hidden rounded-lg bg-background"+ style={frameStyle}+ >+ {image.thumbnailUrl && (+ <img+ data-testid={tid.imageLightboxThumbnail}+ src={image.thumbnailUrl}+ alt={image.name}+ onLoad={(event) => { void settleThumbnail(event.currentTarget) }}+ onError={failThumbnail}+ className={`absolute inset-0 size-full rounded-lg object-contain transition-opacity duration-150 ease-out motion-reduce:transition-none ${thumbnailReady && !originalReady ? "opacity-100" : "opacity-0"}`}+ />+ )}+ {!thumbnailReady && previewVisible && !originalReady && (+ <div+ data-testid={tid.imageLightboxLoading}+ role="status"+ className="absolute inset-0 flex items-center justify-center px-4 text-sm text-muted-foreground"+ >+ 正在加载原图+ </div>+ )}+ {state.originalStatus !== "failed" && (+ <img+ key={state.requestKey}+ data-testid={tid.imageLightboxOriginal}+ src={image.originalUrl}+ alt={image.name}+ onLoad={(event) => { void revealDecodedOriginal(event.currentTarget, state.requestKey) }}+ onError={() => failOriginal(state.requestKey)}+ className={`pointer-events-none absolute inset-0 size-full rounded-lg object-contain transition-opacity duration-150 ease-out motion-reduce:transition-none ${originalReady ? "opacity-100" : "opacity-0"}`}+ />+ )}+ </div>+ {state.originalStatus === "failed" && (+ <div+ data-testid={tid.imageLightboxError}+ role="status"+ className="absolute bottom-3 left-1/2 z-10 flex min-h-11 w-max max-w-[min(90vw,24rem)] -translate-x-1/2 items-center justify-between gap-2 rounded-md border border-border bg-background px-3 py-2 text-sm shadow-sm"+ >+ <span>原图加载失败</span>+ <button+ type="button"+ data-testid={tid.imageLightboxRetry}+ onClick={retryOriginal}+ className="h-12 min-w-12 rounded-md px-3 font-medium text-foreground transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:h-9 sm:min-w-0"+ >+ 重试+ </button>+ </div>+ )}+ </div>+ )+}-// Full-screen image preview. Uses shadcn Dialog for accessibility (focus trap, Esc, aria).export function ImageLightbox({ image, onClose }: { image: ImagePreview; onClose: () => void }) {- const [originalLoaded, setOriginalLoaded] = useState(false)- const [originalFailed, setOriginalFailed] = useState(false)return (- <Dialog open onOpenChange={(o) => { if (!o) onClose() }}>+ <Dialog open onOpenChange={(open) => { if (!open) onClose() }}><DialogContent- className="flex max-h-[90vh] w-auto sm:max-w-none items-center justify-center border-none bg-transparent p-0 shadow-none"+ className="flex max-h-[90vh] w-auto items-center justify-center border-none bg-transparent p-0 shadow-none sm:max-w-none"showCloseButton={false}>- <div data-testid={tid.imageLightbox} className="grid max-h-[85vh] max-w-[90vw] place-items-center">- {image.thumbnailUrl && (- <img data-testid={tid.imageLightboxThumbnail} src={image.thumbnailUrl} alt={image.name} className="col-start-1 row-start-1 max-h-[85vh] max-w-[90vw] rounded-lg object-contain" />- )}- {!originalFailed && (- <img- data-testid={tid.imageLightboxOriginal}- src={image.originalUrl}- alt={image.name}- onLoad={() => setOriginalLoaded(true)}- onError={() => setOriginalFailed(true)}- className={`col-start-1 row-start-1 max-h-[85vh] max-w-[90vw] rounded-lg object-contain ${originalLoaded || !image.thumbnailUrl ? "opacity-100" : "invisible opacity-0"}`}- />- )}- </div>+ <PreviewFrame+ key={`${image.originalUrl}\u0000${image.thumbnailUrl ?? ""}\u0000${image.width ?? ""}\u0000${image.height ?? ""}`}+ image={image}+ /></DialogContent></Dialog>)diff --git a/src/web/src/components/community/messages/message.render.test.ts b/src/web/src/components/community/messages/message.render.test.tsindex 5e288420a..e5cdfe259 100644--- a/src/web/src/components/community/messages/message.render.test.ts+++ b/src/web/src/components/community/messages/message.render.test.ts@@ -422,6 +422,7 @@ describe("Message image attachment layout", () => {act(() => image.parent!.props.onClick())expect(onPreviewImage).toHaveBeenCalledWith({originalUrl: "/original", thumbnailUrl: "/thumbnail", name: "photo.png",+ width: 640, height: 480,})})})diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsxindex c0f68e0e3..2673a277a 100644--- a/src/web/src/components/community/messages/message.tsx+++ b/src/web/src/components/community/messages/message.tsx@@ -388,7 +388,13 @@ function MessageImpl({if (a.kind === "image") return (<buttonkey={i}- onClick={() => onPreviewImage?.({ originalUrl: a.url, thumbnailUrl: a.thumbnailUrl, name: a.name })}+ onClick={() => onPreviewImage?.({+ originalUrl: a.url,+ thumbnailUrl: a.thumbnailUrl,+ name: a.name,+ width: a.width,+ height: a.height,+ })}className="block w-fit max-w-full overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40"><imgdiff --git a/src/web/src/components/community/messages/thread-opener.test.ts b/src/web/src/components/community/messages/thread-opener.test.tsindex cf8cd33fb..b5142af05 100644--- a/src/web/src/components/community/messages/thread-opener.test.ts+++ b/src/web/src/components/community/messages/thread-opener.test.ts@@ -67,7 +67,10 @@ describe("ThreadOpener image attachment layout", () => {message: {id: "opener_1", type: "chat", authorId: "u1", authorName: "Alice",content: "Photo", createdAt: "2026-08-08T00:00:00.000Z",- attachments: [{ kind: "image", name: "photo.png", url: "/original", thumbnailUrl: "/thumbnail" }],+ attachments: [{+ kind: "image", name: "photo.png", url: "/original", thumbnailUrl: "/thumbnail",+ width: 640, height: 480,+ }],},})let renderer: TestRenderer.ReactTestRenderer@@ -82,6 +85,7 @@ describe("ThreadOpener image attachment layout", () => {act(() => image.parent!.props.onClick())expect(onPreviewImage).toHaveBeenCalledWith({originalUrl: "/original", thumbnailUrl: "/thumbnail", name: "photo.png",+ width: 640, height: 480,})})diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsxindex ab9e67163..aade7f8ed 100644--- a/src/web/src/components/community/messages/thread-opener.tsx+++ b/src/web/src/components/community/messages/thread-opener.tsx@@ -122,7 +122,13 @@ export function ThreadOpener({if (a.kind === "image") return (<buttonkey={i}- onClick={() => onPreviewImage?.({ originalUrl: a.url, thumbnailUrl: a.thumbnailUrl, name: a.name })}+ onClick={() => onPreviewImage?.({+ originalUrl: a.url,+ thumbnailUrl: a.thumbnailUrl,+ name: a.name,+ width: a.width,+ height: a.height,+ })}className="block w-fit max-w-full overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40"><imgdiff --git a/src/web/src/lib/community/models/message.ts b/src/web/src/lib/community/models/message.tsindex 9e225bd37..6e514563c 100644--- a/src/web/src/lib/community/models/message.ts+++ b/src/web/src/lib/community/models/message.ts@@ -14,7 +14,13 @@ export type Attachment =| (AttachmentMetadata & { kind: "image"; thumbnailUrl?: string; width?: number; height?: number })| FileAttachment-export type ImagePreview = { originalUrl: string; thumbnailUrl?: string; name: string }+export type ImagePreview = {+ originalUrl: string+ thumbnailUrl?: string+ name: string+ width?: number+ height?: number+}type Embed = {provider?: stringdiff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 6eac3f6e6..de6a9040d 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -56,6 +56,9 @@ export const tid = {imageLightbox: "community-image-lightbox",imageLightboxThumbnail: "community-image-lightbox-thumbnail",imageLightboxOriginal: "community-image-lightbox-original",+ imageLightboxLoading: "community-image-lightbox-loading",+ imageLightboxError: "community-image-lightbox-error",+ imageLightboxRetry: "community-image-lightbox-retry",message: (id: string) => `community-message-${id}`,messageImage: (id: string, index: number) => `community-message-image-${id}-${index}`,diff --git a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.tsindex fc9a19fb6..a371a8aaa 100644--- a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts+++ b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts@@ -1,50 +1,125 @@-import { test, expect } from "./_fixtures/community-fixture"+import type { Locator, Page, TestInfo } from "@playwright/test"import { readFileSync } from "node:fs"+import { deflateSync } from "node:zlib"+import { test, expect } from "./_fixtures/community-fixture"import { tid } from "./_fixtures/testids"import { composerEditable, createServer } from "./_fixtures/actions"-const PNG_FIXTURE = readFileSync("public/icon-192.png")+const LANDSCAPE_FIXTURE = readFileSync("public/blog/no-code-automation-ai-agents/hero.webp")+const PORTRAIT_FIXTURE = readFileSync("public/blog/claude-code-and-codex-same-team/workflow-handoff.webp")-test("image thumbnails defer original loading and survive original errors", async ({ asUser }) => {- test.setTimeout(120_000)- const { page } = await asUser("alice")- const browserErrors: string[] = []- page.on("pageerror", (error) => browserErrors.push(error.message))- page.on("console", (message) => {- if (message.type() === "error") browserErrors.push(message.text())- })- await page.goto("/c")- await page.waitForURL(/\/c/, { timeout: 20_000, waitUntil: "commit" })- await createServer(page, `Thumbnail E2E ${Date.now()}`)- const channelId = new URL(page.url()).pathname.split("/").at(-1)!- const observedGetPaths: string[] = []- let messagePostCount = 0- page.on("request", (request) => {- if (request.method() === "GET") observedGetPaths.push(new URL(request.url()).pathname)- if (- request.method() === "POST"- && new URL(request.url()).pathname === `/api/community/channels/${channelId}/messages`- ) messagePostCount++- })+function crc32(buffer: Buffer): number {+ let crc = 0xffff_ffff+ for (const byte of buffer) {+ crc ^= byte+ for (let bit = 0; bit < 8; bit++) {+ crc = (crc >>> 1) ^ ((crc & 1) === 1 ? 0xedb8_8320 : 0)+ }+ }+ return (crc ^ 0xffff_ffff) >>> 0+}- const uploadResponsePromise = page.waitForResponse((response) => {- const pathname = new URL(response.url()).pathname- return response.request().method() === "POST"- && pathname === `/api/community/channels/${channelId}/attachments`- })- const messageResponsePromise = page.waitForResponse((response) => {- const pathname = new URL(response.url()).pathname- return response.request().method() === "POST"- && pathname === `/api/community/channels/${channelId}/messages`+function pngChunk(type: string, data: Buffer): Buffer {+ const typeBuffer = Buffer.from(type, "ascii")+ const chunk = Buffer.alloc(12 + data.length)+ chunk.writeUInt32BE(data.length, 0)+ typeBuffer.copy(chunk, 4)+ data.copy(chunk, 8)+ chunk.writeUInt32BE(crc32(Buffer.concat([typeBuffer, data])), 8 + data.length)+ return chunk+}++function solidPng(width: number, height: number, color: [number, number, number]): Buffer {+ const row = Buffer.alloc(1 + width * 3)+ for (let x = 0; x < width; x++) {+ row[1 + x * 3] = color[0]+ row[2 + x * 3] = color[1]+ row[3 + x * 3] = color[2]+ }+ const pixels = Buffer.alloc(row.length * height)+ for (let y = 0; y < height; y++) row.copy(pixels, y * row.length)++ const header = Buffer.alloc(13)+ header.writeUInt32BE(width, 0)+ header.writeUInt32BE(height, 4)+ header[8] = 8+ header[9] = 2+ return Buffer.concat([+ Buffer.from("89504e470d0a1a0a", "hex"),+ pngChunk("IHDR", header),+ pngChunk("IDAT", deflateSync(pixels, { level: 9 })),+ pngChunk("IEND", Buffer.alloc(0)),+ ])+}++const EXTREME_LANDSCAPE_FIXTURE = solidPng(4000, 100, [91, 110, 225])+const EXTREME_PORTRAIT_FIXTURE = solidPng(100, 4000, [225, 91, 142])++type Rect = { x: number; y: number; width: number; height: number }++async function boundingRect(locator: Locator): Promise<Rect> {+ const rect = await locator.boundingBox()+ expect(rect).not.toBeNull()+ return rect!+}++function expectSameRect(actual: Rect, expected: Rect) {+ expect(actual.x).toBeCloseTo(expected.x, 1)+ expect(actual.y).toBeCloseTo(expected.y, 1)+ expect(actual.width).toBeCloseTo(expected.width, 1)+ expect(actual.height).toBeCloseTo(expected.height, 1)+}++function expectWithinPreviewViewport(rect: Rect, viewport: { width: number; height: number }) {+ expect(rect.width).toBeLessThanOrEqual(viewport.width * 0.9 + 0.5)+ expect(rect.height).toBeLessThanOrEqual(viewport.height * 0.85 + 0.5)+}++async function previewRects(page: Page) {+ const container = await boundingRect(page.getByTestId(tid.imageLightbox))+ const thumbnail = await boundingRect(page.getByTestId(tid.imageLightboxThumbnail))+ const original = await boundingRect(page.getByTestId(tid.imageLightboxOriginal))+ expectSameRect(thumbnail, container)+ expectSameRect(original, container)+ return { container, thumbnail, original }+}++async function waitForDialogEntrance(page: Page) {+ await expect(page.getByTestId(tid.imageLightbox)).toBeVisible()+ await page.waitForTimeout(200)+}++async function attachScreenshot(testInfo: TestInfo, name: string, page: Page) {+ await testInfo.attach(`${name}.png`, {+ body: await page.screenshot(),+ contentType: "image/png",})+}+async function uploadImage(args: {+ page: Page+ channelId: string+ message: string+ name: string+ buffer: Buffer+ mimeType?: string+}) {+ const { page, channelId, message, name, buffer, mimeType = "image/webp" } = args+ const uploadResponsePromise = page.waitForResponse((response) => (+ response.request().method() === "POST"+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/attachments`+ ))+ const messageResponsePromise = page.waitForResponse((response) => (+ response.request().method() === "POST"+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/messages`+ ))const editable = composerEditable(page)await editable.click()- await editable.pressSequentially("thumbnail network gate")+ await editable.pressSequentially(message)await page.locator('input[type="file"]').last().setInputFiles({- name: "pixel.png",- mimeType: "image/png",- buffer: PNG_FIXTURE,+ name,+ mimeType,+ buffer,})await expect.poll(() => editable.evaluate((element) => document.activeElement === element)).toBe(true)await page.keyboard.press("Enter")@@ -52,108 +127,327 @@ test("image thumbnails defer original loading and survive original errors", asynconst uploadResponse = await uploadResponsePromiseexpect(uploadResponse.ok()).toBe(true)const uploaded = await uploadResponse.json() as { id: string; hasThumbnail?: boolean }- // This is server-authoritative proof that the browser multipart contained a- // valid JPEG thumbnail and that both objects were persisted.expect(uploaded.hasThumbnail).toBe(true)-- const originalPath = `/api/community/channels/${channelId}/attachments/${uploaded.id}`- const thumbnailPath = `${originalPath}/thumbnail`const messageResponse = await messageResponsePromiseexpect(messageResponse.status()).toBe(201)expect((messageResponse.request().postDataJSON() as { attachments?: string[] }).attachments).toEqual([uploaded.id])- expect(messagePostCount).toBe(1)const sent = await messageResponse.json() as { message: { id: string } }- const listImage = page.getByTestId(tid.messageImage(sent.message.id, 0))- await expect(listImage).toHaveAttribute("src", thumbnailPath)- await expect.poll(() => observedGetPaths.filter((path) => path === thumbnailPath).length).toBeGreaterThan(0)- expect(observedGetPaths.filter((path) => path === originalPath)).toHaveLength(0)-- let releaseOriginal!: () => void- const originalGate = new Promise<void>((resolve) => { releaseOriginal = resolve })- await page.route(`**${originalPath}`, async (route) => {- if (- route.request().method() === "GET"- && new URL(route.request().url()).pathname === originalPath- ) {- await originalGate+ const originalPath = `/api/community/channels/${channelId}/attachments/${uploaded.id}`++ return {+ messageId: sent.message.id,+ originalPath,+ thumbnailPath: `${originalPath}/thumbnail`,+ }+}++test("image previews keep one frame through loading, decode, failure, retry, and mobile", async ({ asUser }, testInfo) => {+ test.setTimeout(180_000)+ const { page } = await asUser("alice")+ await page.setViewportSize({ width: 1280, height: 900 })+ await page.goto("/c")+ await page.waitForURL(/\/c/, { timeout: 20_000, waitUntil: "commit" })+ await createServer(page, `Thumbnail E2E ${Date.now()}`)+ const channelUrl = page.url()+ const channelId = new URL(channelUrl).pathname.split("/").at(-1)!+ const observedGetPaths: string[] = []+ let messagePostCount = 0+ page.on("request", (request) => {+ const pathname = new URL(request.url()).pathname+ if (request.method() === "GET") observedGetPaths.push(pathname)+ if (request.method() === "POST" && pathname === `/api/community/channels/${channelId}/messages`) {+ messagePostCount+++ }+ })++ let releaseColdThumbnail!: () => void+ const coldThumbnailGate = new Promise<void>((resolve) => { releaseColdThumbnail = resolve })+ let holdColdThumbnail = true+ let coldThumbnailRequests = 0+ const thumbnailPattern = "**/api/community/channels/**/attachments/**/thumbnail"+ await page.route(thumbnailPattern, async (route) => {+ if (holdColdThumbnail && route.request().method() === "GET") {+ coldThumbnailRequests+++ await coldThumbnailGate}await route.continue()})- const listImageButton = page.getByRole("button", { name: "pixel.png" })- // Message action controls lazy-activate on pointer entry. Let that stable- // render settle before the click, matching a real pointer's hover→press.- await listImageButton.hover()- await listImageButton.click()- await page.waitForTimeout(500)- if (await page.getByTestId(tid.imageLightbox).count() === 0 && browserErrors.length > 0) {- throw new Error(`lightbox render errors: ${browserErrors.join(" | ")}`)- }+ const landscape = await uploadImage({+ page,+ channelId,+ message: "landscape preview network gate",+ name: "landscape.webp",+ buffer: LANDSCAPE_FIXTURE,+ })+ const landscapeListImage = page.getByTestId(tid.messageImage(landscape.messageId, 0))+ await expect(landscapeListImage).toHaveAttribute("src", landscape.thumbnailPath)+ await expect.poll(() => observedGetPaths.filter((path) => path === landscape.thumbnailPath).length).toBeGreaterThan(0)+ expect(observedGetPaths.filter((path) => path === landscape.originalPath)).toHaveLength(0)++ let releaseLandscape!: () => void+ const landscapeGate = new Promise<void>((resolve) => { releaseLandscape = resolve })+ await page.route(`**${landscape.originalPath}`, async (route) => {+ if (route.request().method() === "GET" && new URL(route.request().url()).pathname === landscape.originalPath) {+ await landscapeGate+ }+ await route.continue()+ })+ const landscapeButton = page.getByRole("button", { name: "landscape.webp" })+ await landscapeButton.hover()+ await landscapeButton.click()+ await expect(page.getByTestId(tid.imageLightboxOriginal)).toHaveClass(/opacity-0/)+ await expect.poll(() => observedGetPaths.filter((path) => path === landscape.originalPath).length).toBe(1)+ await expect.poll(() => coldThumbnailRequests).toBeGreaterThan(0)+ await expect(page.getByTestId(tid.imageLightbox)).toBeHidden()+ expect(await page.getByTestId(tid.imageLightboxThumbnail).evaluate((element: HTMLImageElement) => ({+ complete: element.complete,+ naturalWidth: element.naturalWidth,+ }))).toEqual({ complete: false, naturalWidth: 0 })++ holdColdThumbnail = false+ releaseColdThumbnail()await expect(page.getByTestId(tid.imageLightbox)).toBeVisible()- await expect(page.getByTestId(tid.imageLightboxThumbnail)).toHaveAttribute("src", thumbnailPath)- await expect(page.getByTestId(tid.imageLightboxOriginal)).toHaveClass(/invisible/)- await expect.poll(() => observedGetPaths.filter((path) => path === originalPath).length).toBe(1)+ const coldThumbnailReady = await page.getByTestId(tid.imageLightboxThumbnail).evaluate((element: HTMLImageElement) => ({+ complete: element.complete,+ naturalWidth: element.naturalWidth,+ }))+ expect(coldThumbnailReady.complete).toBe(true)+ expect(coldThumbnailReady.naturalWidth).toBeGreaterThan(0)+ await expect(page.getByTestId(tid.imageLightboxThumbnail)).toHaveClass(/opacity-100/)+ await attachScreenshot(testInfo, "desktop-landscape-first-visible", page)+ await page.unroute(thumbnailPattern)++ await waitForDialogEntrance(page)+ const desktopLandscapeLoading = await previewRects(page)+ expectWithinPreviewViewport(desktopLandscapeLoading.container, { width: 1280, height: 900 })+ await attachScreenshot(testInfo, "desktop-landscape-loading", page)- releaseOriginal()- await expect(page.getByTestId(tid.imageLightboxOriginal)).toHaveAttribute("src", originalPath)- await expect(page.getByTestId(tid.imageLightboxOriginal)).not.toHaveClass(/invisible/)+ await page.setViewportSize({ width: 900, height: 700 })+ const desktopLandscapeResized = await previewRects(page)+ expectWithinPreviewViewport(desktopLandscapeResized.container, { width: 900, height: 700 })+ expect(desktopLandscapeResized.container.width).toBeLessThan(desktopLandscapeLoading.container.width)+ await attachScreenshot(testInfo, "desktop-landscape-resized-loading", page)+ await page.setViewportSize({ width: 1280, height: 900 })+ const desktopLandscapeRestored = await previewRects(page)+ expectSameRect(desktopLandscapeRestored.container, desktopLandscapeLoading.container)++ releaseLandscape()+ await expect(page.getByTestId(tid.imageLightboxOriginal)).toHaveClass(/opacity-100/)+ const desktopLandscapeLoaded = await previewRects(page)+ expectSameRect(desktopLandscapeLoaded.container, desktopLandscapeRestored.container)+ await attachScreenshot(testInfo, "desktop-landscape-loaded", page)await page.keyboard.press("Escape")await expect(page.getByTestId(tid.imageLightbox)).toHaveCount(0)+ await page.unroute(`**${landscape.originalPath}`)- const errorUploadResponsePromise = page.waitForResponse((response) =>- response.request().method() === "POST"- && new URL(response.url()).pathname === `/api/community/channels/${channelId}/attachments`,- )- const errorMessageResponsePromise = page.waitForResponse((response) =>- response.request().method() === "POST"- && new URL(response.url()).pathname === `/api/community/channels/${channelId}/messages`,- )-- await editable.click()- await editable.pressSequentially("original error gate")- await page.locator('input[type="file"]').last().setInputFiles({- name: "broken.png",- mimeType: "image/png",- buffer: PNG_FIXTURE,+ const portrait = await uploadImage({+ page,+ channelId,+ message: "portrait preview error gate",+ name: "portrait.webp",+ buffer: PORTRAIT_FIXTURE,})- await expect.poll(() => editable.evaluate((element) => document.activeElement === element)).toBe(true)- await page.keyboard.press("Enter")-- const errorUploaded = await (await errorUploadResponsePromise).json() as {- id: string- hasThumbnail?: boolean- }- expect(errorUploaded.hasThumbnail).toBe(true)- const errorMessageResponse = await errorMessageResponsePromise- expect(errorMessageResponse.status()).toBe(201)- const errorSent = await errorMessageResponse.json() as { message: { id: string } }- const errorOriginalPath = `/api/community/channels/${channelId}/attachments/${errorUploaded.id}`- const errorThumbnailPath = `${errorOriginalPath}/thumbnail`- const originalRequests: string[] = []+ const portraitListImage = page.getByTestId(tid.messageImage(portrait.messageId, 0))+ await expect(portraitListImage).toHaveAttribute("src", portrait.thumbnailPath)+ const portraitOriginalRequests: string[] = []page.on("request", (request) => {- if (request.method() === "GET" && new URL(request.url()).pathname === errorOriginalPath) {- originalRequests.push(request.url())+ if (request.method() === "GET" && new URL(request.url()).pathname === portrait.originalPath) {+ portraitOriginalRequests.push(request.url())}})- const errorListImage = page.getByTestId(tid.messageImage(errorSent.message.id, 0))- await expect(errorListImage).toHaveAttribute("src", errorThumbnailPath)- expect(originalRequests).toHaveLength(0)- await page.route(`**${errorOriginalPath}`, async (route) => {- if (route.request().method() === "GET" && new URL(route.request().url()).pathname === errorOriginalPath) {+ let releasePortraitFailure!: () => void+ const portraitFailureGate = new Promise<void>((resolve) => { releasePortraitFailure = resolve })+ await page.route(`**${portrait.originalPath}`, async (route) => {+ if (route.request().method() !== "GET" || new URL(route.request().url()).pathname !== portrait.originalPath) {+ await route.continue()+ return+ }+ if (portraitOriginalRequests.length === 1) {+ await portraitFailureGateawait route.fulfill({ status: 500, contentType: "text/plain", body: "forced original failure" })return}await route.continue()})- const errorListImageButton = page.getByRole("button", { name: "broken.png" })- await errorListImageButton.hover()- await errorListImageButton.click()- await expect.poll(() => originalRequests.length).toBe(1)- await expect(page.getByTestId(tid.imageLightboxThumbnail)).toHaveAttribute("src", errorThumbnailPath)+ const portraitButton = page.getByRole("button", { name: "portrait.webp" })+ await portraitButton.hover()+ await portraitButton.click()+ await expect.poll(() => portraitOriginalRequests.length).toBe(1)+ await expect(page.getByTestId(tid.imageLightboxOriginal)).toHaveClass(/opacity-0/)+ await waitForDialogEntrance(page)+ const desktopPortraitLoading = await previewRects(page)+ await attachScreenshot(testInfo, "desktop-portrait-loading", page)+ releasePortraitFailure()+ await expect(page.getByTestId(tid.imageLightboxError)).toContainText("原图加载失败")await expect(page.getByTestId(tid.imageLightboxThumbnail)).toBeVisible()- await expect(page.getByTestId(tid.imageLightboxOriginal)).toHaveCount(0)- await page.waitForTimeout(500)- expect(originalRequests).toHaveLength(1)- await expect(errorListImage).toHaveAttribute("src", errorThumbnailPath)+ await waitForDialogEntrance(page)+ const desktopPortraitFailed = {+ container: await boundingRect(page.getByTestId(tid.imageLightbox)),+ thumbnail: await boundingRect(page.getByTestId(tid.imageLightboxThumbnail)),+ }+ expectSameRect(desktopPortraitFailed.thumbnail, desktopPortraitFailed.container)+ expectSameRect(desktopPortraitFailed.container, desktopPortraitLoading.container)+ await attachScreenshot(testInfo, "desktop-portrait-failed", page)++ await page.getByTestId(tid.imageLightboxRetry).click()+ await expect.poll(() => portraitOriginalRequests.length).toBe(2)+ await expect(page.getByTestId(tid.imageLightboxOriginal)).toHaveClass(/opacity-100/)+ const desktopPortraitRetried = await previewRects(page)+ expectSameRect(desktopPortraitRetried.container, desktopPortraitFailed.container)+ await attachScreenshot(testInfo, "desktop-portrait-retried", page)+ expect(messagePostCount).toBe(2)+ await page.keyboard.press("Escape")+ await page.unroute(`**${portrait.originalPath}`)++ const extremeLandscape = await uploadImage({+ page,+ channelId,+ message: "extreme landscape error controls",+ name: "extreme-landscape.png",+ buffer: EXTREME_LANDSCAPE_FIXTURE,+ mimeType: "image/png",+ })+ const extremePortrait = await uploadImage({+ page,+ channelId,+ message: "extreme portrait error controls",+ name: "extreme-portrait.png",+ buffer: EXTREME_PORTRAIT_FIXTURE,+ mimeType: "image/png",+ })+ expect(messagePostCount).toBe(4)++ const { page: mobilePage } = await asUser("alice")+ await mobilePage.setViewportSize({ width: 390, height: 844 })+ await mobilePage.goto(channelUrl)+ await mobilePage.waitForURL(new RegExp(`/c/channels/[^/]+/${channelId}$`), { waitUntil: "commit" })+ await expect(mobilePage.getByTestId(tid.messageImage(landscape.messageId, 0))).toBeVisible()++ let releaseMobileLandscape!: () => void+ const mobileLandscapeGate = new Promise<void>((resolve) => { releaseMobileLandscape = resolve })+ let mobileLandscapeRequests = 0+ await mobilePage.route(`**${landscape.originalPath}`, async (route) => {+ if (route.request().method() === "GET" && new URL(route.request().url()).pathname === landscape.originalPath) {+ mobileLandscapeRequests+++ await mobileLandscapeGate+ }+ await route.continue()+ })+ await mobilePage.getByRole("button", { name: "landscape.webp" }).click()+ await expect.poll(() => mobileLandscapeRequests).toBe(1)+ await expect(mobilePage.getByTestId(tid.imageLightboxOriginal)).toHaveClass(/opacity-0/)+ await waitForDialogEntrance(mobilePage)+ const mobileLandscapeLoading = await previewRects(mobilePage)+ expectWithinPreviewViewport(mobileLandscapeLoading.container, { width: 390, height: 844 })+ await attachScreenshot(testInfo, "mobile-landscape-loading", mobilePage)+ releaseMobileLandscape()+ await expect(mobilePage.getByTestId(tid.imageLightboxOriginal)).toHaveClass(/opacity-100/)+ const mobileLandscapeLoaded = await previewRects(mobilePage)+ expectSameRect(mobileLandscapeLoaded.container, mobileLandscapeLoading.container)+ await attachScreenshot(testInfo, "mobile-landscape-loaded", mobilePage)+ await mobilePage.keyboard.press("Escape")+ await mobilePage.unroute(`**${landscape.originalPath}`)++ let releaseMobilePortrait!: () => void+ const mobilePortraitGate = new Promise<void>((resolve) => { releaseMobilePortrait = resolve })+ let mobilePortraitRequests = 0+ await mobilePage.route(`**${portrait.originalPath}`, async (route) => {+ if (route.request().method() === "GET" && new URL(route.request().url()).pathname === portrait.originalPath) {+ mobilePortraitRequests+++ await mobilePortraitGate+ }+ await route.continue()+ })+ await mobilePage.getByRole("button", { name: "portrait.webp" }).click()+ await expect.poll(() => mobilePortraitRequests).toBe(1)+ await expect(mobilePage.getByTestId(tid.imageLightboxOriginal)).toHaveClass(/opacity-0/)+ await waitForDialogEntrance(mobilePage)+ const mobilePortraitLoading = await previewRects(mobilePage)+ expectWithinPreviewViewport(mobilePortraitLoading.container, { width: 390, height: 844 })+ await attachScreenshot(testInfo, "mobile-portrait-loading", mobilePage)++ await mobilePage.setViewportSize({ width: 844, height: 390 })+ const mobilePortraitLandscapeOrientation = await previewRects(mobilePage)+ expectWithinPreviewViewport(mobilePortraitLandscapeOrientation.container, { width: 844, height: 390 })+ expect(mobilePortraitLandscapeOrientation.container.height).toBeLessThan(mobilePortraitLoading.container.height)+ await attachScreenshot(testInfo, "mobile-portrait-landscape-orientation-loading", mobilePage)+ await mobilePage.setViewportSize({ width: 390, height: 844 })+ const mobilePortraitRestored = await previewRects(mobilePage)+ expectSameRect(mobilePortraitRestored.container, mobilePortraitLoading.container)++ releaseMobilePortrait()+ await expect(mobilePage.getByTestId(tid.imageLightboxOriginal)).toHaveClass(/opacity-100/)+ const mobilePortraitLoaded = await previewRects(mobilePage)+ expectSameRect(mobilePortraitLoaded.container, mobilePortraitRestored.container)+ await attachScreenshot(testInfo, "mobile-portrait-loaded", mobilePage)+ await mobilePage.keyboard.press("Escape")+ await expect(mobilePage.getByTestId(tid.imageLightbox)).toHaveCount(0)++ async function assertExtremeFailure(args: {+ attachment: typeof extremeLandscape+ buttonName: string+ screenshotName: string+ }) {+ const { attachment, buttonName, screenshotName } = args+ let requests = 0+ await mobilePage.route(`**${attachment.originalPath}`, async (route) => {+ if (route.request().method() === "GET" && new URL(route.request().url()).pathname === attachment.originalPath) {+ requests+++ await route.fulfill({ status: 500, contentType: "text/plain", body: "forced extreme failure" })+ return+ }+ await route.continue()+ })++ await mobilePage.getByRole("button", { name: buttonName }).click()+ await expect.poll(() => requests).toBe(1)+ await expect(mobilePage.getByTestId(tid.imageLightboxError)).toBeVisible()+ const frame = await boundingRect(mobilePage.getByTestId(tid.imageLightbox))+ const error = await boundingRect(mobilePage.getByTestId(tid.imageLightboxError))+ const retry = await boundingRect(mobilePage.getByTestId(tid.imageLightboxRetry))+ expect(retry.width).toBeGreaterThanOrEqual(44)+ expect(retry.height).toBeGreaterThanOrEqual(44)+ expect(error.x).toBeGreaterThanOrEqual(0)+ expect(error.y).toBeGreaterThanOrEqual(0)+ expect(error.x + error.width).toBeLessThanOrEqual(390)+ expect(error.y + error.height).toBeLessThanOrEqual(844)+ await attachScreenshot(testInfo, screenshotName, mobilePage)+ await mobilePage.keyboard.press("Escape")+ await mobilePage.unroute(`**${attachment.originalPath}`)+ return { frame, error, retry }+ }++ const mobileExtremeLandscapeFailed = await assertExtremeFailure({+ attachment: extremeLandscape,+ buttonName: "extreme-landscape.png",+ screenshotName: "mobile-extreme-landscape-failed",+ })+ const mobileExtremePortraitFailed = await assertExtremeFailure({+ attachment: extremePortrait,+ buttonName: "extreme-portrait.png",+ screenshotName: "mobile-extreme-portrait-failed",+ })++ await testInfo.attach("image-preview-rects.json", {+ body: Buffer.from(JSON.stringify({+ desktopLandscapeLoading,+ desktopLandscapeResized,+ desktopLandscapeRestored,+ desktopLandscapeLoaded,+ desktopPortraitLoading,+ desktopPortraitFailed,+ desktopPortraitRetried,+ mobileLandscapeLoading,+ mobileLandscapeLoaded,+ mobilePortraitLoading,+ mobilePortraitLandscapeOrientation,+ mobilePortraitRestored,+ mobilePortraitLoaded,+ mobileExtremeLandscapeFailed,+ mobileExtremePortraitFailed,+ }, null, 2)),+ contentType: "application/json",+ })})