From 14603c1c513543ef35747a36ea933744b3f8f63c Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 27 Aug 2026 15:20:56 -0500 Subject: [PATCH 1/2] redact events optimistically and reduce timeline flicker maybe --- .../message/modals/MessageDelete.tsx | 9 +-- src/app/features/room/RoomTimeline.test.tsx | 9 +-- src/app/features/room/RoomTimeline.tsx | 25 +++----- .../hooks/timeline/useProcessedTimeline.ts | 5 ++ .../hooks/timeline/useTimelineSync.test.tsx | 47 ++++++++------- src/app/hooks/timeline/useTimelineSync.ts | 57 +++++++++---------- src/app/utils/matrix.test.ts | 51 +++++++++++++++-- src/app/utils/matrix.ts | 31 +++++++++- 8 files changed, 150 insertions(+), 84 deletions(-) diff --git a/src/app/components/message/modals/MessageDelete.tsx b/src/app/components/message/modals/MessageDelete.tsx index cda942786..fc665b204 100644 --- a/src/app/components/message/modals/MessageDelete.tsx +++ b/src/app/components/message/modals/MessageDelete.tsx @@ -21,6 +21,7 @@ import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { modalAtom, ModalType } from '$state/modal'; import * as css from '$features/room/message/styles.css'; import { createDebugLogger } from '$utils/debugLogger'; +import { optimisticallyRedactEvent } from '$utils/matrix'; import * as Sentry from '@sentry/react'; const debugLog = createDebugLogger('MessageDelete'); @@ -72,9 +73,9 @@ export function MessageDeleteInternal({ room, mEvent, onClose }: MessageDeleteIn const [deleteState, deleteMessage] = useAsyncCallback( useCallback( - (eventId: string, reason?: string) => - mx.redactEvent(room.roomId, eventId, undefined, reason ? { reason } : undefined), - [mx, room] + (reason?: string) => + optimisticallyRedactEvent(mx, room, mEvent, reason ? { reason } : undefined), + [mx, room, mEvent] ) ); @@ -106,7 +107,7 @@ export function MessageDeleteInternal({ room, mEvent, onClose }: MessageDeleteIn debugLog.info('ui', 'Deleting message', { eventId, hasReason: !!reason }); Sentry.metrics.count('sable.message.delete.attempt', 1); - deleteMessage(eventId, reason); + deleteMessage(reason); }; return ( diff --git a/src/app/features/room/RoomTimeline.test.tsx b/src/app/features/room/RoomTimeline.test.tsx index 087a64de2..bb442d05a 100644 --- a/src/app/features/room/RoomTimeline.test.tsx +++ b/src/app/features/room/RoomTimeline.test.tsx @@ -46,6 +46,7 @@ const { }, timelineSync: { eventsLength: 1, + timelineVersion: 0, timeline: { linkedTimelines: [] }, liveTimelineLinked: true, backwardStatus: 'idle', @@ -940,13 +941,13 @@ describe('MemoizedTimelineItem', () => { }); describe('jump reveal and focus-regain read receipts', () => { - it('keeps the timeline hidden while a jump is still pending', () => { + it('keeps rendering the timeline while a jump is still pending', () => { timelineSync.jumpFailed = false; const { getByText } = render( ); - expect(getByText('canRedact:false hideReads:false')).not.toBeVisible(); + expect(getByText('canRedact:false hideReads:false')).toBeVisible(); }); it('restarts a route jump when the Room instance is replaced with the same id', () => { @@ -963,12 +964,12 @@ describe('jump reveal and focus-regain read receipts', () => { expect(timelineSync.loadEventTimeline).toHaveBeenCalledTimes(2); }); - it('reveals the timeline when the jump fails instead of leaving a blank room', () => { + it('keeps the timeline visible when the jump fails', () => { timelineSync.jumpFailed = false; const { getByText, rerender } = render( ); - expect(getByText('canRedact:false hideReads:false')).not.toBeVisible(); + expect(getByText('canRedact:false hideReads:false')).toBeVisible(); timelineSync.jumpFailed = true; act(() => { diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 28faa6c91..3310d54cf 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -773,11 +773,9 @@ export function RoomTimeline({ ); useLayoutEffect(() => { - if (!isReady) return; if (timelineSync.eventsLength > 0) return; - setIsReady(false); hasInitialScrolledRef.current = false; - }, [isReady, timelineSync.eventsLength]); + }, [timelineSync.eventsLength]); const recalcTopSpacer = useCallback(() => { const v = vListRef.current; @@ -886,7 +884,6 @@ export function RoomTimeline({ useEffect(() => { if (!eventId) return; - if (!timelineSyncRef.current.jumpFailed) setIsReady(false); jumpToEvent(eventId); }, [eventId, room, jumpToEvent]); @@ -1324,15 +1321,15 @@ export function RoomTimeline({ if (showLoadingPlaceholders) vListItemCount = 3; // One row so the error and its Retry have somewhere to render. else if (showEmptyPaginationError) vListItemCount = 1; - const vListIndices = useMemo(() => { - // Keep the cache-busting timeline identity explicit for exhaustive-deps. - void timelineSync.timeline; - return Array.from({ length: vListItemCount }, (_, i) => i); - }, [vListItemCount, timelineSync.timeline]); + const vListIndices = useMemo( + () => Array.from({ length: vListItemCount }, (_, i) => i), + [vListItemCount] + ); const processedEvents = useProcessedTimeline({ items: vListIndices, linkedTimelines: timelineSync.timeline.linkedTimelines, + timelineVersion: timelineSync.timelineVersion, ignoredUsersSet, hiddenEvents, mxUserId: mx.getUserId(), @@ -1471,16 +1468,12 @@ export function RoomTimeline({ width: '100%', overflow: 'hidden', position: 'relative', - opacity: - !hideTimelineForRoomState && - (isReady || showLoadingPlaceholders || showEmptyPaginationError) - ? 1 - : 0, + opacity: hideTimelineForRoomState ? 0 : 1, }} > - key={`${room.roomId}:${timelineSync.liveTimelineLinked ? 'live' : (timelineSync.focusItem?.eventId ?? scrollAnchorRef.current)}`} + key={room.roomId} ref={vListRef} data={processedEvents} shift={shouldShift} @@ -1552,7 +1545,7 @@ export function RoomTimeline({ )} - {(!atBottomState || !timelineSync.liveTimelineLinked) && isReady && ( + {(!atBottomState || !timelineSync.liveTimelineLinked) && ( (undefined); return useMemo(() => { + void timelineVersion; const timelineEvents = flattenTimelineEvents(linkedTimelines); const processingOptions: TimelineProcessingOptions = { ignoredUsersSet, @@ -814,5 +818,6 @@ export function useProcessedTimeline({ isReadOnly, hideMemberInReadOnly, skipThreadFilter, + timelineVersion, ]); } diff --git a/src/app/hooks/timeline/useTimelineSync.test.tsx b/src/app/hooks/timeline/useTimelineSync.test.tsx index 900ab9bc9..00def7e86 100644 --- a/src/app/hooks/timeline/useTimelineSync.test.tsx +++ b/src/app/hooks/timeline/useTimelineSync.test.tsx @@ -532,7 +532,7 @@ describe('useTimelineSync', () => { await act(async () => { emitLiveTimelineEvent(room, timeline, events, '@bob:test'); - await Promise.resolve(); + await flushRaf(); }); expect(scrollToBottom).toHaveBeenCalledWith('smooth'); @@ -560,7 +560,7 @@ describe('useTimelineSync', () => { await act(async () => { emitLiveTimelineEvent(room, timeline, events, '@alice:test'); - await Promise.resolve(); + await flushRaf(); }); expect(scrollToBottom).toHaveBeenCalledWith('instant'); @@ -591,7 +591,7 @@ describe('useTimelineSync', () => { await act(async () => { emitLiveTimelineEvent(room, timeline, events, '@bob:test'); - await Promise.resolve(); + await flushRaf(); }); expect(setUnreadInfo).toHaveBeenCalledWith(unread); @@ -1273,7 +1273,7 @@ describe('live-arrive edge cases', () => { it('renders a stale non-live event appended to the live timeline', async () => { const { room, timeline, events } = createRoom(); const { result } = renderSyncHook(room); - const before = result.current.timeline; + const before = result.current.timelineVersion; vi.mocked(isWindowFocused).mockReturnValue(true); await act(async () => { await flushRaf(); @@ -1293,7 +1293,7 @@ describe('live-arrive edge cases', () => { await flushRaf(); }); - expect(result.current.timeline).not.toBe(before); + expect(result.current.timelineVersion).toBeGreaterThan(before); expect(markAsRead).not.toHaveBeenCalled(); vi.mocked(isWindowFocused).mockReturnValue(false); }); @@ -1301,7 +1301,7 @@ describe('live-arrive edge cases', () => { it('renders a removal', async () => { const { room, timeline, events } = createRoom(); const { result } = renderSyncHook(room); - const before = result.current.timeline; + const before = result.current.timelineVersion; await act(async () => { events.pop(); @@ -1309,10 +1309,10 @@ describe('live-arrive edge cases', () => { liveEvent: false, timeline, }); - await Promise.resolve(); + await flushRaf(); }); - expect(result.current.timeline).not.toBe(before); + expect(result.current.timelineVersion).toBeGreaterThan(before); }); it('ignores events emitted for a thread timeline set', async () => { @@ -1320,7 +1320,7 @@ describe('live-arrive edge cases', () => { const otherSet = new EventEmitter() as FakeTimelineSet; const threadTimeline = { ...createTimeline(events), getTimelineSet: () => otherSet }; const { result, scrollToBottom } = renderSyncHook(room); - const before = result.current.timeline; + const before = result.current.timelineVersion; await act(async () => { room.emit(RoomEvent.Timeline, makeLiveEvent(room.roomId, Date.now()), room, false, false, { @@ -1330,14 +1330,14 @@ describe('live-arrive edge cases', () => { await Promise.resolve(); }); - expect(result.current.timeline).toBe(before); + expect(result.current.timelineVersion).toBe(before); expect(scrollToBottom).not.toHaveBeenCalled(); }); it('does not treat a threaded reply as an arrival when it lands on the main set', async () => { const { room, timeline, events } = createRoom(); const { result } = renderSyncHook(room); - const before = result.current.timeline; + const before = result.current.timelineVersion; vi.mocked(isWindowFocused).mockReturnValue(true); await act(async () => { await flushRaf(); @@ -1363,7 +1363,7 @@ describe('live-arrive edge cases', () => { await flushRaf(); }); - expect(result.current.timeline).not.toBe(before); + expect(result.current.timelineVersion).toBeGreaterThan(before); expect(markAsRead).not.toHaveBeenCalled(); vi.mocked(isWindowFocused).mockReturnValue(false); }); @@ -1378,7 +1378,7 @@ describe('live-arrive edge cases', () => { liveEvent: true, timeline, }); - await Promise.resolve(); + await flushRaf(); }); expect(scrollToBottom).toHaveBeenCalledWith('instant'); @@ -1461,7 +1461,7 @@ describe('live-arrive edge cases', () => { liveEvent: false, timeline: freshTimeline, }); - await Promise.resolve(); + await flushRaf(); }); expect(scrollToBottom).toHaveBeenCalledWith('instant'); }); @@ -1504,7 +1504,7 @@ describe('live-arrive edge cases', () => { it('re-renders when an event finishes decrypting', async () => { const { room } = createRoom(); const { result } = renderSyncHook(room); - const before = result.current.timeline; + const before = result.current.timelineVersion; await act(async () => { mxEmitter.emit(MatrixEventEvent.Decrypted, { getRoomId: () => room.roomId }); @@ -1513,13 +1513,13 @@ describe('live-arrive edge cases', () => { }); }); - expect(result.current.timeline).not.toBe(before); + expect(result.current.timelineVersion).toBeGreaterThan(before); }); it('ignores decryption of an event in another room', async () => { const { room } = createRoom(); const { result } = renderSyncHook(room); - const before = result.current.timeline; + const before = result.current.timelineVersion; await act(async () => { mxEmitter.emit(MatrixEventEvent.Decrypted, { getRoomId: () => '!other:test' }); @@ -1528,20 +1528,20 @@ describe('live-arrive edge cases', () => { }); }); - expect(result.current.timeline).toBe(before); + expect(result.current.timelineVersion).toBe(before); }); it('re-renders when a late local echo updates (slow send acknowledgement)', async () => { const { room } = createRoom(); const { result } = renderSyncHook(room); - const before = result.current.timeline; + const before = result.current.timelineVersion; await act(async () => { room.emit(RoomEvent.LocalEchoUpdated, {}, room); - await Promise.resolve(); + await flushRaf(); }); - expect(result.current.timeline).not.toBe(before); + expect(result.current.timelineVersion).toBeGreaterThan(before); }); }); @@ -2409,9 +2409,8 @@ const flushFrame = async () => { }; describe('decryption refresh coalescing', () => { - // Counts distinct timeline objects, not renders: unrelated re-renders reuse the object. const renderTrackingHook = (room: FakeRoom) => { - const seen: unknown[] = []; + const seen: number[] = []; renderHook(() => { const sync = useTimelineSync({ room: room as Room, @@ -2425,7 +2424,7 @@ describe('decryption refresh coalescing', () => { readUptoEventIdRef: { current: undefined }, isInactivePanelRef: { current: false }, }); - if (!seen.includes(sync.timeline)) seen.push(sync.timeline); + if (!seen.includes(sync.timelineVersion)) seen.push(sync.timelineVersion); return sync; }); return seen; diff --git a/src/app/hooks/timeline/useTimelineSync.ts b/src/app/hooks/timeline/useTimelineSync.ts index 35cf886e5..2a4a98a8c 100644 --- a/src/app/hooks/timeline/useTimelineSync.ts +++ b/src/app/hooks/timeline/useTimelineSync.ts @@ -443,6 +443,8 @@ export function useTimelineSync({ const [focusItem, setFocusItem] = useState(); const [jumpFailedFor, setJumpFailedFor] = useState(); const jumpFailed = jumpFailedFor !== undefined && jumpFailedFor === eventId; + const [timelineVersion, setTimelineVersion] = useState(0); + const bumpTimeline = useCallback(() => setTimelineVersion((version) => version + 1), []); const resetAutoScrollPendingRef = useRef(false); const pendingAutoScrollBehaviorRef = useRef<'instant' | 'smooth' | undefined>(undefined); @@ -613,6 +615,22 @@ export function useTimelineSync({ [room] ); + const refreshFrameRef = useRef(undefined); + const scheduleTimelineRefresh = useCallback(() => { + if (refreshFrameRef.current !== undefined) return; + refreshFrameRef.current = requestAnimationFrame(() => { + refreshFrameRef.current = undefined; + if (!alive()) return; + bumpTimeline(); + }); + }, [alive, bumpTimeline]); + useEffect( + () => () => { + if (refreshFrameRef.current !== undefined) cancelAnimationFrame(refreshFrameRef.current); + }, + [] + ); + useLiveEventArrive( room, useCallback( @@ -621,9 +639,7 @@ export function useTimelineSync({ const isDisplayedTimeline = evtTimeline === undefined || linkedTimelinesRef.current.includes(evtTimeline); - if (isDisplayedTimeline) { - setActiveTimeline((ct) => ({ ...ct })); - } + if (isDisplayedTimeline) scheduleTimelineRefresh(); if (!isLive) return; @@ -675,10 +691,10 @@ export function useTimelineSync({ setUnreadInfo, hideReadsRef, isInactivePanelRef, - setActiveTimeline, focusLiveTimeline, redactInFocusedWindow, onReturnToLive, + scheduleTimelineRefresh, ] ) ); @@ -686,34 +702,19 @@ export function useTimelineSync({ const handleLocalEchoUpdated = useCallback( (_mEvent: MatrixEvent, eventRoom: Room | undefined) => { if (eventRoom?.roomId !== room.roomId) return; - setActiveTimeline((ct) => ({ ...ct })); + scheduleTimelineRefresh(); }, - [room, setActiveTimeline] + [room, scheduleTimelineRefresh] ); useMatrixEvent(room, RoomEvent.LocalEchoUpdated, handleLocalEchoUpdated); - const decryptedFrameRef = useRef(undefined); const handleDecrypted = useCallback( (mEvent: MatrixEvent) => { if (mEvent.getRoomId() !== room.roomId) return; - if (decryptedFrameRef.current !== undefined) return; - decryptedFrameRef.current = requestAnimationFrame(() => { - decryptedFrameRef.current = undefined; - if (!alive()) return; - setActiveTimeline((ct) => ({ ...ct })); - }); + scheduleTimelineRefresh(); }, - [alive, room, setActiveTimeline] - ); - - useEffect( - () => () => { - if (decryptedFrameRef.current !== undefined) { - cancelAnimationFrame(decryptedFrameRef.current); - } - }, - [] + [room, scheduleTimelineRefresh] ); useMatrixEvent(mx, MatrixEventEvent.Decrypted, handleDecrypted); @@ -746,12 +747,7 @@ export function useTimelineSync({ ) ); - useThreadUpdate( - room, - useCallback(() => { - setActiveTimeline((ct) => ({ ...ct })); - }, [setActiveTimeline]) - ); + useThreadUpdate(room, scheduleTimelineRefresh); useEffect(() => { const resetAutoScrollPending = resetAutoScrollPendingRef.current; @@ -773,7 +769,7 @@ export function useTimelineSync({ lastScrolledAtEventsLengthRef.current = eventsLength; scrollToBottom(behavior); - }, [isAtBottom, liveTimelineLinked, eventsLength, scrollToBottom]); + }, [isAtBottom, liveTimelineLinked, eventsLength, timelineVersion, scrollToBottom]); useEffect(() => { if (eventId) return; @@ -793,6 +789,7 @@ export function useTimelineSync({ return { timeline, + timelineVersion, eventsLength, liveTimelineLinked, canPaginateBack, diff --git a/src/app/utils/matrix.test.ts b/src/app/utils/matrix.test.ts index aa8d832db..770f6dcef 100644 --- a/src/app/utils/matrix.test.ts +++ b/src/app/utils/matrix.test.ts @@ -21,8 +21,13 @@ vi.mock('@tauri-apps/api/core', () => tauriApi); vi.mock('./mediaTransport', () => mediaTransport); vi.mock('./room/relations', () => reactions); -const { getDMRoomFor, mxcUrlToHttp, rewriteAuthenticatedMediaUrl, toggleReaction } = - await import('./matrix'); +const { + getDMRoomFor, + mxcUrlToHttp, + rewriteAuthenticatedMediaUrl, + toggleReaction, + optimisticallyRedactEvent, +} = await import('./matrix'); describe('rewriteAuthenticatedMediaUrl', () => { beforeEach(() => { @@ -109,28 +114,66 @@ describe('rewriteAuthenticatedMediaUrl', () => { describe('toggleReaction', () => { it('redacts the existing reaction from the current user', () => { + const redaction = {}; const reaction = { getId: () => '$reaction', getSender: () => '@me:example.org', + getRelation: () => ({ event_id: '$message' }), + isRedacted: () => false, + markLocallyRedacted: vi.fn<(event: unknown) => void>(), + unmarkLocallyRedacted: vi.fn<() => void>(), }; reactions.getEventReactions.mockReturnValue({ getSortedAnnotationsByKey: () => [['👍', new Set([reaction])]], }); const mx = { getUserId: () => '@me:example.org', - redactEvent: vi.fn<(roomId: string, eventId: string) => void>(), + makeTxnId: () => 'txn', + redactEvent: vi.fn<(...args: unknown[]) => Promise>(() => Promise.resolve({})), sendEvent: vi.fn<(...args: unknown[]) => void>(), } as unknown as MatrixClient; const room = { roomId: '!room:example.org', getUnfilteredTimelineSet: vi.fn<() => unknown>(), + findEventById: () => redaction, }; toggleReaction(mx, room as never, '$message', '👍'); - expect(mx.redactEvent).toHaveBeenCalledWith('!room:example.org', '$reaction'); + expect(mx.redactEvent).toHaveBeenCalledWith('!room:example.org', '$reaction', 'txn', undefined); + expect(reaction.markLocallyRedacted).toHaveBeenCalledWith(redaction); expect(mx.sendEvent).not.toHaveBeenCalled(); }); + + it('rolls back an optimistic redaction when sending fails', async () => { + const relation = { addEvent: vi.fn<(event: unknown) => Promise>(() => Promise.resolve()) }; + reactions.getEventReactions.mockReturnValue(relation); + const target = { + getId: () => '$reaction', + getRelation: () => ({ event_id: '$message' }), + isRedacted: () => false, + markLocallyRedacted: vi.fn<(event: unknown) => void>(), + unmarkLocallyRedacted: vi.fn<() => void>(), + }; + const error = new Error('failed'); + const mx = { + makeTxnId: () => 'txn', + redactEvent: () => Promise.reject(error), + } as unknown as MatrixClient; + const timelineSet = {}; + const room = { + roomId: '!room:example.org', + getUnfilteredTimelineSet: () => timelineSet, + findEventById: () => ({}), + }; + + await expect( + optimisticallyRedactEvent(mx, room as never, target as never) + ).rejects.toBe(error); + + expect(target.unmarkLocallyRedacted).toHaveBeenCalledOnce(); + expect(relation.addEvent).toHaveBeenCalledWith(target); + }); }); describe('mxcUrlToHttp', () => { diff --git a/src/app/utils/matrix.ts b/src/app/utils/matrix.ts index 7fbd9bfed..4b445c148 100644 --- a/src/app/utils/matrix.ts +++ b/src/app/utils/matrix.ts @@ -571,8 +571,9 @@ export const toggleReaction = ( const myReaction = reactions.find(factoryEventSentBy(mx.getUserId()!)); if (myReaction) { - const eventId = myReaction.getId(); - if (eventId) mx.redactEvent(room.roomId, eventId); + void optimisticallyRedactEvent(mx, room, myReaction, undefined, timelineSet).catch( + () => undefined + ); return; } const rShortcode = @@ -590,3 +591,29 @@ export const toggleReaction = ( ) as TimelineEvents[keyof TimelineEvents] ); }; + +export const optimisticallyRedactEvent = ( + mx: MatrixClient, + room: Room, + target: MatrixEvent, + opts?: { reason?: string }, + timelineSet = room.getUnfilteredTimelineSet() +) => { + const eventId = target.getId(); + if (!eventId) return Promise.reject(new Error('Cannot redact an event without an ID')); + + const txnId = mx.makeTxnId(); + const request = mx.redactEvent(room.roomId, eventId, txnId, opts); + const redaction = room.findEventById(`~${room.roomId}:${txnId}`); + if (!redaction || target.isRedacted()) return request; + + target.markLocallyRedacted(redaction); + return request.catch(async (error) => { + target.unmarkLocallyRedacted(); + const relation = target.getRelation(); + if (relation?.event_id) { + await getEventReactions(timelineSet, relation.event_id)?.addEvent(target); + } + throw error; + }); +}; From d4b5bd735f72bb0da99f82f91467bf4d6dfc5602 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 27 Aug 2026 15:22:26 -0500 Subject: [PATCH 2/2] formatting --- src/app/utils/matrix.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/app/utils/matrix.test.ts b/src/app/utils/matrix.test.ts index 770f6dcef..b1a00ccee 100644 --- a/src/app/utils/matrix.test.ts +++ b/src/app/utils/matrix.test.ts @@ -146,7 +146,9 @@ describe('toggleReaction', () => { }); it('rolls back an optimistic redaction when sending fails', async () => { - const relation = { addEvent: vi.fn<(event: unknown) => Promise>(() => Promise.resolve()) }; + const relation = { + addEvent: vi.fn<(event: unknown) => Promise>(() => Promise.resolve()), + }; reactions.getEventReactions.mockReturnValue(relation); const target = { getId: () => '$reaction', @@ -167,9 +169,7 @@ describe('toggleReaction', () => { findEventById: () => ({}), }; - await expect( - optimisticallyRedactEvent(mx, room as never, target as never) - ).rejects.toBe(error); + await expect(optimisticallyRedactEvent(mx, room as never, target as never)).rejects.toBe(error); expect(target.unmarkLocallyRedacted).toHaveBeenCalledOnce(); expect(relation.addEvent).toHaveBeenCalledWith(target);