From ca76e0f993d40552ce6cd84f724e729e47223ce6 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Tue, 8 Sep 2026 19:29:00 +0200 Subject: [PATCH] fix(call): grant the widget MSC4407 sticky-event capabilities The embedded call widget publishes its MatrixRTC membership as a sticky event, which ClientWidgetApi refuses without org.matrix.msc4407.send.sticky_event. The MembershipManager then shut down and the call dropped. Grant the send and receive capabilities and implement sendStickyEvent, sendDelayedStickyEvent and readStickyEvents on CallWidgetDriver. Also register an MSC4480 sticky_events extension on sliding sync, since matrix-js-sdk only reads sticky events out of /sync v2. --- .changeset/fix-call-sticky-memberships.md | 5 + .../call/CallWidgetDriver.sticky.test.ts | 76 ++++++++++ src/app/plugins/call/CallWidgetDriver.ts | 53 +++++++ src/app/plugins/call/utils.test.ts | 7 + src/app/plugins/call/utils.ts | 2 + src/client/slidingSync.ts | 8 + src/client/stickyEvents.test.ts | 142 ++++++++++++++++++ src/client/stickyEvents.ts | 102 +++++++++++++ 8 files changed, 395 insertions(+) create mode 100644 .changeset/fix-call-sticky-memberships.md create mode 100644 src/app/plugins/call/CallWidgetDriver.sticky.test.ts create mode 100644 src/client/stickyEvents.test.ts create mode 100644 src/client/stickyEvents.ts diff --git a/.changeset/fix-call-sticky-memberships.md b/.changeset/fix-call-sticky-memberships.md new file mode 100644 index 000000000..c9c72c53f --- /dev/null +++ b/.changeset/fix-call-sticky-memberships.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix calls disconnecting on servers that use sticky memberships: the call now has permission to publish them, and sticky memberships also reach clients that sync with sliding sync. diff --git a/src/app/plugins/call/CallWidgetDriver.sticky.test.ts b/src/app/plugins/call/CallWidgetDriver.sticky.test.ts new file mode 100644 index 000000000..62f8ec5f8 --- /dev/null +++ b/src/app/plugins/call/CallWidgetDriver.sticky.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; +import { CallWidgetDriver } from './CallWidgetDriver'; + +const roomId = '!room:example.org'; +const userId = '@alice:example.org'; +const deviceId = 'ALICEDEVICE'; + +const membership = { member: { id: `${userId}:${deviceId}` }, msc4354_sticky_key: 'key' }; + +const makeClient = (overrides: Partial> = {}) => + ({ + getDeviceId: () => deviceId, + getSafeUserId: () => userId, + getRoom: () => null, + ...overrides, + }) as unknown as MatrixClient; + +describe('CallWidgetDriver sticky events', () => { + it('sends a sticky event with its duration', async () => { + const sendSticky = vi + .fn<() => Promise<{ event_id: string }>>() + .mockResolvedValue({ event_id: '$sticky' }); + const driver = new CallWidgetDriver( + makeClient({ _unstable_sendStickyEvent: sendSticky }), + roomId + ); + + await expect( + driver.sendStickyEvent(3_600_000, 'org.matrix.msc4143.rtc.member', membership) + ).resolves.toEqual({ roomId, eventId: '$sticky' }); + expect(sendSticky).toHaveBeenCalledWith( + roomId, + 3_600_000, + null, + 'org.matrix.msc4143.rtc.member', + membership + ); + }); + + it('sends a delayed sticky event', async () => { + const sendDelayedSticky = vi + .fn<() => Promise<{ delay_id: string }>>() + .mockResolvedValue({ delay_id: 'delay-1' }); + const driver = new CallWidgetDriver( + makeClient({ _unstable_sendStickyDelayedEvent: sendDelayedSticky }), + roomId + ); + + await expect( + driver.sendDelayedStickyEvent(8_000, 3_600_000, 'org.matrix.msc4143.rtc.member', membership) + ).resolves.toEqual({ roomId, delayId: 'delay-1' }); + expect(sendDelayedSticky).toHaveBeenCalledWith( + roomId, + 3_600_000, + { delay: 8_000 }, + null, + 'org.matrix.msc4143.rtc.member', + membership + ); + }); + + it('reads the sticky events of a room', async () => { + const event = { getEffectiveEvent: () => ({ event_id: '$one' }) } as unknown as MatrixEvent; + const room = { _unstable_getStickyEvents: () => [event] } as unknown as Room; + const driver = new CallWidgetDriver(makeClient({ getRoom: () => room }), roomId); + + await expect(driver.readStickyEvents(roomId)).resolves.toEqual([{ event_id: '$one' }]); + }); + + it('returns nothing for an unknown room', async () => { + const driver = new CallWidgetDriver(makeClient(), roomId); + + await expect(driver.readStickyEvents(roomId)).resolves.toEqual([]); + }); +}); diff --git a/src/app/plugins/call/CallWidgetDriver.ts b/src/app/plugins/call/CallWidgetDriver.ts index bf9faac08..ac357d6ec 100644 --- a/src/app/plugins/call/CallWidgetDriver.ts +++ b/src/app/plugins/call/CallWidgetDriver.ts @@ -175,6 +175,59 @@ export class CallWidgetDriver extends WidgetDriver { }; } + public async sendStickyEvent( + stickyDurationMs: number, + eventType: string, + content: IContent, + targetRoomId: string | null = null + ): Promise { + const client = this.mx; + const roomId = targetRoomId || this.inRoomId; + + if (!client || !roomId) throw new Error('Not in a room or not attached to a client'); + + const r = await client._unstable_sendStickyEvent( + roomId, + stickyDurationMs, + null, + eventType as keyof TimelineEvents, + content as TimelineEvents[keyof TimelineEvents] + ); + + return { roomId, eventId: r.event_id }; + } + + public async sendDelayedStickyEvent( + delay: number, + stickyDurationMs: number, + eventType: string, + content: IContent, + targetRoomId: string | null = null + ): Promise { + const client = this.mx; + const roomId = targetRoomId || this.inRoomId; + + if (!client || !roomId) throw new Error('Not in a room or not attached to a client'); + + const r = await client._unstable_sendStickyDelayedEvent( + roomId, + stickyDurationMs, + { delay }, + null, + eventType as keyof TimelineEvents, + content as TimelineEvents[keyof TimelineEvents] + ); + + return { roomId, delayId: r.delay_id }; + } + + public async readStickyEvents(roomId: string): Promise { + const room = this.mx.getRoom(roomId); + if (room === null) return []; + + return [...room._unstable_getStickyEvents()].map((e) => e.getEffectiveEvent() as IRoomEvent); + } + public async updateDelayedEvent( delayId: string, action: UpdateDelayedEventAction diff --git a/src/app/plugins/call/utils.test.ts b/src/app/plugins/call/utils.test.ts index 116466b71..496cbacec 100644 --- a/src/app/plugins/call/utils.test.ts +++ b/src/app/plugins/call/utils.test.ts @@ -14,6 +14,13 @@ describe('getCallCapabilities', () => { expect(capabilities.has(MatrixCapabilities.MSC4157UpdateDelayedEvent)).toBe(true); }); + it('includes sticky-event capabilities', () => { + const capabilities = getCallCapabilities(roomId, userId, deviceId); + + expect(capabilities.has(MatrixCapabilities.MSC4407SendStickyEvent)).toBe(true); + expect(capabilities.has(MatrixCapabilities.MSC4407ReceiveStickyEvent)).toBe(true); + }); + it('includes upload and download media capabilities', () => { const capabilities = getCallCapabilities(roomId, userId, deviceId); diff --git a/src/app/plugins/call/utils.ts b/src/app/plugins/call/utils.ts index b61f87aa9..cccb725b4 100644 --- a/src/app/plugins/call/utils.ts +++ b/src/app/plugins/call/utils.ts @@ -20,6 +20,8 @@ export function getCallCapabilities( capabilities.add(MatrixCapabilities.MSC4039DownloadFile); capabilities.add(MatrixCapabilities.MSC4157SendDelayedEvent); capabilities.add(MatrixCapabilities.MSC4157UpdateDelayedEvent); + capabilities.add(MatrixCapabilities.MSC4407SendStickyEvent); + capabilities.add(MatrixCapabilities.MSC4407ReceiveStickyEvent); capabilities.add('moe.sable.thumbnails'); capabilities.add('moe.sable.media_proxy'); capabilities.add(`org.matrix.msc2762.timeline:${roomId}`); diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index c1923ff83..ef5ebfa98 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -32,6 +32,7 @@ import { createDebugLogger } from '$utils/debugLogger'; import { CustomStateEvent } from '$types/matrix/room'; import * as Sentry from '@sentry/react'; import { SlidingSyncSidebarCache } from './slidingSyncSidebarCache'; +import { forwardTimelineStickyEvents, StickyEventsExtension } from './stickyEvents'; import { markPreprocessingSlidingSyncTimelineReset } from './slidingSyncTimelineReset'; const log = createLogger('slidingSync'); @@ -612,6 +613,8 @@ export class SlidingSyncManager { private hydratingSidebarCache = false; + private detachStickyEvents: (() => void) | undefined; + private readonly onCacheRoomData: (roomId: string, data: MSC3575RoomData) => void; private readonly onCacheAccountData: (event: MatrixEvent) => void; @@ -773,6 +776,8 @@ export class SlidingSyncManager { buildSpaceImagePackSubscription() ); + this.slidingSync.registerExtension(new StickyEventsExtension(mx)); + this.onLifecycle = (state, resp, err) => { debugLog.info('sync', `Sliding sync lifecycle: ${state}`, { state, @@ -994,6 +999,7 @@ export class SlidingSyncManager { this.slidingSync.on(SlidingSyncEvent.RoomData, this.onCacheRoomData); this.mx.on(RoomMemberEvent.Membership, this.onMembershipLeave); this.mx.on(ClientEvent.AccountData, this.onCacheAccountData); + this.detachStickyEvents = forwardTimelineStickyEvents(this.mx); this.armPollWatchdog(); @@ -1167,6 +1173,8 @@ export class SlidingSyncManager { this.cacheHydrationResolve = undefined; this.mx.removeListener(RoomMemberEvent.Membership, this.onMembershipLeave); this.mx.removeListener(ClientEvent.AccountData, this.onCacheAccountData); + this.detachStickyEvents?.(); + this.detachStickyEvents = undefined; this.sidebarCache.dispose(); debugLog.info('sync', 'Sliding sync disposed successfully', { diff --git a/src/client/stickyEvents.test.ts b/src/client/stickyEvents.test.ts new file mode 100644 index 000000000..3a6a9a098 --- /dev/null +++ b/src/client/stickyEvents.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { MatrixClient, Room } from '$types/matrix-sdk'; +import { MatrixEvent, RoomEvent } from '$types/matrix-sdk'; +import { forwardTimelineStickyEvents, StickyEventsExtension } from './stickyEvents'; + +const roomId = '!room:example.com'; +const userId = '@user:example.com'; + +const eventJson = (eventId: string, sticky = true) => ({ + type: 'm.rtc.member', + event_id: eventId, + sender: userId, + origin_server_ts: Date.now(), + content: { msc4354_sticky_key: `${userId}:DEVICE` }, + ...(sticky ? { msc4354_sticky: { duration_ms: 60_000 } } : {}), +}); + +const makeRoom = (existing: MatrixEvent[] = []) => { + const added: MatrixEvent[][] = []; + const room = { + roomId, + _unstable_getStickyEvents: () => existing, + _unstable_addStickyEvents: (events: MatrixEvent[]) => added.push(events), + } as unknown as Room; + return { room, added }; +}; + +const makeClient = (room: Room | undefined, supported = true) => + ({ + getRoom: () => room, + getEventMapper: () => (event: Record) => new MatrixEvent(event), + doesServerSupportUnstableFeature: vi.fn<() => Promise>().mockResolvedValue(supported), + }) as unknown as MatrixClient; + +describe('StickyEventsExtension', () => { + it('stays disabled when the server does not support MSC4354', async () => { + const extension = new StickyEventsExtension(makeClient(undefined, false)); + expect(await extension.onRequest(true)).toEqual({ enabled: false }); + }); + + it('enables itself and threads the since token', async () => { + const extension = new StickyEventsExtension(makeClient(makeRoom().room)); + + expect(await extension.onRequest(true)).toEqual({ enabled: true, limit: 100 }); + + await extension.onResponse({ next_batch: '42' }); + expect(await extension.onRequest(false)).toEqual({ enabled: true, limit: 100, since: '42' }); + + expect(await extension.onRequest(true)).toEqual({ enabled: true, limit: 100 }); + }); + + it('feeds sticky events into the room store', async () => { + const { room, added } = makeRoom(); + const extension = new StickyEventsExtension(makeClient(room)); + + await extension.onResponse({ + rooms: { [roomId]: { events: [eventJson('$one'), eventJson('$two')] } }, + }); + + expect(added).toHaveLength(1); + expect(added[0]?.map((event) => event.getId())).toEqual(['$one', '$two']); + expect(added[0]?.[0]?.getRoomId()).toBe(roomId); + }); + + it('ignores events the server did not mark sticky', async () => { + const { room, added } = makeRoom(); + const extension = new StickyEventsExtension(makeClient(room)); + + await extension.onResponse({ + rooms: { [roomId]: { events: [eventJson('$plain', false)] } }, + }); + + expect(added).toHaveLength(0); + }); + + it('does not re-add an event the store already holds', async () => { + const known = new MatrixEvent(eventJson('$one')); + const { room, added } = makeRoom([known]); + const extension = new StickyEventsExtension(makeClient(room)); + + await extension.onResponse({ + rooms: { [roomId]: { events: [eventJson('$one'), eventJson('$two')] } }, + }); + + expect(added).toHaveLength(1); + expect(added[0]?.map((event) => event.getId())).toEqual(['$two']); + }); +}); + +const makeEmitter = () => { + const listeners = new Set<(...args: unknown[]) => void>(); + const mx = { + on: (_event: string, listener: (...args: unknown[]) => void) => listeners.add(listener), + removeListener: (_event: string, listener: (...args: unknown[]) => void) => + listeners.delete(listener), + } as unknown as MatrixClient; + const emit = (...args: unknown[]) => listeners.forEach((listener) => listener(...args)); + return { mx, emit, listeners }; +}; + +describe('forwardTimelineStickyEvents', () => { + it('forwards live sticky timeline events to the room store', () => { + const { room, added } = makeRoom(); + const { mx, emit } = makeEmitter(); + forwardTimelineStickyEvents(mx); + + emit(new MatrixEvent(eventJson('$one')), room, false); + + expect(added).toHaveLength(1); + expect(added[0]?.[0]?.getId()).toBe('$one'); + }); + + it('ignores back-paginated and non-sticky events', () => { + const { room, added } = makeRoom(); + const { mx, emit } = makeEmitter(); + forwardTimelineStickyEvents(mx); + + emit(new MatrixEvent(eventJson('$one')), room, true); + emit(new MatrixEvent(eventJson('$two', false)), room, false); + + expect(added).toHaveLength(0); + }); + + it('stops forwarding once detached', () => { + const { room, added } = makeRoom(); + const { mx, emit, listeners } = makeEmitter(); + const detach = forwardTimelineStickyEvents(mx); + + detach(); + expect(listeners.size).toBe(0); + emit(new MatrixEvent(eventJson('$one')), room, false); + + expect(added).toHaveLength(0); + }); + + it('registers on the timeline event', () => { + const on = vi.fn<(event: string, listener: () => void) => void>(); + const removeListener = vi.fn<(event: string, listener: () => void) => void>(); + forwardTimelineStickyEvents({ on, removeListener } as unknown as MatrixClient); + expect(on).toHaveBeenCalledWith(RoomEvent.Timeline, expect.any(Function)); + }); +}); diff --git a/src/client/stickyEvents.ts b/src/client/stickyEvents.ts new file mode 100644 index 000000000..d751fb922 --- /dev/null +++ b/src/client/stickyEvents.ts @@ -0,0 +1,102 @@ +import type { Extension, IRoomEvent, MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; +import { ExtensionState, RoomEvent, UNSTABLE_MSC4354_STICKY_EVENTS } from '$types/matrix-sdk'; +import { createDebugLogger } from '$utils/debugLogger'; + +const debugLog = createDebugLogger('slidingSync'); + +const STICKY_EVENTS_EXTENSION = 'org.matrix.msc4354.sticky_events'; +const STICKY_EVENTS_LIMIT = 100; + +type StickyEventsRequest = { + enabled: boolean; + limit?: number; + since?: string; +}; + +type StickyEventsResponse = { + next_batch?: string; + rooms?: Record; +}; + +const isSticky = (event: MatrixEvent): boolean => event.unstableStickyInfo !== undefined; + +const rejectKnownStickyEvents = (room: Room, events: MatrixEvent[]): MatrixEvent[] => { + const known = new Set(); + for (const event of room._unstable_getStickyEvents()) { + const eventId = event.getId(); + if (eventId) known.add(eventId); + } + return events.filter((event) => { + const eventId = event.getId(); + return !eventId || !known.has(eventId); + }); +}; + +export const addStickyEvents = (room: Room, events: MatrixEvent[]): void => { + const sticky = rejectKnownStickyEvents(room, events.filter(isSticky)); + if (sticky.length === 0) return; + room._unstable_addStickyEvents(sticky); +}; + +export class StickyEventsExtension implements Extension { + private since: string | undefined; + + private serverSupport: Promise | undefined; + + public constructor(private readonly mx: MatrixClient) {} + + public name(): string { + return STICKY_EVENTS_EXTENSION; + } + + public when(): ExtensionState { + return ExtensionState.PostProcess; + } + + private supported(): Promise { + this.serverSupport ??= this.mx + .doesServerSupportUnstableFeature(UNSTABLE_MSC4354_STICKY_EVENTS) + .catch(() => false); + return this.serverSupport; + } + + public async onRequest(isInitial: boolean): Promise { + if (isInitial) this.since = undefined; + if (!(await this.supported())) return { enabled: false }; + return { + enabled: true, + limit: STICKY_EVENTS_LIMIT, + ...(this.since ? { since: this.since } : {}), + }; + } + + public async onResponse(data: StickyEventsResponse): Promise { + if (!data) return; + if (data.next_batch) this.since = data.next_batch; + + const mapper = this.mx.getEventMapper(); + for (const [roomId, roomData] of Object.entries(data.rooms ?? {})) { + const room = this.mx.getRoom(roomId); + if (!room) { + debugLog.warn('sync', `sticky events for unknown room ${roomId}`); + continue; + } + const events = (roomData.events ?? []).map((event) => mapper({ ...event, room_id: roomId })); + addStickyEvents(room, events); + } + } +} + +export const forwardTimelineStickyEvents = (mx: MatrixClient): (() => void) => { + const onTimeline = ( + event: MatrixEvent, + room: Room | undefined, + toStartOfTimeline: boolean | undefined + ) => { + if (!room || toStartOfTimeline || !isSticky(event)) return; + addStickyEvents(room, [event]); + }; + + mx.on(RoomEvent.Timeline, onTimeline); + return () => mx.removeListener(RoomEvent.Timeline, onTimeline); +};