diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index b9e6408b..eddc13e2 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -1,6 +1,7 @@ -import { Box, Icon, Icons, Text, as, color, toRem } from 'folds'; +import { Box, Chip, Icon, Icons, Text, as, color, toRem } from 'folds'; import { EventTimelineSet, Room } from '$types/matrix-sdk'; import { MouseEventHandler, ReactNode, useCallback, useMemo } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; import classNames from 'classnames'; import parse from 'html-react-parser'; import { useAtomValue } from 'jotai'; @@ -14,9 +15,16 @@ import { } from '$plugins/react-custom-html-parser'; import { useRoomEvent } from '$hooks/useRoomEvent'; import { useSableCosmetics } from '$hooks/useSableCosmetics'; +import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; +import { useIgnoredUsers } from '$hooks/useIgnoredUsers'; import { nicknamesAtom } from '$state/nicknames'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { MessageBadEncryptedContent, MessageDeletedContent, MessageFailedContent } from './content'; +import { + MessageBadEncryptedContent, + MessageBlockedContent, + MessageDeletedContent, + MessageFailedContent, +} from './content'; import * as css from './Reply.css'; import { LinePlaceholder } from './placeholder'; @@ -74,14 +82,19 @@ export const Reply = as<'div', ReplyProps>( [timelineSet, replyEventId] ); const replyEvent = useRoomEvent(room, replyEventId, getFromLocalTimeline); + const queryClient = useQueryClient(); const mx = useMatrixClient(); const { body, formatted_body: formattedBody, format } = replyEvent?.getContent() ?? {}; const sender = replyEvent?.getSender(); + const ignoredUsers = useIgnoredUsers(); + const isBlockedSender = !!sender && ignoredUsers.includes(sender); + const { color: usernameColor, font: usernameFont } = useSableCosmetics(sender ?? '', room); const nicknames = useAtomValue(nicknamesAtom); + const useAuthentication = useMediaAuthentication(); const fallbackBody = replyEvent?.isRedacted() ? ( @@ -90,6 +103,18 @@ export const Reply = as<'div', ReplyProps>( ); const badEncryption = replyEvent?.getContent().msgtype === 'm.bad.encrypted'; + + // An encrypted event that hasn't been decrypted yet (keys pending) has an + // empty result from getClearContent(). Treat it as still-loading rather + // than a failure so the UI shows a placeholder instead of MessageFailedContent + // until the MatrixEventEvent.Decrypted callback fires. + const isPendingDecrypt = + replyEvent !== undefined && + replyEvent !== null && + replyEvent.isEncrypted() && + !replyEvent.isDecryptionFailure() && + !replyEvent.getClearContent(); + let bodyJSX: ReactNode = fallbackBody; if (format === 'org.matrix.custom.html' && formattedBody) { @@ -100,6 +125,7 @@ export const Reply = as<'div', ReplyProps>( .replace(/(?:\r\n|\r|\n)/g, ' '); const parserOpts = getReactCustomHtmlParser(mx, room.roomId, { linkifyOpts: LINKIFY_OPTS, + useAuthentication, nicknames, }); bodyJSX = parse(strippedHtml, parserOpts) as JSX.Element; @@ -124,11 +150,15 @@ export const Reply = as<'div', ReplyProps>( ) } data-event-id={replyEventId} - onClick={onClick} + onClick={replyEvent !== null && !isBlockedSender ? onClick : undefined} > - {replyEvent !== undefined ? ( + {replyEvent !== undefined && !isPendingDecrypt ? ( - {badEncryption ? : bodyJSX} + {(() => { + if (isBlockedSender) return ; + if (badEncryption) return ; + return bodyJSX; + })()} ) : ( ( /> )} + {replyEvent === null && ( + } + onClick={(evt) => { + evt.stopPropagation(); + queryClient.invalidateQueries({ queryKey: [room.roomId, replyEventId] }); + }} + /> + )} ); } diff --git a/src/app/components/message/content/FallbackContent.tsx b/src/app/components/message/content/FallbackContent.tsx index 270504f0..8156a5d0 100644 --- a/src/app/components/message/content/FallbackContent.tsx +++ b/src/app/components/message/content/FallbackContent.tsx @@ -58,6 +58,13 @@ export const MessageEmptyContent = as<'div', { children?: never }>(({ ...props } )); +export const MessageBlockedContent = as<'div', { children?: never }>(({ ...props }, ref) => ( + + + Message from a blocked user + +)); + export const MessageEditedContent = as<'span', { children?: never }>(({ ...props }, ref) => ( {' (edited)'} diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index cc1d0eca..134c38ec 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -298,25 +298,30 @@ export const RoomInput = forwardRef( format: replyFormat, } = replyEvent?.getContent() ?? {}; + // Prefer the live event content; fall back to what was snapshotted in the + // draft when the user hit Reply (the event may not be in SDK state if it + // was redacted or evicted, but the draft always carries the original body). + const htmlBody = + replyFormat === 'org.matrix.custom.html' ? replyFormattedBody : replyDraft?.formattedBody; + const plainBody = replyBody ?? replyDraft?.body; + let replyBodyJSX: ReactNode = replyDraft ? trimReplyFromBody(replyDraft.body) : null; - if (replyFormat === 'org.matrix.custom.html' && replyFormattedBody) { - const strippedHtml = trimReplyFromFormattedBody(replyFormattedBody) + if (htmlBody) { + const strippedHtml = trimReplyFromFormattedBody(htmlBody) .replace(//gi, ' ') .replace(/<\/p>\s*]*>/gi, ' ') .replace(/<\/?p[^>]*>/gi, '') .replace(/(?:\r\n|\r|\n)/g, ' '); const parserOpts = getReactCustomHtmlParser(mx, roomId, { linkifyOpts: LINKIFY_OPTS, + useAuthentication, nicknames, }); replyBodyJSX = parse(strippedHtml, parserOpts); - } else if (replyBody) { - const strippedBody = trimReplyFromBody(replyBody).replace(/(?:\r\n|\r|\n)/g, ' '); - replyBodyJSX = scaleSystemEmoji(trimReplyFromBody(strippedBody)); - } else if (replyDraft) { - const strippedBody = trimReplyFromBody(replyDraft.body).replace(/(?:\r\n|\r|\n)/g, ' '); - replyBodyJSX = scaleSystemEmoji(trimReplyFromBody(strippedBody)); + } else if (plainBody) { + const strippedBody = trimReplyFromBody(plainBody).replace(/(?:\r\n|\r|\n)/g, ' '); + replyBodyJSX = scaleSystemEmoji(strippedBody); } useEffect(() => { diff --git a/src/app/hooks/useRoomEvent.ts b/src/app/hooks/useRoomEvent.ts index d9b36352..70335366 100644 --- a/src/app/hooks/useRoomEvent.ts +++ b/src/app/hooks/useRoomEvent.ts @@ -1,5 +1,12 @@ -import { IEvent, MatrixEvent, Room, CryptoBackend } from '$types/matrix-sdk'; -import { useCallback, useMemo } from 'react'; +import { + IEvent, + MatrixEvent, + MatrixEventEvent, + Room, + RoomEvent, + CryptoBackend, +} from '$types/matrix-sdk'; +import { useCallback, useEffect, useMemo, useState } from 'react'; import to from 'await-to-js'; import { useQuery } from '@tanstack/react-query'; import { useMatrixClient } from './useMatrixClient'; @@ -8,13 +15,23 @@ const useFetchEvent = (room: Room, eventId: string) => { const mx = useMatrixClient(); const fetchEventCallback = useCallback(async () => { + // Use fetchRoomEvent rather than getEventTimeline. + // + // getEventTimeline calls /context, which adds a new EventTimeline to the + // room's UnfilteredTimelineSet. The SDK then emits RoomEvent.TimelineRefresh, + // which RoomTimeline.tsx catches and scrolls the visible window back to the + // live end — causing an unwanted jump-to-bottom on every reply reload. + // + // fetchRoomEvent fetches the raw event without touching the timeline state, + // so there is no side-effect on the visible scroll position. The trade-off + // is that the returned MatrixEvent is standalone (not tracked in SDK state), + // so we handle edits and decryption manually below. const evt = await mx.fetchRoomEvent(room.roomId, eventId); const mEvent = new MatrixEvent(evt); - if (evt.unsigned?.['m.relations'] && evt.unsigned?.['m.relations']['m.replace']) { - const replaceEvt = evt.unsigned?.['m.relations']['m.replace'] as IEvent; - const replaceEvent = new MatrixEvent(replaceEvt); - mEvent.makeReplaced(replaceEvent); + if (evt.unsigned?.['m.relations']?.['m.replace']) { + const replaceEvt = evt.unsigned['m.relations']['m.replace'] as IEvent; + mEvent.makeReplaced(new MatrixEvent(replaceEvt)); } if (mEvent.isEncrypted() && mx.getCrypto()) { @@ -38,21 +55,109 @@ export const useRoomEvent = ( eventId: string, getLocally?: () => MatrixEvent | undefined ) => { + const mx = useMatrixClient(); + + // Shared re-render trigger used by both decryption listeners below. + const [, forceUpdate] = useState(0); + + // `tick` lets useMemo re-run when the reply-target event arrives via sync. + // The Room reference is stable (SDK mutates it in-place), so without this + // the memo would never recompute even when room.findEventById(eventId) would + // now return a result. + const [tick, setTick] = useState(0); + const event = useMemo(() => { - if (getLocally) return getLocally(); - return room.findEventById(eventId); - }, [room, eventId, getLocally]); + // `tick` is in the deps array below — useMemo reruns whenever a timeline + // event for our eventId arrives (see RoomEvent.Timeline below). + // Check the caller's local window first (e.g. the rendered timeline set), + // then fall back to the SDK's full room state. Events that are present in + // room history but outside the currently visible window are found this way + // without a network round-trip. + const local = getLocally?.(); + return local ?? room.findEventById(eventId); + // eslint-disable-next-line react-hooks/exhaustive-deps -- tick intentionally forces re-eval on new timeline events + }, [room, eventId, getLocally, tick]); + + // Re-evaluate the local lookup the moment the target event arrives in the + // room's live timeline. We only subscribe while the event is missing to + // keep overhead to zero once it has been resolved. Checking the event ID + // in the handler avoids spurious setTick calls for unrelated messages. + useEffect(() => { + if (event !== undefined) return undefined; + const onTimeline = (incoming: MatrixEvent) => { + if (incoming.getId() === eventId) setTick((n) => n + 1); + }; + room.on(RoomEvent.Timeline, onTimeline); + return () => { + room.off(RoomEvent.Timeline, onTimeline); + }; + }, [room, event, eventId]); const fetchEvent = useFetchEvent(room, eventId); const { data, error } = useQuery({ + // Only hit the network when neither the visible window nor the SDK's room + // state has the event. Note: fetchRoomEvent does NOT add its result to SDK + // state, so `event` stays undefined after a successful fetch and this flag + // remains true on subsequent renders — but staleTime: Infinity prevents + // any redundant re-fetches. enabled: event === undefined, queryKey: [room.roomId, eventId], queryFn: fetchEvent, staleTime: Infinity, - gcTime: 60 * 60 * 1000, // 1hour + gcTime: 60 * 60 * 1000, // 1 hour + retry: 3, + // Progressive back-off: 1 s → 2 s → 4 s (capped at 30 s). + retryDelay: (attempt) => Math.min(1_000 * 2 ** attempt, 30_000), }); + // ── E2EE retry for standalone fetched events ────────────────────────────── + // fetchRoomEvent returns a MatrixEvent that is NOT tracked in SDK state, so + // the SDK's normal Megolm key-delivery pipeline never fires + // MatrixEventEvent.Decrypted on it. Instead, we piggyback on the Decrypted + // events of SDK-tracked live-timeline events as a proxy signal for + // "new Megolm session keys have arrived" and immediately retry + // attemptDecryption on our standalone event. + useEffect(() => { + if (!data?.isEncrypted() || !data.isDecryptionFailure()) return undefined; + const crypto = mx.getCrypto(); + if (!crypto) return undefined; + + const retryDecrypt = async () => { + const [err] = await to(data.attemptDecryption(crypto as CryptoBackend)); + if (!err && !data.isDecryptionFailure()) forceUpdate((n) => n + 1); + }; + + // Use the last 50 live-timeline events that are still encrypted as + // sentinels. When any of them fires Decrypted it means new keys arrived. + const sentinels = room + .getLiveTimeline() + .getEvents() + .slice(-50) + .filter((e) => e.isEncrypted()); + + const onKeyArrived = () => { + retryDecrypt(); + }; + sentinels.forEach((e) => e.on(MatrixEventEvent.Decrypted, onKeyArrived)); + return () => sentinels.forEach((e) => e.off(MatrixEventEvent.Decrypted, onKeyArrived)); + }, [data, room, mx]); + + // ── Decryption listener for SDK-tracked events ──────────────────────────── + // When an event IS in the SDK state (found locally via `event`), the SDK's + // Megolm pipeline fires MatrixEventEvent.Decrypted on it automatically when + // keys later arrive. Subscribe so the component re-renders without any + // manual retry. + const resolvedEvent = event ?? data ?? undefined; + useEffect(() => { + if (!resolvedEvent?.isEncrypted()) return undefined; + const onDecrypted = () => forceUpdate((n) => n + 1); + resolvedEvent.on(MatrixEventEvent.Decrypted, onDecrypted); + return () => { + resolvedEvent.off(MatrixEventEvent.Decrypted, onDecrypted); + }; + }, [resolvedEvent]); + if (event) return event; if (data) return data; if (error) return null;