From 38dcaa14f79467e359fa41dc7be185ee53b38df8 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 16 Aug 2026 22:54:25 +0200 Subject: [PATCH 1/2] fix(forward): keep search results from being dropped mid-typing useAsyncSearch clears its result whenever the list identity changes. In the room picker that list is derived from pickRoom, whose identity churned on every GlobalModalManager render, so any room activity wiped the search and fell back to recent rooms. Key eligibleSet on the room ids instead of the pickRoom object, and make close stable. --- src/app/components/message/modals/GlobalModalManager.tsx | 6 ++++-- src/app/features/navigate/RoomSearch.tsx | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/app/components/message/modals/GlobalModalManager.tsx b/src/app/components/message/modals/GlobalModalManager.tsx index 9fd4b9add..11df2aaad 100644 --- a/src/app/components/message/modals/GlobalModalManager.tsx +++ b/src/app/components/message/modals/GlobalModalManager.tsx @@ -1,3 +1,4 @@ +import { useCallback } from 'react'; import { useAtom } from 'jotai'; import { OverlayBackdrop, OverlayCenter, Box, Modal } from 'folds'; import { Overlay } from '$components/overlay-stack'; @@ -17,9 +18,10 @@ import { MobileOptionsInternal } from './Options'; export function GlobalModalManager() { const [modal, setModal] = useAtom(modalAtom); - const close = () => { + // stable so modals memoizing on it don't rebuild on every room view render + const close = useCallback(() => { setModal(null); - }; + }, [setModal]); // Forward and MobileOptions render their own back handlers via their children. useDismissOnBack( diff --git a/src/app/features/navigate/RoomSearch.tsx b/src/app/features/navigate/RoomSearch.tsx index 66de20dad..2cbde7542 100644 --- a/src/app/features/navigate/RoomSearch.tsx +++ b/src/app/features/navigate/RoomSearch.tsx @@ -158,9 +158,11 @@ export function RoomSearchModal({ const spaces = useSpaces(mx, allRoomsAtom); const directs = useDirects(mx, allRoomsAtom, mDirects); + // keyed on the ids, not on pickRoom, whose callbacks change on every host render + const eligibleRoomIds = pickRoom?.eligibleRoomIds; const eligibleSet = useMemo( - () => (pickRoom ? new Set(pickRoom.eligibleRoomIds) : null), - [pickRoom] + () => (eligibleRoomIds ? new Set(eligibleRoomIds) : null), + [eligibleRoomIds] ); const rawTopActiveRooms = useTopActiveRooms(searchRoomType, rooms, directs, spaces); From 302c1bb2985ad690702bf23b9e1bd1dc1a5aa4e0 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 16 Aug 2026 22:55:11 +0200 Subject: [PATCH 2/2] fix(poll): stop an unreadable response crashing the room PollEvent treated every m.reference child of a poll as a well formed vote, reading the answers with optional chaining and then dereferencing the result. m.relates_to is lifted out of the encrypted content, so a response that has not decrypted yet still resolves as a child of the poll while carrying no answers, and rendering the room threw. PollResponses had the same unguarded read. The vote total's reduce and a poll start with no answers threw on the same path. Also align vote counting with MSC3381, shared with the voter list: - max_selections defaults to 1 - an over long selection is truncated instead of spoiling the vote - an unknown answer id spoils the whole vote - an id repeated after truncation counts once --- src/app/components/message/PollEvent.test.tsx | 190 ++++++++++++++++++ src/app/components/message/PollEvent.tsx | 52 +++-- .../room/poll-modals/PollResponses.tsx | 20 +- 3 files changed, 237 insertions(+), 25 deletions(-) create mode 100644 src/app/components/message/PollEvent.test.tsx diff --git a/src/app/components/message/PollEvent.test.tsx b/src/app/components/message/PollEvent.test.tsx new file mode 100644 index 000000000..b5f7d776a --- /dev/null +++ b/src/app/components/message/PollEvent.test.tsx @@ -0,0 +1,190 @@ +import { render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import { + M_POLL_END, + M_POLL_KIND_DISCLOSED, + M_POLL_RESPONSE, + M_POLL_START, + M_TEXT, + type MatrixEvent, +} from 'matrix-js-sdk'; +import { PollEvent, getCountedSelections, getPollResponseAnswers } from './PollEvent'; + +const POLL_ID = '$poll'; +const VIEWER = '@bob:e.dev'; + +const pollContent = { + [M_POLL_START.name]: { + question: { [M_TEXT.name]: 'Lunch?', body: 'Lunch?' }, + kind: M_POLL_KIND_DISCLOSED.name, + max_selections: 1, + answers: [ + { id: 'a', [M_TEXT.name]: 'Pizza' }, + { id: 'b', [M_TEXT.name]: 'Sushi' }, + ], + }, +}; + +const childEvent = (sender: string, content: Record) => + ({ + event: { sender, origin_server_ts: 1 }, + getContent: () => content, + getSender: () => sender, + getRelation: () => ({ rel_type: 'm.reference', event_id: POLL_ID }), + getId: () => `$${sender}`, + getAssociatedId: () => POLL_ID, + }) as unknown as MatrixEvent; + +const vote = (sender: string, answers: string[], key: string = M_POLL_RESPONSE.name) => + childEvent(sender, { [key]: { answers } }); + +function makeRoom(children: MatrixEvent[]) { + const roomState = { maySendRedactionForEvent: () => false }; + const liveTimeline = { getState: () => roomState }; + const timelineSet = { relations: { getAllChildEventsForEvent: () => children } }; + + return { + roomId: '!r:e.dev', + on: () => {}, + removeListener: () => {}, + getMember: () => null, + getLiveTimeline: () => liveTimeline, + getUnfilteredTimelineSet: () => timelineSet, + }; +} + +function renderPoll(children: MatrixEvent[], content: Record = pollContent) { + const mEvent = { + getId: () => POLL_ID, + getSender: () => '@alice:e.dev', + sender: { userId: '@alice:e.dev' }, + }; + + return render( + VIEWER } as never} + room={makeRoom(children) as never} + /> + ); +} + +describe('getPollResponseAnswers', () => { + it('reads answers from the unstable and stable namespaces', () => { + expect(getPollResponseAnswers(vote('@a:e.dev', ['a']))).toEqual(['a']); + expect(getPollResponseAnswers(vote('@a:e.dev', ['b'], M_POLL_RESPONSE.altName))).toEqual(['b']); + }); + + it('returns undefined for events that are not usable votes', () => { + expect(getPollResponseAnswers(childEvent('@a:e.dev', {}))).toBeUndefined(); + expect( + getPollResponseAnswers(childEvent('@a:e.dev', { [M_POLL_END.name]: {} })) + ).toBeUndefined(); + expect( + getPollResponseAnswers(childEvent('@a:e.dev', { [M_POLL_RESPONSE.name]: {} })) + ).toBeUndefined(); + expect( + getPollResponseAnswers(childEvent('@a:e.dev', { [M_POLL_RESPONSE.name]: { answers: 'a' } })) + ).toBeUndefined(); + }); + + it('returns undefined for a vote that has not been decrypted', () => { + const pending = childEvent('@a:e.dev', { + algorithm: 'm.megolm.v1.aes-sha2', + ciphertext: 'AwgAEn...', + session_id: 'sess', + }); + expect(getPollResponseAnswers(pending)).toBeUndefined(); + + const failed = childEvent('@a:e.dev', { + msgtype: 'm.bad.encrypted', + body: '** Unable to decrypt: The sender key was not found **', + }); + expect(getPollResponseAnswers(failed)).toBeUndefined(); + }); + + it('drops non-string answer entries', () => { + const bad = childEvent('@a:e.dev', { [M_POLL_RESPONSE.name]: { answers: ['a', 3, null] } }); + expect(getPollResponseAnswers(bad)).toEqual(['a']); + }); +}); + +describe('getCountedSelections', () => { + const answerIds = new Set(['a', 'b', 'c']); + + it('truncates to max_selections rather than spoiling the vote', () => { + expect(getCountedSelections(vote('@a:e.dev', ['a', 'b', 'c']), answerIds, 2)).toEqual([ + 'a', + 'b', + ]); + }); + + it('spoils the vote when any answer id is unknown', () => { + expect(getCountedSelections(vote('@a:e.dev', ['a', 'nope']), answerIds, 2)).toEqual([]); + }); + + it('counts a repeated id once', () => { + expect(getCountedSelections(vote('@a:e.dev', ['a', 'a']), answerIds, 2)).toEqual(['a']); + }); + + it('treats an empty selection as an unvote', () => { + expect(getCountedSelections(vote('@a:e.dev', []), answerIds, 1)).toEqual([]); + }); + + it('spoils a vote it cannot read at all', () => { + expect(getCountedSelections(childEvent('@a:e.dev', {}), answerIds, 1)).toEqual([]); + }); +}); + +describe('PollEvent', () => { + it('renders a poll whose child events include one with no content', () => { + expect(() => renderPoll([vote(VIEWER, ['a']), childEvent('@empty:e.dev', {})])).not.toThrow(); + + expect(screen.getByText('(1 vote)')).toBeTruthy(); + expect(screen.getByText(/^1 vote$/)).toBeTruthy(); + }); + + it('counts a vote sent under the stable namespace', () => { + renderPoll([vote(VIEWER, ['a'], M_POLL_RESPONSE.altName)]); + + expect(screen.getByText('(1 vote)')).toBeTruthy(); + expect(screen.getByText('(0 votes)')).toBeTruthy(); + }); + + it('treats a stable-namespace poll end as an end, not a vote', () => { + renderPoll([childEvent('@alice:e.dev', { [M_POLL_END.altName]: {} })]); + + expect(screen.getByText('This poll has ended.')).toBeTruthy(); + }); + + it('renders a poll whose child events include an undecrypted vote', () => { + expect(() => + renderPoll([ + vote(VIEWER, ['a']), + childEvent('@nokeys:e.dev', { + msgtype: 'm.bad.encrypted', + body: '** Unable to decrypt: The sender key was not found **', + }), + ]) + ).not.toThrow(); + + expect(screen.getByText(/^1 vote$/)).toBeTruthy(); + }); + + it('defaults max_selections to 1 when the poll start omits it', () => { + const { question, answers, kind } = pollContent[M_POLL_START.name]; + renderPoll([vote(VIEWER, ['a', 'b'])], { + [M_POLL_START.name]: { question, answers, kind }, + }); + + expect(screen.getByText('(1 vote)')).toBeTruthy(); + expect(screen.getByText('(0 votes)')).toBeTruthy(); + }); + + it('renders a poll start that carries no answers', () => { + expect(() => + renderPoll([], { [M_POLL_START.name]: { question: { body: 'Broken' } } }) + ).not.toThrow(); + }); +}); diff --git a/src/app/components/message/PollEvent.tsx b/src/app/components/message/PollEvent.tsx index 8714a04ce..be88a9a5d 100644 --- a/src/app/components/message/PollEvent.tsx +++ b/src/app/components/message/PollEvent.tsx @@ -43,6 +43,26 @@ type PollResponse = { answers: string[]; }; }; + +export function getPollResponseAnswers(mEvent: MatrixEvent): string[] | undefined { + const response = M_POLL_RESPONSE.findIn<{ answers?: unknown } | undefined>(mEvent.getContent()); + if (!Array.isArray(response?.answers)) return undefined; + return response.answers.filter((answer): answer is string => typeof answer === 'string'); +} + +const isPollEnd = (mEvent: MatrixEvent): boolean => + M_POLL_END.includedIn(Object.keys(mEvent.getContent())); + +export function getCountedSelections( + mEvent: MatrixEvent, + answerIds: Set, + maxSelections: number +): string[] { + const selections = getPollResponseAnswers(mEvent)?.slice(0, maxSelections); + if (!selections?.length || selections.some((id) => !answerIds.has(id))) return []; + return [...new Set(selections)]; +} + export function PollEvent({ content, mEvent, mx, room }: PollEventProps) { const eventId = mEvent.getId(); const userId = mx.getUserId() ?? ''; @@ -52,9 +72,9 @@ export function PollEvent({ content, mEvent, mx, room }: PollEventProps) { const poll = content[M_POLL_START.name] as PollStartSubtype; const questionBody = (poll?.question as { body?: string })?.body ?? ''; - const answers = (poll as { answers: PollAnswerItem[] })?.answers; - const maxSelections = (poll as { max_selections: number })?.max_selections; - const isDisclosed = (poll as { kind: string })?.kind === M_POLL_KIND_DISCLOSED.name; + const answers = (poll as { answers?: PollAnswerItem[] })?.answers ?? []; + const maxSelections = (poll as { max_selections?: number })?.max_selections ?? 1; + const isDisclosed = M_POLL_KIND_DISCLOSED.matches((poll as { kind?: string })?.kind ?? ''); const canEnd = userId === mEvent.sender?.userId || roomState?.maySendRedactionForEvent(mEvent, userId); @@ -70,7 +90,7 @@ export function PollEvent({ content, mEvent, mx, room }: PollEventProps) { events.findLastIndex((item) => { const itemSender = item.getSender(); return ( - M_POLL_END.name in item.getContent() && + isPollEnd(item) && typeof item.getSender() === 'string' && pollSender && itemSender && @@ -142,7 +162,7 @@ export function PollEvent({ content, mEvent, mx, room }: PollEventProps) { let filteredChildEvents: MatrixEvent[] = []; if (isDisclosed || isEnded) finalArray?.forEach((item) => { - if (M_POLL_END.name in item.getContent()) { + if (isPollEnd(item)) { return; } if (item.event.sender && !voters.has(item.event.sender)) { @@ -151,30 +171,27 @@ export function PollEvent({ content, mEvent, mx, room }: PollEventProps) { } }); + const answerIds = new Set(answers.map((item) => item.id)); + filteredChildEvents?.forEach((item) => { - const VoteContent = item.getContent(); - const response = VoteContent[M_POLL_RESPONSE.name]; - const selections = response?.answers; - if (selections.length > maxSelections || selections.length === 0) { + const counted = getCountedSelections(item, answerIds, maxSelections); + if (counted.length === 0) { if (item.event.sender) voters.delete(item.event.sender); return; } - selections.forEach((selection: string) => { - if (votes[selection] !== undefined) votes[selection] += 1; + counted.forEach((selection) => { + votes[selection] = (votes[selection] ?? 0) + 1; }); }); - const totalVotes = Object.values(votes).reduce((a, b) => a + b); + const totalVotes = Object.values(votes).reduce((a, b) => a + b, 0); const userSelectionEvent = filteredChildEvents.length > 0 ? filteredChildEvents.find((item) => item.event.sender === userId) : finalArray.find((item) => item.event.sender === userId); - const userSelectionContent = userSelectionEvent?.getContent(); - const userSelection: string[] = userSelectionContent - ? userSelectionContent[M_POLL_RESPONSE.name]?.answers - : undefined; - const hasVoted = userSelection?.length > 0; + const userSelection = userSelectionEvent ? getPollResponseAnswers(userSelectionEvent) : undefined; + const hasVoted = (userSelection?.length ?? 0) > 0; const showAnswers = (isDisclosed && (hasVoted || isSnooping)) || isEnded; function handleNewVote(id: string) { @@ -339,6 +356,7 @@ export function PollEvent({ content, mEvent, mx, room }: PollEventProps) { setViewVotersAnswer(undefined)} diff --git a/src/app/features/room/poll-modals/PollResponses.tsx b/src/app/features/room/poll-modals/PollResponses.tsx index 6f014d7a2..19a600fc8 100644 --- a/src/app/features/room/poll-modals/PollResponses.tsx +++ b/src/app/features/room/poll-modals/PollResponses.tsx @@ -25,34 +25,38 @@ import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile'; import { useSpaceOptionally } from '$hooks/useSpace'; import { getMouseEventCords } from '$utils/dom'; import * as css from './PollResponses.css'; -import { useCallback, useEffect, useState } from 'react'; -import type { PollAnswerItem } from '$components/message/PollEvent'; -import { M_POLL_RESPONSE, M_TEXT } from 'matrix-js-sdk'; +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { getCountedSelections, type PollAnswerItem } from '$components/message/PollEvent'; +import { M_TEXT } from 'matrix-js-sdk'; type PollResponsesViewerProps = { room: Room; answers: PollAnswerItem[]; + maxSelections: number; events: MatrixEvent[]; initialSelection: PollAnswerItem; onClose: () => void; }; export const PollResponsesViewer = as<'div', PollResponsesViewerProps>( - ({ className, room, answers, events, initialSelection, onClose, ...props }, ref) => { + ( + { className, room, answers, maxSelections, events, initialSelection, onClose, ...props }, + ref + ) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const space = useSpaceOptionally(); const openProfile = useOpenUserRoomProfile(); const nicknames = useAtomValue(nicknamesAtom); const [selectedOption, setSelectedOption] = useState(initialSelection); + const answerIds = useMemo(() => new Set(answers.map((item) => item.id)), [answers]); const getVotes = useCallback(() => { let votes: MatrixEvent[] = []; events.forEach((item) => { - const response = item.getContent()[M_POLL_RESPONSE.name]; - const selections = response?.answers; - if (selections.includes(selectedOption.id) && item.event.sender) votes.push(item); + const counted = getCountedSelections(item, answerIds, maxSelections); + if (counted.includes(selectedOption.id) && item.event.sender) votes.push(item); }); return votes; - }, [selectedOption, events]); + }, [selectedOption, events, answerIds, maxSelections]); const [votes, setVotes] = useState(getVotes()); useEffect(() => { setSelectedOption(initialSelection);