From 2a63f596fe4a129f1ce4488f65abe52bdd434720 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 15:20:51 -0400 Subject: [PATCH 01/28] fix(threads): thread drawer empty with classic sync MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With classic sync, RoomViewHeader creates Thread objects via room.createThread(id, rootEvent, [], false) — passing no initialEvents. This means thread.events starts as just [rootEvent] (or empty). Two bugs resulted: 1. The gate `if (fromThread.length > 0)` blocked the live-timeline fallback. Since thread.events = [rootEvent], length was 1 (truthy), but after filtering the root out the array was empty — yielding zero replies even though the events were present in the main room timeline. Fix: compute the filtered array first, then gate on its length so the fallback is reached when the thread object has no actual replies yet. 2. Even after #1, subsequent renders and read-receipt logic used thread.events (empty) rather than the live timeline. Fix: add a mount-time useEffect that backfills matching events from the unfiltered live timeline into the Thread object via thread.addEvents() so the authoritative source is populated for future interactions. --- src/app/features/room/ThreadDrawer.tsx | 39 ++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index 00957bc3..3a9d6bb9 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -398,6 +398,33 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra const rootEvent = room.findEventById(threadRootId); + // When the drawer is opened with classic sync, room.createThread() may have + // been called with empty initialEvents so thread.events only has the root. + // Backfill events from the main room timeline into the Thread object so the + // authoritative source is populated for subsequent renders and receipts. + useEffect(() => { + const thread = room.getThread(threadRootId); + if (!thread) return; + const hasRepliesInThread = thread.events.some( + (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + ); + if (hasRepliesInThread) return; // already populated, nothing to do + + const liveEvents = room + .getUnfilteredTimelineSet() + .getLiveTimeline() + .getEvents() + .filter( + (ev) => + ev.threadRootId === threadRootId && + ev.getId() !== threadRootId && + !reactionOrEditEvent(ev) + ); + if (liveEvents.length > 0) { + thread.addEvents(liveEvents, false); + } + }, [room, threadRootId]); + // Re-render when new thread events arrive (including reactions via ThreadEvent.Update). useEffect(() => { const isEventInThread = (mEvent: MatrixEvent): boolean => { @@ -484,11 +511,19 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra // Use the Thread object if available (authoritative source with full history). // Fall back to scanning the live room timeline for local echoes and the // window before the Thread object is registered by the SDK. + // NOTE: With classic sync the Thread object is created via room.createThread() + // with empty initialEvents, so thread.events may only contain the root event. + // We must filter first, then decide whether to fall back — otherwise a thread + // whose events array consists solely of the root event (length === 1) prevents + // the live-timeline fallback from running, and the drawer shows nothing. const replyEvents: MatrixEvent[] = (() => { const thread = room.getThread(threadRootId); const fromThread = thread?.events ?? []; - if (fromThread.length > 0) { - return fromThread.filter((ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)); + const filteredFromThread = fromThread.filter( + (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + ); + if (filteredFromThread.length > 0) { + return filteredFromThread; } return room .getUnfilteredTimelineSet() From 86bdb80816621d7edbbd1935f942cc21d140be7e Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 15:43:31 -0400 Subject: [PATCH 02/28] refactor+test(threads): extract getThreadReplyEvents and add unit tests Extract the replyEvents IIFE into a module-level function so the fix-first- then-check-length logic can be exercised in isolated unit tests without mounting the full component. Tests cover: - Returns thread.events (minus root) when the Thread object has replies. - Excludes reactions (RelationType.Annotation) from the results. - Classic-sync regression: thread.events = [rootEvent] => falls back to the live room timeline (the bug was that length-1 thread blocked the fallback). - Falls back to live timeline when getThread() returns null. - Filters out events belonging to a different thread. - Returns [] when neither source has relevant events. --- .changeset/fix-thread-classic-sync.md | 5 + src/app/features/room/ThreadDrawer.test.ts | 155 +++++++++++++++++++++ src/app/features/room/ThreadDrawer.tsx | 59 ++++---- 3 files changed, 191 insertions(+), 28 deletions(-) create mode 100644 .changeset/fix-thread-classic-sync.md create mode 100644 src/app/features/room/ThreadDrawer.test.ts diff --git a/.changeset/fix-thread-classic-sync.md b/.changeset/fix-thread-classic-sync.md new file mode 100644 index 00000000..bb8cda0b --- /dev/null +++ b/.changeset/fix-thread-classic-sync.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix thread drawer showing no messages when using classic sync. diff --git a/src/app/features/room/ThreadDrawer.test.ts b/src/app/features/room/ThreadDrawer.test.ts new file mode 100644 index 00000000..ef786348 --- /dev/null +++ b/src/app/features/room/ThreadDrawer.test.ts @@ -0,0 +1,155 @@ +/** + * Unit tests for getThreadReplyEvents — the function that decides which events + * to display as replies in the thread drawer. + * + * The bug these tests cover (classic-sync empty thread): + * room.createThread(id, root, [], false) creates a Thread whose .events array + * contains only the root event. After filtering out the root, the old code + * checked `if (fromThread.length > 0)` on the un-filtered array — which was + * truthy — and returned an empty list instead of falling back to the live + * timeline. The fix: filter first, then check. + */ +import { describe, it, expect } from 'vitest'; +import { RelationType } from '$types/matrix-sdk'; +import { getThreadReplyEvents } from './ThreadDrawer'; + +// ── Minimal MatrixEvent factory ─────────────────────────────────────────────── + +type EventInit = { + id: string; + threadRootId?: string; + /** When set, the event is treated as a reaction/annotation */ + relType?: string; +}; + +function makeEvent({ id, threadRootId, relType }: EventInit) { + return { + getId: () => id, + threadRootId, + getRelation: () => (relType ? { rel_type: relType } : null), + getContent: () => ({}), + }; +} + +// ── Minimal Room factory ────────────────────────────────────────────────────── + +type RoomInit = { + thread?: { events: ReturnType[] } | null; + liveEvents?: ReturnType[]; +}; + +function makeRoom({ thread = null, liveEvents = [] }: RoomInit) { + return { + getThread: () => thread, + getUnfilteredTimelineSet: () => ({ + getLiveTimeline: () => ({ + getEvents: () => liveEvents, + }), + }), + }; +} + +// ── Tests ───────────────────────────────────────────────────────────────────── + +const ROOT_ID = '$root-event-id'; +const REPLY_ID = '$reply-event-id'; +const REACTION_ID = '$reaction-event-id'; + +describe('getThreadReplyEvents', () => { + it('returns thread events minus the root when the Thread object has replies', () => { + const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID }); + const replyEvent = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + + const room = makeRoom({ + thread: { events: [rootEvent, replyEvent] as any }, + liveEvents: [], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + expect(result).toHaveLength(1); + expect(result[0].getId()).toBe(REPLY_ID); + }); + + it('excludes reactions from thread events', () => { + const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID }); + const replyEvent = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + const reactionEvent = makeEvent({ + id: REACTION_ID, + threadRootId: ROOT_ID, + relType: RelationType.Annotation, + }); + + const room = makeRoom({ + thread: { events: [rootEvent, replyEvent, reactionEvent] as any }, + liveEvents: [], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + expect(result).toHaveLength(1); + expect(result[0].getId()).toBe(REPLY_ID); + }); + + // ── Classic-sync empty-thread regression ────────────────────────────────── + + it('falls back to the live timeline when thread.events contains only the root (classic-sync case)', () => { + // classic sync: thread created with no initialEvents → events = [rootEvent] + const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID }); + const liveReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + + const room = makeRoom({ + thread: { events: [rootEvent] as any }, + liveEvents: [liveReply as any], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + // Without the fix: `fromThread.length > 0` was truthy → returned filtered + // empty array. With the fix: filtered array is empty → falls back to live. + expect(result).toHaveLength(1); + expect(result[0].getId()).toBe(REPLY_ID); + }); + + it('falls back to the live timeline when there is no Thread object at all', () => { + const liveReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + + const room = makeRoom({ + thread: null, + liveEvents: [liveReply as any], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + expect(result).toHaveLength(1); + expect(result[0].getId()).toBe(REPLY_ID); + }); + + it('excludes events from the live timeline that belong to a different thread', () => { + const otherReply = makeEvent({ id: '$other-reply', threadRootId: '$other-root' }); + const ourReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + + const room = makeRoom({ + thread: null, + liveEvents: [otherReply as any, ourReply as any], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + expect(result).toHaveLength(1); + expect(result[0].getId()).toBe(REPLY_ID); + }); + + it('returns an empty array when neither the thread nor the live timeline has replies', () => { + const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID }); + + const room = makeRoom({ + thread: { events: [rootEvent] as any }, + liveEvents: [], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + expect(result).toHaveLength(0); + }); +}); diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index 3a9d6bb9..23ef1ff0 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -54,6 +54,36 @@ import { RoomInput } from './RoomInput'; import { RoomViewFollowing, RoomViewFollowingPlaceholder } from './RoomViewFollowing'; import * as css from './ThreadDrawer.css'; +/** + * Resolve the list of reply events to show in the thread drawer. + * + * Prefers events from the SDK Thread object (authoritative, full history) but + * falls back to scanning the main room timeline when the Thread object was + * created without `initialEvents` (as happens with classic sync). In that + * case `thread.events` contains only the root event, so filtering it yields an + * empty array — we must fall back rather than showing nothing. + * + * Exported for unit testing. + */ +export function getThreadReplyEvents(room: Room, threadRootId: string): MatrixEvent[] { + const thread = room.getThread(threadRootId); + const fromThread = thread?.events ?? []; + const filteredFromThread = fromThread.filter( + (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + ); + if (filteredFromThread.length > 0) { + return filteredFromThread; + } + return room + .getUnfilteredTimelineSet() + .getLiveTimeline() + .getEvents() + .filter( + (ev) => + ev.threadRootId === threadRootId && ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + ); +} + type ForwardedMessageProps = { isForwarded: boolean; originalTimestamp: number; @@ -508,34 +538,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra markThreadAsRead(); }, [mx, room, threadRootId, forceUpdate]); - // Use the Thread object if available (authoritative source with full history). - // Fall back to scanning the live room timeline for local echoes and the - // window before the Thread object is registered by the SDK. - // NOTE: With classic sync the Thread object is created via room.createThread() - // with empty initialEvents, so thread.events may only contain the root event. - // We must filter first, then decide whether to fall back — otherwise a thread - // whose events array consists solely of the root event (length === 1) prevents - // the live-timeline fallback from running, and the drawer shows nothing. - const replyEvents: MatrixEvent[] = (() => { - const thread = room.getThread(threadRootId); - const fromThread = thread?.events ?? []; - const filteredFromThread = fromThread.filter( - (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev) - ); - if (filteredFromThread.length > 0) { - return filteredFromThread; - } - return room - .getUnfilteredTimelineSet() - .getLiveTimeline() - .getEvents() - .filter( - (ev) => - ev.threadRootId === threadRootId && - ev.getId() !== threadRootId && - !reactionOrEditEvent(ev) - ); - })(); + const replyEvents = getThreadReplyEvents(room, threadRootId); replyEventsRef.current = replyEvents; From cc8bad2853a089c4c9a9f11af3c7361538836007 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 15:21:52 -0400 Subject: [PATCH 03/28] fix(threads): reduce dead space around root message in thread drawer The root message section had two sources of excess whitespace: 1. hideTrack={false} forced a visible scrollbar gutter on the Scroll component even when the message fit within the 200px max-height and no scrolling was needed. Changed to hideTrack (default true = hidden) so the gutter only appears when actually scrollable. 2. padding: S400 0 S200 0 (16px top / 8px bottom) on the root message box was adding significant dead space above the message content that compounds with the Message component's own internal padding. Reduced to S200 0 S100 0 (8px top / 4px bottom). --- src/app/features/room/ThreadDrawer.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index 00957bc3..e4bf2625 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -722,7 +722,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra variant="Background" visibility="Hover" direction="Vertical" - hideTrack={false} + hideTrack style={{ maxHeight: '200px', height: 'fit-content', @@ -733,7 +733,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra className={css.messageList} direction="Column" style={{ - padding: `${config.space.S400} 0 ${config.space.S200} 0`, + padding: `${config.space.S200} 0 ${config.space.S100} 0`, }} > From 8dba3afe85228815a5d014b9b180ab938b54d2f0 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 15:43:36 -0400 Subject: [PATCH 04/28] chore(threads): add changeset for thread drawer spacing fix --- .changeset/fix-thread-ui-spacing.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix-thread-ui-spacing.md diff --git a/.changeset/fix-thread-ui-spacing.md b/.changeset/fix-thread-ui-spacing.md new file mode 100644 index 00000000..445ff082 --- /dev/null +++ b/.changeset/fix-thread-ui-spacing.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Reduce dead space around the root message in the thread drawer. From 3f26cd9515ed99c647d3d29c3b531fbceb8b1354 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 17:56:24 -0400 Subject: [PATCH 05/28] fix: hide ThreadIndicator badge inside ThreadDrawer compose box Inside the ThreadDrawer the user is already in thread context, so showing the "Thread" badge in the reply chip is redundant and visually noisy. The compose box always sets replyDraft.relation.rel_type = RelationType.Thread when threadRootId is set (so the message goes to the right thread), but that should not make the ThreadIndicator visible there. Add !threadRootId guard to the ThreadIndicator render condition. Adds 4 unit tests covering the four branches of the condition. --- .../message/ThreadIndicator.test.tsx | 43 +++++++++++++++++++ src/app/features/room/RoomInput.tsx | 2 +- 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 src/app/components/message/ThreadIndicator.test.tsx diff --git a/src/app/components/message/ThreadIndicator.test.tsx b/src/app/components/message/ThreadIndicator.test.tsx new file mode 100644 index 00000000..d06e1f15 --- /dev/null +++ b/src/app/components/message/ThreadIndicator.test.tsx @@ -0,0 +1,43 @@ +/** + * Tests for the ThreadIndicator visibility condition in the compose strip. + * + * The indicator renders when a user is replying to a thread message from the + * main timeline (no threadRootId). It must NOT appear when composing inside + * the ThreadDrawer (threadRootId is set), because the drawer already makes the + * thread context obvious. + * + * Mirrors the exact render guard in RoomInput.tsx: + * {replyDraft.relation?.rel_type === RelationType.Thread && !threadRootId && ( + * + * )} + */ +import { describe, it, expect } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { RelationType } from '$types/matrix-sdk'; +import { ThreadIndicator } from './Reply'; + +function Subject({ relType, threadRootId }: { relType?: string; threadRootId?: string }) { + return <>{relType === RelationType.Thread && !threadRootId && }; +} + +describe('ThreadIndicator visibility in compose strip', () => { + it('renders in the main timeline compose box when a thread relation is active', () => { + render(); + expect(screen.getByText('Thread')).toBeInTheDocument(); + }); + + it('is hidden inside the ThreadDrawer when threadRootId is set', () => { + render(); + expect(screen.queryByText('Thread')).not.toBeInTheDocument(); + }); + + it('is hidden when the draft has no relation', () => { + render(); + expect(screen.queryByText('Thread')).not.toBeInTheDocument(); + }); + + it('is hidden for a non-thread relation type', () => { + render(); + expect(screen.queryByText('Thread')).not.toBeInTheDocument(); + }); +}); diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 60ee8d20..6eec4209 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -1126,7 +1126,7 @@ export const RoomInput = forwardRef( grow="Yes" style={{ minWidth: 0 }} > - {replyDraft.relation?.rel_type === RelationType.Thread && ( + {replyDraft.relation?.rel_type === RelationType.Thread && !threadRootId && ( )} Date: Tue, 17 Mar 2026 17:57:04 -0400 Subject: [PATCH 06/28] fix: stop sliding sync on dispose and prune inactive room timelines Two memory management issues fixed: 1. SlidingSyncManager.dispose() now calls this.slidingSync.stop() before removing listeners. Without this the SDK's internal Promise loop keeps polling the sliding sync proxy even after the client is disposed, leaking network connections and preventing garbage collection. 2. pruneRoomTimeline() is called from unsubscribeFromRoom(). When a room leaves the active subscription its EventTimeline chain can hold hundreds of events in memory. Once the event count exceeds PRUNE_TIMELINE_THRESHOLD (= ACTIVE_ROOM_TIMELINE_LIMIT_HIGH = 150) the live timeline is reset via EventTimelineSet.resetLiveTimeline(). The full history remains on disk in IndexedDBStore and is re-fetched via the active-room subscription on next open, so there is no user-visible change. Adds 5 unit tests: 1 for dispose, 4 for the pruning threshold boundary. --- src/client/slidingSync.test.ts | 151 +++++++++++++++++++++++++++++++++ src/client/slidingSync.ts | 24 ++++++ 2 files changed, 175 insertions(+) create mode 100644 src/client/slidingSync.test.ts diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts new file mode 100644 index 00000000..b54b5fda --- /dev/null +++ b/src/client/slidingSync.test.ts @@ -0,0 +1,151 @@ +/** + * Unit tests for SlidingSyncManager memory management: + * + * 1. dispose() — must call slidingSync.stop() to halt the polling loop and + * abort in-flight requests. Without this the SDK's Promise loop keeps + * running after the client is "stopped", leaking network traffic and + * event listeners. + * + * 2. pruneRoomTimeline (via unsubscribeFromRoom) — when a room transitions + * from active to background, its in-memory event chain is released if it + * exceeds PRUNE_TIMELINE_THRESHOLD. The full history stays on disk in + * IndexedDBStore and is re-fetched via the active-room subscription on + * next open. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { SlidingSyncManager, type SlidingSyncConfig } from './slidingSync'; + +// ── vi.hoisted mocks ───────────────────────────────────────────────────────── +// Must be defined via vi.hoisted so they're available before vi.mock runs +// (vi.mock calls are hoisted above all imports by vitest's transformer). +const mocks = vi.hoisted(() => ({ + slidingSyncInstance: { + on: vi.fn(), + off: vi.fn(), + removeListener: vi.fn(), + stop: vi.fn(), + modifyRoomSubscriptions: vi.fn(), + modifyRoomSubscriptionInfo: vi.fn(), + addCustomSubscription: vi.fn(), + useCustomSubscription: vi.fn(), + registerExtension: vi.fn(), + getListData: vi.fn(() => null), + getListParams: vi.fn(() => null), + setList: vi.fn(), + setListRanges: vi.fn(), + }, +})); + +// ── Sentry stub ────────────────────────────────────────────────────────────── +vi.mock('@sentry/react', () => ({ + metrics: { count: vi.fn(), gauge: vi.fn(), distribution: vi.fn() }, + addBreadcrumb: vi.fn(), + startInactiveSpan: vi.fn(() => ({ + setAttribute: vi.fn(), + setAttributes: vi.fn(), + end: vi.fn(), + })), + startSpan: vi.fn(async (_opts: unknown, fn: (span: object) => unknown) => + fn({ setAttributes: vi.fn(), setAttribute: vi.fn(), end: vi.fn() }) + ), +})); + +// ── SlidingSync SDK mock ───────────────────────────────────────────────────── +// vi.fn() wrappers are arrow functions internally and cannot be called with `new`. +// A plain function constructor (returning an object) is the correct pattern. +vi.mock('$types/matrix-sdk', async (importOriginal) => { + const actual = await importOriginal>(); + function MockSlidingSync() { + return mocks.slidingSyncInstance; + } + return { ...actual, SlidingSync: MockSlidingSync }; +}); + +// ── Helpers ────────────────────────────────────────────────────────────────── + +function makeMockMx(overrides: Record = {}) { + return { + getUserId: vi.fn().mockReturnValue('@user:example.com'), + getSafeUserId: vi.fn().mockReturnValue('@user:example.com'), + isRoomEncrypted: vi.fn().mockReturnValue(false), + getRoom: vi.fn().mockReturnValue(null), + on: vi.fn(), + off: vi.fn(), + ...overrides, + } as unknown as import('$types/matrix-sdk').MatrixClient; +} + +function makeMockRoom(eventCount: number) { + const events = Array.from({ length: eventCount }, (_, i) => ({ getId: () => `$ev${i}` })); + const resetLiveTimeline = vi.fn(); + return { + getUnfilteredTimelineSet: vi.fn().mockReturnValue({ + getLiveTimeline: vi.fn().mockReturnValue({ getEvents: vi.fn().mockReturnValue(events) }), + resetLiveTimeline, + }), + _resetLiveTimeline: resetLiveTimeline, + }; +} + +function makeManager(mx: ReturnType): SlidingSyncManager { + const config: SlidingSyncConfig = {}; + return new SlidingSyncManager(mx, 'https://sliding.example.com', config); +} + +beforeEach(() => { + vi.clearAllMocks(); +}); + +// ── dispose() ──────────────────────────────────────────────────────────────── + +describe('SlidingSyncManager.dispose()', () => { + it('calls slidingSync.stop() to halt the polling loop', () => { + const manager = makeManager(makeMockMx()); + manager.dispose(); + expect(mocks.slidingSyncInstance.stop).toHaveBeenCalledOnce(); + }); +}); + +// ── pruneRoomTimeline (exercised via unsubscribeFromRoom) ──────────────────── + +// This value must match PRUNE_TIMELINE_THRESHOLD in slidingSync.ts. +const PRUNE_THRESHOLD = 150; + +describe('SlidingSyncManager — timeline pruning on unsubscribe', () => { + it('resets the live timeline when event count exceeds the threshold', () => { + const room = makeMockRoom(PRUNE_THRESHOLD + 1); + const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const manager = makeManager(mx); + + manager.unsubscribeFromRoom('!room:example.com'); + + expect(room._resetLiveTimeline).toHaveBeenCalledOnce(); + }); + + it('does not reset when event count equals the threshold exactly', () => { + const room = makeMockRoom(PRUNE_THRESHOLD); + const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const manager = makeManager(mx); + + manager.unsubscribeFromRoom('!room:example.com'); + + expect(room._resetLiveTimeline).not.toHaveBeenCalled(); + }); + + it('does not reset for rooms with very few events', () => { + const room = makeMockRoom(5); + const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const manager = makeManager(mx); + + manager.unsubscribeFromRoom('!room:example.com'); + + expect(room._resetLiveTimeline).not.toHaveBeenCalled(); + }); + + it('does not throw when the room is not yet in SDK state', () => { + const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(null) }); + const manager = makeManager(mx); + + expect(() => manager.unsubscribeFromRoom('!room:example.com')).not.toThrow(); + }); +}); diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index a644bc2d..75ae66e3 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -53,6 +53,9 @@ const UNENCRYPTED_SUBSCRIPTION_KEY = 'unencrypted'; const ACTIVE_ROOM_TIMELINE_LIMIT_LOW = 50; const ACTIVE_ROOM_TIMELINE_LIMIT_MEDIUM = 100; const ACTIVE_ROOM_TIMELINE_LIMIT_HIGH = 150; +// Rooms with more than this many events in memory are pruned when they go inactive. +// The full history remains on disk (IndexedDBStore); it is re-loaded on next open. +const PRUNE_TIMELINE_THRESHOLD = ACTIVE_ROOM_TIMELINE_LIMIT_HIGH; export type PartialSlidingSyncRequest = { filters?: MSC3575List['filters']; @@ -585,6 +588,8 @@ export class SlidingSyncManager { this.pendingRoomDataListeners.clear(); this.disposed = true; + // Stop the SDK's internal polling loop and abort any in-flight requests. + this.slidingSync.stop(); this.slidingSync.removeListener(SlidingSyncEvent.Lifecycle, this.onLifecycle); const connection = ( typeof navigator !== 'undefined' ? (navigator as any).connection : undefined @@ -615,6 +620,24 @@ export class SlidingSyncManager { ); } + /** + * Reset the live timeline for a room that is no longer actively viewed, + * freeing its in-memory event chain. Only fires when the room has accumulated + * more than PRUNE_TIMELINE_THRESHOLD events. The full history remains on disk + * (IndexedDBStore) and is re-loaded from the server subscription on next open. + */ + private pruneRoomTimeline(roomId: string): void { + const room = this.mx.getRoom(roomId); + if (!room) return; + const tl = room.getUnfilteredTimelineSet().getLiveTimeline(); + if (tl.getEvents().length <= PRUNE_TIMELINE_THRESHOLD) return; + room.getUnfilteredTimelineSet().resetLiveTimeline(); + debugLog.info('timeline', 'Pruned room timeline from memory', { + roomId, + threshold: PRUNE_TIMELINE_THRESHOLD, + }); + } + public setPresenceEnabled(enabled: boolean): void { this.presenceExtension.setEnabled(enabled); } @@ -1026,6 +1049,7 @@ export class SlidingSyncManager { remainingSubscriptions: this.activeRoomSubscriptions.size, syncCycle: this.syncCount, }); + this.pruneRoomTimeline(roomId); } public static async probe( From e1d51ad852bee8726a99d6867ff3a706a93f3388 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 18:05:57 -0400 Subject: [PATCH 07/28] chore: add changeset --- .changeset/fix-thread-indicator-badge.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix-thread-indicator-badge.md diff --git a/.changeset/fix-thread-indicator-badge.md b/.changeset/fix-thread-indicator-badge.md new file mode 100644 index 00000000..c9303ac1 --- /dev/null +++ b/.changeset/fix-thread-indicator-badge.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Hide the redundant "Thread" indicator badge in the compose box when inside the Thread Drawer. From 4b90cc5b5e683034da5a195d0cf7f782a77c2926 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 18:06:08 -0400 Subject: [PATCH 08/28] chore: add changeset --- .changeset/fix-sliding-sync-memory.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix-sliding-sync-memory.md diff --git a/.changeset/fix-sliding-sync-memory.md b/.changeset/fix-sliding-sync-memory.md new file mode 100644 index 00000000..aeb14955 --- /dev/null +++ b/.changeset/fix-sliding-sync-memory.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Stop the sliding sync polling loop on client dispose and free inactive room event timelines from memory. From 67c626c6b2b88428f4bfa1f66bf4caf1266864be Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 18:11:03 -0400 Subject: [PATCH 09/28] fix: correct IndexedDB persistence claim in pruneRoomTimeline comment --- src/client/slidingSync.test.ts | 7 ++++--- src/client/slidingSync.ts | 8 ++++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index b54b5fda..27f267cf 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -8,9 +8,10 @@ * * 2. pruneRoomTimeline (via unsubscribeFromRoom) — when a room transitions * from active to background, its in-memory event chain is released if it - * exceeds PRUNE_TIMELINE_THRESHOLD. The full history stays on disk in - * IndexedDBStore and is re-fetched via the active-room subscription on - * next open. + * exceeds PRUNE_TIMELINE_THRESHOLD. Sliding sync does not persist timeline + * events to IndexedDB, so the pruned events are gone from memory. On next + * open the active-room subscription re-fetches the latest events from the + * server. */ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { SlidingSyncManager, type SlidingSyncConfig } from './slidingSync'; diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 75ae66e3..8f1f2158 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -623,8 +623,12 @@ export class SlidingSyncManager { /** * Reset the live timeline for a room that is no longer actively viewed, * freeing its in-memory event chain. Only fires when the room has accumulated - * more than PRUNE_TIMELINE_THRESHOLD events. The full history remains on disk - * (IndexedDBStore) and is re-loaded from the server subscription on next open. + * more than PRUNE_TIMELINE_THRESHOLD events. + * + * Note: sliding sync does not write timeline events to IndexedDBStore, so + * there is no on-disk copy of the pruned events. The full history is still + * available on the server; on next open the active-room subscription + * re-fetches the latest timeline_limit events. */ private pruneRoomTimeline(roomId: string): void { const room = this.mx.getRoom(roomId); From 023bf2a325744ea98f517e93e834d5c7802ec52e Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 18:22:14 -0400 Subject: [PATCH 10/28] feat: persist room timeline to IndexedDB before pruning from memory --- src/client/slidingSync.test.ts | 49 ++++++++++++++++++++--- src/client/slidingSync.ts | 72 +++++++++++++++++++++++++++++++--- 2 files changed, 109 insertions(+), 12 deletions(-) diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index 27f267cf..01560d14 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -8,14 +8,19 @@ * * 2. pruneRoomTimeline (via unsubscribeFromRoom) — when a room transitions * from active to background, its in-memory event chain is released if it - * exceeds PRUNE_TIMELINE_THRESHOLD. Sliding sync does not persist timeline - * events to IndexedDB, so the pruned events are gone from memory. On next - * open the active-room subscription re-fetches the latest events from the - * server. + * exceeds PRUNE_TIMELINE_THRESHOLD. The recent tail is persisted to + * IndexedDB (via store.setSyncData + store.save) so the events survive an + * app reload; the full history is always available from the server. */ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { SlidingSyncManager, type SlidingSyncConfig } from './slidingSync'; +/** Flush all pending Promise microtasks. */ +const flushPromises = (): Promise => + new Promise((r) => { + setTimeout(r, 0); + }); + // ── vi.hoisted mocks ───────────────────────────────────────────────────────── // Must be defined via vi.hoisted so they're available before vi.mock runs // (vi.mock calls are hoisted above all imports by vitest's transformer). @@ -72,16 +77,26 @@ function makeMockMx(overrides: Record = {}) { getRoom: vi.fn().mockReturnValue(null), on: vi.fn(), off: vi.fn(), + store: { + setSyncData: vi.fn().mockResolvedValue(undefined), + save: vi.fn().mockResolvedValue(undefined), + }, ...overrides, } as unknown as import('$types/matrix-sdk').MatrixClient; } function makeMockRoom(eventCount: number) { - const events = Array.from({ length: eventCount }, (_, i) => ({ getId: () => `$ev${i}` })); + const events = Array.from({ length: eventCount }, (_, i) => ({ + getId: () => `$ev${i}`, + event: { event_id: `$ev${i}`, type: 'm.room.message', content: {} }, + })); const resetLiveTimeline = vi.fn(); return { getUnfilteredTimelineSet: vi.fn().mockReturnValue({ - getLiveTimeline: vi.fn().mockReturnValue({ getEvents: vi.fn().mockReturnValue(events) }), + getLiveTimeline: vi.fn().mockReturnValue({ + getEvents: vi.fn().mockReturnValue(events), + getPaginationToken: vi.fn().mockReturnValue('t123'), + }), resetLiveTimeline, }), _resetLiveTimeline: resetLiveTimeline, @@ -123,6 +138,28 @@ describe('SlidingSyncManager — timeline pruning on unsubscribe', () => { expect(room._resetLiveTimeline).toHaveBeenCalledOnce(); }); + it('persists events to store.setSyncData and store.save after pruning', async () => { + const room = makeMockRoom(PRUNE_THRESHOLD + 1); + const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const manager = makeManager(mx); + + manager.unsubscribeFromRoom('!room:example.com'); + await flushPromises(); + + const { store } = mx as unknown as { + store: { setSyncData: ReturnType; save: ReturnType }; + }; + expect(store.setSyncData).toHaveBeenCalledOnce(); + expect(store.save).toHaveBeenCalledWith(true); + + // The payload must target the correct room and use limited:true so the + // accumulator replaces any stale timeline rather than appending. + const [payload] = store.setSyncData.mock.calls[0] as [ + { rooms: { join: Record } }, + ]; + expect(payload.rooms.join['!room:example.com'].timeline.limited).toBe(true); + }); + it('does not reset when event count equals the threshold exactly', () => { const room = makeMockRoom(PRUNE_THRESHOLD); const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 8f1f2158..0c7c86bc 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -1,8 +1,12 @@ /* eslint-disable max-classes-per-file */ import { ClientEvent, + EventTimeline, Extension, ExtensionState, + IJoinedRoom, + IRoomEvent, + ISyncResponse, MatrixClient, MSC3575List, MSC3575RoomData, @@ -54,7 +58,6 @@ const ACTIVE_ROOM_TIMELINE_LIMIT_LOW = 50; const ACTIVE_ROOM_TIMELINE_LIMIT_MEDIUM = 100; const ACTIVE_ROOM_TIMELINE_LIMIT_HIGH = 150; // Rooms with more than this many events in memory are pruned when they go inactive. -// The full history remains on disk (IndexedDBStore); it is re-loaded on next open. const PRUNE_TIMELINE_THRESHOLD = ACTIVE_ROOM_TIMELINE_LIMIT_HIGH; export type PartialSlidingSyncRequest = { @@ -625,23 +628,80 @@ export class SlidingSyncManager { * freeing its in-memory event chain. Only fires when the room has accumulated * more than PRUNE_TIMELINE_THRESHOLD events. * - * Note: sliding sync does not write timeline events to IndexedDBStore, so - * there is no on-disk copy of the pruned events. The full history is still - * available on the server; on next open the active-room subscription - * re-fetches the latest timeline_limit events. + * The timeline is reset synchronously so memory is freed immediately. Then, + * as a best-effort fire-and-forget step, the snapshot of recent events is + * fed into the SyncAccumulator and flushed to IndexedDB so they survive an + * app reload (the accumulator caps storage at ~50 events per room; the full + * history is always available from the server). */ private pruneRoomTimeline(roomId: string): void { const room = this.mx.getRoom(roomId); if (!room) return; const tl = room.getUnfilteredTimelineSet().getLiveTimeline(); - if (tl.getEvents().length <= PRUNE_TIMELINE_THRESHOLD) return; + const events = tl.getEvents(); + if (events.length <= PRUNE_TIMELINE_THRESHOLD) return; + + // Capture the back-pagination token before resetting the timeline. + const prevBatch = tl.getPaginationToken(EventTimeline.BACKWARDS); + + // Free the in-memory event chain immediately. room.getUnfilteredTimelineSet().resetLiveTimeline(); + + // Persist the tail of the timeline to IndexedDB asynchronously. + // If it fails, the events are still available from the server. + this.persistRoomTimeline( + roomId, + events.map((e) => e.event as IRoomEvent), + prevBatch + ).catch((err: unknown) => { + debugLog.warn('timeline', 'Failed to persist pruned room timeline', { roomId, err }); + }); + debugLog.info('timeline', 'Pruned room timeline from memory', { roomId, threshold: PRUNE_TIMELINE_THRESHOLD, }); } + /** + * Persist a snapshot of room timeline events to the IndexedDB store via a + * synthetic /sync payload. This feeds the SyncAccumulator (which the SDK + * uses for both start-up replay and classic sync persistence) so that the + * last ~50 events are available on the next app load without a server round- + * trip. The sliding sync layer never calls setSyncData itself, so this is + * the only path by which sliding-sync rooms get on-disk history. + */ + private async persistRoomTimeline( + roomId: string, + rawEvents: IRoomEvent[], + prevBatch: string | null + ): Promise { + const payload: ISyncResponse = { + next_batch: '', + account_data: { events: [] }, + rooms: { + join: { + [roomId]: { + summary: {}, + timeline: { + events: rawEvents, + limited: true, + prev_batch: prevBatch, + }, + ephemeral: { events: [] }, + account_data: { events: [] }, + unread_notifications: {}, + } as unknown as IJoinedRoom, + }, + invite: {}, + leave: {}, + knock: {}, + }, + }; + await this.mx.store.setSyncData(payload); + await this.mx.store.save(true); + } + public setPresenceEnabled(enabled: boolean): void { this.presenceExtension.setEnabled(enabled); } From 9c736203adbdefd57b00a522f04d9239c3b8fe3a Mon Sep 17 00:00:00 2001 From: 7w1 Date: Wed, 18 Mar 2026 12:56:52 -0500 Subject: [PATCH 11/28] Update ImageContent.tsx --- src/app/components/message/content/ImageContent.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/app/components/message/content/ImageContent.tsx b/src/app/components/message/content/ImageContent.tsx index 11afcd60..ad51d2a4 100644 --- a/src/app/components/message/content/ImageContent.tsx +++ b/src/app/components/message/content/ImageContent.tsx @@ -204,7 +204,10 @@ export const ImageContent = as<'div', ImageContentProps>( src: srcState.data, onLoad: handleLoad, onError: handleError, - onClick: () => setViewer(true), + onClick: () => { + setIsHovered(false); + setViewer(true); + }, tabIndex: 0, })} From 0f6067e04c46d7cfe8620c9a6bed376ef4b5dc4b Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Wed, 18 Mar 2026 14:31:18 -0400 Subject: [PATCH 12/28] refactor: remove adaptive timeline limits, stop unsubscribing on navigation Replace the adaptive 50/100/150 timeline limit system with a flat ACTIVE_ROOM_TIMELINE_LIMIT=50, matching Element Web approach. Stop calling unsubscribeFromRoom() on room navigation so subscriptions accumulate across the session for instant room switching. Element Web SlidingSyncManager.setRoomVisible() never removes subscriptions at all -- no pruning whatsoever. Our PRUNE_TIMELINE_THRESHOLD=100 guard is more conservative than their approach. - Remove AdaptiveSignals type, readAdaptiveSignals(), resolveAdaptiveRoomTimelineLimit(), applyRoomTimelineLimit() - Remove adaptiveTimeline and configuredTimelineLimit class fields - Remove adaptiveTimeline from SlidingSyncDiagnostics type and UI - Stop unsubscribing on nav in useSlidingSyncActiveRoom - Lower PRUNE_TIMELINE_THRESHOLD from 150 to 100 --- .../developer-tools/DevelopTools.tsx | 7 +- .../developer-tools/SyncDiagnostics.tsx | 3 +- src/app/hooks/useSlidingSyncActiveRoom.ts | 17 ++- src/client/slidingSync.test.ts | 16 ++- src/client/slidingSync.ts | 113 ++---------------- 5 files changed, 27 insertions(+), 129 deletions(-) diff --git a/src/app/features/common-settings/developer-tools/DevelopTools.tsx b/src/app/features/common-settings/developer-tools/DevelopTools.tsx index f8552e19..aec2f2ca 100644 --- a/src/app/features/common-settings/developer-tools/DevelopTools.tsx +++ b/src/app/features/common-settings/developer-tools/DevelopTools.tsx @@ -445,11 +445,8 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { Proxy: {syncDiagnostics.sliding.proxyBaseUrl} - Room timeline: {syncDiagnostics.sliding.timelineLimit} - {syncDiagnostics.sliding.adaptiveTimeline - ? ' (adaptive)' - : ''}{' '} - | page size: {syncDiagnostics.sliding.listPageSize} + Room timeline: {syncDiagnostics.sliding.timelineLimit} | page + size: {syncDiagnostics.sliding.listPageSize} ) : ( diff --git a/src/app/features/settings/developer-tools/SyncDiagnostics.tsx b/src/app/features/settings/developer-tools/SyncDiagnostics.tsx index 07824c85..1d963110 100644 --- a/src/app/features/settings/developer-tools/SyncDiagnostics.tsx +++ b/src/app/features/settings/developer-tools/SyncDiagnostics.tsx @@ -199,8 +199,7 @@ export function SyncDiagnostics() { Sliding proxy: {diagnostics.sliding.proxyBaseUrl} - Room timeline limit: {diagnostics.sliding.timelineLimit} (adaptive:{' '} - {diagnostics.sliding.adaptiveTimeline ? 'yes' : 'no'}) | page size:{' '} + Room timeline limit: {diagnostics.sliding.timelineLimit} | page size:{' '} {diagnostics.sliding.listPageSize} {diagnostics.sliding.lists.map((list) => ( diff --git a/src/app/hooks/useSlidingSyncActiveRoom.ts b/src/app/hooks/useSlidingSyncActiveRoom.ts index a76efe6f..8468f402 100644 --- a/src/app/hooks/useSlidingSyncActiveRoom.ts +++ b/src/app/hooks/useSlidingSyncActiveRoom.ts @@ -7,6 +7,11 @@ import { useSelectedRoom } from '$hooks/router/useSelectedRoom'; * Subscribes the currently selected room to the sliding sync "active room" * custom subscription (higher timeline limit) for the duration the room is open. * + * Subscriptions are intentionally never removed on navigation — once a room + * has been opened it continues receiving background updates so that returning + * to it is instant. Explicit unsubscription (and timeline pruning) only happens + * when the user actually leaves the room via `unsubscribeFromRoom()`. + * * Safe to call unconditionally — it is a no-op when classic sync is in use * (i.e. when there is no SlidingSyncManager for the client). */ @@ -20,23 +25,15 @@ export const useSlidingSyncActiveRoom = (): void => { if (!manager) return undefined; // Wait for the room to be initialized from list sync before subscribing - // with high timeline limit. This prevents timeline ordering issues where + // with the full timeline limit. This prevents timeline ordering issues where // the room might be receiving events from list expansion while we're also // trying to load a large timeline, causing events to be added out of order. const timeoutId = setTimeout(() => { - const room = mx.getRoom(roomId); - if (room) { - // Room exists and has been initialized from list sync - manager.subscribeToRoom(roomId); - } else { - // Room not in cache yet - subscribe anyway (will use default encrypted subscription) - manager.subscribeToRoom(roomId); - } + manager.subscribeToRoom(roomId); }, 100); return () => { clearTimeout(timeoutId); - manager.unsubscribeFromRoom(roomId); }; }, [mx, roomId]); }; diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index 01560d14..c05ef470 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -6,11 +6,15 @@ * running after the client is "stopped", leaking network traffic and * event listeners. * - * 2. pruneRoomTimeline (via unsubscribeFromRoom) — when a room transitions - * from active to background, its in-memory event chain is released if it - * exceeds PRUNE_TIMELINE_THRESHOLD. The recent tail is persisted to - * IndexedDB (via store.setSyncData + store.save) so the events survive an - * app reload; the full history is always available from the server. + * 2. pruneRoomTimeline (via unsubscribeFromRoom) — when a room is explicitly + * unsubscribed (e.g. user leaves the room), its in-memory event chain is + * released if it exceeds PRUNE_TIMELINE_THRESHOLD. The recent tail is + * persisted to IndexedDB (via store.setSyncData + store.save) so the events + * survive an app reload; the full history is always available from the server. + * + * Note: navigation between rooms no longer calls unsubscribeFromRoom — + * subscriptions accumulate across the session so returning to a room is + * instant (matching Element Web's model). */ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { SlidingSyncManager, type SlidingSyncConfig } from './slidingSync'; @@ -125,7 +129,7 @@ describe('SlidingSyncManager.dispose()', () => { // ── pruneRoomTimeline (exercised via unsubscribeFromRoom) ──────────────────── // This value must match PRUNE_TIMELINE_THRESHOLD in slidingSync.ts. -const PRUNE_THRESHOLD = 150; +const PRUNE_THRESHOLD = 100; describe('SlidingSyncManager — timeline pruning on unsubscribe', () => { it('resets the live timeline when event count exceeds the threshold', () => { diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 0c7c86bc..afd7ebfa 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -50,15 +50,11 @@ const LIST_SORT_ORDER = ['by_recency', 'by_name']; // Subscription key for the room the user is actively viewing. // Encrypted rooms get [*,*] required_state; unencrypted rooms also request lazy members. const UNENCRYPTED_SUBSCRIPTION_KEY = 'unencrypted'; -// Adaptive timeline limits for the room the user is actively viewing. -// Lower limits reduce initial bandwidth on constrained devices/connections; -// the user can always paginate further once the room is open. -// These values must be high enough to ensure proper timeline initialization and pagination tokens. -const ACTIVE_ROOM_TIMELINE_LIMIT_LOW = 50; -const ACTIVE_ROOM_TIMELINE_LIMIT_MEDIUM = 100; -const ACTIVE_ROOM_TIMELINE_LIMIT_HIGH = 150; -// Rooms with more than this many events in memory are pruned when they go inactive. -const PRUNE_TIMELINE_THRESHOLD = ACTIVE_ROOM_TIMELINE_LIMIT_HIGH; +// Timeline limit for the active-room subscription (full history load). +// List entries always use LIST_TIMELINE_LIMIT=1 for lightweight previews. +const ACTIVE_ROOM_TIMELINE_LIMIT = 50; +// Events accumulated in a room before its timeline is freed on explicit unsubscribe. +const PRUNE_TIMELINE_THRESHOLD = 100; export type PartialSlidingSyncRequest = { filters?: MSC3575List['filters']; @@ -87,7 +83,6 @@ export type SlidingSyncListDiagnostics = { export type SlidingSyncDiagnostics = { proxyBaseUrl: string; timelineLimit: number; - adaptiveTimeline: boolean; listPageSize: number; lists: SlidingSyncListDiagnostics[]; }; @@ -97,63 +92,6 @@ const clampPositive = (value: number | undefined, fallback: number): number => { return Math.round(value); }; -type AdaptiveSignals = { - saveData: boolean; - effectiveType: string | null; - deviceMemoryGb: number | null; - mobile: boolean; - missingSignals: number; -}; - -const readAdaptiveSignals = (): AdaptiveSignals => { - const navigatorLike = typeof navigator !== 'undefined' ? navigator : undefined; - const connection = (navigatorLike as any)?.connection; - const effectiveType = connection?.effectiveType; - const deviceMemory = (navigatorLike as any)?.deviceMemory; - const uaMobile = (navigatorLike as any)?.userAgentData?.mobile; - const fallbackMobileUA = navigatorLike?.userAgent ?? ''; - const mobileByUA = - typeof uaMobile === 'boolean' - ? uaMobile - : /Mobi|Android|iPhone|iPad|iPod|IEMobile|Opera Mini/i.test(fallbackMobileUA); - const saveData = connection?.saveData === true; - const normalizedEffectiveType = typeof effectiveType === 'string' ? effectiveType : null; - const normalizedDeviceMemory = typeof deviceMemory === 'number' ? deviceMemory : null; - const missingSignals = - Number(normalizedEffectiveType === null) + Number(normalizedDeviceMemory === null); - return { - saveData, - effectiveType: normalizedEffectiveType, - deviceMemoryGb: normalizedDeviceMemory, - mobile: mobileByUA, - missingSignals, - }; -}; - -// Resolve the timeline limit for the active-room subscription based on device/network. -// The list subscription always uses LIST_TIMELINE_LIMIT=1 regardless of conditions. -const resolveAdaptiveRoomTimelineLimit = ( - configuredLimit: number | undefined, - signals: AdaptiveSignals -): number => { - if (typeof configuredLimit === 'number' && configuredLimit > 0) { - return clampPositive(configuredLimit, ACTIVE_ROOM_TIMELINE_LIMIT_HIGH); - } - if (signals.saveData || signals.effectiveType === 'slow-2g' || signals.effectiveType === '2g') { - return ACTIVE_ROOM_TIMELINE_LIMIT_LOW; - } - if ( - signals.effectiveType === '3g' || - (signals.deviceMemoryGb !== null && signals.deviceMemoryGb <= 4) - ) { - return ACTIVE_ROOM_TIMELINE_LIMIT_MEDIUM; - } - if (signals.mobile && signals.missingSignals > 0) { - return ACTIVE_ROOM_TIMELINE_LIMIT_MEDIUM; - } - return ACTIVE_ROOM_TIMELINE_LIMIT_HIGH; -}; - // Minimal required_state for list entries; enough to render the room list sidebar, // compute unread state, and build the space hierarchy without fetching full room history. // Notes: @@ -312,11 +250,7 @@ export class SlidingSyncManager { private readonly listPageSize: number; - private roomTimelineLimit: number; - - private readonly adaptiveTimeline: boolean; - - private readonly configuredTimelineLimit?: number; + private readonly roomTimelineLimit: number; private readonly onConnectionChange: () => void; @@ -364,14 +298,8 @@ export class SlidingSyncManager { this.listPageSize = listPageSize; const includeInviteList = config.includeInviteList !== false; - const adaptiveTimeline = !( - typeof config.timelineLimit === 'number' && config.timelineLimit > 0 - ); - const signals = readAdaptiveSignals(); - const roomTimelineLimit = resolveAdaptiveRoomTimelineLimit(config.timelineLimit, signals); - this.adaptiveTimeline = adaptiveTimeline; + const roomTimelineLimit = clampPositive(config.timelineLimit, ACTIVE_ROOM_TIMELINE_LIMIT); this.roomTimelineLimit = roomTimelineLimit; - this.configuredTimelineLimit = config.timelineLimit; const defaultSubscription = buildEncryptedSubscription(roomTimelineLimit); const lists = buildLists(listPageSize, includeInviteList); @@ -518,23 +446,6 @@ export class SlidingSyncManager { syncNumber: this.syncCount, }); } - - if (this.disposed || !this.adaptiveTimeline) return; - const nextLimit = resolveAdaptiveRoomTimelineLimit( - this.configuredTimelineLimit, - readAdaptiveSignals() - ); - if (nextLimit === this.roomTimelineLimit) return; - debugLog.info('sync', `Adaptive timeline limit updated to ${nextLimit}`, { - limit: nextLimit, - previousLimit: this.roomTimelineLimit, - reason: 'connection change', - }); - this.roomTimelineLimit = nextLimit; - this.applyRoomTimelineLimit(nextLimit); - log.log( - `Sliding Sync adaptive room timeline updated to ${nextLimit} for ${this.mx.getUserId()}` - ); }; } @@ -543,7 +454,6 @@ export class SlidingSyncManager { proxyBaseUrl: this.proxyBaseUrl, listPageSize: this.listPageSize, roomTimelineLimit: this.roomTimelineLimit, - adaptiveTimeline: this.adaptiveTimeline, maxRooms: this.maxRooms, lists: this.listKeys, }); @@ -615,14 +525,6 @@ export class SlidingSyncManager { }); } - private applyRoomTimelineLimit(timelineLimit: number): void { - this.slidingSync.modifyRoomSubscriptionInfo(buildEncryptedSubscription(timelineLimit)); - this.slidingSync.addCustomSubscription( - UNENCRYPTED_SUBSCRIPTION_KEY, - buildUnencryptedSubscription(timelineLimit) - ); - } - /** * Reset the live timeline for a room that is no longer actively viewed, * freeing its in-memory event chain. Only fires when the room has accumulated @@ -710,7 +612,6 @@ export class SlidingSyncManager { return { proxyBaseUrl: this.proxyBaseUrl, timelineLimit: this.roomTimelineLimit, - adaptiveTimeline: this.adaptiveTimeline, listPageSize: this.listPageSize, lists: this.listKeys.map((key) => { const listData = this.slidingSync.getListData(key); From c5eb3020f59b8f31bc8a5e8b068f49d981312fd9 Mon Sep 17 00:00:00 2001 From: Rye Date: Wed, 18 Mar 2026 19:35:36 +0100 Subject: [PATCH 13/28] fix stripping nickname from replies and plain mentions --- src/app/components/editor/output.ts | 71 +++++++++++++++++++++++++++-- src/app/features/room/RoomInput.tsx | 64 +++++++++++++++++++++++++- 2 files changed, 130 insertions(+), 5 deletions(-) diff --git a/src/app/components/editor/output.ts b/src/app/components/editor/output.ts index 9e390192..383678e1 100644 --- a/src/app/components/editor/output.ts +++ b/src/app/components/editor/output.ts @@ -17,6 +17,14 @@ export type OutputOptions = { allowTextFormatting?: boolean; allowInlineMarkdown?: boolean; allowBlockMarkdown?: boolean; + /** + * if true it will remove the nickname of the person from the message + */ + stripNickname?: boolean; + /** + * a map of regex patterns to replace nicknames with, used when stripNickname is true + */ + nickNameReplacement?: Map; }; const textToCustomHtml = (node: Text, opts: OutputOptions): string => { @@ -99,6 +107,12 @@ const ignoreHTMLParseInlineMD = (text: string): string => (txt) => parseInlineMD(txt) ).join(''); +/** + * convert slate internal representation to a custom HTML string that can be sent to the server + * @param node slate node + * @param opts options for output + * @returns custom HTML string + */ export const toMatrixCustomHTML = ( node: Descendant | Descendant[], opts: OutputOptions @@ -106,7 +120,7 @@ export const toMatrixCustomHTML = ( let markdownLines = ''; const parseNode = (n: Descendant, index: number, targetNodes: Descendant[]) => { if (opts.allowBlockMarkdown && 'type' in n && n.type === BlockType.Paragraph) { - const line = toMatrixCustomHTML(n, { + let line = toMatrixCustomHTML(n, { ...opts, allowInlineMarkdown: false, allowBlockMarkdown: false, @@ -114,6 +128,13 @@ export const toMatrixCustomHTML = ( .replace(/$/, '\n') .replace(/^(\\*)>/, '$1>'); + // strip nicknames if needed + if (opts.stripNickname && opts.nickNameReplacement) { + opts.nickNameReplacement?.keys().forEach((key) => { + const replacement = opts.nickNameReplacement!.get(key) ?? ''; + line = line.replaceAll(key, replacement); + }); + } markdownLines += line; if (index === targetNodes.length - 1) { return parseBlockMD(markdownLines, ignoreHTMLParseInlineMD); @@ -175,12 +196,37 @@ const elementToPlainText = (node: CustomElement, children: string): string => { } }; -export const toPlainText = (node: Descendant | Descendant[], isMarkdown: boolean): string => { - if (Array.isArray(node)) return node.map((n) => toPlainText(n, isMarkdown)).join(''); - if (Text.isText(node)) +/** + * convert slate internal representation to a plain text string that can be sent to the server + * @param node the slate node + * @param isMarkdown set true if it's a markdown formatted text + * @param stripNickname whether to strip nicknames + * @param nickNameReplacement the nickname replacement + * @returns the plain text we want to send + */ +export const toPlainText = ( + node: Descendant | Descendant[], + isMarkdown: boolean, + stripNickname = false, + nickNameReplacement?: Map +): string => { + if (Array.isArray(node)) + return node.map((n) => toPlainText(n, isMarkdown, stripNickname, nickNameReplacement)).join(''); + if (Text.isText(node)) { + if (stripNickname && nickNameReplacement) { + let { text } = node; + nickNameReplacement?.keys().forEach((key) => { + const replacement = nickNameReplacement.get(key) ?? ''; + text = text.replaceAll(key, replacement); + }); + return isMarkdown + ? unescapeMarkdownBlockSequences(text, unescapeMarkdownInlineSequences) + : text; + } return isMarkdown ? unescapeMarkdownBlockSequences(node.text, unescapeMarkdownInlineSequences) : node.text; + } const children = node.children.map((n) => toPlainText(n, isMarkdown)).join(''); return elementToPlainText(node, children); @@ -208,10 +254,27 @@ export const trimCommand = (cmdName: string, str: string) => { return str.slice(match[0].length); }; +/** + * Type representing Mentions + */ export type MentionsData = { + /** + * a boolean to denote if it's a room mention + */ room: boolean; + /** + * a set of user ids that are mentioned in the message + */ users: Set; }; + +/** + * get the mentions in a message + * @param mx the matrix client + * @param roomId the room id we will send the message in + * @param editor the slate editor + * @returns the mentions in a message {@link MentionsData} + */ export const getMentions = (mx: MatrixClient, roomId: string, editor: Editor): MentionsData => { const mentionData: MentionsData = { room: false, diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 65e54ab9..719a47a4 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -254,6 +254,10 @@ export const RoomInput = forwardRef( const emojiBtnRef = useRef(null); const micBtnRef = useRef(null); const roomToParents = useAtomValue(roomToParentsAtom); + /** + * Nickname someone set for another user + * this nickname should be treated as private + */ const nicknames = useAtomValue(nicknamesAtom); const powerLevels = usePowerLevelsContext(); @@ -372,6 +376,9 @@ export const RoomInput = forwardRef( let replyBodyJSX: ReactNode = replyDraft ? trimReplyFromBody(replyDraft.body) : null; if (htmlBody) { + /** + * message with linebreaks, etc stripped + */ const strippedHtml = trimReplyFromFormattedBody(htmlBody) .replaceAll(//gi, ' ') .replaceAll(/<\/p>\s*]*>/gi, ' ') @@ -574,12 +581,65 @@ export const RoomInput = forwardRef( uploadBoardHandlers.current?.handleSend(); const commandName = getBeginCommand(editor); - let plainText = toPlainText(editor.children, isMarkdown).trim(); + /** + * a map of regex patterns to replace nicknames with, + * used when stripNickname is true in toMatrixCustomHTML + * during HTML generation for the message content. + * This is necessary because the HTML generation needs to know + * which nicknames to strip in order to generate the correct formatted_body, + * and the plain text generation needs to replace those same nicknames with + * the original user IDs so that the message content remains consistent and + * mentions are correctly processed by the server and clients. + */ + const nicknameReplacement = new Map(); + if (replyEvent) { + /** + * the id of the user being replied to, + * whose nickname (if any) should be stripped + * from the message content and replaced with their + * user ID for correct mention processing + */ + const senderId = replyEvent.getSender(); + if (senderId) { + const nick = nicknames[senderId]; + if (typeof nick === 'string' && nick.length > 0) { + nicknameReplacement.set( + new RegExp(`@?${nick}`, 'g'), + room.getMember(senderId)?.rawDisplayName ?? senderId + ); + } + } + } + /** + * any other users mentioned in the message being replied to, + * whose nicknames should also be stripped and replaced with user IDs + */ + const mentions = getMentions(mx, roomId, editor); + if (mentions?.users) { + mentions.users.forEach((id) => { + const nick = nicknames[id]; + if (typeof nick === 'string' && nick.length > 0) { + nicknameReplacement.set( + new RegExp(`@?${nick}`, 'g'), + room.getMember(id)?.rawDisplayName ?? id + ); + } + }); + } + /** + * the plain text we will send + */ + let plainText = toPlainText(editor.children, isMarkdown, true, nicknameReplacement).trim(); + /** + * the html we will send + */ let customHtml = trimCustomHtml( toMatrixCustomHTML(editor.children, { allowTextFormatting: true, allowBlockMarkdown: isMarkdown, allowInlineMarkdown: isMarkdown, + stripNickname: true, + nickNameReplacement: nicknameReplacement, }) ); let msgType = MsgType.Text; @@ -720,6 +780,7 @@ export const RoomInput = forwardRef( } }, [ editor, + replyEvent, isMarkdown, canSendReaction, mx, @@ -729,6 +790,7 @@ export const RoomInput = forwardRef( silentReply, scheduledTime, editingScheduledDelayId, + nicknames, handleQuickReact, commands, sendTypingStatus, From ce3d20b1f8a3d431984a6ee210a9c95ee0b6a923 Mon Sep 17 00:00:00 2001 From: Rye Date: Wed, 18 Mar 2026 19:45:49 +0100 Subject: [PATCH 14/28] added changeset --- .changeset/fix-mentions-leaking-nicknames.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fix-mentions-leaking-nicknames.md diff --git a/.changeset/fix-mentions-leaking-nicknames.md b/.changeset/fix-mentions-leaking-nicknames.md new file mode 100644 index 00000000..3f4f299d --- /dev/null +++ b/.changeset/fix-mentions-leaking-nicknames.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +fix [accidental leaking of private nicknames](https://github.com/SableClient/Sable/issues/362) for users to be included in the message From b98fa45820370626b5081d00f6ee52331727b508 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Wed, 18 Mar 2026 15:22:56 -0400 Subject: [PATCH 15/28] feat: auto-unsubscribe and prune timeline when local user leaves a room MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wire onMembershipLeave to RoomMemberEvent.Membership in attach()/dispose(). When the local user leaves or is banned from a subscribed room, calls unsubscribeFromRoom() which prunes timelines exceeding PRUNE_TIMELINE_THRESHOLD. Previously, unsubscribeFromRoom() was dead code — nothing in the app called it. Also add 5 unit tests covering: leave, ban, other-user leave, join (no-op), and non-subscribed room (no-op). --- src/client/slidingSync.test.ts | 85 ++++++++++++++++++++++++++++++++++ src/client/slidingSync.ts | 13 ++++++ 2 files changed, 98 insertions(+) diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index c05ef470..1378796f 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -15,6 +15,10 @@ * Note: navigation between rooms no longer calls unsubscribeFromRoom — * subscriptions accumulate across the session so returning to a room is * instant (matching Element Web's model). + * + * 3. onMembershipLeave — when the MatrixClient emits a RoomMemberEvent.Membership + * event indicating the local user left or was banned from a room that is + * actively subscribed, unsubscribeFromRoom() should be called automatically. */ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { SlidingSyncManager, type SlidingSyncConfig } from './slidingSync'; @@ -81,6 +85,7 @@ function makeMockMx(overrides: Record = {}) { getRoom: vi.fn().mockReturnValue(null), on: vi.fn(), off: vi.fn(), + removeListener: vi.fn(), store: { setSyncData: vi.fn().mockResolvedValue(undefined), save: vi.fn().mockResolvedValue(undefined), @@ -191,3 +196,83 @@ describe('SlidingSyncManager — timeline pruning on unsubscribe', () => { expect(() => manager.unsubscribeFromRoom('!room:example.com')).not.toThrow(); }); }); + +// ── onMembershipLeave: auto-unsubscribe on leave/ban ───────────────────────── + +describe('SlidingSyncManager — membership leave auto-unsubscribe', () => { + /** Fire the RoomMemberEvent.Membership listener registered on mx.on */ + function fireMembershipEvent( + mx: ReturnType, + membership: string, + roomId = '!room:example.com', + userId = '@user:example.com', + ) { + const onCall = (mx.on as ReturnType).mock.calls.find( + ([event]: [string]) => event === 'RoomMember.membership', + ); + if (!onCall) throw new Error('onMembershipLeave listener not registered'); + const [, handler] = onCall as [string, (e: unknown, m: { userId: string; roomId: string; membership: string }) => void]; + handler(undefined, { userId, roomId, membership }); + } + + it('unsubscribes when the local user leaves an active room', () => { + const room = makeMockRoom(PRUNE_THRESHOLD + 1); + const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const manager = makeManager(mx); + manager.attach(); + // Manually add to active subscriptions to simulate having visited the room. + manager.subscribeToRoom('!room:example.com'); + + fireMembershipEvent(mx, 'leave'); + + expect(room._resetLiveTimeline).toHaveBeenCalledOnce(); + }); + + it('unsubscribes when the local user is banned from an active room', () => { + const room = makeMockRoom(PRUNE_THRESHOLD + 1); + const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const manager = makeManager(mx); + manager.attach(); + manager.subscribeToRoom('!room:example.com'); + + fireMembershipEvent(mx, 'ban'); + + expect(room._resetLiveTimeline).toHaveBeenCalledOnce(); + }); + + it('does nothing when a different user leaves', () => { + const room = makeMockRoom(PRUNE_THRESHOLD + 1); + const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const manager = makeManager(mx); + manager.attach(); + manager.subscribeToRoom('!room:example.com'); + + fireMembershipEvent(mx, 'leave', '!room:example.com', '@other:example.com'); + + expect(room._resetLiveTimeline).not.toHaveBeenCalled(); + }); + + it('does nothing when membership is join', () => { + const room = makeMockRoom(PRUNE_THRESHOLD + 1); + const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const manager = makeManager(mx); + manager.attach(); + manager.subscribeToRoom('!room:example.com'); + + fireMembershipEvent(mx, 'join'); + + expect(room._resetLiveTimeline).not.toHaveBeenCalled(); + }); + + it('does nothing for a room that was never subscribed', () => { + const room = makeMockRoom(PRUNE_THRESHOLD + 1); + const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const manager = makeManager(mx); + manager.attach(); // registers the listener, but no subscribeToRoom call + + fireMembershipEvent(mx, 'leave'); + + expect(room._resetLiveTimeline).not.toHaveBeenCalled(); + }); +}); + diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index afd7ebfa..1ae64d67 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -7,11 +7,13 @@ import { IJoinedRoom, IRoomEvent, ISyncResponse, + KnownMembership, MatrixClient, MSC3575List, MSC3575RoomData, MSC3575RoomSubscription, MSC3575_WILDCARD, + RoomMemberEvent, SlidingSync, SlidingSyncEvent, SlidingSyncState, @@ -256,6 +258,8 @@ export class SlidingSyncManager { private readonly onLifecycle: (state: SlidingSyncState, resp: unknown, err?: Error) => void; + private readonly onMembershipLeave: (event: unknown, member: { userId: string; roomId: string; membership?: string }) => void; + private presenceExtension!: ExtensionPresence; private listsFullyLoaded = false; @@ -424,6 +428,13 @@ export class SlidingSyncManager { } }; + this.onMembershipLeave = (_event, member) => { + if (member.userId !== this.mx.getUserId()) return; + if (member.membership !== KnownMembership.Leave && member.membership !== KnownMembership.Ban) return; + if (!this.activeRoomSubscriptions.has(member.roomId)) return; + this.unsubscribeFromRoom(member.roomId); + }; + this.onConnectionChange = () => { const isOnline = navigator.onLine; const connectionInfo = @@ -466,6 +477,7 @@ export class SlidingSyncManager { }); this.slidingSync.on(SlidingSyncEvent.Lifecycle, this.onLifecycle); + this.mx.on(RoomMemberEvent.Membership, this.onMembershipLeave); const connection = ( typeof navigator !== 'undefined' ? (navigator as any).connection : undefined ) as @@ -504,6 +516,7 @@ export class SlidingSyncManager { // Stop the SDK's internal polling loop and abort any in-flight requests. this.slidingSync.stop(); this.slidingSync.removeListener(SlidingSyncEvent.Lifecycle, this.onLifecycle); + this.mx.removeListener(RoomMemberEvent.Membership, this.onMembershipLeave); const connection = ( typeof navigator !== 'undefined' ? (navigator as any).connection : undefined ) as From cee2cb6118b3505149f97deaee805df25affe5ed Mon Sep 17 00:00:00 2001 From: Rye Date: Wed, 18 Mar 2026 21:56:31 +0100 Subject: [PATCH 16/28] added fallback body to be spec compliant --- .../components/message/MsgTypeRenderers.tsx | 22 +++++++++ src/app/features/room/RoomInput.tsx | 49 ++++++++++++++----- 2 files changed, 59 insertions(+), 12 deletions(-) diff --git a/src/app/components/message/MsgTypeRenderers.tsx b/src/app/components/message/MsgTypeRenderers.tsx index d1e2601a..93c67bba 100644 --- a/src/app/components/message/MsgTypeRenderers.tsx +++ b/src/app/components/message/MsgTypeRenderers.tsx @@ -109,6 +109,15 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }: const forwardMeta = content['moe.sable.message.forward']; return typeof forwardMeta === 'object'; }, [content]); + + /** + * For the unwrapping of per-message profile fallbacks, we look for tags with the data-mx-profile-fallback attribute + */ + const unwrappedPerMessageProfileMessage = useMemo( + () => customBody?.replace(/]*data-mx-profile-fallback[^>]*>(.*?):\s*<\/strong>/i, ''), + [customBody] + ); + const isJumbo = useMemo(() => { if (!trimmedBody || trimmedBody.length >= 500) return false; if (!JUMBO_EMOJI_REG.test(trimmedBody)) return false; @@ -126,6 +135,19 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }: const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG); const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined; + if (content['com.beeper.per_message_profile']) { + // unwrap per-message profile fallback if present + return ( + + {renderBody({ + body: trimmedBody, + customBody: unwrappedPerMessageProfileMessage, + })} + {edited && } + + ); + } + if (isForwarded && unwrappedForwardedContent) { return ( diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index c650d55e..44094a53 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -159,6 +159,7 @@ import { } from '$hooks/usePerMessageProfile'; import { Microphone, Stop } from '@phosphor-icons/react'; import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec'; +import { sanitizeCustomHtml } from '$utils/sanitize'; import { SchedulePickerDialog } from './schedule-send'; import * as css from './schedule-send/SchedulePickerDialog.css'; import { @@ -688,18 +689,6 @@ export const RoomInput = forwardRef( body, }; - /** - * the currently with the room associated per-message profile, if any, so that it can be included in the message content when sending. - * This allows the server to apply the correct profile-based transformations (e.g. font size adjustments) when processing the message, - * and also allows clients to display an accurate preview of how the message will look with the profile applied while it's being composed. - */ - const perMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId); - - if (perMessageProfile) { - content['com.beeper.per_message_profile'] = - convertPerMessageProfileToBeeperFormat(perMessageProfile); - } - if (replyDraft && !silentReply) { mentionData.users.add(replyDraft.userId); } @@ -710,6 +699,42 @@ export const RoomInput = forwardRef( content.format = 'org.matrix.custom.html'; content.formatted_body = formattedBody; } + + /** + * the currently with the room associated per-message profile, if any, so that it can be included in the message content when sending. + * This allows the server to apply the correct profile-based transformations (e.g. font size adjustments) when processing the message, + * and also allows clients to display an accurate preview of how the message will look with the profile applied while it's being composed. + */ + const perMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId); + + if (perMessageProfile) { + content['com.beeper.per_message_profile'] = + convertPerMessageProfileToBeeperFormat(perMessageProfile); + + // if a per-message profile is used, it must per spec include a fallback + const prefix = `${perMessageProfile.name}: `; + + if (!content.body.startsWith(prefix)) { + // to prevent double-prefixing when the fallback is already present + content.body = prefix + content.body; + } + + /** + * html escaped version of the display name + */ + const escapedName = sanitizeCustomHtml(perMessageProfile.name); + + const htmlPrefix = `${escapedName}: `; + + if (content.formatted_body && !content.formatted_body.startsWith(htmlPrefix)) { + content.formatted_body = htmlPrefix + content.formatted_body; + } else { + // we don't have a formatted body, but we need one + content.format = 'org.matrix.custom.html'; + content.formatted_body = `${htmlPrefix} ${plainText}`; + } + } + if (replyDraft) { content['m.relates_to'] = getReplyContent(replyDraft, room); } From aaa802606d43514042cb44341f0b20c2adf595ac Mon Sep 17 00:00:00 2001 From: Rye Date: Wed, 18 Mar 2026 22:33:41 +0100 Subject: [PATCH 17/28] added missing questionmark lol --- src/app/components/message/MsgTypeRenderers.tsx | 3 ++- src/app/hooks/usePerMessageProfile.ts | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/app/components/message/MsgTypeRenderers.tsx b/src/app/components/message/MsgTypeRenderers.tsx index 93c67bba..5cf1eef0 100644 --- a/src/app/components/message/MsgTypeRenderers.tsx +++ b/src/app/components/message/MsgTypeRenderers.tsx @@ -21,6 +21,7 @@ import { FALLBACK_MIMETYPE, getBlobSafeMimeType } from '$utils/mimeTypes'; import { parseGeoUri, scaleYDimension } from '$utils/common'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; +import { PerMessageProfileBeeperFormat } from '$hooks/usePerMessageProfile'; import { Attachment, AttachmentBox, AttachmentContent, AttachmentHeader } from './attachment'; import { FileHeader, FileDownloadButton } from './FileHeader'; import { @@ -135,7 +136,7 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }: const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG); const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined; - if (content['com.beeper.per_message_profile']) { + if ((content['com.beeper.per_message_profile'] as PerMessageProfileBeeperFormat)?.has_fallback) { // unwrap per-message profile fallback if present return ( diff --git a/src/app/hooks/usePerMessageProfile.ts b/src/app/hooks/usePerMessageProfile.ts index fb0ef3ef..8ef2f8d4 100644 --- a/src/app/hooks/usePerMessageProfile.ts +++ b/src/app/hooks/usePerMessageProfile.ts @@ -50,6 +50,7 @@ export type PerMessageProfileBeeperFormat = { * using the unstable prefix for pronouns, under which it is also stored in profiles */ 'io.fsky.nyx.pronouns'?: PronounSet[]; + has_fallback: boolean; }; /** @@ -67,6 +68,7 @@ export function convertPerMessageProfileToBeeperFormat( displayname: profile.name, avatar_url: profile.avatarUrl, 'io.fsky.nyx.pronouns': profile.pronouns, + has_fallback: true, }; } From 5f7548c7f2da96ba14ccbae541834d725da2d57d Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Wed, 18 Mar 2026 22:48:35 -0400 Subject: [PATCH 18/28] chore: update changeset to reflect full scope of sliding sync memory PR --- .changeset/fix-sliding-sync-memory.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/fix-sliding-sync-memory.md b/.changeset/fix-sliding-sync-memory.md index aeb14955..42e0ce51 100644 --- a/.changeset/fix-sliding-sync-memory.md +++ b/.changeset/fix-sliding-sync-memory.md @@ -2,4 +2,4 @@ default: patch --- -Stop the sliding sync polling loop on client dispose and free inactive room event timelines from memory. +Tighten sliding sync memory management: stop the polling loop on client dispose, persist then prune large room timelines when leaving a room, remove adaptive timeline-limit logic, and auto-unsubscribe when the local user leaves or is banned from a room. From 67c66bb769bbc9e1c77120d7199d5f32c5153359 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Wed, 18 Mar 2026 23:19:30 -0400 Subject: [PATCH 19/28] chore: fix prettier formatting and TypeScript type error in test --- src/client/slidingSync.test.ts | 29 +++++++++++++++++++++++++---- src/client/slidingSync.ts | 17 +++++++++++++---- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index 1378796f..aa76e932 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -89,6 +89,7 @@ function makeMockMx(overrides: Record = {}) { store: { setSyncData: vi.fn().mockResolvedValue(undefined), save: vi.fn().mockResolvedValue(undefined), + removeRoom: vi.fn(), }, ...overrides, } as unknown as import('$types/matrix-sdk').MatrixClient; @@ -169,6 +170,24 @@ describe('SlidingSyncManager — timeline pruning on unsubscribe', () => { expect(payload.rooms.join['!room:example.com'].timeline.limited).toBe(true); }); + it('evicts room from store cache when persist fails', async () => { + const room = makeMockRoom(PRUNE_THRESHOLD + 1); + const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + // Make setSyncData reject to simulate an IndexedDB write failure. + ( + mx as unknown as { store: { setSyncData: ReturnType } } + ).store.setSyncData.mockRejectedValue(new Error('IndexedDB write failed')); + const manager = makeManager(mx); + + manager.unsubscribeFromRoom('!room:example.com'); + await flushPromises(); + + const { store } = mx as unknown as { + store: { removeRoom: ReturnType }; + }; + expect(store.removeRoom).toHaveBeenCalledWith('!room:example.com'); + }); + it('does not reset when event count equals the threshold exactly', () => { const room = makeMockRoom(PRUNE_THRESHOLD); const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); @@ -205,13 +224,16 @@ describe('SlidingSyncManager — membership leave auto-unsubscribe', () => { mx: ReturnType, membership: string, roomId = '!room:example.com', - userId = '@user:example.com', + userId = '@user:example.com' ) { const onCall = (mx.on as ReturnType).mock.calls.find( - ([event]: [string]) => event === 'RoomMember.membership', + (args: unknown[]) => args[0] === 'RoomMember.membership' ); if (!onCall) throw new Error('onMembershipLeave listener not registered'); - const [, handler] = onCall as [string, (e: unknown, m: { userId: string; roomId: string; membership: string }) => void]; + const [, handler] = onCall as [ + string, + (e: unknown, m: { userId: string; roomId: string; membership: string }) => void, + ]; handler(undefined, { userId, roomId, membership }); } @@ -275,4 +297,3 @@ describe('SlidingSyncManager — membership leave auto-unsubscribe', () => { expect(room._resetLiveTimeline).not.toHaveBeenCalled(); }); }); - diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 1ae64d67..679b48ca 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -258,7 +258,10 @@ export class SlidingSyncManager { private readonly onLifecycle: (state: SlidingSyncState, resp: unknown, err?: Error) => void; - private readonly onMembershipLeave: (event: unknown, member: { userId: string; roomId: string; membership?: string }) => void; + private readonly onMembershipLeave: ( + event: unknown, + member: { userId: string; roomId: string; membership?: string } + ) => void; private presenceExtension!: ExtensionPresence; @@ -430,7 +433,8 @@ export class SlidingSyncManager { this.onMembershipLeave = (_event, member) => { if (member.userId !== this.mx.getUserId()) return; - if (member.membership !== KnownMembership.Leave && member.membership !== KnownMembership.Ban) return; + if (member.membership !== KnownMembership.Leave && member.membership !== KnownMembership.Ban) + return; if (!this.activeRoomSubscriptions.has(member.roomId)) return; this.unsubscribeFromRoom(member.roomId); }; @@ -563,13 +567,18 @@ export class SlidingSyncManager { room.getUnfilteredTimelineSet().resetLiveTimeline(); // Persist the tail of the timeline to IndexedDB asynchronously. - // If it fails, the events are still available from the server. + // On failure, evict the room from the store so the next open gets a clean + // server fetch rather than potentially stale cached data. this.persistRoomTimeline( roomId, events.map((e) => e.event as IRoomEvent), prevBatch ).catch((err: unknown) => { - debugLog.warn('timeline', 'Failed to persist pruned room timeline', { roomId, err }); + debugLog.warn('timeline', 'Failed to persist pruned room timeline — evicting store cache', { + roomId, + err, + }); + this.mx.store.removeRoom(roomId); }); debugLog.info('timeline', 'Pruned room timeline from memory', { From 60e8e960a6d5ee5c131c1798cfeff3f908111332 Mon Sep 17 00:00:00 2001 From: melogale Date: Wed, 18 Mar 2026 23:21:59 -0400 Subject: [PATCH 20/28] update to sable call 1.1.4 --- package.json | 4 ++-- pnpm-lock.yaml | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 6c52a2e0..1b3cb9db 100644 --- a/package.json +++ b/package.json @@ -95,7 +95,7 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.26.0", - "@sableclient/sable-call-embedded": "v1.1.3", + "@sableclient/sable-call-embedded": "v1.1.4", "@esbuild-plugins/node-globals-polyfill": "^0.2.3", "@eslint/compat": "2.0.2", "@eslint/js": "9.39.3", @@ -137,4 +137,4 @@ "vitest": "^4.1.0", "wrangler": "^4.70.0" } -} \ No newline at end of file +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index be96be6a..75323029 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -222,8 +222,8 @@ importers: specifier: ^6.2.2 version: 6.2.2(rollup@4.59.0) '@sableclient/sable-call-embedded': - specifier: v1.1.3 - version: 1.1.3 + specifier: v1.1.4 + version: 1.1.4 '@sentry/vite-plugin': specifier: ^5.1.1 version: 5.1.1(rollup@4.59.0) @@ -2426,8 +2426,8 @@ packages: '@rtsao/scc@1.1.0': resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==} - '@sableclient/sable-call-embedded@1.1.3': - resolution: {integrity: sha512-HNxppMEF8am6qhABbvJNc2mlkex7SntUeAMATOoNo2QkiTrutrJ9LPWy0TZskjAp++RrSpEpypKcN3MmOlZEWA==} + '@sableclient/sable-call-embedded@1.1.4': + resolution: {integrity: sha512-XLRcbUPcn7i3QKZAPjIfUkUEXP0E4DOr0dyRoVCWMjHWj28kq+T7jeB2fRr5lB77olBwNHMjIuoTwrv02xiepQ==} '@sentry-internal/browser-utils@10.43.0': resolution: {integrity: sha512-8zYTnzhAPvNkVH1Irs62wl0J/c+0QcJ62TonKnzpSFUUD3V5qz8YDZbjIDGfxy+1EB9fO0sxtddKCzwTHF/MbQ==} @@ -8119,7 +8119,7 @@ snapshots: '@rtsao/scc@1.1.0': {} - '@sableclient/sable-call-embedded@1.1.3': {} + '@sableclient/sable-call-embedded@1.1.4': {} '@sentry-internal/browser-utils@10.43.0': dependencies: From ea2c32a5c0f1543e17337cccb7cc90df550866d7 Mon Sep 17 00:00:00 2001 From: melogale Date: Wed, 18 Mar 2026 23:25:53 -0400 Subject: [PATCH 21/28] changeset --- .changeset/update_calls_to_have_rnnoise_noise_suppression.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/update_calls_to_have_rnnoise_noise_suppression.md diff --git a/.changeset/update_calls_to_have_rnnoise_noise_suppression.md b/.changeset/update_calls_to_have_rnnoise_noise_suppression.md new file mode 100644 index 00000000..ada13936 --- /dev/null +++ b/.changeset/update_calls_to_have_rnnoise_noise_suppression.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +# Update calls to have RNNoise noise suppression. From f846695d8eb85c4128f91a4b5e1e8cf6a3b6abba Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Wed, 18 Mar 2026 23:32:19 -0400 Subject: [PATCH 22/28] =?UTF-8?q?refactor:=20remove=20timeline=20pruning?= =?UTF-8?q?=20=E2=80=94=20unsubscribe=20on=20leave=20is=20sufficient?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/client/slidingSync.test.ts | 157 ++++----------------------------- src/client/slidingSync.ts | 91 ------------------- 2 files changed, 17 insertions(+), 231 deletions(-) diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index aa76e932..bd0643e5 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -6,29 +6,17 @@ * running after the client is "stopped", leaking network traffic and * event listeners. * - * 2. pruneRoomTimeline (via unsubscribeFromRoom) — when a room is explicitly - * unsubscribed (e.g. user leaves the room), its in-memory event chain is - * released if it exceeds PRUNE_TIMELINE_THRESHOLD. The recent tail is - * persisted to IndexedDB (via store.setSyncData + store.save) so the events - * survive an app reload; the full history is always available from the server. - * - * Note: navigation between rooms no longer calls unsubscribeFromRoom — - * subscriptions accumulate across the session so returning to a room is - * instant (matching Element Web's model). - * - * 3. onMembershipLeave — when the MatrixClient emits a RoomMemberEvent.Membership + * 2. onMembershipLeave — when the MatrixClient emits a RoomMemberEvent.Membership * event indicating the local user left or was banned from a room that is * actively subscribed, unsubscribeFromRoom() should be called automatically. + * + * Note: navigation between rooms does not call unsubscribeFromRoom — + * subscriptions accumulate across the session so returning to a room is + * instant (matching Element Web's model). */ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { SlidingSyncManager, type SlidingSyncConfig } from './slidingSync'; -/** Flush all pending Promise microtasks. */ -const flushPromises = (): Promise => - new Promise((r) => { - setTimeout(r, 0); - }); - // ── vi.hoisted mocks ───────────────────────────────────────────────────────── // Must be defined via vi.hoisted so they're available before vi.mock runs // (vi.mock calls are hoisted above all imports by vitest's transformer). @@ -86,33 +74,10 @@ function makeMockMx(overrides: Record = {}) { on: vi.fn(), off: vi.fn(), removeListener: vi.fn(), - store: { - setSyncData: vi.fn().mockResolvedValue(undefined), - save: vi.fn().mockResolvedValue(undefined), - removeRoom: vi.fn(), - }, ...overrides, } as unknown as import('$types/matrix-sdk').MatrixClient; } -function makeMockRoom(eventCount: number) { - const events = Array.from({ length: eventCount }, (_, i) => ({ - getId: () => `$ev${i}`, - event: { event_id: `$ev${i}`, type: 'm.room.message', content: {} }, - })); - const resetLiveTimeline = vi.fn(); - return { - getUnfilteredTimelineSet: vi.fn().mockReturnValue({ - getLiveTimeline: vi.fn().mockReturnValue({ - getEvents: vi.fn().mockReturnValue(events), - getPaginationToken: vi.fn().mockReturnValue('t123'), - }), - resetLiveTimeline, - }), - _resetLiveTimeline: resetLiveTimeline, - }; -} - function makeManager(mx: ReturnType): SlidingSyncManager { const config: SlidingSyncConfig = {}; return new SlidingSyncManager(mx, 'https://sliding.example.com', config); @@ -132,90 +97,6 @@ describe('SlidingSyncManager.dispose()', () => { }); }); -// ── pruneRoomTimeline (exercised via unsubscribeFromRoom) ──────────────────── - -// This value must match PRUNE_TIMELINE_THRESHOLD in slidingSync.ts. -const PRUNE_THRESHOLD = 100; - -describe('SlidingSyncManager — timeline pruning on unsubscribe', () => { - it('resets the live timeline when event count exceeds the threshold', () => { - const room = makeMockRoom(PRUNE_THRESHOLD + 1); - const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); - const manager = makeManager(mx); - - manager.unsubscribeFromRoom('!room:example.com'); - - expect(room._resetLiveTimeline).toHaveBeenCalledOnce(); - }); - - it('persists events to store.setSyncData and store.save after pruning', async () => { - const room = makeMockRoom(PRUNE_THRESHOLD + 1); - const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); - const manager = makeManager(mx); - - manager.unsubscribeFromRoom('!room:example.com'); - await flushPromises(); - - const { store } = mx as unknown as { - store: { setSyncData: ReturnType; save: ReturnType }; - }; - expect(store.setSyncData).toHaveBeenCalledOnce(); - expect(store.save).toHaveBeenCalledWith(true); - - // The payload must target the correct room and use limited:true so the - // accumulator replaces any stale timeline rather than appending. - const [payload] = store.setSyncData.mock.calls[0] as [ - { rooms: { join: Record } }, - ]; - expect(payload.rooms.join['!room:example.com'].timeline.limited).toBe(true); - }); - - it('evicts room from store cache when persist fails', async () => { - const room = makeMockRoom(PRUNE_THRESHOLD + 1); - const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); - // Make setSyncData reject to simulate an IndexedDB write failure. - ( - mx as unknown as { store: { setSyncData: ReturnType } } - ).store.setSyncData.mockRejectedValue(new Error('IndexedDB write failed')); - const manager = makeManager(mx); - - manager.unsubscribeFromRoom('!room:example.com'); - await flushPromises(); - - const { store } = mx as unknown as { - store: { removeRoom: ReturnType }; - }; - expect(store.removeRoom).toHaveBeenCalledWith('!room:example.com'); - }); - - it('does not reset when event count equals the threshold exactly', () => { - const room = makeMockRoom(PRUNE_THRESHOLD); - const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); - const manager = makeManager(mx); - - manager.unsubscribeFromRoom('!room:example.com'); - - expect(room._resetLiveTimeline).not.toHaveBeenCalled(); - }); - - it('does not reset for rooms with very few events', () => { - const room = makeMockRoom(5); - const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); - const manager = makeManager(mx); - - manager.unsubscribeFromRoom('!room:example.com'); - - expect(room._resetLiveTimeline).not.toHaveBeenCalled(); - }); - - it('does not throw when the room is not yet in SDK state', () => { - const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(null) }); - const manager = makeManager(mx); - - expect(() => manager.unsubscribeFromRoom('!room:example.com')).not.toThrow(); - }); -}); - // ── onMembershipLeave: auto-unsubscribe on leave/ban ───────────────────────── describe('SlidingSyncManager — membership leave auto-unsubscribe', () => { @@ -238,62 +119,58 @@ describe('SlidingSyncManager — membership leave auto-unsubscribe', () => { } it('unsubscribes when the local user leaves an active room', () => { - const room = makeMockRoom(PRUNE_THRESHOLD + 1); - const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const mx = makeMockMx(); const manager = makeManager(mx); manager.attach(); - // Manually add to active subscriptions to simulate having visited the room. manager.subscribeToRoom('!room:example.com'); fireMembershipEvent(mx, 'leave'); - expect(room._resetLiveTimeline).toHaveBeenCalledOnce(); + // subscribeToRoom + unsubscribeFromRoom = 2 calls + expect(mocks.slidingSyncInstance.modifyRoomSubscriptions).toHaveBeenCalledTimes(2); }); it('unsubscribes when the local user is banned from an active room', () => { - const room = makeMockRoom(PRUNE_THRESHOLD + 1); - const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const mx = makeMockMx(); const manager = makeManager(mx); manager.attach(); manager.subscribeToRoom('!room:example.com'); fireMembershipEvent(mx, 'ban'); - expect(room._resetLiveTimeline).toHaveBeenCalledOnce(); + expect(mocks.slidingSyncInstance.modifyRoomSubscriptions).toHaveBeenCalledTimes(2); }); it('does nothing when a different user leaves', () => { - const room = makeMockRoom(PRUNE_THRESHOLD + 1); - const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const mx = makeMockMx(); const manager = makeManager(mx); manager.attach(); manager.subscribeToRoom('!room:example.com'); fireMembershipEvent(mx, 'leave', '!room:example.com', '@other:example.com'); - expect(room._resetLiveTimeline).not.toHaveBeenCalled(); + // Only the initial subscribe — no unsubscribe + expect(mocks.slidingSyncInstance.modifyRoomSubscriptions).toHaveBeenCalledTimes(1); }); it('does nothing when membership is join', () => { - const room = makeMockRoom(PRUNE_THRESHOLD + 1); - const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const mx = makeMockMx(); const manager = makeManager(mx); manager.attach(); manager.subscribeToRoom('!room:example.com'); fireMembershipEvent(mx, 'join'); - expect(room._resetLiveTimeline).not.toHaveBeenCalled(); + expect(mocks.slidingSyncInstance.modifyRoomSubscriptions).toHaveBeenCalledTimes(1); }); it('does nothing for a room that was never subscribed', () => { - const room = makeMockRoom(PRUNE_THRESHOLD + 1); - const mx = makeMockMx({ getRoom: vi.fn().mockReturnValue(room) }); + const mx = makeMockMx(); const manager = makeManager(mx); manager.attach(); // registers the listener, but no subscribeToRoom call fireMembershipEvent(mx, 'leave'); - expect(room._resetLiveTimeline).not.toHaveBeenCalled(); + expect(mocks.slidingSyncInstance.modifyRoomSubscriptions).not.toHaveBeenCalled(); }); }); diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 679b48ca..84622b0e 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -1,12 +1,8 @@ /* eslint-disable max-classes-per-file */ import { ClientEvent, - EventTimeline, Extension, ExtensionState, - IJoinedRoom, - IRoomEvent, - ISyncResponse, KnownMembership, MatrixClient, MSC3575List, @@ -55,8 +51,6 @@ const UNENCRYPTED_SUBSCRIPTION_KEY = 'unencrypted'; // Timeline limit for the active-room subscription (full history load). // List entries always use LIST_TIMELINE_LIMIT=1 for lightweight previews. const ACTIVE_ROOM_TIMELINE_LIMIT = 50; -// Events accumulated in a room before its timeline is freed on explicit unsubscribe. -const PRUNE_TIMELINE_THRESHOLD = 100; export type PartialSlidingSyncRequest = { filters?: MSC3575List['filters']; @@ -542,90 +536,6 @@ export class SlidingSyncManager { }); } - /** - * Reset the live timeline for a room that is no longer actively viewed, - * freeing its in-memory event chain. Only fires when the room has accumulated - * more than PRUNE_TIMELINE_THRESHOLD events. - * - * The timeline is reset synchronously so memory is freed immediately. Then, - * as a best-effort fire-and-forget step, the snapshot of recent events is - * fed into the SyncAccumulator and flushed to IndexedDB so they survive an - * app reload (the accumulator caps storage at ~50 events per room; the full - * history is always available from the server). - */ - private pruneRoomTimeline(roomId: string): void { - const room = this.mx.getRoom(roomId); - if (!room) return; - const tl = room.getUnfilteredTimelineSet().getLiveTimeline(); - const events = tl.getEvents(); - if (events.length <= PRUNE_TIMELINE_THRESHOLD) return; - - // Capture the back-pagination token before resetting the timeline. - const prevBatch = tl.getPaginationToken(EventTimeline.BACKWARDS); - - // Free the in-memory event chain immediately. - room.getUnfilteredTimelineSet().resetLiveTimeline(); - - // Persist the tail of the timeline to IndexedDB asynchronously. - // On failure, evict the room from the store so the next open gets a clean - // server fetch rather than potentially stale cached data. - this.persistRoomTimeline( - roomId, - events.map((e) => e.event as IRoomEvent), - prevBatch - ).catch((err: unknown) => { - debugLog.warn('timeline', 'Failed to persist pruned room timeline — evicting store cache', { - roomId, - err, - }); - this.mx.store.removeRoom(roomId); - }); - - debugLog.info('timeline', 'Pruned room timeline from memory', { - roomId, - threshold: PRUNE_TIMELINE_THRESHOLD, - }); - } - - /** - * Persist a snapshot of room timeline events to the IndexedDB store via a - * synthetic /sync payload. This feeds the SyncAccumulator (which the SDK - * uses for both start-up replay and classic sync persistence) so that the - * last ~50 events are available on the next app load without a server round- - * trip. The sliding sync layer never calls setSyncData itself, so this is - * the only path by which sliding-sync rooms get on-disk history. - */ - private async persistRoomTimeline( - roomId: string, - rawEvents: IRoomEvent[], - prevBatch: string | null - ): Promise { - const payload: ISyncResponse = { - next_batch: '', - account_data: { events: [] }, - rooms: { - join: { - [roomId]: { - summary: {}, - timeline: { - events: rawEvents, - limited: true, - prev_batch: prevBatch, - }, - ephemeral: { events: [] }, - account_data: { events: [] }, - unread_notifications: {}, - } as unknown as IJoinedRoom, - }, - invite: {}, - leave: {}, - knock: {}, - }, - }; - await this.mx.store.setSyncData(payload); - await this.mx.store.save(true); - } - public setPresenceEnabled(enabled: boolean): void { this.presenceExtension.setEnabled(enabled); } @@ -1036,7 +946,6 @@ export class SlidingSyncManager { remainingSubscriptions: this.activeRoomSubscriptions.size, syncCycle: this.syncCount, }); - this.pruneRoomTimeline(roomId); } public static async probe( From 4ef628e078f165bcdb1bce298d809535291779ce Mon Sep 17 00:00:00 2001 From: Jae J4 Salokettu Date: Thu, 19 Mar 2026 17:13:46 +0200 Subject: [PATCH 23/28] fix#: correct GitLab docs url following new schema --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 28c7d88f..2a1f7d85 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ You can also download our desktop app for windows and linux from [releases](http ## Self-hosting You have a few options for self hosting, you can: 1. Run the prebuilt docker container. -2. Deploy on a site like GitLab Pages. Jae has a [guide here](https://docs.j4.lc/Public+documentation/Tutorials/Deploying+Sable+on+GitLab+Pages). +2. Deploy on a site like GitLab Pages. Jae has a [guide here](https://docs.j4.lc/Tutorials/Deploying-Sable-on-GitLab-Pages). 3. Build it yourself. ### Docker @@ -85,4 +85,4 @@ pnpm run build # Compiles the app into the dist/ directory ## Deployment and infrastructure Deployment workflows and infrastructure details live in -[`infra/README.md`](infra/README.md). \ No newline at end of file +[`infra/README.md`](infra/README.md). From 54b4da77f78080126ca17af6335e871a68fcc9ea Mon Sep 17 00:00:00 2001 From: Sachin Manimekalai Balakrishnan Date: Thu, 19 Mar 2026 12:07:48 -0400 Subject: [PATCH 24/28] fix: reduce mention highlight background opacity --- .changeset/reduce-mention-highlight-opacity.md | 5 +++++ src/app/components/message/layout/layout.css.ts | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) create mode 100644 .changeset/reduce-mention-highlight-opacity.md diff --git a/.changeset/reduce-mention-highlight-opacity.md b/.changeset/reduce-mention-highlight-opacity.md new file mode 100644 index 00000000..85cb022c --- /dev/null +++ b/.changeset/reduce-mention-highlight-opacity.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Reduced the opacity of mention highlight backgrounds to be less visually intrusive while remaining noticeable. diff --git a/src/app/components/message/layout/layout.css.ts b/src/app/components/message/layout/layout.css.ts index a027af3d..5b15f205 100644 --- a/src/app/components/message/layout/layout.css.ts +++ b/src/app/components/message/layout/layout.css.ts @@ -67,11 +67,11 @@ const HighlightVariant = styleVariants({ const NotifyHighlightVariant = styleVariants({ silent: { - backgroundColor: color.Secondary.Container, + backgroundColor: `color-mix(in srgb, ${color.Secondary.Container} 40%, transparent)`, boxShadow: `inset ${config.borderWidth.B700} 0 0 ${color.Secondary.ContainerLine}`, }, loud: { - backgroundColor: color.Warning.Container, + backgroundColor: `color-mix(in srgb, ${color.Warning.Container} 40%, transparent)`, boxShadow: `inset ${config.borderWidth.B700} 0 0 ${color.Warning.ContainerLine}`, }, }); From 826554a30019289d49dd0e757f97c4c6bdb8e8e3 Mon Sep 17 00:00:00 2001 From: Sachin Manimekalai Balakrishnan Date: Thu, 19 Mar 2026 15:07:05 -0400 Subject: [PATCH 25/28] fix: reduce mention highlight background opacity to 25% --- src/app/components/message/layout/layout.css.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/components/message/layout/layout.css.ts b/src/app/components/message/layout/layout.css.ts index 5b15f205..9928f15e 100644 --- a/src/app/components/message/layout/layout.css.ts +++ b/src/app/components/message/layout/layout.css.ts @@ -67,11 +67,11 @@ const HighlightVariant = styleVariants({ const NotifyHighlightVariant = styleVariants({ silent: { - backgroundColor: `color-mix(in srgb, ${color.Secondary.Container} 40%, transparent)`, + backgroundColor: `color-mix(in srgb, ${color.Secondary.Container} 25%, transparent)`, boxShadow: `inset ${config.borderWidth.B700} 0 0 ${color.Secondary.ContainerLine}`, }, loud: { - backgroundColor: `color-mix(in srgb, ${color.Warning.Container} 40%, transparent)`, + backgroundColor: `color-mix(in srgb, ${color.Warning.Container} 25%, transparent)`, boxShadow: `inset ${config.borderWidth.B700} 0 0 ${color.Warning.ContainerLine}`, }, }); From b7a1cb8d7eca121dff7a99bc1fbed98bcc63171d Mon Sep 17 00:00:00 2001 From: Rye Date: Thu, 19 Mar 2026 20:27:41 +0100 Subject: [PATCH 26/28] added visual marker to mark it as a pmp --- src/app/features/room/message/Message.tsx | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index 0385c7d0..88a4349f 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -401,6 +401,10 @@ function MessageInternal( return convertBeeperFormatToOurPerMessageProfile(pmp); }, [pmp]); + /** + * boolean to indicate wheather we should indicate to the user that it is a pmp + */ + const showPmPInfo = pmp !== undefined; // Profiles and Colors const profile = useUserProfile(senderId, room); const { color: usernameColor, font: usernameFont } = useSableCosmetics(senderId, room); @@ -515,6 +519,26 @@ function MessageInternal( {showPronouns && ( )} + {showPmPInfo && ( + + + + via + + + {senderDisplayName} + + + + )} {tagIconSrc && } From 269e7a16bcf310989fa4ee8a665adf088258441e Mon Sep 17 00:00:00 2001 From: Rye Date: Thu, 19 Mar 2026 20:34:49 +0100 Subject: [PATCH 27/28] fixed placement of space in fallback --- src/app/features/room/RoomInput.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 44094a53..19715dac 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -724,7 +724,7 @@ export const RoomInput = forwardRef( */ const escapedName = sanitizeCustomHtml(perMessageProfile.name); - const htmlPrefix = `${escapedName}: `; + const htmlPrefix = `${escapedName}: `; if (content.formatted_body && !content.formatted_body.startsWith(htmlPrefix)) { content.formatted_body = htmlPrefix + content.formatted_body; From 1a7e71c7fcab4ca65454df8bbd672fafcd0482da Mon Sep 17 00:00:00 2001 From: Rye Date: Thu, 19 Mar 2026 20:40:22 +0100 Subject: [PATCH 28/28] removed unnecessary space oops --- src/app/features/room/RoomInput.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 19715dac..3e264c53 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -731,7 +731,7 @@ export const RoomInput = forwardRef( } else { // we don't have a formatted body, but we need one content.format = 'org.matrix.custom.html'; - content.formatted_body = `${htmlPrefix} ${plainText}`; + content.formatted_body = `${htmlPrefix}${plainText}`; } }