Skip to content

Commit 7797ae7

Browse files
wesbillmanBrain
andauthored
fix(desktop): custom emoji reaction rendering + picker autofocus (#831)
Signed-off-by: Wes <[email protected]> Co-authored-by: Brain <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co>
1 parent 33cfc85 commit 7797ae7

4 files changed

Lines changed: 242 additions & 3 deletions

File tree

‎desktop/src/features/messages/ui/MessageActionBar.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,7 @@ export function MessageActionBar({
378378
</div>
379379
) : null}
380380
<Picker
381+
autoFocus
381382
data={data}
382383
custom={customEmojiCategory}
383384
onEmojiSelect={(emoji: { native?: string; id?: string }) => {

‎desktop/src/features/messages/ui/MessageReactions.tsx‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as React from "react";
22

33
import type { TimelineReaction } from "@/features/messages/types";
44
import { cn } from "@/shared/lib/cn";
5+
import { rewriteRelayUrl } from "@/shared/lib/mediaUrl";
56
import { Popover, PopoverContent, PopoverTrigger } from "@/shared/ui/popover";
67
import { UserAvatar } from "@/shared/ui/UserAvatar";
78

@@ -10,7 +11,9 @@ const MAX_VISIBLE_REACTORS = 10;
1011
/**
1112
* Render a reaction's emoji: a custom (image) emoji when `emojiUrl` is set,
1213
* otherwise the unicode/text glyph. `className` sizes the image to match the
13-
* surrounding text.
14+
* surrounding text. The relay URL is rewritten through the localhost media
15+
* proxy (like every other relay-hosted <img>) — WKWebView bypasses WARP, so a
16+
* direct relay URL gets a Cloudflare Access 403 and renders as a broken image.
1417
*/
1518
function EmojiGlyph({
1619
reaction,
@@ -23,7 +26,7 @@ function EmojiGlyph({
2326
return (
2427
<img
2528
alt={reaction.emoji}
26-
src={reaction.emojiUrl}
29+
src={rewriteRelayUrl(reaction.emojiUrl)}
2730
className={cn(
2831
"inline-block object-contain align-text-bottom",
2932
className,

‎desktop/src/testing/e2eBridge.ts‎

Lines changed: 165 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,9 @@ function createMockCustomEmojiSetEvents(): RelayEvent[] {
420420
[
421421
["d", CUSTOM_EMOJI_SET_D_TAG],
422422
["emoji", "sprout", "https://example.com/e2e/sprout.png"],
423+
// A relay-hosted emoji whose URL matches rewriteRelayUrl()'s pattern,
424+
// used by the reaction guard to assert the proxy rewrite fires.
425+
["emoji", REACTION_EMOJI_SHORTCODE, REACTION_EMOJI_URL],
423426
],
424427
// The current mock identity owns this set, so the settings card's
425428
// "My emoji" section is non-empty and removable.
@@ -516,6 +519,32 @@ declare global {
516519

517520
const DEFAULT_RELAY_HTTP_URL = "http://localhost:3000";
518521
const DEFAULT_RELAY_WS_URL = "ws://localhost:3000";
522+
523+
// NIP event kinds the mock reaction handlers emit.
524+
const KIND_REACTION = 7; // NIP-25 reaction
525+
const KIND_DELETION = 5; // NIP-09 deletion
526+
527+
// Fake media-proxy port the mock answers for `get_media_proxy_port`, so
528+
// `rewriteRelayUrl()` produces a real `http://localhost:<port>/media/...` src
529+
// in e2e (instead of the `sprout-media://` fallback). The reaction guard
530+
// asserts against this exact port.
531+
const MOCK_MEDIA_PROXY_PORT = 54321;
532+
533+
// A relay-hosted custom emoji used by the reaction guard. Its URL matches
534+
// `rewriteRelayUrl()`'s `/media/{64-hex}.{ext}` pattern on the relay origin, so
535+
// reacting with it exercises the proxy rewrite (unlike the `:sprout:` fixture,
536+
// whose external example.com URL passes through unchanged).
537+
const REACTION_EMOJI_SHORTCODE = "react";
538+
const REACTION_EMOJI_SHA = "c".repeat(64);
539+
const REACTION_EMOJI_URL = `${DEFAULT_RELAY_HTTP_URL}/media/${REACTION_EMOJI_SHA}.png`;
540+
541+
// A reaction-target message seeded into `general` with a real 64-hex event id.
542+
// The reaction guard reacts to THIS message: getReactionTargetId() only accepts
543+
// a 64-hex `e` tag, and the other mock seeds (and user-sent messages) use short
544+
// non-hex ids, so they can't be reaction targets. Content is distinctive so the
545+
// test locates its row without relying on seed ordering.
546+
const REACTION_TARGET_EVENT_ID = "d".repeat(64);
547+
const REACTION_TARGET_CONTENT = "React to me with a custom emoji";
519548
const E2E_IDENTITY_OVERRIDE_STORAGE_KEY = "sprout:e2e-identity-override.v1";
520549
const DEFAULT_MOCK_IDENTITY = {
521550
pubkey: "deadbeef".repeat(8),
@@ -1782,6 +1811,20 @@ function getMockMessageStore(channelId: string): RelayEvent[] {
17821811
content: "Hey team — checking in.",
17831812
sig: "mocksig".repeat(20).slice(0, 128),
17841813
},
1814+
// Reaction-target seed for the custom-emoji reaction guard. Real
1815+
// 64-hex id so getReactionTargetId() accepts it as a reaction target
1816+
// (the short-id seeds above can't be reacted to). Backdated after the
1817+
// other seeds, so it stays at row index >= 2 and never displaces
1818+
// first()=welcome / nth(1)=alice that other specs rely on.
1819+
{
1820+
id: REACTION_TARGET_EVENT_ID,
1821+
pubkey: ALICE_PUBKEY,
1822+
created_at: Math.floor(Date.now() / 1000) - 45,
1823+
kind: 9,
1824+
tags: [["h", channelId]],
1825+
content: REACTION_TARGET_CONTENT,
1826+
sig: "mocksig".repeat(20).slice(0, 128),
1827+
},
17851828
]
17861829
: channelId === "a27e1ee9-76a6-5bdf-a5d5-1d85610dad11"
17871830
? [
@@ -2190,15 +2233,28 @@ function handleGetLikedNotes(): RawUserNotesResponse {
21902233
return { notes: [], next_cursor: null };
21912234
}
21922235

2236+
// A random 64-hex event id, matching the shape of real Nostr event ids
2237+
// (sha256 → 64 hex). Most mock events use the 32-hex `createMockEvent` default,
2238+
// but kind:7 reactions need a real 64-hex id: the timeline's deletion path only
2239+
// accepts 64-hex `e` tags (getDeletionTargets in formatTimelineMessages.ts), so
2240+
// a kind:5 targeting a 32-hex reaction id would be silently ignored and the
2241+
// reaction pill would never clear on toggle-off.
2242+
function mockEventId(): string {
2243+
const bytes = new Uint8Array(32);
2244+
crypto.getRandomValues(bytes);
2245+
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
2246+
}
2247+
21932248
function createMockEvent(
21942249
kind: number,
21952250
content: string,
21962251
tags: string[][],
21972252
pubkey = DEFAULT_MOCK_IDENTITY.pubkey,
21982253
createdAt = Math.floor(Date.now() / 1000),
2254+
id = crypto.randomUUID().replace(/-/g, ""),
21992255
): RelayEvent {
22002256
return {
2201-
id: crypto.randomUUID().replace(/-/g, ""),
2257+
id,
22022258
pubkey,
22032259
created_at: createdAt,
22042260
kind,
@@ -4557,6 +4613,102 @@ async function handleSendChannelMessage(
45574613
};
45584614
}
45594615

4616+
/** Locate the channel a stored mock event lives in (reactions carry no channel arg). */
4617+
function findMockEventChannel(eventId: string): string | undefined {
4618+
for (const [channelId, events] of mockMessages) {
4619+
if (events.some((event) => event.id === eventId)) {
4620+
return channelId;
4621+
}
4622+
}
4623+
return undefined;
4624+
}
4625+
4626+
/**
4627+
* Mock the `add_reaction` Tauri command. Mirrors the real Rust command: a
4628+
* kind:7 whose content is the emoji, plus — for a custom emoji — the NIP-30
4629+
* `["emoji", shortcode, url]` tag (shortcode normalized to match the relay).
4630+
* Recorded into the target's channel store and emitted live so the timeline's
4631+
* reaction aggregation renders the pill (the channel subscription includes
4632+
* kind:7). Unicode reactions carry no emoji tag, like the real command.
4633+
*/
4634+
async function handleAddReaction(
4635+
args: { eventId: string; emoji: string; emojiUrl?: string | null },
4636+
config: E2eConfig | undefined,
4637+
): Promise<void> {
4638+
const channelId = findMockEventChannel(args.eventId);
4639+
if (!channelId) {
4640+
throw new Error(`mock add_reaction: unknown target event ${args.eventId}`);
4641+
}
4642+
4643+
const emoji = args.emoji.trim();
4644+
// `h` routes the live event to the channel store (getChannelIdFromTags);
4645+
// `e` names the reaction target. For a custom emoji, the NIP-30
4646+
// `["emoji", shortcode, url]` tag carries the image URL.
4647+
const tags: string[][] = [
4648+
["h", channelId],
4649+
["e", args.eventId],
4650+
];
4651+
if (args.emojiUrl) {
4652+
const shortcode = emoji.replace(/^:+/, "").replace(/:+$/, "").toLowerCase();
4653+
tags.push(["emoji", shortcode, args.emojiUrl]);
4654+
}
4655+
4656+
const event = createMockEvent(
4657+
KIND_REACTION,
4658+
emoji,
4659+
tags,
4660+
getMockMemberPubkey(config),
4661+
Math.floor(Date.now() / 1000),
4662+
// 64-hex id so the kind:5 deletion emitted by remove_reaction is accepted
4663+
// by the timeline (getDeletionTargets requires a 64-hex `e` tag).
4664+
mockEventId(),
4665+
);
4666+
recordMockMessage(channelId, event);
4667+
emitMockLiveEvent(channelId, event);
4668+
}
4669+
4670+
/**
4671+
* Mock the `remove_reaction` Tauri command. Finds the active member's own
4672+
* kind:7 for this target+emoji, removes it from the store, and emits a kind:5
4673+
* deletion so the timeline drops the reaction (the real command deletes via a
4674+
* kind:5 too).
4675+
*/
4676+
async function handleRemoveReaction(
4677+
args: { eventId: string; emoji: string },
4678+
config: E2eConfig | undefined,
4679+
): Promise<void> {
4680+
const channelId = findMockEventChannel(args.eventId);
4681+
if (!channelId) {
4682+
return;
4683+
}
4684+
4685+
const myPubkey = getMockMemberPubkey(config).toLowerCase();
4686+
const emoji = args.emoji.trim();
4687+
const store = getMockMessageStore(channelId);
4688+
const reaction = store.find(
4689+
(event) =>
4690+
event.kind === KIND_REACTION &&
4691+
event.pubkey.toLowerCase() === myPubkey &&
4692+
event.content.trim() === emoji &&
4693+
event.tags.some((t) => t[0] === "e" && t[1] === args.eventId),
4694+
);
4695+
if (!reaction) {
4696+
return;
4697+
}
4698+
4699+
const index = store.indexOf(reaction);
4700+
store.splice(index, 1);
4701+
4702+
const deletion = createMockEvent(
4703+
KIND_DELETION,
4704+
"",
4705+
[["e", reaction.id]],
4706+
getMockMemberPubkey(config),
4707+
);
4708+
recordMockMessage(channelId, deletion);
4709+
emitMockLiveEvent(channelId, deletion);
4710+
}
4711+
45604712
async function handleGetEvent(
45614713
args: {
45624714
eventId: string;
@@ -5323,6 +5475,18 @@ export function maybeInstallE2eTauriMocks() {
53235475
payload as Parameters<typeof handleSendChannelMessage>[0],
53245476
activeConfig,
53255477
);
5478+
case "add_reaction":
5479+
return handleAddReaction(
5480+
payload as Parameters<typeof handleAddReaction>[0],
5481+
activeConfig,
5482+
);
5483+
case "remove_reaction":
5484+
return handleRemoveReaction(
5485+
payload as Parameters<typeof handleRemoveReaction>[0],
5486+
activeConfig,
5487+
);
5488+
case "get_media_proxy_port":
5489+
return MOCK_MEDIA_PROXY_PORT;
53265490
case "pick_and_upload_media":
53275491
return resolveMockUploadDescriptors(activeConfig);
53285492
case "upload_media_bytes":

‎desktop/tests/e2e/custom-emoji.spec.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,74 @@ test("custom emoji round-trips through select-all + send to the timeline", async
9393
// The composer clears after send.
9494
await expect(input.locator("img[data-custom-emoji]")).toHaveCount(0);
9595
});
96+
97+
// Regression guard for custom-emoji REACTIONS.
98+
//
99+
// The bug (shipped in the custom-emoji launch, PR #816): the reaction renderer
100+
// put the relay emoji URL straight into <img src> without going through
101+
// rewriteRelayUrl(). WKWebView bypasses WARP, so the direct relay URL gets a
102+
// Cloudflare Access 403 and shows a broken image — even though the same emoji
103+
// rendered fine inline in chat (that path rewrites). The chat path was covered
104+
// by the tests above; the reaction path was not, which is why it slipped.
105+
//
106+
// This drives the real interactive react flow (hover -> Open reactions ->
107+
// emoji-mart custom category) so it exercises the add_reaction Tauri command,
108+
// then asserts the rendered reaction <img> src points at the localhost media
109+
// proxy. On the pre-fix code the src would be the raw relay URL, so this test
110+
// fails there — exactly the assertion that would have caught the bug.
111+
//
112+
// `:react:` is a relay-hosted fixture emoji (URL on the relay origin matching
113+
// rewriteRelayUrl()'s /media/{64-hex}.{ext} pattern), and the mock bridge
114+
// answers get_media_proxy_port with port 54321 so the rewrite resolves to a
115+
// real localhost URL rather than the sprout-media:// fallback.
116+
117+
const REACTION_SHORTCODE = "react";
118+
const MOCK_MEDIA_PROXY_PORT = 54321;
119+
// A seeded message in `general` with a real 64-hex id — the only reactable
120+
// target in mock mode (getReactionTargetId() requires a 64-hex `e` tag, which
121+
// user-sent mock messages don't have). Mirrors REACTION_TARGET_CONTENT in the
122+
// bridge.
123+
const REACTION_TARGET_CONTENT = "React to me with a custom emoji";
124+
125+
test("reacting with a custom emoji renders via the localhost media proxy", async ({
126+
page,
127+
}) => {
128+
await openGeneral(page);
129+
130+
// Reveal the hover action bar on the seeded reaction-target message, then
131+
// open the reaction picker.
132+
const row = page
133+
.getByTestId("message-row")
134+
.filter({ hasText: REACTION_TARGET_CONTENT })
135+
.last();
136+
await expect(row).toBeVisible();
137+
await row.hover();
138+
await row.getByLabel("Open reactions").click();
139+
140+
// emoji-mart renders inside a Shadow DOM web component. Search by shortcode
141+
// to surface the custom emoji, then click it.
142+
const picker = page.locator("em-emoji-picker");
143+
await picker.locator("input[type='search']").fill(REACTION_SHORTCODE);
144+
// Custom emoji buttons carry the shortcode as their `title` (no aria-label).
145+
await picker.locator(`button[title='${REACTION_SHORTCODE}']`).first().click();
146+
147+
// The reaction pill renders the custom emoji as an <img alt=":react:">. Its
148+
// src must be the localhost proxy URL — proving rewriteRelayUrl() ran. A raw
149+
// relay URL here is the bug.
150+
const reactionImg = row.locator(`img[alt=':${REACTION_SHORTCODE}:']`);
151+
await expect(reactionImg).toBeVisible();
152+
await expect(reactionImg).toHaveAttribute(
153+
"src",
154+
new RegExp(
155+
`^http://localhost:${MOCK_MEDIA_PROXY_PORT}/media/[\\da-f]{64}\\.png$`,
156+
),
157+
);
158+
159+
// Toggle the reaction back off: click the pill, which fires remove_reaction
160+
// -> emits a kind:5 deletion targeting the reaction event. The pill must
161+
// disappear. Guards the mock-bridge deletion path: the reaction event needs a
162+
// 64-hex id, because the timeline only honors deletions whose `e` tag is
163+
// 64-hex (getDeletionTargets). A 32-hex reaction id leaves a stale pill here.
164+
await row.getByLabel(`Toggle :${REACTION_SHORTCODE}: reaction`).click();
165+
await expect(reactionImg).toHaveCount(0);
166+
});

0 commit comments

Comments
 (0)