Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): stabilize share image photo exports (#714)

Gener096c33894e2d
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 5264b8d9c..0f9d22d60 100644
--- a/src/web/src/components/avatar/profile-avatar.error.test.ts
+++ b/src/web/src/components/avatar/profile-avatar.error.test.ts
@@ -1,14 +1,67 @@
import { createElement } from "react"
import TestRenderer, { act } from "react-test-renderer"
-import { describe, expect, it } from "vitest"
+import { afterEach, describe, expect, it, vi } from "vitest"
import { ProfileAvatar } from "./profile-avatar"
globalThis.IS_REACT_ACT_ENVIRONMENT = true
describe("ProfileAvatar photo errors", () => {
- it("shows the fallback only after the photo reports an error", async () => {
- let renderer: TestRenderer.ReactTestRenderer
+ let renderer: TestRenderer.ReactTestRenderer | undefined
+ afterEach(async () => {
+ if (renderer) {
+ await act(async () => renderer?.unmount())
+ renderer = undefined
+ }
+ vi.useRealTimers()
+ })
+
+ it("reveals a cached photo whose load event completed before hydration", async () => {
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ProfileAvatar, {
+ label: "Ada",
+ src: "https://cdn.example.com/cached.png",
+ seed: "user_1",
+ }), {
+ createNodeMock: (element) => element.type === "img"
+ ? { complete: true, naturalWidth: 40, naturalHeight: 40 }
+ : null,
+ })
+ })
+
+ expect(renderer!.root.findByProps({ "data-slot": "avatar-image" }).props).toMatchObject({
+ "data-avatar-photo-state": "ready",
+ })
+ const placeholder = renderer!.root.findByProps({ "data-slot": "avatar-photo-placeholder" })
+ expect(placeholder.props["data-avatar-photo-placeholder"]).toBeUndefined()
+ expect(placeholder.props.className).not.toContain("animate-pulse")
+ })
+
+ it("shows a static neutral placeholder when a cached photo failed before hydration", async () => {
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ProfileAvatar, {
+ label: "Ada",
+ src: "https://cdn.example.com/failed-before-hydration.png",
+ seed: "user_1",
+ }), {
+ createNodeMock: (element) => element.type === "img"
+ ? { complete: true, naturalWidth: 0, naturalHeight: 0 }
+ : null,
+ })
+ })
+
+ expect(renderer!.root.findByProps({ "data-slot": "avatar-image" }).props).toMatchObject({
+ "data-avatar-photo-state": "failed",
+ })
+ const placeholder = renderer!.root.findByProps({ "data-slot": "avatar-photo-placeholder" })
+ expect(placeholder.props["data-avatar-photo-placeholder"]).toBe("failed")
+ expect(placeholder.props.className).not.toContain("animate-pulse")
+ expect(renderer!.root.findAllByProps({ "data-slot": "avatar-fallback" })).toHaveLength(0)
+ expect(renderer!.root.findAll((node) => node.type === "svg")).toHaveLength(0)
+ expect(JSON.stringify(renderer!.toJSON())).not.toContain('"children":["A"]')
+ })
+
+ it("stops the neutral skeleton after the photo reports an error", async () => {
await act(async () => {
renderer = TestRenderer.create(createElement(ProfileAvatar, {
label: "Ada",
@@ -18,11 +71,107 @@ describe("ProfileAvatar photo errors", () => {
})
const image = renderer!.root.findByProps({ "data-slot": "avatar-image" })
+ expect(image.props["data-avatar-photo-state"]).toBe("pending")
+ expect(renderer!.root.findByProps({ "data-slot": "avatar-photo-placeholder" }).props).toMatchObject({
+ "data-avatar-photo-placeholder": "pending",
+ })
+
await act(async () => {
image.props.onError()
})
- expect(renderer!.root.findAllByProps({ "data-slot": "avatar-image" })).toHaveLength(0)
- expect(JSON.stringify(renderer!.toJSON())).toContain('"children":["A"]')
+ expect(renderer!.root.findByProps({ "data-slot": "avatar-image" }).props).toMatchObject({
+ "data-avatar-photo-state": "failed",
+ })
+ const placeholder = renderer!.root.findByProps({ "data-slot": "avatar-photo-placeholder" })
+ expect(placeholder.props["data-avatar-photo-placeholder"]).toBe("failed")
+ expect(placeholder.props.className).not.toContain("animate-pulse")
+ expect(renderer!.root.findAllByProps({ "data-slot": "avatar-fallback" })).toHaveLength(0)
+ })
+
+ it("reveals a loaded photo over its retained neutral placeholder", async () => {
+ vi.useFakeTimers()
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ProfileAvatar, {
+ label: "Ada",
+ src: "https://cdn.example.com/ada.png",
+ seed: "user_1",
+ }))
+ })
+
+ const image = renderer!.root.findByProps({ "data-slot": "avatar-image" })
+ await act(async () => {
+ image.props.onLoad()
+ })
+
+ expect(renderer!.root.findByProps({ "data-slot": "avatar-image" }).props).toMatchObject({
+ "data-avatar-photo-state": "ready",
+ })
+ const placeholder = renderer!.root.findByProps({ "data-slot": "avatar-photo-placeholder" })
+ expect(placeholder.props["data-avatar-photo-placeholder"]).toBeUndefined()
+ expect(placeholder.props.className).not.toContain("animate-pulse")
+
+ await act(async () => vi.advanceTimersByTime(5_000))
+ expect(renderer!.root.findByProps({ "data-slot": "avatar-image" }).props).toMatchObject({
+ "data-avatar-photo-state": "ready",
+ })
+ })
+
+ it("settles a pending photo to a static placeholder after the readiness timeout", async () => {
+ vi.useFakeTimers()
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ProfileAvatar, {
+ label: "Ada",
+ src: "https://cdn.example.com/never.png",
+ seed: "user_1",
+ }))
+ })
+
+ await act(async () => vi.advanceTimersByTime(5_000))
+
+ const image = renderer!.root.findByProps({ "data-slot": "avatar-image" })
+ expect(image.props["data-avatar-photo-state"]).toBe("failed")
+ const placeholder = renderer!.root.findByProps({ "data-slot": "avatar-photo-placeholder" })
+ expect(placeholder.props["data-avatar-photo-placeholder"]).toBe("failed")
+ expect(placeholder.props.className).not.toContain("animate-pulse")
+
+ await act(async () => image.props.onLoad())
+ expect(renderer!.root.findByProps({ "data-slot": "avatar-image" }).props).toMatchObject({
+ "data-avatar-photo-state": "failed",
+ })
+ })
+
+ it("retries from a neutral skeleton when the photo source changes", async () => {
+ const props = {
+ label: "Ada",
+ seed: "user_1",
+ }
+
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ProfileAvatar, {
+ ...props,
+ src: "https://cdn.example.com/first.png",
+ }))
+ })
+ await act(async () => {
+ renderer!.root.findByProps({ "data-slot": "avatar-image" }).props.onError()
+ })
+
+ await act(async () => {
+ renderer!.update(createElement(ProfileAvatar, {
+ ...props,
+ src: "https://cdn.example.com/second.png",
+ }))
+ })
+
+ const image = renderer!.root.findByProps({ "data-slot": "avatar-image" })
+ expect(image.props).toMatchObject({
+ src: "https://cdn.example.com/second.png",
+ "data-avatar-photo-state": "pending",
+ })
+ const placeholder = renderer!.root.findByProps({ "data-slot": "avatar-photo-placeholder" })
+ expect(placeholder.props["data-avatar-photo-placeholder"]).toBe("pending")
+ expect(placeholder.props.className).toContain("animate-pulse")
+ expect(renderer!.root.findAllByProps({ "data-slot": "avatar-fallback" })).toHaveLength(0)
})
})
diff --git a/src/web/src/components/avatar/profile-avatar.test.ts b/src/web/src/components/avatar/profile-avatar.test.ts
index 3b87d82d6..397b98d73 100644
--- a/src/web/src/components/avatar/profile-avatar.test.ts
+++ b/src/web/src/components/avatar/profile-avatar.test.ts
@@ -13,7 +13,7 @@ function render(props: ProfileAvatarProps): string {
}
describe("ProfileAvatar", () => {
- it("mounts a photo immediately without showing the loading fallback", () => {
+ it("mounts a photo over a same-size neutral pending skeleton", () => {
const html = render({
label: "Ada",
src: "https://cdn.example.com/ada.png",
@@ -25,8 +25,14 @@ describe("ProfileAvatar", () => {
expect(html).toContain('data-testid="profile-avatar"')
expect(html).toContain('data-avatar-kind="photo"')
- expect(html).toContain('<img data-slot="avatar-image" src="https://cdn.example.com/ada.png" alt="Ada"')
+ 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).not.toContain('data-slot="avatar-fallback"')
+ expect(html).not.toContain(">A</span>")
+ expect(html).toContain('data-slot="avatar-image" data-avatar-photo-state="pending"')
+ expect(html).toContain('src="https://cdn.example.com/ada.png" alt="Ada"')
+ expect(html).toContain("opacity-0")
+ expect(html).toContain("transition-opacity duration-150 ease-out motion-reduce:transition-none")
expect(html).toContain("width:40px;height:40px")
expect(html).toContain("ring-2")
})
@@ -71,7 +77,10 @@ describe("ProfileAvatar", () => {
})
expect(html).toContain('data-avatar-kind="photo"')
- expect(html).toContain('<img data-slot="avatar-image" src="/api/avatar" alt=""')
+ expect(html).toContain('data-avatar-photo-placeholder="pending"')
+ expect(html).not.toContain('data-slot="avatar-fallback"')
+ expect(html).toContain('data-slot="avatar-image" data-avatar-photo-state="pending"')
+ expect(html).toContain('src="/api/avatar" alt=""')
expect(html).toContain('aria-hidden="true"')
expect(html).not.toContain('role="img"')
expect(html).not.toContain("aria-label")
diff --git a/src/web/src/components/avatar/profile-avatar.tsx b/src/web/src/components/avatar/profile-avatar.tsx
index e579e0730..f9ba0dda4 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 { useState, type ReactNode } from "react"
+import { useCallback, useEffect, useState, type ReactNode } from "react"
import {
Avatar as UiAvatar,
AvatarFallback,
@@ -10,6 +10,8 @@ import { avatarInitial } from "@/lib/community/avatar"
import { cn } from "@/lib/utils"
import { GeneratedAvatar } from "./generated-avatar"
+const PROFILE_PHOTO_READY_TIMEOUT_MS = 5_000
+
export type ProfileAvatarProps = {
label: string
src?: string | null
@@ -22,30 +24,50 @@ export type ProfileAvatarProps = {
"data-testid"?: string
}
-function ProfilePhoto({ src, alt, fallback, fontSize }: {
+function ProfilePhoto({ src, alt }: {
src: string
alt: string
- fallback: string
- fontSize: number
}) {
- const [failed, setFailed] = useState(false)
+ 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])
- if (failed) {
- return (
- <AvatarFallback className="font-medium" style={{ fontSize }}>
- {fallback}
- </AvatarFallback>
- )
- }
+ useEffect(() => {
+ if (status !== "pending") return
+ const timeout = setTimeout(() => settleStatus("failed"), PROFILE_PHOTO_READY_TIMEOUT_MS)
+ return () => clearTimeout(timeout)
+ }, [settleStatus, status])
return (
- <img
- data-slot="avatar-image"
- src={src}
- alt={alt}
- className="aspect-square size-full rounded-full object-cover"
- onError={() => setFailed(true)}
- />
+ <>
+ <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")}
+ />
+ </>
)
}
@@ -80,8 +102,6 @@ export function ProfileAvatar({
key={resolved.url}
src={resolved.url}
alt={accessibleLabel}
- fallback={avatarInitial(safeLabel)}
- fontSize={size * 0.4}
/>
) : resolved.kind === "beam" ? (
<span className="size-full overflow-hidden rounded-full">
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 5266ca9e7..7001fea80 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
@@ -8,6 +8,7 @@ import {
ShareCardImageTimeoutError,
ShareCardRenderError,
ShareImageSnapshotError,
+ type ShareCardImageDisposition,
copyRenderedShareCard,
createShareImageSnapshot,
downloadRenderedShareCard,
@@ -229,7 +230,13 @@ describe("MessageShareDialog message context", () => {
})
describe("waitForShareCardImages", () => {
- function image(overrides: Partial<HTMLImageElement> = {}) {
+ function image(
+ overrides: Partial<HTMLImageElement> = {},
+ {
+ profilePhoto = false,
+ photoState = "pending",
+ }: { profilePhoto?: boolean; photoState?: "pending" | "ready" | "failed" } = {},
+ ) {
const listeners = new Map<string, () => void>()
const value = {
complete: false,
@@ -238,6 +245,10 @@ describe("waitForShareCardImages", () => {
decode: vi.fn().mockResolvedValue(undefined),
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
+ )),
...overrides,
} as unknown as HTMLImageElement
return { value, listeners }
@@ -273,6 +284,32 @@ describe("waitForShareCardImages", () => {
expect(paint).not.toHaveBeenCalled()
})
+ it("degrades a profile-photo error to its fallback disposition", async () => {
+ const avatar = image({}, { profilePhoto: true })
+ const paint = vi.fn().mockResolvedValue(undefined)
+ const waiting = waitForShareCardImages(card([avatar.value]), paint)
+ avatar.listeners.get("error")?.()
+
+ await expect(waiting).resolves.toEqual([
+ { image: avatar.value, mode: "fallback" },
+ ])
+ expect(avatar.value.decode).not.toHaveBeenCalled()
+ expect(paint).toHaveBeenCalledOnce()
+ })
+
+ it("immediately degrades an already-failed profile photo without waiting again", async () => {
+ const avatar = image({}, { profilePhoto: true, photoState: "failed" })
+ 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(avatar.value.decode).not.toHaveBeenCalled()
+ 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)
@@ -302,6 +339,29 @@ describe("waitForShareCardImages", () => {
}
})
+ it("degrades a pending-forever profile photo within the shared bound", async () => {
+ vi.useFakeTimers()
+ try {
+ const avatar = image({}, { profilePhoto: true })
+ const attachment = image({ complete: true, naturalWidth: 96, naturalHeight: 64 })
+ const paint = vi.fn().mockResolvedValue(undefined)
+ const waiting = waitForShareCardImages(card([avatar.value, attachment.value]), paint, 50)
+
+ await vi.advanceTimersByTimeAsync(50)
+ await expect(waiting).resolves.toEqual([
+ { image: avatar.value, mode: "fallback" },
+ { image: attachment.value, mode: "snapshot" },
+ ])
+
+ expect(attachment.value.decode).toHaveBeenCalledOnce()
+ expect(avatar.value.removeEventListener).toHaveBeenCalledWith("load", expect.any(Function))
+ expect(avatar.value.removeEventListener).toHaveBeenCalledWith("error", expect.any(Function))
+ expect(paint).toHaveBeenCalledOnce()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
it("bounds a pending-forever decode and degrades to the loaded bitmap", async () => {
vi.useFakeTimers()
try {
@@ -323,11 +383,50 @@ describe("waitForShareCardImages", () => {
vi.useRealTimers()
}
})
+
+ it.each([
+ ["rejects", vi.fn().mockRejectedValue(new Error("decode failed"))],
+ ["times out", vi.fn(() => new Promise<void>(() => {}))],
+ ])("degrades a profile photo when decode %s", async (_name, decode) => {
+ vi.useFakeTimers()
+ try {
+ const avatar = image({
+ complete: true,
+ naturalWidth: 40,
+ naturalHeight: 40,
+ decode,
+ }, { profilePhoto: true })
+ const paint = vi.fn().mockResolvedValue(undefined)
+ const waiting = waitForShareCardImages(card([avatar.value]), paint, 50)
+
+ await vi.advanceTimersByTimeAsync(50)
+ await expect(waiting).resolves.toEqual([
+ { image: avatar.value, mode: "fallback" },
+ ])
+ expect(paint).toHaveBeenCalledOnce()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("aborts a pending image wait and removes every listener", async () => {
+ const avatar = image({}, { profilePhoto: true })
+ const paint = vi.fn().mockResolvedValue(undefined)
+ const controller = new AbortController()
+ const waiting = waitForShareCardImages(card([avatar.value]), paint, 50, controller.signal)
+
+ controller.abort()
+
+ await expect(waiting).rejects.toMatchObject({ name: "AbortError" })
+ expect(avatar.value.removeEventListener).toHaveBeenCalledWith("load", expect.any(Function))
+ expect(avatar.value.removeEventListener).toHaveBeenCalledWith("error", expect.any(Function))
+ expect(paint).not.toHaveBeenCalled()
+ })
})
describe("snapshotShareCardImages", () => {
function image() {
- return { replaceWith: vi.fn() } as unknown as HTMLImageElement
+ return { parentNode: {}, replaceWith: vi.fn() } as unknown as HTMLImageElement
}
function canvas() {
@@ -341,6 +440,13 @@ describe("snapshotShareCardImages", () => {
return { querySelectorAll: () => images } as unknown as HTMLElement
}
+ function prepared(
+ images: HTMLImageElement[],
+ mode: ShareCardImageDisposition["mode"] = "snapshot",
+ ): ShareCardImageDisposition[] {
+ return images.map((image) => ({ image, mode }))
+ }
+
it("replaces every live image with its local canvas snapshot and restores it", async () => {
const avatar = image()
const attachment = image()
@@ -349,7 +455,7 @@ describe("snapshotShareCardImages", () => {
const createSnapshot = vi.fn()
.mockReturnValueOnce(avatarCanvas)
.mockReturnValueOnce(attachmentCanvas)
- const waitForImages = vi.fn().mockResolvedValue(undefined)
+ const waitForImages = vi.fn().mockResolvedValue(prepared([avatar, attachment]))
const waitForPaint = vi.fn().mockResolvedValue(undefined)
const restore = await snapshotShareCardImages(
@@ -381,7 +487,7 @@ describe("snapshotShareCardImages", () => {
const createSnapshot = vi.fn()
.mockReturnValueOnce(firstCanvas)
.mockReturnValueOnce(secondCanvas)
- const waitForImages = vi.fn().mockResolvedValue(undefined)
+ const waitForImages = vi.fn().mockResolvedValue(prepared([avatar]))
const waitForPaint = vi.fn().mockResolvedValue(undefined)
const restoreFirst = await snapshotShareCardImages(
@@ -419,7 +525,7 @@ describe("snapshotShareCardImages", () => {
snapshotShareCardImages(
card([avatar, attachment]),
createSnapshot,
- vi.fn().mockResolvedValue(undefined),
+ vi.fn().mockResolvedValue(prepared([avatar, attachment])),
vi.fn().mockRejectedValue(new Error("paint failed")),
),
).rejects.toThrow("paint failed")
@@ -440,7 +546,7 @@ describe("snapshotShareCardImages", () => {
snapshotShareCardImages(
card([avatar, attachment]),
createSnapshot,
- vi.fn().mockResolvedValue(undefined),
+ vi.fn().mockResolvedValue(prepared([avatar, attachment])),
vi.fn().mockResolvedValue(undefined),
),
).rejects.toBeInstanceOf(ShareImageSnapshotError)
@@ -514,7 +620,7 @@ describe("snapshotShareCardImages", () => {
const restore = await snapshotShareCardImages(
card([hiddenImage, attachment]),
createSnapshot,
- vi.fn().mockResolvedValue(undefined),
+ vi.fn().mockResolvedValue(prepared([hiddenImage, attachment])),
vi.fn().mockResolvedValue(undefined),
)
@@ -523,6 +629,37 @@ describe("snapshotShareCardImages", () => {
restore()
expect(attachmentCanvas.replaceWith).toHaveBeenCalledWith(attachment)
})
+
+ it("suppresses a pending profile photo so the neutral placeholder DOM is rasterized", async () => {
+ const avatar = image()
+ const placeholder = {
+ hidden: false,
+ parentNode: {},
+ replaceWith: vi.fn(),
+ }
+ const createSnapshot = vi.fn()
+ vi.stubGlobal("document", { createElement: vi.fn(() => placeholder) })
+
+ try {
+ const restore = await snapshotShareCardImages(
+ card([avatar]),
+ createSnapshot,
+ vi.fn().mockResolvedValue(prepared([avatar], "fallback")),
+ vi.fn().mockResolvedValue(undefined),
+ )
+
+ expect(createSnapshot).not.toHaveBeenCalled()
+ expect(placeholder.hidden).toBe(true)
+ expect(avatar.replaceWith).toHaveBeenCalledWith(placeholder)
+
+ restore()
+ restore()
+ expect(placeholder.replaceWith).toHaveBeenCalledOnce()
+ expect(placeholder.replaceWith).toHaveBeenCalledWith(avatar)
+ } finally {
+ vi.unstubAllGlobals()
+ }
+ })
})
describe("renderShareCard", () => {
@@ -685,6 +822,60 @@ describe("renderShareCard", () => {
expect(rasterize).not.toHaveBeenCalled()
})
+ it("aborts a pending snapshot and restores its late result once", async () => {
+ let finishSnapshot: ((restore: () => void) => void) | undefined
+ const restore = vi.fn()
+ const snapshotImages = vi.fn((_node: HTMLElement, signal?: AbortSignal) => (
+ new Promise<() => void>((resolve) => {
+ expect(signal?.aborted).toBe(false)
+ finishSnapshot = resolve
+ })
+ ))
+ const rasterize = vi.fn()
+ const controller = new AbortController()
+ const rendering = renderShareCard(node, snapshotImages, rasterize, {
+ signal: controller.signal,
+ loadFonts: vi.fn(),
+ })
+ const rejected = expect(rendering).rejects.toMatchObject({ name: "AbortError" })
+
+ controller.abort()
+ await rejected
+ finishSnapshot?.(restore)
+ await vi.waitFor(() => expect(restore).toHaveBeenCalledOnce())
+
+ expect(rasterize).not.toHaveBeenCalled()
+ })
+
+ it("aborts an active rasterizer and restores snapshots exactly once", async () => {
+ vi.stubGlobal("getComputedStyle", vi.fn(() => style))
+ let finishRaster!: (blob: Blob) => void
+ const restore = vi.fn()
+ const rasterize = vi.fn(() => new Promise<Blob>((resolve) => {
+ finishRaster = resolve
+ }))
+ const controller = new AbortController()
+ const rendering = renderShareCard(
+ node,
+ vi.fn().mockResolvedValue(restore),
+ rasterize,
+ {
+ signal: controller.signal,
+ loadFonts: vi.fn().mockResolvedValue(undefined),
+ },
+ )
+ const rejected = expect(rendering).rejects.toMatchObject({ name: "AbortError" })
+ await vi.waitFor(() => expect(rasterize).toHaveBeenCalledOnce())
+
+ controller.abort()
+ await rejected
+ expect(restore).toHaveBeenCalledOnce()
+
+ finishRaster(new Blob(["png"]))
+ await Promise.resolve()
+ expect(restore).toHaveBeenCalledOnce()
+ })
+
it.each(["fonts", "rasterize"] as const)(
"stops after a late %s result and keeps cleanup exact",
async (blockedStage) => {
@@ -895,6 +1086,58 @@ describe("writeShareCardToClipboard", () => {
})
describe("MessageShareDialog action feedback", () => {
+ class ClipboardItemStub {
+ constructor(readonly items: Record<string, Blob>) {}
+ }
+
+ function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
+ }
+
+ function setupActionEnvironment(write = vi.fn().mockResolvedValue(undefined)) {
+ const click = vi.fn()
+ const createObjectURL = vi.fn(() => "blob:share-card")
+ const revokeObjectURL = vi.fn()
+ vi.stubGlobal("window", { setTimeout, clearTimeout })
+ vi.stubGlobal("navigator", { userAgent: "Macintosh", clipboard: { write } })
+ vi.stubGlobal("ClipboardItem", ClipboardItemStub)
+ vi.stubGlobal("document", {
+ documentElement: {},
+ fonts: { ready: Promise.resolve() },
+ createElement: vi.fn(() => ({ click })),
+ })
+ vi.stubGlobal("getComputedStyle", vi.fn(() => ({
+ getPropertyValue: vi.fn(() => ""),
+ })))
+ vi.stubGlobal("URL", { createObjectURL, revokeObjectURL })
+ const renderer = renderMessage(message(), {
+ createNodeMock: () => ({ querySelectorAll: () => [] }),
+ })
+ const copyButton = renderer.root.findByProps({ "data-testid": tid.messageShareCopy })
+ const downloadButton = renderer.root.findAllByType("button").find(
+ (button) => button.children.includes("Download"),
+ )!
+ const dialog = renderer.root.find(
+ (node) => typeof node.props.onOpenChange === "function",
+ )
+ return {
+ click,
+ copyButton,
+ createObjectURL,
+ dialog,
+ downloadButton,
+ renderer,
+ revokeObjectURL,
+ write,
+ }
+ }
+
afterEach(() => {
vi.mocked(toBlob).mockReset()
vi.mocked(toast.success).mockReset()
@@ -966,4 +1209,151 @@ describe("MessageShareDialog action feedback", () => {
)
expect(toast.success).not.toHaveBeenCalled()
})
+
+ it("keeps Copy as the first winner when Download is clicked during its render", async () => {
+ const rendering = deferred<Blob | null>()
+ const blob = new Blob(["png"], { type: "image/png" })
+ vi.mocked(toBlob).mockReturnValue(rendering.promise)
+ const harness = setupActionEnvironment()
+ let copy!: Promise<void>
+ let download!: Promise<void>
+
+ act(() => {
+ copy = harness.copyButton.props.onClick()
+ download = harness.downloadButton.props.onClick()
+ })
+
+ expect(download).toBe(copy)
+ await vi.waitFor(() => expect(toBlob).toHaveBeenCalledOnce())
+ await act(async () => {
+ rendering.resolve(blob)
+ await copy
+ })
+
+ expect(harness.write).toHaveBeenCalledOnce()
+ expect(harness.click).not.toHaveBeenCalled()
+ expect(toast.success).toHaveBeenCalledOnce()
+ expect(toast.success).toHaveBeenCalledWith("Image copied to clipboard")
+ act(() => harness.renderer.unmount())
+ })
+
+ it("keeps Download as the first winner when Copy is clicked during its render", async () => {
+ const rendering = deferred<Blob | null>()
+ const blob = new Blob(["png"], { type: "image/png" })
+ vi.mocked(toBlob).mockReturnValue(rendering.promise)
+ const harness = setupActionEnvironment()
+ let download!: Promise<void>
+ let copy!: Promise<void>
+
+ act(() => {
+ download = harness.downloadButton.props.onClick()
+ copy = harness.copyButton.props.onClick()
+ })
+
+ expect(copy).toBe(download)
+ await vi.waitFor(() => expect(toBlob).toHaveBeenCalledOnce())
+ await act(async () => {
+ rendering.resolve(blob)
+ await download
+ })
+
+ expect(harness.click).toHaveBeenCalledOnce()
+ expect(harness.write).not.toHaveBeenCalled()
+ expect(toast.success).toHaveBeenCalledOnce()
+ expect(toast.success).toHaveBeenCalledWith("Image downloaded")
+ })
+
+ it("releases a failed flight so the action can be retried", async () => {
+ const blob = new Blob(["png"], { type: "image/png" })
+ const write = vi.fn()
+ .mockRejectedValueOnce(new Error("clipboard denied"))
+ .mockResolvedValueOnce(undefined)
+ vi.mocked(toBlob).mockResolvedValue(blob)
+ const harness = setupActionEnvironment(write)
+
+ await act(async () => {
+ await harness.copyButton.props.onClick()
+ })
+ await act(async () => {
+ await harness.copyButton.props.onClick()
+ })
+
+ expect(toBlob).toHaveBeenCalledTimes(2)
+ expect(write).toHaveBeenCalledTimes(2)
+ expect(toast.error).toHaveBeenCalledOnce()
+ expect(toast.error).toHaveBeenCalledWith("Couldn't copy image — try Download instead")
+ expect(toast.success).toHaveBeenCalledOnce()
+ expect(toast.success).toHaveBeenCalledWith("Image copied to clipboard")
+ act(() => harness.renderer.unmount())
+ })
+
+ it("never invokes a pending writer after the dialog closes", async () => {
+ const rendering = deferred<Blob | null>()
+ vi.mocked(toBlob).mockReturnValue(rendering.promise)
+ const harness = setupActionEnvironment()
+ let copy!: Promise<void>
+
+ act(() => {
+ copy = harness.copyButton.props.onClick()
+ })
+ await vi.waitFor(() => expect(toBlob).toHaveBeenCalledOnce())
+ act(() => harness.dialog.props.onOpenChange(false))
+ await act(async () => {
+ await copy
+ rendering.resolve(new Blob(["png"], { type: "image/png" }))
+ await Promise.resolve()
+ })
+
+ expect(harness.write).not.toHaveBeenCalled()
+ expect(harness.click).not.toHaveBeenCalled()
+ expect(toast.success).not.toHaveBeenCalled()
+ expect(toast.error).not.toHaveBeenCalled()
+ expect(harness.copyButton.props.disabled).toBe(false)
+ })
+
+ it("never invokes a pending writer after the dialog unmounts", async () => {
+ const rendering = deferred<Blob | null>()
+ vi.mocked(toBlob).mockReturnValue(rendering.promise)
+ const harness = setupActionEnvironment()
+ let copy!: Promise<void>
+
+ act(() => {
+ copy = harness.copyButton.props.onClick()
+ })
+ await vi.waitFor(() => expect(toBlob).toHaveBeenCalledOnce())
+ act(() => harness.renderer.unmount())
+ await act(async () => {
+ await copy
+ rendering.resolve(new Blob(["png"], { type: "image/png" }))
+ await Promise.resolve()
+ })
+
+ expect(harness.write).not.toHaveBeenCalled()
+ expect(toast.success).not.toHaveBeenCalled()
+ expect(toast.error).not.toHaveBeenCalled()
+ })
+
+ it("suppresses late feedback when the dialog closes after Clipboard API invocation", async () => {
+ const writing = deferred<void>()
+ const write = vi.fn(() => writing.promise)
+ vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
+ const harness = setupActionEnvironment(write)
+ let copy!: Promise<void>
+
+ act(() => {
+ copy = harness.copyButton.props.onClick()
+ })
+ await vi.waitFor(() => expect(write).toHaveBeenCalledOnce())
+ act(() => harness.dialog.props.onOpenChange(false))
+ await act(async () => {
+ writing.resolve()
+ await copy
+ })
+
+ expect(write).toHaveBeenCalledOnce()
+ expect(toast.success).not.toHaveBeenCalled()
+ expect(toast.error).not.toHaveBeenCalled()
+ expect(harness.copyButton.props.disabled).toBe(false)
+ expect(harness.copyButton.children).toContain("Copy image")
+ })
})
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 ee508e6aa..f6a69068d 100644
--- a/src/web/src/components/community/messages/message-share-dialog.tsx
+++ b/src/web/src/components/community/messages/message-share-dialog.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useCallback, useMemo, useRef, useState } from "react"
+import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import Image from "next/image"
import { toBlob } from "html-to-image"
import { toast } from "sonner"
@@ -51,55 +51,89 @@ export class ShareImageSnapshotError extends Error {
}
}
+export type ShareCardImageDisposition = {
+ image: HTMLImageElement
+ mode: "snapshot" | "fallback"
+}
+
+function createShareCardAbortError(): DOMException {
+ return new DOMException("Share-card render aborted", "AbortError")
+}
+
+function isProfilePhoto(image: HTMLImageElement): boolean {
+ return image.hasAttribute("data-avatar-photo-state")
+}
+
+function isFailedProfilePhoto(image: HTMLImageElement): boolean {
+ return image.getAttribute("data-avatar-photo-state") === "failed"
+}
+
async function waitForImageLoad(
image: HTMLImageElement,
- timeoutMs: number,
-): Promise<void> {
+ deadline: number,
+ signal?: AbortSignal,
+): Promise<ShareCardImageDisposition["mode"]> {
+ const fallbackOrThrow = (error: Error): ShareCardImageDisposition["mode"] => {
+ if (isProfilePhoto(image)) return "fallback"
+ throw error
+ }
+ if (signal?.aborted) throw createShareCardAbortError()
+ if (isFailedProfilePhoto(image)) return "fallback"
+
if (!image.complete) {
- const result = await new Promise<"loaded" | "error" | "timeout">((resolve) => {
+ const result = await new Promise<"loaded" | "error" | "timeout" | "aborted">((resolve) => {
let finished = false
- const finish = (result: "loaded" | "error" | "timeout") => {
+ const finish = (result: "loaded" | "error" | "timeout" | "aborted") => {
if (finished) return
finished = true
image.removeEventListener("load", loaded)
image.removeEventListener("error", failed)
+ signal?.removeEventListener("abort", aborted)
clearTimeout(timer)
resolve(result)
}
const loaded = () => finish("loaded")
const failed = () => finish("error")
- const timer = setTimeout(() => finish("timeout"), timeoutMs)
+ const aborted = () => finish("aborted")
+ const timer = setTimeout(() => finish("timeout"), Math.max(0, deadline - Date.now()))
image.addEventListener("load", loaded, { once: true })
image.addEventListener("error", failed, { once: true })
- // Close the tiny race where the resource settles between the initial
- // `complete` read and listener registration.
+ signal?.addEventListener("abort", aborted, { once: true })
if (image.complete) finish(image.naturalWidth > 0 ? "loaded" : "error")
+ else if (signal?.aborted) finish("aborted")
})
- // A request that never emits load/error must fail this capture attempt so
- // Download/Copy leave their busy state and the user can retry; capturing
- // the avatar's transient empty branch would silently recreate the bug.
- if (result === "timeout") throw new ShareCardImageTimeoutError()
- if (result === "error") throw new ShareImageSnapshotError()
+ if (result === "aborted") throw createShareCardAbortError()
+ if (result === "timeout") return fallbackOrThrow(new ShareCardImageTimeoutError())
+ if (result === "error") return fallbackOrThrow(new ShareImageSnapshotError())
}
+ if (isFailedProfilePhoto(image)) return "fallback"
if (image.naturalWidth <= 0 || image.naturalHeight <= 0) {
- throw new ShareImageSnapshotError()
+ return fallbackOrThrow(new ShareImageSnapshotError())
}
if (image.decode) {
- // Once load has supplied a real bitmap, decode() is only an optimization.
- // Mobile WebKit may reject or never resolve it for cached images, so bound
- // this wait and degrade to the already-loaded bitmap instead of deadlocking.
- await new Promise<void>((resolve) => {
+ const result = await new Promise<"decoded" | "failed" | "timeout" | "aborted">((resolve) => {
let finished = false
- const finish = () => {
+ const finish = (result: "decoded" | "failed" | "timeout" | "aborted") => {
if (finished) return
finished = true
+ signal?.removeEventListener("abort", aborted)
clearTimeout(timer)
- resolve()
+ resolve(result)
}
- const timer = setTimeout(finish, timeoutMs)
- Promise.resolve().then(() => image.decode()).then(finish, finish)
+ const aborted = () => finish("aborted")
+ const timer = setTimeout(() => finish("timeout"), Math.max(0, deadline - Date.now()))
+ signal?.addEventListener("abort", aborted, { once: true })
+ Promise.resolve().then(() => image.decode()).then(
+ () => finish("decoded"),
+ () => finish("failed"),
+ )
+ if (signal?.aborted) finish("aborted")
})
+ if (result === "aborted") throw createShareCardAbortError()
+ if (isFailedProfilePhoto(image)) return "fallback"
+ if (result !== "decoded" && isProfilePhoto(image)) return "fallback"
}
+ return "snapshot"
}
function nextPaint(): Promise<void> {
@@ -107,25 +141,31 @@ function nextPaint(): Promise<void> {
return new Promise((resolve) => requestAnimationFrame(() => resolve()))
}
-/**
- * Base UI's photo avatar has a transient loading state where its root contains
- * neither the photo nor the fallback. Desktop usually hits a warm cache;
- * mobile share can rasterise during that gap and permanently export a blank
- * circle. Settle every card image, then yield a paint so the avatar's loaded or
- * fallback branch commits before html-to-image clones computed styles.
- */
export async function waitForShareCardImages(
node: HTMLElement,
waitForPaint: () => Promise<void> = nextPaint,
timeoutMs = SHARE_IMAGE_READY_TIMEOUT_MS,
-): Promise<void> {
- await Promise.all(
- [...node.querySelectorAll("img")].map((image) => waitForImageLoad(image, timeoutMs)),
+ signal?: AbortSignal,
+): Promise<ShareCardImageDisposition[]> {
+ const deadline = Date.now() + timeoutMs
+ const dispositions = await Promise.all(
+ [...node.querySelectorAll("img")].map(async (image) => ({
+ image,
+ mode: await waitForImageLoad(image, deadline, signal),
+ })),
)
+ if (signal?.aborted) throw createShareCardAbortError()
await waitForPaint()
+ if (signal?.aborted) throw createShareCardAbortError()
+ return dispositions
}
-type ShareImageWaiter = (node: HTMLElement) => Promise<void>
+type ShareImageWaiter = (
+ node: HTMLElement,
+ waitForPaint?: () => Promise<void>,
+ timeoutMs?: number,
+ signal?: AbortSignal,
+) => Promise<ShareCardImageDisposition[]>
type ShareImageSnapshotter = (image: HTMLImageElement) => HTMLCanvasElement | null
function copySnapshotPresentation(
@@ -215,27 +255,37 @@ export async function snapshotShareCardImages(
createSnapshot: ShareImageSnapshotter = createShareImageSnapshot,
waitForImages: ShareImageWaiter = waitForShareCardImages,
waitForPaint: () => Promise<void> = nextPaint,
+ signal?: AbortSignal,
): Promise<() => void> {
- await waitForImages(node)
- const images = [...node.querySelectorAll("img")]
- const snapshots: Array<{ image: HTMLImageElement; canvas: HTMLCanvasElement }> = []
+ const dispositions = await waitForImages(node, undefined, undefined, signal)
+ const replacements: Array<{ image: HTMLImageElement; replacement: Element }> = []
let restored = false
const restore = () => {
if (restored) return
restored = true
- for (const { image, canvas } of snapshots) {
- if (canvas.parentNode) canvas.replaceWith(image)
+ for (const { image, replacement } of replacements.reverse()) {
+ if (replacement.parentNode) replacement.replaceWith(image)
}
}
try {
- for (const image of images) {
+ for (const { image, mode } of dispositions) {
+ if (!image.parentNode) continue
+ if (mode === "fallback") {
+ const placeholder = document.createElement("span")
+ placeholder.hidden = true
+ image.replaceWith(placeholder)
+ replacements.push({ image, replacement: placeholder })
+ continue
+ }
const canvas = createSnapshot(image)
if (!canvas) continue
image.replaceWith(canvas)
- snapshots.push({ image, canvas })
+ replacements.push({ image, replacement: canvas })
}
+ if (signal?.aborted) throw createShareCardAbortError()
await waitForPaint()
+ if (signal?.aborted) throw createShareCardAbortError()
return restore
} catch (error) {
restore()
@@ -243,12 +293,29 @@ export async function snapshotShareCardImages(
}
}
-type ShareCardImageSnapshotter = (node: HTMLElement) => Promise<() => void>
+type ShareCardImageSnapshotter = (
+ node: HTMLElement,
+ signal?: AbortSignal,
+) => Promise<() => void>
type ShareCardRasterizer = typeof toBlob
type ShareCardRenderOptions = {
timeoutMs?: number
loadFonts?: () => Promise<void>
onStage?: (stage: ShareCardRenderStage) => void
+ signal?: AbortSignal
+}
+
+function snapshotShareCardImagesForRender(
+ node: HTMLElement,
+ signal?: AbortSignal,
+): Promise<() => void> {
+ return snapshotShareCardImages(
+ node,
+ createShareImageSnapshot,
+ waitForShareCardImages,
+ nextPaint,
+ signal,
+ )
}
async function loadShareCardFonts(): Promise<void> {
@@ -261,7 +328,7 @@ async function loadShareCardFonts(): Promise<void> {
export async function renderShareCard(
node: HTMLElement,
- snapshotImages: ShareCardImageSnapshotter = snapshotShareCardImages,
+ snapshotImages: ShareCardImageSnapshotter = snapshotShareCardImagesForRender,
rasterize: ShareCardRasterizer = toBlob,
options: ShareCardRenderOptions = {},
): Promise<Blob> {
@@ -271,8 +338,8 @@ export async function renderShareCard(
let restoreImages: (() => void) | null = null
let cleanupRequested = false
let cleanupComplete = false
- let timedOut = false
- let timeoutError: ShareCardRenderError | null = null
+ let stopped = false
+ let terminalError: Error | null = null
const enterStage = (nextStage: ShareCardRenderStage) => {
stage = nextStage
@@ -287,26 +354,35 @@ export async function renderShareCard(
}
enterStage("snapshot")
- let rejectDeadline!: (reason: ShareCardRenderError) => void
+ let rejectDeadline!: (reason: Error) => void
const deadline = new Promise<never>((_resolve, reject) => {
rejectDeadline = reject
})
- const timer = setTimeout(() => {
- timedOut = true
- timeoutError = new ShareCardRenderError(stage, true)
+ const stop = (error: Error) => {
+ if (stopped) return
+ stopped = true
+ terminalError = error
try {
cleanup()
- rejectDeadline(timeoutError)
- } catch (error) {
- rejectDeadline(new ShareCardRenderError("cleanup", false, error))
+ rejectDeadline(error)
+ } catch (cleanupError) {
+ terminalError = new ShareCardRenderError("cleanup", false, cleanupError)
+ rejectDeadline(terminalError)
}
- }, timeoutMs)
+ }
+ const timer = setTimeout(
+ () => stop(new ShareCardRenderError(stage, true)),
+ timeoutMs,
+ )
+ const abort = () => stop(createShareCardAbortError())
+ if (options.signal?.aborted) abort()
+ else options.signal?.addEventListener("abort", abort, { once: true })
const lifecycle = async (): Promise<Blob> => {
try {
- restoreImages = await snapshotImages(node)
+ restoreImages = await snapshotImages(node, options.signal)
if (cleanupRequested) cleanup()
- if (timedOut) throw timeoutError
+ if (terminalError) throw terminalError
enterStage("fonts")
try {
@@ -314,7 +390,7 @@ export async function renderShareCard(
} catch {
// Font loading is best-effort; the fallback font is still renderable.
}
- if (timedOut) throw timeoutError
+ if (terminalError) throw terminalError
enterStage("rasterize")
const blob = await rasterize(node, {
@@ -324,7 +400,7 @@ export async function renderShareCard(
// (the card's own rounded bg sits on top of this).
backgroundColor: getComputedStyle(node).getPropertyValue("--card")?.trim() || undefined,
})
- if (timedOut) throw timeoutError
+ if (terminalError) throw terminalError
if (!blob) throw new Error("Rasterizer returned no image")
return blob
} catch (error) {
@@ -343,6 +419,7 @@ export async function renderShareCard(
return await Promise.race([lifecycle(), deadline])
} finally {
clearTimeout(timer)
+ options.signal?.removeEventListener("abort", abort)
}
}
@@ -369,11 +446,11 @@ export async function copyRenderedShareCard(
await write(blob)
}
-export async function downloadRenderedShareCard(
- render: ShareCardRenderer,
+async function saveShareCardDownload(
+ blob: Blob,
filename: string,
- save: ShareCardBlobWriter = (blob) => {
- const url = URL.createObjectURL(blob)
+ save: ShareCardBlobWriter = (value) => {
+ const url = URL.createObjectURL(value)
try {
const anchor = document.createElement("a")
anchor.href = url
@@ -383,10 +460,18 @@ export async function downloadRenderedShareCard(
URL.revokeObjectURL(url)
}
},
+): Promise<void> {
+ await save(blob)
+}
+
+export async function downloadRenderedShareCard(
+ render: ShareCardRenderer,
+ filename: string,
+ save?: ShareCardBlobWriter,
): Promise<void> {
const blob = await render()
if (!blob) throw new ShareCardRenderError("rasterize")
- await save(blob)
+ await saveShareCardDownload(blob, filename, save)
}
export function shareCardRenderErrorMessage(error: unknown): string | null {
@@ -402,6 +487,12 @@ export function shareCardRenderErrorMessage(error: unknown): string | null {
: `Couldn't generate image — ${stage} failed`
}
+type ShareCardExportFlight = {
+ id: number
+ controller: AbortController
+ promise: Promise<void>
+}
+
// Share one OR several messages as an image. Renders a self-contained "share
// card" that mirrors the in-app message blob(s) (avatar / name / content — NO
// timestamp, per spec) plus an Alook brand footer, then rasterises THAT SAME
@@ -426,6 +517,11 @@ export function MessageShareDialog({ m, open, onClose }: {
// the drag happened in, so a drag never wraps the avatar/name/footer OR bleeds
// across messages (Alli #133: highlight is per-message). Keyed by message id.
const bodyRefs = useRef(new Map<string, HTMLDivElement | null>())
+ const exportOwnerRef = useRef<{
+ generation: number
+ active: ShareCardExportFlight | null
+ }>({ generation: 0, active: null })
+ const copiedTimerRef = useRef<number | null>(null)
const [busy, setBusy] = useState<"copy" | "download" | null>(null)
const [copied, setCopied] = useState(false)
// Drives the Reset button's presence. Gus (uiux #95): the button is HIDDEN
@@ -460,49 +556,104 @@ export function MessageShareDialog({ m, open, onClose }: {
setHighlighted(false)
}, [])
- // Rasterise the card node to a PNG blob. pixelRatio 2 keeps the live image
- // snapshots and the rest of the card crisp when pasted into other apps.
- const render = async (): Promise<Blob | null> => {
- const node = cardRef.current
- if (!node) return null
- return renderShareCard(node)
- }
-
- const copy = async () => {
- setBusy("copy")
- try {
- await copyRenderedShareCard(render)
- setCopied(true)
- toast.success("Image copied to clipboard")
- window.setTimeout(() => setCopied(false), 1600)
- } catch (error) {
- toast.error(shareCardRenderErrorMessage(error) ?? "Couldn't copy image — try Download instead")
- } finally {
- setBusy(null)
+ const invalidateExport = useCallback(() => {
+ const owner = exportOwnerRef.current
+ owner.generation += 1
+ owner.active?.controller.abort()
+ owner.active = null
+ if (copiedTimerRef.current !== null) {
+ window.clearTimeout(copiedTimerRef.current)
+ copiedTimerRef.current = null
}
- }
+ }, [])
- const download = async () => {
- setBusy("download")
- try {
- const firstAuthorId = messages[0]?.authorId
- const firstAuthor = firstAuthorId
- ? readCommunityProfile(profilesByUserId.get(firstAuthorId), firstAuthorId)
- : null
- await downloadRenderedShareCard(
- render,
- `alook-message-${firstAuthor?.name ?? "share"}.png`,
- )
- toast.success("Image downloaded")
- } catch (error) {
- toast.error(shareCardRenderErrorMessage(error) ?? "Couldn't generate image")
- } finally {
- setBusy(null)
+ useEffect(() => {
+ if (!open) invalidateExport()
+ }, [invalidateExport, open])
+
+ useEffect(() => () => invalidateExport(), [invalidateExport])
+
+ const startExport = useCallback((action: "copy" | "download"): Promise<void> => {
+ const owner = exportOwnerRef.current
+ if (owner.active) return owner.active.promise
+
+ const id = owner.generation + 1
+ const controller = new AbortController()
+ const flight: ShareCardExportFlight = {
+ id,
+ controller,
+ promise: Promise.resolve(),
}
- }
+ owner.generation = id
+ owner.active = flight
+ if (copiedTimerRef.current !== null) {
+ window.clearTimeout(copiedTimerRef.current)
+ copiedTimerRef.current = null
+ }
+ setCopied(false)
+ setBusy(action)
+
+ const firstAuthorId = messages[0]?.authorId
+ const firstAuthor = firstAuthorId
+ ? readCommunityProfile(profilesByUserId.get(firstAuthorId), firstAuthorId)
+ : null
+ const filename = `alook-message-${firstAuthor?.name ?? "share"}.png`
+ const isCurrent = () => (
+ exportOwnerRef.current.generation === id && !controller.signal.aborted
+ )
+
+ flight.promise = (async () => {
+ try {
+ const node = cardRef.current
+ if (!node) throw new ShareCardRenderError("rasterize")
+ const blob = await renderShareCard(node, undefined, undefined, {
+ signal: controller.signal,
+ })
+ if (!isCurrent()) return
+
+ if (action === "copy") await writeShareCardToClipboard(blob)
+ else await saveShareCardDownload(blob, filename)
+ if (!isCurrent()) return
+
+ if (action === "copy") {
+ setCopied(true)
+ toast.success("Image copied to clipboard")
+ copiedTimerRef.current = window.setTimeout(() => {
+ if (!isCurrent()) return
+ copiedTimerRef.current = null
+ setCopied(false)
+ }, 1600)
+ } else {
+ toast.success("Image downloaded")
+ }
+ } catch (error) {
+ if (!isCurrent()) return
+ toast.error(
+ shareCardRenderErrorMessage(error)
+ ?? (action === "copy" ? "Couldn't copy image — try Download instead" : "Couldn't generate image"),
+ )
+ } finally {
+ if (exportOwnerRef.current.active?.id !== id) return
+ exportOwnerRef.current.active = null
+ if (!controller.signal.aborted) setBusy(null)
+ }
+ })()
+
+ return flight.promise
+ }, [messages, profilesByUserId])
+
+ const close = useCallback(() => {
+ invalidateExport()
+ setBusy(null)
+ setCopied(false)
+ onClose()
+ }, [invalidateExport, onClose])
+
+ const copy = useCallback(() => startExport("copy"), [startExport])
+ const download = useCallback(() => startExport("download"), [startExport])
return (
- <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
+ <Dialog open={open} onOpenChange={(o) => !o && close()}>
{/* NOTE: DialogContent's base class carries `sm:max-w-sm` (384px). That's
a responsive variant, so it sorts AFTER a plain `max-w-[…]` in the
generated CSS and would silently cap the dialog at 384px — the reason a
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 c7f824c52..adb7dc6a6 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
@@ -1,9 +1,210 @@
import { test, expect } from "./_fixtures/community-fixture"
+import type { Locator, Page, Route } from "@playwright/test"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
import { createInvite, seedChannel, seedServer } from "./_fixtures/seed"
import { tid } from "./_fixtures/testids"
type SamplePoint = { x: number; y: number }
+type CaptureKind = "clipboard" | "download"
+
+async function uploadPhoto(page: Page): Promise<void> {
+ const status = await page.evaluate(async () => {
+ const canvas = document.createElement("canvas")
+ canvas.width = 48
+ canvas.height = 48
+ const context = canvas.getContext("2d")!
+ context.fillStyle = "rgb(220, 35, 60)"
+ context.fillRect(0, 0, canvas.width, canvas.height)
+ const avatar = await new Promise<Blob>((resolve, reject) => canvas.toBlob(
+ (blob) => blob ? resolve(blob) : reject(new Error("PNG encode failed")),
+ "image/png",
+ ))
+ const avatarForm = new FormData()
+ avatarForm.append("file", avatar, "avatar.png")
+ const avatarResponse = await fetch("/api/community/users/me/avatar", {
+ method: "POST",
+ body: avatarForm,
+ credentials: "include",
+ })
+ return avatarResponse.status
+ })
+ expect(status).toBe(200)
+}
+
+async function seedPhotoMessage(page: Page, channelId: string, content: string) {
+ await uploadPhoto(page)
+ const seeded = await page.evaluate(async ({ targetId, body }) => {
+ const messageResponse = await fetch(`/api/community/channels/${targetId}/messages`, {
+ method: "POST",
+ credentials: "include",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ content: body,
+ attachments: [],
+ nonce: `e2e:${crypto.randomUUID()}`,
+ }),
+ })
+ const message = await messageResponse.json() as { message: { id: string } }
+ return {
+ messageStatus: messageResponse.status,
+ messageId: message.message.id,
+ }
+ }, { targetId: channelId, body: content })
+
+ expect(seeded).toMatchObject({ messageStatus: 201 })
+ return seeded.messageId
+}
+
+async function openShareDialog(page: Page, messageId: string): Promise<Locator> {
+ const row = page.getByTestId(tid.message(messageId))
+ await expect(row).toBeVisible()
+ await row.hover()
+ await page.getByTestId(tid.messageShare(messageId)).click()
+ await page.getByRole("button", { name: "Share 1 selected messages as image" }).click()
+ const dialog = page.getByRole("dialog", { name: "Share message" })
+ await expect(dialog).toBeVisible()
+ return dialog
+}
+
+async function installShareCapture(page: Page, rejectFirstClipboard = false): Promise<void> {
+ await page.evaluate((rejectFirst) => {
+ const captureWindow = window as typeof window & {
+ __shareCaptures?: {
+ clipboard: Blob[]
+ clipboardAttempts: number
+ download: Blob[]
+ }
+ }
+ captureWindow.__shareCaptures = {
+ clipboard: [],
+ clipboardAttempts: 0,
+ download: [],
+ }
+ const nativeCreateObjectUrl = URL.createObjectURL.bind(URL)
+ URL.createObjectURL = ((value: Blob | MediaSource) => {
+ if (value instanceof Blob && value.type === "image/png") {
+ captureWindow.__shareCaptures!.download.push(value)
+ }
+ return nativeCreateObjectUrl(value)
+ }) as typeof URL.createObjectURL
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: {
+ write: async (items: ClipboardItem[]) => {
+ const captures = captureWindow.__shareCaptures!
+ captures.clipboardAttempts += 1
+ if (rejectFirst && captures.clipboardAttempts === 1) {
+ throw new Error("clipboard denied by test")
+ }
+ captures.clipboard.push(await items[0]!.getType("image/png"))
+ },
+ },
+ })
+ }, rejectFirstClipboard)
+}
+
+async function shareCaptureCounts(page: Page) {
+ return page.evaluate(() => {
+ const captures = (window as typeof window & {
+ __shareCaptures?: {
+ clipboard: Blob[]
+ clipboardAttempts: number
+ download: Blob[]
+ }
+ }).__shareCaptures
+ return {
+ clipboard: captures?.clipboard.length ?? 0,
+ clipboardAttempts: captures?.clipboardAttempts ?? 0,
+ download: captures?.download.length ?? 0,
+ }
+ })
+}
+
+async function avatarSamplePoint(card: Locator): Promise<SamplePoint> {
+ return card.evaluate((cardNode) => {
+ const avatar = cardNode.querySelector('[data-avatar-kind="photo"]')!
+ const cardRect = cardNode.getBoundingClientRect()
+ const avatarRect = avatar.getBoundingClientRect()
+ return {
+ x: (avatarRect.left - cardRect.left + avatarRect.width / 2) * 2,
+ y: (avatarRect.top - cardRect.top + avatarRect.height / 2) * 2,
+ }
+ })
+}
+
+async function capturedPixel(
+ page: Page,
+ kind: CaptureKind,
+ index: number,
+ point: SamplePoint,
+) {
+ return page.evaluate(async ({ captureKind, captureIndex, sample }) => {
+ const captures = (window as typeof window & {
+ __shareCaptures?: { clipboard: Blob[]; download: Blob[] }
+ }).__shareCaptures
+ const blob = captures?.[captureKind][captureIndex]
+ if (!blob) throw new Error(`Missing ${captureKind} capture ${captureIndex}`)
+ const bitmap = await createImageBitmap(blob)
+ const canvas = document.createElement("canvas")
+ canvas.width = bitmap.width
+ canvas.height = bitmap.height
+ const context = canvas.getContext("2d")!
+ context.drawImage(bitmap, 0, 0)
+ const pixel = [...context.getImageData(
+ Math.round(sample.x),
+ Math.round(sample.y),
+ 1,
+ 1,
+ ).data]
+ const dimensions = { width: bitmap.width, height: bitmap.height }
+ bitmap.close()
+ return { pixel, ...dimensions }
+ }, { captureKind: kind, captureIndex: index, sample: point })
+}
+
+async function waitForRowPhoto(page: Page, messageId: string): Promise<Locator> {
+ const image = page.getByTestId(tid.message(messageId)).locator(
+ '[data-avatar-kind="photo"] [data-slot="avatar-image"]',
+ )
+ await expect.poll(() => image.evaluate((node: HTMLImageElement) => (
+ node.complete && node.naturalWidth > 0
+ ))).toBe(true)
+ return image
+}
+
+function isRedPhoto(pixel: number[]): boolean {
+ return pixel[0]! > 180 && pixel[1]! < 80 && pixel[2]! < 100 && pixel[3] === 255
+}
+
+async function holdNextAvatarRequest(page: Page) {
+ let shouldHold = false
+ let heldRoute: Route | undefined
+ let resolveHeld!: () => void
+ const held = new Promise<void>((resolve) => { resolveHeld = resolve })
+ let getCount = 0
+ await page.route("**/api/community/users/*/avatar*", async (route) => {
+ if (route.request().method() !== "GET") {
+ await route.continue()
+ return
+ }
+ getCount += 1
+ if (!shouldHold || heldRoute) {
+ await route.continue()
+ return
+ }
+ heldRoute = route
+ resolveHeld()
+ })
+ return {
+ arm: () => { shouldHold = true },
+ disarm: () => { shouldHold = false },
+ getCount: () => getCount,
+ wait: async () => {
+ await held
+ return heldRoute!
+ },
+ }
+}
test("consecutive share-image exports reuse rendered avatar, attachment, and invite icon pixels", async ({ asUser }) => {
test.setTimeout(120_000)
@@ -211,3 +412,263 @@ test("consecutive share-image exports reuse rendered avatar, attachment, and inv
expect(pixels.inviteIcon[2]).toBeLessThan(120)
}
})
+
+test("a warm share avatar is a distinct node with the same cached versioned source", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `Warm share avatar ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "warm-share-avatar")
+ const { page } = await asUser("alice")
+ const route = `/c/channels/${serverId}/${channelId}`
+ await gotoAfterUserWsAuth(page, route)
+ const messageId = await seedPhotoMessage(page, channelId, "Warm avatar cache evidence")
+ await gotoAfterUserWsAuth(page, route)
+
+ const rowImage = await waitForRowPhoto(page, messageId)
+ await rowImage.evaluate((image) => {
+ ;(window as typeof window & { __warmRowAvatar?: Element }).__warmRowAvatar = image
+ performance.clearResourceTimings()
+ })
+ await installShareCapture(page)
+ const dialog = await openShareDialog(page, messageId)
+ const card = dialog.locator("[data-share-card]")
+ const shareImage = card.locator('[data-avatar-photo-state="ready"]')
+ await expect(shareImage).toBeVisible()
+ const point = await avatarSamplePoint(card)
+
+ const identity = await shareImage.evaluate((image: HTMLImageElement) => {
+ const row = (window as typeof window & { __warmRowAvatar?: HTMLImageElement }).__warmRowAvatar
+ return {
+ distinct: row !== image,
+ rowSrc: row?.currentSrc,
+ shareSrc: image.currentSrc,
+ }
+ })
+ expect(identity.distinct).toBe(true)
+ expect(identity.rowSrc).toBe(identity.shareSrc)
+ expect(identity.shareSrc).toMatch(/\/api\/community\/users\/[^/]+\/avatar\?v=\d+$/)
+
+ const downloadStarted = page.waitForEvent("download")
+ await dialog.getByRole("button", { name: "Download" }).click()
+ await downloadStarted
+ await dialog.getByRole("button", { name: "Copy image" }).click()
+ await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible()
+
+ expect(await shareCaptureCounts(page)).toEqual({
+ clipboard: 1,
+ clipboardAttempts: 1,
+ download: 1,
+ })
+ expect(isRedPhoto((await capturedPixel(page, "download", 0, point)).pixel)).toBe(true)
+ expect(isRedPhoto((await capturedPixel(page, "clipboard", 0, point)).pixel)).toBe(true)
+ const transfers = await page.evaluate((src) => performance
+ .getEntriesByName(src)
+ .filter((entry): entry is PerformanceResourceTiming => entry.entryType === "resource")
+ .map((entry) => entry.transferSize), identity.shareSrc!)
+ expect(transfers.every((size) => size === 0)).toBe(true)
+})
+
+test("an immediate cold Copy waits for the real photo and owns the whole generation", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `Cold share avatar ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "cold-share-avatar")
+ const { page } = await asUser("alice")
+ const route = `/c/channels/${serverId}/${channelId}`
+ await gotoAfterUserWsAuth(page, route)
+ const messageId = await seedPhotoMessage(page, channelId, "Cold avatar should win before deadline")
+ const avatarRequests = await holdNextAvatarRequest(page)
+ await gotoAfterUserWsAuth(page, route)
+ await waitForRowPhoto(page, messageId)
+ const baselineRequests = avatarRequests.getCount()
+ avatarRequests.arm()
+ await installShareCapture(page)
+ await uploadPhoto(page)
+ const held = await avatarRequests.wait()
+
+ const dialog = await openShareDialog(page, messageId)
+ const card = dialog.locator("[data-share-card]")
+ await expect(card.locator('[data-avatar-photo-state="pending"]')).toBeVisible()
+ const pendingPlaceholder = card.locator('[data-avatar-photo-placeholder="pending"]')
+ await expect(pendingPlaceholder).toBeVisible()
+ await expect(pendingPlaceholder).toHaveClass(/animate-pulse/)
+ await expect(card.locator('[data-avatar-kind="photo"] [data-slot="avatar-fallback"]')).toHaveCount(0)
+ await expect(card.locator('[data-avatar-kind="photo"] svg')).toHaveCount(0)
+ const point = await avatarSamplePoint(card)
+ await page.evaluate((copyTestId) => {
+ const copy = document.querySelector<HTMLButtonElement>(`[data-testid="${copyTestId}"]`)!
+ const dialog = copy.closest('[role="dialog"]')!
+ const download = [...dialog.querySelectorAll<HTMLButtonElement>("button")]
+ .find((button) => button.textContent?.includes("Download"))!
+ copy.click()
+ copy.disabled = false
+ copy.click()
+ download.disabled = false
+ download.click()
+ }, tid.messageShareCopy)
+ avatarRequests.disarm()
+ await held.continue()
+
+ await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible()
+ expect(await shareCaptureCounts(page)).toEqual({
+ clipboard: 1,
+ clipboardAttempts: 1,
+ download: 0,
+ })
+ expect(avatarRequests.getCount()).toBe(baselineRequests + 1)
+ expect(isRedPhoto((await capturedPixel(page, "clipboard", 0, point)).pixel)).toBe(true)
+})
+
+for (const scenario of [
+ { name: "an avatar error", action: "copy", outcome: "abort" },
+ { name: "an avatar timeout", action: "download", outcome: "timeout" },
+] as const) {
+ test(`${scenario.name} exports neutral placeholder pixels and a remount retries the photo`, async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `Fallback share avatar ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, `fallback-${scenario.outcome}`)
+ const { page } = await asUser("alice")
+ const route = `/c/channels/${serverId}/${channelId}`
+ await gotoAfterUserWsAuth(page, route)
+ const messageId = await seedPhotoMessage(page, channelId, `Fallback for ${scenario.outcome}`)
+ const avatarRequests = await holdNextAvatarRequest(page)
+ await gotoAfterUserWsAuth(page, route)
+ await waitForRowPhoto(page, messageId)
+ const baselineRequests = avatarRequests.getCount()
+ avatarRequests.arm()
+ await installShareCapture(page)
+ await uploadPhoto(page)
+ const held = await avatarRequests.wait()
+
+ let dialog = await openShareDialog(page, messageId)
+ const card = dialog.locator("[data-share-card]")
+ await expect(card.locator('[data-avatar-photo-state="pending"]')).toBeVisible()
+ const pendingPlaceholder = card.locator('[data-avatar-photo-placeholder="pending"]')
+ await expect(pendingPlaceholder).toBeVisible()
+ await expect(pendingPlaceholder).toHaveClass(/animate-pulse/)
+ await expect(card.locator('[data-avatar-kind="photo"] [data-slot="avatar-fallback"]')).toHaveCount(0)
+ await expect(card.locator('[data-avatar-kind="photo"] svg')).toHaveCount(0)
+ const fallbackPoint = await avatarSamplePoint(card)
+ const firstDownload = scenario.action === "download" ? page.waitForEvent("download") : null
+ await dialog.getByRole("button", {
+ name: scenario.action === "copy" ? "Copy image" : "Download",
+ }).click()
+ if (scenario.outcome === "abort") await held.abort("failed")
+ if (firstDownload) await firstDownload
+ if (scenario.action === "copy") {
+ await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible({ timeout: 10_000 })
+ } else {
+ await expect(dialog.getByRole("button", { name: "Download" })).toBeEnabled({ timeout: 10_000 })
+ avatarRequests.disarm()
+ await held.abort("failed").catch(() => {})
+ }
+ const failedPlaceholder = card.locator('[data-avatar-photo-placeholder="failed"]')
+ await expect(failedPlaceholder).toBeVisible()
+ await expect(failedPlaceholder).not.toHaveClass(/animate-pulse/)
+
+ const firstKind: CaptureKind = scenario.action === "copy" ? "clipboard" : "download"
+ const fallback = await capturedPixel(page, firstKind, 0, fallbackPoint)
+ expect(fallback.width).toBeGreaterThan(0)
+ expect(fallback.height).toBeGreaterThan(0)
+ expect(fallback.pixel[3]).toBe(255)
+ expect(isRedPhoto(fallback.pixel)).toBe(false)
+ expect(avatarRequests.getCount()).toBe(baselineRequests + 1)
+
+ avatarRequests.disarm()
+ await page.keyboard.press("Escape")
+ await expect(dialog).not.toBeVisible()
+ dialog = await openShareDialog(page, messageId)
+ await expect(dialog.locator('[data-avatar-photo-state="ready"]')).toBeVisible()
+ const retryPoint = await avatarSamplePoint(dialog.locator("[data-share-card]"))
+ await dialog.getByRole("button", { name: "Copy image" }).click()
+ await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible()
+ const retryIndex = scenario.action === "copy" ? 1 : 0
+ expect(isRedPhoto((await capturedPixel(page, "clipboard", retryIndex, retryPoint)).pixel)).toBe(true)
+ })
+}
+
+test("clipboard failure releases retry and Download keeps first-wins ownership", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `Share retry ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "share-retry")
+ const { page } = await asUser("alice")
+ const route = `/c/channels/${serverId}/${channelId}`
+ await gotoAfterUserWsAuth(page, route)
+ const messageId = await seedPhotoMessage(page, channelId, "Retry and first-wins")
+ await gotoAfterUserWsAuth(page, route)
+ await waitForRowPhoto(page, messageId)
+ await installShareCapture(page, true)
+ const dialog = await openShareDialog(page, messageId)
+ await expect(dialog.locator('[data-avatar-photo-state="ready"]')).toBeVisible()
+
+ await dialog.getByRole("button", { name: "Copy image" }).click()
+ await expect(page.getByText("Couldn't copy image — try Download instead", { exact: true })).toBeVisible()
+ await dialog.getByRole("button", { name: "Copy image" }).click()
+ await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible()
+ await expect.poll(() => shareCaptureCounts(page)).toEqual({
+ clipboard: 1,
+ clipboardAttempts: 2,
+ download: 0,
+ })
+ await expect(dialog.getByRole("button", { name: "Copy image" })).toBeVisible({ timeout: 5_000 })
+
+ const downloadStarted = page.waitForEvent("download")
+ await page.evaluate((copyTestId) => {
+ const copy = document.querySelector<HTMLButtonElement>(`[data-testid="${copyTestId}"]`)!
+ const dialog = copy.closest('[role="dialog"]')!
+ const download = [...dialog.querySelectorAll<HTMLButtonElement>("button")]
+ .find((button) => button.textContent?.includes("Download"))!
+ download.click()
+ download.disabled = false
+ download.click()
+ copy.disabled = false
+ copy.click()
+ }, tid.messageShareCopy)
+ await downloadStarted
+ await expect.poll(() => shareCaptureCounts(page)).toEqual({
+ clipboard: 1,
+ clipboardAttempts: 2,
+ download: 1,
+ })
+})
+
+test("closing a cold export suppresses its writer and reopening starts fresh", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `Share close ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "share-close")
+ const { page } = await asUser("alice")
+ const route = `/c/channels/${serverId}/${channelId}`
+ await gotoAfterUserWsAuth(page, route)
+ const messageId = await seedPhotoMessage(page, channelId, "Close invalidates cold export")
+ const avatarRequests = await holdNextAvatarRequest(page)
+ await gotoAfterUserWsAuth(page, route)
+ await waitForRowPhoto(page, messageId)
+ avatarRequests.arm()
+ await installShareCapture(page)
+ await uploadPhoto(page)
+ const held = await avatarRequests.wait()
+
+ let dialog = await openShareDialog(page, messageId)
+ await expect(dialog.locator('[data-avatar-photo-state="pending"]')).toBeVisible()
+ await dialog.getByRole("button", { name: "Copy image" }).click()
+ await expect(dialog.getByRole("button", { name: "Copy image" })).toBeDisabled()
+ await page.keyboard.press("Escape")
+ await expect(dialog).not.toBeVisible()
+ avatarRequests.disarm()
+ await held.continue().catch(() => {})
+ await expect.poll(() => shareCaptureCounts(page)).toEqual({
+ clipboard: 0,
+ clipboardAttempts: 0,
+ download: 0,
+ })
+ await expect(page.getByText("Image copied to clipboard", { exact: true })).toHaveCount(0)
+ await expect(page.getByText("Couldn't copy image — try Download instead", { exact: true })).toHaveCount(0)
+
+ dialog = await openShareDialog(page, messageId)
+ await expect(dialog.locator('[data-avatar-photo-state="ready"]')).toBeVisible()
+ await dialog.getByRole("button", { name: "Copy image" }).click()
+ await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible()
+ await expect.poll(() => shareCaptureCounts(page)).toEqual({
+ clipboard: 1,
+ clipboardAttempts: 1,
+ download: 0,
+ })
+})