Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): make share image exports immutable (#779)

Gener71677ac8d2c9
diff --git a/src/web/src/app/api/community/share-image/avatar/[userId]/route.test.ts b/src/web/src/app/api/community/share-image/avatar/[userId]/route.test.ts
new file mode 100644
index 000000000..1987ba380
--- /dev/null
+++ b/src/web/src/app/api/community/share-image/avatar/[userId]/route.test.ts
@@ -0,0 +1,199 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const routeMocks = vi.hoisted(() => ({
+ getPublicProfileForViewer: vi.fn(),
+ getDb: vi.fn(() => ({ db: true })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: routeMocks.getDb }))
+vi.mock("@alook/shared", () => ({
+ queries: {
+ communityUserProfile: {
+ getPublicProfileForViewer: (...args: unknown[]) => routeMocks.getPublicProfileForViewer(...args),
+ },
+ },
+}))
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(req, { env: { DB: "database" }, userId: "viewer-1", params })
+ }),
+}))
+
+import { GET, allowedExternalAvatarUrl } from "./route"
+
+function request(userId = "u2", query = "") {
+ return GET(
+ new NextRequest(`http://localhost/api/community/share-image/avatar/${userId}${query}`),
+ { params: { userId } } as never,
+ )
+}
+
+function imageResponse(size = 3, headers: Record<string, string> = {}) {
+ const bytes = new ArrayBuffer(size)
+ new Uint8Array(bytes).set([1, 2, 3].slice(0, size))
+ return new Response(bytes, {
+ headers: { "Content-Type": "image/png", ...headers },
+ })
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ routeMocks.getPublicProfileForViewer.mockResolvedValue({
+ id: "u2",
+ image: "https://avatars.githubusercontent.com/u/42?v=4&token=private",
+ })
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(imageResponse()))
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+})
+
+describe("allowedExternalAvatarUrl", () => {
+ it.each([
+ "http://avatars.githubusercontent.com/u/1",
+ "https://user:[email protected]/u/1",
+ "https://avatars.githubusercontent.com:444/u/1",
+ "https://avatars.githubusercontent.com.evil.example/u/1",
+ "https://127.0.0.1/avatar.png",
+ "https://169.254.169.254/latest/meta-data",
+ "https://10.0.0.2/avatar.png",
+ "file:///etc/passwd",
+ "not a url",
+ ])("rejects unsafe avatar source %s", (source) => {
+ expect(allowedExternalAvatarUrl(source)).toBeNull()
+ })
+
+ it.each([
+ "https://avatars.githubusercontent.com/u/1",
+ "https://lh3.googleusercontent.com/a/photo",
+ "https://avatars.githubusercontent.com:443/u/1",
+ ])("allows exact HTTPS identity hosts %s", (source) => {
+ expect(allowedExternalAvatarUrl(source)?.href).toBe(new URL(source).href)
+ })
+})
+
+describe("GET /api/community/share-image/avatar/[userId]", () => {
+ it("loads only the viewer-visible profile source and never trusts a client URL", async () => {
+ const response = await request("u2", "?url=http://169.254.169.254/latest/meta-data&token=leak")
+
+ expect(response.status).toBe(200)
+ expect(routeMocks.getDb).toHaveBeenCalledWith("database")
+ expect(routeMocks.getPublicProfileForViewer).toHaveBeenCalledWith(
+ expect.anything(),
+ "u2",
+ "viewer-1",
+ )
+ const fetchMock = vi.mocked(fetch)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ const [target, init] = fetchMock.mock.calls[0]!
+ expect(String(target)).toBe("https://avatars.githubusercontent.com/u/42?v=4&token=private")
+ expect(init).toMatchObject({ redirect: "manual" })
+ expect(init).not.toHaveProperty("credentials")
+ const headers = new Headers(init?.headers)
+ expect(headers.get("authorization")).toBeNull()
+ expect(headers.get("cookie")).toBeNull()
+ expect(response.headers.get("content-type")).toBe("image/png")
+ expect(response.headers.get("cache-control")).toBe("private, max-age=300")
+ expect(response.headers.get("x-content-type-options")).toBe("nosniff")
+ expect([...new Uint8Array(await response.arrayBuffer())]).toEqual([1, 2, 3])
+ })
+
+ it.each([
+ null,
+ "http://avatars.githubusercontent.com/u/1",
+ "https://127.0.0.1/avatar.png",
+ "https://example.com/avatar.png",
+ ])("rejects missing or non-allowlisted stored source %s without fetching", async (image) => {
+ routeMocks.getPublicProfileForViewer.mockResolvedValue({ id: "u2", image })
+
+ const response = await request()
+
+ expect(response.status).toBe(404)
+ expect(fetch).not.toHaveBeenCalled()
+ })
+
+ it("rejects upstream redirects before a private-network hop", async () => {
+ vi.mocked(fetch).mockResolvedValueOnce(new Response(null, {
+ status: 302,
+ headers: { Location: "http://127.0.0.1/admin" },
+ }))
+
+ const response = await request()
+
+ expect(response.status).toBe(502)
+ expect(await response.json()).toEqual({ error: "external avatar redirect rejected" })
+ })
+
+ it("rejects non-image responses", async () => {
+ vi.mocked(fetch).mockResolvedValueOnce(new Response("not an image", {
+ headers: { "Content-Type": "text/html" },
+ }))
+
+ const response = await request()
+
+ expect(response.status).toBe(502)
+ expect(await response.json()).toEqual({ error: "external avatar unavailable" })
+ })
+
+ it("rejects an oversized response before reading its body", async () => {
+ vi.mocked(fetch).mockResolvedValueOnce(imageResponse(0, {
+ "Content-Length": String(5 * 1024 * 1024 + 1),
+ }))
+
+ const response = await request()
+
+ expect(response.status).toBe(502)
+ expect(await response.json()).toEqual({ error: "external avatar unavailable" })
+ })
+
+ it("stops an oversized streamed response without a declared length", async () => {
+ const chunk = new Uint8Array(3 * 1024 * 1024)
+ vi.mocked(fetch).mockResolvedValueOnce(new Response(new ReadableStream({
+ start(controller) {
+ controller.enqueue(chunk)
+ controller.enqueue(chunk)
+ controller.close()
+ },
+ }), { headers: { "Content-Type": "image/png" } }))
+
+ const response = await request()
+
+ expect(response.status).toBe(502)
+ expect(await response.json()).toEqual({ error: "external avatar unavailable" })
+ })
+
+ it("times out the upstream fetch at the fixed bound", async () => {
+ vi.useFakeTimers()
+ vi.mocked(fetch).mockImplementationOnce((_target, init) => new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => {
+ reject(new DOMException("aborted", "AbortError"))
+ }, { once: true })
+ }))
+ const pending = request()
+
+ await vi.advanceTimersByTimeAsync(5_000)
+ const response = await pending
+
+ expect(response.status).toBe(504)
+ expect(await response.json()).toEqual({ error: "external avatar timed out" })
+ })
+
+ it("does not log the stored URL when upstream fetching fails", async () => {
+ const log = vi.spyOn(console, "log").mockImplementation(() => {})
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
+ const error = vi.spyOn(console, "error").mockImplementation(() => {})
+ vi.mocked(fetch).mockRejectedValueOnce(new Error("network failed"))
+
+ const response = await request()
+
+ expect(response.status).toBe(502)
+ expect(log).not.toHaveBeenCalled()
+ expect(warn).not.toHaveBeenCalled()
+ expect(error).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/share-image/avatar/[userId]/route.ts b/src/web/src/app/api/community/share-image/avatar/[userId]/route.ts
new file mode 100644
index 000000000..06f0f707c
--- /dev/null
+++ b/src/web/src/app/api/community/share-image/avatar/[userId]/route.ts
@@ -0,0 +1,117 @@
+import { NextRequest } from "next/server"
+import { queries } from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeError } from "@/lib/middleware/helpers"
+
+const ALLOWED_AVATAR_HOSTS = new Set([
+ "avatars.githubusercontent.com",
+ "lh3.googleusercontent.com",
+])
+const ALLOWED_IMAGE_TYPES = new Set([
+ "image/avif",
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/webp",
+])
+const MAX_AVATAR_BYTES = 5 * 1024 * 1024
+const AVATAR_FETCH_TIMEOUT_MS = 5_000
+
+export function allowedExternalAvatarUrl(value: string): URL | null {
+ let url: URL
+ try {
+ url = new URL(value)
+ } catch {
+ return null
+ }
+ if (
+ url.protocol !== "https:"
+ || url.username
+ || url.password
+ || (url.port && url.port !== "443")
+ || !ALLOWED_AVATAR_HOSTS.has(url.hostname.toLowerCase())
+ ) return null
+ return url
+}
+
+async function readLimitedImage(response: Response): Promise<{ bytes: Uint8Array; type: string }> {
+ if (!response.ok || response.status >= 300) throw new Error("avatar request failed")
+ const type = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? ""
+ if (!ALLOWED_IMAGE_TYPES.has(type)) throw new Error("avatar response is not a supported image")
+ const contentLength = Number(response.headers.get("content-length") ?? "0")
+ if (Number.isFinite(contentLength) && contentLength > MAX_AVATAR_BYTES) {
+ throw new Error("avatar response is too large")
+ }
+ if (!response.body) throw new Error("avatar response body is missing")
+
+ const reader = response.body.getReader()
+ const chunks: Uint8Array[] = []
+ let size = 0
+ try {
+ while (true) {
+ const result = await reader.read()
+ if (result.done) break
+ size += result.value.byteLength
+ if (size > MAX_AVATAR_BYTES) {
+ await reader.cancel()
+ throw new Error("avatar response is too large")
+ }
+ chunks.push(result.value)
+ }
+ } finally {
+ reader.releaseLock()
+ }
+
+ const bytes = new Uint8Array(size)
+ let offset = 0
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset)
+ offset += chunk.byteLength
+ }
+ return { bytes, type }
+}
+
+export const GET = withAuth(async (_req: NextRequest, ctx) => {
+ const userId = ctx.params?.userId
+ if (!userId) return writeError("missing user id", 400)
+
+ const profile = await queries.communityUserProfile.getPublicProfileForViewer(
+ getDb(ctx.env.DB),
+ userId,
+ ctx.userId,
+ )
+ const source = profile?.image ? allowedExternalAvatarUrl(profile.image) : null
+ if (!source) return writeError("external avatar not found", 404)
+
+ const controller = new AbortController()
+ const timer = setTimeout(() => controller.abort(), AVATAR_FETCH_TIMEOUT_MS)
+ try {
+ const response = await fetch(source, {
+ redirect: "manual",
+ signal: controller.signal,
+ headers: { Accept: [...ALLOWED_IMAGE_TYPES].join(", ") },
+ })
+ if (response.status >= 300 && response.status < 400) {
+ return writeError("external avatar redirect rejected", 502)
+ }
+ const image = await readLimitedImage(response)
+ const body = new ArrayBuffer(image.bytes.byteLength)
+ new Uint8Array(body).set(image.bytes)
+ return new Response(body, {
+ headers: {
+ "Content-Type": image.type,
+ "Content-Length": String(image.bytes.byteLength),
+ "Cache-Control": "private, max-age=300",
+ "X-Content-Type-Options": "nosniff",
+ },
+ })
+ } catch {
+ return writeError(
+ controller.signal.aborted ? "external avatar timed out" : "external avatar unavailable",
+ controller.signal.aborted ? 504 : 502,
+ )
+ } finally {
+ clearTimeout(timer)
+ }
+})
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 a7e5ed519..a97873d6c 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
@@ -1,21 +1,14 @@
-import { afterEach, describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import React from "react"
import { act, render } from "@/test/react-dom-harness"
import { toBlob } from "html-to-image"
import { toast } from "sonner"
import {
MessageShareDialog,
- ShareCardImageTimeoutError,
ShareCardRenderError,
- ShareImageSnapshotError,
- type ShareCardImageDisposition,
copyRenderedShareCard,
- createShareImageSnapshot,
downloadRenderedShareCard,
- renderShareCard,
shareCardRenderErrorMessage,
- snapshotShareCardImages,
- waitForShareCardImages,
writeShareCardToClipboard,
} from "./message-share-dialog"
import type { RenderMsg } from "@/lib/community/models/message"
@@ -26,24 +19,49 @@ const profileState = vi.hoisted(() => ({ map: new Map<string, Record<string, unk
const componentMocks = vi.hoisted(() => ({
avatarProps: vi.fn(),
bodyProps: vi.fn(),
- buttonProps: vi.fn(),
dialogProps: vi.fn(),
}))
+const sessionMocks = vi.hoisted(() => ({
+ prepare: vi.fn(),
+ capture: vi.fn(),
+}))
+
vi.mock("@/stores/community/ws", () => ({
useProfilesByUserId: () => profileState.map,
}))
-
+vi.mock("@/lib/community/share-image-session", () => {
+ class ShareImageSessionError extends Error {
+ constructor(
+ readonly stage: "source" | "assets" | "fonts" | "freeze" | "rasterize",
+ readonly timedOut = false,
+ cause?: unknown,
+ ) {
+ super(`Share image failed during ${stage}`)
+ this.name = "ShareImageSessionError"
+ this.cause = cause
+ }
+ }
+ return {
+ ShareImageSessionError,
+ prepareShareImageSession: sessionMocks.prepare,
+ capturePreparedShareImage: sessionMocks.capture,
+ }
+})
vi.mock("html-to-image", () => ({ toBlob: vi.fn() }))
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
-vi.mock("next/image", () => ({
- default: (props: React.ComponentProps<"img">) => props.src === "/alook.svg"
- ? React.createElement("span", { "data-alook-logo": "" })
- : React.createElement("img", props),
+vi.mock("@/components/community/shell/animated-alook-logo", () => ({
+ AnimatedAlookLogo: (props: React.ComponentProps<"svg">) => React.createElement(
+ "svg",
+ { ...props, "data-inline-alook-logo": "", viewBox: "0 0 16 16" },
+ React.createElement("path", { d: "M0 0h16v16H0z" }),
+ ),
}))
vi.mock("../avatar", () => ({
Avatar: (props: Record<string, unknown>) => {
componentMocks.avatarProps(props)
- return React.createElement("div", { "data-mock-avatar": "" })
+ return props.src
+ ? React.createElement("img", { src: props.src, "data-avatar-photo-state": "ready" })
+ : React.createElement("span", { "data-avatar-kind": "beam" })
},
}))
vi.mock("./message-body", () => ({
@@ -53,10 +71,10 @@ vi.mock("./message-body", () => ({
},
}))
vi.mock("@/components/ui/button", () => ({
- Button: (props: React.ComponentProps<"button">) => {
- componentMocks.buttonProps(props)
- return React.createElement("button", props)
- },
+ Button: ({ variant: _variant, size: _size, ...props }: React.ComponentProps<"button"> & {
+ variant?: string
+ size?: string
+ }) => React.createElement("button", props),
}))
vi.mock("@/components/ui/dialog", () => {
const Passthrough = ({ children }: { children?: React.ReactNode }) => children
@@ -83,64 +101,213 @@ function message(overrides: Partial<RenderMsg> = {}): RenderMsg {
}
}
-function renderMessage(
- m: RenderMsg,
-) {
+function preparedFrom(source: HTMLElement) {
+ const card = source.cloneNode(true) as HTMLElement
+ card.removeAttribute("data-share-card-source")
+ card.setAttribute("data-share-card", "")
+ card.dataset.shareSessionState = "ready"
+ return Object.freeze({
+ markup: card.outerHTML,
+ width: 672,
+ height: 240,
+ backgroundColor: "rgb(255, 255, 255)",
+ fontEmbedCSS: "@font-face{font-family:brand;src:url(data:font/woff2;base64,AA==)}",
+ })
+}
+
+function renderMessage(m: RenderMsg | RenderMsg[] = message()) {
+ const values = Array.isArray(m) ? m : [m]
profileState.map = new Map()
- if (m.authorId) {
- profileState.map.set(m.authorId, {
- id: m.authorId,
- name: m.authorName,
- ...(m.authorAvatar ? { avatar: m.authorAvatar } : {}),
- avatarVersion: m.authorAvatarVersion ?? 0,
+ for (const value of values) {
+ if (!value.authorId) continue
+ profileState.map.set(value.authorId, {
+ id: value.authorId,
+ name: value.authorName,
+ ...(value.authorAvatar ? { avatar: value.authorAvatar } : {}),
+ avatarVersion: value.authorAvatarVersion ?? 0,
})
}
- return render(React.createElement(MessageShareDialog, {
- m,
- open: true,
- onClose: vi.fn(),
- }))
+ return render(React.createElement(MessageShareDialog, { m, open: true, onClose: vi.fn() }))
}
-function latestCapturedProps(
- capture: ReturnType<typeof vi.fn>,
- predicate: (props: Record<string, unknown>) => boolean = () => true,
-) {
- const props = capture.mock.calls
- .toReversed()
- .map(([value]) => value as Record<string, unknown>)
- .find(predicate)
- if (!props) throw new Error("Expected captured component props")
- return props
+async function renderReady(m: RenderMsg | RenderMsg[] = message()) {
+ const renderer = renderMessage(m)
+ await vi.waitFor(() => {
+ expect(renderer.container.querySelector('[data-share-session-state="ready"]')).not.toBeNull()
+ })
+ return renderer
}
-function capturedNode(
- capture: ReturnType<typeof vi.fn>,
- predicate: (props: Record<string, unknown>) => boolean = () => true,
-) {
- return {
- get props() {
- return latestCapturedProps(capture, predicate) as Record<string, unknown> & {
- disabled?: boolean
- onClick: () => Promise<void>
- onOpenChange: (open: boolean) => void
- }
- },
- get children() { return React.Children.toArray(latestCapturedProps(capture, predicate).children) },
- }
+function buttonWithText(container: HTMLElement, text: string): HTMLButtonElement {
+ const button = [...container.querySelectorAll("button")]
+ .find((candidate) => candidate.textContent?.includes(text))
+ if (!button) throw new Error(`Missing ${text} button`)
+ return button
}
-function actionButton(testId?: string, text?: string) {
- return capturedNode(componentMocks.buttonProps, (props) => (
- (testId === undefined || props["data-testid"] === testId)
- && (text === undefined || React.Children.toArray(props.children).includes(text))
- ))
+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 }
}
-describe("MessageShareDialog message context", () => {
- it("renders the live message timestamp beside the author", () => {
+class ClipboardItemStub {
+ constructor(readonly items: Record<string, Blob>) {}
+}
+
+function installWebClipboard(write = vi.fn().mockResolvedValue(undefined)) {
+ vi.stubGlobal("ClipboardItem", ClipboardItemStub)
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: { write },
+ })
+ return write
+}
+
+function installMobileNative(invoke: ReturnType<typeof vi.fn>) {
+ Object.defineProperty(window, "__TAURI__", {
+ configurable: true,
+ value: { core: { invoke } },
+ })
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue("iPhone")
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ sessionMocks.prepare.mockImplementation(async (source: HTMLElement) => preparedFrom(source))
+ sessionMocks.capture.mockImplementation(async (
+ source: HTMLElement,
+ fontEmbedCSS: string,
+ rasterize: typeof toBlob,
+ options: { signal?: AbortSignal },
+ ) => {
+ if (options.signal?.aborted) throw new DOMException("aborted", "AbortError")
+ const blob = await rasterize(source, { fontEmbedCSS })
+ if (!blob) throw new ShareCardRenderError("rasterize")
+ return blob
+ })
+ vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
+})
+
+afterEach(() => {
+ Reflect.deleteProperty(window, "__TAURI__")
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+})
+
+describe("MessageShareDialog session lifecycle", () => {
+ it("keeps export actions disabled until the immutable preview is ready", async () => {
+ const preparation = deferred<ReturnType<typeof preparedFrom>>()
+ sessionMocks.prepare.mockReturnValueOnce(preparation.promise)
+ const renderer = renderMessage()
+
+ await vi.waitFor(() => expect(sessionMocks.prepare).toHaveBeenCalledTimes(1))
+ expect(renderer.container.querySelector("[data-share-card-source]")).not.toBeNull()
+ expect(renderer.container.querySelector("[data-share-card]")).toBeNull()
+ expect(buttonWithText(renderer.container, "Download").disabled).toBe(true)
+ expect(buttonWithText(renderer.container, "Copy image").disabled).toBe(true)
+
+ await act(async () => preparation.resolve(preparedFrom(
+ sessionMocks.prepare.mock.calls[0]![0] as HTMLElement,
+ )))
+
+ expect(renderer.container.querySelector("[data-share-card-source]")).toBeNull()
+ expect(renderer.container.querySelector("[data-share-card]")).not.toBeNull()
+ expect(buttonWithText(renderer.container, "Download").disabled).toBe(false)
+ expect(buttonWithText(renderer.container, "Copy image").disabled).toBe(false)
+ })
+
+ it("renders message context and an inline brand SVG in the prepared preview", async () => {
+ const createdAt = "2026-08-13T03:17:00.000Z"
+ const renderer = await renderReady(message({
+ createdAt,
+ authorAvatar: "https://avatars.githubusercontent.com/u/1?v=4",
+ content: "@Bob\n**visible** body",
+ replyTo: { id: "original", authorName: "Bob", text: "Original **body**" },
+ attachments: [
+ { kind: "image", name: "photo.png", url: "/photo.png", width: 800, height: 400 },
+ { kind: "file", name: "notes.txt", url: "/notes.txt" },
+ ],
+ reactions: [{ emoji: "👍", count: 2, me: true, userIds: ["u1"] }],
+ }))
+ const preview = renderer.container.querySelector('[data-share-session-state="ready"]')!
+
+ expect(preview.querySelector("[data-share-timestamp]")?.textContent).toBe(formatMessageTime(createdAt))
+ expect(preview.querySelector('[data-testid="message-share-reply-m1"]')?.textContent)
+ .toContain("Original body")
+ expect(preview.querySelector("[data-mock-message-body]")?.textContent).toBe("**visible** body")
+ expect(preview.querySelector('[data-testid="message-share-image-m1-0"]')).not.toBeNull()
+ expect(preview.textContent).not.toContain("notes.txt")
+ expect(preview.querySelector("[data-share-identity-id=u1]")).not.toBeNull()
+ expect(preview.querySelector("svg[data-inline-alook-logo]")).not.toBeNull()
+ expect(preview.querySelector('img[src="/alook.svg"]')).toBeNull()
+ expect(preview.querySelector("[data-share-brand]")?.getAttribute("data-share-brand-font"))
+ .toBe("caveat")
+ })
+
+ it("keeps the ready preview frozen across profile-store rerenders", async () => {
+ const shared = message({ authorAvatar: "/api/community/users/u1/avatar?v=1" })
+ const renderer = await renderReady(shared)
+ const card = renderer.container.querySelector("[data-share-card]")!
+ const markup = card.outerHTML
+ profileState.map = new Map([["u1", {
+ id: "u1",
+ name: "Changed live profile",
+ avatar: "/api/community/users/u1/avatar?v=2",
+ avatarVersion: 2,
+ }]])
+
+ renderer.rerender(React.createElement(MessageShareDialog, {
+ m: shared,
+ open: true,
+ onClose: vi.fn(),
+ }))
+ await act(async () => Promise.resolve())
+
+ expect(sessionMocks.prepare).toHaveBeenCalledTimes(1)
+ expect(renderer.container.querySelector("[data-share-card]")?.outerHTML).toBe(markup)
+ })
+
+ it("shows a typed preparation error and retries from the source tree", async () => {
+ sessionMocks.prepare
+ .mockRejectedValueOnce(new ShareCardRenderError("assets", true))
+ .mockImplementationOnce(async (source: HTMLElement) => preparedFrom(source))
+ const renderer = renderMessage()
+
+ await vi.waitFor(() => expect(renderer.container.textContent).toContain("preparing images took too long"))
+ expect(buttonWithText(renderer.container, "Copy image").disabled).toBe(true)
+
+ await act(async () => buttonWithText(renderer.container, "Retry").click())
+ await vi.waitFor(() => expect(renderer.container.querySelector("[data-share-card]")).not.toBeNull())
+ expect(sessionMocks.prepare).toHaveBeenCalledTimes(2)
+ })
+
+ it("applies highlights only to the immutable preview and invalidates its PNG", async () => {
+ const renderer = await renderReady(message({ content: "highlight this text" }))
+ const body = renderer.container.querySelector<HTMLElement>("[data-share-body-id=m1]")!
+ const text = body.querySelector("[data-mock-message-body]")!.firstChild!
+ const selection = window.getSelection()!
+ const range = document.createRange()
+ range.setStart(text, 0)
+ range.setEnd(text, 9)
+ selection.removeAllRanges()
+ selection.addRange(range)
+
+ await act(async () => body.dispatchEvent(new MouseEvent("mouseup", { bubbles: true })))
+
+ expect(body.querySelector("mark[data-hl]")?.textContent).toBe("highlight")
+ expect(buttonWithText(renderer.container, "Reset highlight")).not.toBeNull()
+ })
+})
+
+describe("MessageShareDialog message projection", () => {
+ it("renders the live message timestamp beside the author", async () => {
const createdAt = "2026-08-13T03:17:00.000Z"
- const renderer = renderMessage(message({ createdAt }))
+ const renderer = await renderReady(message({ createdAt }))
const timestamp = renderer.container.querySelector("[data-share-timestamp]")!
expect(timestamp.textContent).toBe(formatMessageTime(createdAt))
@@ -150,8 +317,8 @@ describe("MessageShareDialog message context", () => {
expect(timestamp.parentElement?.classList).toContain("gap-2")
})
- it("keeps the author and timestamp collapsed for grouped follow-ups", () => {
- const renderer = renderMessage(message({
+ it("keeps the author and timestamp collapsed for grouped follow-ups", async () => {
+ const renderer = await renderReady(message({
grouped: true,
createdAt: "2026-08-13T03:18:00.000Z",
}))
@@ -159,17 +326,18 @@ describe("MessageShareDialog message context", () => {
expect(renderer.container.querySelector("[data-share-timestamp]")).toBeNull()
})
- it("passes the custom avatar URL as an image source, not as fallback copy", () => {
- renderMessage(message({ authorAvatar: "/api/community/users/u1/avatar" }))
- expect(latestCapturedProps(componentMocks.avatarProps)).toMatchObject({
+ it("passes the custom avatar URL as an image source, not as fallback copy", async () => {
+ await renderReady(message({ authorAvatar: "/api/community/users/u1/avatar" }))
+
+ expect(componentMocks.avatarProps).toHaveBeenCalledWith(expect.objectContaining({
label: "Alice",
src: "/api/community/users/u1/avatar",
seed: "u1",
- })
+ }))
})
- it("renders the reply author and plain-text excerpt above the shared message", () => {
- const renderer = renderMessage(message({
+ it("renders the reply author and plain-text excerpt above the shared message", async () => {
+ const renderer = await renderReady(message({
replyTo: {
id: "original",
authorName: "Bob",
@@ -184,8 +352,8 @@ describe("MessageShareDialog message context", () => {
])
})
- it("keeps the reply header while sharing only projected message content", () => {
- const renderer = renderMessage(message({
+ it("keeps the reply header while sharing only projected message content", async () => {
+ const renderer = await renderReady(message({
content: "@Bob Smith\n**visible** body",
replyTo: {
id: "original",
@@ -194,7 +362,9 @@ describe("MessageShareDialog message context", () => {
},
}))
- expect(latestCapturedProps(componentMocks.bodyProps).text).toBe("**visible** body")
+ expect(componentMocks.bodyProps).toHaveBeenCalledWith(expect.objectContaining({
+ text: "**visible** body",
+ }))
const reply = renderer.container.querySelector('[data-testid="message-share-reply-m1"]')!
expect([...reply.querySelectorAll("span")].map((span) => span.textContent)).toEqual([
"@Bob Smith",
@@ -202,20 +372,20 @@ describe("MessageShareDialog message context", () => {
])
})
- it("omits a standalone body for an attachment-only canonical reply", () => {
- const renderer = renderMessage(message({
+ it("omits a standalone body for an attachment-only canonical reply", async () => {
+ const renderer = await renderReady(message({
content: "@Bob\n",
replyTo: { id: "original", authorName: "Bob", text: "Original body" },
attachments: [{ kind: "image", name: "photo.png", url: "/photo.png" }],
}))
expect(renderer.container.querySelectorAll("[data-mock-message-body]")).toHaveLength(0)
- expect(renderer.container.querySelector('[data-testid="message-share-image-m1-0"]'))
+ expect(renderer.container.querySelector(`[data-testid="${tid.messageShareImage("m1", 0)}"]`))
.not.toBeNull()
})
- it("renders the deleted-original state without stale reply details", () => {
- const renderer = renderMessage(message({
+ it("renders the deleted-original state without stale reply details", async () => {
+ const renderer = await renderReady(message({
replyTo: {
id: "original",
authorName: "Bob",
@@ -225,12 +395,13 @@ describe("MessageShareDialog message context", () => {
}))
const reply = renderer.container.querySelector('[data-testid="message-share-reply-m1"]')!
- const text = [...reply.querySelectorAll("span")].map((span) => span.textContent)
- expect(text).toEqual(["Original message was deleted"])
+ expect([...reply.querySelectorAll("span")].map((span) => span.textContent)).toEqual([
+ "Original message was deleted",
+ ])
})
- it("renders every emoji reaction with its count", () => {
- const renderer = renderMessage(message({
+ it("renders every emoji reaction with its count", async () => {
+ const renderer = await renderReady(message({
reactions: [
{ emoji: "👍", count: 2, me: true, userIds: ["u1", "u2"] },
{ emoji: "🎉", count: 11, me: false, userIds: [] },
@@ -238,12 +409,13 @@ describe("MessageShareDialog message context", () => {
}))
const reactions = renderer.container.querySelector('[data-testid="message-share-reactions-m1"]')!
- const text = [...reactions.querySelectorAll("span")].map((span) => span.textContent)
- expect(text).toEqual(expect.arrayContaining(["👍", "2", "🎉", "11"]))
+ expect([...reactions.querySelectorAll("span")].map((span) => span.textContent)).toEqual(
+ expect.arrayContaining(["👍", "2", "🎉", "11"]),
+ )
})
- it("renders attached originals at their intrinsic ratio and omits files", () => {
- const renderer = renderMessage(message({
+ it("renders attached originals at intrinsic ratio and omits files", async () => {
+ const renderer = await renderReady(message({
attachments: [
{
kind: "image",
@@ -258,7 +430,7 @@ describe("MessageShareDialog message context", () => {
}))
const image = renderer.container.querySelector<HTMLImageElement>(
- '[data-testid="message-share-image-m1-0"]',
+ `[data-testid="${tid.messageShareImage("m1", 0)}"]`,
)!
expect(image.getAttribute("src")).toBe("/original-photo.png")
expect(image.alt).toBe("photo.png")
@@ -268,17 +440,14 @@ describe("MessageShareDialog message context", () => {
expect(image.style.aspectRatio).toBe("1200/800")
expect(image.className).toContain("max-h-75")
expect(image.className).toContain("max-w-full")
- expect(image.className).toContain("rounded-lg")
expect(image.className).toContain("object-contain")
expect(image.parentElement?.className).toContain("w-fit")
- expect(image.parentElement?.className).toContain("max-w-full")
- expect(image.parentElement?.className).toContain("rounded-lg")
expect(image.parentElement?.className).toContain("border")
expect(renderer.container.querySelectorAll('[src="/notes.txt"]')).toHaveLength(0)
})
- it("keeps image previews above reactions like the live message", () => {
- const renderer = renderMessage(message({
+ it("keeps image previews above reactions like the live message", async () => {
+ const renderer = await renderReady(message({
content: "",
attachments: [{ kind: "image", name: "photo.png", url: "/photo.png" }],
reactions: [{ emoji: "👍", count: 2, me: false, userIds: [] }],
@@ -290,1032 +459,114 @@ describe("MessageShareDialog message context", () => {
expect(contextOrder).toEqual(["message-share-images-m1", "message-share-reactions-m1"])
})
- it("does not add empty context containers", () => {
- const renderer = renderMessage(message())
- const contexts = renderer.container.querySelectorAll('[data-testid^="message-share-"]')
- expect(contexts).toHaveLength(0)
- })
-})
-
-describe("waitForShareCardImages", () => {
- function image(
- overrides: Partial<HTMLImageElement> = {},
- {
- profilePhoto = false,
- photoState = "pending",
- remoteKind,
- remoteState = "pending",
- }: {
- profilePhoto?: boolean
- photoState?: "pending" | "ready" | "failed"
- remoteKind?: "identity" | "content"
- remoteState?: "pending" | "ready" | "error"
- } = {},
- ) {
- const listeners = new Map<string, () => void>()
- const value = {
- complete: false,
- naturalWidth: 0,
- naturalHeight: 0,
- 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) => {
- if (profilePhoto && name === "data-avatar-photo-state") return photoState
- if (name === "data-remote-image-kind") return remoteKind ?? null
- if (name === "data-remote-image-state") return remoteKind ? remoteState : null
- return null
- }),
- ...overrides,
- } as unknown as HTMLImageElement
- return { value, listeners }
- }
-
- function card(images: HTMLImageElement[]): HTMLElement {
- return { querySelectorAll: () => images } as unknown as HTMLElement
- }
-
- it("waits for a pending avatar load, decodes it, and yields a paint", async () => {
- const avatar = image()
- const paint = vi.fn().mockResolvedValue(undefined)
- const waiting = waitForShareCardImages(card([avatar.value]), paint)
-
- expect(paint).not.toHaveBeenCalled()
- Object.defineProperty(avatar.value, "naturalWidth", { value: 40 })
- Object.defineProperty(avatar.value, "naturalHeight", { value: 40 })
- avatar.listeners.get("load")?.()
- await waiting
+ it("does not add empty context containers", async () => {
+ const renderer = await renderReady(message())
+ const card = renderer.container.querySelector("[data-share-card]")!
- expect(avatar.value.decode).toHaveBeenCalledOnce()
- expect(paint).toHaveBeenCalledOnce()
- })
-
- it("rejects an image error before paint so capture cannot snapshot an empty branch", async () => {
- const avatar = image()
- const paint = vi.fn().mockResolvedValue(undefined)
- const waiting = waitForShareCardImages(card([avatar.value]), paint)
- avatar.listeners.get("error")?.()
- await expect(waiting).rejects.toBeInstanceOf(ShareImageSnapshotError)
-
- expect(avatar.value.decode).not.toHaveBeenCalled()
- 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("degrades a failed shared identity image without exposing substitute pixels", async () => {
- const avatar = image({}, { remoteKind: "identity", remoteState: "error" })
- const paint = vi.fn().mockResolvedValue(undefined)
-
- await expect(waitForShareCardImages(card([avatar.value]), paint)).resolves.toEqual([
- { image: avatar.value, mode: "fallback" },
- ])
- expect(avatar.value.addEventListener).not.toHaveBeenCalled()
- expect(paint).toHaveBeenCalledOnce()
- })
-
- it("rejects a failed shared content image before rasterization", async () => {
- const attachment = image({}, { remoteKind: "content", remoteState: "error" })
- const paint = vi.fn().mockResolvedValue(undefined)
-
- await expect(waitForShareCardImages(card([attachment.value]), paint))
- .rejects.toBeInstanceOf(ShareImageSnapshotError)
- expect(attachment.value.addEventListener).not.toHaveBeenCalled()
- expect(paint).not.toHaveBeenCalled()
- })
-
- it("rejects native pixels that remain pending in the shared content lifecycle", async () => {
- const attachment = image({
- complete: true,
- naturalWidth: 96,
- naturalHeight: 64,
- }, { remoteKind: "content", remoteState: "pending" })
- const paint = vi.fn().mockResolvedValue(undefined)
-
- await expect(waitForShareCardImages(card([attachment.value]), paint))
- .rejects.toBeInstanceOf(ShareImageSnapshotError)
- expect(attachment.value.decode).toHaveBeenCalledOnce()
- expect(paint).toHaveBeenCalledOnce()
- })
-
- it("decodes an already-loaded cached avatar without waiting for another event", async () => {
- const avatar = image({ complete: true, naturalWidth: 40, naturalHeight: 40 })
- const paint = vi.fn().mockResolvedValue(undefined)
- await waitForShareCardImages(card([avatar.value]), paint)
-
- expect(avatar.value.addEventListener).not.toHaveBeenCalled()
- expect(avatar.value.decode).toHaveBeenCalledOnce()
- expect(paint).toHaveBeenCalledOnce()
- })
-
- it("rejects a pending-forever image within the bound and removes its listeners", async () => {
- vi.useFakeTimers()
- try {
- const avatar = image()
- const paint = vi.fn().mockResolvedValue(undefined)
- const waiting = waitForShareCardImages(card([avatar.value]), paint, 50)
- const rejected = expect(waiting).rejects.toBeInstanceOf(ShareCardImageTimeoutError)
-
- await vi.advanceTimersByTimeAsync(50)
- await rejected
-
- expect(avatar.value.removeEventListener).toHaveBeenCalledWith("load", expect.any(Function))
- expect(avatar.value.removeEventListener).toHaveBeenCalledWith("error", expect.any(Function))
- expect(paint).not.toHaveBeenCalled()
- } finally {
- vi.useRealTimers()
- }
- })
-
- 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 {
- const avatar = image({
- complete: true,
- naturalWidth: 40,
- naturalHeight: 40,
- decode: vi.fn(() => new Promise<void>(() => {})),
- })
- const paint = vi.fn().mockResolvedValue(undefined)
- const waiting = waitForShareCardImages(card([avatar.value]), paint, 50)
-
- await vi.advanceTimersByTimeAsync(50)
- await waiting
-
- expect(avatar.value.decode).toHaveBeenCalledOnce()
- expect(paint).toHaveBeenCalledOnce()
- } finally {
- 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()
+ expect(card.querySelectorAll('[data-testid^="message-share-"]')).toHaveLength(0)
})
})
-describe("snapshotShareCardImages", () => {
- function image() {
- return { parentNode: {}, replaceWith: vi.fn() } as unknown as HTMLImageElement
- }
-
- function canvas() {
- return {
- parentNode: {},
- replaceWith: vi.fn(),
- } as unknown as HTMLCanvasElement
- }
-
- function card(images: HTMLImageElement[]): HTMLElement {
- 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()
- const avatarCanvas = canvas()
- const attachmentCanvas = canvas()
- const createSnapshot = vi.fn()
- .mockReturnValueOnce(avatarCanvas)
- .mockReturnValueOnce(attachmentCanvas)
- const waitForImages = vi.fn().mockResolvedValue(prepared([avatar, attachment]))
- const waitForPaint = vi.fn().mockResolvedValue(undefined)
-
- const restore = await snapshotShareCardImages(
- card([avatar, attachment]),
- createSnapshot,
- waitForImages,
- waitForPaint,
- )
-
- expect(waitForImages).toHaveBeenCalledOnce()
- expect(createSnapshot).toHaveBeenNthCalledWith(1, avatar)
- expect(createSnapshot).toHaveBeenNthCalledWith(2, attachment)
- expect(avatar.replaceWith).toHaveBeenCalledWith(avatarCanvas)
- expect(attachment.replaceWith).toHaveBeenCalledWith(attachmentCanvas)
- expect(waitForPaint).toHaveBeenCalledOnce()
-
- restore()
- restore()
- expect(avatarCanvas.replaceWith).toHaveBeenCalledOnce()
- expect(avatarCanvas.replaceWith).toHaveBeenCalledWith(avatar)
- expect(attachmentCanvas.replaceWith).toHaveBeenCalledOnce()
- expect(attachmentCanvas.replaceWith).toHaveBeenCalledWith(attachment)
- })
-
- it("supports consecutive captures of the same React-owned images", async () => {
- const avatar = image()
- const firstCanvas = canvas()
- const secondCanvas = canvas()
- const createSnapshot = vi.fn()
- .mockReturnValueOnce(firstCanvas)
- .mockReturnValueOnce(secondCanvas)
- const waitForImages = vi.fn().mockResolvedValue(prepared([avatar]))
- const waitForPaint = vi.fn().mockResolvedValue(undefined)
-
- const restoreFirst = await snapshotShareCardImages(
- card([avatar]),
- createSnapshot,
- waitForImages,
- waitForPaint,
- )
- restoreFirst()
- const restoreSecond = await snapshotShareCardImages(
- card([avatar]),
- createSnapshot,
- waitForImages,
- waitForPaint,
- )
- restoreSecond()
-
- expect(createSnapshot).toHaveBeenCalledTimes(2)
- expect(avatar.replaceWith).toHaveBeenNthCalledWith(1, firstCanvas)
- expect(avatar.replaceWith).toHaveBeenNthCalledWith(2, secondCanvas)
- expect(firstCanvas.replaceWith).toHaveBeenCalledWith(avatar)
- expect(secondCanvas.replaceWith).toHaveBeenCalledWith(avatar)
- })
-
- it("restores every replaced image when the snapshot paint fails", async () => {
- const avatar = image()
- const attachment = image()
- const avatarCanvas = canvas()
- const attachmentCanvas = canvas()
- const createSnapshot = vi.fn()
- .mockReturnValueOnce(avatarCanvas)
- .mockReturnValueOnce(attachmentCanvas)
-
- await expect(
- snapshotShareCardImages(
- card([avatar, attachment]),
- createSnapshot,
- vi.fn().mockResolvedValue(prepared([avatar, attachment])),
- vi.fn().mockRejectedValue(new Error("paint failed")),
- ),
- ).rejects.toThrow("paint failed")
-
- expect(avatarCanvas.replaceWith).toHaveBeenCalledWith(avatar)
- expect(attachmentCanvas.replaceWith).toHaveBeenCalledWith(attachment)
- })
-
- it("restores earlier images when a later snapshot fails", async () => {
- const avatar = image()
- const attachment = image()
- const avatarCanvas = canvas()
- const createSnapshot = vi.fn()
- .mockReturnValueOnce(avatarCanvas)
- .mockImplementationOnce(() => { throw new ShareImageSnapshotError() })
-
- await expect(
- snapshotShareCardImages(
- card([avatar, attachment]),
- createSnapshot,
- vi.fn().mockResolvedValue(prepared([avatar, attachment])),
- vi.fn().mockResolvedValue(undefined),
- ),
- ).rejects.toBeInstanceOf(ShareImageSnapshotError)
-
- expect(avatarCanvas.replaceWith).toHaveBeenCalledWith(avatar)
- })
-
- it("aborts capture instead of replacing a tainted image with a blank canvas", () => {
- const drawImage = vi.fn()
- const canvas = {
- className: "",
- style: { cssText: "", width: "", height: "" },
- setAttribute: vi.fn(),
- getContext: vi.fn(() => ({ drawImage })),
- toDataURL: vi.fn(() => { throw new Error("tainted") }),
- }
- const createElement = vi.fn(() => canvas)
- vi.stubGlobal("document", { createElement })
- vi.stubGlobal("getComputedStyle", () => ({ objectFit: "cover" }))
-
- expect(() => createShareImageSnapshot({
- naturalWidth: 512,
- naturalHeight: 512,
- className: "rounded-full",
- style: { cssText: "" },
- attributes: [],
- getBoundingClientRect: () => ({ width: 40, height: 40 }),
- } as unknown as HTMLImageElement)).toThrow(ShareImageSnapshotError)
-
- expect(drawImage).toHaveBeenCalledOnce()
- expect(canvas.toDataURL).toHaveBeenCalledOnce()
- expect(createElement).toHaveBeenCalledOnce()
- vi.unstubAllGlobals()
- })
-
- it.each([
- { name: "zero intrinsic size", naturalWidth: 0, naturalHeight: 0, context: { drawImage: vi.fn() } },
- { name: "missing 2D context", naturalWidth: 512, naturalHeight: 512, context: null },
- ])("rejects $name instead of returning a blank canvas", ({ naturalWidth, naturalHeight, context }) => {
- const canvas = {
- className: "",
- style: { cssText: "", width: "", height: "" },
- setAttribute: vi.fn(),
- getContext: vi.fn(() => context),
- toDataURL: vi.fn(),
- }
- vi.stubGlobal("document", { createElement: vi.fn(() => canvas) })
- vi.stubGlobal("getComputedStyle", () => ({ objectFit: "cover" }))
-
- expect(() => createShareImageSnapshot({
- naturalWidth,
- naturalHeight,
- className: "rounded-full",
- style: { cssText: "" },
- attributes: [],
- getBoundingClientRect: () => ({ width: 40, height: 40 }),
- } as unknown as HTMLImageElement)).toThrow(ShareImageSnapshotError)
-
- expect(canvas.toDataURL).not.toHaveBeenCalled()
- vi.unstubAllGlobals()
- })
-
- it("skips a zero-size image while snapshotting the remaining images", async () => {
- const hiddenImage = image()
- const attachment = image()
- const attachmentCanvas = canvas()
- const createSnapshot = vi.fn()
- .mockReturnValueOnce(null)
- .mockReturnValueOnce(attachmentCanvas)
-
- const restore = await snapshotShareCardImages(
- card([hiddenImage, attachment]),
- createSnapshot,
- vi.fn().mockResolvedValue(prepared([hiddenImage, attachment])),
- vi.fn().mockResolvedValue(undefined),
- )
-
- expect(hiddenImage.replaceWith).not.toHaveBeenCalled()
- expect(attachment.replaceWith).toHaveBeenCalledWith(attachmentCanvas)
- 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", () => {
- const node = {} as HTMLElement
- const style = { getPropertyValue: vi.fn(() => "") }
-
- afterEach(() => {
- vi.useRealTimers()
- vi.unstubAllGlobals()
- })
-
- it("records the complete render lifecycle and restores snapshots once", async () => {
- vi.stubGlobal("getComputedStyle", vi.fn(() => style))
- const stages: string[] = []
- const restore = vi.fn()
- const blob = new Blob(["png"], { type: "image/png" })
- const snapshotImages = vi.fn().mockResolvedValue(restore)
- const loadFonts = vi.fn().mockResolvedValue(undefined)
- const rasterize = vi.fn().mockResolvedValue(blob)
-
- await expect(renderShareCard(node, snapshotImages, rasterize, {
- loadFonts,
- onStage: (stage) => stages.push(stage),
- })).resolves.toBe(blob)
-
- expect(stages).toEqual(["snapshot", "fonts", "rasterize", "cleanup"])
- expect(loadFonts).toHaveBeenCalledOnce()
- expect(restore).toHaveBeenCalledOnce()
- })
-
- it("types snapshot preparation failures and skips rasterization", async () => {
- const failure = new ShareImageSnapshotError()
- const snapshotImages = vi.fn().mockRejectedValue(failure)
- const rasterize = vi.fn()
-
- await expect(renderShareCard(node, snapshotImages, rasterize, {
- loadFonts: vi.fn(),
- })).rejects.toMatchObject({
- stage: "snapshot",
- timedOut: false,
- cause: failure,
- })
-
- expect(rasterize).not.toHaveBeenCalled()
- })
-
- it("keeps font loading best-effort and proceeds to rasterization", async () => {
- vi.stubGlobal("getComputedStyle", vi.fn(() => style))
- const restore = vi.fn()
- const blob = new Blob(["png"], { type: "image/png" })
- const rasterize = vi.fn().mockResolvedValue(blob)
-
- await expect(renderShareCard(
- node,
- vi.fn().mockResolvedValue(restore),
- rasterize,
- { loadFonts: vi.fn().mockRejectedValue(new Error("font unavailable")) },
- )).resolves.toBe(blob)
-
- expect(rasterize).toHaveBeenCalledOnce()
- expect(restore).toHaveBeenCalledOnce()
- })
-
- it("uses the real document font contract when no font waiter is injected", async () => {
- const load = vi.fn().mockResolvedValue(undefined)
- const ready = Promise.resolve()
- vi.stubGlobal("document", { documentElement: {}, fonts: { load, ready } })
- vi.stubGlobal("getComputedStyle", vi.fn((target) => (
- target === document.documentElement
- ? { getPropertyValue: vi.fn(() => "Caveat") }
- : style
- )))
-
- await renderShareCard(
- node,
- vi.fn().mockResolvedValue(vi.fn()),
- vi.fn().mockResolvedValue(new Blob(["png"])),
- )
-
- expect(load).toHaveBeenCalledWith("16px Caveat")
- })
-
- it.each([
- {
- name: "a rejected rasterizer",
- result: () => Promise.reject(new Error("raster failed")),
- },
- {
- name: "a null rasterizer result",
- result: () => Promise.resolve(null),
- },
- ])("types $name and restores snapshots once", async ({ result }) => {
- vi.stubGlobal("getComputedStyle", vi.fn(() => style))
- const restore = vi.fn()
-
- await expect(renderShareCard(
- node,
- vi.fn().mockResolvedValue(restore),
- vi.fn(result),
- { loadFonts: vi.fn().mockResolvedValue(undefined) },
- )).rejects.toMatchObject({ stage: "rasterize", timedOut: false })
-
- expect(restore).toHaveBeenCalledOnce()
- })
-
- it.each(["snapshot", "fonts", "rasterize"] as const)(
- "applies the single total deadline while in %s",
- async (blockedStage) => {
- vi.useFakeTimers()
- vi.stubGlobal("getComputedStyle", vi.fn(() => style))
- const never = () => new Promise<never>(() => {})
- const restore = vi.fn()
- const snapshotImages = blockedStage === "snapshot"
- ? vi.fn(never)
- : vi.fn().mockResolvedValue(restore)
- const loadFonts = blockedStage === "fonts"
- ? vi.fn(never)
- : vi.fn().mockResolvedValue(undefined)
- const rasterize = blockedStage === "rasterize"
- ? vi.fn(never)
- : vi.fn().mockResolvedValue(new Blob(["png"]))
- const rendering = renderShareCard(node, snapshotImages, rasterize, {
- timeoutMs: 50,
- loadFonts,
- })
- const rejected = expect(rendering).rejects.toMatchObject({
- stage: blockedStage,
- timedOut: true,
- })
-
- await vi.advanceTimersByTimeAsync(50)
- await rejected
-
- expect(restore).toHaveBeenCalledTimes(blockedStage === "snapshot" ? 0 : 1)
- },
- )
-
- it("restores a late snapshot result after the caller deadline has fired", async () => {
- vi.useFakeTimers()
- let finishSnapshot: ((restore: () => void) => void) | undefined
- const restore = vi.fn()
- const snapshotImages = vi.fn(() => new Promise<() => void>((resolve) => {
- finishSnapshot = resolve
- }))
- const rasterize = vi.fn()
- const rendering = renderShareCard(node, snapshotImages, rasterize, {
- timeoutMs: 50,
- loadFonts: vi.fn(),
- })
- const rejected = expect(rendering).rejects.toMatchObject({
- stage: "snapshot",
- timedOut: true,
- })
-
- await vi.advanceTimersByTimeAsync(50)
- await rejected
- finishSnapshot?.(restore)
- await vi.waitFor(() => expect(restore).toHaveBeenCalledOnce())
-
- 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) => {
- vi.useFakeTimers()
- vi.stubGlobal("getComputedStyle", vi.fn(() => style))
- let finishStage: (() => void) | undefined
- const restore = vi.fn()
- const loadFonts = blockedStage === "fonts"
- ? vi.fn(() => new Promise<void>((resolve) => { finishStage = resolve }))
- : vi.fn().mockResolvedValue(undefined)
- const rasterize = blockedStage === "rasterize"
- ? vi.fn(() => new Promise<Blob>((resolve) => {
- finishStage = () => resolve(new Blob(["png"]))
- }))
- : vi.fn().mockResolvedValue(new Blob(["png"]))
- const rendering = renderShareCard(
- node,
- vi.fn().mockResolvedValue(restore),
- rasterize,
- { timeoutMs: 50, loadFonts },
- )
- const outcome = rendering.catch((error) => error)
-
- await vi.advanceTimersByTimeAsync(50)
- expect(await outcome).toMatchObject({ stage: blockedStage, timedOut: true })
- finishStage?.()
- await vi.waitFor(() => expect(restore).toHaveBeenCalledOnce())
-
- expect(rasterize).toHaveBeenCalledTimes(blockedStage === "fonts" ? 0 : 1)
- },
- )
-
- it("surfaces cleanup failure when the deadline restores a blocked raster", async () => {
- vi.useFakeTimers()
- vi.stubGlobal("getComputedStyle", vi.fn(() => style))
- const failure = new Error("restore failed")
- const restore = vi.fn(() => { throw failure })
- const rendering = renderShareCard(
- node,
- vi.fn().mockResolvedValue(restore),
- vi.fn(() => new Promise<never>(() => {})),
- { timeoutMs: 50, loadFonts: vi.fn().mockResolvedValue(undefined) },
- )
- const outcome = rendering.catch((error) => error)
-
- await vi.advanceTimersByTimeAsync(50)
-
- expect(await outcome).toMatchObject({
- stage: "cleanup",
- timedOut: false,
- cause: failure,
- })
- expect(restore).toHaveBeenCalledOnce()
- })
-
- it("types cleanup failures and never repeats the restore callback", async () => {
- vi.stubGlobal("getComputedStyle", vi.fn(() => style))
- const failure = new Error("restore failed")
- const restore = vi.fn(() => { throw failure })
-
- await expect(renderShareCard(
- node,
- vi.fn().mockResolvedValue(restore),
- vi.fn().mockResolvedValue(new Blob(["png"])),
- { loadFonts: vi.fn().mockResolvedValue(undefined) },
- )).rejects.toMatchObject({
- stage: "cleanup",
- timedOut: false,
- cause: failure,
- })
-
- expect(restore).toHaveBeenCalledOnce()
- })
-
- it("does not reach clipboard or download writers when rendering fails", async () => {
- const failure = new ShareCardRenderError("fonts", true)
- const render = vi.fn().mockRejectedValue(failure)
- const clipboardWrite = vi.fn()
- const downloadSave = vi.fn()
-
- await expect(copyRenderedShareCard(render, clipboardWrite)).rejects.toBe(failure)
- await expect(downloadRenderedShareCard(render, "share.png", downloadSave)).rejects.toBe(failure)
-
- expect(clipboardWrite).not.toHaveBeenCalled()
- expect(downloadSave).not.toHaveBeenCalled()
- })
-
- it("types a renderer that resolves without a blob before action writers", async () => {
- const render = vi.fn().mockResolvedValue(null)
- const clipboardWrite = vi.fn()
- const downloadSave = vi.fn()
-
- await expect(copyRenderedShareCard(render, clipboardWrite)).rejects.toMatchObject({
- stage: "rasterize",
- timedOut: false,
- })
- await expect(downloadRenderedShareCard(render, "share.png", downloadSave)).rejects.toMatchObject({
- stage: "rasterize",
- timedOut: false,
- })
-
- expect(clipboardWrite).not.toHaveBeenCalled()
- expect(downloadSave).not.toHaveBeenCalled()
- })
-
- it("writes only after a completed render", async () => {
- const order: string[] = []
- const blob = new Blob(["png"], { type: "image/png" })
- const render = vi.fn(async () => {
- order.push("render")
- return blob
+describe("MessageShareDialog exports", () => {
+ it("reuses one finalized PNG for consecutive Copy then Download", async () => {
+ const write = vi.fn().mockResolvedValue(undefined)
+ const createObjectURL = vi.fn(() => "blob:share-card")
+ const revokeObjectURL = vi.fn()
+ const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {})
+ vi.stubGlobal("ClipboardItem", class ClipboardItem {
+ constructor(readonly items: Record<string, Blob>) {}
})
- const clipboardWrite = vi.fn(() => { order.push("copy") })
- const downloadSave = vi.fn(() => { order.push("download") })
-
- await copyRenderedShareCard(render, clipboardWrite)
- await downloadRenderedShareCard(render, "share.png", downloadSave)
-
- expect(order).toEqual(["render", "copy", "render", "download"])
- })
-
- it.each([
- ["snapshot", "preparing images"],
- ["fonts", "loading fonts"],
- ["rasterize", "rendering the image"],
- ["cleanup", "restoring the preview"],
- ] as const)("formats visible %s stage failures", (stage, label) => {
- expect(shareCardRenderErrorMessage(new ShareCardRenderError(stage))).toBe(
- `Couldn't generate image — ${label} failed`,
- )
- expect(shareCardRenderErrorMessage(new ShareCardRenderError(stage, true))).toBe(
- `Couldn't generate image — ${label} took too long`,
- )
- })
-
- it("leaves post-render action errors to their action-specific UI", () => {
- expect(shareCardRenderErrorMessage(new Error("clipboard denied"))).toBeNull()
- })
-})
-
-describe("writeShareCardToClipboard", () => {
- class ClipboardItemStub {
- constructor(readonly items: Record<string, Blob>) {}
- }
-
- afterEach(() => {
- vi.unstubAllGlobals()
- })
-
- it("forwards PNG bytes once through the native desktop clipboard", async () => {
- const invoke = vi.fn().mockResolvedValue(undefined)
- const webWrite = vi.fn()
- vi.stubGlobal("window", {
- __TAURI__: {},
- __TAURI_INTERNALS__: { invoke },
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: { write },
})
- vi.stubGlobal("navigator", { userAgent: "Macintosh", clipboard: { write: webWrite } })
- const bytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])
+ vi.stubGlobal("URL", Object.assign(URL, { createObjectURL, revokeObjectURL }))
+ const renderer = await renderReady()
- await writeShareCardToClipboard(new Blob([bytes], { type: "image/png" }))
+ await act(async () => buttonWithText(renderer.container, "Copy image").click())
+ await vi.waitFor(() => expect(toast.success).toHaveBeenCalledWith("Image copied to clipboard"))
+ await act(async () => buttonWithText(renderer.container, "Download").click())
+ await vi.waitFor(() => expect(toast.success).toHaveBeenCalledWith("Image downloaded"))
- expect(invoke).toHaveBeenCalledOnce()
- expect(invoke.mock.calls[0][0]).toBe("plugin:clipboard-manager|write_image")
- expect([...new Uint8Array(invoke.mock.calls[0][1].image)]).toEqual([...bytes])
- expect(webWrite).not.toHaveBeenCalled()
+ expect(sessionMocks.capture).toHaveBeenCalledTimes(1)
+ expect(toBlob).toHaveBeenCalledTimes(1)
+ expect(write).toHaveBeenCalledTimes(1)
+ expect(click).toHaveBeenCalledTimes(1)
+ expect(createObjectURL).toHaveBeenCalledTimes(1)
+ await vi.waitFor(() => expect(revokeObjectURL).toHaveBeenCalledWith("blob:share-card"))
})
- it("does not retry WebKit after a native clipboard rejection", async () => {
- const failure = new Error("native clipboard rejected")
- const invoke = vi.fn().mockRejectedValue(failure)
- const webWrite = vi.fn()
- vi.stubGlobal("window", {
- __TAURI__: {},
- __TAURI_INTERNALS__: { invoke },
+ it("reports rasterization failure without invoking clipboard", async () => {
+ const write = vi.fn()
+ vi.stubGlobal("ClipboardItem", class ClipboardItem {})
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: { write },
})
- vi.stubGlobal("navigator", { userAgent: "Macintosh", clipboard: { write: webWrite } })
-
- await expect(writeShareCardToClipboard(new Blob(["png"]))).rejects.toBe(failure)
-
- expect(invoke).toHaveBeenCalledOnce()
- expect(webWrite).not.toHaveBeenCalled()
- })
-
- it("does not retry WebKit when the Tauri invoke bridge is missing", async () => {
- const webWrite = vi.fn()
- vi.stubGlobal("window", { __TAURI__: {} })
- vi.stubGlobal("navigator", { userAgent: "Macintosh", clipboard: { write: webWrite } })
- vi.stubGlobal("ClipboardItem", ClipboardItemStub)
+ sessionMocks.capture.mockRejectedValueOnce(new ShareCardRenderError("rasterize", true))
+ const renderer = await renderReady()
- await expect(writeShareCardToClipboard(new Blob(["png"]))).rejects.toThrow()
-
- expect(webWrite).not.toHaveBeenCalled()
+ await act(async () => buttonWithText(renderer.container, "Copy image").click())
+ await vi.waitFor(() => expect(toast.error).toHaveBeenCalledWith(
+ "Couldn't generate image — rendering the image took too long",
+ ))
+ expect(write).not.toHaveBeenCalled()
+ expect(buttonWithText(renderer.container, "Copy image").disabled).toBe(false)
})
- it.each([
- ["ordinary Web", {}, "Macintosh"],
- ["Tauri mobile", { __TAURI__: {} }, "iPhone"],
- ])("keeps %s on Web Clipboard", async (_surface, testWindow, userAgent) => {
- const webWrite = vi.fn().mockResolvedValue(undefined)
- vi.stubGlobal("window", testWindow)
- vi.stubGlobal("navigator", { userAgent, clipboard: { write: webWrite } })
- vi.stubGlobal("ClipboardItem", ClipboardItemStub)
-
- await writeShareCardToClipboard(new Blob(["png"], { type: "image/png" }))
-
- expect(webWrite).toHaveBeenCalledOnce()
- })
-})
-
-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("navigator", { userAgent: "Macintosh", clipboard: { write } })
- vi.stubGlobal("ClipboardItem", ClipboardItemStub)
- Object.defineProperty(document, "fonts", {
+ it("aborts an active export and suppresses its late receipt after close", async () => {
+ const rendered = deferred<Blob>()
+ sessionMocks.capture.mockReturnValueOnce(rendered.promise)
+ const write = vi.fn()
+ vi.stubGlobal("ClipboardItem", class ClipboardItem {})
+ Object.defineProperty(navigator, "clipboard", {
configurable: true,
- value: { ready: Promise.resolve() },
+ value: { write },
})
- const anchor = document.createElement("a")
- vi.spyOn(anchor, "click").mockImplementation(click)
- const createElement = document.createElement.bind(document)
- vi.spyOn(document, "createElement").mockImplementation((tagName, options) => (
- tagName === "a" ? anchor : createElement(tagName, options)
- ))
- vi.stubGlobal("getComputedStyle", vi.fn(() => ({
- getPropertyValue: vi.fn(() => ""),
- })))
- vi.stubGlobal("URL", { createObjectURL, revokeObjectURL })
- const renderer = renderMessage(message())
- const copyButton = actionButton(tid.messageShareCopy)
- const downloadButton = actionButton(undefined, "Download")
- const dialog = capturedNode(
- componentMocks.dialogProps,
- (props) => typeof props.onOpenChange === "function",
- )
- return {
- click,
- copyButton,
- createObjectURL,
- dialog,
- downloadButton,
- renderer,
- revokeObjectURL,
- write,
- }
- }
+ const renderer = await renderReady()
- function setupMobileActionEnvironment(invoke: ReturnType<typeof vi.fn>) {
- Object.defineProperty(window, "__TAURI__", {
- configurable: true,
- value: { core: { invoke } },
- })
- vi.spyOn(navigator, "userAgent", "get").mockReturnValue("iPhone")
- Object.defineProperty(document, "fonts", {
- configurable: true,
- value: { ready: Promise.resolve() },
- })
- vi.stubGlobal("getComputedStyle", vi.fn(() => ({
- getPropertyValue: vi.fn(() => ""),
- })))
- const renderer = renderMessage(message())
- const copyButton = actionButton(tid.messageShareCopy)
- const saveButton = actionButton(tid.messageShareSave)
- const dialog = capturedNode(
- componentMocks.dialogProps,
- (props) => typeof props.onOpenChange === "function",
- )
- return { copyButton, dialog, renderer, saveButton }
- }
+ await act(async () => buttonWithText(renderer.container, "Copy image").click())
+ const dialogProps = componentMocks.dialogProps.mock.calls.at(-1)?.[0] as {
+ onOpenChange: (open: boolean) => void
+ }
+ await act(async () => dialogProps.onOpenChange(false))
+ await act(async () => rendered.resolve(new Blob(["late"], { type: "image/png" })))
- afterEach(() => {
- Reflect.deleteProperty(window, "__TAURI__")
- vi.mocked(toBlob).mockReset()
- vi.mocked(toast.success).mockReset()
- vi.mocked(toast.error).mockReset()
- vi.restoreAllMocks()
- vi.unstubAllGlobals()
+ expect(write).not.toHaveBeenCalled()
+ expect(toast.success).not.toHaveBeenCalled()
+ expect(toast.error).not.toHaveBeenCalled()
})
- it("routes mobile copy and shows success only after the native terminal receipt", async () => {
+ it("shows mobile copy success only after the terminal native receipt", async () => {
const native = deferred<Record<string, unknown>>()
const invoke = vi.fn(() => native.promise)
- vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
- const harness = setupMobileActionEnvironment(invoke)
- let copy!: Promise<void>
+ installMobileNative(invoke)
+ const renderer = await renderReady()
+ const copy = buttonWithText(renderer.container, "Copy image")
+ const save = buttonWithText(renderer.container, "Save image")
- act(() => { copy = harness.copyButton.props.onClick() })
- await vi.waitFor(() => expect(invoke).toHaveBeenCalledOnce())
+ await act(async () => copy.click())
+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(1))
expect(invoke.mock.calls[0]![0]).toBe("mobile_share_image_copy")
- expect(harness.copyButton.props.disabled).toBe(true)
- expect(harness.saveButton.props.disabled).toBe(true)
+ expect(copy.disabled).toBe(true)
+ expect(save.disabled).toBe(true)
expect(toast.success).not.toHaveBeenCalled()
- const attemptId = (invoke.mock.calls[0]![1] as {
- payload: { attemptId: string }
- }).payload.attemptId
+ const attemptId = invoke.mock.calls[0]![1].payload.attemptId as string
- await act(async () => {
- native.resolve({ attemptId, status: "copied", destination: "clipboard" })
- await copy
- })
-
- expect(toast.success).toHaveBeenCalledWith("Image copied to clipboard")
+ await act(async () => native.resolve({
+ attemptId,
+ status: "copied",
+ destination: "clipboard",
+ }))
+ await vi.waitFor(() => expect(toast.success).toHaveBeenCalledWith("Image copied to clipboard"))
expect(toast.error).not.toHaveBeenCalled()
- expect(harness.copyButton.children).toContain("Copied")
})
it.each([
["photos", "Saved to Photos"],
["pictures", "Saved to Pictures/Alook"],
["document", "Image saved"],
- ] as const)("maps mobile %s receipt to exact save feedback", async (destination, feedback) => {
+ ] as const)("maps the mobile %s receipt to exact save feedback", async (destination, feedback) => {
const invoke = vi.fn(async (_command: string, args: {
payload: { attemptId: string; filename: string }
}) => ({
@@ -1323,316 +574,304 @@ describe("MessageShareDialog action feedback", () => {
status: "saved",
destination,
}))
- vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
- const harness = setupMobileActionEnvironment(invoke)
+ installMobileNative(invoke)
+ const renderer = await renderReady()
- await act(async () => { await harness.saveButton.props.onClick() })
+ await act(async () => buttonWithText(renderer.container, "Save image").click())
- expect(invoke).toHaveBeenCalledOnce()
+ expect(invoke).toHaveBeenCalledTimes(1)
expect(invoke.mock.calls[0]![0]).toBe("mobile_share_image_save")
- expect((invoke.mock.calls[0]![1] as {
- payload: { filename: string }
- }).payload.filename).toBe("alook-message-Alice.png")
+ expect(invoke.mock.calls[0]![1].payload.filename).toBe("alook-message-Alice.png")
expect(toast.success).toHaveBeenCalledWith(feedback)
expect(toast.error).not.toHaveBeenCalled()
})
it("keeps mobile cancellation silent and re-enables both actions", async () => {
const invoke = vi.fn().mockRejectedValue({ code: "cancelled", message: "cancelled" })
- vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
- const harness = setupMobileActionEnvironment(invoke)
+ installMobileNative(invoke)
+ const renderer = await renderReady()
- await act(async () => { await harness.saveButton.props.onClick() })
+ await act(async () => buttonWithText(renderer.container, "Save image").click())
expect(toast.success).not.toHaveBeenCalled()
expect(toast.error).not.toHaveBeenCalled()
- expect(harness.copyButton.props.disabled).toBe(false)
- expect(harness.saveButton.props.disabled).toBe(false)
+ expect(buttonWithText(renderer.container, "Copy image").disabled).toBe(false)
+ expect(buttonWithText(renderer.container, "Save image").disabled).toBe(false)
})
- it("shows mobile Photos denial and oversize failures without success", async () => {
- const invoke = vi.fn().mockRejectedValue({
- code: "permission_denied",
- message: "denied",
- })
- vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
- let harness = setupMobileActionEnvironment(invoke)
+ it("shows mobile permission and oversize failures without success", async () => {
+ const denied = vi.fn().mockRejectedValue({ code: "permission_denied", message: "denied" })
+ installMobileNative(denied)
+ let renderer = await renderReady()
- await act(async () => { await harness.saveButton.props.onClick() })
+ await act(async () => buttonWithText(renderer.container, "Save image").click())
expect(toast.error).toHaveBeenCalledWith(
"Couldn't save image — allow Photos access in Settings",
)
expect(toast.success).not.toHaveBeenCalled()
- act(() => harness.renderer.unmount())
+ renderer.unmount()
vi.mocked(toast.error).mockReset()
- vi.mocked(toBlob).mockResolvedValue({
+ const invoke = vi.fn()
+ Object.defineProperty(window, "__TAURI__", {
+ configurable: true,
+ value: { core: { invoke } },
+ })
+ sessionMocks.capture.mockResolvedValueOnce({
type: "image/png",
size: 10 * 1024 * 1024 + 1,
} as Blob)
- harness = setupMobileActionEnvironment(vi.fn())
- await act(async () => { await harness.copyButton.props.onClick() })
+ renderer = await renderReady()
+ await act(async () => buttonWithText(renderer.container, "Copy image").click())
expect(toast.error).toHaveBeenCalledWith("Image is too large — select fewer messages")
expect(toast.success).not.toHaveBeenCalled()
+ expect(invoke).not.toHaveBeenCalled()
})
- it("keeps the first mobile action as sole native owner during overlap", async () => {
+ it("keeps the first mobile action as sole owner during overlap", async () => {
const native = deferred<Record<string, unknown>>()
const invoke = vi.fn(() => native.promise)
- vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
- const harness = setupMobileActionEnvironment(invoke)
- let copy!: Promise<void>
- let save!: Promise<void>
+ installMobileNative(invoke)
+ const renderer = await renderReady()
+ const copy = buttonWithText(renderer.container, "Copy image")
+ const save = buttonWithText(renderer.container, "Save image")
act(() => {
- copy = harness.copyButton.props.onClick()
- save = harness.saveButton.props.onClick()
+ copy.click()
+ save.click()
})
-
- expect(save).toBe(copy)
- await vi.waitFor(() => expect(invoke).toHaveBeenCalledOnce())
+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(1))
expect(invoke.mock.calls[0]![0]).toBe("mobile_share_image_copy")
- const attemptId = (invoke.mock.calls[0]![1] as {
- payload: { attemptId: string }
- }).payload.attemptId
- await act(async () => {
- native.resolve({ attemptId, status: "copied", destination: "clipboard" })
- await copy
- })
- expect(toast.success).toHaveBeenCalledOnce()
+ const attemptId = invoke.mock.calls[0]![1].payload.attemptId as string
+ await act(async () => native.resolve({
+ attemptId,
+ status: "copied",
+ destination: "clipboard",
+ }))
+ await vi.waitFor(() => expect(toast.success).toHaveBeenCalledTimes(1))
})
- it("suppresses late mobile feedback when closed after native invocation", async () => {
+ it("suppresses late mobile feedback after close", async () => {
const native = deferred<Record<string, unknown>>()
const invoke = vi.fn(() => native.promise)
- vi.mocked(toBlob).mockResolvedValue(new Blob(["png"], { type: "image/png" }))
- const harness = setupMobileActionEnvironment(invoke)
- let save!: Promise<void>
-
- act(() => { save = harness.saveButton.props.onClick() })
- await vi.waitFor(() => expect(invoke).toHaveBeenCalledOnce())
- act(() => harness.dialog.props.onOpenChange(false))
- const attemptId = (invoke.mock.calls[0]![1] as {
- payload: { attemptId: string }
- }).payload.attemptId
- await act(async () => {
- native.resolve({ attemptId, status: "saved", destination: "photos" })
- await save
- })
+ installMobileNative(invoke)
+ const renderer = await renderReady()
+
+ await act(async () => buttonWithText(renderer.container, "Save image").click())
+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(1))
+ const dialogProps = componentMocks.dialogProps.mock.calls.at(-1)?.[0] as {
+ onOpenChange: (open: boolean) => void
+ }
+ act(() => dialogProps.onOpenChange(false))
+ const attemptId = invoke.mock.calls[0]![1].payload.attemptId as string
+ await act(async () => native.resolve({
+ attemptId,
+ status: "saved",
+ destination: "photos",
+ }))
+ await act(async () => Promise.resolve())
expect(toast.success).not.toHaveBeenCalled()
expect(toast.error).not.toHaveBeenCalled()
- expect(harness.copyButton.props.disabled).toBe(false)
})
- it("confirms a completed image download", async () => {
- const blob = new Blob(["png"], { type: "image/png" })
- const click = vi.fn()
- const createObjectURL = vi.fn(() => "blob:share-card")
- const revokeObjectURL = vi.fn()
- vi.mocked(toBlob).mockResolvedValue(blob)
- Object.defineProperty(document, "fonts", {
- configurable: true,
- value: { ready: Promise.resolve() },
- })
- const anchor = document.createElement("a")
- vi.spyOn(anchor, "click").mockImplementation(click)
- const createElement = document.createElement.bind(document)
- vi.spyOn(document, "createElement").mockImplementation((tagName, options) => (
- tagName === "a" ? anchor : createElement(tagName, options)
+ it.each([
+ ["Copy", "Download", "Image copied to clipboard"],
+ ["Download", "Copy image", "Image downloaded"],
+ ] as const)("keeps %s as first winner when %s overlaps", async (first, second, feedback) => {
+ const rendered = deferred<Blob>()
+ sessionMocks.capture.mockReturnValueOnce(rendered.promise)
+ const write = installWebClipboard()
+ const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {})
+ vi.stubGlobal("URL", Object.assign(URL, {
+ createObjectURL: vi.fn(() => "blob:share-card"),
+ revokeObjectURL: vi.fn(),
+ }))
+ const renderer = await renderReady()
+ const firstButton = buttonWithText(renderer.container, first === "Copy" ? "Copy image" : first)
+ const secondButton = buttonWithText(renderer.container, second)
+
+ act(() => {
+ firstButton.click()
+ secondButton.click()
+ })
+ await act(async () => rendered.resolve(new Blob(["png"], { type: "image/png" })))
+ await vi.waitFor(() => expect(toast.success).toHaveBeenCalledWith(feedback))
+
+ if (first === "Copy") {
+ expect(write).toHaveBeenCalledTimes(1)
+ expect(click).not.toHaveBeenCalled()
+ } else {
+ expect(click).toHaveBeenCalledTimes(1)
+ expect(write).not.toHaveBeenCalled()
+ }
+ })
+
+ it("releases a failed action so Copy can retry the finalized PNG", async () => {
+ const write = installWebClipboard(vi.fn()
+ .mockRejectedValueOnce(new Error("clipboard denied"))
+ .mockResolvedValueOnce(undefined))
+ const renderer = await renderReady()
+
+ await act(async () => buttonWithText(renderer.container, "Copy image").click())
+ await vi.waitFor(() => expect(toast.error).toHaveBeenCalledWith(
+ "Couldn't copy image — try Download instead",
))
- vi.stubGlobal("getComputedStyle", vi.fn(() => ({
- getPropertyValue: vi.fn(() => ""),
- })))
- vi.stubGlobal("URL", { createObjectURL, revokeObjectURL })
- renderMessage(message())
- const downloadButton = actionButton(undefined, "Download")
-
- expect(downloadButton).toBeDefined()
- await act(async () => {
- await (downloadButton.props.onClick as () => Promise<void>)()
- })
+ await act(async () => buttonWithText(renderer.container, "Copy image").click())
+ await vi.waitFor(() => expect(toast.success).toHaveBeenCalledWith("Image copied to clipboard"))
- expect(click).toHaveBeenCalledOnce()
- expect(createObjectURL).toHaveBeenCalledWith(blob)
- expect(revokeObjectURL).toHaveBeenCalledWith("blob:share-card")
- expect(toast.success).toHaveBeenCalledWith("Image downloaded")
- expect(toast.error).not.toHaveBeenCalled()
+ expect(sessionMocks.capture).toHaveBeenCalledTimes(1)
+ expect(write).toHaveBeenCalledTimes(2)
})
- it("does not confirm a failed image download", async () => {
- renderMessage(message())
- const downloadButton = actionButton(undefined, "Download")
+ it("suppresses a late raster result after unmount", async () => {
+ const rendered = deferred<Blob>()
+ sessionMocks.capture.mockReturnValueOnce(rendered.promise)
+ const write = installWebClipboard()
+ const renderer = await renderReady()
- expect(downloadButton).toBeDefined()
- await act(async () => {
- await (downloadButton.props.onClick as () => Promise<void>)()
- })
+ await act(async () => buttonWithText(renderer.container, "Copy image").click())
+ renderer.unmount()
+ await act(async () => rendered.resolve(new Blob(["late"], { type: "image/png" })))
- expect(toast.error).toHaveBeenCalledWith(
- "Couldn't generate image — rendering the image failed",
- )
+ expect(write).not.toHaveBeenCalled()
expect(toast.success).not.toHaveBeenCalled()
+ expect(toast.error).not.toHaveBeenCalled()
})
- it("shows a stage-specific render failure instead of clipboard advice", async () => {
- renderMessage(message())
- const copyButton = actionButton(tid.messageShareCopy)
+ it("suppresses late feedback after close once Clipboard API is in flight", async () => {
+ const write = deferred<void>()
+ installWebClipboard(vi.fn(() => write.promise))
+ const renderer = await renderReady()
- await act(async () => {
- await (copyButton.props.onClick as () => Promise<void>)()
- })
+ await act(async () => buttonWithText(renderer.container, "Copy image").click())
+ await vi.waitFor(() => expect(navigator.clipboard.write).toHaveBeenCalledTimes(1))
+ const dialogProps = componentMocks.dialogProps.mock.calls.at(-1)?.[0] as {
+ onOpenChange: (open: boolean) => void
+ }
+ act(() => dialogProps.onOpenChange(false))
+ await act(async () => write.resolve())
+ await act(async () => Promise.resolve())
- expect(toast.error).toHaveBeenCalledWith(
- "Couldn't generate image — rendering the image failed",
- )
expect(toast.success).not.toHaveBeenCalled()
+ expect(toast.error).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()
- })
+ it("does not confirm a failed image download", async () => {
+ sessionMocks.capture.mockRejectedValueOnce(new ShareCardRenderError("rasterize"))
+ const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {})
+ const renderer = await renderReady()
- expect(download).toBe(copy)
- await vi.waitFor(() => expect(toBlob).toHaveBeenCalledOnce())
- await act(async () => {
- rendering.resolve(blob)
- await copy
- })
+ await act(async () => buttonWithText(renderer.container, "Download").click())
+ await vi.waitFor(() => expect(toast.error).toHaveBeenCalledWith(
+ "Couldn't generate image — rendering the image failed",
+ ))
- 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())
+ expect(click).not.toHaveBeenCalled()
+ expect(toast.success).not.toHaveBeenCalled()
})
+})
- it("keeps Download as the first winner when Copy is clicked during its render", async () => {
- const rendering = deferred<Blob | null>()
+describe("share image action helpers", () => {
+ it("hands only a completed PNG to copy and download writers", async () => {
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>
+ const copyWrite = vi.fn()
+ const downloadWrite = vi.fn()
- act(() => {
- download = harness.downloadButton.props.onClick()
- copy = harness.copyButton.props.onClick()
- })
+ await copyRenderedShareCard(async () => blob, copyWrite)
+ await downloadRenderedShareCard(async () => blob, "share.png", downloadWrite)
- 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")
+ expect(copyWrite).toHaveBeenCalledWith(blob)
+ expect(downloadWrite).toHaveBeenCalledWith(blob)
})
- it("releases a failed flight so the action can be retried", async () => {
- const blob = new Blob(["png"], { type: "image/png" })
+ it("rejects an empty raster result before either writer", async () => {
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 expect(copyRenderedShareCard(async () => null, write)).rejects.toMatchObject({
+ stage: "rasterize",
})
- await act(async () => {
- await harness.copyButton.props.onClick()
+ await expect(downloadRenderedShareCard(async () => null, "share.png", write)).rejects.toMatchObject({
+ stage: "rasterize",
})
-
- 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())
+ expect(write).not.toHaveBeenCalled()
})
- 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>
+ it.each([
+ ["source", "preparing the preview"],
+ ["assets", "preparing images"],
+ ["fonts", "loading fonts"],
+ ["freeze", "freezing the preview"],
+ ["rasterize", "rendering the image"],
+ ] as const)("maps %s failures to stage-specific feedback", (stage, copy) => {
+ expect(shareCardRenderErrorMessage(new ShareCardRenderError(stage))).toBe(
+ `Couldn't generate image — ${copy} failed`,
+ )
+ expect(shareCardRenderErrorMessage(new ShareCardRenderError(stage, true))).toBe(
+ `Couldn't generate image — ${copy} took too long`,
+ )
+ })
- act(() => {
- copy = harness.copyButton.props.onClick()
+ it("writes web PNG bytes through one Clipboard API call", async () => {
+ const write = vi.fn().mockResolvedValue(undefined)
+ vi.stubGlobal("ClipboardItem", class ClipboardItem {
+ constructor(readonly items: Record<string, Blob>) {}
})
- 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()
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: { write },
})
+ const blob = new Blob(["png"], { type: "image/png" })
- 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)
- })
+ await writeShareCardToClipboard(blob)
- 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>
+ expect(write).toHaveBeenCalledTimes(1)
+ expect(write.mock.calls[0]![0]).toHaveLength(1)
+ expect(write.mock.calls[0]![0]![0].items).toEqual({ "image/png": blob })
+ })
- act(() => {
- copy = harness.copyButton.props.onClick()
+ it("forwards PNG bytes once through the native desktop clipboard", async () => {
+ const invoke = vi.fn().mockResolvedValue(undefined)
+ const webWrite = vi.fn()
+ vi.stubGlobal("window", {
+ __TAURI__: {},
+ __TAURI_INTERNALS__: { invoke },
})
- 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()
+ vi.stubGlobal("navigator", { userAgent: "Macintosh", clipboard: { write: webWrite } })
+ const bytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])
+
+ await writeShareCardToClipboard(new Blob([bytes], { type: "image/png" }))
+
+ expect(invoke).toHaveBeenCalledTimes(1)
+ expect(invoke.mock.calls[0]![0]).toBe("plugin:clipboard-manager|write_image")
+ expect([...new Uint8Array(invoke.mock.calls[0]![1].image)]).toEqual([...bytes])
+ expect(webWrite).not.toHaveBeenCalled()
+ })
+
+ it("does not retry Web Clipboard after a native desktop rejection", async () => {
+ const failure = new Error("native clipboard rejected")
+ const invoke = vi.fn().mockRejectedValue(failure)
+ const webWrite = vi.fn()
+ vi.stubGlobal("window", {
+ __TAURI__: {},
+ __TAURI_INTERNALS__: { invoke },
})
+ vi.stubGlobal("navigator", { userAgent: "Macintosh", clipboard: { write: webWrite } })
- expect(harness.write).not.toHaveBeenCalled()
- expect(toast.success).not.toHaveBeenCalled()
- expect(toast.error).not.toHaveBeenCalled()
+ await expect(writeShareCardToClipboard(new Blob(["png"]))).rejects.toBe(failure)
+
+ expect(invoke).toHaveBeenCalledTimes(1)
+ expect(webWrite).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>
+ it("does not retry Web Clipboard when the native invoke bridge is missing", async () => {
+ const webWrite = vi.fn()
+ vi.stubGlobal("window", { __TAURI__: {} })
+ vi.stubGlobal("navigator", { userAgent: "Macintosh", clipboard: { write: webWrite } })
+ vi.stubGlobal("ClipboardItem", ClipboardItemStub)
- 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
- })
+ await expect(writeShareCardToClipboard(new Blob(["png"]))).rejects.toThrow()
- 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")
+ expect(webWrite).not.toHaveBeenCalled()
})
})
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 bc01a8021..648bd4474 100644
--- a/src/web/src/components/community/messages/message-share-dialog.tsx
+++ b/src/web/src/components/community/messages/message-share-dialog.tsx
@@ -1,7 +1,6 @@
"use client"
-import { useCallback, useEffect, useMemo, useRef, useState } from "react"
-import Image from "next/image"
+import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent } from "react"
import { toBlob } from "html-to-image"
import { toast } from "sonner"
import { Check, Copy, Download, Highlighter, Loader2 } from "lucide-react"
@@ -19,440 +18,23 @@ import type { RenderMsg } from "@/lib/community/models/message"
import { displayReplyContent } from "@/lib/community/reply-content"
import { useProfilesByUserId } from "@/stores/community/ws"
import { readCommunityProfile } from "@/lib/community/profile-read"
+import { AnimatedAlookLogo } from "@/components/community/shell/animated-alook-logo"
+import {
+ capturePreparedShareImage,
+ prepareShareImageSession,
+ ShareImageSessionError,
+ type PreparedShareImageSession,
+} from "@/lib/community/share-image-session"
-const SHARE_IMAGE_READY_TIMEOUT_MS = 5_000
-const SHARE_IMAGE_RENDER_TIMEOUT_MS = 15_000
-const SHARE_IMAGE_PIXEL_RATIO = 2
-
-export type ShareCardRenderStage = "snapshot" | "fonts" | "rasterize" | "cleanup"
-
-export class ShareCardRenderError extends Error {
- constructor(
- readonly stage: ShareCardRenderStage,
- readonly timedOut = false,
- cause?: unknown,
- ) {
- super(`Share-card render ${timedOut ? "timed out" : "failed"} during ${stage}`)
- this.name = "ShareCardRenderError"
- this.cause = cause
- }
-}
-
-export class ShareCardImageTimeoutError extends Error {
- constructor() {
- super("A share-card image did not finish loading in time")
- this.name = "ShareCardImageTimeoutError"
- }
-}
-
-export class ShareImageSnapshotError extends Error {
- constructor() {
- super("Share-card image pixels are not readable")
- this.name = "ShareImageSnapshotError"
- }
-}
-
-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")
- || image.getAttribute("data-remote-image-kind") === "identity"
-}
-
-function isFailedProfilePhoto(image: HTMLImageElement): boolean {
- return image.getAttribute("data-avatar-photo-state") === "failed"
- || (
- image.getAttribute("data-remote-image-kind") === "identity"
- && image.getAttribute("data-remote-image-state") === "error"
- )
-}
-
-function isFailedContentImage(image: HTMLImageElement): boolean {
- return image.getAttribute("data-remote-image-kind") === "content"
- && image.getAttribute("data-remote-image-state") === "error"
-}
-
-function isReadyProfilePhoto(image: HTMLImageElement): boolean {
- if (image.getAttribute("data-remote-image-kind") === "identity") {
- return image.getAttribute("data-remote-image-state") === "ready"
- }
- return image.getAttribute("data-avatar-photo-state") === "ready"
-}
-
-function isUnreadyContentImage(image: HTMLImageElement): boolean {
- return image.getAttribute("data-remote-image-kind") === "content"
- && image.getAttribute("data-remote-image-state") !== "ready"
-}
-
-async function waitForImageLoad(
- image: HTMLImageElement,
- 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 (isFailedContentImage(image)) throw new ShareImageSnapshotError()
-
- if (!image.complete) {
- const result = await new Promise<"loaded" | "error" | "timeout" | "aborted">((resolve) => {
- let finished = false
- 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 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 })
- signal?.addEventListener("abort", aborted, { once: true })
- if (image.complete) finish(image.naturalWidth > 0 ? "loaded" : "error")
- else if (signal?.aborted) finish("aborted")
- })
- 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 (isFailedContentImage(image)) throw new ShareImageSnapshotError()
- if (image.naturalWidth <= 0 || image.naturalHeight <= 0) {
- return fallbackOrThrow(new ShareImageSnapshotError())
- }
- if (image.decode) {
- const result = await new Promise<"decoded" | "failed" | "timeout" | "aborted">((resolve) => {
- let finished = false
- const finish = (result: "decoded" | "failed" | "timeout" | "aborted") => {
- if (finished) return
- finished = true
- signal?.removeEventListener("abort", aborted)
- clearTimeout(timer)
- resolve(result)
- }
- 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 (isFailedContentImage(image)) throw new ShareImageSnapshotError()
- if (result !== "decoded" && isProfilePhoto(image)) return "fallback"
- }
- return "snapshot"
-}
-
-function nextPaint(): Promise<void> {
- if (typeof requestAnimationFrame !== "function") return Promise.resolve()
- return new Promise((resolve) => requestAnimationFrame(() => resolve()))
-}
-
-export async function waitForShareCardImages(
- node: HTMLElement,
- waitForPaint: () => Promise<void> = nextPaint,
- timeoutMs = SHARE_IMAGE_READY_TIMEOUT_MS,
- 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.map((disposition) => {
- if (isProfilePhoto(disposition.image) && !isReadyProfilePhoto(disposition.image)) {
- return { ...disposition, mode: "fallback" }
- }
- if (isUnreadyContentImage(disposition.image)) throw new ShareImageSnapshotError()
- return disposition
- })
-}
-
-type ShareImageWaiter = (
- node: HTMLElement,
- waitForPaint?: () => Promise<void>,
- timeoutMs?: number,
- signal?: AbortSignal,
-) => Promise<ShareCardImageDisposition[]>
-type ShareImageSnapshotter = (image: HTMLImageElement) => HTMLCanvasElement | null
-
-function copySnapshotPresentation(
- image: HTMLImageElement,
- canvas: HTMLCanvasElement,
- width: number,
- height: number,
-): void {
- canvas.className = image.className
- canvas.style.cssText = image.style.cssText
- for (const attribute of [...image.attributes]) {
- if (attribute.name.startsWith("data-") || attribute.name.startsWith("aria-")) {
- canvas.setAttribute(attribute.name, attribute.value)
- }
- }
- canvas.style.width = `${width}px`
- canvas.style.height = `${height}px`
-}
-
-function drawShareImageSnapshot(
- image: HTMLImageElement,
- canvas: HTMLCanvasElement,
- objectFit: string,
-): void {
- if (image.naturalWidth <= 0 || image.naturalHeight <= 0) {
- throw new ShareImageSnapshotError()
- }
- const context = canvas.getContext("2d")
- if (!context) throw new ShareImageSnapshotError()
-
- const sourceWidth = image.naturalWidth
- const sourceHeight = image.naturalHeight
- const targetWidth = canvas.width
- const targetHeight = canvas.height
- const containScale = Math.min(targetWidth / sourceWidth, targetHeight / sourceHeight)
- const coverScale = Math.max(targetWidth / sourceWidth, targetHeight / sourceHeight)
- const scale = objectFit === "contain"
- ? containScale
- : objectFit === "cover"
- ? coverScale
- : objectFit === "none"
- ? SHARE_IMAGE_PIXEL_RATIO
- : objectFit === "scale-down"
- ? Math.min(SHARE_IMAGE_PIXEL_RATIO, containScale)
- : null
-
- if (scale === null) {
- context.drawImage(image, 0, 0, targetWidth, targetHeight)
- return
- }
-
- const width = sourceWidth * scale
- const height = sourceHeight * scale
- context.drawImage(
- image,
- (targetWidth - width) / 2,
- (targetHeight - height) / 2,
- width,
- height,
- )
-}
-
-export function createShareImageSnapshot(image: HTMLImageElement): HTMLCanvasElement | null {
- const rect = image.getBoundingClientRect()
- if (rect.width <= 0 || rect.height <= 0) return null
-
- const createCanvas = () => {
- const canvas = document.createElement("canvas")
- canvas.width = Math.max(1, Math.round(rect.width * SHARE_IMAGE_PIXEL_RATIO))
- canvas.height = Math.max(1, Math.round(rect.height * SHARE_IMAGE_PIXEL_RATIO))
- copySnapshotPresentation(image, canvas, rect.width, rect.height)
- return canvas
- }
-
- const canvas = createCanvas()
- try {
- drawShareImageSnapshot(image, canvas, getComputedStyle(image).objectFit)
- canvas.toDataURL()
- return canvas
- } catch {
- throw new ShareImageSnapshotError()
- }
-}
-
-export async function snapshotShareCardImages(
- node: HTMLElement,
- createSnapshot: ShareImageSnapshotter = createShareImageSnapshot,
- waitForImages: ShareImageWaiter = waitForShareCardImages,
- waitForPaint: () => Promise<void> = nextPaint,
- signal?: AbortSignal,
-): Promise<() => void> {
- 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, replacement } of replacements.reverse()) {
- if (replacement.parentNode) replacement.replaceWith(image)
- }
- }
-
- try {
- 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)
- replacements.push({ image, replacement: canvas })
- }
- if (signal?.aborted) throw createShareCardAbortError()
- await waitForPaint()
- if (signal?.aborted) throw createShareCardAbortError()
- return restore
- } catch (error) {
- restore()
- throw error
- }
-}
-
-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> {
- const caveatFont = getComputedStyle(document.documentElement)
- .getPropertyValue("--font-caveat")
- .trim()
- if (document.fonts?.load && caveatFont) await document.fonts.load(`16px ${caveatFont}`)
- await document.fonts?.ready
-}
+export { ShareImageSessionError as ShareCardRenderError }
-export async function renderShareCard(
+async function renderShareCard(
node: HTMLElement,
- snapshotImages: ShareCardImageSnapshotter = snapshotShareCardImagesForRender,
- rasterize: ShareCardRasterizer = toBlob,
- options: ShareCardRenderOptions = {},
+ fontEmbedCSS = "",
+ rasterize = toBlob,
+ options: { timeoutMs?: number; signal?: AbortSignal } = {},
): Promise<Blob> {
- const timeoutMs = options.timeoutMs ?? SHARE_IMAGE_RENDER_TIMEOUT_MS
- const loadFonts = options.loadFonts ?? loadShareCardFonts
- let stage: ShareCardRenderStage = "snapshot"
- let restoreImages: (() => void) | null = null
- let cleanupRequested = false
- let cleanupComplete = false
- let stopped = false
- let terminalError: Error | null = null
-
- const enterStage = (nextStage: ShareCardRenderStage) => {
- stage = nextStage
- options.onStage?.(nextStage)
- }
- const cleanup = () => {
- cleanupRequested = true
- if (!restoreImages || cleanupComplete) return
- enterStage("cleanup")
- cleanupComplete = true
- restoreImages()
- }
-
- enterStage("snapshot")
- let rejectDeadline!: (reason: Error) => void
- const deadline = new Promise<never>((_resolve, reject) => {
- rejectDeadline = reject
- })
- const stop = (error: Error) => {
- if (stopped) return
- stopped = true
- terminalError = error
- try {
- cleanup()
- rejectDeadline(error)
- } catch (cleanupError) {
- terminalError = new ShareCardRenderError("cleanup", false, cleanupError)
- rejectDeadline(terminalError)
- }
- }
- 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, options.signal)
- if (cleanupRequested) cleanup()
- if (terminalError) throw terminalError
-
- enterStage("fonts")
- try {
- await loadFonts()
- } catch {
- // Font loading is best-effort; the fallback font is still renderable.
- }
- if (terminalError) throw terminalError
-
- enterStage("rasterize")
- const blob = await rasterize(node, {
- pixelRatio: SHARE_IMAGE_PIXEL_RATIO,
- fetchRequestInit: { credentials: "same-origin" },
- // Solid backdrop so the exported PNG never bleeds transparent corners
- // (the card's own rounded bg sits on top of this).
- backgroundColor: getComputedStyle(node).getPropertyValue("--card")?.trim() || undefined,
- })
- if (terminalError) throw terminalError
- if (!blob) throw new Error("Rasterizer returned no image")
- return blob
- } catch (error) {
- if (error instanceof ShareCardRenderError) throw error
- throw new ShareCardRenderError(stage, false, error)
- } finally {
- try {
- cleanup()
- } catch (error) {
- throw new ShareCardRenderError("cleanup", false, error)
- }
- }
- }
-
- try {
- return await Promise.race([lifecycle(), deadline])
- } finally {
- clearTimeout(timer)
- options.signal?.removeEventListener("abort", abort)
- }
+ return capturePreparedShareImage(node, fontEmbedCSS, rasterize, options)
}
type ShareCardRenderer = () => Promise<Blob | null>
@@ -482,7 +64,7 @@ export async function copyRenderedShareCard(
write: ShareCardBlobWriter = writeShareCardToClipboard,
): Promise<void> {
const blob = await render()
- if (!blob) throw new ShareCardRenderError("rasterize")
+ if (!blob) throw new ShareImageSessionError("rasterize")
await write(blob)
}
@@ -491,14 +73,11 @@ async function saveShareCardDownload(
filename: string,
save: ShareCardBlobWriter = (value) => {
const url = URL.createObjectURL(value)
- try {
- const anchor = document.createElement("a")
- anchor.href = url
- anchor.download = filename
- anchor.click()
- } finally {
- URL.revokeObjectURL(url)
- }
+ const anchor = document.createElement("a")
+ anchor.href = url
+ anchor.download = filename
+ anchor.click()
+ queueMicrotask(() => URL.revokeObjectURL(url))
},
): Promise<void> {
await save(blob)
@@ -510,17 +89,18 @@ export async function downloadRenderedShareCard(
save?: ShareCardBlobWriter,
): Promise<void> {
const blob = await render()
- if (!blob) throw new ShareCardRenderError("rasterize")
+ if (!blob) throw new ShareImageSessionError("rasterize")
await saveShareCardDownload(blob, filename, save)
}
export function shareCardRenderErrorMessage(error: unknown): string | null {
- if (!(error instanceof ShareCardRenderError)) return null
+ if (!(error instanceof ShareImageSessionError)) return null
const stage = {
- snapshot: "preparing images",
+ source: "preparing the preview",
+ assets: "preparing images",
fonts: "loading fonts",
+ freeze: "freezing the preview",
rasterize: "rendering the image",
- cleanup: "restoring the preview",
}[error.stage]
return error.timedOut
? `Couldn't generate image — ${stage} took too long`
@@ -533,18 +113,11 @@ type ShareCardExportFlight = {
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 / timestamp /
-// content) plus an Alook brand footer, then rasterises THAT SAME
-// node to PNG (WYSIWYG) via html-to-image — fully client-side, no backend. The
-// captured node has a fixed width and its own solid background so the export is
-// stable regardless of the surrounding theme surface.
-//
-// Multi-message (Gus uiux #128, Alli #133): pass an array of the selected
-// messages (in order). Consecutive same-author messages collapse the avatar/
-// name (each carries `grouped`, computed by the message list — reused verbatim),
-// exactly like the chat stream. Everything else — toBlob capture, Download/Copy,
-// drag-highlight — is shared; highlight is per-message (each body its own ref).
+type ShareSessionState =
+ | { status: "idle" | "preparing" }
+ | { status: "ready"; value: PreparedShareImageSession; filename: string }
+ | { status: "error"; message: string }
+
export function MessageShareDialog({ m, open, onClose }: {
m: RenderMsg | RenderMsg[]
open: boolean
@@ -553,47 +126,65 @@ export function MessageShareDialog({ m, open, onClose }: {
const messages = useMemo(() => (Array.isArray(m) ? m : [m]), [m])
const mobileNative = isTauri() && isMobile()
const profilesByUserId = useProfilesByUserId()
- const cardRef = useRef<HTMLDivElement>(null)
- // One body wrapper per message — highlight operations are scoped to the body
- // 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 profilesByUserIdRef = useRef(profilesByUserId)
+ const messagesRef = useRef(messages)
+ const previewRef = useRef<HTMLDivElement>(null)
const exportOwnerRef = useRef<{
generation: number
active: ShareCardExportFlight | null
}>({ generation: 0, active: null })
const copiedTimerRef = useRef<number | null>(null)
+ const pngRef = useRef<{
+ revision: number
+ promise: Promise<Blob>
+ } | 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
- // (not disabled) when there's nothing to reset — "less is more". Mirrors the
- // DOM (any `mark[data-hl]` across the bodies) after each apply/reset.
const [highlighted, setHighlighted] = useState(false)
+ const [captureRevision, setCaptureRevision] = useState(0)
+ const [prepareAttempt, setPrepareAttempt] = useState(0)
+ const [preparationNode, setPreparationNode] = useState<HTMLDivElement | null>(null)
+ const [session, setSession] = useState<ShareSessionState>({ status: "idle" })
- const anyHighlight = useCallback(
- () => [...bodyRefs.current.values()].some((b) => b && hasHighlights(b)),
- [],
- )
+ useEffect(() => {
+ profilesByUserIdRef.current = profilesByUserId
+ }, [profilesByUserId])
+
+ useEffect(() => {
+ messagesRef.current = messages
+ }, [messages])
+
+ const anyHighlight = useCallback(() => {
+ const preview = previewRef.current
+ return !!preview && [...preview.querySelectorAll<HTMLElement>("[data-share-body-id]")]
+ .some((body) => hasHighlights(body))
+ }, [])
- // On mouseup inside a message body, wrap the current selection in a highlight.
- // Text-node-level wrapping (see highlight-range.ts) — never surroundContents,
- // so it survives spanning multiple markdown elements. Drags stack; the browser
- // selection is collapsed afterward so it doesn't also land in the PNG. Scoped
- // to the one body the drag is in — a selection straying outside it is ignored.
- const onBodyMouseUp = useCallback((id: string) => {
- const body = bodyRefs.current.get(id)
- if (!body) return
+ const onPreviewMouseUp = useCallback((event: ReactMouseEvent<HTMLDivElement>) => {
+ if (busy !== null) return
+ const target = event.target instanceof Element ? event.target : null
+ const body = target?.closest<HTMLElement>("[data-share-body-id]")
+ if (!body || !previewRef.current?.contains(body)) return
const sel = window.getSelection?.()
if (!sel || sel.isCollapsed || sel.rangeCount === 0) return
const range = sel.getRangeAt(0)
if (!body.contains(range.commonAncestorContainer)) return
const added = applyHighlightToRange(body, range)
sel.removeAllRanges()
- if (added > 0) setHighlighted(anyHighlight())
- }, [anyHighlight])
+ if (added <= 0) return
+ pngRef.current = null
+ setCaptureRevision((value) => value + 1)
+ setHighlighted(anyHighlight())
+ }, [anyHighlight, busy])
const resetHighlights = useCallback(() => {
- for (const body of bodyRefs.current.values()) if (body) clearHighlights(body)
+ const preview = previewRef.current
+ if (!preview) return
+ for (const body of preview.querySelectorAll<HTMLElement>("[data-share-body-id]")) {
+ clearHighlights(body)
+ }
+ pngRef.current = null
+ setCaptureRevision((value) => value + 1)
setHighlighted(false)
}, [])
@@ -602,6 +193,7 @@ export function MessageShareDialog({ m, open, onClose }: {
owner.generation += 1
owner.active?.controller.abort()
owner.active = null
+ pngRef.current = null
if (copiedTimerRef.current !== null) {
window.clearTimeout(copiedTimerRef.current)
copiedTimerRef.current = null
@@ -609,14 +201,49 @@ export function MessageShareDialog({ m, open, onClose }: {
}, [])
useEffect(() => {
- if (!open) invalidateExport()
+ if (open) return
+ invalidateExport()
+ setBusy(null)
+ setCopied(false)
+ setSession({ status: "idle" })
+ setHighlighted(false)
}, [invalidateExport, open])
useEffect(() => () => invalidateExport(), [invalidateExport])
+ useEffect(() => {
+ if (!open) return
+ const source = preparationNode
+ if (!source) return
+ const controller = new AbortController()
+ const firstAuthorId = messagesRef.current[0]?.authorId
+ const firstAuthor = firstAuthorId
+ ? readCommunityProfile(profilesByUserIdRef.current.get(firstAuthorId), firstAuthorId)
+ : null
+ const filename = `alook-message-${firstAuthor?.name ?? "share"}.png`
+ setSession({ status: "preparing" })
+ setHighlighted(false)
+ pngRef.current = null
+ void prepareShareImageSession(source, { signal: controller.signal }).then(
+ (value) => {
+ if (controller.signal.aborted) return
+ setSession({ status: "ready", value, filename })
+ },
+ (error) => {
+ if (controller.signal.aborted || (error as { name?: unknown })?.name === "AbortError") return
+ setSession({
+ status: "error",
+ message: shareCardRenderErrorMessage(error) ?? "Couldn't prepare share image",
+ })
+ },
+ )
+ return () => controller.abort()
+ }, [open, preparationNode, prepareAttempt])
+
const startExport = useCallback((action: "copy" | "download"): Promise<void> => {
const owner = exportOwnerRef.current
if (owner.active) return owner.active.promise
+ if (session.status !== "ready") return Promise.resolve()
const id = owner.generation + 1
const controller = new AbortController()
@@ -634,22 +261,27 @@ export function MessageShareDialog({ m, open, onClose }: {
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 filename = session.filename
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,
- })
+ const node = previewRef.current?.querySelector<HTMLElement>("[data-share-card]")
+ if (!node) throw new ShareImageSessionError("rasterize")
+ let rendered = pngRef.current
+ if (!rendered || rendered.revision !== captureRevision) {
+ const promise = renderShareCard(node, session.value.fontEmbedCSS, toBlob, {
+ signal: controller.signal,
+ })
+ rendered = { revision: captureRevision, promise }
+ pngRef.current = rendered
+ promise.catch(() => {
+ if (pngRef.current?.promise === promise) pngRef.current = null
+ })
+ }
+ const blob = await rendered.promise
if (!isCurrent()) return
let mobileDestination: "photos" | "pictures" | "document" | null = null
@@ -714,7 +346,7 @@ export function MessageShareDialog({ m, open, onClose }: {
})()
return flight.promise
- }, [messages, mobileNative, profilesByUserId])
+ }, [captureRevision, mobileNative, session])
const close = useCallback(() => {
invalidateExport()
@@ -738,24 +370,43 @@ export function MessageShareDialog({ m, open, onClose }: {
<DialogTitle>{messages.length > 1 ? `Share ${messages.length} messages` : "Share message"}</DialogTitle>
</DialogHeader>
- {/* Preview area — the padding frames the card; the card itself is what
- gets captured. Scrolls when the card is tall (many messages, Alli
- #137): only the PREVIEW is height-bounded + scrollable — `toBlob`
- captures `cardRef` (the full card), so the export is never cut by
- this scroll bound. */}
- <div className="max-h-[60vh] overflow-y-auto bg-muted/40 px-6 py-6">
- {/* The card takes the full preview width — a generous, poster-like
- default so the share image reads as a proper card at any content
- length. The CARD itself is NOT height-capped: the exported PNG is
- the full card (Alli #137). Runaway height is bounded PER MESSAGE
- (each body clamps at 32 lines, below), and the PREVIEW container
- (the wrapper above) scrolls — so a many-message selection is fully
- exported but doesn't blow the popup out. */}
- <div
- ref={cardRef}
- data-share-card
- className="rounded-xl bg-card p-5 shadow-(--e1)"
- >
+ <div className="thin-scrollbar max-h-[60vh] overflow-y-auto bg-muted/40 px-6 py-6">
+ {session.status === "ready" ? (
+ <div
+ ref={previewRef}
+ onMouseUp={onPreviewMouseUp}
+ dangerouslySetInnerHTML={{ __html: session.value.markup }}
+ />
+ ) : (
+ <div
+ data-share-session-state={session.status}
+ className="flex min-h-48 flex-col items-center justify-center gap-3 rounded-xl bg-card p-5 text-sm text-muted-foreground shadow-(--e1)"
+ >
+ {session.status === "error" ? (
+ <>
+ <span>{session.message}</span>
+ <Button size="sm" variant="outline" onClick={() => setPrepareAttempt((value) => value + 1)}>
+ Retry
+ </Button>
+ </>
+ ) : (
+ <>
+ <Loader2 className="animate-spin" />
+ <span>Preparing share image…</span>
+ </>
+ )}
+ </div>
+ )}
+ {open && session.status !== "ready" && (
+ <div
+ aria-hidden
+ className="pointer-events-none fixed left-[-10000px] top-0 w-[calc(100vw-5rem)] max-w-2xl opacity-0"
+ >
+ <div
+ ref={setPreparationNode}
+ data-share-card-source
+ className="rounded-xl bg-card p-5 shadow-(--e1)"
+ >
{messages.map((msg) => {
const author = msg.authorId
? readCommunityProfile(profilesByUserId.get(msg.authorId), msg.authorId)
@@ -789,12 +440,14 @@ export function MessageShareDialog({ m, open, onClose }: {
{msg.grouped
? <div className="w-10 shrink-0" aria-hidden />
: (
+ <div data-share-identity-id={msg.authorId} className="size-10 shrink-0">
<Avatar
label={author?.name ?? msg.authorName ?? "Unknown"}
src={author?.avatar}
seed={msg.authorId}
size={40}
/>
+ </div>
)}
<div className="min-w-0 flex-1">
{!msg.grouped && (
@@ -816,21 +469,9 @@ export function MessageShareDialog({ m, open, onClose }: {
</span>
</div>
)}
- {/* Each body: clamp at 32 lines (Alli #137 — one number for
- single & multi share). Two layers, same as the original
- single-message card: `max-h` hard-bounds any structure
- (multi-paragraph markdown escapes line-clamp alone), and
- `line-clamp-[32]` gives a single-block message a tidy
- ellipsis. Each body also drives its own drag-highlight
- (per-message scope, Alli #133) via its ref in `bodyRefs`;
- the `mark[data-hl]` styles are the soft-yellow marker
- (rasterises cleanly under html-to-image — plain bg +
- box-decoration-break, no mask). max-h ≈ 32 lines at the
- body's 15px/leading-snug. */}
{visibleContent && (
<div
- ref={(el) => { bodyRefs.current.set(msg.id, el) }}
- onMouseUp={() => onBodyMouseUp(msg.id)}
+ data-share-body-id={msg.id}
className="max-h-164 overflow-hidden line-clamp-32 [&_mark[data-hl]]:rounded-xs [&_mark[data-hl]]:bg-[rgba(255,208,92,0.5)] [&_mark[data-hl]]:p-[0_1px] [&_mark[data-hl]]:[box-decoration-break:clone] [&_mark[data-hl]]:[-webkit-box-decoration-break:clone] [&_mark[data-hl]]:text-inherit"
>
<MessageBody
@@ -890,18 +531,20 @@ export function MessageShareDialog({ m, open, onClose }: {
)
})}
- {/* Brand footer — Alook logo + brand font, mirrors the marketing
- footer treatment. One footer for the whole card, single or multi. */}
<div className="mt-4 flex items-center gap-1.5 border-t border-border/50 pt-3">
- <Image src="/alook.svg" alt="" width={16} height={16} />
+ <AnimatedAlookLogo className="size-4" />
<span
+ data-share-brand
+ data-share-brand-font="caveat"
className="text-sm font-bold tracking-tight text-muted-foreground"
style={{ fontFamily: "var(--font-brand)" }}
>
Alook
</span>
</div>
- </div>
+ </div>
+ </div>
+ )}
</div>
<div className="flex items-center justify-between gap-2 px-5 pt-3 pb-5">
@@ -922,7 +565,7 @@ export function MessageShareDialog({ m, open, onClose }: {
size="sm"
data-testid={mobileNative ? tid.messageShareSave : undefined}
onClick={download}
- disabled={busy !== null}
+ disabled={busy !== null || session.status !== "ready"}
>
{busy === "download" ? <Loader2 className="animate-spin" /> : <Download />}
{mobileNative ? "Save image" : "Download"}
@@ -931,7 +574,7 @@ export function MessageShareDialog({ m, open, onClose }: {
size="sm"
data-testid={tid.messageShareCopy}
onClick={copy}
- disabled={busy !== null}
+ disabled={busy !== null || session.status !== "ready"}
>
{busy === "copy" ? <Loader2 className="animate-spin" /> : copied ? <Check /> : <Copy />}
{copied ? "Copied" : "Copy image"}
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
new file mode 100644
index 000000000..f8d629f5e
--- /dev/null
+++ b/src/web/src/lib/community/share-image-session.dom.test.ts
@@ -0,0 +1,1004 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { act } from "@/test/react-dom-harness"
+import { getFontEmbedCSS } from "html-to-image"
+import {
+ capturePreparedShareImage,
+ prepareShareImageSession,
+} from "./share-image-session"
+
+const FONT_CSS = "@font-face{font-family:Brand;src:url(data:font/woff2;base64,AA==)}"
+
+vi.mock("html-to-image", () => ({ getFontEmbedCSS: vi.fn() }))
+
+class DecodableImage {
+ onload: ((event: Event) => void) | null = null
+ onerror: ((event: Event) => void) | null = null
+ naturalWidth = 2
+ naturalHeight = 2
+ decode = vi.fn().mockResolvedValue(undefined)
+
+ set src(_value: string) {
+ queueMicrotask(() => this.onload?.(new Event("load")))
+ }
+}
+
+function sourceCard(markup: string): HTMLElement {
+ const wrapper = document.createElement("div")
+ wrapper.innerHTML = `
+ <div data-share-card-source style="width:320px;background-color:rgb(255,255,255);--card:rgb(255,255,255)">
+ ${markup}
+ <span data-share-brand data-share-brand-font="Brand" style="font-family:Brand;font-weight:700">Alook</span>
+ </div>
+ `
+ const source = wrapper.firstElementChild as HTMLElement
+ document.body.appendChild(source)
+ return source
+}
+
+function imageResponse(
+ bytes = new Uint8Array([1, 2, 3]),
+ contentType = "image/png",
+): Response {
+ return new Response(bytes, {
+ headers: {
+ "Content-Type": contentType,
+ "Content-Length": String(bytes.byteLength),
+ },
+ })
+}
+
+function dataUrlResponse(bytes: Uint8Array) {
+ return {
+ ok: true,
+ blob: vi.fn().mockResolvedValue(new Blob([bytes], { type: "image/png" })),
+ }
+}
+
+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 prepare(
+ source: HTMLElement,
+ fetchAsset: typeof fetch = vi.fn(),
+ maxSessionAssetBytes?: number,
+) {
+ return prepareShareImageSession(source, {
+ fetchAsset,
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ maxSessionAssetBytes,
+ staticizeAsset: async (blob) => blob,
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })
+}
+
+beforeEach(() => {
+ vi.mocked(getFontEmbedCSS).mockResolvedValue(FONT_CSS)
+ vi.stubGlobal("Image", DecodableImage)
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 320, 180))
+ Object.defineProperty(document, "fonts", {
+ configurable: true,
+ value: {
+ load: vi.fn().mockResolvedValue([{} as FontFace]),
+ ready: Promise.resolve(),
+ check: vi.fn(() => true),
+ },
+ })
+})
+
+afterEach(() => {
+ document.body.replaceChildren()
+ delete (document as Document & { fonts?: FontFaceSet }).fonts
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+})
+
+describe("prepareShareImageSession", () => {
+ it("prepares an image-free source with default options", async () => {
+ const requestFrame = vi.fn((callback: FrameRequestCallback) => {
+ callback(1)
+ return 1
+ })
+ vi.stubGlobal("requestAnimationFrame", requestFrame)
+ const source = sourceCard("<span>default options</span>")
+
+ const prepared = await prepareShareImageSession(source)
+
+ expect(prepared.markup).toContain("default options")
+ expect(getFontEmbedCSS).toHaveBeenCalledTimes(1)
+ expect(Object.isFrozen(prepared)).toBe(true)
+ })
+
+ 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())
+
+ const prepared = await prepare(source, fetchAsset)
+
+ expect(fetchAsset).toHaveBeenCalledTimes(1)
+ expect(fetchAsset.mock.calls[0]![0]).toMatch(/\/content\.png$/)
+ expect(fetchAsset.mock.calls[0]![1]).toMatchObject({
+ credentials: "same-origin",
+ redirect: "error",
+ })
+ expect(prepared.markup).toContain("data-share-card=\"\"")
+ expect(prepared.markup).not.toContain("data-share-card-source")
+ expect(prepared.markup).toContain("data:image/png;base64,AQID")
+ expect(prepared.markup).toContain("data-share-byte-backed=\"true\"")
+ expect(prepared.markup).toContain("animation: none !important")
+ expect(prepared.fontEmbedCSS).toBe(FONT_CSS)
+ expect(source.querySelector("img")?.getAttribute("src")).toBe("/content.png")
+ expect(document.querySelector("[data-share-detached-tree]")).toBeNull()
+ expect(Object.isFrozen(prepared)).toBe(true)
+ })
+
+ it("normalizes an external visible avatar through the scoped same-origin route", async () => {
+ const source = sourceCard(`
+ <div data-share-identity-id="user 1">
+ <img data-avatar-photo-state="ready" src="https://avatars.githubusercontent.com/u/1?v=4">
+ </div>
+ `)
+ const fetchAsset = vi.fn().mockResolvedValue(imageResponse())
+
+ const prepared = await prepare(source, fetchAsset)
+
+ expect(fetchAsset).toHaveBeenCalledWith(
+ "/api/community/share-image/avatar/user%201",
+ expect.objectContaining({ credentials: "same-origin", redirect: "error" }),
+ )
+ expect(prepared.markup).not.toContain("avatars.githubusercontent.com")
+ expect(prepared.markup).toContain("data:image/png;base64,AQID")
+ })
+
+ it("encodes the format-defined default frame as a static PNG before ready", async () => {
+ const bitmap = { width: 8, height: 8, close: vi.fn() }
+ const createBitmap = vi.fn().mockResolvedValue(bitmap)
+ const drawImage = vi.fn()
+ vi.stubGlobal("createImageBitmap", createBitmap)
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => ({
+ drawImage,
+ }) as unknown as CanvasRenderingContext2D)
+ vi.spyOn(HTMLCanvasElement.prototype, "toBlob").mockImplementation((callback) => {
+ callback(new Blob([new Uint8Array([9])], { type: "image/png" }))
+ })
+ const source = sourceCard('<img src="/animated.gif" alt="animated">')
+ const fetchAsset = vi.fn().mockResolvedValue(imageResponse(
+ new Uint8Array([71, 73, 70]),
+ "image/gif",
+ ))
+
+ const prepared = await prepareShareImageSession(source, {
+ fetchAsset,
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })
+
+ expect(createBitmap).toHaveBeenCalledTimes(1)
+ expect(createBitmap.mock.calls[0]![0]).toMatchObject({ type: "image/gif", size: 3 })
+ expect(drawImage).toHaveBeenCalledWith(bitmap, 0, 0, 8, 8)
+ expect(prepared.markup).toContain("data:image/png;base64,CQ==")
+ expect(prepared.markup).not.toContain("data:image/gif")
+ expect(bitmap.close).toHaveBeenCalledTimes(1)
+ })
+
+ it("uses the largest occurrence target for a repeated asset regardless of DOM order", async () => {
+ const run = async (order: readonly ["small", "large"] | readonly ["large", "small"]) => {
+ vi.mocked(HTMLElement.prototype.getBoundingClientRect).mockImplementation(function () {
+ if (!(this instanceof HTMLImageElement)) return new DOMRect(0, 0, 320, 180)
+ return this.dataset.size === "large"
+ ? new DOMRect(0, 0, 80, 40)
+ : new DOMRect(0, 0, 20, 10)
+ })
+ const source = sourceCard(order.map((size) => (
+ `<img data-size="${size}" src="/same.png">`
+ )).join(""))
+ const targets: Array<{ width: number; height: number }> = []
+ const staticizeAsset = vi.fn(async (_blob: Blob, target: { width: number; height: number }) => {
+ targets.push(target)
+ return new Blob([JSON.stringify(target)], { type: "image/png" })
+ })
+ const fetchAsset = vi.fn(() => Promise.resolve(imageResponse()))
+ const prepared = await prepareShareImageSession(source, {
+ fetchAsset,
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ staticizeAsset,
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })
+ const parsed = document.createElement("div")
+ parsed.innerHTML = prepared.markup
+ const card = parsed.firstElementChild as HTMLElement
+ document.body.appendChild(card)
+ const sources = [...card.querySelectorAll<HTMLImageElement>("img")]
+ .map((image) => image.src)
+ const exported = await capturePreparedShareImage(card, FONT_CSS, async (capture) => {
+ const captureSources = [...capture.querySelectorAll<HTMLImageElement>("img")]
+ .map((image) => image.src)
+ expect(captureSources).toEqual(sources)
+ return new Blob([sources[0]!], { type: "image/png" })
+ })
+ card.remove()
+ source.remove()
+ return {
+ exportBytes: [...new Uint8Array(await exported.arrayBuffer())],
+ fetchAsset,
+ sources,
+ staticizeAsset,
+ targets,
+ }
+ }
+
+ const smallFirst = await run(["small", "large"])
+ const largeFirst = await run(["large", "small"])
+
+ for (const result of [smallFirst, largeFirst]) {
+ expect(result.fetchAsset).toHaveBeenCalledTimes(1)
+ expect(result.staticizeAsset).toHaveBeenCalledTimes(1)
+ expect(result.targets).toEqual([{ width: 160, height: 80 }])
+ expect(new Set(result.sources).size).toBe(1)
+ }
+ expect(smallFirst.sources[0]).toBe(largeFirst.sources[0])
+ expect(smallFirst.exportBytes).toEqual(largeFirst.exportBytes)
+ })
+
+ it("keeps unsupported decode semantics split between content and identity", async () => {
+ vi.stubGlobal("createImageBitmap", vi.fn().mockRejectedValue(new Error("codec unavailable")))
+ const fetchAsset = vi.fn(() => Promise.resolve(imageResponse()))
+ const content = sourceCard('<img src="/content.webp">')
+
+ await expect(prepareShareImageSession(content, {
+ fetchAsset,
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })).rejects.toMatchObject({ stage: "assets" })
+
+ content.remove()
+ const identity = sourceCard(`
+ <div data-share-identity-id="u1">
+ <img data-avatar-photo-state="ready" src="/avatar.webp">
+ </div>
+ `)
+ const prepared = await prepareShareImageSession(identity, {
+ fetchAsset,
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })
+ expect(prepared.markup).toContain("data-share-identity-fallback=\"beam\"")
+ expect(prepared.markup).not.toContain("<img")
+ })
+
+ it("treats decoded dimension overflow as a hard budget error for identities", async () => {
+ const bitmap = { width: 8_193, height: 1, close: vi.fn() }
+ vi.stubGlobal("createImageBitmap", vi.fn().mockResolvedValue(bitmap))
+ const source = sourceCard(`
+ <div data-share-identity-id="u1">
+ <img data-avatar-photo-state="ready" src="/avatar.png">
+ </div>
+ `)
+
+ await expect(prepareShareImageSession(source, {
+ fetchAsset: vi.fn().mockResolvedValue(imageResponse()),
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })).rejects.toMatchObject({
+ stage: "assets",
+ cause: { name: "ShareImageSessionBudgetError" },
+ })
+ expect(bitmap.close).toHaveBeenCalledTimes(1)
+ expect(source.querySelector("[data-share-identity-fallback]")).toBeNull()
+ })
+
+ it("caps summed decoded pixels across unique session assets", async () => {
+ const bitmaps = [
+ { width: 4_096, height: 2_048, close: vi.fn() },
+ { width: 4_096, height: 2_049, close: vi.fn() },
+ ]
+ vi.stubGlobal("createImageBitmap", vi.fn()
+ .mockResolvedValueOnce(bitmaps[0])
+ .mockResolvedValueOnce(bitmaps[1]))
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => ({
+ drawImage: vi.fn(),
+ }) as unknown as CanvasRenderingContext2D)
+ vi.spyOn(HTMLCanvasElement.prototype, "toBlob").mockImplementation((callback) => {
+ callback(new Blob([new Uint8Array([9])], { type: "image/png" }))
+ })
+ const source = sourceCard('<img src="/one.png"><img src="/two.png">')
+
+ await expect(prepareShareImageSession(source, {
+ fetchAsset: vi.fn(() => Promise.resolve(imageResponse())),
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })).rejects.toMatchObject({
+ stage: "assets",
+ cause: { name: "ShareImageSessionBudgetError" },
+ })
+ expect(bitmaps[0].close).toHaveBeenCalledTimes(1)
+ expect(bitmaps[1].close).toHaveBeenCalledTimes(1)
+ expect(source.querySelector("[data-share-byte-backed]")).toBeNull()
+ })
+
+ it("treats oversized static PNG output as a hard budget error for identities", async () => {
+ const source = sourceCard(`
+ <div data-share-identity-id="u1">
+ <img data-avatar-photo-state="ready" src="/avatar.png">
+ </div>
+ `)
+ const oversizedPng = {
+ type: "image/png",
+ size: 10 * 1024 * 1024 + 1,
+ } as Blob
+
+ await expect(prepareShareImageSession(source, {
+ fetchAsset: vi.fn().mockResolvedValue(imageResponse()),
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ staticizeAsset: vi.fn().mockResolvedValue(oversizedPng),
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })).rejects.toMatchObject({
+ stage: "assets",
+ cause: { name: "ShareImageSessionBudgetError" },
+ })
+ expect(source.querySelector("[data-share-identity-fallback]")).toBeNull()
+ })
+
+ it("fetches external content without credentials and fails the session atomically on error", async () => {
+ const source = sourceCard('<img src="https://cdn.example/photo.png" alt="content">')
+ const fetchAsset = vi.fn().mockRejectedValue(new Error("CORS denied"))
+
+ await expect(prepare(source, fetchAsset)).rejects.toMatchObject({ stage: "assets" })
+ expect(fetchAsset).toHaveBeenCalledWith(
+ "https://cdn.example/photo.png",
+ expect.objectContaining({ credentials: "omit", redirect: "error" }),
+ )
+ expect(source.querySelector("img")?.getAttribute("src")).toBe("https://cdn.example/photo.png")
+ expect(source.querySelector("[data-share-identity-fallback]")).toBeNull()
+ expect(document.querySelector("[data-share-detached-tree]")).toBeNull()
+ })
+
+ it("seeds nested avatar fallbacks by stable identity instead of the changing photo URL", async () => {
+ const markup = (url: string) => `
+ <div data-share-identity-id="u1" aria-label="Alice">
+ <span data-avatar-kind="photo">
+ <img data-avatar-photo-state="error" src="${url}">
+ </span>
+ </div>
+ `
+ const fetchAsset = vi.fn().mockRejectedValue(new Error("offline"))
+ const first = sourceCard(markup("https://avatars.githubusercontent.com/u/1?v=old"))
+ const firstPrepared = await prepare(first, fetchAsset)
+ first.remove()
+ const second = sourceCard(markup("https://avatars.githubusercontent.com/u/1?v=new"))
+ const secondPrepared = await prepare(second, fetchAsset)
+
+ expect(firstPrepared.markup).toBe(secondPrepared.markup)
+ expect(firstPrepared.markup).toContain("data-share-identity-fallback=\"beam\"")
+ expect(firstPrepared.markup).not.toContain("<img")
+ expect(first.querySelector("img")).not.toBeNull()
+ })
+
+ it("counts a repeated asset once against the session byte budget", async () => {
+ const fetchAsset = vi.fn().mockResolvedValue(imageResponse())
+ const source = sourceCard('<img src="/warm.png"><img src="/warm.png">')
+
+ const prepared = await prepare(source, fetchAsset, 3)
+
+ expect(fetchAsset).toHaveBeenCalledTimes(1)
+ expect(prepared.markup.match(/data:image\/png;base64,AQID/g)).toHaveLength(2)
+ })
+
+ it("accepts unique assets totaling exactly the aggregate session byte budget", async () => {
+ const source = sourceCard('<img src="/one.png"><img src="/two.png">')
+ const fetchAsset = vi.fn((input: string | URL | Request) => Promise.resolve(
+ imageResponse(String(input).endsWith("one.png")
+ ? new Uint8Array([1, 2])
+ : new Uint8Array([3, 4, 5])),
+ ))
+
+ const prepared = await prepare(source, fetchAsset, 5)
+
+ expect(fetchAsset).toHaveBeenCalledTimes(2)
+ expect(prepared.markup).toContain("data:image/png;base64,AQI=")
+ expect(prepared.markup).toContain("data:image/png;base64,AwQF")
+ })
+
+ it("fails atomically when unique assets exceed the aggregate session byte budget", async () => {
+ const source = sourceCard('<img src="/one.png"><img src="/two.png">')
+ const fetchAsset = vi.fn(() => Promise.resolve(imageResponse()))
+
+ await expect(prepare(source, fetchAsset, 5)).rejects.toMatchObject({
+ stage: "assets",
+ cause: { name: "ShareImageSessionBudgetError" },
+ })
+
+ expect(fetchAsset).toHaveBeenCalledTimes(2)
+ expect(source.querySelectorAll('img[src$=".png"]')).toHaveLength(2)
+ expect(source.querySelector("[data-share-byte-backed]")).toBeNull()
+ expect(document.querySelector("[data-share-detached-tree]")).toBeNull()
+ })
+
+ it("does not downgrade an aggregate byte overflow to an avatar fallback", async () => {
+ const source = sourceCard(`
+ <div data-share-identity-id="u1">
+ <img data-avatar-photo-state="ready" src="https://avatars.githubusercontent.com/u/1?v=4">
+ </div>
+ `)
+ const fetchAsset = vi.fn(() => Promise.resolve(
+ imageResponse(new Uint8Array([1, 2, 3, 4, 5, 6])),
+ ))
+
+ await expect(prepare(source, fetchAsset, 5)).rejects.toMatchObject({
+ stage: "assets",
+ cause: { name: "ShareImageSessionBudgetError" },
+ })
+
+ expect(source.querySelector("img")).not.toBeNull()
+ expect(source.querySelector("[data-share-identity-fallback]")).toBeNull()
+ expect(document.querySelector("[data-share-detached-tree]")).toBeNull()
+ })
+
+ it("starts a fresh aggregate byte budget when preparation is retried", async () => {
+ const source = sourceCard('<img src="/one.png"><img src="/two.png">')
+ const firstFetch = vi.fn(() => Promise.resolve(imageResponse()))
+
+ await expect(prepare(source, firstFetch, 5)).rejects.toMatchObject({ stage: "assets" })
+
+ const retryFetch = vi.fn(() => Promise.resolve(imageResponse(new Uint8Array([1, 2]))))
+ const prepared = await prepare(source, retryFetch, 5)
+
+ expect(retryFetch).toHaveBeenCalledTimes(2)
+ expect(prepared.markup.match(/data:image\/png;base64,AQI=/g)).toHaveLength(2)
+ expect(source.querySelector("[data-share-byte-backed]")).toBeNull()
+ })
+
+ it.each([
+ ["first then second", ["one", "two"]],
+ ["second then first", ["two", "one"]],
+ ] as const)("fails over-budget concurrent assets when they finish %s", async (_label, order) => {
+ const source = sourceCard('<img src="/one.png"><img src="/two.png">')
+ const responses = {
+ one: deferred<Response>(),
+ two: deferred<Response>(),
+ }
+ const fetchAsset = vi.fn((input: string | URL | Request) => (
+ String(input).endsWith("one.png") ? responses.one.promise : responses.two.promise
+ ))
+ const preparation = prepare(source, fetchAsset, 5)
+ const assertion = expect(preparation).rejects.toMatchObject({
+ stage: "assets",
+ cause: { name: "ShareImageSessionBudgetError" },
+ })
+ await vi.waitFor(() => expect(fetchAsset).toHaveBeenCalledTimes(2))
+
+ for (const key of order) {
+ responses[key].resolve(imageResponse())
+ await Promise.resolve()
+ }
+
+ await assertion
+ expect(document.querySelector("[data-share-detached-tree]")).toBeNull()
+ })
+
+ it("cancels remaining response reads when the aggregate byte budget is exceeded", async () => {
+ const source = sourceCard('<img src="/overflow.png"><img src="/blocked.png">')
+ const overflow = deferred<Response>()
+ const blockedPull = vi.fn(() => new Promise<void>(() => {}))
+ const blockedCancel = vi.fn()
+ const blockedResponse = new Response(new ReadableStream<Uint8Array>({
+ pull: blockedPull,
+ cancel: blockedCancel,
+ }), { headers: { "Content-Type": "image/png" } })
+ const fetchAsset = vi.fn((input: string | URL | Request) => (
+ String(input).endsWith("overflow.png") ? overflow.promise : Promise.resolve(blockedResponse)
+ ))
+ const preparation = prepare(source, fetchAsset, 5)
+ const assertion = expect(preparation).rejects.toMatchObject({
+ stage: "assets",
+ cause: { name: "ShareImageSessionBudgetError" },
+ })
+ await vi.waitFor(() => expect(blockedPull).toHaveBeenCalled())
+
+ overflow.resolve(imageResponse(new Uint8Array([1, 2, 3, 4, 5, 6])))
+
+ await assertion
+ await vi.waitFor(() => expect(blockedCancel).toHaveBeenCalled())
+ })
+
+ it("times out a non-cooperative asset request", async () => {
+ vi.useFakeTimers()
+ const source = sourceCard('<img src="/pending.png">')
+ const fetchAsset = vi.fn(() => new Promise<Response>(() => {}))
+ const pending = prepareShareImageSession(source, {
+ fetchAsset,
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ timeoutMs: 25,
+ })
+ const assertion = expect(pending).rejects.toMatchObject({ stage: "assets", timedOut: true })
+
+ await act(async () => vi.advanceTimersByTimeAsync(25))
+
+ await assertion
+ expect(document.querySelector("[data-share-detached-tree]")).toBeNull()
+ })
+
+ it("treats an empty font embed as a hard preparation failure", async () => {
+ const source = sourceCard("<span>hello</span>")
+
+ await expect(prepareShareImageSession(source, {
+ getFontCSS: vi.fn().mockResolvedValue(""),
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })).rejects.toMatchObject({ stage: "fonts", timedOut: false })
+ })
+
+ it("times out while waiting for unresolved source placeholders", async () => {
+ vi.useFakeTimers()
+ const source = sourceCard('<span data-slot="skeleton">loading</span>')
+ const pending = prepareShareImageSession(source, {
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ timeoutMs: 25,
+ })
+ const assertion = expect(pending).rejects.toMatchObject({ stage: "source", timedOut: true })
+
+ await act(async () => vi.advanceTimersByTimeAsync(25))
+
+ await assertion
+ })
+
+ it("uses requestAnimationFrame for default paint waits", async () => {
+ const requestFrame = vi.fn((callback: FrameRequestCallback) => {
+ callback(1)
+ return 1
+ })
+ vi.stubGlobal("requestAnimationFrame", requestFrame)
+ const source = sourceCard("<span>ready</span>")
+
+ const prepared = await prepareShareImageSession(source, {
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ })
+
+ expect(prepared.markup).toContain("ready")
+ expect(requestFrame).toHaveBeenCalledTimes(4)
+ })
+
+ it("falls back to resolved paint waits when requestAnimationFrame is unavailable", async () => {
+ vi.stubGlobal("requestAnimationFrame", undefined)
+ const source = sourceCard("<span>ready</span>")
+
+ const prepared = await prepareShareImageSession(source, {
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ })
+
+ expect(prepared.markup).toContain("ready")
+ })
+
+ it("waits through irrelevant source mutations until the skeleton is removed", async () => {
+ const source = sourceCard('<span data-slot="skeleton">loading</span>')
+ const pending = prepare(source)
+
+ source.appendChild(document.createElement("span"))
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ source.querySelector('[data-slot="skeleton"]')!.remove()
+
+ await expect(pending).resolves.toMatchObject({ fontEmbedCSS: FONT_CSS })
+ })
+
+ it("handles a source skeleton disappearing during observer setup", async () => {
+ const disconnect = vi.fn()
+ class RaceMutationObserver {
+ constructor(_callback: MutationCallback) {}
+
+ observe(target: Node) {
+ ;(target as Element).querySelector('[data-slot="skeleton"]')?.remove()
+ }
+
+ disconnect() {
+ disconnect()
+ }
+ }
+ vi.stubGlobal("MutationObserver", RaceMutationObserver)
+ const source = sourceCard('<span data-slot="skeleton">loading</span>')
+
+ await expect(prepare(source)).resolves.toMatchObject({ fontEmbedCSS: FONT_CSS })
+ expect(disconnect).toHaveBeenCalled()
+ })
+
+ it("propagates an external abort while waiting for the source", async () => {
+ const controller = new AbortController()
+ const source = sourceCard('<span data-slot="skeleton">loading</span>')
+ const pending = prepareShareImageSession(source, {
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ signal: controller.signal,
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })
+
+ controller.abort()
+
+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })
+ })
+
+ it("counts padded base64 data URLs while ignoring ASCII whitespace", async () => {
+ const readDataUrl = vi.fn().mockResolvedValue(dataUrlResponse(new Uint8Array([7])))
+ vi.stubGlobal("fetch", readDataUrl)
+ const source = sourceCard('<img alt="inline">')
+ source.querySelector("img")!.setAttribute("src", "data:image/png;BASE64,A\tA\f\r\n == ")
+
+ const prepared = await prepare(source, vi.fn(), 1)
+
+ expect(readDataUrl).toHaveBeenCalledTimes(1)
+ expect(prepared.markup).toContain("data:image/png;base64,Bw==")
+ })
+
+ it("counts percent escapes and UTF-8 code points in non-base64 data URLs", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(dataUrlResponse(new Uint8Array([8]))))
+ const source = sourceCard('<img alt="inline">')
+ source.querySelector("img")!.setAttribute("src", "data:image/png,A%20é中😀")
+
+ const prepared = await prepare(source, vi.fn(), 11)
+
+ expect(prepared.markup).toContain("data:image/png;base64,CA==")
+ })
+
+ it("rejects malformed and unreadable data URLs atomically", async () => {
+ const malformed = sourceCard('<img src="data:image/png;base64" alt="malformed">')
+ await expect(prepare(malformed)).rejects.toMatchObject({ stage: "assets" })
+ malformed.remove()
+
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, { status: 500 })))
+ const unreadable = sourceCard('<img src="data:image/png;base64,AQ==" alt="unreadable">')
+ await expect(prepare(unreadable)).rejects.toMatchObject({ stage: "assets" })
+ })
+
+ it("fails when the platform static decoder is unavailable or returns no pixels", async () => {
+ vi.stubGlobal("createImageBitmap", undefined)
+ const unavailable = sourceCard('<img src="/content.png">')
+ await expect(prepareShareImageSession(unavailable, {
+ fetchAsset: vi.fn().mockResolvedValue(imageResponse()),
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })).rejects.toMatchObject({ stage: "assets" })
+ unavailable.remove()
+
+ const bitmap = { width: 0, height: 2, close: vi.fn() }
+ vi.stubGlobal("createImageBitmap", vi.fn().mockResolvedValue(bitmap))
+ const empty = sourceCard('<img src="/empty.png">')
+ await expect(prepareShareImageSession(empty, {
+ fetchAsset: vi.fn().mockResolvedValue(imageResponse()),
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })).rejects.toMatchObject({ stage: "assets" })
+ expect(bitmap.close).toHaveBeenCalledTimes(1)
+ })
+
+ it("rejects unsupported, declared-oversized, and streamed-oversized responses", async () => {
+ const unsupported = sourceCard('<img src="/asset.svg">')
+ await expect(prepare(unsupported, vi.fn().mockResolvedValue(
+ imageResponse(new Uint8Array([1]), "image/svg+xml"),
+ ))).rejects.toMatchObject({ stage: "assets" })
+ unsupported.remove()
+
+ const declared = sourceCard('<img src="/declared.png">')
+ await expect(prepare(declared, vi.fn().mockResolvedValue(new Response(new Uint8Array([1]), {
+ headers: {
+ "Content-Type": "image/png",
+ "Content-Length": String(10 * 1024 * 1024 + 1),
+ },
+ })))).rejects.toMatchObject({ stage: "assets" })
+ declared.remove()
+
+ const streamed = sourceCard('<img src="/streamed.png">')
+ const oversized = new Uint8Array(10 * 1024 * 1024 + 1)
+ const response = new Response(new ReadableStream<Uint8Array>({
+ start(streamController) {
+ streamController.enqueue(oversized)
+ streamController.close()
+ },
+ }), { headers: { "Content-Type": "image/png" } })
+ await expect(prepare(streamed, vi.fn().mockResolvedValue(response)))
+ .rejects.toMatchObject({ stage: "assets" })
+ })
+
+ it("reads bodyless responses and enforces their post-read size", async () => {
+ const bodyless = sourceCard('<img src="/bodyless.png">')
+ const bodylessResponse = {
+ ok: true,
+ headers: new Headers({ "Content-Type": "image/png" }),
+ body: null,
+ blob: vi.fn().mockResolvedValue(new Blob([new Uint8Array([1, 2, 3])], {
+ type: "image/png",
+ })),
+ } as unknown as Response
+
+ await expect(prepare(bodyless, vi.fn().mockResolvedValue(bodylessResponse), 3))
+ .resolves.toMatchObject({ fontEmbedCSS: FONT_CSS })
+ expect(bodylessResponse.blob).toHaveBeenCalledTimes(1)
+ bodyless.remove()
+
+ const oversized = sourceCard('<img src="/bodyless-large.png">')
+ const oversizedResponse = {
+ ok: true,
+ headers: new Headers({ "Content-Type": "image/png" }),
+ body: null,
+ blob: vi.fn().mockResolvedValue({
+ size: 10 * 1024 * 1024 + 1,
+ type: "image/png",
+ } as Blob),
+ } as unknown as Response
+ await expect(prepare(oversized, vi.fn().mockResolvedValue(oversizedResponse)))
+ .rejects.toMatchObject({ stage: "assets" })
+ })
+
+ it("fails atomically when FileReader cannot encode or read the static PNG", async () => {
+ class NonStringFileReader extends EventTarget {
+ result: string | ArrayBuffer | null = new ArrayBuffer(0)
+ error: DOMException | null = null
+
+ abort() {}
+
+ readAsDataURL() {
+ queueMicrotask(() => this.dispatchEvent(new Event("load")))
+ }
+ }
+ vi.stubGlobal("FileReader", NonStringFileReader)
+ const nonString = sourceCard('<img src="/non-string.png">')
+ await expect(prepare(nonString, vi.fn().mockResolvedValue(imageResponse())))
+ .rejects.toMatchObject({ stage: "assets" })
+ nonString.remove()
+
+ class ErrorFileReader extends EventTarget {
+ result: string | ArrayBuffer | null = null
+ error: DOMException | null = null
+
+ abort() {}
+
+ readAsDataURL() {
+ queueMicrotask(() => this.dispatchEvent(new Event("error")))
+ }
+ }
+ vi.stubGlobal("FileReader", ErrorFileReader)
+ const unreadable = sourceCard('<img src="/unreadable.png">')
+ await expect(prepare(unreadable, vi.fn().mockResolvedValue(imageResponse())))
+ .rejects.toMatchObject({ stage: "assets" })
+ })
+
+ it("fails when installed PNG bytes have no pixels or reject decode", async () => {
+ class ZeroPixelImage extends DecodableImage {
+ naturalWidth = 0
+ }
+ vi.stubGlobal("Image", ZeroPixelImage)
+ const zeroPixel = sourceCard('<img src="/zero.png">')
+ await expect(prepare(zeroPixel, vi.fn().mockResolvedValue(imageResponse())))
+ .rejects.toMatchObject({ stage: "assets" })
+ zeroPixel.remove()
+
+ class RejectingDecodeImage extends DecodableImage {
+ decode = vi.fn().mockRejectedValue(new Error("decode rejected"))
+ }
+ vi.stubGlobal("Image", RejectingDecodeImage)
+ const rejected = sourceCard('<img src="/rejected.png">')
+ await expect(prepare(rejected, vi.fn().mockResolvedValue(imageResponse())))
+ .rejects.toMatchObject({ stage: "assets" })
+ })
+
+ it("rejects a staticizer result that is not PNG", async () => {
+ const source = sourceCard('<img src="/content.png">')
+
+ await expect(prepareShareImageSession(source, {
+ fetchAsset: vi.fn().mockResolvedValue(imageResponse()),
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ staticizeAsset: vi.fn().mockResolvedValue(new Blob(["jpeg"], { type: "image/jpeg" })),
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })).rejects.toMatchObject({ stage: "assets" })
+ })
+
+ it("replaces a bare failed identity image using its measured geometry", async () => {
+ const source = sourceCard('<img data-avatar-photo-state="error" src="/avatar.png">')
+
+ const prepared = await prepare(source, vi.fn().mockRejectedValue(new Error("offline")))
+
+ expect(prepared.markup).toContain('data-share-identity-fallback="beam"')
+ expect(prepared.markup).toContain("width: 320px")
+ expect(prepared.markup).toContain("height: 180px")
+ expect(prepared.markup).not.toContain("<img")
+ })
+
+ it("marks image frames ready and removes placeholders and direct statuses", async () => {
+ const source = sourceCard(`
+ <span data-remote-image-frame data-remote-image-state="loading">
+ <img src="/content.png" loading="lazy" crossorigin="anonymous" srcset="/large.png 2x">
+ <span data-remote-image-placeholder>loading</span>
+ <span role="status">loading</span>
+ </span>
+ `)
+
+ const prepared = await prepare(source, vi.fn().mockResolvedValue(imageResponse()))
+
+ expect(prepared.markup).toContain('data-remote-image-state="ready"')
+ expect(prepared.markup).not.toContain("data-remote-image-placeholder")
+ expect(prepared.markup).not.toContain('role="status"')
+ expect(prepared.markup).not.toContain("srcset=")
+ expect(prepared.markup).not.toContain("crossorigin=")
+ expect(prepared.markup).not.toContain("loading=")
+ })
+
+ it("loads only the explicit primary face instead of the computed fallback list", async () => {
+ const primaryFace = { family: "caveat", status: "loaded" } as FontFace
+ vi.mocked(document.fonts.load).mockImplementation(async (font) => {
+ if (font.includes("Fallback")) {
+ throw new DOMException("Fallback font has no source", "NetworkError")
+ }
+ return [primaryFace]
+ })
+ const source = sourceCard("<span>font guard</span>")
+ const brand = source.querySelector<HTMLElement>("[data-share-brand]")!
+ brand.dataset.shareBrandFont = "caveat"
+ brand.style.fontFamily = 'caveat, "caveat Fallback"'
+
+ await expect(prepare(source)).resolves.toMatchObject({ fontEmbedCSS: FONT_CSS })
+ expect(getComputedStyle(brand).fontFamily).toBe('caveat, "caveat Fallback"')
+ expect(document.fonts.load).toHaveBeenCalledTimes(1)
+ expect(document.fonts.load).toHaveBeenCalledWith('700 14px "caveat"', "Alook")
+ })
+
+ it.each([
+ ["missing", null],
+ ["empty", " \t "],
+ ])("keeps a %s primary brand marker as a hard preparation failure", async (_label, marker) => {
+ const source = sourceCard("<span>font guard</span>")
+ const brand = source.querySelector<HTMLElement>("[data-share-brand]")!
+ if (marker === null) brand.removeAttribute("data-share-brand-font")
+ else brand.dataset.shareBrandFont = marker
+ const getFontCSS = vi.fn().mockResolvedValue(FONT_CSS)
+
+ await expect(prepareShareImageSession(source, {
+ getFontCSS,
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })).rejects.toMatchObject({ stage: "fonts", timedOut: false })
+ expect(document.fonts.load).not.toHaveBeenCalled()
+ expect(getFontCSS).not.toHaveBeenCalled()
+ })
+
+ it("keeps an empty brand font match as a hard preparation failure", async () => {
+ vi.mocked(document.fonts.load).mockResolvedValue([])
+ const source = sourceCard("<span>font guard</span>")
+ const getFontCSS = vi.fn().mockResolvedValue(FONT_CSS)
+
+ await expect(prepareShareImageSession(source, {
+ getFontCSS,
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })).rejects.toMatchObject({ stage: "fonts", timedOut: false })
+ expect(getFontCSS).not.toHaveBeenCalled()
+ })
+
+ it("keeps a rejected brand font load as a hard preparation failure", async () => {
+ vi.mocked(document.fonts.load).mockRejectedValue(new Error("font load rejected"))
+ const source = sourceCard("<span>font guard</span>")
+ const getFontCSS = vi.fn().mockResolvedValue(FONT_CSS)
+
+ await expect(prepareShareImageSession(source, {
+ getFontCSS,
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })).rejects.toMatchObject({ stage: "fonts", timedOut: false })
+ expect(getFontCSS).not.toHaveBeenCalled()
+ })
+
+ it("keeps a rejected font readiness wait as a hard preparation failure", async () => {
+ const readiness = deferred<FontFaceSet>()
+ Object.defineProperty(document.fonts, "ready", {
+ configurable: true,
+ value: readiness.promise,
+ })
+ const source = sourceCard("<span>font guard</span>")
+ const getFontCSS = vi.fn().mockResolvedValue(FONT_CSS)
+ const pending = prepareShareImageSession(source, {
+ getFontCSS,
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })
+ const assertion = expect(pending).rejects.toMatchObject({ stage: "fonts", timedOut: false })
+ await vi.waitFor(() => expect(document.fonts.load).toHaveBeenCalledTimes(1))
+
+ readiness.reject(new Error("font readiness rejected"))
+
+ await assertion
+ expect(getFontCSS).not.toHaveBeenCalled()
+ })
+
+ it("rejects invalid session byte budgets before asset preparation", async () => {
+ const source = sourceCard("<span>invalid budget</span>")
+
+ await expect(prepareShareImageSession(source, {
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ maxSessionAssetBytes: 0,
+ waitForPaint: vi.fn().mockResolvedValue(undefined),
+ })).rejects.toMatchObject({ stage: "assets" })
+ })
+
+ it("rejects a URL image inserted after the preparation snapshot", async () => {
+ const source = sourceCard("<span>late image</span>")
+ let paints = 0
+ const waitForPaint = vi.fn(async () => {
+ paints += 1
+ if (paints !== 3) return
+ document.querySelector<HTMLElement>("[data-share-detached-tree] [data-share-card-source]")
+ ?.insertAdjacentHTML("beforeend", '<img src="/late.png">')
+ })
+
+ await expect(prepareShareImageSession(source, {
+ getFontCSS: vi.fn().mockResolvedValue(FONT_CSS),
+ waitForPaint,
+ })).rejects.toMatchObject({ stage: "assets" })
+ })
+
+ it("wraps an unexpected post-asset installation error as a freeze failure", async () => {
+ const source = sourceCard('<img src="/content.png">')
+ const removeAttribute = Element.prototype.removeAttribute
+ vi.spyOn(Element.prototype, "removeAttribute").mockImplementation(function (name) {
+ if (this instanceof HTMLImageElement && name === "srcset") {
+ throw new Error("install failed")
+ }
+ return removeAttribute.call(this, name)
+ })
+
+ await expect(prepare(source, vi.fn().mockResolvedValue(imageResponse())))
+ .rejects.toMatchObject({ stage: "freeze", cause: { message: "install failed" } })
+ })
+})
+
+describe("capturePreparedShareImage", () => {
+ it("rasterizes a detached byte-backed clone with the prepared font CSS", async () => {
+ const preview = sourceCard('<img src="data:image/png;base64,AQID">')
+ preview.removeAttribute("data-share-card-source")
+ preview.setAttribute("data-share-card", "")
+ const blob = new Blob(["png"], { type: "image/png" })
+ const rasterize = vi.fn(async (node: HTMLElement) => {
+ expect(node).not.toBe(preview)
+ expect(node.parentElement?.dataset.shareDetachedTree).toBe("true")
+ expect(node.dataset.shareCaptureTree).toBe("true")
+ node.setAttribute("data-mutated-during-capture", "")
+ return blob
+ })
+
+ const result = await capturePreparedShareImage(preview, FONT_CSS, rasterize)
+
+ expect(result).toBe(blob)
+ expect(rasterize).toHaveBeenCalledWith(expect.any(HTMLElement), expect.objectContaining({
+ pixelRatio: 2,
+ fontEmbedCSS: FONT_CSS,
+ cacheBust: false,
+ includeQueryParams: true,
+ }))
+ expect(preview.hasAttribute("data-mutated-during-capture")).toBe(false)
+ expect(document.querySelector("[data-share-detached-tree]")).toBeNull()
+ })
+
+ it("rejects a ready preview that still contains a URL-backed image", async () => {
+ const preview = sourceCard('<img src="https://cdn.example/not-ready.png">')
+ const rasterize = vi.fn()
+
+ await expect(capturePreparedShareImage(preview, FONT_CSS, rasterize)).rejects.toMatchObject({
+ stage: "rasterize",
+ })
+ expect(rasterize).not.toHaveBeenCalled()
+ })
+
+ it("times out a non-cooperative rasterizer and removes its detached tree", async () => {
+ vi.useFakeTimers()
+ const preview = sourceCard("<span>ready</span>")
+ const rasterize = vi.fn(() => new Promise<Blob | null>(() => {}))
+ const pending = capturePreparedShareImage(preview, FONT_CSS, rasterize, { timeoutMs: 25 })
+ const assertion = expect(pending).rejects.toMatchObject({
+ stage: "rasterize",
+ timedOut: true,
+ })
+
+ await act(async () => vi.advanceTimersByTimeAsync(25))
+
+ await assertion
+ expect(document.querySelector("[data-share-detached-tree]")).toBeNull()
+ })
+})
diff --git a/src/web/src/lib/community/share-image-session.ts b/src/web/src/lib/community/share-image-session.ts
new file mode 100644
index 000000000..b537b5f35
--- /dev/null
+++ b/src/web/src/lib/community/share-image-session.ts
@@ -0,0 +1,817 @@
+import type { Options as HtmlToImageOptions } from "html-to-image/lib/types"
+import { getFontEmbedCSS } from "html-to-image"
+import { renderFaceSvg } from "@/lib/avatar/face"
+
+const SHARE_IMAGE_ASSET_TIMEOUT_MS = 5_000
+const SHARE_IMAGE_RENDER_TIMEOUT_MS = 15_000
+const SHARE_IMAGE_MAX_ASSET_BYTES = 10 * 1024 * 1024
+const SHARE_IMAGE_MAX_SESSION_ASSET_BYTES = 10 * 1024 * 1024
+const SHARE_IMAGE_MAX_DECODED_DIMENSION = 8_192
+const SHARE_IMAGE_MAX_DECODED_PIXELS = 16 * 1024 * 1024
+const SHARE_IMAGE_MAX_SESSION_DECODED_PIXELS = 16 * 1024 * 1024
+const SHARE_IMAGE_MAX_STATIC_DIMENSION = 4_096
+const SHARE_IMAGE_MAX_STATIC_PIXELS = 4 * 1024 * 1024
+const SHARE_IMAGE_MAX_STATIC_ASSET_BYTES = 10 * 1024 * 1024
+const SHARE_IMAGE_MAX_SESSION_STATIC_BYTES = 10 * 1024 * 1024
+const SHARE_IMAGE_PIXEL_RATIO = 2
+
+const THEME_PROPERTIES = [
+ "--background",
+ "--foreground",
+ "--card",
+ "--card-foreground",
+ "--primary",
+ "--primary-foreground",
+ "--secondary",
+ "--secondary-foreground",
+ "--muted",
+ "--muted-foreground",
+ "--accent",
+ "--accent-foreground",
+ "--border",
+ "--ring",
+ "--font-sans",
+ "--font-caveat",
+ "--font-brand",
+ "--radius",
+ "--e1",
+ "--e2",
+] as const
+
+const FROZEN_PROPERTIES = [
+ "color",
+ "background-color",
+ "border-top-color",
+ "border-right-color",
+ "border-bottom-color",
+ "border-left-color",
+ "border-top-left-radius",
+ "border-top-right-radius",
+ "border-bottom-right-radius",
+ "border-bottom-left-radius",
+ "box-shadow",
+ "font-family",
+ "font-size",
+ "font-style",
+ "font-weight",
+ "letter-spacing",
+ "line-height",
+ "text-decoration-color",
+ "text-shadow",
+] as const
+
+export type ShareImageSessionStage = "source" | "assets" | "fonts" | "freeze" | "rasterize"
+
+export class ShareImageSessionError extends Error {
+ constructor(
+ readonly stage: ShareImageSessionStage,
+ readonly timedOut = false,
+ cause?: unknown,
+ ) {
+ super(`Share image ${timedOut ? "timed out" : "failed"} during ${stage}`)
+ this.name = "ShareImageSessionError"
+ this.cause = cause
+ }
+}
+
+export type PreparedShareImageSession = Readonly<{
+ markup: string
+ width: number
+ height: number
+ backgroundColor: string
+ fontEmbedCSS: string
+}>
+
+type ShareImageFetch = typeof fetch
+type ShareImageFontEmbedder = typeof getFontEmbedCSS
+type ShareImageRasterizer = (
+ node: HTMLElement,
+ options?: HtmlToImageOptions,
+) => Promise<Blob | null>
+type ShareImageAssetTarget = { width: number; height: number }
+type ShareImageStaticizer = (
+ blob: Blob,
+ target: ShareImageAssetTarget,
+ signal: AbortSignal,
+ budget: ShareImageAssetBudget,
+) => Promise<Blob>
+type ShareImageStaticizeQueue = (run: () => Promise<Blob>) => Promise<Blob>
+
+type PrepareShareImageSessionOptions = {
+ fetchAsset?: ShareImageFetch
+ getFontCSS?: ShareImageFontEmbedder
+ maxSessionAssetBytes?: number
+ timeoutMs?: number
+ signal?: AbortSignal
+ staticizeAsset?: ShareImageStaticizer
+ waitForPaint?: () => Promise<void>
+}
+
+type CaptureShareImageOptions = {
+ timeoutMs?: number
+ signal?: AbortSignal
+}
+
+type ShareImageAssetBudget = {
+ maxBytes: number
+ usedBytes: number
+ decodedPixels: number
+ staticBytes: number
+}
+
+class ShareImageSessionBudgetError extends Error {
+ constructor(readonly limit: string) {
+ super(`Share image assets exceed the ${limit} limit`)
+ this.name = "ShareImageSessionBudgetError"
+ }
+}
+
+function abortError(): DOMException {
+ return new DOMException("Share image aborted", "AbortError")
+}
+
+function throwIfAborted(signal?: AbortSignal): void {
+ if (signal?.aborted) throw abortError()
+}
+
+function nextPaint(): Promise<void> {
+ if (typeof requestAnimationFrame !== "function") return Promise.resolve()
+ return new Promise((resolve) => requestAnimationFrame(() => resolve()))
+}
+
+async function withDeadline<T>(
+ stage: ShareImageSessionStage,
+ timeoutMs: number,
+ signal: AbortSignal | undefined,
+ run: (deadlineSignal: AbortSignal) => Promise<T>,
+): Promise<T> {
+ throwIfAborted(signal)
+ const controller = new AbortController()
+ let timedOut = false
+ let rejectInterrupted: ((reason: unknown) => void) | null = null
+ const abort = () => {
+ controller.abort()
+ rejectInterrupted?.(abortError())
+ }
+ signal?.addEventListener("abort", abort, { once: true })
+ const interrupted = new Promise<never>((_resolve, reject) => {
+ rejectInterrupted = reject
+ })
+ const timer = setTimeout(() => {
+ timedOut = true
+ controller.abort()
+ rejectInterrupted?.(new ShareImageSessionError(stage, true))
+ }, timeoutMs)
+ try {
+ return await Promise.race([run(controller.signal), interrupted])
+ } catch (error) {
+ if (signal?.aborted) throw abortError()
+ if (timedOut) throw new ShareImageSessionError(stage, true, error)
+ if (error instanceof ShareImageSessionError) throw error
+ throw new ShareImageSessionError(stage, false, error)
+ } finally {
+ clearTimeout(timer)
+ signal?.removeEventListener("abort", abort)
+ controller.abort()
+ }
+}
+
+async function waitForSource(
+ node: HTMLElement,
+ signal: AbortSignal,
+ waitForPaint: () => Promise<void>,
+): Promise<void> {
+ while (node.querySelector('[data-slot="skeleton"]')) {
+ await new Promise<void>((resolve, reject) => {
+ const observer = new MutationObserver(() => {
+ if (node.querySelector('[data-slot="skeleton"]')) return
+ observer.disconnect()
+ signal.removeEventListener("abort", abort)
+ resolve()
+ })
+ const abort = () => {
+ observer.disconnect()
+ reject(abortError())
+ }
+ observer.observe(node, { childList: true, subtree: true })
+ signal.addEventListener("abort", abort, { once: true })
+ if (!node.querySelector('[data-slot="skeleton"]')) {
+ observer.disconnect()
+ signal.removeEventListener("abort", abort)
+ resolve()
+ }
+ })
+ }
+ await waitForPaint()
+ throwIfAborted(signal)
+ await waitForPaint()
+}
+
+function imageSource(image: HTMLImageElement): string {
+ return image.currentSrc || image.getAttribute("src") || ""
+}
+
+function imageKind(image: HTMLImageElement): "identity" | "content" {
+ return image.hasAttribute("data-avatar-photo-state")
+ || image.getAttribute("data-remote-image-kind") === "identity"
+ ? "identity"
+ : "content"
+}
+
+function assetRequest(image: HTMLImageElement): { cacheKey: string; url: string; credentials: RequestCredentials } {
+ const source = imageSource(image)
+ if (!source) throw new Error("Image source is missing")
+ if (source.startsWith("data:")) return { cacheKey: source, url: source, credentials: "omit" }
+
+ const sourceUrl = new URL(source, window.location.href)
+ if (sourceUrl.origin === window.location.origin) {
+ return { cacheKey: sourceUrl.href, url: sourceUrl.href, credentials: "same-origin" }
+ }
+ if (imageKind(image) === "content") {
+ return { cacheKey: sourceUrl.href, url: sourceUrl.href, credentials: "omit" }
+ }
+
+ const identityId = image.closest<HTMLElement>("[data-share-identity-id]")
+ ?.dataset.shareIdentityId
+ if (!identityId) throw new Error("External identity has no visible profile id")
+ const url = `/api/community/share-image/avatar/${encodeURIComponent(identityId)}`
+ return { cacheKey: `${url}:${sourceUrl.href}`, url, credentials: "same-origin" }
+}
+
+function consumeAssetBytes(budget: ShareImageAssetBudget, byteLength: number): void {
+ if (byteLength > budget.maxBytes - budget.usedBytes) {
+ throw new ShareImageSessionBudgetError("raw session bytes")
+ }
+ budget.usedBytes += byteLength
+}
+
+function consumeDecodedPixels(budget: ShareImageAssetBudget, width: number, height: number): void {
+ const pixels = width * height
+ if (
+ width > SHARE_IMAGE_MAX_DECODED_DIMENSION
+ || height > SHARE_IMAGE_MAX_DECODED_DIMENSION
+ || pixels > SHARE_IMAGE_MAX_DECODED_PIXELS
+ || pixels > SHARE_IMAGE_MAX_SESSION_DECODED_PIXELS - budget.decodedPixels
+ ) {
+ throw new ShareImageSessionBudgetError("decoded pixel")
+ }
+ budget.decodedPixels += pixels
+}
+
+function consumeStaticBytes(budget: ShareImageAssetBudget, byteLength: number): void {
+ if (
+ byteLength > SHARE_IMAGE_MAX_STATIC_ASSET_BYTES
+ || byteLength > SHARE_IMAGE_MAX_SESSION_STATIC_BYTES - budget.staticBytes
+ ) {
+ throw new ShareImageSessionBudgetError("static PNG byte")
+ }
+ budget.staticBytes += byteLength
+}
+
+function dataUrlByteLength(dataUrl: string): number {
+ const comma = dataUrl.indexOf(",")
+ if (comma < 0) throw new Error("Image data URL is malformed")
+ const metadata = dataUrl.slice(0, comma).toLowerCase()
+ const payload = dataUrl.slice(comma + 1)
+ if (metadata.split(";").includes("base64")) {
+ let encodedLength = 0
+ let last = ""
+ let penultimate = ""
+ for (let index = 0; index < payload.length; index += 1) {
+ const code = payload.charCodeAt(index)
+ if (code === 9 || code === 10 || code === 12 || code === 13 || code === 32) continue
+ encodedLength += 1
+ penultimate = last
+ last = payload[index]!
+ }
+ const padding = last === "=" ? (penultimate === "=" ? 2 : 1) : 0
+ return Math.max(0, Math.floor(encodedLength * 3 / 4) - padding)
+ }
+
+ let byteLength = 0
+ for (let index = 0; index < payload.length; index += 1) {
+ const code = payload.charCodeAt(index)
+ if (code === 37 && /^[\da-f]{2}$/i.test(payload.slice(index + 1, index + 3))) {
+ byteLength += 1
+ index += 2
+ continue
+ }
+ const codePoint = payload.codePointAt(index)!
+ byteLength += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4
+ if (codePoint > 0xffff) index += 1
+ }
+ return byteLength
+}
+
+function assetTarget(image: HTMLImageElement): ShareImageAssetTarget {
+ const rect = image.getBoundingClientRect()
+ return {
+ width: Math.max(0, Math.ceil(rect.width * SHARE_IMAGE_PIXEL_RATIO)),
+ height: Math.max(0, Math.ceil(rect.height * SHARE_IMAGE_PIXEL_RATIO)),
+ }
+}
+
+function mergeAssetTarget(
+ targets: Map<string, ShareImageAssetTarget>,
+ cacheKey: string,
+ target: ShareImageAssetTarget,
+): void {
+ const current = targets.get(cacheKey)
+ targets.set(cacheKey, {
+ width: Math.max(current?.width ?? 0, target.width),
+ height: Math.max(current?.height ?? 0, target.height),
+ })
+}
+
+function staticImageSize(
+ sourceWidth: number,
+ sourceHeight: number,
+ target: ShareImageAssetTarget,
+): ShareImageAssetTarget {
+ const targetWidth = target.width > 0 ? target.width : SHARE_IMAGE_MAX_STATIC_DIMENSION
+ const targetHeight = target.height > 0 ? target.height : SHARE_IMAGE_MAX_STATIC_DIMENSION
+ const scale = Math.min(
+ 1,
+ targetWidth / sourceWidth,
+ targetHeight / sourceHeight,
+ SHARE_IMAGE_MAX_STATIC_DIMENSION / sourceWidth,
+ SHARE_IMAGE_MAX_STATIC_DIMENSION / sourceHeight,
+ Math.sqrt(SHARE_IMAGE_MAX_STATIC_PIXELS / (sourceWidth * sourceHeight)),
+ )
+ return {
+ width: Math.max(1, Math.floor(sourceWidth * scale)),
+ height: Math.max(1, Math.floor(sourceHeight * scale)),
+ }
+}
+
+function canvasToPng(canvas: HTMLCanvasElement, signal: AbortSignal): Promise<Blob> {
+ throwIfAborted(signal)
+ return new Promise((resolve, reject) => {
+ let settled = false
+ const finish = (blob?: Blob | null, error?: unknown) => {
+ if (settled) return
+ settled = true
+ signal.removeEventListener("abort", abort)
+ if (error) reject(error)
+ else if (!blob || blob.size === 0) reject(new Error("Static PNG encoder returned no image"))
+ else resolve(blob)
+ }
+ const abort = () => finish(undefined, abortError())
+ signal.addEventListener("abort", abort, { once: true })
+ canvas.toBlob(
+ (blob) => finish(blob),
+ "image/png",
+ )
+ })
+}
+
+async function staticizeImageBlob(
+ blob: Blob,
+ target: ShareImageAssetTarget,
+ signal: AbortSignal,
+ budget: ShareImageAssetBudget,
+): Promise<Blob> {
+ throwIfAborted(signal)
+ if (typeof createImageBitmap !== "function") {
+ 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)
+ } finally {
+ bitmap.close()
+ if (canvas) {
+ canvas.width = 0
+ canvas.height = 0
+ }
+ }
+}
+
+async function dataUrlBlob(dataUrl: string, signal: AbortSignal): Promise<Blob> {
+ const response = await fetch(dataUrl, { signal })
+ if (!response.ok) throw new Error("Image data URL could not be read")
+ return response.blob()
+}
+
+async function readImageResponse(
+ response: Response,
+ signal: AbortSignal,
+ budget: ShareImageAssetBudget,
+): Promise<Blob> {
+ if (!response.ok) throw new Error(`Image request returned ${response.status}`)
+ const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase()
+ if (!contentType?.startsWith("image/") || contentType === "image/svg+xml") {
+ throw new Error("Image request returned an unsupported content type")
+ }
+ const declaredSize = Number(response.headers.get("content-length") ?? "0")
+ if (Number.isFinite(declaredSize) && declaredSize > SHARE_IMAGE_MAX_ASSET_BYTES) {
+ throw new Error("Image response is too large")
+ }
+ if (!response.body) {
+ const blob = await response.blob()
+ if (blob.size > SHARE_IMAGE_MAX_ASSET_BYTES) throw new Error("Image response is too large")
+ consumeAssetBytes(budget, blob.size)
+ return blob.type ? blob : new Blob([blob], { type: contentType })
+ }
+
+ const reader = response.body.getReader()
+ const abort = () => {
+ void reader.cancel(abortError()).catch(() => undefined)
+ }
+ signal.addEventListener("abort", abort, { once: true })
+ const chunks: Uint8Array[] = []
+ let size = 0
+ try {
+ while (true) {
+ throwIfAborted(signal)
+ const result = await reader.read()
+ throwIfAborted(signal)
+ if (result.done) break
+ size += result.value.byteLength
+ if (size > SHARE_IMAGE_MAX_ASSET_BYTES) {
+ await reader.cancel()
+ throw new Error("Image response is too large")
+ }
+ try {
+ consumeAssetBytes(budget, result.value.byteLength)
+ } catch (error) {
+ void reader.cancel(error).catch(() => undefined)
+ throw error
+ }
+ chunks.push(result.value)
+ }
+ } finally {
+ signal.removeEventListener("abort", abort)
+ reader.releaseLock()
+ }
+ const bytes = new ArrayBuffer(size)
+ const view = new Uint8Array(bytes)
+ let offset = 0
+ for (const chunk of chunks) {
+ view.set(chunk, offset)
+ offset += chunk.byteLength
+ }
+ return new Blob([bytes], { type: contentType })
+}
+
+function blobToDataUrl(blob: Blob, signal: AbortSignal): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader()
+ const abort = () => {
+ reader.abort()
+ reject(abortError())
+ }
+ reader.addEventListener("load", () => {
+ signal.removeEventListener("abort", abort)
+ if (typeof reader.result === "string") resolve(reader.result)
+ else reject(new Error("Image bytes could not be encoded"))
+ }, { once: true })
+ reader.addEventListener("error", () => {
+ signal.removeEventListener("abort", abort)
+ reject(reader.error ?? new Error("Image bytes could not be read"))
+ }, { once: true })
+ signal.addEventListener("abort", abort, { once: true })
+ reader.readAsDataURL(blob)
+ })
+}
+
+function decodeDataUrl(dataUrl: string, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const image = new Image()
+ let settled = false
+ const finish = (error?: unknown) => {
+ if (settled) return
+ settled = true
+ signal.removeEventListener("abort", abort)
+ image.onload = null
+ image.onerror = null
+ if (error) reject(error)
+ else resolve()
+ }
+ const abort = () => finish(abortError())
+ image.onload = () => {
+ if (image.naturalWidth <= 0 || image.naturalHeight <= 0) {
+ finish(new Error("Decoded image has no pixels"))
+ return
+ }
+ Promise.resolve(image.decode?.()).then(
+ () => finish(),
+ (error) => finish(error),
+ )
+ }
+ image.onerror = () => finish(new Error("Image bytes could not be decoded"))
+ signal.addEventListener("abort", abort, { once: true })
+ image.src = dataUrl
+ })
+}
+
+async function resolveImage(
+ image: HTMLImageElement,
+ fetchAsset: ShareImageFetch,
+ signal: AbortSignal,
+ assetCache: Map<string, Promise<string>>,
+ assetTargets: Map<string, ShareImageAssetTarget>,
+ budget: ShareImageAssetBudget,
+ staticizeAsset: ShareImageStaticizer,
+ enqueueStaticize: ShareImageStaticizeQueue,
+): Promise<string | null> {
+ const kind = imageKind(image)
+ try {
+ const request = assetRequest(image)
+ const cached = assetCache.get(request.cacheKey)
+ if (cached) return await cached
+ const pending = (async () => {
+ let blob: Blob
+ if (request.url.startsWith("data:")) {
+ consumeAssetBytes(budget, dataUrlByteLength(request.url))
+ blob = await dataUrlBlob(request.url, signal)
+ } else {
+ const response = await fetchAsset(request.url, {
+ credentials: request.credentials,
+ redirect: "error",
+ signal,
+ })
+ 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
+ })()
+ assetCache.set(request.cacheKey, pending)
+ return await pending
+ } catch (error) {
+ if (signal.aborted) throw abortError()
+ if (error instanceof ShareImageSessionBudgetError) throw error
+ if (kind === "identity") return null
+ throw error
+ }
+}
+
+function replaceIdentityWithFallback(image: HTMLImageElement): void {
+ const identityRoot = image.closest<HTMLElement>("[data-share-identity-id]")
+ const fallbackRoot = image.closest<HTMLElement>("[data-avatar-kind], [role=img]")
+ ?? identityRoot
+ const seed = identityRoot?.dataset.shareIdentityId
+ || fallbackRoot?.getAttribute("aria-label")
+ || imageSource(image)
+ const replacement = image.ownerDocument.createElement("span")
+ replacement.dataset.shareIdentityFallback = "beam"
+ replacement.setAttribute("aria-hidden", "true")
+ replacement.style.cssText = "display:inline-flex;width:100%;height:100%;overflow:hidden;border-radius:inherit"
+ replacement.innerHTML = renderFaceSvg(seed)
+ if (fallbackRoot) {
+ fallbackRoot.replaceChildren(replacement)
+ fallbackRoot.dataset.avatarKind = "beam"
+ return
+ }
+ const rect = image.getBoundingClientRect()
+ replacement.style.width = `${rect.width}px`
+ replacement.style.height = `${rect.height}px`
+ image.replaceWith(replacement)
+}
+
+function installImageBytes(image: HTMLImageElement, dataUrl: string): void {
+ image.src = dataUrl
+ image.removeAttribute("srcset")
+ image.removeAttribute("crossorigin")
+ image.removeAttribute("loading")
+ image.style.opacity = "1"
+ image.dataset.shareByteBacked = "true"
+ image.dataset.remoteImageState = "ready"
+ const frame = image.closest<HTMLElement>(
+ "[data-remote-image-frame], [data-streamdown=image-wrapper], [data-avatar-kind]",
+ )
+ if (!frame) return
+ frame.dataset.remoteImageState = "ready"
+ for (const placeholder of frame.querySelectorAll("[data-remote-image-placeholder]")) {
+ placeholder.remove()
+ }
+ for (const status of frame.querySelectorAll(':scope > [role="status"]')) status.remove()
+}
+
+function freezeTree(root: HTMLElement): { width: number; height: number; backgroundColor: string } {
+ const rect = root.getBoundingClientRect()
+ if (rect.width <= 0 || rect.height <= 0) throw new Error("Share card has no layout")
+ const rootStyle = getComputedStyle(root)
+ for (const property of THEME_PROPERTIES) {
+ const value = rootStyle.getPropertyValue(property).trim()
+ if (value) root.style.setProperty(property, value)
+ }
+ root.style.width = `${rect.width}px`
+ root.style.height = `${rect.height}px`
+ root.style.minWidth = `${rect.width}px`
+ root.style.maxWidth = `${rect.width}px`
+ root.style.boxSizing = "border-box"
+
+ const elements = [root, ...root.querySelectorAll<HTMLElement>("*")]
+ for (const element of elements) {
+ const computed = getComputedStyle(element)
+ for (const property of FROZEN_PROPERTIES) {
+ const value = computed.getPropertyValue(property)
+ if (value) element.style.setProperty(property, value)
+ }
+ element.style.setProperty("animation", "none", "important")
+ element.style.setProperty("transition", "none", "important")
+ element.style.setProperty("caret-color", "transparent")
+ }
+ root.dataset.shareSessionState = "ready"
+ return {
+ width: rect.width,
+ height: rect.height,
+ backgroundColor: rootStyle.getPropertyValue("--card").trim() || rootStyle.backgroundColor,
+ }
+}
+
+function mountDetached(source: HTMLElement): { host: HTMLDivElement; card: HTMLElement } {
+ const sourceRect = source.getBoundingClientRect()
+ const host = document.createElement("div")
+ host.dataset.shareDetachedTree = "true"
+ host.setAttribute("aria-hidden", "true")
+ host.style.cssText = [
+ "position:fixed",
+ "left:-10000px",
+ "top:0",
+ `width:${Math.max(1, sourceRect.width)}px`,
+ "pointer-events:none",
+ "opacity:0",
+ "z-index:-1",
+ ].join(";")
+ const card = source.cloneNode(true) as HTMLElement
+ host.appendChild(card)
+ document.body.appendChild(host)
+ return { host, card }
+}
+
+async function loadAndEmbedFonts(
+ card: HTMLElement,
+ getFontCSS: ShareImageFontEmbedder,
+ signal: AbortSignal,
+): Promise<string> {
+ const brand = card.querySelector<HTMLElement>("[data-share-brand]")
+ const primaryFontFamily = brand?.dataset.shareBrandFont?.trim()
+ if (!brand || !primaryFontFamily) throw new Error("Share-card brand font is missing")
+ const loadedFaces = await document.fonts.load(
+ `700 14px ${JSON.stringify(primaryFontFamily)}`,
+ brand.textContent.trim(),
+ )
+ if (loadedFaces.length === 0) throw new Error("Brand font is unavailable")
+ await document.fonts.ready
+ throwIfAborted(signal)
+ const css = await getFontCSS(card)
+ if (!css.trim()) throw new Error("Share-card fonts could not be embedded")
+ return css
+}
+
+export async function prepareShareImageSession(
+ source: HTMLElement,
+ options: PrepareShareImageSessionOptions = {},
+): Promise<PreparedShareImageSession> {
+ const timeoutMs = options.timeoutMs ?? SHARE_IMAGE_ASSET_TIMEOUT_MS
+ const waitForPaint = options.waitForPaint ?? nextPaint
+ await withDeadline("source", timeoutMs, options.signal, (signal) => (
+ waitForSource(source, signal, waitForPaint)
+ ))
+ throwIfAborted(options.signal)
+
+ const { host, card } = mountDetached(source)
+ try {
+ const maxSessionAssetBytes = options.maxSessionAssetBytes ?? SHARE_IMAGE_MAX_SESSION_ASSET_BYTES
+ if (!Number.isSafeInteger(maxSessionAssetBytes) || maxSessionAssetBytes <= 0) {
+ throw new ShareImageSessionError("assets", false, new Error("Session asset limit is invalid"))
+ }
+ const images = [...card.querySelectorAll<HTMLImageElement>("img")]
+ const assetCache = new Map<string, Promise<string>>()
+ const budget: ShareImageAssetBudget = {
+ maxBytes: maxSessionAssetBytes,
+ usedBytes: 0,
+ decodedPixels: 0,
+ staticBytes: 0,
+ }
+ let staticizeTail = Promise.resolve()
+ const enqueueStaticize: ShareImageStaticizeQueue = (run) => {
+ const result = staticizeTail.then(run, run)
+ staticizeTail = result.then(() => undefined, () => undefined)
+ return result
+ }
+ const resolved = await withDeadline("assets", timeoutMs, options.signal, async (signal) => {
+ await waitForPaint()
+ throwIfAborted(signal)
+ const assetTargets = new Map<string, ShareImageAssetTarget>()
+ for (const image of images) {
+ try {
+ const request = assetRequest(image)
+ mergeAssetTarget(assetTargets, request.cacheKey, assetTarget(image))
+ } catch {
+ // Preserve the existing per-image content failure / identity fallback semantics.
+ }
+ }
+ return Promise.all(images.map((image) => resolveImage(
+ image,
+ options.fetchAsset ?? fetch,
+ signal,
+ assetCache,
+ assetTargets,
+ budget,
+ options.staticizeAsset ?? staticizeImageBlob,
+ enqueueStaticize,
+ )))
+ })
+ for (let index = 0; index < images.length; index += 1) {
+ const image = images[index]!
+ const dataUrl = resolved[index]
+ if (dataUrl) installImageBytes(image, dataUrl)
+ else replaceIdentityWithFallback(image)
+ }
+ if ([...card.querySelectorAll<HTMLImageElement>("img")].some((image) => (
+ !imageSource(image).startsWith("data:")
+ ))) {
+ throw new ShareImageSessionError("assets", false, new Error("Session contains a URL image"))
+ }
+
+ const fontEmbedCSS = await withDeadline("fonts", timeoutMs, options.signal, (signal) => (
+ loadAndEmbedFonts(card, options.getFontCSS ?? getFontEmbedCSS, signal)
+ ))
+ const frozen = await withDeadline("freeze", timeoutMs, options.signal, async (signal) => {
+ await waitForPaint()
+ throwIfAborted(signal)
+ card.removeAttribute("data-share-card-source")
+ card.setAttribute("data-share-card", "")
+ return freezeTree(card)
+ })
+ return Object.freeze({
+ markup: card.outerHTML,
+ ...frozen,
+ fontEmbedCSS,
+ })
+ } catch (error) {
+ if (error instanceof ShareImageSessionError || (error as { name?: unknown })?.name === "AbortError") {
+ throw error
+ }
+ throw new ShareImageSessionError("freeze", false, error)
+ } finally {
+ host.remove()
+ }
+}
+
+export async function capturePreparedShareImage(
+ source: HTMLElement,
+ fontEmbedCSS: string,
+ rasterize: ShareImageRasterizer,
+ options: CaptureShareImageOptions = {},
+): Promise<Blob> {
+ const timeoutMs = options.timeoutMs ?? SHARE_IMAGE_RENDER_TIMEOUT_MS
+ return withDeadline("rasterize", timeoutMs, options.signal, async (signal) => {
+ if ([...source.querySelectorAll<HTMLImageElement>("img")].some((image) => (
+ !imageSource(image).startsWith("data:")
+ ))) {
+ throw new Error("Ready share session contains a URL image")
+ }
+ const { host, card } = mountDetached(source)
+ const removeHost = () => host.remove()
+ signal.addEventListener("abort", removeHost, { once: true })
+ try {
+ card.dataset.shareCaptureTree = "true"
+ for (const element of [card, ...card.querySelectorAll<HTMLElement>("*")]) {
+ element.style.setProperty("animation", "none", "important")
+ element.style.setProperty("transition", "none", "important")
+ }
+ throwIfAborted(signal)
+ const blob = await rasterize(card, {
+ pixelRatio: SHARE_IMAGE_PIXEL_RATIO,
+ backgroundColor: getComputedStyle(card).getPropertyValue("--card").trim() || undefined,
+ fontEmbedCSS,
+ includeQueryParams: true,
+ cacheBust: false,
+ })
+ throwIfAborted(signal)
+ if (!blob) throw new Error("Rasterizer returned no image")
+ return blob
+ } finally {
+ signal.removeEventListener("abort", removeHost)
+ removeHost()
+ }
+ })
+}
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 a07483beb..067d3ceca 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,62 +1,120 @@
-import { test, expect } from "./_fixtures/community-fixture"
-import type { Locator, Page, Route } from "@playwright/test"
+import { expect, test } from "./_fixtures/community-fixture"
+import type { Locator, Page } 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"
+type SamplePoint = { x: number; y: number }
type MobileShareTestState = {
calls: Array<{ command: string; attemptId: string; filename?: string }>
finish: (index: number, destination: "clipboard" | "pictures") => void
}
-async function uploadPhoto(page: Page): Promise<void> {
- const status = await page.evaluate(async () => {
+const TWO_FRAME_GIF_BASE64 = "R0lGODlhCAAIAIEAAP8AAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQIFAAAACwAAAAACAAIAAAIDwABCBxIsKDBgwgTKkwYEAAh+QQIFAAAACwAAAAACAAIAIEAAP8AAAAAAAAAAAAIDwABCBxIsKDBgwgTKkwYEAA7"
+
+async function solidPng(page: Page, color: string, width: number, height: number) {
+ return page.evaluate(async ({ fill, targetWidth, targetHeight }) => {
const canvas = document.createElement("canvas")
- canvas.width = 48
- canvas.height = 48
+ canvas.width = targetWidth
+ canvas.height = targetHeight
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")),
+ context.fillStyle = fill
+ context.fillRect(0, 0, targetWidth, targetHeight)
+ const blob = await new Promise<Blob>((resolve, reject) => canvas.toBlob(
+ (value) => value ? resolve(value) : 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", {
+ return [...new Uint8Array(await blob.arrayBuffer())]
+ }, { fill: color, targetWidth: width, targetHeight: height })
+}
+
+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) => {
+ const form = new FormData()
+ form.append("file", new Blob([new Uint8Array(png)], { type: "image/png" }), "avatar.png")
+ return (await fetch("/api/community/users/me/avatar", {
method: "POST",
- body: avatarForm,
+ body: form,
credentials: "include",
- })
- return avatarResponse.status
- })
+ })).status
+ }, bytes)
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`, {
+async function seedMessage(
+ page: Page,
+ channelId: string,
+ content: string,
+ attachmentIds: string[] = [],
+) {
+ const result = await page.evaluate(async ({ targetId, body, attachments }) => {
+ const response = await fetch(`/api/community/channels/${targetId}/messages`, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
content: body,
- attachments: [],
+ 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 })
+ const payload = await response.json() as { message: { id: string; createdAt: string } }
+ return { status: response.status, ...payload.message }
+ }, { targetId: channelId, body: content, attachments: attachmentIds })
+ expect(result.status).toBe(201)
+ return result
+}
- expect(seeded).toMatchObject({ messageStatus: 201 })
- return seeded.messageId
+async function uploadAttachment(page: Page, channelId: string) {
+ const bytes = await solidPng(page, "rgb(20, 105, 220)", 96, 64)
+ const result = await page.evaluate(async ({ targetId, png }) => {
+ const form = new FormData()
+ form.append("file", new Blob([new Uint8Array(png)], { type: "image/png" }), "blue.png")
+ const response = await fetch(`/api/community/channels/${targetId}/attachments`, {
+ method: "POST",
+ body: form,
+ credentials: "include",
+ })
+ const payload = await response.json() as { id: string }
+ return { status: response.status, id: payload.id }
+ }, { targetId: channelId, png: bytes })
+ expect(result.status).toBe(200)
+ return result.id
+}
+
+async function uploadAnimatedAttachment(page: Page, channelId: string) {
+ const result = await page.evaluate(async ({ targetId, base64 }) => {
+ const binary = atob(base64)
+ const bytes = new Uint8Array(binary.length)
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)
+ const form = new FormData()
+ form.append("file", new Blob([bytes], { type: "image/gif" }), "red-blue.gif")
+ const response = await fetch(`/api/community/channels/${targetId}/attachments`, {
+ method: "POST",
+ body: form,
+ credentials: "include",
+ })
+ const payload = await response.json() as { id: string }
+ return { status: response.status, id: payload.id }
+ }, { targetId: channelId, base64: TWO_FRAME_GIF_BASE64 })
+ expect(result.status).toBe(200)
+ return result.id
+}
+
+async function uploadServerIcon(page: Page, serverId: string): Promise<void> {
+ const bytes = await solidPng(page, "rgb(25, 180, 80)", 64, 64)
+ const status = await page.evaluate(async ({ targetId, png }) => {
+ const form = new FormData()
+ form.append("file", new Blob([new Uint8Array(png)], { type: "image/png" }), "icon.png")
+ return (await fetch(`/api/community/servers/${targetId}/icon`, {
+ method: "POST",
+ body: form,
+ credentials: "include",
+ })).status
+ }, { targetId: serverId, png: bytes })
+ expect(status).toBe(200)
}
async function openShareDialog(page: Page, messageId: string): Promise<Locator> {
@@ -70,20 +128,19 @@ async function openShareDialog(page: Page, messageId: string): Promise<Locator>
return dialog
}
+async function waitForReady(dialog: Locator): Promise<Locator> {
+ const card = dialog.locator("[data-share-card]")
+ await expect(card).toBeVisible({ timeout: 15_000 })
+ await expect(dialog.getByRole("button", { name: "Copy image" })).toBeEnabled()
+ return card
+}
+
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: [],
+ __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") {
@@ -107,107 +164,22 @@ async function installShareCapture(page: Page, rejectFirstClipboard = false): Pr
}, rejectFirstClipboard)
}
-async function shareCaptureCounts(page: Page) {
+async function captureCounts(page: Page) {
return page.evaluate(() => {
const captures = (window as typeof window & {
- __shareCaptures?: {
- clipboard: Blob[]
- clipboardAttempts: number
- download: Blob[]
- }
+ __shareCaptures?: { clipboard: Blob[]; 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!
- },
- }
+async function clipboardAttempts(page: Page) {
+ return page.evaluate(() => (window as typeof window & {
+ __shareCaptures?: { clipboardAttempts: number }
+ }).__shareCaptures?.clipboardAttempts ?? 0)
}
async function installMobileShareNativeStub(page: Page): Promise<void> {
@@ -272,85 +244,146 @@ async function finishMobileShareCall(
}, { callIndex: index, resultDestination: destination })
}
+async function captureDigest(page: Page, kind: CaptureKind, index: number) {
+ return page.evaluate(async ({ captureKind, captureIndex }) => {
+ const blob = (window as typeof window & {
+ __shareCaptures?: { clipboard: Blob[]; download: Blob[] }
+ }).__shareCaptures?.[captureKind][captureIndex]
+ if (!blob) throw new Error(`Missing ${captureKind} capture ${captureIndex}`)
+ const digest = await crypto.subtle.digest("SHA-256", await blob.arrayBuffer())
+ return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("")
+ }, { captureKind: kind, captureIndex: index })
+}
+
+async function capturePixel(
+ page: Page,
+ kind: CaptureKind,
+ index: number,
+ point: SamplePoint,
+) {
+ return page.evaluate(async ({ captureKind, captureIndex, sample }) => {
+ const blob = (window as typeof window & {
+ __shareCaptures?: { clipboard: Blob[]; download: Blob[] }
+ }).__shareCaptures?.[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 result = { pixel, width: bitmap.width, height: bitmap.height }
+ bitmap.close()
+ return result
+ }, { captureKind: kind, captureIndex: index, sample: point })
+}
+
+async function comparePreviewToCapture(
+ page: Page,
+ card: Locator,
+ captureIndex: number,
+) {
+ const screenshot = await card.screenshot({ animations: "disabled" })
+ return page.evaluate(async ({ previewBase64, index }) => {
+ const captured = (window as typeof window & {
+ __shareCaptures?: { clipboard: Blob[] }
+ }).__shareCaptures?.clipboard[index]
+ if (!captured) throw new Error(`Missing clipboard capture ${index}`)
+ const binary = atob(previewBase64)
+ const previewBytes = new Uint8Array(binary.length)
+ for (let i = 0; i < binary.length; i += 1) previewBytes[i] = binary.charCodeAt(i)
+ const [preview, exported] = await Promise.all([
+ createImageBitmap(new Blob([previewBytes], { type: "image/png" })),
+ createImageBitmap(captured),
+ ])
+ const previewCanvas = document.createElement("canvas")
+ previewCanvas.width = exported.width
+ previewCanvas.height = exported.height
+ const previewContext = previewCanvas.getContext("2d")!
+ previewContext.drawImage(preview, 0, 0, exported.width, exported.height)
+ const exportCanvas = document.createElement("canvas")
+ exportCanvas.width = exported.width
+ exportCanvas.height = exported.height
+ const exportContext = exportCanvas.getContext("2d")!
+ exportContext.drawImage(exported, 0, 0)
+ const previewPixels = previewContext.getImageData(0, 0, exported.width, exported.height).data
+ const exportPixels = exportContext.getImageData(0, 0, exported.width, exported.height).data
+ let difference = 0
+ let samples = 0
+ for (let y = 0; y < exported.height; y += 4) {
+ for (let x = 0; x < exported.width; x += 4) {
+ const offset = (y * exported.width + x) * 4
+ difference += Math.abs(previewPixels[offset]! - exportPixels[offset]!)
+ difference += Math.abs(previewPixels[offset + 1]! - exportPixels[offset + 1]!)
+ difference += Math.abs(previewPixels[offset + 2]! - exportPixels[offset + 2]!)
+ samples += 3
+ }
+ }
+ const result = {
+ previewWidth: preview.width,
+ previewHeight: preview.height,
+ exportWidth: exported.width,
+ exportHeight: exported.height,
+ meanChannelDifference: difference / samples,
+ }
+ preview.close()
+ exported.close()
+ return result
+ }, { previewBase64: screenshot.toString("base64"), index: captureIndex })
+}
+
+function sampleCenter(card: Locator, selector: string): Promise<SamplePoint> {
+ return card.evaluate((cardNode, selector) => {
+ const targetNode = cardNode.querySelector(selector)
+ if (!targetNode) throw new Error(`Missing ${selector}`)
+ const cardRect = cardNode.getBoundingClientRect()
+ const targetRect = targetNode.getBoundingClientRect()
+ return {
+ x: (targetRect.left - cardRect.left + targetRect.width / 2) * 2,
+ y: (targetRect.top - cardRect.top + targetRect.height / 2) * 2,
+ }
+ }, selector)
+}
+
test("share image timestamp matches the live row and survives both exports", async ({ asUser }) => {
test.setTimeout(120_000)
const serverId = await seedServer("alice", `Share timestamp ${Date.now()}`)
const channelId = await seedChannel("alice", serverId, "share-timestamp")
const { page } = await asUser("alice")
await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
-
- const seeded = await page.evaluate(async (targetId) => {
- const response = await fetch(`/api/community/channels/${targetId}/messages`, {
- method: "POST",
- credentials: "include",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- content: "Share timestamp parity",
- attachments: [],
- nonce: `e2e:${crypto.randomUUID()}`,
- }),
- })
- const payload = await response.json() as {
- message: { id: string; createdAt: string }
- }
- return {
- status: response.status,
- messageId: payload.message.id,
- createdAt: payload.message.createdAt,
- }
- }, channelId)
- expect(seeded.status).toBe(201)
-
+ const seeded = await seedMessage(page, channelId, "Share timestamp parity")
const expectedTimestamp = await page.evaluate((createdAt) => (
new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" })
.format(new Date(createdAt))
), seeded.createdAt)
- const row = page.getByTestId(tid.message(seeded.messageId))
- await expect(row).toContainText(expectedTimestamp)
-
+ await expect(page.getByTestId(tid.message(seeded.id))).toContainText(expectedTimestamp)
await installShareCapture(page)
- const dialog = await openShareDialog(page, seeded.messageId)
- const card = dialog.locator("[data-share-card]")
- await expect(card.locator("[data-share-timestamp]")).toHaveText(expectedTimestamp)
+ const dialog = await openShareDialog(page, seeded.id)
+ const card = await waitForReady(dialog)
+ await expect(card.locator("[data-share-timestamp]")).toHaveText(expectedTimestamp)
+ await dialog.getByRole("button", { name: "Copy image" }).click()
+ await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible()
const downloadStarted = page.waitForEvent("download")
await dialog.getByRole("button", { name: "Download" }).click()
await downloadStarted
- await expect(dialog.getByRole("button", { name: "Copy image" })).toBeEnabled()
- 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: 1,
- })
+
+ await expect.poll(() => captureCounts(page)).toEqual({ clipboard: 1, download: 1 })
await expect(card.locator("[data-share-timestamp]")).toHaveText(expectedTimestamp)
})
-test("mobile routing waits for native copy and save receipts", async ({ asUser }) => {
+test("mobile routing waits for native copy and save terminal receipts", async ({ asUser }) => {
test.setTimeout(120_000)
const serverId = await seedServer("alice", `Mobile share receipt ${Date.now()}`)
const channelId = await seedChannel("alice", serverId, "mobile-share-receipt")
const { page } = await asUser("alice")
await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
- const seeded = await page.evaluate(async (targetId) => {
- const response = await fetch(`/api/community/channels/${targetId}/messages`, {
- method: "POST",
- credentials: "include",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- content: "Native receipt controls success",
- attachments: [],
- nonce: `e2e:${crypto.randomUUID()}`,
- }),
- })
- const payload = await response.json() as { message: { id: string } }
- return { status: response.status, messageId: payload.message.id }
- }, channelId)
- expect(seeded.status).toBe(201)
+ const seeded = await seedMessage(page, channelId, "Native receipt controls success")
await installMobileShareNativeStub(page)
- const dialog = await openShareDialog(page, seeded.messageId)
+ const dialog = await openShareDialog(page, seeded.id)
+ await waitForReady(dialog)
const copy = dialog.getByRole("button", { name: "Copy image" })
const save = dialog.getByRole("button", { name: "Save image" })
await expect(dialog.getByRole("button", { name: "Download" })).toHaveCount(0)
@@ -362,14 +395,12 @@ test("mobile routing waits for native copy and save receipts", async ({ asUser }
await expect(page.getByText("Image copied to clipboard", { exact: true })).toHaveCount(0)
await finishMobileShareCall(page, 0, "clipboard")
await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible()
- await expect(copy).toBeVisible({ timeout: 5_000 })
await save.click()
await expect.poll(() => mobileShareCalls(page)).toHaveLength(2)
await expect(page.getByText("Saved to Pictures/Alook", { exact: true })).toHaveCount(0)
await finishMobileShareCall(page, 1, "pictures")
await expect(page.getByText("Saved to Pictures/Alook", { exact: true })).toBeVisible()
-
expect(await mobileShareCalls(page)).toEqual([
expect.objectContaining({ command: "mobile_share_image_copy" }),
expect.objectContaining({
@@ -379,484 +410,343 @@ test("mobile routing waits for native copy and save receipts", async ({ asUser }
])
})
-test("consecutive share-image exports reuse rendered avatar, attachment, and invite icon pixels", async ({ asUser }) => {
+test("a real two-frame GIF is frozen to frame zero before ready and reused by both exports", async ({ asUser }) => {
test.setTimeout(120_000)
- const serverId = await seedServer("alice", `Share assets ${Date.now()}`)
- const channelId = await seedChannel("alice", serverId, "share-assets")
- const inviteToken = await createInvite("alice", serverId)
+ const serverId = await seedServer("alice", `Animated share ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "animated-share")
const { page } = await asUser("alice")
- const route = `/c/channels/${serverId}/${channelId}`
- await gotoAfterUserWsAuth(page, route)
-
- const seeded = await page.evaluate(async ({ targetId, targetServerId, token }) => {
- async function solidPng(color: string, width: number, height: number): Promise<Blob> {
- const canvas = document.createElement("canvas")
- canvas.width = width
- canvas.height = height
- const context = canvas.getContext("2d")!
- context.fillStyle = color
- context.fillRect(0, 0, width, height)
- return new Promise((resolve, reject) => canvas.toBlob(
- (blob) => blob ? resolve(blob) : reject(new Error("PNG encode failed")),
- "image/png",
- ))
- }
-
- const avatarForm = new FormData()
- avatarForm.append("file", await solidPng("rgb(220, 35, 60)", 48, 48), "avatar.png")
- const avatarResponse = await fetch("/api/community/users/me/avatar", {
- method: "POST",
- body: avatarForm,
- credentials: "include",
- })
-
- const iconForm = new FormData()
- iconForm.append("file", await solidPng("rgb(25, 180, 80)", 64, 64), "server-icon.png")
- const iconResponse = await fetch(`/api/community/servers/${targetServerId}/icon`, {
- method: "POST",
- body: iconForm,
- credentials: "include",
- })
+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
+ const attachmentId = await uploadAnimatedAttachment(page, channelId)
+ const seeded = await seedMessage(page, channelId, "Frame zero stays immutable", [attachmentId])
+ await installShareCapture(page)
- const attachmentForm = new FormData()
- attachmentForm.append(
- "file",
- await solidPng("rgb(20, 105, 220)", 96, 64),
- "blue-message.png",
- )
- const attachmentResponse = await fetch(`/api/community/channels/${targetId}/attachments`, {
- method: "POST",
- body: attachmentForm,
- credentials: "include",
- })
- const attachment = await attachmentResponse.json() as { id: string }
+ const dialog = await openShareDialog(page, seeded.id)
+ const card = await waitForReady(dialog)
+ const image = card.getByTestId(tid.messageShareImage(seeded.id, 0))
+ await expect(image).toHaveAttribute("src", /^data:image\/png;base64,/)
+ const before = await image.screenshot({ animations: "allow" })
+ await page.waitForTimeout(500)
+ const after = await image.screenshot({ animations: "allow" })
+ expect(after.equals(before)).toBe(true)
+ const point = await sampleCenter(card, `[data-testid="${tid.messageShareImage(seeded.id, 0)}"]`)
- const messageResponse = await fetch(`/api/community/channels/${targetId}/messages`, {
- method: "POST",
- credentials: "include",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- content: `All rendered images must survive export\n/c/invite/${token}`,
- attachments: [attachment.id],
- nonce: `e2e:${crypto.randomUUID()}`,
- }),
- })
- const message = await messageResponse.json() as { message: { id: string } }
- return {
- avatarStatus: avatarResponse.status,
- iconStatus: iconResponse.status,
- attachmentStatus: attachmentResponse.status,
- messageStatus: messageResponse.status,
- messageId: message.message.id,
- }
- }, { targetId: channelId, targetServerId: serverId, token: inviteToken })
+ await dialog.getByRole("button", { name: "Copy image" }).click()
+ await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible()
+ const downloadStarted = page.waitForEvent("download")
+ await dialog.getByRole("button", { name: "Download" }).click()
+ await downloadStarted
+ await expect.poll(() => captureCounts(page)).toEqual({ clipboard: 1, download: 1 })
+
+ 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)
+ expect(downloaded.pixel).toEqual(copied.pixel)
+})
- expect(seeded).toMatchObject({
- avatarStatus: 200,
- iconStatus: 200,
- attachmentStatus: 200,
- messageStatus: 201,
- })
- let releaseServerIcon!: () => void
- const serverIconGate = new Promise<void>((resolve) => { releaseServerIcon = resolve })
- const serverIconPattern = `**/api/community/servers/${serverId}/icon*`
- await page.route(serverIconPattern, async (route) => {
- if (route.request().method() === "GET") await serverIconGate
- await route.continue()
- })
+test("ready preview resolves all assets once and Copy then Download reuse identical PNG bytes", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `Share byte session ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "share-byte-session")
+ const inviteToken = await createInvite("alice", serverId)
+ const { page } = await asUser("alice")
+ const route = `/c/channels/${serverId}/${channelId}`
await gotoAfterUserWsAuth(page, route)
- const railServerImage = page.getByTestId(tid.serverIcon(serverId)).locator('[data-remote-image-kind="identity"]')
- await expect(railServerImage).toHaveAttribute("data-remote-image-state", "pending")
- const pendingServerFrame = await railServerImage.locator("xpath=..").boundingBox()
- expect(pendingServerFrame).not.toBeNull()
- releaseServerIcon()
- await expect(railServerImage).toHaveAttribute("data-remote-image-state", "ready")
- expect(await railServerImage.locator("xpath=..").boundingBox()).toEqual(pendingServerFrame)
- await page.unroute(serverIconPattern)
- const row = page.getByTestId(tid.message(seeded.messageId))
- await expect(row).toBeVisible()
- await row.hover()
- await page.getByTestId(tid.messageShare(seeded.messageId)).click()
- await page.getByRole("button", { name: "Share 1 selected messages as image" }).click()
-
- const dialog = page.getByRole("dialog", { name: "Share message" })
- const card = dialog.locator("[data-share-card]")
- const avatar = card.locator('[data-slot="avatar-image"]')
- const attachmentId = tid.messageShareImage(seeded.messageId, 0)
- const attachment = card.getByTestId(attachmentId)
- const inviteIcon = card.getByTestId(tid.inviteCard(inviteToken)).locator("img")
- await expect(avatar).toBeVisible()
- await expect(attachment).toBeVisible()
- await expect(inviteIcon).toBeVisible()
- await expect.poll(() => avatar.evaluate((image: HTMLImageElement) => (
- image.complete && image.naturalWidth > 0
- ))).toBe(true)
- await expect.poll(() => attachment.evaluate((image: HTMLImageElement) => (
- image.complete && image.naturalWidth > 0
- ))).toBe(true)
- await expect.poll(() => inviteIcon.evaluate((image: HTMLImageElement) => (
- image.complete && image.naturalWidth > 0
- ))).toBe(true)
-
- const points = await card.evaluate((cardNode, { imageTestId, inviteTestId }) => {
- const cardRect = cardNode.getBoundingClientRect()
- const sample = (image: Element): SamplePoint => {
- const rect = image.getBoundingClientRect()
- return {
- x: (rect.left - cardRect.left + rect.width / 2) * 2,
- y: (rect.top - cardRect.top + rect.height / 2) * 2,
- }
- }
- return {
- avatar: sample(cardNode.querySelector('[data-slot="avatar-image"]')!),
- attachment: sample(cardNode.querySelector(`[data-testid="${imageTestId}"]`)!),
- inviteIcon: sample(cardNode.querySelector(`[data-testid="${inviteTestId}"] img`)!),
- }
- }, { imageTestId: attachmentId, inviteTestId: tid.inviteCard(inviteToken) })
-
- await page.evaluate(() => {
- const nativeCreateObjectUrl = URL.createObjectURL.bind(URL)
- ;(window as typeof window & { __shareImageBlobs?: Blob[] }).__shareImageBlobs = []
- URL.createObjectURL = ((value: Blob | MediaSource) => {
- if (value instanceof Blob && value.type === "image/png") {
- ;(window as typeof window & { __shareImageBlobs?: Blob[] }).__shareImageBlobs!.push(value)
- }
- return nativeCreateObjectUrl(value)
- }) as typeof URL.createObjectURL
- Object.defineProperty(navigator, "clipboard", {
- configurable: true,
- value: {
- write: async (items: ClipboardItem[]) => {
- const blob = await items[0]!.getType("image/png")
- ;(window as typeof window & { __shareImageBlobs?: Blob[] }).__shareImageBlobs!.push(blob)
- },
- },
- })
- })
+ await uploadAvatar(page)
+ await uploadServerIcon(page, serverId)
+ const attachmentId = await uploadAttachment(page, channelId)
+ const seeded = await seedMessage(
+ page,
+ channelId,
+ `Byte-backed avatar, attachment, invite, and inline logo\n/c/invite/${inviteToken}`,
+ [attachmentId],
+ )
+ await installShareCapture(page)
- const dynamicImagePaths = [
- "/avatar",
- "/attachments/",
- "/icon",
- ]
- const imageRequestsDuringCapture: string[] = []
- let captureStarted = false
+ const dialog = await openShareDialog(page, seeded.id)
+ const card = await waitForReady(dialog)
+ const images = await card.locator("img").evaluateAll((nodes: HTMLImageElement[]) => (
+ nodes.map((node) => node.currentSrc || node.src)
+ ))
+ expect(images.length).toBeGreaterThanOrEqual(3)
+ 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)
+
+ const avatarPoint = await sampleCenter(card, "[data-share-identity-id]")
+ const attachmentPoint = await sampleCenter(
+ card,
+ `[data-testid="${tid.messageShareImage(seeded.id, 0)}"]`,
+ )
+ const invitePoint = await sampleCenter(
+ card,
+ `[data-testid="${tid.inviteCard(inviteToken)}"] img`,
+ )
+ const networkAfterReady: string[] = []
page.on("request", (request) => {
- if (!captureStarted || request.method() !== "GET") return
const pathname = new URL(request.url()).pathname
- if (dynamicImagePaths.some((suffix) => pathname.includes(suffix))) {
- imageRequestsDuringCapture.push(pathname)
- }
+ if (
+ request.resourceType() === "font"
+ || /avatar|attachments|\/icon|share-image/.test(pathname)
+ ) networkAfterReady.push(pathname)
})
- captureStarted = true
+ await dialog.getByRole("button", { name: "Copy image" }).click()
+ await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible()
const downloadStarted = page.waitForEvent("download")
await dialog.getByRole("button", { name: "Download" }).click()
const download = await downloadStarted
- expect(download.suggestedFilename()).toMatch(/^alook-message-.*\.png$/)
- await dialog.getByRole("button", { name: "Copy image" }).click()
- await expect(dialog.getByRole("button", { name: "Copied" })).toBeVisible()
-
- const exports = await page.evaluate(async ({ avatarPoint, attachmentPoint, inviteIconPoint }) => {
- const blobs = (window as typeof window & { __shareImageBlobs?: Blob[] }).__shareImageBlobs
- if (!blobs || blobs.length !== 2) throw new Error("Share image blobs were not captured")
- return Promise.all(blobs.map(async (blob) => {
- 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 read = ({ x, y }: SamplePoint) => [
- ...context.getImageData(Math.round(x), Math.round(y), 1, 1).data,
- ]
- return {
- avatar: read(avatarPoint),
- attachment: read(attachmentPoint),
- inviteIcon: read(inviteIconPoint),
- width: bitmap.width,
- height: bitmap.height,
- }
- }))
- }, {
- avatarPoint: points.avatar,
- attachmentPoint: points.attachment,
- inviteIconPoint: points.inviteIcon,
- })
-
- expect(imageRequestsDuringCapture).toEqual([])
- expect(exports).toHaveLength(2)
- for (const pixels of exports) {
- expect(pixels.width).toBeGreaterThan(0)
- expect(pixels.height).toBeGreaterThan(0)
- expect(pixels.avatar[0]).toBeGreaterThan(180)
- expect(pixels.avatar[1]).toBeLessThan(80)
- expect(pixels.avatar[2]).toBeLessThan(100)
- expect(pixels.attachment[0]).toBeLessThan(80)
- expect(pixels.attachment[1]).toBeGreaterThan(70)
- expect(pixels.attachment[2]).toBeGreaterThan(180)
- expect(pixels.inviteIcon[0]).toBeLessThan(80)
- expect(pixels.inviteIcon[1]).toBeGreaterThan(140)
- expect(pixels.inviteIcon[2]).toBeLessThan(120)
- }
+ expect(download.suggestedFilename()).toMatch(/^alook-message-.+\.png$/)
+ await expect.poll(() => captureCounts(page)).toEqual({ clipboard: 1, download: 1 })
+
+ expect(networkAfterReady).toEqual([])
+ 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)
+ expect(avatar.pixel[0]).toBeGreaterThan(180)
+ expect(avatar.pixel[1]).toBeLessThan(80)
+ expect(attachment.pixel[2]).toBeGreaterThan(180)
+ expect(invite.pixel[1]).toBeGreaterThan(140)
+ 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)
})
-test("a warm share avatar is a distinct node with the same cached versioned source", async ({ asUser }) => {
+test("cold preparation disables export until the held avatar bytes are ready", 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 serverId = await seedServer("alice", `Cold share ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "cold-share")
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 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)
- 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,
+ let release!: () => void
+ const gate = new Promise<void>((resolve) => { release = resolve })
+ let heldRequests = 0
+ await page.route("**/api/community/users/*/avatar*", async (avatarRoute) => {
+ if (avatarRoute.request().method() === "GET") {
+ heldRequests += 1
+ await gate
}
+ await avatarRoute.continue()
})
- 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
+ const dialog = await openShareDialog(page, seeded.id)
+ await expect.poll(() => heldRequests).toBeGreaterThan(0)
+ await expect(dialog.locator('[data-share-session-state="preparing"]')).toBeVisible()
+ await expect(dialog.locator("[data-share-card]")).toHaveCount(0)
+ await expect(dialog.getByRole("button", { name: "Copy image" })).toBeDisabled()
+ await expect(dialog.getByRole("button", { name: "Download" })).toBeDisabled()
+
+ release()
+ const card = await waitForReady(dialog)
+ await expect(card.locator('img[data-share-byte-backed="true"]')).toHaveAttribute("src", /^data:image\//)
+ const requestsAtReady = heldRequests
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)
+ expect(heldRequests).toBe(requestsAtReady)
+ expect(await captureCounts(page)).toEqual({ clipboard: 1, download: 0 })
})
-test("an immediate cold Copy waits for the real photo and owns the whole generation", async ({ asUser }) => {
+test("closing cold preparation suppresses output and reopening starts a fresh session", 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 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, "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 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)
- 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()
+ let release!: () => void
+ const gate = new Promise<void>((resolve) => { release = resolve })
+ let heldRequests = 0
+ const avatarPattern = "**/api/community/users/*/avatar*"
+ await page.route(avatarPattern, async (avatarRoute) => {
+ if (avatarRoute.request().method() === "GET") {
+ heldRequests += 1
+ await gate
+ }
+ await avatarRoute.continue().catch(() => {})
+ })
+
+ let dialog = await openShareDialog(page, seeded.id)
+ await expect.poll(() => heldRequests).toBeGreaterThan(0)
+ await expect(dialog.locator('[data-share-session-state="preparing"]')).toBeVisible()
+ await page.keyboard.press("Escape")
+ await expect(dialog).not.toBeVisible()
+ release()
+ await page.unroute(avatarPattern)
+ await expect.poll(() => captureCounts(page)).toEqual({ clipboard: 0, download: 0 })
+ await expect(page.getByText("Image copied to clipboard", { exact: true })).toHaveCount(0)
+ dialog = await openShareDialog(page, seeded.id)
+ await waitForReady(dialog)
+ 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: 0,
- })
- expect(avatarRequests.getCount()).toBe(baselineRequests + 1)
- expect(isRedPhoto((await capturedPixel(page, "clipboard", 0, point)).pixel)).toBe(true)
+ await expect.poll(() => captureCounts(page)).toEqual({ clipboard: 1, download: 0 })
})
-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("avatar failure is deterministic while content-image failure is atomic and retryable", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `Share failures ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "share-failures")
+ const { page } = await asUser("alice")
+ const route = `/c/channels/${serverId}/${channelId}`
+ await gotoAfterUserWsAuth(page, route)
+ await uploadAvatar(page)
+ const avatarMessage = await seedMessage(page, channelId, "Avatar failure uses a seeded fallback")
+ const attachmentId = await uploadAttachment(page, channelId)
+ const contentMessage = await seedMessage(page, channelId, "Content failure aborts", [attachmentId])
+ await expect(page.getByTestId(tid.message(avatarMessage.id)).locator('[data-slot="avatar-image"]')).toBeVisible()
+
+ await page.route("**/api/community/users/*/avatar*", async (avatarRoute) => {
+ if (avatarRoute.request().method() === "GET") await avatarRoute.abort("failed")
+ else await avatarRoute.continue()
})
-}
+ let dialog = await openShareDialog(page, avatarMessage.id)
+ let card = await waitForReady(dialog)
+ const fallback = card.locator("[data-share-identity-fallback=beam]")
+ await expect(fallback).toBeVisible()
+ const firstFallback = await fallback.innerHTML()
+ await page.keyboard.press("Escape")
+ dialog = await openShareDialog(page, avatarMessage.id)
+ card = await waitForReady(dialog)
+ expect(await card.locator("[data-share-identity-fallback=beam]").innerHTML()).toBe(firstFallback)
+ await page.keyboard.press("Escape")
+ await page.unroute("**/api/community/users/*/avatar*")
+
+ const rowImage = page.getByTestId(tid.messageImage(contentMessage.id, 0))
+ await expect(rowImage).toBeVisible()
+ const attachmentUrl = await rowImage.getAttribute("src")
+ expect(attachmentUrl).toBeTruthy()
+ const attachmentPath = new URL(attachmentUrl!, page.url()).pathname
+ const attachmentPattern = `**${attachmentPath}*`
+ await page.route(attachmentPattern, async (attachmentRoute) => attachmentRoute.abort("failed"))
+ 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)
+ await expect(dialog.getByRole("button", { name: "Copy image" })).toBeDisabled()
+
+ await page.unroute(attachmentPattern)
+ await dialog.getByRole("button", { name: "Retry" }).click()
+ card = await waitForReady(dialog)
+ await expect(card.getByTestId(tid.messageShareImage(contentMessage.id, 0))).toHaveAttribute("src", /^data:image\//)
+})
-test("clipboard failure releases retry and Download keeps first-wins ownership", async ({ asUser }) => {
+test("clipboard failure releases retry and Download keeps first-winner 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 gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
+ const seeded = await seedMessage(page, channelId, "Retry and first-wins")
await installShareCapture(page, true)
- const dialog = await openShareDialog(page, messageId)
- await expect(dialog.locator('[data-avatar-photo-state="ready"]')).toBeVisible()
+ const dialog = await openShareDialog(page, seeded.id)
+ await waitForReady(dialog)
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 })
+ await expect.poll(() => clipboardAttempts(page)).toBe(2)
+ expect(await captureCounts(page)).toEqual({ clipboard: 1, download: 0 })
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")]
+ const ownerDialog = copy.closest('[role="dialog"]')!
+ const download = [...ownerDialog.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,
- })
+ await expect.poll(() => captureCounts(page)).toEqual({ clipboard: 1, download: 1 })
})
-test("closing a cold export suppresses its writer and reopening starts fresh", async ({ asUser }) => {
+test("light and dark desktop and narrow previews match their frozen full PNG", async ({ asUser }) => {
test.setTimeout(120_000)
- const serverId = await seedServer("alice", `Share close ${Date.now()}`)
- const channelId = await seedChannel("alice", serverId, "share-close")
+ const serverId = await seedServer("alice", `Share matrix ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "share-matrix")
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()
+ const seeded = await seedMessage(page, channelId, "Frozen theme, font, logo, geometry, and full-card pixels")
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)
+ const observations: Array<{
+ scheme: "light" | "dark"
+ viewport: "desktop" | "narrow"
+ width: number
+ background: string
+ difference: number
+ }> = []
+ let captureIndex = 0
+ for (const scheme of ["light", "dark"] as const) {
+ for (const viewport of ["desktop", "narrow"] as const) {
+ await page.setViewportSize(viewport === "desktop"
+ ? { width: 1280, height: 900 }
+ : { width: 390, height: 844 })
+ await page.evaluate((value) => {
+ document.documentElement.classList.toggle("dark", value === "dark")
+ document.documentElement.style.colorScheme = value
+ }, scheme)
+ const dialog = await openShareDialog(page, seeded.id)
+ const card = await waitForReady(dialog)
+ const style = await card.evaluate((node) => {
+ const computed = getComputedStyle(node)
+ const brand = node.querySelector<HTMLElement>("[data-share-brand]")!
+ return {
+ width: node.getBoundingClientRect().width,
+ background: computed.backgroundColor,
+ borderRadius: computed.borderRadius,
+ brandFont: getComputedStyle(brand).fontFamily,
+ animation: computed.animationName,
+ transition: computed.transitionProperty,
+ }
+ })
+ expect(style.borderRadius).not.toBe("0px")
+ expect(style.brandFont).not.toContain("var(")
+ expect(style.animation).toBe("none")
+ expect(style.transition).toBe("none")
+ await expect(card.getByTestId(tid.alookLogo)).toBeVisible()
+
+ await dialog.getByRole("button", { name: "Copy image" }).click()
+ await expect.poll(() => captureCounts(page)).toMatchObject({ clipboard: captureIndex + 1 })
+ const comparison = await comparePreviewToCapture(page, card, captureIndex)
+ expect(Math.abs(comparison.exportWidth - comparison.previewWidth * 2)).toBeLessThanOrEqual(2)
+ expect(Math.abs(comparison.exportHeight - comparison.previewHeight * 2)).toBeLessThanOrEqual(2)
+ expect(comparison.meanChannelDifference).toBeLessThan(28)
+ observations.push({
+ scheme,
+ viewport,
+ width: style.width,
+ background: style.background,
+ difference: comparison.meanChannelDifference,
+ })
+ captureIndex += 1
+ 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()
- 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,
- })
+ const desktopWidth = observations.find((value) => value.viewport === "desktop")!.width
+ const narrowWidth = observations.find((value) => value.viewport === "narrow")!.width
+ expect(narrowWidth).toBeLessThan(desktopWidth)
+ expect(observations.find((value) => value.scheme === "light")!.background)
+ .not.toBe(observations.find((value) => value.scheme === "dark")!.background)
})