Skip to content

Commit d8b602a

Browse files
wesbillmanBrain
andauthored
fix(desktop): robust emoji picker — unify picker + fix custom emoji in editing, status, reactions (#837)
Signed-off-by: Wes <[email protected]> Co-authored-by: Brain <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co>
1 parent 06bc67f commit d8b602a

24 files changed

Lines changed: 696 additions & 107 deletions

‎desktop/scripts/check-file-sizes.mjs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,17 @@ const overrides = new Map([
4242
["src/features/channels/useUnreadChannels.ts", 717], // NIP-RS read marker tracking + participated/authored/followed thread ID sets + localStorage persistence + catch-up REQ with thread activity collection + thread reply activity feed items + mutedRootIds denylist with localStorage persistence + muteThread/unmuteThread callbacks + markChannelRead latestByChannelRef fallback chain (matches markChannelUnread)
4343
["src/features/notifications/hooks.ts", 535], // notification settings + feed notification lifecycle + profile batch resolution + truncated-pubkey guard + badge state
4444
["src/features/home/ui/HomeView.tsx", 505], // inbox/feed orchestration + thread context + reply/delete flow + NIP-RS read-state projection wiring (useHomeInboxReadState)
45-
["src/features/messages/hooks.ts", 525], // message query/mutation hooks + optimistic updates + custom-emoji reaction URL resolution (reactionEmojiUrl from cached relay set) + outgoing tag split (splitOutgoingTags) routing custom-emoji tags through the dedicated emoji_tags send arg so they skip the imeta-only gate
45+
["src/features/messages/hooks.ts", 530], // message query/mutation hooks + optimistic updates + custom-emoji reaction URL resolution (reactionEmojiUrl from cached relay set) + outgoing tag split (splitOutgoingTags) routing custom-emoji tags through the dedicated emoji_tags send arg so they skip the imeta-only gate; edit mutation splits the merged tag set the same way so edited custom emoji ride the dedicated emoji_tags arg
4646
["src/features/messages/lib/useRichTextEditor.ts", 620], // editor setup + 3 inline Tiptap keymap extensions (macEmacs/smartShiftEnter/submitOnEnter) + editorProps.handleKeyDown for ↑-to-edit + editable-toggle focus-restore (records isFocused before disable on send, re-focuses on re-enable so the WebView blur-on-disable doesn't strand focus on body) + custom-emoji atom-node wiring (useComposerCustomEmoji extension + src re-resolve effect; replacePlainTextRange inserts the selectable/copyable CustomEmojiNode for `:shortcode:` so it behaves like a built-in emoji glyph). Split candidate: extract the 3 keymap extensions to a sibling module (tracked follow-up).
47-
["src/features/messages/ui/MessageComposer.tsx", 860], // media upload handlers (paste, drop, dialog) + channelId reset effect + edit mode (pre-fill, save, cancel, escape) + composer autofocus (#572) + Sprout code-block paste branch (round-trips copy-button output as a literal codeBlock so Markdown can't reshape it) + scroll-to-bottom on multi-line paste (#619) + Slack-style attachment-editable edits: seed pendingImeta from edit target, stash/restore user's draft pendingImeta across edit-mode entry/exit, re-append imeta markdown lines on edit-submit so renderer draws them + custom emoji: useCustomEmoji feeds picker/autocomplete and mergeOutgoingTags attaches NIP-30 emoji tags on send; insertEmoji inserts a known `:shortcode:` as the selectable CustomEmojiNode atom (else plain native unicode)
47+
["src/features/messages/ui/MessageComposer.tsx", 870], // media upload handlers (paste, drop, dialog) + channelId reset effect + edit mode (pre-fill, save, cancel, escape) + composer autofocus (#572) + Sprout code-block paste branch (round-trips copy-button output as a literal codeBlock so Markdown can't reshape it) + scroll-to-bottom on multi-line paste (#619) + Slack-style attachment-editable edits: seed pendingImeta from edit target, stash/restore user's draft pendingImeta across edit-mode entry/exit, re-append imeta markdown lines on edit-submit so renderer draws them + custom emoji: useCustomEmoji feeds picker/autocomplete and mergeOutgoingTags attaches NIP-30 emoji tags on send AND on edit-save (so edited custom emoji stay resolvable); insertEmoji inserts a known `:shortcode:` as the selectable CustomEmojiNode atom (else plain native unicode)
4848
["src/features/settings/ui/SettingsView.tsx", 600],
4949
["src/features/sidebar/ui/AppSidebar.tsx", 830], // channels + forums creation forms + Pulse nav + channel sections state/dialogs + SidebarDndContext wrapper + sectionIds memo for DnD section reorder + controlled create-channel dialog for ⌘⇧N shortcut
5050
["src/features/sidebar/ui/CustomChannelSection.tsx", 615], // ChannelGroupSection + CustomChannelSection + SectionHeaderActions + ChannelContextMenuItems + MoveToSectionSubmenu + per-section mark-all-read + DnD wrappers (SortableSectionShell, DraggableChannelRow, DroppableSectionBody, DroppableUngroupedBody) + draggable prop on ChannelGroupSection
5151
["src/shared/api/relayClientSession.ts", 1040], // durable websocket session manager with reconnect/replay/recovery state + sendTypingIndicator + fetchChannelHistoryBefore + subscribeToChannelLive (huddle TTS) + subscribeToHuddleEvents (huddle indicator) + disconnect() for workspace switch teardown + fetchEvents/subscribeLive/publishEvent for NIP-RS read state + publishUserStatus/subscribeToUserStatusUpdates (NIP-38) + ConnectionState plumbing & stall-watchdog wiring for half-open WS detection (Warp orange-icon case) + terminal session latch (auth rejection no longer racing back to reconnecting) — emitter + watchdog + reconnect policy logic extracted to relayConnectionStateEmitter.ts / relayStallWatchdog.ts / relayReconnectPolicy.ts
5252
["src-tauri/src/migration.rs", 1010], // worktree shared-agent-data symlink sync (SHARED_AGENT_FILES + SHARED_AGENT_DIRS symlink-to-canonical + sibling pack migration) + mcp_command provider reconciliation + persona_pack_path reconciliation + tests
5353
["src-tauri/src/commands/media.rs", 730], // ffmpeg video transcode + poster frame extraction + run_ffmpeg_with_timeout (find_ffmpeg via resolve_command, is_video_file, transcode_to_mp4, extract_poster_frame, transcode_and_extract_poster) + spawn_blocking wrappers + tests
5454
["src-tauri/src/commands/agents.rs", 910], // remote agent lifecycle routing (local + provider branches) + scope enforcement + persona pack metadata wiring + mcp_toolsets field + NIP-OA auth_tag in deploy payload + relay-mesh client preflight (start_local_agent_with_preflight + StartTarget split: async ensure outside store lock, then sync spawn under lock)
55-
["src-tauri/src/commands/messages.rs", 525], // feed multi-query + NIP-50 search + forum thread resolution + thread ref + edit_message media_tags param (Slack-style attachment-editable edits) + add_reaction custom-emoji branch (build_custom_emoji_reaction when emoji_url is set)
55+
["src-tauri/src/commands/messages.rs", 530], // feed multi-query + NIP-50 search + forum thread resolution + thread ref + edit_message media_tags + emoji_tags params (Slack-style attachment edits + edited custom emoji stay resolvable) + add_reaction custom-emoji branch (build_custom_emoji_reaction when emoji_url is set)
5656
["src-tauri/src/nostr_convert.rs", 1150], // 12 Nostr event→model converters (channels, profiles, members, notes, search, agents, relay members) + rank_user_search_results helper for NIP-50 user search + 33 unit tests
5757
["src-tauri/src/managed_agents/runtime.rs", 1390], // ... + respond-to gate env (SPROUT_ACP_RESPOND_TO[_ALLOWLIST]) + per-mode env builder + tests + persona/agent env_vars spawn merge (helper + tests now in env_vars.rs) + system-wide orphan sweep (proc_listallpids/proc on macOS, /proc on Linux) + SPROUT_MANAGED_AGENT env marker check (KERN_PROCARGS2 on macOS, /proc/environ on Linux), instance-scoped by app identifier so coexisting Sprout instances don't reap each other's agents + relay_mesh_model_id detector (mesh preset-env match) + tests
5858
["src-tauri/src/managed_agents/discovery.rs", 680], // KNOWN_ACP_PROVIDERS catalog + resolve_command cache + login_shell_path + classify_provider (four-state: Available/AdapterMissing/CliMissing/NotInstalled) + discover_acp_providers with dynamic install_hint + known_acp_provider/known_acp_provider_exact + normalize_agent_args + 15 unit tests
@@ -71,7 +71,7 @@ const overrides = new Map([
7171
["src/features/channels/ui/AddChannelBotDialog.tsx", 690], // provider mode: Run on selector, trust warning, probe effect, single-agent enforcement, provider warnings display + RespondTo field + reuse guardrail
7272
["src/features/settings/ui/ChannelTemplatesSettingsCard.tsx", 850], // template CRUD card + TemplateFormDialog (persona/team chip selectors + provider assignments + canvas template) + TemplateTeamSelector + ProviderAssignments + ProviderRow
7373
["src/shared/api/types.ts", 650], // ... + AcpProviderCatalogEntry + AcpProvider (narrowed subtype) + InstallRuntimeResult + RespondToMode + respondTo/respondToAllowlist on ManagedAgent/Create/Update inputs
74-
["src-tauri/src/events.rs", 825], // event builders + build_huddle_guidelines (kind:48106) + post_event_raw transport helper + participant p-tag on join/leave + NIP-43 relay admin builders (add/remove/change-role) + check_relay_role + DM/presence/workflow command builders + NIP-IA identity-archive builders (9035/9036) + .allow_self_tagging() guards (nostr 0.44 strips self-`p` by default; self-archive/unarchive needs it preserved) + spec vector 1 layout test + emoji_tags() NIP-30 builder (mirrors the imeta_tags injection guard, first elem must be "emoji")
74+
["src-tauri/src/events.rs", 830], // event builders + build_huddle_guidelines (kind:48106) + post_event_raw transport helper + participant p-tag on join/leave + NIP-43 relay admin builders (add/remove/change-role) + check_relay_role + DM/presence/workflow command builders + NIP-IA identity-archive builders (9035/9036) + .allow_self_tagging() guards (nostr 0.44 strips self-`p` by default; self-archive/unarchive needs it preserved) + spec vector 1 layout test + emoji_tags() NIP-30 builder (mirrors the imeta_tags injection guard, first elem must be "emoji"); build_message_edit also threads emoji_tags so edited custom emoji stay resolvable
7575
["src-tauri/src/huddle/mod.rs", 1020], // huddle state machine + Tauri commands + sync protocol doc; state/relay/pipeline extracted + emit_huddle_state_changed wiring
7676
["src-tauri/src/huddle/models.rs", 950], // model download manager for Parakeet TDT-CTC STT + Pocket TTS with streaming downloads + SHA-256 verification + Rust-native tar extraction + version manifest + atomic swap + hot-start signaling + MODEL_LICENSE.txt sidecar (fail-closed readiness) + idempotent legacy Moonshine dir cleanup + tts_readiness_requires_license_sidecar test + Mary (VCTK p333) reference voice attribution block
7777
["src-tauri/src/huddle/stt.rs", 580], // STT pipeline + PTT edge-detection flush + PTT gating (is_speech AND ptt_active) + barge-in for VAD mode + rubato resampler + earshot VAD + sherpa-onnx transcription

‎desktop/src-tauri/src/commands/messages.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,7 @@ pub async fn edit_message(
402402
event_id: String,
403403
content: String,
404404
media_tags: Vec<Vec<String>>,
405+
emoji_tags: Option<Vec<Vec<String>>>,
405406
state: State<'_, AppState>,
406407
) -> Result<(), String> {
407408
let channel_uuid = uuid::Uuid::parse_str(&channel_id)
@@ -413,7 +414,9 @@ pub async fn edit_message(
413414
if trimmed.is_empty() && media_tags.is_empty() {
414415
return Err("edit must have content or attachments".into());
415416
}
416-
let builder = events::build_message_edit(channel_uuid, target_eid, trimmed, &media_tags)?;
417+
let emoji = emoji_tags.unwrap_or_default();
418+
let builder =
419+
events::build_message_edit(channel_uuid, target_eid, trimmed, &media_tags, &emoji)?;
417420
submit_event(builder, &state).await?;
418421
Ok(())
419422
}

‎desktop/src-tauri/src/events.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,19 +302,23 @@ pub fn build_forum_comment(
302302

303303
/// Kind 40003 — edit a message. Carries the full new content AND a fresh
304304
/// imeta tag set; the receiver overlays the imeta tags onto the original
305-
/// event so the rendered message reflects exactly the edited state.
305+
/// event so the rendered message reflects exactly the edited state. NIP-30
306+
/// custom-emoji tags ride along the same way so an edited body's `:shortcode:`s
307+
/// stay resolvable (the send path attaches these too).
306308
pub fn build_message_edit(
307309
channel_id: Uuid,
308310
target_event_id: EventId,
309311
content: &str,
310312
media_tags: &[Vec<String>],
313+
custom_emoji_tags: &[Vec<String>],
311314
) -> Result<EventBuilder, String> {
312315
check_content(content)?;
313316
let mut tags = vec![
314317
tag(vec!["h", &channel_id.to_string()])?,
315318
tag(vec!["e", &target_event_id.to_hex()])?,
316319
];
317320
imeta_tags(media_tags, &mut tags)?;
321+
emoji_tags(custom_emoji_tags, &mut tags)?;
318322
Ok(EventBuilder::new(Kind::Custom(40003), content).tags(tags))
319323
}
320324

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import data from "@emoji-mart/data";
2+
import Picker from "@emoji-mart/react";
3+
import * as React from "react";
4+
5+
import { buildCustomEmojiCategory } from "@/features/custom-emoji/emojiMartCategory";
6+
import { useCustomEmoji } from "@/features/custom-emoji/hooks";
7+
8+
/**
9+
* The one emoji picker for the whole app. Every place that lets a user choose
10+
* an emoji — composing a message, reacting to a regular or system message,
11+
* setting a status — renders this, so the config and custom-emoji wiring can't
12+
* drift across call sites (they used to, and that's why custom emoji were
13+
* missing from some pickers).
14+
*
15+
* It always wires the workspace custom-emoji palette in via `useCustomEmoji()`,
16+
* so custom emoji show up everywhere for free. Selection is normalized to a
17+
* single string: a standard emoji emits its `native` glyph; a custom emoji has
18+
* no `native`, so it emits its `:shortcode:` (the emoji-mart `id` is the
19+
* shortcode). Consumers store/send that string and let the existing renderers
20+
* (reactions' `emojiUrl`, the remark shortcode plugin) resolve it to an image.
21+
*
22+
* Only the raw picker lives here — not the Popover/trigger. Those differ per
23+
* site (ghost button vs status swatch, popover vs dialog content) and forcing
24+
* them into one wrapper would be less clear, not more. The thing that drifted
25+
* was the picker config + custom wiring + select handling; that's what this
26+
* centralizes.
27+
*/
28+
type EmojiPickerProps = {
29+
/** Autofocus the search field when the picker mounts (e.g. reaction popovers). */
30+
autoFocus?: boolean;
31+
/** Called with the chosen emoji as a string: `native` glyph or `:shortcode:`. */
32+
onSelect: (emoji: string) => void;
33+
};
34+
35+
export const EmojiPicker = React.memo(function EmojiPicker({
36+
autoFocus = false,
37+
onSelect,
38+
}: EmojiPickerProps) {
39+
const customEmoji = useCustomEmoji();
40+
const custom = React.useMemo(
41+
() => buildCustomEmojiCategory(customEmoji),
42+
[customEmoji],
43+
);
44+
45+
return (
46+
<Picker
47+
autoFocus={autoFocus}
48+
custom={custom}
49+
data={data}
50+
maxFrequentRows={2}
51+
onEmojiSelect={(emoji: { native?: string; id?: string }) => {
52+
// Standard emoji carry a `native` glyph. Custom emoji don't — emit
53+
// their `:shortcode:` (emoji-mart `id` == shortcode) instead. Ignore a
54+
// malformed selection that has neither.
55+
const value = emoji.native ?? (emoji.id ? `:${emoji.id}:` : "");
56+
if (value) {
57+
onSelect(value);
58+
}
59+
}}
60+
perLine={8}
61+
previewPosition="none"
62+
set="native"
63+
skinTonePosition="search"
64+
theme="auto"
65+
/>
66+
);
67+
});

‎desktop/src/features/messages/hooks.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,13 @@ export function useEditMessageMutation(channel: Channel | null) {
491491
throw new Error("No channel selected.");
492492
}
493493

494-
await editMessage(channel.id, eventId, content, mediaTags);
494+
// `mediaTags` arrives as the merged outgoing set (imeta + NIP-30 emoji).
495+
// Split so each rides its own validated Tauri arg — emoji tags must NOT
496+
// go through the imeta-only `mediaTags` channel (the Rust `imeta_tags`
497+
// guard rejects any non-imeta prefix), mirroring the send path.
498+
const { mediaTags: imetaTags, emojiTags } = splitOutgoingTags(mediaTags);
499+
500+
await editMessage(channel.id, eventId, content, imetaTags, emojiTags);
495501
},
496502
onSuccess: (_data, { eventId, content, mediaTags }) => {
497503
if (!channel) {

‎desktop/src/features/messages/lib/applyEditTagOverlay.d.mts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77
export type Tag = string[];
88

99
/**
10-
* Merge an event's tags with an edit's tags: imeta from the edit (full new
11-
* attachment set), all other tag kinds from the original. Pass-through when
12-
* `editTags` is `undefined`.
10+
* Merge an event's tags with an edit's tags: imeta + NIP-30 emoji tags from the
11+
* edit (full new attachment + custom-emoji set), all other tag kinds from the
12+
* original. Pass-through when `editTags` is `undefined`.
1313
*/
1414
export function applyEditTagOverlay(
1515
originalTags: Tag[],

‎desktop/src/features/messages/lib/applyEditTagOverlay.mjs‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,16 @@
1212
/**
1313
* Merge the original event's tags with an edit's tags so that:
1414
* - `imeta` tags come exclusively from the edit (full new attachment set);
15+
* - `emoji` (NIP-30 custom-emoji) tags come from the edit *when the edit
16+
* supplies any* — the edited body may add or remove custom emoji, so a
17+
* supplied set rebuilds the shortcode→url map. But when the edit supplies
18+
* NO emoji tags, the original's emoji tags are PRESERVED. A tag-less edit
19+
* can come from an older build (before edits carried emoji tags) or another
20+
* client that doesn't know this path; dropping the original's emoji tags
21+
* there would strip the only shortcode→url mapping and re-break a
22+
* `:shortcode:` that the original rendered fine. Preserving on empty is
23+
* strictly safe: an orphaned emoji tag whose shortcode is no longer in the
24+
* body resolves nothing, so it can't cause a stale render.
1525
* - all other tag kinds (`h`, `e`, `p` mentions, etc.) come exclusively
1626
* from the original — the edit can't rewrite channel membership,
1727
* thread refs, or mention targets.
@@ -20,7 +30,14 @@
2030
*/
2131
export function applyEditTagOverlay(originalTags, editTags) {
2232
if (!editTags) return originalTags;
23-
const nonImetaOriginal = originalTags.filter((t) => t[0] !== "imeta");
24-
const imetaFromEdit = editTags.filter((t) => t[0] === "imeta");
25-
return [...nonImetaOriginal, ...imetaFromEdit];
33+
const editEmoji = editTags.filter((t) => t[0] === "emoji");
34+
// imeta is always fully replaced by the edit. emoji is replaced only when
35+
// the edit actually supplies emoji tags; otherwise the original's are kept.
36+
const droppedFromOriginal =
37+
editEmoji.length > 0
38+
? (t) => t[0] !== "imeta" && t[0] !== "emoji"
39+
: (t) => t[0] !== "imeta";
40+
const baseFromOriginal = originalTags.filter(droppedFromOriginal);
41+
const overlaidFromEdit = editTags.filter((t) => t[0] === "imeta");
42+
return [...baseFromOriginal, ...overlaidFromEdit, ...editEmoji];
2643
}

0 commit comments

Comments
 (0)