Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): preserve loaded avatars while sharing messages (#899)

Gustavo Ye6e059f81368b
diff --git a/src/web/src/components/community/messages/message-share-dialog.dom.test.ts b/src/web/src/components/community/messages/message-share-dialog.dom.test.ts
index fa455ef5d..18a2c6beb 100644
--- a/src/web/src/components/community/messages/message-share-dialog.dom.test.ts
+++ b/src/web/src/components/community/messages/message-share-dialog.dom.test.ts
@@ -435,7 +435,8 @@ describe("MessageShareDialog message projection", () => {
const image = renderer.container.querySelector<HTMLImageElement>(
`[data-testid="${tid.messageShareImage("m1", 0)}"]`,
)!
- expect(image.getAttribute("src")).toBe("/original-photo.png")
+ expect(image.getAttribute("src")).toBeNull()
+ expect(image.getAttribute("data-share-image-src")).toBe("/original-photo.png")
expect(image.alt).toBe("photo.png")
expect(image.width).toBe(1200)
expect(image.height).toBe(800)
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 8543499c1..44b087bf0 100644
--- a/src/web/src/components/community/messages/message-share-dialog.tsx
+++ b/src/web/src/components/community/messages/message-share-dialog.tsx
@@ -14,6 +14,7 @@ import { isDesktop, isMobile, isTauri, stripInlineMarkup } from "@alook/shared"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Avatar } from "../avatar"
+import { ShareImagePreparationContext } from "@/components/remote-image/share-image-context"
import { MessageBody } from "./message-body"
import { attachmentAspectRatio } from "./attachment-layout"
import { tid } from "@/lib/community/testids"
@@ -303,6 +304,7 @@ export function MessageShareDialog({ m, open, onClose }: {
data-share-card-source
className="rounded-xl bg-card p-5 shadow-(--e1)"
>
+ <ShareImagePreparationContext value={true}>
{messages.map((msg) => {
const author = msg.authorId
? readCommunityProfile(profilesByUserId.get(msg.authorId), msg.authorId)
@@ -389,7 +391,7 @@ export function MessageShareDialog({ m, open, onClose }: {
>
<img
data-testid={tid.messageShareImage(msg.id, index)}
- src={attachment.url}
+ data-share-image-src={attachment.url}
alt={attachment.name}
width={attachment.width}
height={attachment.height}
@@ -427,6 +429,7 @@ export function MessageShareDialog({ m, open, onClose }: {
)
})}
+ </ShareImagePreparationContext>
<div className="mt-4 flex items-center gap-1.5 border-t border-border/50 pt-3">
<AnimatedAlookLogo className="size-4" />
<span
diff --git a/src/web/src/components/community/messages/message.render.dom.test.ts b/src/web/src/components/community/messages/message.render.dom.test.ts
index f81fc2b06..b0f3d8bf7 100644
--- a/src/web/src/components/community/messages/message.render.dom.test.ts
+++ b/src/web/src/components/community/messages/message.render.dom.test.ts
@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
import { readFileSync } from "node:fs"
import { resolve } from "node:path"
import React from "react"
-import { act } from "@/test/react-dom-harness"
+import { act, fireEvent } from "@/test/react-dom-harness"
import { renderCommunity as rtlRender } from "@/test/community-owner-harness"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import {
@@ -355,6 +355,53 @@ afterEach(() => {
})
describe("Message memo comparator", () => {
+ it.each([true, false])("selects an external-link message without navigating (hover: %s)", async (hoverCapable) => {
+ const onToggleSelect = vi.fn()
+ const view = rtlRender(makeTree({
+ m: baseMsg({ content: "https://example.com/selection" }),
+ onOpenThread: vi.fn(), onEnterSelect: vi.fn(), onToggleSelect,
+ hoverCapable, selectMode: true, selected: true,
+ }))
+ const link = await view.findByRole("link", { name: "Link: https://example.com/selection" })
+ const click = new MouseEvent("click", { bubbles: true, cancelable: true })
+ act(() => { link.dispatchEvent(click) })
+ expect(click.defaultPrevented).toBe(true)
+ expect(onToggleSelect).toHaveBeenCalledOnce()
+ })
+
+ it.each([true, false])("preserves the activated live avatar through share selection (hover: %s)", (hoverCapable) => {
+ const props = { m: baseMsg(), onOpenThread: vi.fn(), onEnterSelect: vi.fn(), hoverCapable }
+ const view = rtlRender(makeTree(props))
+ if (hoverCapable) {
+ fireEvent.pointerEnter(view.container.querySelector(".group.relative")!, { pointerType: "mouse" })
+ }
+ const avatar = view.container.querySelector("[data-avatar-kind]")
+ expect(avatar).not.toBeNull()
+ view.rerender(makeTree({ ...props, selectMode: true, selected: true }))
+ expect(view.container.querySelector("[data-avatar-kind]")).toBe(avatar)
+ view.rerender(makeTree({ ...props, selectMode: false }))
+ expect(view.container.querySelector("[data-avatar-kind]")).toBe(avatar)
+ })
+
+ it("keeps an inactive desktop row bare while selecting and restores ordinary activation afterward", () => {
+ const props = { m: baseMsg(), onOpenThread: vi.fn(), onEnterSelect: vi.fn(), hoverCapable: true }
+ const view = rtlRender(makeTree(props))
+ const avatar = view.container.querySelector("[data-avatar-kind]")
+ expect(view.container.querySelector("mock-context-menu")).toBeNull()
+ view.rerender(makeTree({ ...props, selectMode: true }))
+ const row = view.container.querySelector(".group.relative")!
+ fireEvent.pointerEnter(row, { pointerType: "mouse" })
+ fireEvent.pointerDown(row, { pointerType: "touch" })
+ fireEvent.focus(row)
+ fireEvent.keyDown(row, { key: "F10", shiftKey: true })
+ expect(view.container.querySelector("[data-avatar-kind]")).toBe(avatar)
+ expect(view.container.querySelector("mock-context-menu")).toBeNull()
+ view.rerender(makeTree(props))
+ expect(view.container.querySelector("[data-avatar-kind]")).toBe(avatar)
+ fireEvent.pointerEnter(view.container.querySelector(".group.relative")!, { pointerType: "mouse" })
+ expect(view.container.querySelector("mock-context-menu")).not.toBeNull()
+ })
+
it("keeps selection controls out of the message row layout", () => {
let renderer: DomRenderer
act(() => {
@@ -1773,9 +1820,7 @@ describe("Message lazy overlays", () => {
const target = { closest: () => authorButton }
act(() => row.props.onPointerEnter({ target }))
- expect(renderer!.root.findAll(
- (node) => node.props["data-slot"] === "context-menu-trigger",
- )).toHaveLength(0)
+ expect(renderer!.root.findAllByType("mock-context-menu")).toHaveLength(0)
const event = { clientX: 10, clientY: 20 }
act(() => authorButton!.props.onClick(event))
@@ -1783,7 +1828,7 @@ describe("Message lazy overlays", () => {
expect(onOpenProfile).toHaveBeenCalledWith("Alice", event, undefined, "u1")
})
- it("does not mount the ContextMenu root until the row is activated", () => {
+ it("keeps the context-menu root and toolbar lazy until activation", () => {
const onOpenThread = vi.fn()
let renderer: DomRenderer
act(() => {
@@ -1793,14 +1838,9 @@ describe("Message lazy overlays", () => {
{ createNodeMock: () => genericMock },
)
})
- // Before activation: the row renders but the ContextMenu content
- // (MessageContextItems) is not in the tree. We assert no element carries the
- // context-menu content marker by checking the rendered JSON has no
- // "ContextMenu"-typed node. A cheap structural proxy: the "Add reaction"
- // toolbar (only mounted when activated) is absent.
const json = renderer!.toJSON()
const tree = JSON.stringify(json)
- // The reaction-add testid only renders inside the activated toolbar.
+ expect(tree).not.toContain("mock-context-menu")
expect(tree).not.toContain("reaction-add")
})
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index ff8d01268..5be80b4c5 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -262,12 +262,6 @@ function MessageImpl({
// "Mark"; flips to "Unmark" silently once the read resolves (no spinner).
const markMenuOpen = (toolbarOpen || contextOpen || touchMenuOpen) && !!onMark
const { data: markedData } = useMessageMarked(m.id, markMenuOpen)
- // Lazy-mount the row's Base UI overlay roots (ContextMenu / DropdownMenu /
- // EmojiPicker Popover / reaction Tooltips). Eagerly mounting them per visible
- // row was the bulk of the switch re-render storm (FloatingTree/MenuRoot ×1000s).
- // Activate on the first
- // hover OR focus OR keydown/contextmenu — focus/keydown are required for a11y
- // (keyboard context menu / Tab-to-row have no pointerenter).
const [activated, setActivated] = useAtom(useCreateAtom(false))
if (m.type === "system") {
@@ -313,12 +307,12 @@ function MessageImpl({
// A hybrid device can alternate between mouse and touch. Switching the menu
// shell after a mouse gesture must not remove the row's touch swipe handler.
const swipeReplyEnabled = interactive && touchInputCapable && !selectMode && !!onReply
- const activateOverlays = interactive && !activated
+ const activateOverlays = interactive && !selectMode && !activated
? (event: React.SyntheticEvent<HTMLElement>) => {
if (shouldActivateMessageOverlays(event.target)) setActivated(true)
}
: undefined
- const activateLinkOrOverlays = interactive && !activated
+ const activateLinkOrOverlays = interactive && !selectMode && !activated
? (event: React.SyntheticEvent<HTMLElement>) => {
if (messageExternalLinkTargetFromEventTarget(event.target)) {
setActivated(true)
@@ -327,7 +321,7 @@ function MessageImpl({
}
}
: undefined
- const activate = interactive
+ const activate = interactive && !selectMode
? (event: React.PointerEvent<HTMLElement>) => {
if (!messageEventBelongsToRow(event.target, event.currentTarget)) return
const pointerType = messageLinkPointerType(event.nativeEvent)
@@ -345,7 +339,7 @@ function MessageImpl({
}
}
: undefined
- const activateFromKeyboard = interactive
+ const activateFromKeyboard = interactive && !selectMode
? (event: React.KeyboardEvent<HTMLElement>) => {
if (!messageEventBelongsToRow(event.target, event.currentTarget)) return
if (
@@ -404,7 +398,7 @@ function MessageImpl({
? { transform: `translate3d(${swipeVisual.offset}px, 0, 0)` }
: undefined}
onPointerEnter={activate}
- onPointerDownCapture={interactive
+ onPointerDownCapture={interactive && !selectMode
? (event) => {
if (!messageEventBelongsToRow(event.target, event.currentTarget)) return
keyboardLinkActivationRef.current = false
@@ -522,7 +516,7 @@ function MessageImpl({
? (event) => {
if (messageEventBelongsToRow(event.target, event.currentTarget)) onToggleSelect?.()
}
- : interactive && touchFallbackActive
+ : interactive && !selectMode && touchFallbackActive
? (event) => {
if (!messageEventBelongsToRow(event.target, event.currentTarget)) return
const selection = window.getSelection()
@@ -553,6 +547,10 @@ function MessageImpl({
onClickCapture={interactive
? (event) => {
if (!messageEventBelongsToRow(event.target, event.currentTarget)) return
+ if (selectMode) {
+ event.preventDefault()
+ return
+ }
const target = messageExternalLinkTargetFromEventTarget(event.target)
if (!target) {
linkPointerRef.current = null
@@ -893,9 +891,7 @@ function MessageImpl({
</div>
)
- // Not interactive → render the bare row. In select mode the row itself is a
- // toggle target, so no action-menu trigger is mounted.
- if (!interactive || selectMode) return row
+ if (!interactive) return row
// Coarse/touch input: tap opens the existing dropdown menu. Deliberately do
// not mount ContextMenuTrigger here — its long-press gesture competes with
@@ -903,9 +899,9 @@ function MessageImpl({
if (touchFallbackActive || touchMenuOpen) {
return (
<DropdownMenu
- open={touchMenuOpen}
+ open={touchMenuOpen && !selectMode}
onOpenChange={(open) => {
- setTouchMenuOpen(open)
+ setTouchMenuOpen(open && !selectMode)
if (!open) setLinkTarget(null)
}}
>
@@ -923,6 +919,7 @@ function MessageImpl({
)}
{row}
<DropdownMenuTrigger
+ disabled={selectMode}
render={(
<button
type="button"
@@ -948,26 +945,22 @@ function MessageImpl({
)
}
- // Not yet activated on desktop → render the bare row (which carries
- // the pointerenter/focus/keydown activation handlers). The row's Base UI
- // ContextMenu root is only mounted once hover/focus has activated it — and a
- // right-click is always preceded by a pointerenter (mouse arriving on the
- // row), and Shift+F10 by focus, so the menu is mounted before it's invoked.
- // (The share-as-image dialog now lives in MessageList — the share button
- // enters multi-select mode; the dialog opens from the select bar there.)
- // In select mode the row is a toggle target — no context menu / toolbar.
if (!activated) return row
return (
<ContextMenu
+ disabled={selectMode}
+ open={contextOpen && !selectMode}
onOpenChange={(open) => {
- setContextOpen(open)
+ setContextOpen(open && !selectMode)
if (!open) setLinkTarget(null)
}}
>
<ContextMenuTrigger className="select-text" render={row} />
- <ContextMenuContent className="w-48">
- <MessageContextItems {...menuHandlers} {...linkMenuHandlers} />
- </ContextMenuContent>
+ {!selectMode && (
+ <ContextMenuContent className="w-48">
+ <MessageContextItems {...menuHandlers} {...linkMenuHandlers} />
+ </ContextMenuContent>
+ )}
</ContextMenu>
)
}
diff --git a/src/web/src/components/remote-image/remote-image.dom.test.ts b/src/web/src/components/remote-image/remote-image.dom.test.ts
index ef987f17d..036e5ba20 100644
--- a/src/web/src/components/remote-image/remote-image.dom.test.ts
+++ b/src/web/src/components/remote-image/remote-image.dom.test.ts
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"
import { act, fireEvent, render, screen } from "@/test/react-dom-harness"
import { RemoteContentImage, RemoteIdentityImage } from "./remote-image"
import { RemoteMarkdownImage } from "./remote-markdown-image"
+import { ShareImagePreparationContext } from "./share-image-context"
import { ApplicationOwnerProvider, createApplicationOwner } from "@/lib/application-owner"
function setImageMetrics(
@@ -28,6 +29,19 @@ afterEach(() => {
})
describe("remote image state adapters", () => {
+ it("keeps remote URLs inert while rendering a share preparation tree", () => {
+ const rendered = render(React.createElement(ShareImagePreparationContext, { value: true },
+ React.createElement(RemoteIdentityImage, { src: "/avatar.png", alt: "Ada" }),
+ React.createElement(RemoteContentImage, { src: "/attachment.png", alt: "Photo" }),
+ React.createElement(RemoteMarkdownImage, { src: "/markdown.png", alt: "Diagram" }),
+ ))
+ const images = [...rendered.container.querySelectorAll("img")]
+ expect(images).toHaveLength(3)
+ expect(images.map((image) => image.getAttribute("data-share-image-src")))
+ .toEqual(["/avatar.png", "/attachment.png", "/markdown.png"])
+ expect(images.every((image) => !image.hasAttribute("src"))).toBe(true)
+ })
+
it("keeps an identity failure neutral and static", () => {
const rendered = render(React.createElement(
"span",
diff --git a/src/web/src/components/remote-image/remote-image.tsx b/src/web/src/components/remote-image/remote-image.tsx
index cf109b4d8..1e02f8965 100644
--- a/src/web/src/components/remote-image/remote-image.tsx
+++ b/src/web/src/components/remote-image/remote-image.tsx
@@ -9,6 +9,7 @@ import {
type MouseEvent,
} from "react"
import { cn } from "@/lib/utils"
+import { useShareImageSource } from "./share-image-context"
import {
useRemoteImageAttempt,
type RemoteImageStatus,
@@ -31,6 +32,7 @@ function IdentityImageAttempt({
profilePhoto = false,
"data-testid": testId,
}: IdentityImageProps) {
+ const sourceProps = useShareImageSource(src)
const [status, attempt, , imageRef, onLoad, onError, retry] = useRemoteImageAttempt()
const retryAfterReconnect = useEffectEvent(() => {
if (status !== "ready") retry()
@@ -64,7 +66,7 @@ function IdentityImageAttempt({
data-avatar-photo-state={profilePhoto ? legacyStatus : undefined}
data-remote-image-kind="identity"
data-remote-image-state={status}
- src={src}
+ {...sourceProps}
alt={alt}
className={cn(
"absolute inset-0 size-full object-cover transition-opacity duration-150 ease-out motion-reduce:transition-none",
@@ -120,6 +122,7 @@ function ContentImageAttempt({
"data-testid": testId,
...imageProps
}: ContentImageProps) {
+ const sourceProps = useShareImageSource(src)
const [status, attempt, readyImage, imageRef, onLoad, onError, retry] = useRemoteImageAttempt()
const notifyReady = useEffectEvent((image: HTMLImageElement) => onReady?.(image))
@@ -149,7 +152,7 @@ function ContentImageAttempt({
data-testid={testId}
data-remote-image-kind="content"
data-remote-image-state={status}
- src={src}
+ {...sourceProps}
alt={alt}
loading={loading}
className={cn(
diff --git a/src/web/src/components/remote-image/remote-markdown-image.tsx b/src/web/src/components/remote-image/remote-markdown-image.tsx
index da28c74de..db3846f7c 100644
--- a/src/web/src/components/remote-image/remote-markdown-image.tsx
+++ b/src/web/src/components/remote-image/remote-markdown-image.tsx
@@ -3,6 +3,7 @@
import { Download } from "lucide-react"
import { FileDownloadButton } from "@/components/file-download-button"
import { cn } from "@/lib/utils"
+import { useShareImageSource } from "./share-image-context"
import { useRemoteImageAttempt } from "./remote-image-attempt"
function dimension(value: unknown): number | undefined {
@@ -27,6 +28,7 @@ function MarkdownImageAttempt({
node,
...rest
}: MarkdownImageProps) {
+ const sourceProps = useShareImageSource(src ?? "")
void node
const [status, attempt, , imageRef, onLoad, onError, retry] = useRemoteImageAttempt()
const imageWidth = dimension(width)
@@ -59,7 +61,7 @@ function MarkdownImageAttempt({
data-streamdown="image"
data-remote-image-kind="content"
data-remote-image-state={status}
- src={src}
+ {...sourceProps}
alt={alt}
width={imageWidth}
height={imageHeight}
diff --git a/src/web/src/components/remote-image/share-image-context.ts b/src/web/src/components/remote-image/share-image-context.ts
new file mode 100644
index 000000000..37bc13e79
--- /dev/null
+++ b/src/web/src/components/remote-image/share-image-context.ts
@@ -0,0 +1,11 @@
+"use client"
+
+import { createContext, useContext } from "react"
+
+export const ShareImagePreparationContext = createContext(false)
+
+export function useShareImageSource(src: string) {
+ return useContext(ShareImagePreparationContext)
+ ? { "data-share-image-src": src, srcSet: undefined }
+ : { src }
+}
diff --git a/src/web/src/lib/community/share-image-session.dom.test.ts b/src/web/src/lib/community/share-image-session.dom.test.ts
index 69aa70d26..f6a288dfa 100644
--- a/src/web/src/lib/community/share-image-session.dom.test.ts
+++ b/src/web/src/lib/community/share-image-session.dom.test.ts
@@ -116,6 +116,107 @@ describe("prepareShareImageSession", () => {
expect(Object.isFrozen(prepared)).toBe(true)
})
+ it("reuses loaded pixels once for deferred duplicate images without fetching or decoding source bytes", async () => {
+ const live = document.createElement("img")
+ live.src = "/loaded.png"
+ Object.defineProperties(live, {
+ complete: { value: true },
+ naturalWidth: { value: 800 },
+ naturalHeight: { value: 400 },
+ })
+ document.body.appendChild(live)
+ const drawImage = vi.fn()
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({ drawImage } as unknown as CanvasRenderingContext2D)
+ vi.spyOn(HTMLCanvasElement.prototype, "toBlob").mockImplementation((callback) => callback(new Blob(["pixels"], { type: "image/png" })))
+ const fetchAsset = vi.fn()
+ const staticizeAsset = vi.fn()
+ const source = sourceCard('<img data-share-image-src="/loaded.png"><img data-share-image-src="/loaded.png">')
+
+ const prepared = await prepareShareImageSession(source, {
+ fetchAsset, staticizeAsset, waitForPaint: async () => {},
+ })
+
+ expect(fetchAsset).not.toHaveBeenCalled()
+ expect(staticizeAsset).not.toHaveBeenCalled()
+ expect(drawImage).toHaveBeenCalledExactlyOnceWith(live, 0, 0, 640, 320)
+ expect(prepared.markup.match(/data-share-byte-backed=/g)).toHaveLength(2)
+ expect(prepared.markup).not.toContain("data-share-image-src")
+ expect(live.isConnected).toBe(true)
+ expect(live.getAttribute("src")).toBe("/loaded.png")
+ expect(source.querySelector("img")?.hasAttribute("src")).toBe(false)
+ })
+
+ it("falls back to the asset path when the browser protects loaded cross-origin pixels", async () => {
+ const live = document.createElement("img")
+ live.src = "https://images.example.test/photo.png"
+ Object.defineProperties(live, {
+ complete: { value: true }, naturalWidth: { value: 10 }, naturalHeight: { value: 10 },
+ })
+ document.body.appendChild(live)
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({ drawImage: vi.fn() } as unknown as CanvasRenderingContext2D)
+ vi.spyOn(HTMLCanvasElement.prototype, "toBlob").mockImplementation(() => { throw new DOMException("Protected pixels", "SecurityError") })
+ const fetchAsset = vi.fn().mockResolvedValue(imageResponse())
+ const source = sourceCard('<img data-share-image-src="https://images.example.test/photo.png">')
+
+ const prepared = await prepare(source, fetchAsset)
+
+ expect(fetchAsset).toHaveBeenCalledTimes(1)
+ expect(prepared.markup).toContain("data-share-byte-backed")
+ })
+
+ it.each(["missing context", "encoder failure", "static budget"])("does not refetch a loaded image after %s", async (failure) => {
+ const live = document.createElement("img")
+ live.src = "/loaded.png"
+ Object.defineProperties(live, {
+ complete: { value: true }, naturalWidth: { value: 10 }, naturalHeight: { value: 10 },
+ })
+ document.body.appendChild(live)
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(failure === "missing context"
+ ? null : { drawImage: vi.fn() } as unknown as CanvasRenderingContext2D)
+ vi.spyOn(HTMLCanvasElement.prototype, "toBlob").mockImplementation((callback) => {
+ if (failure === "encoder failure") throw new Error("Encoder failed")
+ const blob = new Blob(["pixels"], { type: "image/png" })
+ Object.defineProperty(blob, "size", { value: 10 * 1024 * 1024 + 1 })
+ callback(blob)
+ })
+ const fetchAsset = vi.fn()
+ const source = sourceCard('<img data-share-image-src="/loaded.png">')
+
+ await expect(prepare(source, fetchAsset)).rejects.toMatchObject({ stage: "assets" })
+
+ expect(fetchAsset).not.toHaveBeenCalled()
+ expect(live.isConnected).toBe(true)
+ expect(document.querySelector("[data-share-detached-tree]")).toBeNull()
+ })
+
+ it.each([false, true])("keeps identity-proxy failures separate from content sharing the same URL (loaded=%s)", async (loaded) => {
+ const url = "https://images.example.test/shared.png"
+ if (loaded) {
+ const live = document.createElement("img")
+ live.src = url
+ Object.defineProperties(live, {
+ complete: { value: true }, naturalWidth: { value: 10 }, naturalHeight: { value: 10 },
+ })
+ document.body.appendChild(live)
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({ drawImage: vi.fn() } as unknown as CanvasRenderingContext2D)
+ vi.spyOn(HTMLCanvasElement.prototype, "toBlob").mockImplementation(() => { throw new DOMException("Protected pixels", "SecurityError") })
+ }
+ const source = sourceCard(`<span data-share-identity-id="peer"><img data-remote-image-kind="identity" data-share-image-src="${url}"></span><img data-share-image-src="${url}" alt="content">`)
+ const fetchAsset = vi.fn(async (input: RequestInfo | URL) => (
+ String(input).startsWith("/api/community/share-image/avatar/")
+ ? new Response(null, { status: 404 }) : imageResponse()
+ ))
+
+ const prepared = await prepare(source, fetchAsset)
+
+ expect(fetchAsset.mock.calls.map(([input]) => input)).toEqual([
+ "/api/community/share-image/avatar/peer", url,
+ ])
+ expect(prepared.markup).toContain("data-share-identity-fallback")
+ expect(prepared.markup).toContain('alt="content"')
+ expect(prepared.markup).toContain("data-share-byte-backed")
+ })
+
it("resolves same-origin images to immutable bytes without mutating the React source", async () => {
const source = sourceCard('<img src="/content.png" alt="content">')
const fetchAsset = vi.fn().mockResolvedValue(imageResponse())
diff --git a/src/web/src/lib/community/share-image-session.ts b/src/web/src/lib/community/share-image-session.ts
index 0977159c1..0884c417c 100644
--- a/src/web/src/lib/community/share-image-session.ts
+++ b/src/web/src/lib/community/share-image-session.ts
@@ -208,7 +208,7 @@ async function waitForSource(
}
function imageSource(image: HTMLImageElement): string {
- return image.currentSrc || image.getAttribute("src") || ""
+ return image.getAttribute("data-share-image-src") || image.currentSrc || image.getAttribute("src") || ""
}
function imageKind(image: HTMLImageElement): "identity" | "content" {
@@ -358,13 +358,54 @@ function canvasToPng(canvas: HTMLCanvasElement, signal: AbortSignal): Promise<Bl
}
const abort = () => finish(undefined, abortError())
signal.addEventListener("abort", abort, { once: true })
- canvas.toBlob(
- (blob) => finish(blob),
- "image/png",
- )
+ try {
+ canvas.toBlob((blob) => finish(blob), "image/png")
+ } catch (error) {
+ finish(undefined, error)
+ }
})
}
+async function staticizeImage(
+ image: HTMLImageElement | ImageBitmap,
+ target: ShareImageAssetTarget,
+ signal: AbortSignal,
+ budget: ShareImageAssetBudget,
+): Promise<Blob> {
+ throwIfAborted(signal)
+ const loaded = image instanceof HTMLImageElement
+ const width = loaded ? image.naturalWidth : image.width
+ const height = loaded ? image.naturalHeight : image.height
+ if (width <= 0 || height <= 0) throw new Error("Decoded image has no pixels")
+ if (!loaded) consumeDecodedPixels(budget, width, height)
+ const size = staticImageSize(width, height, target)
+ const canvas = document.createElement("canvas")
+ canvas.width = size.width
+ canvas.height = size.height
+ try {
+ const context = canvas.getContext("2d")
+ if (!context) throw new Error("Static image canvas is unavailable")
+ context.drawImage(image, 0, 0, size.width, size.height)
+ const blob = await canvasToPng(canvas, signal)
+ if (loaded) consumeDecodedPixels(budget, size.width, size.height)
+ return blob
+ } finally {
+ canvas.width = 0
+ canvas.height = 0
+ }
+}
+
+function loadedImageSources(source: HTMLElement): Map<string, HTMLImageElement> {
+ const images = new Map<string, HTMLImageElement>()
+ for (const image of document.querySelectorAll<HTMLImageElement>("img")) {
+ if (source.contains(image) || image.closest("[data-share-detached-tree], [data-share-card]")) continue
+ if (!image.complete || image.naturalWidth <= 0 || image.naturalHeight <= 0) continue
+ const url = imageSource(image)
+ if (url) images.set(new URL(url, window.location.href).href, image)
+ }
+ return images
+}
+
async function staticizeImageBlob(
blob: Blob,
target: ShareImageAssetTarget,
@@ -376,27 +417,10 @@ async function staticizeImageBlob(
throw new Error("Static image decoding is unavailable")
}
const bitmap = await createImageBitmap(blob)
- let canvas: HTMLCanvasElement | null = null
try {
- throwIfAborted(signal)
- if (bitmap.width <= 0 || bitmap.height <= 0) {
- throw new Error("Decoded image has no pixels")
- }
- consumeDecodedPixels(budget, bitmap.width, bitmap.height)
- const size = staticImageSize(bitmap.width, bitmap.height, target)
- canvas = document.createElement("canvas")
- canvas.width = size.width
- canvas.height = size.height
- const context = canvas.getContext("2d")
- if (!context) throw new Error("Static image canvas is unavailable")
- context.drawImage(bitmap, 0, 0, size.width, size.height)
- return await canvasToPng(canvas, signal)
+ return await staticizeImage(bitmap, target, signal, budget)
} finally {
bitmap.close()
- if (canvas) {
- canvas.width = 0
- canvas.height = 0
- }
}
}
@@ -518,6 +542,14 @@ function decodeDataUrl(dataUrl: string, signal: AbortSignal): Promise<void> {
})
}
+async function encodeStaticImage(blob: Blob, signal: AbortSignal, budget: ShareImageAssetBudget): Promise<string> {
+ if (blob.type !== "image/png") throw new Error("Static image encoder returned a non-PNG image")
+ consumeStaticBytes(budget, blob.size)
+ const dataUrl = await blobToDataUrl(blob, signal)
+ await decodeDataUrl(dataUrl, signal)
+ return dataUrl
+}
+
async function resolveImage(
image: HTMLImageElement,
fetchAsset: ShareImageFetch,
@@ -527,9 +559,29 @@ async function resolveImage(
budget: ShareImageAssetBudget,
staticizeAsset: ShareImageStaticizer,
enqueueStaticize: ShareImageStaticizeQueue,
+ loadedImages: Map<string, HTMLImageElement>,
): Promise<string | null> {
const kind = imageKind(image)
try {
+ const source = imageSource(image)
+ if (!source) throw new Error("Image source is missing")
+ const cacheKey = new URL(source, window.location.href).href
+ const target = assetTargets.get(cacheKey) ?? assetTarget(image)
+ const loaded = loadedImages.get(cacheKey)
+ if (loaded) {
+ const pixelKey = `pixels:${cacheKey}`
+ let pixels = assetCache.get(pixelKey)
+ if (!pixels) {
+ pixels = enqueueStaticize(() => staticizeImage(loaded, target, signal, budget))
+ .then((blob) => encodeStaticImage(blob, signal, budget))
+ assetCache.set(pixelKey, pixels)
+ }
+ try {
+ return await pixels
+ } catch (error) {
+ if (!(error instanceof DOMException && error.name === "SecurityError")) throw error
+ }
+ }
const request = assetRequest(image)
const cached = assetCache.get(request.cacheKey)
if (cached) return await cached
@@ -546,19 +598,8 @@ async function resolveImage(
})
blob = await readImageResponse(response, signal, budget)
}
- const staticBlob = await enqueueStaticize(() => staticizeAsset(
- blob,
- assetTargets.get(request.cacheKey) ?? assetTarget(image),
- signal,
- budget,
- ))
- if (staticBlob.type !== "image/png") {
- throw new Error("Static image encoder returned a non-PNG image")
- }
- consumeStaticBytes(budget, staticBlob.size)
- const dataUrl = await blobToDataUrl(staticBlob, signal)
- await decodeDataUrl(dataUrl, signal)
- return dataUrl
+ const staticBlob = await enqueueStaticize(() => staticizeAsset(blob, target, signal, budget))
+ return encodeStaticImage(staticBlob, signal, budget)
})()
assetCache.set(request.cacheKey, pending)
return await pending
@@ -594,6 +635,7 @@ function replaceIdentityWithFallback(image: HTMLImageElement): void {
}
function installImageBytes(image: HTMLImageElement, dataUrl: string): void {
+ image.removeAttribute("data-share-image-src")
image.src = dataUrl
image.removeAttribute("srcset")
image.removeAttribute("crossorigin")
@@ -699,6 +741,7 @@ export async function prepareShareImageSession(
))
throwIfAborted(options.signal)
+ const loadedImages = loadedImageSources(source)
const { host, card } = mountDetached(source)
try {
const maxSessionAssetBytes = options.maxSessionAssetBytes ?? SHARE_IMAGE_MAX_SESSION_ASSET_BYTES
@@ -726,8 +769,8 @@ export async function prepareShareImageSession(
const assetTargets = new Map<string, ShareImageAssetTarget>()
for (const image of images) {
try {
- const request = assetRequest(image)
- mergeAssetTarget(assetTargets, request.cacheKey, assetTarget(image))
+ const url = imageSource(image)
+ if (url) mergeAssetTarget(assetTargets, new URL(url, window.location.href).href, assetTarget(image))
} catch {
continue
}
@@ -749,6 +792,7 @@ export async function prepareShareImageSession(
budget,
options.staticizeAsset ?? staticizeImageBlob,
enqueueStaticize,
+ loadedImages,
))
} catch (error) {
if (imageKind(image) === "identity"
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 b3cea2647..cb69e4083 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
@@ -217,7 +217,6 @@ test("image previews keep one frame through loading, decode, failure, retry, and
await page.route(thumbnailPattern, async (route) => {
if (
holdColdThumbnail
- && coldThumbnailRequests === 0
&& route.request().method() === "GET"
) {
coldThumbnailRequests++
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 94232b321..e932a9f23 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,3 +1,5 @@
+import { createServer } from "node:http"
+import type { AddressInfo } from "node:net"
import { expect, test } from "./_fixtures/community-fixture"
import type { Locator, Page } from "@playwright/test"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
@@ -29,6 +31,30 @@ async function solidPng(page: Page, color: string, width: number, height: number
}, { fill: color, targetWidth: width, targetHeight: height })
}
+async function waitForLoadedImages(root: Locator): Promise<void> {
+ await expect.poll(() => root.locator("img").evaluateAll((images: HTMLImageElement[]) => (
+ images.length > 0 && images.every((image) => image.complete && image.naturalWidth > 0)
+ ))).toBe(true)
+ await root.locator("img").evaluateAll((images: HTMLImageElement[]) => (
+ Promise.all(images.map((image) => image.decode()))
+ ))
+}
+
+async function reloadWithUnavailableImage(page: Page, route: string, image: Locator): Promise<void> {
+ await gotoAfterUserWsAuth(page, route)
+ await expect(image).toBeAttached()
+ const source = await image.getAttribute("src")
+ expect(source).toBeTruthy()
+ expect(await page.evaluate((src) => {
+ const url = new URL(src!, location.href).href
+ return [...document.images].filter((candidate) => (
+ (candidate.currentSrc || candidate.src) === url
+ && candidate.complete
+ && candidate.naturalWidth > 0
+ )).length
+ }, source)).toBe(0)
+}
+
async function uploadAvatar(page: Page, color = "rgb(220, 35, 60)"): Promise<void> {
const bytes = await solidPng(page, color, 48, 48)
const status = await page.evaluate(async (png) => {
@@ -421,14 +447,23 @@ test("mobile routing waits for native copy and save terminal receipts", async ({
])
})
-test("a real two-frame GIF is frozen to frame zero before ready and reused by both exports", async ({ asUser }) => {
+test("a loaded two-frame GIF is frozen to a displayed frame and reused by both exports", async ({ asUser }) => {
test.setTimeout(120_000)
const serverId = await seedServer("alice", `Animated share ${Date.now()}`)
const channelId = await seedChannel("alice", serverId, "animated-share")
const { page } = await asUser("alice")
await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
const attachmentId = await uploadAnimatedAttachment(page, channelId)
- const seeded = await seedMessage(page, channelId, "Frame zero stays immutable", [attachmentId])
+ const seeded = await seedMessage(page, channelId, "The displayed animation frame stays immutable", [attachmentId])
+ const row = page.getByTestId(tid.message(seeded.id))
+ await row.hover()
+ await waitForLoadedImages(row)
+ const animatedSource = await row.getByTestId(tid.messageImage(seeded.id, 0)).evaluate((image: HTMLImageElement) => image.currentSrc || image.src)
+ const assetRequests: string[] = []
+ await page.route(animatedSource, async (route) => {
+ assetRequests.push(route.request().url())
+ await route.abort("failed")
+ })
await installShareCapture(page)
const dialog = await openShareDialog(page, seeded.id)
@@ -451,13 +486,15 @@ test("a real two-frame GIF is frozen to frame zero before ready and reused by bo
expect(await captureDigest(page, "clipboard", 0)).toBe(await captureDigest(page, "download", 0))
const copied = await capturePixel(page, "clipboard", 0, point)
const downloaded = await capturePixel(page, "download", 0, point)
- expect(copied.pixel[0]).toBeGreaterThan(200)
- expect(copied.pixel[1]).toBeLessThan(40)
- expect(copied.pixel[2]).toBeLessThan(40)
+ const isRed = copied.pixel[0]! > 200 && copied.pixel[1]! < 40 && copied.pixel[2]! < 40
+ const isBlue = copied.pixel[0]! < 40 && copied.pixel[1]! < 40 && copied.pixel[2]! > 200
+ expect(isRed || isBlue).toBe(true)
+ expect(copied.pixel[3]).toBe(255)
expect(downloaded.pixel).toEqual(copied.pixel)
+ expect(assetRequests).toEqual([])
})
-test("ready preview resolves all assets once and Copy then Download reuse identical PNG bytes", async ({ asUser }) => {
+test("loaded avatar and content prepare and export without requesting or decoding source assets again", async ({ asUser }, testInfo) => {
test.setTimeout(120_000)
const serverId = await seedServer("alice", `Share byte session ${Date.now()}`)
const channelId = await seedChannel("alice", serverId, "share-byte-session")
@@ -471,9 +508,42 @@ test("ready preview resolves all assets once and Copy then Download reuse identi
const seeded = await seedMessage(
page,
channelId,
- `Byte-backed avatar, attachment, invite, and inline logo\n/c/invite/${inviteToken}`,
+ `Loaded avatar, attachment, markdown, invite, and inline logo\n![Inline blue](/api/community/channels/${channelId}/attachments/${attachmentId})\n/c/invite/${inviteToken}`,
[attachmentId],
)
+ const row = page.getByTestId(tid.message(seeded.id))
+ await expect(row.getByTestId(tid.inviteCard(inviteToken))).toBeVisible()
+ await row.hover()
+ await waitForLoadedImages(row)
+ const originals = await row.locator("img").elementHandles()
+ const sourceUrls = await row.locator("img").evaluateAll((images: HTMLImageElement[]) => (
+ [...new Set(images.map((image) => image.currentSrc || image.src))]
+ ))
+ const blockedAssetRequests: string[] = []
+ for (const sourceUrl of sourceUrls) {
+ await page.route(sourceUrl, async (requestRoute) => {
+ blockedAssetRequests.push(requestRoute.request().url())
+ await requestRoute.abort("failed")
+ })
+ }
+ await page.evaluate((urls) => {
+ const tracked = new Set(urls)
+ const state = { imageDecodeSources: [] as string[], bitmapSourceDecodes: 0 }
+ Object.defineProperty(window, "__shareSourceDecodes", { configurable: true, value: state })
+ const nativeDecode = HTMLImageElement.prototype.decode
+ HTMLImageElement.prototype.decode = function () {
+ const url = this.currentSrc || this.src
+ if (tracked.has(url)) state.imageDecodeSources.push(url)
+ return nativeDecode.call(this)
+ }
+ const nativeBitmap = window.createImageBitmap.bind(window)
+ window.createImageBitmap = ((source: ImageBitmapSource, ...args: unknown[]) => {
+ if (source instanceof HTMLImageElement && tracked.has(source.currentSrc || source.src)) {
+ state.bitmapSourceDecodes += 1
+ }
+ return Reflect.apply(nativeBitmap, window, [source, ...args])
+ }) as typeof createImageBitmap
+ }, sourceUrls)
await installShareCapture(page)
const dialog = await openShareDialog(page, seeded.id)
@@ -481,20 +551,18 @@ test("ready preview resolves all assets once and Copy then Download reuse identi
const images = await card.locator("img").evaluateAll((nodes: HTMLImageElement[]) => (
nodes.map((node) => node.currentSrc || node.src)
))
- expect(images.length).toBeGreaterThanOrEqual(3)
+ expect(images.length).toBeGreaterThanOrEqual(4)
expect(images.every((source) => source.startsWith("data:image/"))).toBe(true)
await expect(card.locator('img[src="/alook.svg"]')).toHaveCount(0)
await expect(card.getByTestId(tid.alookLogo)).toBeVisible()
- const frozenMarkup = await card.innerHTML()
- await uploadAvatar(page, "rgb(30, 190, 100)")
- await page.waitForTimeout(250)
- expect(await card.innerHTML()).toBe(frozenMarkup)
+ expect(blockedAssetRequests).toEqual([])
const avatarPoint = await sampleCenter(card, "[data-share-identity-id]")
const attachmentPoint = await sampleCenter(
card,
`[data-testid="${tid.messageShareImage(seeded.id, 0)}"]`,
)
+ const markdownPoint = await sampleCenter(card, 'img[alt="Inline blue"]')
const invitePoint = await sampleCenter(
card,
`[data-testid="${tid.inviteCard(inviteToken)}"] img`,
@@ -514,20 +582,119 @@ test("ready preview resolves all assets once and Copy then Download reuse identi
await dialog.getByRole("button", { name: "Download" }).click()
const download = await downloadStarted
expect(download.suggestedFilename()).toMatch(/^alook-message-.+\.png$/)
+ const exportPath = testInfo.outputPath("warm-source-share.png")
+ await download.saveAs(exportPath)
+ await testInfo.attach("warm-source-share", { path: exportPath, contentType: "image/png" })
await expect.poll(() => captureCounts(page)).toEqual({ clipboard: 1, download: 1 })
expect(networkAfterReady).toEqual([])
+ expect(blockedAssetRequests).toEqual([])
+ expect(await page.evaluate(() => (
+ window as typeof window & {
+ __shareSourceDecodes: { imageDecodeSources: string[]; bitmapSourceDecodes: number }
+ }
+ ).__shareSourceDecodes)).toEqual({ imageDecodeSources: [], bitmapSourceDecodes: 0 })
expect(await captureDigest(page, "clipboard", 0)).toBe(await captureDigest(page, "download", 0))
const avatar = await capturePixel(page, "clipboard", 0, avatarPoint)
const attachment = await capturePixel(page, "clipboard", 0, attachmentPoint)
const invite = await capturePixel(page, "clipboard", 0, invitePoint)
+ const markdown = await capturePixel(page, "clipboard", 0, markdownPoint)
expect(avatar.pixel[0]).toBeGreaterThan(180)
expect(avatar.pixel[1]).toBeLessThan(80)
expect(attachment.pixel[2]).toBeGreaterThan(180)
expect(invite.pixel[1]).toBeGreaterThan(140)
+ expect(markdown.pixel[2]).toBeGreaterThan(180)
+ expect((await capturePixel(page, "download", 0, avatarPoint)).pixel).toEqual(avatar.pixel)
+ expect((await capturePixel(page, "download", 0, attachmentPoint)).pixel).toEqual(attachment.pixel)
+ expect((await capturePixel(page, "download", 0, invitePoint)).pixel).toEqual(invite.pixel)
+ expect((await capturePixel(page, "download", 0, markdownPoint)).pixel).toEqual(markdown.pixel)
const box = await card.boundingBox()
expect(Math.abs(avatar.width - box!.width * 2)).toBeLessThanOrEqual(2)
expect(Math.abs(avatar.height - box!.height * 2)).toBeLessThanOrEqual(2)
+ await page.keyboard.press("Escape")
+ for (const original of originals) {
+ expect(await original.evaluate((image) => image.isConnected && (image as HTMLImageElement).complete && (image as HTMLImageElement).naturalWidth > 0)).toBe(true)
+ }
+ expect(blockedAssetRequests).toEqual([])
+
+ const reopened = await openShareDialog(page, seeded.id)
+ const frozenCard = await waitForReady(reopened)
+ const frozenMarkup = await frozenCard.innerHTML()
+ const liveAvatar = row.locator('[data-slot="avatar-image"]')
+ const previousAvatarSrc = await liveAvatar.getAttribute("src")
+ expect(previousAvatarSrc).toBeTruthy()
+ await uploadAvatar(page, "rgb(30, 190, 100)")
+ await expect(liveAvatar).not.toHaveAttribute("src", previousAvatarSrc!)
+ expect(await frozenCard.innerHTML()).toBe(frozenMarkup)
+})
+
+test("loaded cross-origin pixels without CORS require the explicit fetch fallback", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `Cross-origin share ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "cross-origin-share")
+ const { page } = await asUser("alice")
+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
+ const bytes = Buffer.from(await solidPng(page, "rgb(20, 105, 220)", 96, 64))
+ let allowCors = false
+ const requests: Array<{ mode: string | undefined; corsAllowed: boolean }> = []
+ const origin = createServer((request, response) => {
+ requests.push({ mode: request.headers["sec-fetch-mode"] as string | undefined, corsAllowed: allowCors })
+ response.writeHead(200, {
+ "Content-Type": "image/png",
+ "Cache-Control": "no-store",
+ ...(allowCors ? { "Access-Control-Allow-Origin": "*" } : {}),
+ })
+ response.end(bytes)
+ })
+ await new Promise<void>((resolve) => origin.listen(0, "127.0.0.1", resolve))
+ try {
+ const sourceUrl = `http://127.0.0.1:${(origin.address() as AddressInfo).port}/protected.png`
+ const message = await seedMessage(page, channelId, `![Protected cross-origin](${sourceUrl})`)
+ const row = page.getByTestId(tid.message(message.id))
+ const image = row.locator('img[alt="Protected cross-origin"]')
+ await row.hover()
+ await waitForLoadedImages(row)
+ const original = await image.elementHandle()
+ expect(original).not.toBeNull()
+ const readability = await image.evaluate((source: HTMLImageElement) => {
+ const canvas = document.createElement("canvas")
+ canvas.width = source.naturalWidth
+ canvas.height = source.naturalHeight
+ canvas.getContext("2d")!.drawImage(source, 0, 0)
+ try {
+ canvas.toDataURL("image/png")
+ return "readable"
+ } catch (error) {
+ return error instanceof DOMException ? error.name : String(error)
+ }
+ })
+ expect(readability).toBe("SecurityError")
+ const requestsBeforeShare = requests.length
+ await installShareCapture(page)
+ const dialog = await openShareDialog(page, message.id)
+ await expect(dialog.getByText("Couldn't generate image — preparing images failed")).toBeVisible({ timeout: 15_000 })
+ await expect(dialog.locator("[data-share-card]")).toHaveCount(0)
+ await expect(dialog.getByRole("button", { name: "Copy image" })).toBeDisabled()
+ expect(requests.slice(requestsBeforeShare)).toContainEqual({ mode: "cors", corsAllowed: false })
+ expect(await original!.evaluate((source) => source.isConnected && (source as HTMLImageElement).complete)).toBe(true)
+
+ allowCors = true
+ await dialog.getByRole("button", { name: "Retry" }).click()
+ const card = await waitForReady(dialog)
+ expect(requests.slice(requestsBeforeShare)).toContainEqual({ mode: "cors", corsAllowed: true })
+ await expect(card.locator('img[alt="Protected cross-origin"]')).toHaveAttribute("src", /^data:image\/png;base64,/)
+ const point = await sampleCenter(card, 'img[alt="Protected cross-origin"]')
+ await dialog.getByRole("button", { name: "Copy image" }).click()
+ await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible()
+ const copied = await capturePixel(page, "clipboard", 0, point)
+ expect(copied.pixel[2]).toBeGreaterThan(180)
+ expect(copied.pixel[0]).toBeLessThan(80)
+ await page.keyboard.press("Escape")
+ expect(await original!.evaluate((source) => source.isConnected && (source as HTMLImageElement).complete)).toBe(true)
+ } finally {
+ origin.closeAllConnections()
+ await new Promise<void>((resolve, reject) => origin.close((error) => error ? reject(error) : resolve()))
+ }
})
test("cold preparation disables export until the held avatar bytes are ready", async ({ asUser }) => {
@@ -540,7 +707,6 @@ test("cold preparation disables export until the held avatar bytes are ready", a
await uploadAvatar(page)
const seeded = await seedMessage(page, channelId, "Cold avatar is resolved before export")
await expect(page.getByTestId(tid.message(seeded.id)).locator('[data-slot="avatar-image"]')).toBeVisible()
- await installShareCapture(page)
let release!: () => void
const gate = new Promise<void>((resolve) => { release = resolve })
@@ -553,6 +719,9 @@ test("cold preparation disables export until the held avatar bytes are ready", a
await avatarRoute.continue()
})
+ await reloadWithUnavailableImage(page, route, page.getByTestId(tid.message(seeded.id)).locator('[data-slot="avatar-image"]'))
+ await installShareCapture(page)
+
const dialog = await openShareDialog(page, seeded.id)
await expect.poll(() => heldRequests).toBeGreaterThan(0)
await expect(dialog.locator('[data-share-session-state="preparing"]')).toBeVisible()
@@ -580,7 +749,6 @@ test("closing cold preparation suppresses output and reopening starts a fresh se
await uploadAvatar(page)
const seeded = await seedMessage(page, channelId, "Close invalidates cold preparation")
await expect(page.getByTestId(tid.message(seeded.id)).locator('[data-slot="avatar-image"]')).toBeVisible()
- await installShareCapture(page)
let release!: () => void
const gate = new Promise<void>((resolve) => { release = resolve })
@@ -594,6 +762,9 @@ test("closing cold preparation suppresses output and reopening starts a fresh se
await avatarRoute.continue().catch(() => {})
})
+ await reloadWithUnavailableImage(page, route, page.getByTestId(tid.message(seeded.id)).locator('[data-slot="avatar-image"]'))
+ await installShareCapture(page)
+
let dialog = await openShareDialog(page, seeded.id)
await expect.poll(() => heldRequests).toBeGreaterThan(0)
await expect(dialog.locator('[data-share-session-state="preparing"]')).toBeVisible()
@@ -611,6 +782,46 @@ test("closing cold preparation suppresses output and reopening starts a fresh se
await expect.poll(() => captureCounts(page)).toEqual({ clipboard: 1, download: 0 })
})
+test("loaded live avatar stays mounted through share selection and dialog close", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `Share avatar identity ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "share-avatar-identity")
+ const { page } = await asUser("alice")
+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
+ await uploadAvatar(page)
+ const message = await seedMessage(page, channelId, "Keep the loaded avatar https://example.test/selection")
+ const row = page.getByTestId(tid.message(message.id))
+ const avatar = row.locator('[data-slot="avatar-image"]')
+ await row.hover()
+ await expect(avatar).toHaveAttribute("data-avatar-photo-state", "ready")
+ const original = await avatar.elementHandle()
+ expect(original).not.toBeNull()
+ await page.getByTestId(tid.messageShare(message.id)).click()
+ expect(await original!.evaluate((image) => image.isConnected)).toBe(true)
+ const originalUrl = page.url()
+ const pageCount = page.context().pages().length
+ const link = row.getByRole("link", { name: "Link: https://example.test/selection" })
+ await link.click()
+ await expect(page.getByRole("button", { name: "Share 0 selected messages as image" })).toBeDisabled()
+ await link.click()
+ await expect(page.getByRole("button", { name: "Share 1 selected messages as image" })).toBeEnabled()
+ await row.click({ button: "right" })
+ await expect(page.getByRole("menu")).toHaveCount(0)
+ await page.getByRole("button", { name: "Share 1 selected messages as image" }).click()
+ const dialog = page.getByRole("dialog", { name: "Share message" })
+ await waitForReady(dialog)
+ expect(await original!.evaluate((image) => image.isConnected)).toBe(true)
+ await page.keyboard.press("Escape")
+ await expect(dialog).not.toBeVisible()
+ expect(await original!.evaluate((image) => image.isConnected)).toBe(true)
+ await expect(avatar).toHaveAttribute("data-avatar-photo-state", "ready")
+ expect(page.url()).toBe(originalUrl)
+ expect(page.context().pages()).toHaveLength(pageCount)
+ await row.click({ button: "right" })
+ await expect(page.getByRole("menu")).toBeVisible()
+ await page.keyboard.press("Escape")
+})
+
test("stalled avatar falls back and a single text message exports", async ({ asUser }) => {
test.setTimeout(120_000)
const serverId = await seedServer("alice", `Share avatar timeout ${Date.now()}`)
@@ -620,7 +831,6 @@ test("stalled avatar falls back and a single text message exports", async ({ asU
await uploadAvatar(page)
const message = await seedMessage(page, channelId, "Text survives an unavailable avatar")
await expect(page.getByTestId(tid.message(message.id)).locator('[data-slot="avatar-image"]')).toBeVisible()
- await installShareCapture(page)
let release!: () => void
const blocked = new Promise<void>((resolve) => { release = resolve })
const pattern = "**/api/community/users/*/avatar*"
@@ -629,6 +839,8 @@ test("stalled avatar falls back and a single text message exports", async ({ asU
await route.abort("failed").catch(() => undefined)
})
try {
+ await reloadWithUnavailableImage(page, `/c/channels/${serverId}/${channelId}`, page.getByTestId(tid.message(message.id)).locator('[data-slot="avatar-image"]'))
+ await installShareCapture(page)
const dialog = await openShareDialog(page, message.id)
const card = await waitForReady(dialog)
await expect(card.locator("[data-share-identity-fallback=beam]")).toBeVisible()
@@ -662,6 +874,7 @@ test("avatar failure is deterministic while content-image failure is atomic and
if (avatarRoute.request().method() === "GET") await avatarRoute.abort("failed")
else await avatarRoute.continue()
})
+ await reloadWithUnavailableImage(page, route, page.getByTestId(tid.message(avatarMessage.id)).locator('[data-slot="avatar-image"]'))
let dialog = await openShareDialog(page, avatarMessage.id)
let card = await waitForReady(dialog)
const fallback = card.locator("[data-share-identity-fallback=beam]")
@@ -681,6 +894,7 @@ test("avatar failure is deterministic while content-image failure is atomic and
const attachmentPath = new URL(attachmentUrl!, page.url()).pathname
const attachmentPattern = `**${attachmentPath}*`
await page.route(attachmentPattern, async (attachmentRoute) => attachmentRoute.abort("failed"))
+ await reloadWithUnavailableImage(page, route, rowImage)
dialog = await openShareDialog(page, contentMessage.id)
await expect(dialog.getByText("Couldn't generate image — preparing images failed")).toBeVisible({ timeout: 15_000 })
await expect(dialog.locator("[data-share-card]")).toHaveCount(0)