Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): unify remote image states (#716)

Generff24fb4b311e
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index a83d41731..38a0ac469 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -68,6 +68,7 @@ export const SPEC_SECONDS = {
"54-authenticated-context-menu-policy.spec.ts": 55,
"54-blog-multizone.spec.ts": 60,
"55-message-scroll-characterization.spec.ts": 180,
+ "56-remote-image-state-contract.spec.ts": 15,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index b08b31f1c..3d04e2b6f 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -71,7 +71,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([579, 579, 584, 584, 584])
+ expect(totals.sort((left, right) => left - right)).toEqual([582, 585, 585, 586, 587])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index bfd9ca1a3..e7d6a82cf 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -2259,17 +2259,17 @@ html.dark .blog-content [data-rehype-pretty-code-figure] span {
}
/* Community Markdown images keep Streamdown's wrapper/actions while matching
- the 300px attachment cap. Width remains responsive and intrinsic ratio wins. */
+ the stable shared remote-image frame and 300px attachment cap. */
[data-community-message-body] [data-streamdown="image-wrapper"] {
max-width: 100%;
}
[data-community-message-body] [data-streamdown="image"] {
display: block;
- width: auto;
- height: auto;
+ width: 100%;
+ height: 100%;
max-width: 100%;
- max-height: 18.75rem;
+ max-height: 100%;
object-fit: contain;
}
diff --git a/src/web/src/components/agent-chat/chat-view-parts.test.ts b/src/web/src/components/agent-chat/chat-view-parts.test.ts
index ad25ab544..b89095902 100644
--- a/src/web/src/components/agent-chat/chat-view-parts.test.ts
+++ b/src/web/src/components/agent-chat/chat-view-parts.test.ts
@@ -1,7 +1,13 @@
-import { describe, it, expect, vi } from "vitest"
-import { createElement } from "react"
+import React, { createElement } from "react"
import { renderToStaticMarkup } from "react-dom/server"
-import type { Agent } from "@alook/shared"
+import TestRenderer, { act } from "react-test-renderer"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import type { Agent, Artifact } from "@alook/shared"
+import { FileCard } from "@/components/agent-chat/event-cards/file-card"
+import { RemoteMarkdownImage } from "@/components/remote-image/remote-markdown-image"
+import { ArtifactCard, MENTION_COMPONENTS } from "./chat-view-parts"
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
const agents: Agent[] = []
@@ -14,8 +20,6 @@ vi.mock("@/components/agent-preview-card", () => ({
createElement("div", { "data-preview-agent-id": agent.id }),
}))
-import { MENTION_COMPONENTS } from "./chat-view-parts"
-
const agent = (id: string, name: string): Agent => ({
id,
workspace_id: "ws_1",
@@ -69,3 +73,58 @@ describe("MentionHighlight", () => {
expect(html).toContain("@Ada")
})
})
+
+const IMAGE_ARTIFACT: Artifact = {
+ id: "artifact-1",
+ conversation_id: "conversation-1",
+ agent_id: "agent-1",
+ filename: "diagram.png",
+ content_type: "image/png",
+ size: 128,
+ source: "agent",
+ has_thumbnail: true,
+ created_at: "2026-01-01T00:00:00Z",
+}
+
+describe("Agent Chat remote images", () => {
+ let renderer: TestRenderer.ReactTestRenderer | undefined
+
+ afterEach(async () => {
+ if (renderer) await act(async () => renderer?.unmount())
+ renderer = undefined
+ })
+
+ it("uses the shared Markdown image adapter", () => {
+ expect(MENTION_COMPONENTS.img).toBe(RemoteMarkdownImage)
+ })
+
+ it("keeps a failed artifact thumbnail as an explicit retryable image card", async () => {
+ const onClick = vi.fn()
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(ArtifactCard, {
+ artifact: IMAGE_ARTIFACT,
+ version: 1,
+ hasDuplicates: false,
+ onClick,
+ workspaceId: "workspace-1",
+ }), {
+ createNodeMock: (element) => {
+ if (element.type === "img") return { complete: false, naturalWidth: 0, naturalHeight: 0 }
+ if (element.props["data-remote-image-frame"] !== undefined) return {}
+ return null
+ },
+ })
+ })
+
+ const image = renderer!.root.findByProps({ "data-remote-image-kind": "content" })
+ const originalSrc = image.props.src
+ await act(async () => image.props.onError())
+
+ expect(renderer!.root.findAllByType(FileCard)).toHaveLength(0)
+ const retry = renderer!.root.findByType("button")
+ expect(retry.children).toEqual(["Retry"])
+ await act(async () => retry.props.onClick())
+ expect(renderer!.root.findByProps({ "data-remote-image-kind": "content" }).props.src).toBe(originalSrc)
+ expect(onClick).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/components/agent-chat/chat-view-parts.tsx b/src/web/src/components/agent-chat/chat-view-parts.tsx
index 6bc588fab..a5fbe4fb9 100644
--- a/src/web/src/components/agent-chat/chat-view-parts.tsx
+++ b/src/web/src/components/agent-chat/chat-view-parts.tsx
@@ -1,6 +1,6 @@
"use client";
-import React, { useState } from "react";
+import React from "react";
import type { Artifact } from "@alook/shared";
import { useAgentContext } from "@/contexts/agent-context";
import { AgentPreviewCard } from "@/components/agent-preview-card";
@@ -11,6 +11,8 @@ import {
} from "@/components/ui/popover";
import { FileCard } from "@/components/agent-chat/event-cards/file-card";
import { getArtifactThumbnailUrl } from "@/components/artifact-content-renderer";
+import { RemoteContentImage } from "@/components/remote-image/remote-image";
+import { RemoteMarkdownImage } from "@/components/remote-image/remote-markdown-image";
function MentionHighlight(
props: Record<string, unknown> & { children?: React.ReactNode },
@@ -51,6 +53,7 @@ export const MENTION_COMPONENTS: Record<
string,
React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>
> = {
+ img: RemoteMarkdownImage,
mention: MentionHighlight,
p: ({
children,
@@ -91,26 +94,22 @@ export function ArtifactCard({
onClick: (a: Artifact) => void;
workspaceId: string;
}) {
- const [thumbError, setThumbError] = useState(false);
const thumbnailUrl = artifact.has_thumbnail
? getArtifactThumbnailUrl(artifact.id, workspaceId)
: undefined;
- if (thumbnailUrl && !thumbError) {
+ if (thumbnailUrl) {
return (
- <button
- type="button"
- onClick={() => onClick(artifact)}
- className="max-w-64 overflow-hidden rounded-(--radius) border border-(--border) cursor-pointer [transition:translate_.2s_cubic-bezier(.2,.8,.2,1),box-shadow_.2s_ease] hover:-translate-y-0.5 [box-shadow:var(--e1)] hover:[box-shadow:var(--e2)]"
- >
- <img
- src={thumbnailUrl}
- alt={artifact.filename}
- loading="lazy"
- onError={() => setThumbError(true)}
- className="block w-full h-auto"
- />
- </button>
+ <RemoteContentImage
+ src={thumbnailUrl}
+ alt={artifact.filename}
+ loading="lazy"
+ onActivate={() => onClick(artifact)}
+ frameClassName="w-64 max-w-full rounded-(--radius) border border-(--border) [transition:translate_.2s_cubic-bezier(.2,.8,.2,1),box-shadow_.2s_ease] hover:-translate-y-0.5 hover:[box-shadow:var(--e2)] [box-shadow:var(--e1)]"
+ frameStyle={{ aspectRatio: "8/5" }}
+ imageClassName="object-contain"
+ errorLabel="Preview failed to load"
+ />
);
}
diff --git a/src/web/src/components/agent-chat/image-lightbox.tsx b/src/web/src/components/agent-chat/image-lightbox.tsx
index 5bee0a913..b5a6c77b5 100644
--- a/src/web/src/components/agent-chat/image-lightbox.tsx
+++ b/src/web/src/components/agent-chat/image-lightbox.tsx
@@ -5,6 +5,7 @@ import { createPortal } from "react-dom";
import type { Artifact } from "@alook/shared";
import { X, Download } from "lucide-react";
import { getArtifactUrl } from "@/components/artifact-content-renderer";
+import { RemoteContentImage } from "@/components/remote-image/remote-image";
type LightboxProps = {
open: boolean;
@@ -55,6 +56,7 @@ export function ImageLightbox(props: LightboxProps) {
<a
href={downloadUrl}
download={alt}
+ aria-label={`Download ${alt}`}
onClick={(e) => e.stopPropagation()}
className="rounded-full p-2 text-white/70 hover:text-white hover:bg-white/10 transition-colors"
>
@@ -63,18 +65,33 @@ export function ImageLightbox(props: LightboxProps) {
)}
<button
type="button"
+ aria-label="Close image"
onClick={onClose}
className="rounded-full p-2 text-white/70 hover:text-white hover:bg-white/10 transition-colors"
>
<X className="size-5" />
</button>
</div>
- <img
- src={src}
- alt={alt}
- onClick={(e) => e.stopPropagation()}
- className="max-w-[90vw] max-h-[90vh] object-contain rounded-lg"
- />
+ {props.imageUrl ? (
+ <img
+ src={src}
+ alt={alt}
+ onClick={(e) => e.stopPropagation()}
+ className="max-h-[90vh] max-w-[90vw] rounded-lg object-contain"
+ />
+ ) : (
+ <div onClick={(event) => event.stopPropagation()}>
+ <RemoteContentImage
+ src={src}
+ alt={alt}
+ loading="eager"
+ loadingLabel="Loading image"
+ frameClassName="h-[min(75vh,48rem)] w-[min(90vw,64rem)] rounded-lg bg-background/10"
+ imageClassName="rounded-lg object-contain"
+ errorLabel="Image failed to load"
+ />
+ </div>
+ )}
</div>,
document.body,
);
diff --git a/src/web/src/components/agent-chat/message-list.tsx b/src/web/src/components/agent-chat/message-list.tsx
index 83d586356..362dfd310 100644
--- a/src/web/src/components/agent-chat/message-list.tsx
+++ b/src/web/src/components/agent-chat/message-list.tsx
@@ -24,6 +24,7 @@ import { toast } from "sonner";
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
import { useHoverCapable } from "@/hooks/use-hover-capable";
import { useLongPress } from "@/hooks/use-long-press";
+import { RemoteContentImage } from "@/components/remote-image/remote-image";
const MENTION_ALLOWED_TAGS = { mention: ["data-agent-id"] };
const MENTION_LITERAL_TAGS = ["mention"];
@@ -233,14 +234,17 @@ function ImageAttachmentCards({
? getArtifactThumbnailUrl(a.id, workspaceId)
: undefined;
return thumbUrl ? (
- <button
+ <RemoteContentImage
key={a.id}
- type="button"
- onClick={(e) => { e.stopPropagation(); onArtifactClick(a); }}
- className="max-w-48 overflow-hidden rounded-(--radius) border border-(--border) cursor-pointer [transition:translate_.2s_cubic-bezier(.2,.8,.2,1),box-shadow_.2s_ease] hover:-translate-y-0.5 [box-shadow:var(--e1)] hover:[box-shadow:var(--e2)]"
- >
- <img src={thumbUrl} alt={a.filename} loading="lazy" className="block w-full h-auto" />
- </button>
+ src={thumbUrl}
+ alt={a.filename}
+ loading="lazy"
+ onActivate={(event) => { event.stopPropagation(); onArtifactClick(a); }}
+ frameClassName="w-48 max-w-full rounded-(--radius) border border-(--border) [transition:translate_.2s_cubic-bezier(.2,.8,.2,1),box-shadow_.2s_ease] hover:-translate-y-0.5 hover:[box-shadow:var(--e2)] [box-shadow:var(--e1)]"
+ frameStyle={{ aspectRatio: "8/5" }}
+ imageClassName="object-contain"
+ errorLabel="Preview failed to load"
+ />
) : (
<button
key={a.id}
diff --git a/src/web/src/components/artifact-content-renderer.tsx b/src/web/src/components/artifact-content-renderer.tsx
index 84c0c9320..05ff3e05a 100644
--- a/src/web/src/components/artifact-content-renderer.tsx
+++ b/src/web/src/components/artifact-content-renderer.tsx
@@ -6,6 +6,7 @@ import type { Artifact } from "@alook/shared";
import { Loader2, Download } from "lucide-react";
import { Streamdown } from "streamdown";
import { mermaid, cjk } from "@/lib/streamdown-plugins";
+import { RemoteContentImage } from "@/components/remote-image/remote-image";
const TEXT_TYPES = new Set([
"application/json",
@@ -100,10 +101,15 @@ export function ArtifactContentRenderer({ artifact, workspaceId }: ArtifactConte
if (isImageType(artifact.content_type)) {
return (
<div className="flex justify-center">
- <img
+ <RemoteContentImage
src={url}
alt={artifact.filename}
- className="max-w-full rounded-md"
+ loading="eager"
+ loadingLabel="Loading image"
+ frameClassName="w-full max-w-3xl rounded-md"
+ frameStyle={{ aspectRatio: "4/3" }}
+ imageClassName="rounded-md object-contain"
+ errorLabel="Image preview failed to load"
/>
</div>
);
diff --git a/src/web/src/components/avatar/agent-avatar.test.ts b/src/web/src/components/avatar/agent-avatar.test.ts
index a4ba9c0da..b71e36531 100644
--- a/src/web/src/components/avatar/agent-avatar.test.ts
+++ b/src/web/src/components/avatar/agent-avatar.test.ts
@@ -2,30 +2,39 @@ import { describe, it, expect } from "vitest"
import { AgentAvatar } from "./agent-avatar"
import { GeneratedAvatar } from "./generated-avatar"
import { serializeBeamSeed } from "@/lib/avatar/seed-url"
+import { RemoteIdentityImage } from "@/components/remote-image/remote-image"
// A legacy procedural config value (the format the removed engine used to
// store) — the renderer must ignore it and fall back to an id-seeded beam.
const LEGACY_CONFIG = 'avatar:{"shape":"book","eye":"happy","nose":"dash","bg":1}'
-type ImgEl = { type: "img"; props: { src: string; alt: string; style: { width: number; height: number } } }
+type PhotoEl = {
+ type: "span"
+ props: {
+ className: string
+ style: { width: number; height: number }
+ children: { type: typeof RemoteIdentityImage; props: { src: string; alt: string } }
+ }
+}
type BeamEl = { type: typeof GeneratedAvatar; props: { seed: string; size: number } }
describe("AgentAvatar", () => {
- it("renders an <img> for a photo URL (https)", () => {
- const el = AgentAvatar({ name: "Bot", avatarUrl: "https://cdn.example.com/a.png", size: 40 }) as unknown as ImgEl
- expect(el.type).toBe("img")
- expect(el.props.src).toBe("https://cdn.example.com/a.png")
+ it("renders the shared identity state for a photo URL (https)", () => {
+ const el = AgentAvatar({ name: "Bot", avatarUrl: "https://cdn.example.com/a.png", size: 40 }) as unknown as PhotoEl
+ expect(el.type).toBe("span")
+ expect(el.props.children.type).toBe(RemoteIdentityImage)
+ expect(el.props.children.props.src).toBe("https://cdn.example.com/a.png")
expect(el.props.style).toEqual({ width: 40, height: 40 })
})
- it("renders an <img> for a routable leading-/ avatar URL (bot/user avatar routes)", () => {
+ it("renders the shared identity state for a routable leading-/ avatar URL", () => {
const el = AgentAvatar({
name: "Bot",
avatarUrl: "/api/community/bots/b1/avatar",
size: 24,
- }) as unknown as ImgEl
- expect(el.type).toBe("img")
- expect(el.props.src).toBe("/api/community/bots/b1/avatar")
+ }) as unknown as PhotoEl
+ expect(el.props.children.type).toBe(RemoteIdentityImage)
+ expect(el.props.children.props.src).toBe("/api/community/bots/b1/avatar")
})
it("renders beam with the stored seed for a avatar:beam value", () => {
@@ -60,7 +69,7 @@ describe("AgentAvatar", () => {
avatarUrl: "/api/avatar",
className: "rounded-xl",
alt: "",
- }) as unknown as ImgEl & { props: { className: string; alt: string } }
+ }) as unknown as PhotoEl
const generated = AgentAvatar({
name: "Bot",
seed: "bot-id",
@@ -68,7 +77,7 @@ describe("AgentAvatar", () => {
}) as unknown as BeamEl & { props: { className: string } }
expect(photo.props.className).toContain("rounded-xl")
expect(photo.props.className).not.toContain("rounded-full")
- expect(photo.props.alt).toBe("")
+ expect(photo.props.children.props.alt).toBe("")
expect(generated.props.className).toContain("rounded-xl")
expect(generated.props.className).not.toContain("rounded-full")
})
diff --git a/src/web/src/components/avatar/agent-avatar.tsx b/src/web/src/components/avatar/agent-avatar.tsx
index d78e4d9ce..5487d0fb3 100644
--- a/src/web/src/components/avatar/agent-avatar.tsx
+++ b/src/web/src/components/avatar/agent-avatar.tsx
@@ -3,6 +3,7 @@
import { GeneratedAvatar } from "./generated-avatar";
import { resolveAvatar } from "@/lib/avatar/resolve";
import { cn } from "@/lib/utils";
+import { RemoteIdentityImage } from "@/components/remote-image/remote-image";
interface AgentAvatarProps {
name?: string | null;
@@ -20,12 +21,20 @@ export function AgentAvatar({ name, avatarUrl, seed, size = 32, className, alt }
const avatarClassName = cn("shrink-0 rounded-full", className);
if (resolved.kind === "photo") {
return (
- <img
- src={resolved.url}
- alt={alt ?? name ?? ""}
- className={cn("object-cover", avatarClassName)}
+ <span
+ role={alt === "" ? undefined : "img"}
+ aria-label={alt === "" ? undefined : alt ?? name ?? undefined}
+ aria-hidden={alt === "" ? true : undefined}
+ className={cn("relative block overflow-hidden", avatarClassName)}
style={{ width: size, height: size }}
- />
+ >
+ <RemoteIdentityImage
+ src={resolved.url}
+ alt=""
+ className="rounded-[inherit]"
+ placeholderClassName="rounded-[inherit]"
+ />
+ </span>
);
}
return <GeneratedAvatar seed={resolved.seed} size={size} className={avatarClassName} />;
diff --git a/src/web/src/components/avatar/animated-avatar.tsx b/src/web/src/components/avatar/animated-avatar.tsx
index 620128162..bc5acaf0d 100644
--- a/src/web/src/components/avatar/animated-avatar.tsx
+++ b/src/web/src/components/avatar/animated-avatar.tsx
@@ -3,6 +3,8 @@
import { useEffect, useRef, useState } from "react";
import { GeneratedAvatar } from "./generated-avatar";
import { resolveAvatar } from "@/lib/avatar/resolve";
+import { RemoteIdentityImage } from "@/components/remote-image/remote-image";
+import { cn } from "@/lib/utils";
// beam is a static SVG with no animatable internal parts, so only the
// container-level animations survive the migration off the procedural
@@ -53,7 +55,18 @@ export function AnimatedAvatar({ seed, avatarUrl, size, className, isHovered, is
return (
<div className={animClass ?? undefined}>
{resolved.kind === "photo" ? (
- <img src={resolved.url} alt="" className={`object-cover align-middle ${className ?? ""}`} style={{ width: size, height: size }} />
+ <span
+ aria-hidden
+ className={cn("relative block overflow-hidden align-middle", className)}
+ style={{ width: size, height: size }}
+ >
+ <RemoteIdentityImage
+ src={resolved.url}
+ alt=""
+ className="rounded-[inherit]"
+ placeholderClassName="rounded-[inherit]"
+ />
+ </span>
) : (
<GeneratedAvatar seed={resolved.seed} size={size} className={className} />
)}
diff --git a/src/web/src/components/avatar/profile-avatar.error.test.ts b/src/web/src/components/avatar/profile-avatar.error.test.ts
index 0f9d22d60..71ac3071f 100644
--- a/src/web/src/components/avatar/profile-avatar.error.test.ts
+++ b/src/web/src/components/avatar/profile-avatar.error.test.ts
@@ -5,6 +5,16 @@ import { ProfileAvatar } from "./profile-avatar"
globalThis.IS_REACT_ACT_ENVIRONMENT = true
+function imageEvent() {
+ return {
+ currentTarget: {
+ naturalWidth: 40,
+ naturalHeight: 40,
+ decode: () => Promise.resolve(),
+ },
+ }
+}
+
describe("ProfileAvatar photo errors", () => {
let renderer: TestRenderer.ReactTestRenderer | undefined
@@ -101,7 +111,8 @@ describe("ProfileAvatar photo errors", () => {
const image = renderer!.root.findByProps({ "data-slot": "avatar-image" })
await act(async () => {
- image.props.onLoad()
+ image.props.onLoad(imageEvent())
+ await Promise.resolve()
})
expect(renderer!.root.findByProps({ "data-slot": "avatar-image" }).props).toMatchObject({
@@ -135,7 +146,10 @@ describe("ProfileAvatar photo errors", () => {
expect(placeholder.props["data-avatar-photo-placeholder"]).toBe("failed")
expect(placeholder.props.className).not.toContain("animate-pulse")
- await act(async () => image.props.onLoad())
+ await act(async () => {
+ image.props.onLoad(imageEvent())
+ await Promise.resolve()
+ })
expect(renderer!.root.findByProps({ "data-slot": "avatar-image" }).props).toMatchObject({
"data-avatar-photo-state": "failed",
})
diff --git a/src/web/src/components/avatar/profile-avatar.test.ts b/src/web/src/components/avatar/profile-avatar.test.ts
index 397b98d73..2989ed875 100644
--- a/src/web/src/components/avatar/profile-avatar.test.ts
+++ b/src/web/src/components/avatar/profile-avatar.test.ts
@@ -26,7 +26,7 @@ describe("ProfileAvatar", () => {
expect(html).toContain('data-testid="profile-avatar"')
expect(html).toContain('data-avatar-kind="photo"')
expect(html).toContain('data-slot="avatar-photo-placeholder" data-avatar-photo-placeholder="pending"')
- expect(html).toContain("size-full rounded-full bg-muted animate-pulse motion-reduce:animate-none")
+ expect(html).toContain("absolute inset-0 bg-muted animate-pulse motion-reduce:animate-none rounded-full")
expect(html).not.toContain('data-slot="avatar-fallback"')
expect(html).not.toContain(">A</span>")
expect(html).toContain('data-slot="avatar-image" data-avatar-photo-state="pending"')
diff --git a/src/web/src/components/avatar/profile-avatar.tsx b/src/web/src/components/avatar/profile-avatar.tsx
index f9ba0dda4..8070a99dd 100644
--- a/src/web/src/components/avatar/profile-avatar.tsx
+++ b/src/web/src/components/avatar/profile-avatar.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useCallback, useEffect, useState, type ReactNode } from "react"
+import { type ReactNode } from "react"
import {
Avatar as UiAvatar,
AvatarFallback,
@@ -8,10 +8,9 @@ import {
import { resolveAvatar } from "@/lib/avatar/resolve"
import { avatarInitial } from "@/lib/community/avatar"
import { cn } from "@/lib/utils"
+import { RemoteIdentityImage } from "@/components/remote-image/remote-image"
import { GeneratedAvatar } from "./generated-avatar"
-const PROFILE_PHOTO_READY_TIMEOUT_MS = 5_000
-
export type ProfileAvatarProps = {
label: string
src?: string | null
@@ -24,53 +23,6 @@ export type ProfileAvatarProps = {
"data-testid"?: string
}
-function ProfilePhoto({ src, alt }: {
- src: string
- alt: string
-}) {
- const [status, setStatus] = useState<"pending" | "ready" | "failed">("pending")
- const settleStatus = useCallback((next: "ready" | "failed") => {
- setStatus((current) => current === "pending" ? next : current)
- }, [])
- const reconcileCompletedPhoto = useCallback((image: HTMLImageElement | null) => {
- if (!image?.complete) return
- settleStatus(image.naturalWidth > 0 && image.naturalHeight > 0 ? "ready" : "failed")
- }, [settleStatus])
-
- useEffect(() => {
- if (status !== "pending") return
- const timeout = setTimeout(() => settleStatus("failed"), PROFILE_PHOTO_READY_TIMEOUT_MS)
- return () => clearTimeout(timeout)
- }, [settleStatus, status])
-
- return (
- <>
- <span
- data-slot="avatar-photo-placeholder"
- data-avatar-photo-placeholder={status === "ready" ? undefined : status}
- aria-hidden
- className={cn(
- "size-full rounded-full bg-muted",
- status === "pending" && "animate-pulse motion-reduce:animate-none",
- )}
- />
- <img
- ref={reconcileCompletedPhoto}
- data-slot="avatar-image"
- data-avatar-photo-state={status}
- src={src}
- alt={alt}
- className={cn(
- "absolute inset-0 aspect-square size-full rounded-full object-cover transition-opacity duration-150 ease-out motion-reduce:transition-none",
- status === "ready" ? "opacity-100" : "opacity-0",
- )}
- onLoad={() => settleStatus("ready")}
- onError={() => settleStatus("failed")}
- />
- </>
- )
-}
-
export function ProfileAvatar({
label,
src,
@@ -98,10 +50,12 @@ export function ProfileAvatar({
aria-hidden={decorative ? true : undefined}
>
{resolved.kind === "photo" ? (
- <ProfilePhoto
- key={resolved.url}
+ <RemoteIdentityImage
src={resolved.url}
alt={accessibleLabel}
+ className="aspect-square rounded-full"
+ placeholderClassName="rounded-full"
+ profilePhoto
/>
) : resolved.kind === "beam" ? (
<span className="size-full overflow-hidden rounded-full">
diff --git a/src/web/src/components/community/channels/channel-header.tsx b/src/web/src/components/community/channels/channel-header.tsx
index 7c1a331ec..d1359f86d 100644
--- a/src/web/src/components/community/channels/channel-header.tsx
+++ b/src/web/src/components/community/channels/channel-header.tsx
@@ -14,7 +14,7 @@ import { Skeleton } from "@/components/ui/skeleton"
import { EntityIcon } from "../entity-icon"
import { SlugHint } from "../settings/slug-hint"
import { previewSlug } from "@/lib/community/slug-preview"
-import { SeededBackdrop } from "@/components/avatar"
+import { ServerIcon } from "@/components/community/server-icon"
import type { RightPanel } from "@/components/community/shell/panel-types"
import type { EntityKind } from "@/lib/community/models/navigation"
import { CreateDialogShell } from "../settings/create-dialog-shell"
@@ -209,13 +209,16 @@ function ServerCrumb({ id, name, icon, size = 5, className = "" }: { id: string;
const iconTextCls = size === 7 ? "text-xs" : size === 6 ? "text-[0.6875rem]" : "text-[0.625rem]"
const initialTextCls = size === 7 ? "text-base" : size === 6 ? "text-sm" : "text-xs"
return (
- <span
+ <ServerIcon
+ id={id}
+ name={name}
+ initial={avatarInitial(name)}
+ icon={icon}
+ size={size * 4}
+ fontSize={size === 7 ? 16 : size === 6 ? 14 : 12}
className={`relative grid shrink-0 place-items-center overflow-hidden rounded-md ${icon ? `font-semibold ${iconTextCls} bg-secondary text-foreground` : `font-brand font-bold ${initialTextCls} text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)]`} ${sizeCls} ${className}`}
- aria-label={name}
title={name}
- >
- {icon ? <img src={icon} alt="" className="size-full object-cover" /> : <><SeededBackdrop seed={id} /><span className="relative -translate-x-px [-webkit-text-stroke:0.5px_currentColor]">{avatarInitial(name)}</span></>}
- </span>
+ />
)
}
diff --git a/src/web/src/components/community/messages/attachment-layout.ts b/src/web/src/components/community/messages/attachment-layout.ts
index e674bfab1..c0ab3da1a 100644
--- a/src/web/src/components/community/messages/attachment-layout.ts
+++ b/src/web/src/components/community/messages/attachment-layout.ts
@@ -8,8 +8,10 @@ export function attachmentAspectRatio(
export function attachmentImageFrameStyle(
width: number | undefined,
height: number | undefined,
-): { width: string; aspectRatio: string } | undefined {
- if (!width || !height || width <= 0 || height <= 0) return undefined
+): { width: string; aspectRatio: string } {
+ if (!width || !height || width <= 0 || height <= 0) {
+ return { width: "min(100%, 300px)", aspectRatio: "4/3" }
+ }
const constrainedWidth = Math.min(width, 300 * width / height)
const roundedWidth = Math.round(constrainedWidth * 1000) / 1000
return {
diff --git a/src/web/src/components/community/messages/image-lightbox.test.ts b/src/web/src/components/community/messages/image-lightbox.test.ts
index 7c46693af..1af459618 100644
--- a/src/web/src/components/community/messages/image-lightbox.test.ts
+++ b/src/web/src/components/community/messages/image-lightbox.test.ts
@@ -53,10 +53,13 @@ describe("ImageLightbox", () => {
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")
+ expect(frame.parent?.props.className).not.toContain("invisible")
+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxLoading }).children)
+ .toEqual(["Loading original image"])
await loadThumbnail(renderer, 800, 450)
- expect(renderer.root.findByProps({ "data-testid": tid.imageLightbox }).parent?.props.className).toContain("visible")
+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightbox }).parent?.props.className)
+ .not.toContain("invisible")
act(() => original.props.onLoad(imageEvent(800, 450, () => decodePromise)))
expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-0")
@@ -102,7 +105,7 @@ describe("ImageLightbox", () => {
expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-100")
})
- it("commits legacy natural dimensions with the decoded reveal", async () => {
+ it("keeps the safe legacy frame until the decoded original commits once", async () => {
let resolveDecode!: () => void
const decodePromise = new Promise<void>((resolve) => { resolveDecode = resolve })
const { renderer } = renderLightbox({
@@ -114,12 +117,12 @@ describe("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" })
+ expect(frame().props.style).toEqual({ width: "min(200px, 90vw, 85vh)", aspectRatio: "1 / 1" })
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(frame().props.style).toEqual({ width: "min(200px, 90vw, 85vh)", aspectRatio: "1 / 1" })
expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxOriginal }).props.className).toContain("opacity-0")
await act(async () => {
@@ -193,7 +196,22 @@ describe("ImageLightbox", () => {
})
})
- it("keeps a cold preview hidden until the thumbnail decodes, then paints it before an already-decoded original", async () => {
+ it("turns a stalled eager original into a static retryable error", async () => {
+ vi.useFakeTimers()
+ const { renderer } = renderLightbox({ originalUrl: "/stalled", name: "stalled" })
+ const loading = renderer.root.findByProps({ "data-testid": tid.imageLightboxLoading })
+ expect(loading.props.className).toContain("motion-reduce:animate-none")
+
+ await act(async () => vi.advanceTimersByTime(5_000))
+
+ expect(renderer.root.findAllByProps({ "data-testid": tid.imageLightboxLoading })).toHaveLength(0)
+ const error = renderer.root.findByProps({ "data-testid": tid.imageLightboxError })
+ expect(error.findByType("span").children).toEqual(["Failed to load original image"])
+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxRetry }).props.className).toContain("min-w-12")
+ vi.useRealTimers()
+ })
+
+ it("shows a cold pending frame, then paints the thumbnail before an already-decoded original", async () => {
let runAnimationFrame: FrameRequestCallback | undefined
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
runAnimationFrame = callback
@@ -212,7 +230,8 @@ describe("ImageLightbox", () => {
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")
+ expect(frame().parent?.props.className).not.toContain("invisible")
+ expect(renderer.root.findByProps({ "data-testid": tid.imageLightboxLoading })).toBeDefined()
await act(async () => {
original.props.onLoad(imageEvent(1200, 630, () => Promise.resolve()))
await Promise.resolve()
@@ -220,7 +239,7 @@ describe("ImageLightbox", () => {
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(frame().parent?.props.className).not.toContain("invisible")
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")
diff --git a/src/web/src/components/community/messages/image-lightbox.tsx b/src/web/src/components/community/messages/image-lightbox.tsx
index d5a917cde..6eb65ffd0 100644
--- a/src/web/src/components/community/messages/image-lightbox.tsx
+++ b/src/web/src/components/community/messages/image-lightbox.tsx
@@ -9,104 +9,56 @@ import {
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
-}
+import { useRemoteImageAttempt } from "@/components/remote-image/remote-image-attempt"
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 [dimensions, setDimensions] = useState<ImageDimensions | undefined>(knownDimensions)
+ const [revealedAttempt, setRevealedAttempt] = useState<number | null>(null)
+ const [
+ thumbnailStatus,
+ thumbnailAttempt,
+ ,
+ thumbnailRef,
+ onThumbnailLoad,
+ onThumbnailError,
+ ] = useRemoteImageAttempt({ eligible: !!image.thumbnailUrl })
+ const [
+ originalStatus,
+ originalAttempt,
+ originalImage,
+ originalRef,
+ onOriginalLoad,
+ onOriginalError,
+ retryOriginal,
+ ] = useRemoteImageAttempt()
- const frameStyle = previewFrameStyle(state.dimensions)
- const originalReady = state.originalStatus === "ready"
- const thumbnailReady = state.thumbnailStatus === "ready"
- const previewVisible = state.thumbnailStatus !== "loading"
+ const frameStyle = previewFrameStyle(dimensions)
+ const thumbnailReady = !!image.thumbnailUrl && thumbnailStatus === "ready"
+ const thumbnailSettled = !image.thumbnailUrl || thumbnailStatus !== "pending"
+ const originalReady = originalStatus === "ready" && revealedAttempt === originalAttempt
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
+ if (originalStatus !== "ready" || !originalImage || !thumbnailSettled) return
+ const requestKey = originalAttempt
+ const naturalDimensions = validImageDimensions(originalImage.naturalWidth, originalImage.naturalHeight)
+ const reveal = () => {
+ setDimensions(knownDimensions ?? naturalDimensions)
+ setRevealedAttempt(requestKey)
}
-
- 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)
+ if (typeof requestAnimationFrame !== "function") {
+ reveal()
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,
- }))
- }
+ const frameId = requestAnimationFrame(reveal)
+ return () => cancelAnimationFrame(frameId)
+ }, [knownDimensions, originalAttempt, originalImage, originalStatus, thumbnailSettled])
return (
- <div className={`relative w-fit ${previewVisible ? "visible" : "invisible"}`}>
+ <div className="relative w-fit">
<div
data-testid={tid.imageLightbox}
className="relative overflow-hidden rounded-lg bg-background"
@@ -114,36 +66,43 @@ function PreviewFrame({ image }: { image: ImagePreview }) {
>
{image.thumbnailUrl && (
<img
+ key={`thumbnail-${thumbnailAttempt}`}
+ ref={thumbnailRef}
data-testid={tid.imageLightboxThumbnail}
+ data-remote-image-kind="content"
+ data-remote-image-state={thumbnailStatus}
src={image.thumbnailUrl}
alt={image.name}
- onLoad={(event) => { void settleThumbnail(event.currentTarget) }}
- onError={failThumbnail}
+ onLoad={onThumbnailLoad}
+ onError={onThumbnailError}
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 && (
+ {!thumbnailReady && !originalReady && originalStatus === "pending" && (
<div
data-testid={tid.imageLightboxLoading}
role="status"
- className="absolute inset-0 flex items-center justify-center px-4 text-sm text-muted-foreground"
+ className="absolute inset-0 flex animate-pulse items-center justify-center bg-muted/70 px-4 text-sm text-muted-foreground motion-reduce:animate-none"
>
Loading original image
</div>
)}
- {state.originalStatus !== "failed" && (
+ {originalStatus !== "error" && (
<img
- key={state.requestKey}
+ key={`original-${originalAttempt}`}
+ ref={originalRef}
data-testid={tid.imageLightboxOriginal}
+ data-remote-image-kind="content"
+ data-remote-image-state={originalStatus}
src={image.originalUrl}
alt={image.name}
- onLoad={(event) => { void revealDecodedOriginal(event.currentTarget, state.requestKey) }}
- onError={() => failOriginal(state.requestKey)}
+ onLoad={onOriginalLoad}
+ onError={onOriginalError}
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" && (
+ {originalStatus === "error" && (
<div
data-testid={tid.imageLightboxError}
role="status"
diff --git a/src/web/src/components/community/messages/message-body.test.ts b/src/web/src/components/community/messages/message-body.test.ts
index 4578aa3f9..18128916f 100644
--- a/src/web/src/components/community/messages/message-body.test.ts
+++ b/src/web/src/components/community/messages/message-body.test.ts
@@ -63,7 +63,7 @@ describe("MessageBody — theme contrast", () => {
})
describe("MessageBody — remote image geometry", () => {
- it("keeps Streamdown's native image wrapper and download control", () => {
+ it("keeps Streamdown's native image wrapper and download control", async () => {
let renderer: TestRenderer.ReactTestRenderer
act(() => {
renderer = TestRenderer.create(
@@ -73,14 +73,21 @@ describe("MessageBody — remote image geometry", () => {
expect(renderer!.root.findAllByProps({ "data-streamdown": "image-wrapper" })).toHaveLength(1)
const image = renderer!.root.findByProps({ "data-streamdown": "image" })
- act(() => image.props.onLoad({}))
+ await act(async () => image.props.onLoad({
+ currentTarget: {
+ decode: () => Promise.resolve(),
+ naturalWidth: 800,
+ naturalHeight: 450,
+ },
+ }))
expect(renderer!.root.findByProps({ title: "Download image" }).type).toBe("button")
})
it("caps community Markdown images at 300px without distorting their ratio", () => {
const css = readFileSync(resolve(componentDirectory, "../../../app/globals.css"), "utf8")
expect(css).toContain('[data-community-message-body] [data-streamdown="image-wrapper"]')
- expect(css).toMatch(/\[data-community-message-body\] \[data-streamdown="image"\][^{]*\{[^}]*width: auto;[^}]*height: auto;[^}]*max-width: 100%;[^}]*max-height: 18\.75rem;[^}]*object-fit: contain;/s)
+ expect(css).toMatch(/\[data-community-message-body\] \[data-streamdown="image-wrapper"\][^{]*\{[^}]*max-width: 100%;/s)
+ expect(css).toMatch(/\[data-community-message-body\] \[data-streamdown="image"\][^{]*\{[^}]*width: 100%;[^}]*height: 100%;[^}]*max-width: 100%;[^}]*max-height: 100%;[^}]*object-fit: contain;/s)
})
})
diff --git a/src/web/src/components/community/messages/message-markdown.test.ts b/src/web/src/components/community/messages/message-markdown.test.ts
index 831019c86..97d7e3873 100644
--- a/src/web/src/components/community/messages/message-markdown.test.ts
+++ b/src/web/src/components/community/messages/message-markdown.test.ts
@@ -5,6 +5,7 @@ import {
buildMdComponents,
MD_COMPONENTS,
} from "./message-markdown"
+import { RemoteMarkdownImage } from "@/components/remote-image/remote-markdown-image"
// `components.mention(...)` returns a plain React element (JSX under the
// hood) — inspecting `.props` here reaches into the MentionPill it wraps
@@ -33,6 +34,11 @@ describe("mentionNameFromText", () => {
})
describe("buildMdComponents — mention pill onClick wiring", () => {
+ it("keeps the shared remote image adapter in static and callback component maps", () => {
+ expect(MD_COMPONENTS.img).toBe(RemoteMarkdownImage)
+ expect(buildMdComponents(vi.fn()).img).toBe(RemoteMarkdownImage)
+ })
+
it("wires onClick to call onOpenProfile with the name (no @, no #dddd) and no discriminator when the tag wasn't stashed", () => {
const onOpenProfile = vi.fn()
const components = buildMdComponents(onOpenProfile)
diff --git a/src/web/src/components/community/messages/message-markdown.tsx b/src/web/src/components/community/messages/message-markdown.tsx
index 8bc5db6ef..0fd16bee4 100644
--- a/src/web/src/components/community/messages/message-markdown.tsx
+++ b/src/web/src/components/community/messages/message-markdown.tsx
@@ -3,6 +3,7 @@ import { Spoiler, MentionPill } from "./inline-marks"
import { ChannelRefPill } from "./channel-ref-pill"
import { ServerRefPill } from "./server-ref-pill"
import { PlatformLinkBadge } from "./platform-link-badge"
+import { RemoteMarkdownImage } from "@/components/remote-image/remote-markdown-image"
// Match `/c/invite/<token>` — with or without an origin.
// - token allows [A-Za-z0-9_-] (nanoid alphabet) and length 6..64 (short + old
@@ -65,6 +66,7 @@ export function mentionNameFromText(text: string): string {
export const MD_COMPONENTS = {
a: PlatformLinkBadge,
+ img: RemoteMarkdownImage,
spoiler: ({ children }: { children?: React.ReactNode }) => <Spoiler>{children}</Spoiler>,
mention: ({ children, ...rest }: Record<string, unknown> & { children?: React.ReactNode }) => (
<MentionPill everyone={rest["data-everyone"] === "1"}>{children}</MentionPill>
diff --git a/src/web/src/components/community/messages/message-share-dialog.test.ts b/src/web/src/components/community/messages/message-share-dialog.test.ts
index 7001fea80..c895c6cb0 100644
--- a/src/web/src/components/community/messages/message-share-dialog.test.ts
+++ b/src/web/src/components/community/messages/message-share-dialog.test.ts
@@ -235,7 +235,14 @@ describe("waitForShareCardImages", () => {
{
profilePhoto = false,
photoState = "pending",
- }: { profilePhoto?: boolean; photoState?: "pending" | "ready" | "failed" } = {},
+ remoteKind,
+ remoteState = "pending",
+ }: {
+ profilePhoto?: boolean
+ photoState?: "pending" | "ready" | "failed"
+ remoteKind?: "identity" | "content"
+ remoteState?: "pending" | "ready" | "error"
+ } = {},
) {
const listeners = new Map<string, () => void>()
const value = {
@@ -246,9 +253,12 @@ describe("waitForShareCardImages", () => {
addEventListener: vi.fn((type: string, listener: () => void) => listeners.set(type, listener)),
removeEventListener: vi.fn((type: string) => listeners.delete(type)),
hasAttribute: vi.fn((name: string) => profilePhoto && name === "data-avatar-photo-state"),
- getAttribute: vi.fn((name: string) => (
- profilePhoto && name === "data-avatar-photo-state" ? photoState : null
- )),
+ getAttribute: vi.fn((name: string) => {
+ if (profilePhoto && name === "data-avatar-photo-state") return photoState
+ if (name === "data-remote-image-kind") return remoteKind ?? null
+ if (name === "data-remote-image-state") return remoteKind ? remoteState : null
+ return null
+ }),
...overrides,
} as unknown as HTMLImageElement
return { value, listeners }
@@ -310,6 +320,41 @@ describe("waitForShareCardImages", () => {
expect(paint).toHaveBeenCalledOnce()
})
+ it("degrades a failed shared identity image without exposing substitute pixels", async () => {
+ const avatar = image({}, { remoteKind: "identity", remoteState: "error" })
+ const paint = vi.fn().mockResolvedValue(undefined)
+
+ await expect(waitForShareCardImages(card([avatar.value]), paint)).resolves.toEqual([
+ { image: avatar.value, mode: "fallback" },
+ ])
+ expect(avatar.value.addEventListener).not.toHaveBeenCalled()
+ expect(paint).toHaveBeenCalledOnce()
+ })
+
+ it("rejects a failed shared content image before rasterization", async () => {
+ const attachment = image({}, { remoteKind: "content", remoteState: "error" })
+ const paint = vi.fn().mockResolvedValue(undefined)
+
+ await expect(waitForShareCardImages(card([attachment.value]), paint))
+ .rejects.toBeInstanceOf(ShareImageSnapshotError)
+ expect(attachment.value.addEventListener).not.toHaveBeenCalled()
+ expect(paint).not.toHaveBeenCalled()
+ })
+
+ it("rejects native pixels that remain pending in the shared content lifecycle", async () => {
+ const attachment = image({
+ complete: true,
+ naturalWidth: 96,
+ naturalHeight: 64,
+ }, { remoteKind: "content", remoteState: "pending" })
+ const paint = vi.fn().mockResolvedValue(undefined)
+
+ await expect(waitForShareCardImages(card([attachment.value]), paint))
+ .rejects.toBeInstanceOf(ShareImageSnapshotError)
+ expect(attachment.value.decode).toHaveBeenCalledOnce()
+ expect(paint).toHaveBeenCalledOnce()
+ })
+
it("decodes an already-loaded cached avatar without waiting for another event", async () => {
const avatar = image({ complete: true, naturalWidth: 40, naturalHeight: 40 })
const paint = vi.fn().mockResolvedValue(undefined)
diff --git a/src/web/src/components/community/messages/message-share-dialog.tsx b/src/web/src/components/community/messages/message-share-dialog.tsx
index f6a69068d..bcea7c6d8 100644
--- a/src/web/src/components/community/messages/message-share-dialog.tsx
+++ b/src/web/src/components/community/messages/message-share-dialog.tsx
@@ -62,10 +62,32 @@ function createShareCardAbortError(): DOMException {
function isProfilePhoto(image: HTMLImageElement): boolean {
return image.hasAttribute("data-avatar-photo-state")
+ || image.getAttribute("data-remote-image-kind") === "identity"
}
function isFailedProfilePhoto(image: HTMLImageElement): boolean {
return image.getAttribute("data-avatar-photo-state") === "failed"
+ || (
+ image.getAttribute("data-remote-image-kind") === "identity"
+ && image.getAttribute("data-remote-image-state") === "error"
+ )
+}
+
+function isFailedContentImage(image: HTMLImageElement): boolean {
+ return image.getAttribute("data-remote-image-kind") === "content"
+ && image.getAttribute("data-remote-image-state") === "error"
+}
+
+function isReadyProfilePhoto(image: HTMLImageElement): boolean {
+ if (image.getAttribute("data-remote-image-kind") === "identity") {
+ return image.getAttribute("data-remote-image-state") === "ready"
+ }
+ return image.getAttribute("data-avatar-photo-state") === "ready"
+}
+
+function isUnreadyContentImage(image: HTMLImageElement): boolean {
+ return image.getAttribute("data-remote-image-kind") === "content"
+ && image.getAttribute("data-remote-image-state") !== "ready"
}
async function waitForImageLoad(
@@ -79,6 +101,7 @@ async function waitForImageLoad(
}
if (signal?.aborted) throw createShareCardAbortError()
if (isFailedProfilePhoto(image)) return "fallback"
+ if (isFailedContentImage(image)) throw new ShareImageSnapshotError()
if (!image.complete) {
const result = await new Promise<"loaded" | "error" | "timeout" | "aborted">((resolve) => {
@@ -107,6 +130,7 @@ async function waitForImageLoad(
if (result === "error") return fallbackOrThrow(new ShareImageSnapshotError())
}
if (isFailedProfilePhoto(image)) return "fallback"
+ if (isFailedContentImage(image)) throw new ShareImageSnapshotError()
if (image.naturalWidth <= 0 || image.naturalHeight <= 0) {
return fallbackOrThrow(new ShareImageSnapshotError())
}
@@ -131,6 +155,7 @@ async function waitForImageLoad(
})
if (result === "aborted") throw createShareCardAbortError()
if (isFailedProfilePhoto(image)) return "fallback"
+ if (isFailedContentImage(image)) throw new ShareImageSnapshotError()
if (result !== "decoded" && isProfilePhoto(image)) return "fallback"
}
return "snapshot"
@@ -157,7 +182,13 @@ export async function waitForShareCardImages(
if (signal?.aborted) throw createShareCardAbortError()
await waitForPaint()
if (signal?.aborted) throw createShareCardAbortError()
- return dispositions
+ return dispositions.map((disposition) => {
+ if (isProfilePhoto(disposition.image) && !isReadyProfilePhoto(disposition.image)) {
+ return { ...disposition, mode: "fallback" }
+ }
+ if (isUnreadyContentImage(disposition.image)) throw new ShareImageSnapshotError()
+ return disposition
+ })
}
type ShareImageWaiter = (
diff --git a/src/web/src/components/community/messages/message.render.test.ts b/src/web/src/components/community/messages/message.render.test.ts
index 2f84166f6..d2ebe88ec 100644
--- a/src/web/src/components/community/messages/message.render.test.ts
+++ b/src/web/src/components/community/messages/message.render.test.ts
@@ -1284,9 +1284,10 @@ describe("Message image attachment layout", () => {
expect(image.props).toMatchObject({ width: 396, height: 702 })
expect(image.props.className).toContain("size-full")
expect(image.props.className).toContain("absolute")
- expect(image.parent?.props.className).toContain("relative")
- expect(image.parent?.props.className).toContain("max-w-full")
- expect(image.parent?.props.style).toEqual({
+ const frame = renderer!.root.findByProps({ "data-remote-image-frame": true })
+ expect(frame.props.className).toContain("relative")
+ expect(frame.props.className).toContain("max-w-full")
+ expect(frame.props.style).toEqual({
width: "min(100%, 169.231px)",
aspectRatio: "396/702",
})
diff --git a/src/web/src/components/community/messages/message.test.ts b/src/web/src/components/community/messages/message.test.ts
index 64c5cd90f..3f1c7ccc2 100644
--- a/src/web/src/components/community/messages/message.test.ts
+++ b/src/web/src/components/community/messages/message.test.ts
@@ -45,8 +45,14 @@ describe("attachmentImageFrameStyle", () => {
})
})
- it("keeps legacy incomplete dimensions on intrinsic fallback", () => {
- expect(attachmentImageFrameStyle(undefined, 80)).toBeUndefined()
- expect(attachmentImageFrameStyle(120, undefined)).toBeUndefined()
+ it("reserves a safe fixed frame for legacy incomplete dimensions", () => {
+ expect(attachmentImageFrameStyle(undefined, 80)).toEqual({
+ width: "min(100%, 300px)",
+ aspectRatio: "4/3",
+ })
+ expect(attachmentImageFrameStyle(120, undefined)).toEqual({
+ width: "min(100%, 300px)",
+ aspectRatio: "4/3",
+ })
})
})
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index fe966f9eb..8bf695ada 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -28,7 +28,7 @@ import { avatarInitial } from "@/lib/community/avatar"
import { stripInlineMarkup } from "@alook/shared"
import type { FileAttachment, ImagePreview, RenderMsg } from "@/lib/community/models/message"
import type { OpenProfile } from "@/components/community/social/profile-types"
-import { attachmentAspectRatio, attachmentImageFrameStyle } from "./attachment-layout"
+import { attachmentImageFrameStyle } from "./attachment-layout"
import { AttachmentCard } from "./attachment-card"
import { displayReplyContent } from "@/lib/community/reply-content"
import {
@@ -41,6 +41,7 @@ import {
import { useMobileAvatarMention } from "./use-mobile-avatar-mention"
import { useCommunityProfile } from "@/stores/community/ws"
import { MessageReactions } from "./message-reactions"
+import { RemoteContentImage, RemoteIdentityImage } from "@/components/remote-image/remote-image"
// Whether the "Share as Image" action is offered for a message. Share is
// computed inside `Message` from the message alone (no handler is threaded in),
@@ -693,32 +694,27 @@ function MessageImpl({
if (a.kind === "image") {
const frameStyle = attachmentImageFrameStyle(a.width, a.height)
return (
- <button
+ <RemoteContentImage
key={i}
- onClick={() => onPreviewImage?.({
+ data-testid={tid.messageImage(m.id, i)}
+ src={a.thumbnailUrl ?? a.url}
+ alt={a.name}
+ width={a.width}
+ height={a.height}
+ loading="lazy"
+ onActivate={() => onPreviewImage?.({
originalUrl: a.url,
thumbnailUrl: a.thumbnailUrl,
name: a.name,
width: a.width,
height: a.height,
})}
- className={`${frameStyle ? "relative" : "w-fit"} block max-w-full overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40`}
- style={frameStyle}
- >
- <img
- data-testid={tid.messageImage(m.id, i)}
- src={a.thumbnailUrl ?? a.url}
- alt={a.name}
- width={a.width}
- height={a.height}
- className={frameStyle
- ? "absolute inset-0 block size-full rounded-lg object-contain"
- : "block h-auto w-auto max-h-75 max-w-full rounded-lg object-contain"}
- style={frameStyle ? undefined : { aspectRatio: attachmentAspectRatio(a.width, a.height) }}
- onLoad={onImageLoad}
- loading="lazy"
- />
- </button>
+ frameClassName="block max-w-full rounded-lg border border-border transition-colors hover:border-primary/40"
+ frameStyle={frameStyle}
+ imageClassName="block rounded-lg object-contain"
+ errorLabel="Attachment failed to load"
+ onReady={onImageLoad ? () => onImageLoad() : undefined}
+ />
)
}
return <AttachmentCard key={i} attachment={a} onPreview={onPreviewAttachment} />
@@ -743,7 +739,14 @@ function MessageImpl({
{embed.author && (
<div className="mb-2 flex items-center gap-2">
{embed.author.iconUrl ? (
- <img src={embed.author.iconUrl} alt="" className="size-5 rounded-full" />
+ <span className="relative block size-5 overflow-hidden rounded-full" aria-hidden>
+ <RemoteIdentityImage
+ src={embed.author.iconUrl}
+ alt=""
+ className="rounded-full"
+ placeholderClassName="rounded-full"
+ />
+ </span>
) : (
<span className="grid size-5 place-items-center rounded-full bg-muted text-[9px] font-semibold text-muted-foreground">{avatarInitial(embed.author.name)}</span>
)}
@@ -774,19 +777,46 @@ function MessageImpl({
)}
{embed.image && (
- <img src={embed.image.url} alt="" width={embed.image.width} height={embed.image.height} className="mt-2 w-full max-w-100 rounded-sm object-cover" style={{ aspectRatio: embed.image.width && embed.image.height ? `${embed.image.width}/${embed.image.height}` : "40/21" }} onLoad={onImageLoad} />
+ <RemoteContentImage
+ src={embed.image.url}
+ alt="Embed image"
+ width={embed.image.width}
+ height={embed.image.height}
+ loading="lazy"
+ frameClassName="mt-2 w-full max-w-100 rounded-sm"
+ frameStyle={{ aspectRatio: embed.image.width && embed.image.height ? `${embed.image.width}/${embed.image.height}` : "40/21" }}
+ imageClassName="rounded-sm object-cover"
+ errorLabel="Embed image failed to load"
+ onReady={onImageLoad ? () => onImageLoad() : undefined}
+ />
)}
{embed.footer && (
<div className="mt-2 flex items-center gap-2 text-[11px] text-muted-foreground">
- {embed.footer.iconUrl && <img src={embed.footer.iconUrl} alt="" className="size-4 rounded-full" />}
+ {embed.footer.iconUrl && (
+ <span className="relative block size-4 overflow-hidden rounded-full" aria-hidden>
+ <RemoteIdentityImage
+ src={embed.footer.iconUrl}
+ alt=""
+ className="rounded-full"
+ placeholderClassName="rounded-full"
+ />
+ </span>
+ )}
<span>{embed.footer.text}</span>
</div>
)}
</div>
{embed.thumbnail && (
- <img src={embed.thumbnail.url} alt="" className="ml-3 size-16 shrink-0 rounded-md object-cover" />
+ <RemoteContentImage
+ src={embed.thumbnail.url}
+ alt="Embed thumbnail"
+ loading="lazy"
+ frameClassName="ml-3 size-16 shrink-0 rounded-md"
+ imageClassName="rounded-md object-cover"
+ errorLabel="Thumbnail failed to load"
+ />
)}
</article>
))}
diff --git a/src/web/src/components/community/messages/thread-opener.test.ts b/src/web/src/components/community/messages/thread-opener.test.ts
index 724d412ac..8139a1b68 100644
--- a/src/web/src/components/community/messages/thread-opener.test.ts
+++ b/src/web/src/components/community/messages/thread-opener.test.ts
@@ -138,9 +138,10 @@ describe("ThreadOpener image attachment layout", () => {
expect(image.props).toMatchObject({ width: 396, height: 702 })
expect(image.props.className).toContain("size-full")
expect(image.props.className).toContain("absolute")
- expect(image.parent?.props.className).toContain("relative")
- expect(image.parent?.props.className).toContain("max-w-full")
- expect(image.parent?.props.style).toEqual({
+ const frame = renderer!.root.findByProps({ "data-remote-image-frame": true })
+ expect(frame.props.className).toContain("relative")
+ expect(frame.props.className).toContain("max-w-full")
+ expect(frame.props.style).toEqual({
width: "min(100%, 169.231px)",
aspectRatio: "396/702",
})
diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsx
index 2db11e2fb..f05b00521 100644
--- a/src/web/src/components/community/messages/thread-opener.tsx
+++ b/src/web/src/components/community/messages/thread-opener.tsx
@@ -3,7 +3,7 @@
import { MessagesSquare, ArrowUpRight } from "lucide-react"
import { Avatar } from "../avatar"
import { MessageBody } from "./message-body"
-import { attachmentAspectRatio, attachmentImageFrameStyle } from "./attachment-layout"
+import { attachmentImageFrameStyle } from "./attachment-layout"
import { formatMessageTime } from "@/lib/community/format-time"
import { Skeleton } from "@/components/ui/skeleton"
import { avatarInitial } from "@/lib/community/avatar"
@@ -17,6 +17,7 @@ import { useMobileAvatarMention } from "./use-mobile-avatar-mention"
import { useCommunityProfile } from "@/stores/community/ws"
import { useHoverCapable } from "@/hooks/use-hover-capable"
import { MessageReactions } from "./message-reactions"
+import { RemoteContentImage } from "@/components/remote-image/remote-image"
// Thread opener — the parent message the thread was created from, pinned at
// the top of the thread's message list. Deliberately styled like a REGULAR
@@ -157,31 +158,26 @@ export function ThreadOpener({
if (a.kind === "image") {
const frameStyle = attachmentImageFrameStyle(a.width, a.height)
return (
- <button
+ <RemoteContentImage
key={i}
- onClick={() => onPreviewImage?.({
+ data-testid={tid.threadOpenerImage(i)}
+ src={a.thumbnailUrl ?? a.url}
+ alt={a.name}
+ width={a.width}
+ height={a.height}
+ loading="lazy"
+ onActivate={() => onPreviewImage?.({
originalUrl: a.url,
thumbnailUrl: a.thumbnailUrl,
name: a.name,
width: a.width,
height: a.height,
})}
- className={`${frameStyle ? "relative" : "w-fit"} block max-w-full overflow-hidden rounded-lg border border-border transition-colors hover:border-primary/40`}
- style={frameStyle}
- >
- <img
- data-testid={tid.threadOpenerImage(i)}
- src={a.thumbnailUrl ?? a.url}
- alt={a.name}
- width={a.width}
- height={a.height}
- className={frameStyle
- ? "absolute inset-0 block size-full rounded-lg object-contain"
- : "block h-auto w-auto max-h-75 max-w-full rounded-lg object-contain"}
- style={frameStyle ? undefined : { aspectRatio: attachmentAspectRatio(a.width, a.height) }}
- loading="lazy"
- />
- </button>
+ frameClassName="block max-w-full rounded-lg border border-border transition-colors hover:border-primary/40"
+ frameStyle={frameStyle}
+ imageClassName="block rounded-lg object-contain"
+ errorLabel="Attachment failed to load"
+ />
)
}
return <AttachmentCard key={i} attachment={a} onPreview={onPreviewAttachment} />
diff --git a/src/web/src/components/community/server-icon.test.ts b/src/web/src/components/community/server-icon.test.ts
index 9a98b1930..faee4d8fe 100644
--- a/src/web/src/components/community/server-icon.test.ts
+++ b/src/web/src/components/community/server-icon.test.ts
@@ -28,6 +28,17 @@ describe("ServerIcon seeded fallback", () => {
expect(svg(render("Alook"))).toBe(svg(render("Renamed")))
})
+ it("allows compact canonical callers to preserve their prior initial size", () => {
+ const html = renderToStaticMarkup(createElement(ServerIcon, {
+ id: "server-id",
+ name: "Alook",
+ initial: "A",
+ size: 10,
+ fontSize: 7,
+ }))
+ expect(html).toContain("width:10px;height:10px;font-size:7px")
+ })
+
it("leaves uploaded icons untouched", () => {
const html = renderToStaticMarkup(createElement(ServerIcon, {
id: "server-id",
@@ -35,7 +46,9 @@ describe("ServerIcon seeded fallback", () => {
initial: "A",
icon: "/icon.png",
}))
- expect(html).toContain('<img src="/icon.png" alt="Alook"')
+ expect(html).toContain('role="img" aria-label="Alook"')
+ expect(html).toContain('data-remote-image-kind="identity"')
+ expect(html).toContain('src="/icon.png" alt=""')
expect(html).not.toContain("<svg")
})
})
diff --git a/src/web/src/components/community/server-icon.tsx b/src/web/src/components/community/server-icon.tsx
index fe42a9f98..2fdb87541 100644
--- a/src/web/src/components/community/server-icon.tsx
+++ b/src/web/src/components/community/server-icon.tsx
@@ -1,4 +1,5 @@
import { SeededBackdrop } from "@/components/avatar"
+import { RemoteIdentityImage } from "@/components/remote-image/remote-image"
import { cn } from "@/lib/utils"
// The one server icon/avatar. A custom uploaded `icon` shows as a cropped
@@ -16,14 +17,20 @@ export function ServerIcon({
initial,
icon,
size = 40,
+ fontSize,
className,
+ title,
+ "data-rail-drag-preview": railDragPreview,
}: {
id: string
name: string
initial: string
icon?: string | null
size?: number
+ fontSize?: number
className?: string
+ title?: string
+ "data-rail-drag-preview"?: boolean | ""
}) {
return (
<div
@@ -32,10 +39,19 @@ export function ServerIcon({
icon ? "bg-secondary text-foreground" : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)]",
className,
)}
- style={{ width: size, height: size, fontSize: Math.round(size * 0.5) }}
+ style={{ width: size, height: size, fontSize: fontSize ?? Math.round(size * 0.5) }}
+ role="img"
+ aria-label={name}
+ title={title}
+ data-rail-drag-preview={railDragPreview}
>
{icon ? (
- <img src={icon} alt={name} className="size-full object-cover" />
+ <RemoteIdentityImage
+ src={icon}
+ alt=""
+ className="rounded-[inherit]"
+ placeholderClassName="rounded-[inherit]"
+ />
) : (
<>
<SeededBackdrop seed={id} />
diff --git a/src/web/src/components/community/shell/rail-folder.tsx b/src/web/src/components/community/shell/rail-folder.tsx
index 357d35ebc..b195c5cef 100644
--- a/src/web/src/components/community/shell/rail-folder.tsx
+++ b/src/web/src/components/community/shell/rail-folder.tsx
@@ -4,7 +4,7 @@ import { memo, useEffect, useRef } from "react"
import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem } from "@/components/ui/context-menu"
import { RailIndicator } from "./rail-indicator"
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"
-import { SeededBackdrop } from "@/components/avatar"
+import { ServerIcon } from "@/components/community/server-icon"
import { tid } from "@/lib/community/testids"
import type { FolderServer } from "@/lib/community/models/navigation"
import type { RailEntity, RailOperation } from "@/lib/community/server-rail-model"
@@ -81,15 +81,19 @@ function RailFolderImpl({
{Array.from({ length: 4 }).map((_, i) => {
const s = folderServers[i]
return s ? (
- <span
+ <ServerIcon
key={s.id}
+ id={s.id}
+ name={s.name}
+ initial={s.initial}
+ icon={s.icon}
+ size={10}
+ fontSize={7}
className={[
"relative grid aspect-square place-items-center overflow-hidden rounded-sm text-[7px] font-semibold",
s.icon ? "bg-card text-muted-foreground" : "text-white [text-shadow:0_1px_1px_rgb(0_0_0/0.35)]",
].join(" ")}
- >
- {s.icon ? <img src={s.icon} alt={s.name} className="size-full object-cover" /> : <><SeededBackdrop seed={s.id} /><span className="relative">{s.initial}</span></>}
- </span>
+ />
) : (
<span key={i} className="aspect-square rounded-sm bg-card/50" />
)
diff --git a/src/web/src/components/community/shell/sortable-server.tsx b/src/web/src/components/community/shell/sortable-server.tsx
index 0b9728ccf..affc41fc1 100644
--- a/src/web/src/components/community/shell/sortable-server.tsx
+++ b/src/web/src/components/community/shell/sortable-server.tsx
@@ -16,7 +16,7 @@ import {
} from "@/components/ui/tooltip";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { NumberTicker } from "@/components/ui/number-ticker";
-import { SeededBackdrop } from "@/components/avatar";
+import { ServerIcon } from "@/components/community/server-icon";
import { tid } from "@/lib/community/testids";
import type { Server } from "@/lib/community/models/navigation"
import type { RailEntity, RailOperation } from "@/lib/community/server-rail-model"
@@ -132,7 +132,14 @@ function SortableServerImpl({
active ? "cursor-default" : "cursor-pointer",
].join(" ")}
>
- <span data-rail-drag-preview className={[
+ <ServerIcon
+ data-rail-drag-preview
+ id={server.id}
+ name={server.name}
+ initial={server.initial}
+ icon={server.icon}
+ size={40}
+ className={[
"pointer-events-none relative grid size-10 place-items-center overflow-hidden font-brand text-xl font-bold transition-all duration-150",
active
? "cursor-default rounded-xl"
@@ -143,22 +150,7 @@ function SortableServerImpl({
: "bg-card group-hover/server:bg-primary group-hover/server:text-primary-foreground"
: "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)] group-hover/server:brightness-110",
].join(" ")}
- >
- {server.icon ? (
- <img
- src={server.icon}
- alt={server.name}
- className="size-full object-cover"
- />
- ) : (
- <>
- <SeededBackdrop seed={server.id} />
- <span className="relative -translate-x-0.5 [-webkit-text-stroke:0.5px_currentColor]">
- {server.initial}
- </span>
- </>
- )}
- </span>
+ />
</button>
{server.mentions > 0 && (
<span
diff --git a/src/web/src/components/remote-image/remote-image-attempt.ts b/src/web/src/components/remote-image/remote-image-attempt.ts
new file mode 100644
index 000000000..a93339c82
--- /dev/null
+++ b/src/web/src/components/remote-image/remote-image-attempt.ts
@@ -0,0 +1,126 @@
+"use client"
+
+import {
+ useCallback,
+ useEffect,
+ useReducer,
+ useState,
+ type RefCallback,
+ type SyntheticEvent,
+} from "react"
+
+export const REMOTE_IMAGE_TIMEOUT_MS = 5_000
+
+export type RemoteImageStatus = "pending" | "ready" | "error"
+
+type AttemptState = {
+ attempt: number
+ status: RemoteImageStatus
+ image?: HTMLImageElement
+}
+
+type AttemptAction =
+ | { type: "ready"; attempt: number; image: HTMLImageElement }
+ | { type: "error"; attempt: number }
+ | { type: "retry" }
+
+function reduceAttempt(state: AttemptState, action: AttemptAction): AttemptState {
+ if (action.type === "retry") {
+ return { attempt: state.attempt + 1, status: "pending" }
+ }
+ if (state.attempt !== action.attempt || state.status !== "pending") return state
+ return action.type === "ready"
+ ? { attempt: state.attempt, status: "ready", image: action.image }
+ : { attempt: state.attempt, status: "error" }
+}
+
+type RemoteImageAttemptOptions = {
+ eligible?: boolean
+ timeoutMs?: number
+}
+
+export function useRemoteImageAttempt({
+ eligible = true,
+ timeoutMs = REMOTE_IMAGE_TIMEOUT_MS,
+}: RemoteImageAttemptOptions = {}) {
+ const [state, dispatch] = useReducer(reduceAttempt, {
+ attempt: 0,
+ status: "pending",
+ })
+ const decode = useCallback(async (image: HTMLImageElement, attempt: number) => {
+ try {
+ await image.decode?.()
+ } catch {
+ dispatch({ type: "error", attempt })
+ return
+ }
+ if (image.naturalWidth <= 0 || image.naturalHeight <= 0) {
+ dispatch({ type: "error", attempt })
+ return
+ }
+ dispatch({ type: "ready", attempt, image })
+ }, [])
+
+ const imageRef = useCallback<RefCallback<HTMLImageElement>>((image) => {
+ if (!image?.complete) return
+ if (image.naturalWidth <= 0 || image.naturalHeight <= 0) {
+ dispatch({ type: "error", attempt: state.attempt })
+ return
+ }
+ void decode(image, state.attempt)
+ }, [decode, state.attempt])
+
+ const onLoad = useCallback((event: SyntheticEvent<HTMLImageElement>) => {
+ void decode(event.currentTarget, state.attempt)
+ }, [decode, state.attempt])
+
+ const onImageError = useCallback(() => {
+ dispatch({ type: "error", attempt: state.attempt })
+ }, [state.attempt])
+
+ const retry = useCallback(() => dispatch({ type: "retry" }), [])
+
+ useEffect(() => {
+ if (!eligible || state.status !== "pending") return
+ const attempt = state.attempt
+ const timeout = setTimeout(() => dispatch({ type: "error", attempt }), timeoutMs)
+ return () => clearTimeout(timeout)
+ }, [eligible, state.attempt, state.status, timeoutMs])
+
+ return [
+ state.status,
+ state.attempt,
+ state.image,
+ imageRef,
+ onLoad,
+ onImageError,
+ retry,
+ ] as const
+}
+
+export function useRemoteImageEligibility(lazy: boolean) {
+ const [element, setElement] = useState<HTMLElement | null>(null)
+ const [eligible, setEligible] = useState(!lazy)
+ const ref = useCallback((next: HTMLElement | null) => setElement(next), [])
+
+ useEffect(() => {
+ if (!lazy) {
+ setEligible(true)
+ return
+ }
+ if (!element || eligible) return
+ if (typeof IntersectionObserver === "undefined") {
+ setEligible(true)
+ return
+ }
+ const observer = new IntersectionObserver((entries) => {
+ if (!entries.some((entry) => entry.isIntersecting)) return
+ setEligible(true)
+ observer.disconnect()
+ }, { rootMargin: "300px" })
+ observer.observe(element)
+ return () => observer.disconnect()
+ }, [element, eligible, lazy])
+
+ return [eligible, ref] as const
+}
diff --git a/src/web/src/components/remote-image/remote-image.test.ts b/src/web/src/components/remote-image/remote-image.test.ts
new file mode 100644
index 000000000..79b950173
--- /dev/null
+++ b/src/web/src/components/remote-image/remote-image.test.ts
@@ -0,0 +1,239 @@
+import React from "react"
+
+import TestRenderer, { act } from "react-test-renderer"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { RemoteContentImage, RemoteIdentityImage } from "./remote-image"
+import { RemoteMarkdownImage } from "./remote-markdown-image"
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+function imageEvent(
+ decode: () => Promise<void> = () => Promise.resolve(),
+ naturalWidth = 320,
+ naturalHeight = 200,
+) {
+ return { currentTarget: { decode, naturalWidth, naturalHeight } }
+}
+
+function createNodeMock(element: React.ReactElement) {
+ if (element.type === "img") {
+ return { complete: false, naturalWidth: 0, naturalHeight: 0 }
+ }
+ if (element.props["data-remote-image-frame"] !== undefined) return {}
+ return null
+}
+
+describe("remote image state adapters", () => {
+ let renderer: TestRenderer.ReactTestRenderer | undefined
+
+ afterEach(async () => {
+ if (renderer) await act(async () => renderer?.unmount())
+ renderer = undefined
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ })
+
+ it("keeps an identity failure neutral and static", async () => {
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ "span",
+ { className: "relative block size-10" },
+ React.createElement(RemoteIdentityImage, {
+ src: "/avatar.png",
+ alt: "Ada",
+ placeholderClassName: "rounded-full",
+ }),
+ ),
+ )
+ })
+ const image = renderer!.root.findByProps({ "data-remote-image-kind": "identity" })
+ await act(async () => image.props.onError())
+
+ expect(renderer!.root.findByProps({ "data-remote-image-kind": "identity" }).props)
+ .toMatchObject({ src: "/avatar.png", "data-remote-image-state": "error" })
+ const placeholder = renderer!.root.findByProps({ "data-remote-image-placeholder": "identity" })
+ expect(placeholder.props["data-remote-image-state"]).toBe("error")
+ expect(placeholder.props["data-avatar-photo-placeholder"]).toBeUndefined()
+ expect(placeholder.props["data-slot"]).toBeUndefined()
+ expect(placeholder.props.className).not.toContain("animate-pulse")
+ expect(renderer!.root.findAll((node) => node.type === "svg")).toHaveLength(0)
+ })
+
+ it("retries content with the exact URL and fences callbacks from the old attempt", async () => {
+ let resolveOldDecode!: () => void
+ const oldDecode = new Promise<void>((resolve) => { resolveOldDecode = resolve })
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(RemoteContentImage, {
+ src: "https://cdn.example.com/photo.png?size=2",
+ alt: "Photo",
+ loading: "eager",
+ frameStyle: { width: 320, aspectRatio: "8/5" },
+ }),
+ { createNodeMock },
+ )
+ })
+ const oldImage = renderer!.root.findByProps({ "data-remote-image-kind": "content" })
+ const oldOnLoad = oldImage.props.onLoad
+ const oldOnError = oldImage.props.onError
+
+ act(() => oldOnLoad(imageEvent(() => oldDecode)))
+ await act(async () => oldOnError())
+ const retry = renderer!.root.findByType("button")
+ expect(retry.props.className).toContain("min-h-11")
+ expect(retry.props.className).toContain("min-w-11")
+
+ await act(async () => retry.props.onClick())
+ const retried = renderer!.root.findByProps({ "data-remote-image-kind": "content" })
+ expect(retried.props.src).toBe("https://cdn.example.com/photo.png?size=2")
+ expect(retried.props["data-remote-image-state"]).toBe("pending")
+
+ await act(async () => {
+ oldOnError()
+ resolveOldDecode()
+ await oldDecode
+ })
+ expect(renderer!.root.findByProps({ "data-remote-image-kind": "content" }).props["data-remote-image-state"])
+ .toBe("pending")
+
+ await act(async () => {
+ retried.props.onLoad(imageEvent())
+ await Promise.resolve()
+ })
+ expect(renderer!.root.findByProps({ "data-remote-image-kind": "content" }).props["data-remote-image-state"])
+ .toBe("ready")
+ })
+
+ it("does not start a lazy timeout until the frame becomes viewport-eligible", async () => {
+ vi.useFakeTimers()
+ let observe!: IntersectionObserverCallback
+ vi.stubGlobal("IntersectionObserver", class {
+ constructor(callback: IntersectionObserverCallback) {
+ observe = callback
+ }
+ observe() {}
+ disconnect() {}
+ unobserve() {}
+ takeRecords() { return [] }
+ readonly root = null
+ readonly rootMargin = "300px"
+ readonly thresholds = [0]
+ })
+
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(RemoteContentImage, {
+ src: "/below-the-fold.png",
+ alt: "Below the fold",
+ loading: "lazy",
+ timeoutMs: 100,
+ frameStyle: { width: 300, aspectRatio: "4/3" },
+ }),
+ { createNodeMock },
+ )
+ })
+ await act(async () => vi.advanceTimersByTime(500))
+ expect(renderer!.root.findByProps({ "data-remote-image-kind": "content" }).props["data-remote-image-state"])
+ .toBe("pending")
+
+ await act(async () => observe([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver))
+ await act(async () => vi.advanceTimersByTime(100))
+ expect(renderer!.root.findByProps({ "data-remote-image-kind": "content" }).props["data-remote-image-state"])
+ .toBe("error")
+ })
+
+ it("rejects a decoded image without natural pixels", async () => {
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(RemoteContentImage, {
+ src: "/empty.png",
+ alt: "Empty image",
+ loading: "eager",
+ frameStyle: { width: 300, aspectRatio: "4/3" },
+ }),
+ { createNodeMock },
+ )
+ })
+
+ const image = renderer!.root.findByProps({ "data-remote-image-kind": "content" })
+ await act(async () => {
+ image.props.onLoad(imageEvent(() => Promise.resolve(), 0, 0))
+ await Promise.resolve()
+ })
+
+ expect(renderer!.root.findByProps({ "data-remote-image-kind": "content" }).props)
+ .toMatchObject({ src: "/empty.png", "data-remote-image-state": "error" })
+ })
+
+ it("resets to pending when the source changes", async () => {
+ const render = (src: string) => React.createElement(RemoteContentImage, {
+ src,
+ alt: "Photo",
+ loading: "eager",
+ frameStyle: { width: 300, aspectRatio: "4/3" },
+ })
+ await act(async () => {
+ renderer = TestRenderer.create(render("/first.png"), { createNodeMock })
+ })
+ await act(async () => renderer!.root.findByProps({ "data-remote-image-kind": "content" }).props.onError())
+ expect(renderer!.root.findByProps({ "data-remote-image-kind": "content" }).props["data-remote-image-state"])
+ .toBe("error")
+
+ await act(async () => renderer!.update(render("/second.png")))
+ expect(renderer!.root.findByProps({ "data-remote-image-kind": "content" }).props)
+ .toMatchObject({ src: "/second.png", "data-remote-image-state": "pending" })
+ })
+
+ it("keeps Markdown image geometry and retries the exact source", async () => {
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(RemoteMarkdownImage, {
+ src: "https://cdn.example.com/diagram.png?version=2",
+ alt: "Architecture diagram",
+ width: "800",
+ height: "400",
+ }),
+ { createNodeMock },
+ )
+ })
+
+ const wrapper = renderer!.root.findByProps({ "data-streamdown": "image-wrapper" })
+ expect(wrapper.props.style).toEqual({ width: "min(100%, 600px)", aspectRatio: "800/400" })
+ const image = renderer!.root.findByProps({ "data-streamdown": "image" })
+ expect(image.props).toMatchObject({
+ src: "https://cdn.example.com/diagram.png?version=2",
+ alt: "Architecture diagram",
+ loading: "lazy",
+ "data-remote-image-state": "pending",
+ })
+
+ await act(async () => image.props.onError())
+ const retry = renderer!.root.findByType("button")
+ expect(retry.children).toEqual(["Retry"])
+ expect(retry.props.className).toContain("min-h-11")
+ await act(async () => retry.props.onClick())
+
+ expect(renderer!.root.findByProps({ "data-streamdown": "image" }).props).toMatchObject({
+ src: "https://cdn.example.com/diagram.png?version=2",
+ "data-remote-image-state": "pending",
+ })
+ expect(renderer!.root.findByProps({ "data-streamdown": "image-wrapper" }).props.style)
+ .toEqual({ width: "min(100%, 600px)", aspectRatio: "800/400" })
+ })
+
+ it("reserves a safe frame for Markdown images without dimensions", async () => {
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(RemoteMarkdownImage, {
+ src: "/legacy.png",
+ alt: "Legacy image",
+ }),
+ { createNodeMock },
+ )
+ })
+
+ expect(renderer!.root.findByProps({ "data-streamdown": "image-wrapper" }).props.style)
+ .toEqual({ width: "min(100%, 300px)", aspectRatio: "4/3" })
+ })
+})
diff --git a/src/web/src/components/remote-image/remote-image.tsx b/src/web/src/components/remote-image/remote-image.tsx
new file mode 100644
index 000000000..34858b04c
--- /dev/null
+++ b/src/web/src/components/remote-image/remote-image.tsx
@@ -0,0 +1,208 @@
+"use client"
+
+import {
+ Fragment,
+ useEffect,
+ useEffectEvent,
+ type CSSProperties,
+ type ImgHTMLAttributes,
+ type MouseEvent,
+} from "react"
+import { cn } from "@/lib/utils"
+import {
+ REMOTE_IMAGE_TIMEOUT_MS,
+ useRemoteImageAttempt,
+ useRemoteImageEligibility,
+ type RemoteImageStatus,
+} from "./remote-image-attempt"
+
+type IdentityImageProps = {
+ src: string
+ alt: string
+ className?: string
+ placeholderClassName?: string
+ profilePhoto?: boolean
+ timeoutMs?: number
+ "data-testid"?: string
+}
+
+function IdentityImageAttempt({
+ src,
+ alt,
+ className,
+ placeholderClassName,
+ profilePhoto = false,
+ timeoutMs,
+ "data-testid": testId,
+}: IdentityImageProps) {
+ const [status, attempt, , imageRef, onLoad, onError] = useRemoteImageAttempt({ timeoutMs })
+ const legacyStatus = status === "error" ? "failed" : status
+
+ return (
+ <>
+ <span
+ data-slot={profilePhoto ? "avatar-photo-placeholder" : undefined}
+ data-avatar-photo-placeholder={profilePhoto && status !== "ready" ? legacyStatus : undefined}
+ data-remote-image-placeholder="identity"
+ data-remote-image-state={status}
+ aria-hidden
+ className={cn(
+ "absolute inset-0 bg-muted",
+ status === "pending" && "animate-pulse motion-reduce:animate-none",
+ placeholderClassName,
+ )}
+ />
+ <img
+ key={attempt}
+ ref={imageRef}
+ data-testid={testId}
+ data-slot={profilePhoto ? "avatar-image" : undefined}
+ data-avatar-photo-state={profilePhoto ? legacyStatus : undefined}
+ data-remote-image-kind="identity"
+ data-remote-image-state={status}
+ src={src}
+ alt={alt}
+ className={cn(
+ "absolute inset-0 size-full object-cover transition-opacity duration-150 ease-out motion-reduce:transition-none",
+ status === "ready" ? "opacity-100" : "opacity-0",
+ className,
+ )}
+ onLoad={onLoad}
+ onError={onError}
+ />
+ </>
+ )
+}
+
+export function RemoteIdentityImage(props: IdentityImageProps) {
+ return <IdentityImageAttempt key={props.src} {...props} />
+}
+
+type ContentImageProps = Omit<
+ ImgHTMLAttributes<HTMLImageElement>,
+ "children" | "onError" | "onLoad" | "ref" | "src" | "style"
+> & {
+ src: string
+ alt: string
+ frameClassName?: string
+ frameStyle?: CSSProperties
+ imageClassName?: string
+ imageStyle?: CSSProperties
+ loadingLabel?: string
+ errorLabel?: string
+ retryLabel?: string
+ timeoutMs?: number
+ onActivate?: (event: MouseEvent<HTMLButtonElement>) => void
+ activateLabel?: string
+ onReady?: (image: HTMLImageElement) => void
+ onStateChange?: (status: RemoteImageStatus) => void
+ "data-testid"?: string
+}
+
+function ContentImageAttempt({
+ src,
+ alt,
+ frameClassName,
+ frameStyle,
+ imageClassName,
+ imageStyle,
+ loading = "lazy",
+ loadingLabel,
+ errorLabel = "Image failed to load",
+ retryLabel = "Retry",
+ timeoutMs = REMOTE_IMAGE_TIMEOUT_MS,
+ onActivate,
+ activateLabel,
+ onReady,
+ onStateChange,
+ "data-testid": testId,
+ ...imageProps
+}: ContentImageProps) {
+ const [eligible, eligibilityRef] = useRemoteImageEligibility(loading === "lazy")
+ const [status, attempt, readyImage, imageRef, onLoad, onError, retry] = useRemoteImageAttempt({
+ eligible,
+ timeoutMs,
+ })
+ const notifyReady = useEffectEvent((image: HTMLImageElement) => onReady?.(image))
+
+ useEffect(() => onStateChange?.(status), [onStateChange, status])
+ useEffect(() => {
+ if (status === "ready" && readyImage) notifyReady(readyImage)
+ }, [readyImage, status])
+
+ const media = (
+ <Fragment>
+ {status === "pending" && (
+ <span
+ data-remote-image-placeholder
+ aria-hidden
+ className="absolute inset-0 bg-muted/70 animate-pulse motion-reduce:animate-none"
+ />
+ )}
+ {status === "pending" && loadingLabel && (
+ <span className="absolute inset-0 flex items-center justify-center px-4 text-sm text-muted-foreground">
+ {loadingLabel}
+ </span>
+ )}
+ <img
+ {...imageProps}
+ key={attempt}
+ ref={imageRef}
+ data-testid={testId}
+ data-remote-image-kind="content"
+ data-remote-image-state={status}
+ src={src}
+ alt={alt}
+ loading={loading}
+ className={cn(
+ "absolute inset-0 size-full transition-opacity duration-150 ease-out motion-reduce:transition-none",
+ status === "ready" ? "opacity-100" : "opacity-0",
+ imageClassName,
+ )}
+ style={imageStyle}
+ onLoad={onLoad}
+ onError={onError}
+ />
+ </Fragment>
+ )
+
+ return (
+ <div
+ ref={eligibilityRef}
+ data-remote-image-frame
+ data-remote-image-state={status}
+ className={cn("relative overflow-hidden bg-muted/30", frameClassName)}
+ style={frameStyle}
+ >
+ {onActivate && status !== "error" ? (
+ <button
+ type="button"
+ aria-label={activateLabel ?? `Open ${alt}`}
+ onClick={onActivate}
+ className="absolute inset-0 z-1 block size-full cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
+ >
+ {media}
+ </button>
+ ) : media}
+ {status === "error" && (
+ <div
+ role="status"
+ className="absolute inset-0 z-2 flex flex-col items-center justify-center gap-1 bg-muted px-2 text-center text-xs text-muted-foreground"
+ >
+ <span>{errorLabel}</span>
+ <button
+ type="button"
+ onClick={retry}
+ className="inline-flex min-h-11 min-w-11 items-center justify-center 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"
+ >
+ {retryLabel}
+ </button>
+ </div>
+ )}
+ </div>
+ )
+}
+
+export function RemoteContentImage(props: ContentImageProps) {
+ return <ContentImageAttempt key={props.src} {...props} />
+}
diff --git a/src/web/src/components/remote-image/remote-markdown-image.tsx b/src/web/src/components/remote-image/remote-markdown-image.tsx
new file mode 100644
index 000000000..85105ec27
--- /dev/null
+++ b/src/web/src/components/remote-image/remote-markdown-image.tsx
@@ -0,0 +1,151 @@
+"use client"
+
+import { Download } from "lucide-react"
+import { useCallback } from "react"
+import { cn } from "@/lib/utils"
+import { useRemoteImageAttempt, useRemoteImageEligibility } from "./remote-image-attempt"
+
+const EXTENSION_RE = /\.[^/.]+$/
+
+function dimension(value: unknown): number | undefined {
+ const parsed = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""))
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined
+}
+
+async function downloadRemoteImage(src: string, alt: string) {
+ try {
+ const blob = await fetch(src).then((response) => response.blob())
+ const pathName = new URL(src, window.location.origin).pathname.split("/").pop() || ""
+ const pathExtension = pathName.split(".").pop()
+ const hasExtension = pathName.includes(".") && pathExtension && pathExtension.length <= 4
+ let filename = pathName
+ if (!hasExtension) {
+ const extension = blob.type.includes("jpeg") || blob.type.includes("jpg")
+ ? "jpg"
+ : blob.type.includes("svg")
+ ? "svg"
+ : blob.type.includes("gif")
+ ? "gif"
+ : blob.type.includes("webp")
+ ? "webp"
+ : "png"
+ filename = `${(alt || pathName || "image").replace(EXTENSION_RE, "")}.${extension}`
+ }
+ const objectUrl = URL.createObjectURL(blob)
+ const anchor = document.createElement("a")
+ anchor.href = objectUrl
+ anchor.download = filename
+ document.body.appendChild(anchor)
+ anchor.click()
+ anchor.remove()
+ URL.revokeObjectURL(objectUrl)
+ } catch {
+ window.open(src, "_blank")
+ }
+}
+
+type MarkdownImageProps = Record<string, unknown> & {
+ src?: string
+ alt?: string
+ className?: string
+ width?: number | string
+ height?: number | string
+}
+
+function MarkdownImageAttempt({
+ src,
+ alt = "",
+ className,
+ width,
+ height,
+ node,
+ ...rest
+}: MarkdownImageProps) {
+ void node
+ const [eligible, eligibilityRef] = useRemoteImageEligibility(true)
+ const [status, attempt, , imageRef, onLoad, onError, retry] = useRemoteImageAttempt({
+ eligible,
+ })
+ const imageWidth = dimension(width)
+ const imageHeight = dimension(height)
+ const aspectRatio = imageWidth && imageHeight ? `${imageWidth}/${imageHeight}` : "4/3"
+ const frameWidth = imageWidth && imageHeight
+ ? Math.min(imageWidth, 300 * imageWidth / imageHeight)
+ : imageWidth ? Math.min(imageWidth, 300) : 300
+ const download = useCallback(() => {
+ if (src) void downloadRemoteImage(src, alt)
+ }, [alt, src])
+
+ if (!src) return null
+
+ return (
+ <div
+ ref={eligibilityRef}
+ data-streamdown="image-wrapper"
+ data-remote-image-state={status}
+ className="group relative my-4 inline-block max-w-full overflow-hidden rounded-lg bg-muted/30"
+ style={{ width: `min(100%, ${frameWidth}px)`, aspectRatio }}
+ >
+ {status === "pending" && (
+ <span
+ aria-hidden
+ data-remote-image-placeholder
+ className="absolute inset-0 bg-muted/70 animate-pulse motion-reduce:animate-none"
+ />
+ )}
+ <img
+ {...rest}
+ key={attempt}
+ ref={imageRef}
+ data-streamdown="image"
+ data-remote-image-kind="content"
+ data-remote-image-state={status}
+ src={src}
+ alt={alt}
+ width={imageWidth}
+ height={imageHeight}
+ loading="lazy"
+ className={cn(
+ "absolute inset-0 size-full rounded-lg object-contain transition-opacity duration-150 ease-out motion-reduce:transition-none",
+ status === "ready" ? "opacity-100" : "opacity-0",
+ className,
+ )}
+ onLoad={onLoad}
+ onError={onError}
+ />
+ {status === "error" && (
+ <div
+ role="status"
+ data-streamdown="image-fallback"
+ className="absolute inset-0 z-2 flex flex-col items-center justify-center gap-1 bg-muted px-2 text-center text-xs text-muted-foreground"
+ >
+ <span>Image not available</span>
+ <button
+ type="button"
+ onClick={retry}
+ className="inline-flex min-h-11 min-w-11 items-center justify-center 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"
+ >
+ Retry
+ </button>
+ </div>
+ )}
+ {status === "ready" && (
+ <>
+ <span className="pointer-events-none absolute inset-0 hidden rounded-lg bg-foreground/10 group-hover:block" />
+ <button
+ type="button"
+ title="Download image"
+ onClick={download}
+ className="absolute right-2 bottom-2 flex size-8 cursor-pointer items-center justify-center rounded-md border border-border bg-background/90 opacity-0 shadow-sm backdrop-blur-sm transition-all duration-200 hover:bg-background group-hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <Download className="size-3.5" />
+ </button>
+ </>
+ )}
+ </div>
+ )
+}
+
+export function RemoteMarkdownImage(props: MarkdownImageProps) {
+ return props.src ? <MarkdownImageAttempt key={props.src} {...props} /> : null
+}
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.ts
index faeb9cebe..3830fd8a6 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
@@ -44,7 +44,7 @@ async function waitForDialogEntrance(page: Page) {
await lightbox.evaluate((element, ids) => {
const dialog = element.closest<HTMLElement>("[data-slot='dialog-content']")
if (!dialog) throw new Error("lightbox dialog content disappeared")
- return Promise.all(dialog.getAnimations({ subtree: true }).map((animation) => animation.finished))
+ return Promise.all(dialog.getAnimations().map((animation) => animation.finished))
.then(() => new Promise<void>((resolveStable, rejectStable) => {
let previous = ""
let unchangedFrames = 0
@@ -184,6 +184,14 @@ test("image previews keep one frame through loading, decode, failure, retry, and
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)
+ const landscapeListFrame = landscapeListImage.locator("xpath=ancestor::*[@data-remote-image-frame]")
+ await expect(landscapeListFrame).toHaveAttribute("data-remote-image-state", "pending")
+ const pendingListRect = await boundingRect(landscapeListFrame)
+ await page.emulateMedia({ reducedMotion: "reduce" })
+ expect(await landscapeListFrame.locator("[data-remote-image-placeholder]").evaluate((element) => (
+ getComputedStyle(element).animationName
+ ))).toBe("none")
+ await page.emulateMedia({ reducedMotion: "no-preference" })
let releaseLandscape!: () => void
const landscapeGate = new Promise<void>((resolve) => { releaseLandscape = resolve })
@@ -199,7 +207,10 @@ test("image previews keep one frame through loading, decode, failure, retry, and
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()
+ await expect(page.getByTestId(tid.imageLightbox)).toBeVisible()
+ await expect(page.getByTestId(tid.imageLightboxLoading)).toBeVisible()
+ await waitForDialogEntrance(page)
+ const coldPendingRect = await previewRects(page)
expect(await page.getByTestId(tid.imageLightboxThumbnail).evaluate((element: HTMLImageElement) => ({
complete: element.complete,
naturalWidth: element.naturalWidth,
@@ -207,7 +218,10 @@ test("image previews keep one frame through loading, decode, failure, retry, and
holdColdThumbnail = false
releaseColdThumbnail()
+ await expect(landscapeListFrame).toHaveAttribute("data-remote-image-state", "ready")
+ expectSameRect(await boundingRect(landscapeListFrame), pendingListRect)
await expect(page.getByTestId(tid.imageLightbox)).toBeVisible()
+ expectSameRect(await previewRects(page).then((rects) => rects.container), coldPendingRect.container)
const coldThumbnailReady = await page.getByTestId(tid.imageLightboxThumbnail).evaluate((element: HTMLImageElement) => ({
complete: element.complete,
naturalWidth: element.naturalWidth,
@@ -218,7 +232,6 @@ test("image previews keep one frame through loading, decode, failure, retry, and
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)
diff --git a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
index ab2d59472..ce747d5c2 100644
--- a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
+++ b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
@@ -85,10 +85,43 @@ test("real bot avatars become unreadable after single delete and authenticated m
const upload = await uploadAvatar(alice.page, botId)
expect(upload.status).toBe(200)
- await alice.page.reload()
+ let releaseAvatar!: () => void
+ const avatarGate = new Promise<void>((resolve) => { releaseAvatar = resolve })
+ let failAvatar = true
+ let avatarRequests = 0
+ await alice.page.route(`**${avatarPath}*`, async (route) => {
+ if (route.request().method() === "GET") {
+ avatarRequests++
+ if (failAvatar) {
+ await avatarGate
+ return route.fulfill({ status: 503, body: "avatar unavailable" })
+ }
+ }
+ await route.continue()
+ })
+ await alice.page.reload({ waitUntil: "commit" })
await expect(alice.page.getByText(botName, { exact: true })).toBeVisible()
const avatar = alice.page.locator(`img[src="${upload.url}"]`)
- await expect(avatar).toBeVisible()
+ await expect(avatar).toHaveAttribute("data-remote-image-state", "pending")
+ const avatarFrame = avatar.locator("xpath=..")
+ const pendingFrame = await avatarFrame.boundingBox()
+ expect(pendingFrame).not.toBeNull()
+ await expect(avatarFrame.locator('[data-remote-image-placeholder="identity"][data-remote-image-state="pending"]'))
+ .toBeVisible()
+ releaseAvatar()
+ await expect(avatar).toHaveAttribute("data-remote-image-state", "error")
+ await expect(avatarFrame.locator('[data-remote-image-placeholder="identity"][data-remote-image-state="error"]'))
+ .toBeVisible()
+ await expect(avatarFrame.locator("svg")).toHaveCount(0)
+ expect(await avatarFrame.boundingBox()).toEqual(pendingFrame)
+
+ failAvatar = false
+ await alice.page.reload({ waitUntil: "commit" })
+ await expect.poll(() => avatarRequests).toBeGreaterThan(1)
+ await expect(avatar).toHaveAttribute("data-remote-image-state", "ready")
+ const readyFrame = await avatarFrame.boundingBox()
+ expect(readyFrame).toEqual(pendingFrame)
+ await alice.page.unroute(`**${avatarPath}*`)
await expect.poll(() => avatar.evaluate((img: HTMLImageElement) => img.complete && img.naturalWidth)).toBe(1)
expect(await alice.page.evaluate(async (path) => (
await fetch(`${path}?before=${crypto.randomUUID()}`, { cache: "no-store" })
diff --git a/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts b/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts
index adb7dc6a6..bf26c0743 100644
--- a/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts
+++ b/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts
@@ -284,7 +284,22 @@ test("consecutive share-image exports reuse rendered avatar, attachment, and inv
attachmentStatus: 200,
messageStatus: 201,
})
+ let releaseServerIcon!: () => void
+ const serverIconGate = new Promise<void>((resolve) => { releaseServerIcon = resolve })
+ const serverIconPattern = `**/api/community/servers/${serverId}/icon*`
+ await page.route(serverIconPattern, async (route) => {
+ if (route.request().method() === "GET") await serverIconGate
+ await route.continue()
+ })
await gotoAfterUserWsAuth(page, route)
+ const railServerImage = page.getByTestId(tid.serverIcon(serverId)).locator('[data-remote-image-kind="identity"]')
+ await expect(railServerImage).toHaveAttribute("data-remote-image-state", "pending")
+ const pendingServerFrame = await railServerImage.locator("xpath=..").boundingBox()
+ expect(pendingServerFrame).not.toBeNull()
+ releaseServerIcon()
+ await expect(railServerImage).toHaveAttribute("data-remote-image-state", "ready")
+ expect(await railServerImage.locator("xpath=..").boundingBox()).toEqual(pendingServerFrame)
+ await page.unroute(serverIconPattern)
const row = page.getByTestId(tid.message(seeded.messageId))
await expect(row).toBeVisible()
await row.hover()
diff --git a/src/web/src/test/e2e-ui/56-remote-image-state-contract.spec.ts b/src/web/src/test/e2e-ui/56-remote-image-state-contract.spec.ts
new file mode 100644
index 000000000..8288cc4f3
--- /dev/null
+++ b/src/web/src/test/e2e-ui/56-remote-image-state-contract.spec.ts
@@ -0,0 +1,153 @@
+import type { Locator } from "@playwright/test"
+import { test, expect } from "./_fixtures/community-fixture"
+import { solidPngFixture, structuredJpegFixture } from "../fixtures/media"
+
+const ARTIFACT_IMAGE = solidPngFixture(800, 450, [39, 111, 191])
+const ARTIFACT_THUMBNAIL = structuredJpegFixture(320, 180)
+
+async function expectStableFrame(frame: Locator, expected: { width: number; height: number }) {
+ await expect.poll(async () => {
+ const box = await frame.boundingBox()
+ return box ? { width: box.width, height: box.height } : null
+ }).toEqual(expected)
+}
+
+test("Workspace artifact thumbnails and full images hold geometry through failure and exact-URL retry", async ({ asUser }) => {
+ test.setTimeout(180_000)
+ const { context, page } = await asUser("alice", { viewport: { width: 1280, height: 800 } })
+ const suffix = Date.now().toString(36)
+ const slug = `remote-image-${suffix}`
+
+ const workspaceResponse = await context.request.post("/api/workspaces", {
+ data: { name: `Remote image ${suffix}`, slug },
+ })
+ expect(workspaceResponse.status()).toBe(201)
+ const workspace = await workspaceResponse.json() as { id: string; slug: string }
+ const onboardedResponse = await context.request.post(`/api/workspaces/${workspace.id}/onboarded`)
+ expect(onboardedResponse.status()).toBe(200)
+
+ const tokenResponse = await context.request.post(`/api/machine-tokens?workspace_id=${workspace.id}`, {
+ data: { name: `remote-image-${suffix}` },
+ })
+ expect(tokenResponse.status()).toBe(201)
+ const { token } = await tokenResponse.json() as { token: string }
+ const activationResponse = await context.request.post("/api/machine-tokens/activate", {
+ data: {
+ token,
+ hostname: `remote-image-${suffix}`,
+ runtimes: [{ type: "codex", version: "e2e" }],
+ },
+ })
+ expect(activationResponse.status()).toBe(200)
+ const activation = await activationResponse.json() as { runtimes: Array<{ id: string }> }
+
+ const agentResponse = await context.request.post(`/api/agents?workspace_id=${workspace.id}`, {
+ data: {
+ name: `Remote Image ${suffix}`,
+ description: "",
+ instructions: "",
+ runtime_id: activation.runtimes[0]!.id,
+ },
+ })
+ expect(agentResponse.status()).toBe(201)
+ const agent = await agentResponse.json() as { id: string }
+ const conversationResponse = await context.request.post(
+ `/api/agents/${agent.id}/conversation?workspace_id=${workspace.id}`,
+ { data: {} },
+ )
+ expect(conversationResponse.status()).toBe(200)
+ const conversation = await conversationResponse.json() as { id: string }
+
+ const messageResponse = await context.request.post(
+ `/api/conversations/${conversation.id}/messages?workspace_id=${workspace.id}`,
+ {
+ multipart: {
+ content: "Review this artifact",
+ file: {
+ name: "artifact.png",
+ mimeType: "image/png",
+ buffer: ARTIFACT_IMAGE,
+ },
+ "thumbnail:0": {
+ name: "thumbnail.jpg",
+ mimeType: "image/jpeg",
+ buffer: ARTIFACT_THUMBNAIL,
+ },
+ },
+ },
+ )
+ expect([201, 500]).toContain(messageResponse.status())
+
+ let releaseThumbnailFailure!: () => void
+ const thumbnailGate = new Promise<void>((resolve) => { releaseThumbnailFailure = resolve })
+ let thumbnailRequests = 0
+ await page.route("**/api/artifacts/*/thumbnail?*", async (route) => {
+ if (route.request().method() !== "GET") return route.continue()
+ thumbnailRequests += 1
+ if (thumbnailRequests === 1) {
+ await thumbnailGate
+ return route.fulfill({ status: 503, body: "thumbnail unavailable" })
+ }
+ return route.continue()
+ })
+
+ await page.goto(`/w/${workspace.slug}/agents/${agent.id}`, { waitUntil: "commit" })
+ const thumbnail = page.locator('img[alt="artifact.png"][src*="/thumbnail"]')
+ await expect(thumbnail).toHaveAttribute("data-remote-image-state", "pending", { timeout: 20_000 })
+ const thumbnailFrame = thumbnail.locator("xpath=ancestor::*[@data-remote-image-frame][1]")
+ const thumbnailPendingBox = await thumbnailFrame.boundingBox()
+ expect(thumbnailPendingBox).not.toBeNull()
+ const thumbnailSize = {
+ width: thumbnailPendingBox!.width,
+ height: thumbnailPendingBox!.height,
+ }
+
+ releaseThumbnailFailure()
+ await expect(thumbnail).toHaveAttribute("data-remote-image-state", "error")
+ await expect(thumbnailFrame.getByRole("button", { name: "Retry" })).toBeVisible()
+ await expectStableFrame(thumbnailFrame, thumbnailSize)
+ const thumbnailUrl = await thumbnail.getAttribute("src")
+ await thumbnailFrame.getByRole("button", { name: "Retry" }).click()
+ await expect.poll(() => thumbnailRequests).toBe(2)
+ await expect(thumbnail).toHaveAttribute("src", thumbnailUrl!)
+ await expect(thumbnail).toHaveAttribute("data-remote-image-state", "ready")
+ await expectStableFrame(thumbnailFrame, thumbnailSize)
+ await page.unroute("**/api/artifacts/*/thumbnail?*")
+
+ let releaseContentFailure!: () => void
+ const contentGate = new Promise<void>((resolve) => { releaseContentFailure = resolve })
+ let contentRequests = 0
+ await page.route("**/api/artifacts/*/content?*", async (route) => {
+ if (route.request().method() !== "GET") return route.continue()
+ contentRequests += 1
+ if (contentRequests === 1) {
+ await contentGate
+ return route.fulfill({ status: 503, body: "content unavailable" })
+ }
+ return route.continue()
+ })
+
+ await page.getByRole("button", { name: "Open artifact.png" }).first().click()
+ const fullImage = page.locator('img[alt="artifact.png"][src*="/content"]')
+ await expect(fullImage).toHaveAttribute("data-remote-image-state", "pending")
+ await expect(page.getByRole("link", { name: "Download artifact.png" })).toBeVisible()
+ const contentFrame = fullImage.locator("xpath=ancestor::*[@data-remote-image-frame][1]")
+ const contentPendingBox = await contentFrame.boundingBox()
+ expect(contentPendingBox).not.toBeNull()
+ const contentSize = {
+ width: contentPendingBox!.width,
+ height: contentPendingBox!.height,
+ }
+
+ releaseContentFailure()
+ await expect(fullImage).toHaveAttribute("data-remote-image-state", "error")
+ await expectStableFrame(contentFrame, contentSize)
+ const contentUrl = await fullImage.getAttribute("src")
+ await contentFrame.getByRole("button", { name: "Retry" }).click()
+ await expect.poll(() => contentRequests).toBe(2)
+ await expect(fullImage).toHaveAttribute("src", contentUrl!)
+ await expect(fullImage).toHaveAttribute("data-remote-image-state", "ready")
+ await expectStableFrame(contentFrame, contentSize)
+ await page.getByRole("button", { name: "Close image" }).click()
+ await expect(fullImage).toHaveCount(0)
+})