From 2a8836e44a387b88112e1097670b1c8be4a7baf0 Mon Sep 17 00:00:00 2001 From: "Timo K." Date: Fri, 20 Nov 2026 01:01:28 +0100 Subject: [PATCH] never use rtcSession.room (Relation classes refactor) make sure everything is passed through dedicated room / client props. --- component/ElementCall.test.tsx | 3 + component/callViewClient.test.ts | 3 + component/callViewClient.ts | 6 ++ component/index.tsx | 4 + src/button/ReactionToggleButton.test.tsx | 81 ++++++++++++----- src/reactions/ReactionsReader.test.tsx | 110 +++++++++++++---------- src/reactions/ReactionsReader.ts | 73 ++++++++------- src/reactions/useReactionsSender.tsx | 60 +++++++------ src/room/CallView.tsx | 9 ++ src/room/InCallView.test.tsx | 8 +- src/room/InCallView.tsx | 23 ++++- src/room/RoomPage.tsx | 4 +- src/room/useLoadGroupCall.ts | 11 ++- src/tile/GridTile.test.tsx | 40 ++++++--- src/utils/test-viewmodel.ts | 69 +++++++------- 15 files changed, 319 insertions(+), 185 deletions(-) diff --git a/component/ElementCall.test.tsx b/component/ElementCall.test.tsx index 9be39e90f..e878cc34a 100644 --- a/component/ElementCall.test.tsx +++ b/component/ElementCall.test.tsx @@ -47,6 +47,9 @@ function mockClient(knownRoom: Room | null = room): MatrixClient { getSyncState: () => null, getUser: () => null, getCrypto: () => undefined, + sendEvent: vi.fn(), + redactEvent: vi.fn(), + decryptEventIfNeeded: vi.fn(), setDisplayName: vi.fn(), setAvatarUrl: vi.fn(), uploadContent: vi.fn(), diff --git a/component/callViewClient.test.ts b/component/callViewClient.test.ts index 9e120fa63..aa18249c2 100644 --- a/component/callViewClient.test.ts +++ b/component/callViewClient.test.ts @@ -22,6 +22,9 @@ function mockHost(): MatrixClient & { token: string } { off: vi.fn(), getUser: vi.fn(() => null), getCrypto: vi.fn(() => undefined), + sendEvent: vi.fn(), + redactEvent: vi.fn(), + decryptEventIfNeeded: vi.fn(), setDisplayName: vi.fn(), setAvatarUrl: vi.fn(), uploadContent: vi.fn(), diff --git a/component/callViewClient.ts b/component/callViewClient.ts index ae5d8702d..a6f91cbbb 100644 --- a/component/callViewClient.ts +++ b/component/callViewClient.ts @@ -42,12 +42,18 @@ export function createCallViewClient( getSyncState: host.getSyncState.bind(host), // `on`/`off`, to listen for: // - `ClientEvent.Sync` (RTC slot homeserver connection) + // - `MatrixEventEvent.Decrypted` (reactions once decrypted) on: host.on.bind(host), off: host.off.bind(host), // The host's store, which only its sync fills getUser: host.getUser.bind(host), // The device's crypto: there must never be a second one getCrypto: host.getCrypto.bind(host), + // Reactions and raised hands: the host's crypto encrypts and decrypts them, + // and its room gets the local echo + sendEvent: host.sendEvent.bind(host), + redactEvent: host.redactEvent.bind(host), + decryptEventIfNeeded: host.decryptEventIfNeeded.bind(host), // Credentials, static, we can use own getUserId: own.getUserId.bind(own), diff --git a/component/index.tsx b/component/index.tsx index 1e07c175a..b32bda3d1 100644 --- a/component/index.tsx +++ b/component/index.tsx @@ -232,6 +232,8 @@ export const ElementCall: FC = ({ | "currentState" // Joined and invited members, for the RTC slot and the call view model | "getMembersWithMembership" + // Raised hands already in the room, for the reactions reader + | "relations" // `on`/`off`, to listen for: // - the RTC session's room events // - `RoomEvent.Name` (room name) @@ -239,6 +241,8 @@ export const ElementCall: FC = ({ // - `RoomStateEvent.Events` (RTC slot status) // - `RoomStateEvent.Members` (RTC slot and call view model members) // - `RoomEvent.Timeline` and `RoomStickyEventsEvent.Update` (call notifications) + // - `RoomEvent.Timeline`, `RoomEvent.Redaction` and + // `RoomEvent.LocalEchoUpdated` (reactions and raised hands) | "on" | "off" > | null; diff --git a/src/button/ReactionToggleButton.test.tsx b/src/button/ReactionToggleButton.test.tsx index 54201aa9b..1fe21df44 100644 --- a/src/button/ReactionToggleButton.test.tsx +++ b/src/button/ReactionToggleButton.test.tsx @@ -10,6 +10,7 @@ import { expect, test } from "vitest"; import { TooltipProvider } from "@vector-im/compound-web"; import { userEvent } from "@testing-library/user-event"; import { type ReactNode } from "react"; +import { type MatrixClient, type Room } from "matrix-js-sdk"; import { ReactionToggleButton } from "./ReactionToggleButton"; import { ElementCallReactionEventType } from "../reactions"; @@ -25,9 +26,13 @@ const localIdent = `${localRtcMember.userId}:${localRtcMember.deviceId}`; function TestComponent({ rtcSession, + matrixRoom, + client, vm, }: { rtcSession: MockRTCSession; + matrixRoom: Room; + client: MatrixClient; vm: CallViewModel; }): ReactNode { return ( @@ -35,6 +40,8 @@ function TestComponent({ { const user = userEvent.setup(); - const { vm, rtcSession } = getBasicCallViewModelEnvironment([alice]); + const { vm, rtcSession, matrixRoom, client } = + getBasicCallViewModelEnvironment([alice]); const { getByLabelText, container } = render( - , + , ); await user.click(getByLabelText("Reactions")); expect(container).toMatchSnapshot(); @@ -60,15 +73,20 @@ test("Can open menu", async () => { test("Can raise hand", async () => { const user = userEvent.setup(); - const { vm, rtcSession, handRaisedSubject$ } = + const { vm, rtcSession, matrixRoom, client, handRaisedSubject$ } = getBasicCallViewModelEnvironment([local, alice]); const { getByLabelText, container } = render( - , + , ); await user.click(getByLabelText("Reactions")); await user.click(getByLabelText("Raise hand")); - expect(rtcSession.room.client.sendEvent).toHaveBeenCalledWith( - rtcSession.room.roomId, + expect(client.sendEvent).toHaveBeenCalledWith( + matrixRoom.roomId, "m.reaction", { "m.relates_to": { @@ -94,10 +112,15 @@ test("Can raise hand", async () => { test("Can lower hand", async () => { const reactionEventId = "$my-reaction-event:example.org"; const user = userEvent.setup(); - const { vm, rtcSession, handRaisedSubject$ } = + const { vm, rtcSession, matrixRoom, client, handRaisedSubject$ } = getBasicCallViewModelEnvironment([local, alice]); const { getByLabelText, container } = render( - , + , ); await user.click(getByLabelText("Reactions")); await user.click(getByLabelText("Raise hand")); @@ -112,8 +135,8 @@ test("Can lower hand", async () => { }); await user.click(getByLabelText("Reactions")); await user.click(getByLabelText("Lower hand")); - expect(rtcSession.room.client.redactEvent).toHaveBeenCalledWith( - rtcSession.room.roomId, + expect(client.redactEvent).toHaveBeenCalledWith( + matrixRoom.roomId, reactionEventId, ); act(() => { @@ -125,14 +148,20 @@ test("Can lower hand", async () => { test("Can react with emoji", async () => { const user = userEvent.setup(); - const { vm, rtcSession } = getBasicCallViewModelEnvironment([local, alice]); + const { vm, rtcSession, matrixRoom, client } = + getBasicCallViewModelEnvironment([local, alice]); const { getByLabelText, getByText } = render( - , + , ); await user.click(getByLabelText("Reactions")); await user.click(getByText("🐶")); - expect(rtcSession.room.client.sendEvent).toHaveBeenCalledWith( - rtcSession.room.roomId, + expect(client.sendEvent).toHaveBeenCalledWith( + matrixRoom.roomId, ElementCallReactionEventType, { "m.relates_to": { @@ -147,16 +176,22 @@ test("Can react with emoji", async () => { test("Can fully expand emoji picker", async () => { const user = userEvent.setup(); - const { vm, rtcSession } = getBasicCallViewModelEnvironment([local, alice]); + const { vm, rtcSession, matrixRoom, client } = + getBasicCallViewModelEnvironment([local, alice]); const { getByLabelText, container, getByText } = render( - , + , ); await user.click(getByLabelText("Reactions")); await user.click(getByLabelText("Show more")); expect(container).toMatchSnapshot(); await user.click(getByText("🦗")); - expect(rtcSession.room.client.sendEvent).toHaveBeenCalledWith( - rtcSession.room.roomId, + expect(client.sendEvent).toHaveBeenCalledWith( + matrixRoom.roomId, ElementCallReactionEventType, { "m.relates_to": { @@ -171,9 +206,15 @@ test("Can fully expand emoji picker", async () => { test("Can close reaction dialog", async () => { const user = userEvent.setup(); - const { vm, rtcSession } = getBasicCallViewModelEnvironment([local, alice]); + const { vm, rtcSession, matrixRoom, client } = + getBasicCallViewModelEnvironment([local, alice]); const { getByLabelText, container } = render( - , + , ); await user.click(getByLabelText("Reactions")); await user.click(getByLabelText("Show more")); diff --git a/src/reactions/ReactionsReader.test.tsx b/src/reactions/ReactionsReader.test.tsx index dd82a718c..44a75be93 100644 --- a/src/reactions/ReactionsReader.test.tsx +++ b/src/reactions/ReactionsReader.test.tsx @@ -31,7 +31,7 @@ afterEach(() => { }); test("handles a hand raised reaction", () => { - const { rtcSession } = getBasicRTCSession([local, alice]); + const { rtcSession, matrixRoom, client } = getBasicRTCSession([local, alice]); const reactionEventId = "$my_event_id:example.org"; const localTimestamp = new Date(); withTestScheduler(({ schedule, expectObservable }) => { @@ -39,14 +39,16 @@ test("handles a hand raised reaction", () => { const { raisedHands$ } = new ReactionsReader( testScope(), rtcSession.asMockedSession(), + matrixRoom, + client, ); schedule("ab", { a: () => {}, b: () => { - rtcSession.room.emit( + matrixRoom.emit( MatrixRoomEvent.Timeline, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: matrixRoom.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: EventType.Reaction, @@ -58,7 +60,7 @@ test("handles a hand raised reaction", () => { }, }, }), - rtcSession.room, + matrixRoom, undefined, false, {} as IRoomTimelineData, @@ -80,7 +82,7 @@ test("handles a hand raised reaction", () => { }); test("handles a redaction", () => { - const { rtcSession } = getBasicRTCSession([local, alice]); + const { rtcSession, matrixRoom, client } = getBasicRTCSession([local, alice]); const reactionEventId = "$my_event_id:example.org"; const localTimestamp = new Date(); withTestScheduler(({ schedule, expectObservable }) => { @@ -88,14 +90,16 @@ test("handles a redaction", () => { const { raisedHands$ } = new ReactionsReader( testScope(), rtcSession.asMockedSession(), + matrixRoom, + client, ); schedule("abc", { a: () => {}, b: () => { - rtcSession.room.emit( + matrixRoom.emit( MatrixRoomEvent.Timeline, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: matrixRoom.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: EventType.Reaction, @@ -107,23 +111,23 @@ test("handles a redaction", () => { }, }, }), - rtcSession.room, + matrixRoom, undefined, false, {} as IRoomTimelineData, ); }, c: () => { - rtcSession.room.emit( + matrixRoom.emit( MatrixRoomEvent.Redaction, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: matrixRoom.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: EventType.RoomRedaction, redacts: reactionEventId, }), - rtcSession.room, + matrixRoom, undefined, ); }, @@ -144,7 +148,7 @@ test("handles a redaction", () => { }); test("handles waiting for event decryption", () => { - const { rtcSession } = getBasicRTCSession([local, alice]); + const { rtcSession, matrixRoom, client } = getBasicRTCSession([local, alice]); const reactionEventId = "$my_event_id:example.org"; const localTimestamp = new Date(); withTestScheduler(({ schedule, expectObservable }) => { @@ -152,12 +156,14 @@ test("handles waiting for event decryption", () => { const { raisedHands$ } = new ReactionsReader( testScope(), rtcSession.asMockedSession(), + matrixRoom, + client, ); schedule("abc", { a: () => {}, b: () => { const encryptedEvent = new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: matrixRoom.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: EventType.Reaction, @@ -171,20 +177,20 @@ test("handles waiting for event decryption", () => { }); // Should ignore encrypted events that are still encrypting encryptedEvent["decryptionPromise"] = Promise.resolve(); - rtcSession.room.emit( + matrixRoom.emit( MatrixRoomEvent.Timeline, encryptedEvent, - rtcSession.room, + matrixRoom, undefined, false, {} as IRoomTimelineData, ); }, c: () => { - rtcSession.room.client.emit( + client.emit( MatrixEventEvent.Decrypted, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: matrixRoom.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: EventType.Reaction, @@ -214,7 +220,7 @@ test("handles waiting for event decryption", () => { }); test("hands rejecting events without a proper membership", () => { - const { rtcSession } = getBasicRTCSession([local, alice]); + const { rtcSession, matrixRoom, client } = getBasicRTCSession([local, alice]); const reactionEventId = "$my_event_id:example.org"; const localTimestamp = new Date(); withTestScheduler(({ schedule, expectObservable }) => { @@ -222,14 +228,16 @@ test("hands rejecting events without a proper membership", () => { const { raisedHands$ } = new ReactionsReader( testScope(), rtcSession.asMockedSession(), + matrixRoom, + client, ); schedule("ab", { a: () => {}, b: () => { - rtcSession.room.emit( + matrixRoom.emit( MatrixRoomEvent.Timeline, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: matrixRoom.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: EventType.Reaction, @@ -241,7 +249,7 @@ test("hands rejecting events without a proper membership", () => { }, }, }), - rtcSession.room, + matrixRoom, undefined, false, {} as IRoomTimelineData, @@ -256,7 +264,7 @@ test("hands rejecting events without a proper membership", () => { }); test("handles a reaction", () => { - const { rtcSession } = getBasicRTCSession([local, alice]); + const { rtcSession, matrixRoom, client } = getBasicRTCSession([local, alice]); const reactionEventId = "$my_event_id:example.org"; const reaction = ReactionSet[1]; @@ -268,14 +276,16 @@ test("handles a reaction", () => { const { reactions$ } = new ReactionsReader( testScope(), rtcSession.asMockedSession(), + matrixRoom, + client, ); schedule(`abc`, { a: () => {}, b: () => { - rtcSession.room.emit( + matrixRoom.emit( MatrixRoomEvent.Timeline, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: matrixRoom.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: ElementCallReactionEventType, @@ -287,7 +297,7 @@ test("handles a reaction", () => { }, }, }), - rtcSession.room, + matrixRoom, undefined, false, {} as IRoomTimelineData, @@ -316,7 +326,7 @@ test("handles a reaction", () => { }); test("ignores bad reaction events", () => { - const { rtcSession } = getBasicRTCSession([local, alice]); + const { rtcSession, room, client } = getBasicRTCSession([local, alice]); const reactionEventId = "$my_event_id:example.org"; const reaction = ReactionSet[1]; @@ -327,30 +337,32 @@ test("ignores bad reaction events", () => { const { reactions$ } = new ReactionsReader( testScope(), rtcSession.asMockedSession(), + room, + client, ); schedule("ab", { a: () => {}, b: () => { // Missing content - rtcSession.room.emit( + room.emit( MatrixRoomEvent.Timeline, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: room.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: ElementCallReactionEventType, content: {}, }), - rtcSession.room, + room, undefined, false, {} as IRoomTimelineData, ); // Wrong relates event - rtcSession.room.emit( + room.emit( MatrixRoomEvent.Timeline, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: room.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: ElementCallReactionEventType, @@ -362,16 +374,16 @@ test("ignores bad reaction events", () => { }, }, }), - rtcSession.room, + room, undefined, false, {} as IRoomTimelineData, ); // Wrong rtc member event - rtcSession.room.emit( + room.emit( MatrixRoomEvent.Timeline, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: room.roomId, event_id: reactionEventId, sender: aliceRtcMember.userId, type: ElementCallReactionEventType, @@ -383,16 +395,16 @@ test("ignores bad reaction events", () => { }, }, }), - rtcSession.room, + room, undefined, false, {} as IRoomTimelineData, ); // No emoji - rtcSession.room.emit( + room.emit( MatrixRoomEvent.Timeline, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: room.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: ElementCallReactionEventType, @@ -403,16 +415,16 @@ test("ignores bad reaction events", () => { }, }, }), - rtcSession.room, + room, undefined, false, {} as IRoomTimelineData, ); // Invalid emoji - rtcSession.room.emit( + room.emit( MatrixRoomEvent.Timeline, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: room.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: ElementCallReactionEventType, @@ -424,7 +436,7 @@ test("ignores bad reaction events", () => { }, }, }), - rtcSession.room, + room, undefined, false, {} as IRoomTimelineData, @@ -439,7 +451,7 @@ test("ignores bad reaction events", () => { }); test("that reactions cannot be spammed", () => { - const { rtcSession } = getBasicRTCSession([local, alice]); + const { rtcSession, matrixRoom, client } = getBasicRTCSession([local, alice]); const reactionEventId = "$my_event_id:example.org"; const reactionA = ReactionSet[1]; const reactionB = ReactionSet[2]; @@ -452,14 +464,16 @@ test("that reactions cannot be spammed", () => { const { reactions$ } = new ReactionsReader( testScope(), rtcSession.asMockedSession(), + matrixRoom, + client, ); schedule("abcd", { a: () => {}, b: () => { - rtcSession.room.emit( + matrixRoom.emit( MatrixRoomEvent.Timeline, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: matrixRoom.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: ElementCallReactionEventType, @@ -471,17 +485,17 @@ test("that reactions cannot be spammed", () => { }, }, }), - rtcSession.room, + matrixRoom, undefined, false, {} as IRoomTimelineData, ); }, c: () => { - rtcSession.room.emit( + matrixRoom.emit( MatrixRoomEvent.Timeline, new MatrixEvent({ - room_id: rtcSession.room.roomId, + room_id: matrixRoom.roomId, event_id: reactionEventId, sender: localRtcMember.userId, type: ElementCallReactionEventType, @@ -493,7 +507,7 @@ test("that reactions cannot be spammed", () => { }, }, }), - rtcSession.room, + matrixRoom, undefined, false, {} as IRoomTimelineData, diff --git a/src/reactions/ReactionsReader.ts b/src/reactions/ReactionsReader.ts index 7ce59812a..f1fc3da73 100644 --- a/src/reactions/ReactionsReader.ts +++ b/src/reactions/ReactionsReader.ts @@ -11,7 +11,12 @@ import { type MatrixRTCSession, } from "matrix-js-sdk/lib/matrixrtc"; import { logger } from "matrix-js-sdk/lib/logger"; -import { type MatrixEvent, MatrixEventEvent } from "matrix-js-sdk"; +import { + type MatrixClient, + type MatrixEvent, + MatrixEventEvent, + type Room, +} from "matrix-js-sdk"; import { type ReactionEventContent } from "matrix-js-sdk/lib/types"; import { RelationType, @@ -58,6 +63,28 @@ export class ReactionsReader { public constructor( private readonly scope: ObservableScope, private readonly rtcSession: MatrixRTCSession, + private readonly room: Pick< + Room, + // To ignore events from other rooms + | "roomId" + // The raised hands already in the room, as reactions to memberships + | "relations" + // `on`/`off`, to listen for: + // - `RoomEvent.Timeline` (new reactions) + // - `RoomEvent.Redaction` (lowered hands) + // - `RoomEvent.LocalEchoUpdated` (the real id of our own reactions) + | "on" + | "off" + >, + private readonly client: Pick< + MatrixClient, + // Reactions that arrived encrypted + | "decryptEventIfNeeded" + // `on`/`off`, to listen for: + // - `MatrixEventEvent.Decrypted` (reactions once decrypted) + | "on" + | "off" + >, ) { // Hide reactions after a given time. this.reactionsSubject$ @@ -76,47 +103,26 @@ export class ReactionsReader { // TODO: Convert this class to the functional reactive style and get rid of // all this manual setup and teardown for event listeners - this.rtcSession.room.on(MatrixRoomEvent.Timeline, this.handleReactionEvent); + this.room.on(MatrixRoomEvent.Timeline, this.handleReactionEvent); this.scope.onEnd(() => - this.rtcSession.room.off( - MatrixRoomEvent.Timeline, - this.handleReactionEvent, - ), + this.room.off(MatrixRoomEvent.Timeline, this.handleReactionEvent), ); - this.rtcSession.room.on( - MatrixRoomEvent.Redaction, - this.handleReactionEvent, - ); + this.room.on(MatrixRoomEvent.Redaction, this.handleReactionEvent); this.scope.onEnd(() => - this.rtcSession.room.off( - MatrixRoomEvent.Redaction, - this.handleReactionEvent, - ), + this.room.off(MatrixRoomEvent.Redaction, this.handleReactionEvent), ); - this.rtcSession.room.client.on( - MatrixEventEvent.Decrypted, - this.handleReactionEvent, - ); + this.client.on(MatrixEventEvent.Decrypted, this.handleReactionEvent); this.scope.onEnd(() => - this.rtcSession.room.client.off( - MatrixEventEvent.Decrypted, - this.handleReactionEvent, - ), + this.client.off(MatrixEventEvent.Decrypted, this.handleReactionEvent), ); // We listen for a local echo to get the real event ID, as timeline events // may still be sending. - this.rtcSession.room.on( - MatrixRoomEvent.LocalEchoUpdated, - this.handleReactionEvent, - ); + this.room.on(MatrixRoomEvent.LocalEchoUpdated, this.handleReactionEvent); this.scope.onEnd(() => - this.rtcSession.room.off( - MatrixRoomEvent.LocalEchoUpdated, - this.handleReactionEvent, - ), + this.room.off(MatrixRoomEvent.LocalEchoUpdated, this.handleReactionEvent), ); this.rtcSession.on( @@ -145,7 +151,7 @@ export class ReactionsReader { membershipEventId: string, expectedSender: string, ): MatrixEvent | undefined { - const relations = this.rtcSession.room.relations.getChildEventsForEvent( + const relations = this.room.relations.getChildEventsForEvent( membershipEventId, RelationType.Annotation, EventType.Reaction, @@ -235,9 +241,8 @@ export class ReactionsReader { * @param event The incoming matrix event, which may or may not be decrypted. */ private handleReactionEvent = (event: MatrixEvent): void => { - const room = this.rtcSession.room; // Decrypted events might come from a different room - if (event.getRoomId() !== room.roomId) return; + if (event.getRoomId() !== this.room.roomId) return; // Skip any events that are still sending. if (event.isSending()) return; @@ -246,7 +251,7 @@ export class ReactionsReader { // Skip any event without a sender or event ID. if (!sender || !reactionEventId) return; - room.client + this.client .decryptEventIfNeeded(event) .catch((e) => logger.warn(`Failed to decrypt ${event.getId()}`, e)); if (event.isBeingDecrypted() || event.isDecryptionFailure()) return; diff --git a/src/reactions/useReactionsSender.tsx b/src/reactions/useReactionsSender.tsx index 1b7e099a2..08510fc77 100644 --- a/src/reactions/useReactionsSender.tsx +++ b/src/reactions/useReactionsSender.tsx @@ -5,7 +5,12 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial Please see LICENSE in the repository root for full details. */ -import { EventType, RelationType } from "matrix-js-sdk"; +import { + EventType, + type MatrixClient, + RelationType, + type Room, +} from "matrix-js-sdk"; import { createContext, use, @@ -47,19 +52,32 @@ export const useReactionsSender = (): ReactionsSenderContextType => { export const ReactionsSenderProvider = ({ children, rtcSession, + room, + client, vm, }: { children: ReactNode; rtcSession: MatrixRTCSession; + /** The room the reactions are sent in. */ + room: Pick; + client: Pick< + MatrixClient, + // Our own membership, which the reactions relate to + | "getUserId" + | "getDeviceId" + // Sending reactions and raising a hand + | "sendEvent" + // Lowering a hand + | "redactEvent" + >; vm: CallViewModel; }): JSX.Element => { const memberships = useMatrixRTCSessionMemberships(rtcSession); const clientState = useClientState(); const supportsReactions = clientState?.state === "valid" && clientState.supportedFeatures.reactions; - const room = rtcSession.room; - const myUserId = room.client.getUserId(); - const myDeviceId = room.client.getDeviceId(); + const myUserId = client.getUserId(); + const myDeviceId = client.getDeviceId(); const myMembershipIdentifier = `${myUserId}:${myDeviceId}`; const myMembershipEvent = useMemo( @@ -99,8 +117,8 @@ export const ReactionsSenderProvider = ({ if (!myMembershipEvent) { throw new Error("Cannot find own membership event"); } - const reaction = await room.client.sendEvent( - rtcSession.room.roomId, + const reaction = await client.sendEvent( + room.roomId, EventType.Reaction, { "m.relates_to": { @@ -116,20 +134,14 @@ export const ReactionsSenderProvider = ({ } } else { try { - await room.client.redactEvent(rtcSession.room.roomId, myReactionId); + await client.redactEvent(room.roomId, myReactionId); logger.debug("Redacted raise hand event"); } catch (ex) { logger.error("Failed to redact reaction event", myReactionId, ex); throw ex; } } - }, [ - myMembershipEvent, - myMembershipIdentifier, - myRaisedHand, - rtcSession, - room, - ]); + }, [myMembershipEvent, myMembershipIdentifier, myRaisedHand, client, room]); const sendReaction = useCallback( async (reaction: ReactionOption) => { @@ -140,20 +152,16 @@ export const ReactionsSenderProvider = ({ if (!myMembershipEvent) { throw new Error("Cannot find own membership event"); } - await room.client.sendEvent( - rtcSession.room.roomId, - ElementCallReactionEventType, - { - "m.relates_to": { - rel_type: RelationType.Reference, - event_id: myMembershipEvent, - }, - emoji: reaction.emoji, - name: reaction.name, + await client.sendEvent(room.roomId, ElementCallReactionEventType, { + "m.relates_to": { + rel_type: RelationType.Reference, + event_id: myMembershipEvent, }, - ); + emoji: reaction.emoji, + name: reaction.name, + }); }, - [myMembershipEvent, myReaction, room, myMembershipIdentifier, rtcSession], + [myMembershipEvent, myReaction, client, room, myMembershipIdentifier], ); return ( diff --git a/src/room/CallView.tsx b/src/room/CallView.tsx index 2e165fa17..acd67dcf7 100644 --- a/src/room/CallView.tsx +++ b/src/room/CallView.tsx @@ -105,8 +105,13 @@ interface Props { | "baseUrl" // Homeserver connection (RTC slot): whether the client is syncing | "getSyncState" + // Reactions and raised hands: sending, lowering, and decrypting + | "sendEvent" + | "redactEvent" + | "decryptEventIfNeeded" // `on`/`off`, to listen for: // - `ClientEvent.Sync` (RTC slot homeserver connection) + // - `MatrixEventEvent.Decrypted` (reactions once decrypted) | "on" | "off" // Profile: display name and avatar, for the settings and the call ended view @@ -135,12 +140,16 @@ interface Props { | "getMembersWithMembership" // Call notifications, for the call view model | "_unstable_getStickyEvents" + // Raised hands already in the room, for the reactions reader + | "relations" // `on`/`off`, to listen for: // - `RoomEvent.Name` (room name) // - `RoomEvent.CurrentStateUpdated` (avatar and join rule hooks) // - `RoomStateEvent.Events` (RTC slot status) // - `RoomStateEvent.Members` (RTC slot and call view model members) // - `RoomEvent.Timeline` and `RoomStickyEventsEvent.Update` (call notifications) + // - `RoomEvent.Timeline`, `RoomEvent.Redaction` and + // `RoomEvent.LocalEchoUpdated` (reactions and raised hands) | "on" | "off" >; diff --git a/src/room/InCallView.test.tsx b/src/room/InCallView.test.tsx index f6bc938f6..96fe8f0c5 100644 --- a/src/room/InCallView.test.tsx +++ b/src/room/InCallView.test.tsx @@ -137,7 +137,7 @@ function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & { } { const mediaDevices = args.mediaDevices ?? mockMediaDevices({}); const muteState = mockMuteStates(); - const { vm, footerVm, developerSettingsVm, rtcSession } = + const { vm, footerVm, developerSettingsVm, rtcSession, matrixRoom, client } = getBasicCallViewModelEnvironment( [local, alice], undefined, @@ -146,8 +146,6 @@ function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & { ); rtcSession.joined = true; - const room = rtcSession.room; - const client = room.client; const inCallView = ( ); @@ -171,6 +169,8 @@ function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & { {content} diff --git a/src/room/InCallView.tsx b/src/room/InCallView.tsx index 941875726..0734457de 100644 --- a/src/room/InCallView.tsx +++ b/src/room/InCallView.tsx @@ -153,8 +153,13 @@ export interface ActiveCallProps extends Omit< | "baseUrl" // Homeserver connection (RTC slot): whether the client is syncing | "getSyncState" + // Reactions and raised hands: sending, lowering, and decrypting + | "sendEvent" + | "redactEvent" + | "decryptEventIfNeeded" // `on`/`off`, to listen for: // - `ClientEvent.Sync` (RTC slot homeserver connection) + // - `MatrixEventEvent.Decrypted` (reactions once decrypted) | "on" | "off" // Profile: display name and avatar, for the settings and the call ended view @@ -174,10 +179,14 @@ export interface ActiveCallProps extends Omit< | "getMembersWithMembership" // Call notifications, for the call view model | "_unstable_getStickyEvents" + // Raised hands already in the room, for the reactions reader + | "relations" // `on`/`off`, to listen for: // - `RoomStateEvent.Events` (RTC slot status) // - `RoomStateEvent.Members` (RTC slot and call view model members) // - `RoomEvent.Timeline` and `RoomStickyEventsEvent.Update` (call notifications) + // - `RoomEvent.Timeline`, `RoomEvent.Redaction` and + // `RoomEvent.LocalEchoUpdated` (reactions and raised hands) | "on" | "off" >; @@ -208,7 +217,12 @@ export const ActiveCall: FC = (props) => { useEffect(() => { rootLogger.info("START CALL VIEW SCOPE"); const scope = new ObservableScope(); - const reactionsReader = new ReactionsReader(scope, props.rtcSession); + const reactionsReader = new ReactionsReader( + scope, + props.rtcSession, + props.matrixRoom, + props.client, + ); const { autoLeaveWhenOthersLeft, waitForCallPickup, sendNotificationType } = urlParams; @@ -319,7 +333,12 @@ export const ActiveCall: FC = (props) => { if (developerSettingsVm === null) return null; return ( - + { // call has a title of its own. So it is set here, for whichever room we have // got as far as knowing about. const loadedRoom = - groupCallState.kind === "loaded" ? groupCallState.rtcSession.room : null; + groupCallState.kind === "loaded" ? groupCallState.room : null; const roomName = useRoomName(loadedRoom); usePageTitle( roomName ?? @@ -116,7 +116,7 @@ export const RoomPage: FC = (): ReactNode => { return ( => { + const fetchOrCreateGroupCall = async (): Promise< + Pick + > => { const room = await fetchOrCreateRoom(); activeRoom.current = room; logger.debug(`Fetched / joined room ${roomIdOrAlias}`); const rtcSession = client.matrixRTC.getRoomSession(room); - return rtcSession; + return { room, rtcSession }; }; const waitForClientSyncing = async (): Promise => { @@ -367,7 +370,9 @@ export const useLoadGroupCall = ( logger.log("Start loading group call"); waitForClientSyncing() .then(fetchOrCreateGroupCall) - .then((rtcSession) => setState({ kind: "loaded", rtcSession })) + .then(({ room, rtcSession }) => + setState({ kind: "loaded", room, rtcSession }), + ) .then(observeMyMembership) .catch((error) => setState({ kind: "failed", error })); } diff --git a/src/tile/GridTile.test.tsx b/src/tile/GridTile.test.tsx index 93f0fdaf5..7fce4d4c4 100644 --- a/src/tile/GridTile.test.tsx +++ b/src/tile/GridTile.test.tsx @@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial Please see LICENSE in the repository root for full details. */ -import { test, expect } from "vitest"; +import { test, expect, vi } from "vitest"; import { act, render, screen } from "@testing-library/react"; import { axe } from "vitest-axe"; import { @@ -39,18 +39,15 @@ global.IntersectionObserver = class MockIntersectionObserver { const fakeRtcSession = { on: () => {}, off: () => {}, - room: { - on: () => {}, - off: () => {}, - client: { - getUserId: () => null, - getDeviceId: () => null, - on: () => {}, - off: () => {}, - }, - }, memberships: [], } as unknown as MatrixRTCSession; +const fakeRoom = { roomId: "!room:example.org" }; +const fakeClient = { + getUserId: () => null, + getDeviceId: () => null, + sendEvent: vi.fn(), + redactEvent: vi.fn(), +}; const callVm = { reactions$: constant({}), @@ -68,7 +65,12 @@ test("GridTile displays remote media", async () => { ); const { container } = render( - + {}} @@ -99,7 +101,12 @@ test("GridTile displays local media", async () => { ); const { container } = render( - + {}} @@ -132,7 +139,12 @@ test("GridTile displays ringing media", async () => { }); const { container } = render( - + {}} diff --git a/src/utils/test-viewmodel.ts b/src/utils/test-viewmodel.ts index 04117346f..9a7b44526 100644 --- a/src/utils/test-viewmodel.ts +++ b/src/utils/test-viewmodel.ts @@ -53,7 +53,8 @@ export function getBasicRTCSession( initialRtcMemberships: CallMembership[] = [localRtcMember, aliceRtcMember], ): { rtcSession: MockRTCSession; - matrixRoom: Room; + room: Room; + client: MatrixClient; rtcMemberships$: BehaviorSubject; } { const matrixRoomId = "!myRoomId:example.com"; @@ -61,36 +62,37 @@ export function getBasicRTCSession( const roomEmitter = new EventEmitter(); const clientEmitter = new EventEmitter(); + const client = { + getUserId: () => localRtcMember.userId, + getDeviceId: () => localRtcMember.deviceId, + getSyncState: () => SyncState.Syncing, + getDomain: () => "example.com", + getAccessToken: () => "fake-token", + sendEvent: vitest.fn().mockResolvedValue({ event_id: "$fake:event" }), + redactEvent: vitest.fn().mockResolvedValue({ event_id: "$fake:event" }), + decryptEventIfNeeded: vitest.fn().mockResolvedValue(undefined), + on: vitest + .fn() + .mockImplementation( + (eventName: string, fn: (...args: unknown[]) => void) => { + clientEmitter.on(eventName, fn); + }, + ), + emit: (eventName: string, ...args: unknown[]) => + clientEmitter.emit(eventName, ...args), + off: vitest + .fn() + .mockImplementation( + (eventName: string, fn: (...args: unknown[]) => void) => { + clientEmitter.off(eventName, fn); + }, + ), + } as Partial as MatrixClient; const matrixRoom = mockMatrixRoom({ relations: { getChildEventsForEvent: vitest.fn(), } as Partial as RelationsContainer, - client: { - getUserId: () => localRtcMember.userId, - getDeviceId: () => localRtcMember.deviceId, - getSyncState: () => SyncState.Syncing, - getDomain: () => "example.com", - getAccessToken: () => "fake-token", - sendEvent: vitest.fn().mockResolvedValue({ event_id: "$fake:event" }), - redactEvent: vitest.fn().mockResolvedValue({ event_id: "$fake:event" }), - decryptEventIfNeeded: vitest.fn().mockResolvedValue(undefined), - on: vitest - .fn() - .mockImplementation( - (eventName: string, fn: (...args: unknown[]) => void) => { - clientEmitter.on(eventName, fn); - }, - ), - emit: (eventName: string, ...args: unknown[]) => - clientEmitter.emit(eventName, ...args), - off: vitest - .fn() - .mockImplementation( - (eventName: string, fn: (...args: unknown[]) => void) => { - clientEmitter.off(eventName, fn); - }, - ), - } as Partial as MatrixClient, + client, getMember: (userId) => matrixRoomMembers.get(userId) ?? null, getMembers: () => Array.from(matrixRoomMembers.values()), getMembersWithMembership: () => Array.from(matrixRoomMembers.values()), @@ -125,6 +127,7 @@ export function getBasicRTCSession( return { rtcSession: fakeRtcSession, matrixRoom, + client, rtcMemberships$, }; } @@ -146,13 +149,13 @@ export function getBasicCallViewModelEnvironment( developerSettingsVm: ViewModel; rtcMemberships$: BehaviorSubject; rtcSession: MockRTCSession; + matrixRoom: Room; + client: MatrixClient; handRaisedSubject$: BehaviorSubject>; reactionsSubject$: BehaviorSubject>; } { - const { rtcSession, matrixRoom, rtcMemberships$ } = getBasicRTCSession( - members, - initialRtcMemberships, - ); + const { rtcSession, matrixRoom, client, rtcMemberships$ } = + getBasicRTCSession(members, initialRtcMemberships); const handRaisedSubject$ = new BehaviorSubject({}); const reactionsSubject$ = new BehaviorSubject({}); @@ -199,7 +202,7 @@ export function getBasicCallViewModelEnvironment( { rtcParticipation, matrixRoom, - client: matrixRoom.client, + client, mediaDevices, muteStates, encryptionSystem: { kind: E2eeType.PER_PARTICIPANT }, @@ -230,6 +233,8 @@ export function getBasicCallViewModelEnvironment( developerSettingsVm: createDeveloperSettingsTabViewModel(testScope(), vm), rtcMemberships$, rtcSession, + matrixRoom, + client, handRaisedSubject$: handRaisedSubject$, reactionsSubject$: reactionsSubject$, };