(
let replyBodyJSX: ReactNode = replyDraft ? trimReplyFromBody(replyDraft.body) : null;
if (htmlBody) {
+ /**
+ * message with linebreaks, etc stripped
+ */
const strippedHtml = trimReplyFromFormattedBody(htmlBody)
.replaceAll(/
/gi, ' ')
.replaceAll(/<\/p>\s*]*>/gi, ' ')
@@ -489,7 +503,7 @@ export const RoomInput = forwardRef(
return getVideoMsgContent(mx, fileItem, upload.mxc);
}
if (fileItem.file.type.startsWith('audio')) {
- return getAudioMsgContent(fileItem, upload.mxc, audioMsgWaveform, audioMsgLength);
+ return getAudioMsgContent(fileItem, upload.mxc);
}
return getFileMsgContent(fileItem, upload.mxc);
});
@@ -561,7 +575,7 @@ export const RoomInput = forwardRef(
contents.map((content) =>
mx
.sendMessage(roomId, threadRootId ?? null, content as any)
- .then((res) => {
+ .then((res: { event_id: string }) => {
debugLog.info('message', 'Uploaded file message sent', {
roomId,
eventId: res.event_id,
@@ -621,12 +635,65 @@ export const RoomInput = forwardRef(
uploadBoardHandlers.current?.handleSend();
const commandName = getBeginCommand(editor);
- let plainText = toPlainText(editor.children, isMarkdown).trim();
+ /**
+ * a map of regex patterns to replace nicknames with,
+ * used when stripNickname is true in toMatrixCustomHTML
+ * during HTML generation for the message content.
+ * This is necessary because the HTML generation needs to know
+ * which nicknames to strip in order to generate the correct formatted_body,
+ * and the plain text generation needs to replace those same nicknames with
+ * the original user IDs so that the message content remains consistent and
+ * mentions are correctly processed by the server and clients.
+ */
+ const nicknameReplacement = new Map();
+ if (replyEvent) {
+ /**
+ * the id of the user being replied to,
+ * whose nickname (if any) should be stripped
+ * from the message content and replaced with their
+ * user ID for correct mention processing
+ */
+ const senderId = replyEvent.getSender();
+ if (senderId) {
+ const nick = nicknames[senderId];
+ if (typeof nick === 'string' && nick.length > 0) {
+ nicknameReplacement.set(
+ new RegExp(`@?${nick}`, 'g'),
+ room.getMember(senderId)?.rawDisplayName ?? senderId
+ );
+ }
+ }
+ }
+ /**
+ * any other users mentioned in the message being replied to,
+ * whose nicknames should also be stripped and replaced with user IDs
+ */
+ const mentions = getMentions(mx, roomId, editor);
+ if (mentions?.users) {
+ mentions.users.forEach((id) => {
+ const nick = nicknames[id];
+ if (typeof nick === 'string' && nick.length > 0) {
+ nicknameReplacement.set(
+ new RegExp(`@?${nick}`, 'g'),
+ room.getMember(id)?.rawDisplayName ?? id
+ );
+ }
+ });
+ }
+ /**
+ * the plain text we will send
+ */
+ let plainText = toPlainText(editor.children, isMarkdown, true, nicknameReplacement).trim();
+ /**
+ * the html we will send
+ */
let customHtml = trimCustomHtml(
toMatrixCustomHTML(editor.children, {
allowTextFormatting: true,
allowBlockMarkdown: isMarkdown,
allowInlineMarkdown: isMarkdown,
+ stripNickname: true,
+ nickNameReplacement: nicknameReplacement,
})
);
let msgType = MsgType.Text;
@@ -759,7 +826,7 @@ export const RoomInput = forwardRef(
},
() => mx.sendMessage(roomId, threadRootId ?? null, content as any)
)
- .then((res) => {
+ .then((res: { event_id: string }) => {
debugLog.info('message', 'Message sent successfully', {
roomId,
eventId: res.event_id,
@@ -783,6 +850,7 @@ export const RoomInput = forwardRef(
}
}, [
editor,
+ replyEvent,
isMarkdown,
canSendReaction,
mx,
@@ -792,6 +860,7 @@ export const RoomInput = forwardRef(
silentReply,
scheduledTime,
editingScheduledDelayId,
+ nicknames,
handleQuickReact,
commands,
sendTypingStatus,
@@ -805,41 +874,54 @@ export const RoomInput = forwardRef(
const handleKeyDown: KeyboardEventHandler = useCallback(
(evt) => {
- if (autocompleteQuery && isKeyHotkey('arrowdown', evt)) {
- evt.preventDefault();
- document
- .querySelector('[data-autocomplete-menu]')
- ?.dispatchEvent(new CustomEvent('autocomplete-navigate', { detail: { direction: 1 } }));
- return;
- }
- if (autocompleteQuery && isKeyHotkey('arrowup', evt)) {
- evt.preventDefault();
- document
- .querySelector('[data-autocomplete-menu]')
- ?.dispatchEvent(
+ const autocompleteMenu = document.querySelector('[data-autocomplete-menu]');
+ const isMenuVisible = !!(autocompleteQuery && autocompleteMenu);
+
+ if (isMenuVisible) {
+ if (isKeyHotkey('arrowdown', evt)) {
+ evt.preventDefault();
+ autocompleteMenu.dispatchEvent(
+ new CustomEvent('autocomplete-navigate', { detail: { direction: 1 } })
+ );
+ return;
+ }
+ if (isKeyHotkey('arrowup', evt)) {
+ evt.preventDefault();
+ autocompleteMenu.dispatchEvent(
new CustomEvent('autocomplete-navigate', { detail: { direction: -1 } })
);
- return;
+ return;
+ }
+
+ if ((isKeyHotkey('enter', evt) || isKeyHotkey('tab', evt)) && !isComposing(evt)) {
+ const selectedItem =
+ autocompleteMenu.querySelector('button[data-selected="true"]') ??
+ autocompleteMenu.querySelector('button');
+
+ if (selectedItem) {
+ evt.preventDefault();
+ selectedItem.click();
+ return;
+ }
+ }
}
+
if (
(isKeyHotkey('mod+enter', evt) || (!enterForNewline && isKeyHotkey('enter', evt))) &&
!isComposing(evt)
) {
evt.preventDefault();
- if (autocompleteQuery) {
- const selectedItem =
- document.querySelector(
- '[data-autocomplete-menu] button[data-selected]'
- ) ?? document.querySelector('[data-autocomplete-menu] button');
- selectedItem?.click();
- return;
- }
submit().catch((error) => {
log.error('submit failed', { roomId }, error);
});
+ return;
}
if (isKeyHotkey('escape', evt)) {
evt.preventDefault();
+ if (showAudioRecorder) {
+ audioRecorderRef.current?.cancel();
+ return;
+ }
if (autocompleteQuery) {
setAutocompleteQuery(undefined);
return;
@@ -847,7 +929,15 @@ export const RoomInput = forwardRef(
setReplyDraft(undefined);
}
},
- [submit, roomId, setReplyDraft, enterForNewline, autocompleteQuery, isComposing]
+ [
+ submit,
+ roomId,
+ setReplyDraft,
+ enterForNewline,
+ autocompleteQuery,
+ isComposing,
+ showAudioRecorder,
+ ]
);
const handleKeyUp: KeyboardEventHandler = useCallback(
@@ -1049,7 +1139,7 @@ export const RoomInput = forwardRef(
editableName="RoomInput"
editor={editor}
key={inputKey}
- placeholder="Send a message..."
+ placeholder={showAudioRecorder && mobileOrTablet() ? '' : 'Send a message...'}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
onPaste={handlePaste}
@@ -1126,7 +1216,7 @@ export const RoomInput = forwardRef(
grow="Yes"
style={{ minWidth: 0 }}
>
- {replyDraft.relation?.rel_type === RelationType.Thread && (
+ {replyDraft.relation?.rel_type === RelationType.Thread && !threadRootId && (
)}
(
>
}
before={
- pickFile('*')}
- variant="SurfaceVariant"
- size="300"
- radii="300"
- title="Upload File"
- aria-label="Upload and attach a File"
- >
-
-
+ !(showAudioRecorder && mobileOrTablet()) && (
+ pickFile('*')}
+ variant="SurfaceVariant"
+ size="300"
+ radii="300"
+ title="Upload File"
+ aria-label="Upload and attach a File"
+ >
+
+
+ )
}
after={
<>
+ {showAudioRecorder && (
+ setShowAudioRecorder(false)}
+ onRecordingComplete={(payload) => {
+ const extension = getSupportedAudioExtension(payload.audioCodec);
+ const file = new File(
+ [payload.audioBlob],
+ `sable-audio-message-${Date.now()}.${extension}`,
+ {
+ type: payload.audioCodec,
+ }
+ );
+ handleFiles([file], {
+ waveform: payload.waveform,
+ audioDuration: payload.audioLength,
+ });
+ setShowAudioRecorder(false);
+ }}
+ onAudioLengthUpdate={() => {}}
+ onWaveformUpdate={() => {}}
+ />
+ )}
+
+ {/* ── Mic button — always present; icon swaps to Stop while recording ── */}
+ {
+ if (mobileOrTablet()) return;
+ if (showAudioRecorder) {
+ audioRecorderRef.current?.stop();
+ } else {
+ setShowAudioRecorder(true);
+ }
+ }}
+ onPointerDown={() => {
+ if (!mobileOrTablet()) return;
+ if (showAudioRecorder) return;
+ micHoldStartRef.current = Date.now();
+ setShowAudioRecorder(true);
+
+ let cleanup: () => void;
+ const onUp = () => {
+ cleanup();
+ const held = Date.now() - micHoldStartRef.current;
+ if (held >= HOLD_THRESHOLD_MS) {
+ setTimeout(() => {
+ audioRecorderRef.current?.stop();
+ }, 50);
+ } else {
+ setTimeout(() => {
+ audioRecorderRef.current?.cancel();
+ }, 50);
+ }
+ };
+ cleanup = () => {
+ window.removeEventListener('pointerup', onUp);
+ window.removeEventListener('pointercancel', cleanup);
+ };
+ window.addEventListener('pointerup', onUp);
+ window.addEventListener('pointercancel', cleanup);
+ }}
+ >
+ {showAudioRecorder ? (
+
+ ) : (
+
+ )}
+
+
(
>
- setShowAudioRecorder(!showAudioRecorder)}
- >
-
-
- {showAudioRecorder && (
- {
- setShowAudioRecorder(false);
- }}
- onRecordingComplete={(audioBlob) => {
- const file = new File(
- [audioBlob],
- `sable-audio-message-${Date.now()}.${getSupportedAudioExtension(audioBlob.type)}`,
- {
- type: audioBlob.type,
- }
- );
- handleFiles([file]);
- // Close the recorder after handling the file, to give some feedback that the recording was successful
- setShowAudioRecorder(false);
- }}
- onAudioLengthUpdate={(len) => setAudioMsgLength(len)}
- onWaveformUpdate={(w) => setAudioMsgWaveform(w)}
- />
- }
- />
- )}
{(emojiBoardTab: EmojiBoardTab | undefined, setEmojiBoardTab) => (
0)` on the un-filtered array — which was
+ * truthy — and returned an empty list instead of falling back to the live
+ * timeline. The fix: filter first, then check.
+ */
+import { describe, it, expect } from 'vitest';
+import { RelationType } from '$types/matrix-sdk';
+import { getThreadReplyEvents } from './ThreadDrawer';
+
+// ── Minimal MatrixEvent factory ───────────────────────────────────────────────
+
+type EventInit = {
+ id: string;
+ threadRootId?: string;
+ /** When set, the event is treated as a reaction/annotation */
+ relType?: string;
+};
+
+function makeEvent({ id, threadRootId, relType }: EventInit) {
+ return {
+ getId: () => id,
+ threadRootId,
+ getRelation: () => (relType ? { rel_type: relType } : null),
+ getContent: () => ({}),
+ };
+}
+
+// ── Minimal Room factory ──────────────────────────────────────────────────────
+
+type RoomInit = {
+ thread?: { events: ReturnType[] } | null;
+ liveEvents?: ReturnType[];
+};
+
+function makeRoom({ thread = null, liveEvents = [] }: RoomInit) {
+ return {
+ getThread: () => thread,
+ getUnfilteredTimelineSet: () => ({
+ getLiveTimeline: () => ({
+ getEvents: () => liveEvents,
+ }),
+ }),
+ };
+}
+
+// ── Tests ─────────────────────────────────────────────────────────────────────
+
+const ROOT_ID = '$root-event-id';
+const REPLY_ID = '$reply-event-id';
+const REACTION_ID = '$reaction-event-id';
+
+describe('getThreadReplyEvents', () => {
+ it('returns thread events minus the root when the Thread object has replies', () => {
+ const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID });
+ const replyEvent = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
+
+ const room = makeRoom({
+ thread: { events: [rootEvent, replyEvent] as any },
+ liveEvents: [],
+ });
+
+ const result = getThreadReplyEvents(room as any, ROOT_ID);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].getId()).toBe(REPLY_ID);
+ });
+
+ it('excludes reactions from thread events', () => {
+ const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID });
+ const replyEvent = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
+ const reactionEvent = makeEvent({
+ id: REACTION_ID,
+ threadRootId: ROOT_ID,
+ relType: RelationType.Annotation,
+ });
+
+ const room = makeRoom({
+ thread: { events: [rootEvent, replyEvent, reactionEvent] as any },
+ liveEvents: [],
+ });
+
+ const result = getThreadReplyEvents(room as any, ROOT_ID);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].getId()).toBe(REPLY_ID);
+ });
+
+ // ── Classic-sync empty-thread regression ──────────────────────────────────
+
+ it('falls back to the live timeline when thread.events contains only the root (classic-sync case)', () => {
+ // classic sync: thread created with no initialEvents → events = [rootEvent]
+ const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID });
+ const liveReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
+
+ const room = makeRoom({
+ thread: { events: [rootEvent] as any },
+ liveEvents: [liveReply as any],
+ });
+
+ const result = getThreadReplyEvents(room as any, ROOT_ID);
+
+ // Without the fix: `fromThread.length > 0` was truthy → returned filtered
+ // empty array. With the fix: filtered array is empty → falls back to live.
+ expect(result).toHaveLength(1);
+ expect(result[0].getId()).toBe(REPLY_ID);
+ });
+
+ it('falls back to the live timeline when there is no Thread object at all', () => {
+ const liveReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
+
+ const room = makeRoom({
+ thread: null,
+ liveEvents: [liveReply as any],
+ });
+
+ const result = getThreadReplyEvents(room as any, ROOT_ID);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].getId()).toBe(REPLY_ID);
+ });
+
+ it('excludes events from the live timeline that belong to a different thread', () => {
+ const otherReply = makeEvent({ id: '$other-reply', threadRootId: '$other-root' });
+ const ourReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
+
+ const room = makeRoom({
+ thread: null,
+ liveEvents: [otherReply as any, ourReply as any],
+ });
+
+ const result = getThreadReplyEvents(room as any, ROOT_ID);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].getId()).toBe(REPLY_ID);
+ });
+
+ it('returns an empty array when neither the thread nor the live timeline has replies', () => {
+ const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID });
+
+ const room = makeRoom({
+ thread: { events: [rootEvent] as any },
+ liveEvents: [],
+ });
+
+ const result = getThreadReplyEvents(room as any, ROOT_ID);
+
+ expect(result).toHaveLength(0);
+ });
+});
diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx
index 00957bc3..53ab2f37 100644
--- a/src/app/features/room/ThreadDrawer.tsx
+++ b/src/app/features/room/ThreadDrawer.tsx
@@ -54,6 +54,36 @@ import { RoomInput } from './RoomInput';
import { RoomViewFollowing, RoomViewFollowingPlaceholder } from './RoomViewFollowing';
import * as css from './ThreadDrawer.css';
+/**
+ * Resolve the list of reply events to show in the thread drawer.
+ *
+ * Prefers events from the SDK Thread object (authoritative, full history) but
+ * falls back to scanning the main room timeline when the Thread object was
+ * created without `initialEvents` (as happens with classic sync). In that
+ * case `thread.events` contains only the root event, so filtering it yields an
+ * empty array — we must fall back rather than showing nothing.
+ *
+ * Exported for unit testing.
+ */
+export function getThreadReplyEvents(room: Room, threadRootId: string): MatrixEvent[] {
+ const thread = room.getThread(threadRootId);
+ const fromThread = thread?.events ?? [];
+ const filteredFromThread = fromThread.filter(
+ (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
+ );
+ if (filteredFromThread.length > 0) {
+ return filteredFromThread;
+ }
+ return room
+ .getUnfilteredTimelineSet()
+ .getLiveTimeline()
+ .getEvents()
+ .filter(
+ (ev) =>
+ ev.threadRootId === threadRootId && ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
+ );
+}
+
type ForwardedMessageProps = {
isForwarded: boolean;
originalTimestamp: number;
@@ -398,6 +428,33 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
const rootEvent = room.findEventById(threadRootId);
+ // When the drawer is opened with classic sync, room.createThread() may have
+ // been called with empty initialEvents so thread.events only has the root.
+ // Backfill events from the main room timeline into the Thread object so the
+ // authoritative source is populated for subsequent renders and receipts.
+ useEffect(() => {
+ const thread = room.getThread(threadRootId);
+ if (!thread) return;
+ const hasRepliesInThread = thread.events.some(
+ (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
+ );
+ if (hasRepliesInThread) return; // already populated, nothing to do
+
+ const liveEvents = room
+ .getUnfilteredTimelineSet()
+ .getLiveTimeline()
+ .getEvents()
+ .filter(
+ (ev) =>
+ ev.threadRootId === threadRootId &&
+ ev.getId() !== threadRootId &&
+ !reactionOrEditEvent(ev)
+ );
+ if (liveEvents.length > 0) {
+ thread.addEvents(liveEvents, false);
+ }
+ }, [room, threadRootId]);
+
// Re-render when new thread events arrive (including reactions via ThreadEvent.Update).
useEffect(() => {
const isEventInThread = (mEvent: MatrixEvent): boolean => {
@@ -481,26 +538,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
markThreadAsRead();
}, [mx, room, threadRootId, forceUpdate]);
- // Use the Thread object if available (authoritative source with full history).
- // Fall back to scanning the live room timeline for local echoes and the
- // window before the Thread object is registered by the SDK.
- const replyEvents: MatrixEvent[] = (() => {
- const thread = room.getThread(threadRootId);
- const fromThread = thread?.events ?? [];
- if (fromThread.length > 0) {
- return fromThread.filter((ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev));
- }
- return room
- .getUnfilteredTimelineSet()
- .getLiveTimeline()
- .getEvents()
- .filter(
- (ev) =>
- ev.threadRootId === threadRootId &&
- ev.getId() !== threadRootId &&
- !reactionOrEditEvent(ev)
- );
- })();
+ const replyEvents = getThreadReplyEvents(room, threadRootId);
replyEventsRef.current = replyEvents;
@@ -722,7 +760,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
variant="Background"
visibility="Hover"
direction="Vertical"
- hideTrack={false}
+ hideTrack
style={{
maxHeight: '200px',
height: 'fit-content',
@@ -733,7 +771,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
className={css.messageList}
direction="Column"
style={{
- padding: `${config.space.S400} 0 ${config.space.S200} 0`,
+ padding: `${config.space.S200} 0 ${config.space.S100} 0`,
}}
>
diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx
index 9dd200ed..0ee9f339 100644
--- a/src/app/features/room/message/Message.tsx
+++ b/src/app/features/room/message/Message.tsx
@@ -79,7 +79,7 @@ import { MessageSourceCodeItem } from '$components/message/modals/MessageSource'
import { MessageForwardItem } from '$components/message/modals/MessageForward';
import { MessageDeleteItem } from '$components/message/modals/MessageDelete';
import { MessageReportItem } from '$components/message/modals/MessageReport';
-import { filterPronounsByLanguage } from '$utils/pronouns';
+import { filterPronounsByLanguage, getParsedPronouns } from '$utils/pronouns';
import { useMentionClickHandler } from '$hooks/useMentionClickHandler';
import {
addStickerToDefaultPack,
@@ -381,6 +381,8 @@ function MessageInternal(
const profile = useUserProfile(senderId, room);
const { color: usernameColor, font: usernameFont } = useSableCosmetics(senderId, room);
+ const [highlightMentions] = useSetting(settingsAtom, 'highlightMentions');
+
// Avatars
// Prefer the room-scoped member avatar (m.room.member) over the global profile
// avatar so per-room avatar overrides are respected in the timeline.
@@ -390,11 +392,6 @@ function MessageInternal(
return mxc ? mxcUrlToHttp(mx, mxc, useAuthentication, 48, 48, 'crop') : undefined;
}, [pmp, collapse, profile.avatarUrl, senderId, mx, room, useAuthentication]);
- const displayName = useMemo(
- () => pmp?.displayname || senderDisplayName,
- [pmp, senderDisplayName]
- );
-
const cachedAvatar = useBlobCache(avatarUrl ?? undefined);
// UI State
@@ -423,8 +420,32 @@ function MessageInternal(
const [mobileOptionsOpen, setMobileOptionsOpen] = useState(false);
const optionsRef = useRef(null);
+
const [showPronouns] = useSetting(settingsAtom, 'showPronouns');
+ const [parsePronouns] = useSetting(settingsAtom, 'parsePronouns');
+
const [useRightBubbles] = useSetting(settingsAtom, 'useRightBubbles');
+ const { cleanedDisplayName, inlinePronoun } = useMemo(() => {
+ const rawName = pmp?.displayname || senderDisplayName || '';
+ return getParsedPronouns(rawName, parsePronouns);
+ }, [pmp, senderDisplayName, parsePronouns]);
+
+ const mergedPronouns = useMemo(() => {
+ const existing = profile.pronouns ? [...profile.pronouns] : [];
+
+ if (inlinePronoun) {
+ const isDupe = existing.some((p) => p.summary?.toLowerCase() === inlinePronoun);
+
+ if (!isDupe) {
+ existing.push({
+ summary: inlinePronoun,
+ language: 'en',
+ });
+ }
+ }
+
+ return existing;
+ }, [profile.pronouns, inlinePronoun]);
useEffect(() => {
if (!mobileOptionsOpen) return undefined;
@@ -457,11 +478,11 @@ function MessageInternal(
onClick={onUsernameClick}
>
- {displayName}
+ {cleanedDisplayName}
{showPronouns && (
-
+
)}
{tagIconSrc && }