Skip to content

Commit 0944c1d

Browse files
johnmatthewtennantThomas
andauthored
fix(emoji): recover transient image failures without reopening chats (#2000)
Signed-off-by: John Tennant <[email protected]> Co-authored-by: Thomas <ef494d9d97846d01e6a8bf964c4cf817a3303cbc4fa1e2b5a88f2a0b4055a94f@buzz.block.builderlab.xyz>
1 parent c775bef commit 0944c1d

3 files changed

Lines changed: 106 additions & 4 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// @vitest-environment jsdom
2+
import "@testing-library/jest-dom/vitest";
3+
import { act, cleanup, fireEvent, render } from "@testing-library/react";
4+
import { afterEach, expect, it, vi } from "vitest";
5+
import { CustomEmoji } from "./CustomEmoji";
6+
7+
const emoji = { shortcode: "party", url: "https://emoji.test/party.png" };
8+
const media = (url: string) => url;
9+
afterEach(() => {
10+
cleanup();
11+
vi.useRealTimers();
12+
});
13+
14+
it("recovers a transient image failure without remounting the message", () => {
15+
vi.useFakeTimers();
16+
const view = render(<CustomEmoji emoji={emoji} media={media} />);
17+
fireEvent.error(view.getByRole("img"));
18+
expect(view.container).toHaveTextContent(":party:");
19+
act(() => vi.advanceTimersByTime(2_000));
20+
expect(view.getByRole("img")).toHaveAttribute("src", emoji.url);
21+
fireEvent.load(view.getByRole("img"));
22+
expect(view.container).not.toHaveTextContent(":party:");
23+
expect(vi.getTimerCount()).toBe(0);
24+
});
25+
26+
it("bounds retries and cancels pending recovery when unmounted", () => {
27+
vi.useFakeTimers();
28+
const view = render(<CustomEmoji emoji={emoji} media={media} />);
29+
for (const delay of [2_000, 10_000, 30_000]) {
30+
fireEvent.error(view.getByRole("img"));
31+
act(() => vi.advanceTimersByTime(delay - 1));
32+
expect(view.queryByRole("img")).toBeNull();
33+
act(() => vi.advanceTimersByTime(1));
34+
expect(view.getByRole("img")).toHaveAttribute("src", emoji.url);
35+
}
36+
fireEvent.error(view.getByRole("img"));
37+
expect(view.container).toHaveTextContent(":party:");
38+
expect(vi.getTimerCount()).toBe(0);
39+
view.unmount();
40+
const pending = render(<CustomEmoji emoji={emoji} media={media} />);
41+
fireEvent.error(pending.getByRole("img"));
42+
pending.unmount();
43+
expect(vi.getTimerCount()).toBe(0);
44+
});
45+
46+
it("gives a changed source its own retry budget and never requests denied media", () => {
47+
vi.useFakeTimers();
48+
const view = render(<CustomEmoji emoji={emoji} media={media} />);
49+
fireEvent.error(view.getByRole("img"));
50+
const next = { ...emoji, url: "https://emoji.test/new.png" };
51+
view.rerender(<CustomEmoji emoji={next} media={media} />);
52+
expect(vi.getTimerCount()).toBe(0);
53+
fireEvent.error(view.getByRole("img"));
54+
act(() => vi.advanceTimersByTime(2_000));
55+
expect(view.getByRole("img")).toHaveAttribute("src", next.url);
56+
view.rerender(<CustomEmoji emoji={next} media={() => undefined} />);
57+
expect(view.queryByRole("img")).toBeNull();
58+
expect(view.container).toHaveTextContent(":party:");
59+
expect(vi.getTimerCount()).toBe(0);
60+
});

‎src/bundled/emoji/CustomEmoji.tsx‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
import { useState } from "react";
1+
import { useEffect, useState } from "react";
22
import type { CustomEmoji as Emoji } from "../../features/relay/emoji";
33
import styles from "./Emoji.module.css";
44

5+
const RETRY_DELAYS_MS = [2_000, 10_000, 30_000];
6+
57
/** Event URLs never bypass the captured community's media policy. */
68
export function CustomEmoji({
79
emoji,
@@ -11,9 +13,25 @@ export function CustomEmoji({
1113
media(url: string): string | undefined;
1214
}) {
1315
const src = media(emoji.url);
14-
const [failed, setFailed] = useState<string>();
1516
const literal = `:${emoji.shortcode}:`;
16-
return src && failed !== src ? (
17+
return src ? <EmojiImage key={src} src={src} literal={literal} /> : literal;
18+
}
19+
20+
function EmojiImage({ src, literal }: { src: string; literal: string }) {
21+
const [failed, setFailed] = useState(false);
22+
const [attempt, setAttempt] = useState(0);
23+
// Transient media failures must recover while the message stays mounted.
24+
// Bound requests for missing images and cancel recovery when the source leaves.
25+
useEffect(() => {
26+
const delay = RETRY_DELAYS_MS[attempt];
27+
if (!failed || delay === undefined) return;
28+
const timer = window.setTimeout(() => {
29+
setAttempt(attempt + 1);
30+
setFailed(false);
31+
}, delay);
32+
return () => window.clearTimeout(timer);
33+
}, [failed, attempt]);
34+
return !failed ? (
1735
<img
1836
className={styles.customEmoji}
1937
data-copy-emoji={literal}
@@ -24,7 +42,7 @@ export function CustomEmoji({
2442
width={22}
2543
height={22}
2644
loading="lazy"
27-
onError={() => setFailed(src)}
45+
onError={() => setFailed(true)}
2846
/>
2947
) : (
3048
literal

‎tests/browser/emoji.spec.mjs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ test("community picker uses keyboard, proxy thumbnails, event-local history and
1515
// Parallel fixtures must not invalidate each other’s optimized lazy imports.
1616
const cacheDir = await mkdtemp(join(tmpdir(), "buzz-emoji-vite-"));
1717
let server;
18+
let releaseHistoric;
19+
const historicFailure = new Promise((resolve) => {
20+
releaseHistoric = resolve;
21+
});
1822
try {
1923
server = await createServer({
2024
cacheDir,
@@ -26,7 +30,15 @@ test("community picker uses keyboard, proxy thumbnails, event-local history and
2630
server: { host: "127.0.0.1", port: 0, strictPort: false },
2731
});
2832
const errors = watchPageErrors(page);
33+
let historicRequests = 0;
2934
await page.route("**/emoji-media/**", async (route) => {
35+
if (
36+
route.request().url().includes("original.png") &&
37+
++historicRequests === 1
38+
) {
39+
await historicFailure;
40+
return route.fulfill({ status: 503, body: "temporarily unavailable" });
41+
}
3042
if (route.request().url().includes("broken.png"))
3143
return route.fulfill({ status: 404, body: "missing" });
3244
return route.fulfill({
@@ -77,6 +89,17 @@ test("community picker uses keyboard, proxy thumbnails, event-local history and
7789
page.getByRole("link", { name: "https://example.test/:party" }),
7890
).toHaveAttribute("href", "https://example.test/:party");
7991
const historic = page.locator('img[src*="original.png"]');
92+
// A transient media failure must recover while the same message remains mounted.
93+
const historicMessage = page.locator("p").filter({ hasText: "Historic" });
94+
releaseHistoric();
95+
await expect(historicMessage).toContainText(":unknown:party:");
96+
const mountedHistoric = await historicMessage.elementHandle();
97+
await expect(historic).toHaveCount(1);
98+
await expect(historic).toHaveJSProperty("naturalWidth", 22);
99+
expect(historicRequests).toBe(2);
100+
expect(await mountedHistoric.evaluate((node) => node.isConnected)).toBe(
101+
true,
102+
);
80103
const originalSrc = await historic.getAttribute("src");
81104
expect(originalSrc).toContain("/emoji-media/a/");
82105
await expect(page.locator('img[src*="reaction.png"]')).toHaveCount(1);
@@ -1121,6 +1144,7 @@ test("community picker uses keyboard, proxy thumbnails, event-local history and
11211144
await expect(page.getByRole("alert")).toHaveCount(0);
11221145
expect(errors.unexplained()).toEqual([]);
11231146
} finally {
1147+
releaseHistoric();
11241148
try {
11251149
await server?.close();
11261150
} finally {

0 commit comments

Comments
 (0)