fix: fix poll crashing and fix forward not searching correctly (#1822)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Fixes #

#### Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
Erwan Leboucher authored and GitHub committed 2026-08-16 23:12:32 +02:00
commit bb8baacf6d
5 files changed
+245 -29

No files matched your search

@@ -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<string, unknown>) =>
({
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<string, unknown> = pollContent) {
const mEvent = {
getId: () => POLL_ID,
getSender: () => '@alice:e.dev',
sender: { userId: '@alice:e.dev' },
};
return render(
<PollEvent
content={content}
mEvent={mEvent as unknown as MatrixEvent}
mx={{ getUserId: () => 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();
});
});
+35 -17
View File
@@ -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<string>,
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) {
<PollResponsesViewer
room={room}
answers={answers}
maxSelections={maxSelections}
events={filteredChildEvents}
initialSelection={ViewVotersAnswer}
onClose={() => setViewVotersAnswer(undefined)}
@@ -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(
+4 -2
View File
@@ -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);
@@ -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);