From e1b7844ff84ea307ef5d0997b1c18d25906539ba Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 2 Mar 2026 19:34:51 -0500 Subject: [PATCH 01/13] Add initial sliding sync support --- config.json | 4 + .../settings/developer-tools/DevelopTools.tsx | 2 + .../developer-tools/SyncDiagnostics.tsx | 120 ++++++++++ src/app/hooks/useClientConfig.ts | 11 + .../pages/client/BackgroundNotifications.tsx | 20 +- src/app/pages/client/ClientRoot.tsx | 18 +- .../client/sidebar/AccountSwitcherTab.tsx | 4 +- src/client/initMatrix.ts | 105 ++++++++- src/client/slidingSync.ts | 208 ++++++++++++++++++ src/types/matrix-sdk.ts | 1 + 10 files changed, 477 insertions(+), 16 deletions(-) create mode 100644 src/app/features/settings/developer-tools/SyncDiagnostics.tsx create mode 100644 src/client/slidingSync.ts diff --git a/config.json b/config.json index ef8a5218..5444bfcb 100644 --- a/config.json +++ b/config.json @@ -13,6 +13,10 @@ "webPushAppID": "cc.cinny.web" }, + "slidingSync": { + "enabled": false + }, + "featuredCommunities": { "openAsDefault": false, "spaces": [ diff --git a/src/app/features/settings/developer-tools/DevelopTools.tsx b/src/app/features/settings/developer-tools/DevelopTools.tsx index e9bc3de8..d65c97db 100644 --- a/src/app/features/settings/developer-tools/DevelopTools.tsx +++ b/src/app/features/settings/developer-tools/DevelopTools.tsx @@ -10,6 +10,7 @@ import { AccountDataEditor, AccountDataSubmitCallback } from '$components/Accoun import { copyToClipboard } from '$utils/dom'; import { SequenceCardStyle } from '$features/settings/styles.css'; import { AccountData } from './AccountData'; +import { SyncDiagnostics } from './SyncDiagnostics'; type DeveloperToolsProps = { requestClose: () => void; @@ -111,6 +112,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { )} + {developerTools && } {developerTools && ( { + let joinedRooms = 0; + let inviteRooms = 0; + let roomsMissingName = 0; + let roomsMissingAvatar = 0; + let roomsWithoutLiveEvents = 0; + let roomsWithBackPagination = 0; + + rooms.forEach((room) => { + const membership = room.getMyMembership(); + if (membership === Membership.Join) joinedRooms += 1; + if (membership === Membership.Invite) inviteRooms += 1; + + if (!room.name || room.name.trim().length === 0) roomsMissingName += 1; + + const roomAvatar = room.getMxcAvatarUrl(); + const fallbackAvatar = room.getAvatarFallbackMember()?.getMxcAvatarUrl(); + if (!roomAvatar && !fallbackAvatar) roomsMissingAvatar += 1; + + const liveTimeline = room.getLiveTimeline(); + if (liveTimeline.getEvents().length === 0) roomsWithoutLiveEvents += 1; + if (liveTimeline.getPaginationToken(Direction.Backward)) roomsWithBackPagination += 1; + }); + + return { + totalRooms: rooms.length, + joinedRooms, + inviteRooms, + roomsMissingName, + roomsMissingAvatar, + roomsWithoutLiveEvents, + roomsWithBackPagination, + }; +}; + +const formatListCoverage = (knownCount: number, rangeEnd: number): string => { + if (knownCount <= 0) return '0/0'; + const loadedCount = Math.max(0, Math.min(knownCount, rangeEnd + 1)); + return `${loadedCount}/${knownCount}`; +}; + +export function SyncDiagnostics() { + const mx = useMatrixClient(); + const clientConfig = useClientConfig(); + const [, setTick] = useState(0); + + useEffect(() => { + const intervalId = window.setInterval(() => setTick((v) => v + 1), 1000); + return () => window.clearInterval(intervalId); + }, []); + + const diagnostics = getClientSyncDiagnostics(mx); + const roomDiagnostics = getRoomRenderingDiagnostics(mx.getRooms()); + + return ( + + Sync Diagnostics + + + + Transport: {diagnostics.transport} + {diagnostics.fallbackFromSliding ? ' (fallback)' : ''} + + State: {diagnostics.syncState ?? 'null'} + + Sliding configured: {clientConfig.slidingSync?.enabled ? 'yes' : 'no'} + + + Room counts: {roomDiagnostics.totalRooms} total, {roomDiagnostics.joinedRooms} joined,{' '} + {roomDiagnostics.inviteRooms} invites + + Rooms missing name: {roomDiagnostics.roomsMissingName} + Rooms missing avatar: {roomDiagnostics.roomsMissingAvatar} + + Rooms without live events: {roomDiagnostics.roomsWithoutLiveEvents} + + + Rooms with more history to paginate: {roomDiagnostics.roomsWithBackPagination} + + + {diagnostics.sliding && ( + <> + Sliding proxy: {diagnostics.sliding.proxyBaseUrl} + {diagnostics.sliding.lists.map((list) => ( + + List `{list.key}` coverage: {formatListCoverage(list.knownCount, list.rangeEnd)} + + ))} + + )} + + + + ); +} diff --git a/src/app/hooks/useClientConfig.ts b/src/app/hooks/useClientConfig.ts index b47dc5c4..6f795a80 100644 --- a/src/app/hooks/useClientConfig.ts +++ b/src/app/hooks/useClientConfig.ts @@ -20,6 +20,17 @@ export type ClientConfig = { webPushAppID?: string; }; + slidingSync?: { + enabled?: boolean; + proxyBaseUrl?: string; + listPageSize?: number; + timelineLimit?: number; + pollTimeoutMs?: number; + maxRooms?: number; + includeInviteList?: boolean; + probeTimeoutMs?: number; + }; + featuredCommunities?: { openAsDefault?: boolean; spaces?: string[]; diff --git a/src/app/pages/client/BackgroundNotifications.tsx b/src/app/pages/client/BackgroundNotifications.tsx index 33d60838..d66c1e7d 100644 --- a/src/app/pages/client/BackgroundNotifications.tsx +++ b/src/app/pages/client/BackgroundNotifications.tsx @@ -27,10 +27,15 @@ import { nicknamesAtom } from '$state/nicknames'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { buildRoomMessageNotification } from '$utils/notificationStyle'; import { mobileOrTablet } from '$utils/user-agent'; +import { startClient, stopClient } from '$client/initMatrix'; +import { useClientConfig } from '$hooks/useClientConfig'; const log = createLogger('BackgroundNotifications'); -const startBackgroundClient = async (session: Session): Promise => { +const startBackgroundClient = async ( + session: Session, + slidingSyncConfig: ReturnType['slidingSync'] +): Promise => { const mx = createClient({ baseUrl: session.baseUrl, accessToken: session.accessToken, @@ -38,7 +43,10 @@ const startBackgroundClient = async (session: Session): Promise => deviceId: session.deviceId, timelineSupport: false, }); - await mx.startClient({ lazyLoadMembers: true, initialSyncLimit: 0 }); + await startClient(mx, { + baseUrl: session.baseUrl, + slidingSync: slidingSyncConfig, + }); return mx; }; @@ -63,6 +71,7 @@ const waitForSync = (mx: MatrixClient): Promise => }); export function BackgroundNotifications() { + const clientConfig = useClientConfig(); const sessions = useAtomValue(sessionsAtom); const activeSessionId = useAtomValue(activeSessionIdAtom); const setActiveSessionId = useSetAtom(activeSessionIdAtom); @@ -128,7 +137,7 @@ export function BackgroundNotifications() { current.forEach((mx, userId) => { if (!activeIds.has(userId)) { log.log('stopping background client for', userId); - mx.stopClient(); + stopClient(mx); current.delete(userId); } }); @@ -137,7 +146,7 @@ export function BackgroundNotifications() { if (current.has(session.userId)) return; log.log('starting background client for', session.userId); - startBackgroundClient(session) + startBackgroundClient(session, clientConfig.slidingSync) .then(async (mx) => { current.set(session.userId, mx); @@ -229,10 +238,11 @@ export function BackgroundNotifications() { }); return () => { - current.forEach((mx) => mx.stopClient()); + current.forEach((mx) => stopClient(mx)); current.clear(); }; }, [ + clientConfig.slidingSync, inactiveSessions, forcePushOnMobile, showNotifications, diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx index 4f06f56e..1fd61d4b 100644 --- a/src/app/pages/client/ClientRoot.tsx +++ b/src/app/pages/client/ClientRoot.tsx @@ -25,6 +25,7 @@ import { initClient, logoutClient, startClient, + stopClient, } from '$client/initMatrix'; import { SplashScreen } from '$components/splash-screen'; import { ServerConfigsLoader } from '$components/ServerConfigsLoader'; @@ -40,6 +41,7 @@ import { createLogger } from '$utils/debug'; import { useSyncNicknames } from '$hooks/useNickname'; import { useAppVisibility } from '$hooks/useAppVisibility'; import { getHomePath } from '$pages/pathUtils'; +import { useClientConfig } from '$hooks/useClientConfig'; import { pushSessionToSW } from '../../../sw-session'; import { SyncStatus } from './SyncStatus'; import { SpecVersions } from './SpecVersions'; @@ -139,7 +141,7 @@ function ClientRootOptions({ mx, onLogout }: ClientRootOptionsProps) { const useLogoutListener = (mx?: MatrixClient) => { useEffect(() => { const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async () => { - mx?.stopClient(); + if (mx) stopClient(mx); await mx?.clearStores(); window.localStorage.clear(); window.location.reload(); @@ -158,6 +160,7 @@ type ClientRootProps = { export function ClientRoot({ children }: ClientRootProps) { const [loading, setLoading] = useState(true); const navigate = useNavigate(); + const clientConfig = useClientConfig(); const sessions = useAtomValue(sessionsAtom); const [activeSessionId, setActiveSessionId] = useAtom(activeSessionIdAtom); const setSessions = useSetAtom(sessionsAtom); @@ -189,7 +192,14 @@ export function ClientRoot({ children }: ClientRootProps) { ); const mx = loadState.status === AsyncStatus.Success ? loadState.data : undefined; const [startState, startMatrix] = useAsyncCallback( - useCallback((m) => startClient(m), []) + useCallback( + (m) => + startClient(m, { + baseUrl: activeSession?.baseUrl, + slidingSync: clientConfig.slidingSync, + }), + [activeSession?.baseUrl, clientConfig.slidingSync] + ) ); useEffect(() => { @@ -205,7 +215,7 @@ export function ClientRoot({ children }: ClientRootProps) { // Update the SW immediately so media requests use the new account's token pushSessionToSW(activeSession.baseUrl, activeSession.accessToken); if (mx?.clientRunning) { - mx.stopClient(); + stopClient(mx); } setLoading(true); loadedUserIdRef.current = undefined; @@ -231,7 +241,7 @@ export function ClientRoot({ children }: ClientRootProps) { () => () => { if (mx?.clientRunning) { log.log('ClientRoot unmounting — stopping client', mx.getUserId()); - mx.stopClient(); + stopClient(mx); } }, [mx] diff --git a/src/app/pages/client/sidebar/AccountSwitcherTab.tsx b/src/app/pages/client/sidebar/AccountSwitcherTab.tsx index a41e7172..727623f6 100644 --- a/src/app/pages/client/sidebar/AccountSwitcherTab.tsx +++ b/src/app/pages/client/sidebar/AccountSwitcherTab.tsx @@ -24,7 +24,7 @@ import { nameInitials } from '$utils/common'; import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix'; import { stopPropagation } from '$utils/keyboard'; import { getHomePath, getLoginPath, withSearchParam } from '$pages/pathUtils'; -import { logoutClient, initClient } from '$client/initMatrix'; +import { logoutClient, initClient, stopClient } from '$client/initMatrix'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useUserProfile } from '$hooks/useUserProfile'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; @@ -201,7 +201,7 @@ export function AccountSwitcherTab() { const handleAddAccount = () => { const url = withSearchParam(getLoginPath(), { addAccount: '1' }); setMenuAnchor(undefined); - mx.stopClient(); + stopClient(mx); setTimeout(() => window.location.assign(url), 100); }; diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 40f1c283..e77072a7 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -17,8 +17,17 @@ import { getLocalStorageItem } from '$state/utils/atomWithLocalStorage'; import { createLogger } from '$utils/debug'; import { pushSessionToSW } from '../sw-session'; import { cryptoCallbacks } from './secretStorageKeys'; +import { SlidingSyncConfig, SlidingSyncDiagnostics, SlidingSyncManager } from './slidingSync'; const log = createLogger('initMatrix'); +const slidingSyncByClient = new WeakMap(); +type SyncTransport = 'classic' | 'sliding'; +type SyncTransportMeta = { + transport: SyncTransport; + slidingConfigured: boolean; + fallbackFromSliding: boolean; +}; +const syncTransportByClient = new WeakMap(); const deleteDatabase = (name: string): Promise => new Promise((resolve) => { @@ -244,21 +253,107 @@ export const initClient = async (session: Session): Promise => { return mx; }; -export const startClient = async (mx: MatrixClient) => { +export type StartClientConfig = { + baseUrl?: string; + slidingSync?: SlidingSyncConfig; +}; + +export type ClientSyncDiagnostics = SyncTransportMeta & { + syncState: string | null; + sliding?: SlidingSyncDiagnostics; +}; + +const disposeSlidingSync = (mx: MatrixClient): void => { + const manager = slidingSyncByClient.get(mx); + if (!manager) return; + manager.dispose(); + slidingSyncByClient.delete(mx); +}; + +export const stopClient = (mx: MatrixClient): void => { + disposeSlidingSync(mx); + mx.stopClient(); +}; + +export const startClient = async (mx: MatrixClient, config?: StartClientConfig) => { log.log('startClient', mx.getUserId()); - await mx.startClient({ - lazyLoadMembers: true, + disposeSlidingSync(mx); + const slidingConfig = config?.slidingSync; + const proxyBaseUrl = slidingConfig?.proxyBaseUrl ?? config?.baseUrl; + const canUseSliding = slidingConfig?.enabled === true && typeof proxyBaseUrl === 'string'; + syncTransportByClient.set(mx, { + transport: 'classic', + slidingConfigured: slidingConfig?.enabled === true, + fallbackFromSliding: false, }); + + if (!canUseSliding) { + await mx.startClient({ + lazyLoadMembers: true, + }); + return; + } + + const resolvedProxyBaseUrl = proxyBaseUrl; + const manager = new SlidingSyncManager(mx, resolvedProxyBaseUrl, slidingConfig); + const supported = await SlidingSyncManager.probe( + mx, + resolvedProxyBaseUrl, + manager.probeTimeoutMs + ); + if (!supported) { + syncTransportByClient.set(mx, { + transport: 'classic', + slidingConfigured: true, + fallbackFromSliding: true, + }); + log.warn('Sliding Sync unavailable, falling back to classic sync for', mx.getUserId()); + await mx.startClient({ + lazyLoadMembers: true, + }); + return; + } + + manager.attach(); + slidingSyncByClient.set(mx, manager); + syncTransportByClient.set(mx, { + transport: 'sliding', + slidingConfigured: true, + fallbackFromSliding: false, + }); + + try { + await mx.startClient({ + lazyLoadMembers: true, + slidingSync: manager.slidingSync, + }); + } catch (err) { + disposeSlidingSync(mx); + throw err; + } }; export const clearCacheAndReload = async (mx: MatrixClient) => { log.log('clearCacheAndReload', mx.getUserId()); - mx.stopClient(); + stopClient(mx); clearNavToActivePathStore(mx.getSafeUserId()); await mx.store.deleteAllData(); window.location.reload(); }; +export const getClientSyncDiagnostics = (mx: MatrixClient): ClientSyncDiagnostics => { + const meta = syncTransportByClient.get(mx) ?? { + transport: 'classic', + slidingConfigured: false, + fallbackFromSliding: false, + }; + return { + ...meta, + syncState: mx.getSyncState(), + sliding: slidingSyncByClient.get(mx)?.getDiagnostics(), + }; +}; + /** * Logs out a Matrix client and cleans up its SDK stores + IndexedDB databases. * Does NOT touch the Jotai sessions atom — callers must do that themselves @@ -267,7 +362,7 @@ export const clearCacheAndReload = async (mx: MatrixClient) => { export const logoutClient = async (mx: MatrixClient, session?: Session) => { log.log('logoutClient', { userId: mx.getUserId(), sessionUserId: session?.userId }); pushSessionToSW(); - mx.stopClient(); + stopClient(mx); try { await mx.logout(); } catch { diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts new file mode 100644 index 00000000..11051d2e --- /dev/null +++ b/src/client/slidingSync.ts @@ -0,0 +1,208 @@ +import { + MatrixClient, + MSC3575List, + MSC3575RoomSubscription, + SlidingSync, + SlidingSyncEvent, + SlidingSyncState, + MSC3575_STATE_KEY_LAZY, + MSC3575_STATE_KEY_ME, + EventType, +} from '$types/matrix-sdk'; +import { createLogger } from '$utils/debug'; + +const log = createLogger('slidingSync'); + +const LIST_JOINED = 'joined'; +const LIST_INVITES = 'invites'; +const DEFAULT_LIST_PAGE_SIZE = 50; +const DEFAULT_TIMELINE_LIMIT = 30; +const DEFAULT_POLL_TIMEOUT_MS = 30000; +const DEFAULT_MAX_ROOMS = 5000; + +export type SlidingSyncConfig = { + enabled?: boolean; + proxyBaseUrl?: string; + listPageSize?: number; + timelineLimit?: number; + pollTimeoutMs?: number; + maxRooms?: number; + includeInviteList?: boolean; + probeTimeoutMs?: number; +}; + +export type SlidingSyncListDiagnostics = { + key: string; + knownCount: number; + rangeEnd: number; +}; + +export type SlidingSyncDiagnostics = { + proxyBaseUrl: string; + lists: SlidingSyncListDiagnostics[]; +}; + +const clampPositive = (value: number | undefined, fallback: number): number => { + if (typeof value !== 'number' || Number.isNaN(value) || value <= 0) return fallback; + return Math.round(value); +}; + +const buildDefaultSubscription = (timelineLimit: number): MSC3575RoomSubscription => ({ + timeline_limit: timelineLimit, + required_state: [ + [EventType.RoomMember, MSC3575_STATE_KEY_ME], + [EventType.RoomMember, MSC3575_STATE_KEY_LAZY], + [EventType.RoomCreate, ''], + [EventType.RoomName, ''], + [EventType.RoomAvatar, ''], + [EventType.RoomCanonicalAlias, ''], + [EventType.RoomEncryption, ''], + [EventType.RoomTombstone, ''], + [EventType.RoomJoinRules, ''], + [EventType.RoomHistoryVisibility, ''], + [EventType.SpaceChild, '*'], + [EventType.SpaceParent, '*'], + ], +}); + +const buildLists = ( + pageSize: number, + timelineLimit: number, + includeInviteList: boolean +): Map => { + const lists = new Map(); + lists.set(LIST_JOINED, { + ranges: [[0, Math.max(0, pageSize - 1)]], + timeline_limit: timelineLimit, + slow_get_all_rooms: true, + filters: { + is_invite: false, + }, + }); + + if (includeInviteList) { + lists.set(LIST_INVITES, { + ranges: [[0, Math.max(0, pageSize - 1)]], + timeline_limit: timelineLimit, + slow_get_all_rooms: true, + filters: { + is_invite: true, + }, + }); + } + + return lists; +}; + +const getListEndIndex = (list: MSC3575List | null): number => { + if (!list?.ranges?.length) return -1; + return list.ranges.reduce((max, range) => Math.max(max, range[1] ?? -1), -1); +}; + +export class SlidingSyncManager { + private disposed = false; + + private readonly maxRooms: number; + + private readonly listKeys: string[]; + + private readonly onLifecycle: (state: SlidingSyncState, resp: unknown, err?: Error) => void; + + public readonly slidingSync: SlidingSync; + + public readonly probeTimeoutMs: number; + + public constructor( + private readonly mx: MatrixClient, + private readonly proxyBaseUrl: string, + config: SlidingSyncConfig + ) { + const listPageSize = clampPositive(config.listPageSize, DEFAULT_LIST_PAGE_SIZE); + const timelineLimit = clampPositive(config.timelineLimit, DEFAULT_TIMELINE_LIMIT); + const pollTimeoutMs = clampPositive(config.pollTimeoutMs, DEFAULT_POLL_TIMEOUT_MS); + this.probeTimeoutMs = clampPositive(config.probeTimeoutMs, 5000); + this.maxRooms = clampPositive(config.maxRooms, DEFAULT_MAX_ROOMS); + const includeInviteList = config.includeInviteList !== false; + + const subscription = buildDefaultSubscription(timelineLimit); + const lists = buildLists(listPageSize, timelineLimit, includeInviteList); + this.listKeys = Array.from(lists.keys()); + this.slidingSync = new SlidingSync(proxyBaseUrl, lists, subscription, mx, pollTimeoutMs); + + this.onLifecycle = (state, resp, err) => { + if (this.disposed || err || !resp || state !== SlidingSyncState.Complete) return; + this.expandListsToKnownCount(); + }; + } + + public attach(): void { + this.slidingSync.on(SlidingSyncEvent.Lifecycle, this.onLifecycle); + } + + public dispose(): void { + if (this.disposed) return; + this.disposed = true; + this.slidingSync.removeListener(SlidingSyncEvent.Lifecycle, this.onLifecycle); + } + + public getDiagnostics(): SlidingSyncDiagnostics { + return { + proxyBaseUrl: this.proxyBaseUrl, + lists: this.listKeys.map((key) => { + const listData = this.slidingSync.getListData(key); + const params = this.slidingSync.getListParams(key); + return { + key, + knownCount: listData?.joinedCount ?? 0, + rangeEnd: getListEndIndex(params), + }; + }), + }; + } + + private expandListsToKnownCount(): void { + this.listKeys.forEach((key) => { + const listData = this.slidingSync.getListData(key); + const knownCount = listData?.joinedCount ?? 0; + if (knownCount <= 0) return; + + const desiredEnd = Math.min(knownCount, this.maxRooms) - 1; + const existing = this.slidingSync.getListParams(key); + const currentEnd = getListEndIndex(existing); + if (desiredEnd === currentEnd) return; + + this.slidingSync.setListRanges(key, [[0, desiredEnd]]); + if (knownCount > this.maxRooms) { + log.warn( + `Sliding Sync list "${key}" capped at ${this.maxRooms}/${knownCount} rooms for ${this.mx.getUserId()}` + ); + } + }); + } + + public static async probe( + mx: MatrixClient, + proxyBaseUrl: string, + probeTimeoutMs: number + ): Promise { + try { + const response = await mx.slidingSync( + { + lists: { + probe: { + ranges: [[0, 0]], + timeline_limit: 1, + }, + }, + timeout: 0, + clientTimeout: probeTimeoutMs, + }, + proxyBaseUrl + ); + + return typeof response.pos === 'string' && response.pos.length > 0; + } catch { + return false; + } + } +} diff --git a/src/types/matrix-sdk.ts b/src/types/matrix-sdk.ts index 2e08feca..fcfef123 100644 --- a/src/types/matrix-sdk.ts +++ b/src/types/matrix-sdk.ts @@ -10,6 +10,7 @@ export * from 'matrix-js-sdk/lib/interactive-auth'; export * from 'matrix-js-sdk/lib/content-repo'; export * from 'matrix-js-sdk/lib/sync'; export * from 'matrix-js-sdk/lib/sync-accumulator'; +export * from 'matrix-js-sdk/lib/sliding-sync'; export { createClient } from 'matrix-js-sdk/lib/matrix'; export * from 'matrix-js-sdk/lib/models/event'; From a22e82459056ef02c05bd5c6a702858db9b6ae68 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 2 Mar 2026 20:48:39 -0500 Subject: [PATCH 02/13] vscode merge issue fml --- src/types/matrix-sdk.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/types/matrix-sdk.ts b/src/types/matrix-sdk.ts index 014421e8..942a94d3 100644 --- a/src/types/matrix-sdk.ts +++ b/src/types/matrix-sdk.ts @@ -14,10 +14,8 @@ export * from 'matrix-js-sdk/lib/interactive-auth'; export * from 'matrix-js-sdk/lib/content-repo'; export * from 'matrix-js-sdk/lib/sync'; export * from 'matrix-js-sdk/lib/sync-accumulator'; -<<<<<<< HEAD export * from 'matrix-js-sdk/lib/sliding-sync'; export { createClient } from 'matrix-js-sdk/lib/matrix'; -======= const amendClientOpts = (opts: ICreateClientOpts): ICreateClientOpts => ({ ...opts, @@ -30,7 +28,6 @@ const amendClientOpts = (opts: ICreateClientOpts): ICreateClientOpts => ({ // a production bundling init-order bug involving RoomWidgetClient re-exports. export const createClient = (opts: ICreateClientOpts): MatrixClient => new MatrixClient(amendClientOpts(opts)); ->>>>>>> origin export * from 'matrix-js-sdk/lib/models/event'; export * from 'matrix-js-sdk/lib/models/room'; From ec46b898d6be7a3fa678faba5ea2dd52aa01d09a Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 2 Mar 2026 20:51:53 -0500 Subject: [PATCH 03/13] Fix duplicate exports --- src/types/matrix-sdk.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/types/matrix-sdk.ts b/src/types/matrix-sdk.ts index 942a94d3..f6c5c7db 100644 --- a/src/types/matrix-sdk.ts +++ b/src/types/matrix-sdk.ts @@ -14,8 +14,6 @@ export * from 'matrix-js-sdk/lib/interactive-auth'; export * from 'matrix-js-sdk/lib/content-repo'; export * from 'matrix-js-sdk/lib/sync'; export * from 'matrix-js-sdk/lib/sync-accumulator'; -export * from 'matrix-js-sdk/lib/sliding-sync'; -export { createClient } from 'matrix-js-sdk/lib/matrix'; const amendClientOpts = (opts: ICreateClientOpts): ICreateClientOpts => ({ ...opts, From 93c63764190842802d94f57175730257adb3a6bd Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 2 Mar 2026 20:53:49 -0500 Subject: [PATCH 04/13] Fix exports --- src/types/matrix-sdk.ts | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/src/types/matrix-sdk.ts b/src/types/matrix-sdk.ts index f6c5c7db..b4a7d09a 100644 --- a/src/types/matrix-sdk.ts +++ b/src/types/matrix-sdk.ts @@ -7,6 +7,7 @@ import { MemoryCryptoStore } from 'matrix-js-sdk/lib/crypto/store/memory-crypto- // Import Matrix symbols from this module instead of matrix-js-sdk directly. export * from 'matrix-js-sdk/lib/client'; export * from 'matrix-js-sdk/lib/serverCapabilities'; +export * from 'matrix-js-sdk/lib/embedded'; export * from 'matrix-js-sdk/lib/http-api/index'; export * from 'matrix-js-sdk/lib/autodiscovery'; export * from 'matrix-js-sdk/lib/errors'; @@ -14,18 +15,7 @@ export * from 'matrix-js-sdk/lib/interactive-auth'; export * from 'matrix-js-sdk/lib/content-repo'; export * from 'matrix-js-sdk/lib/sync'; export * from 'matrix-js-sdk/lib/sync-accumulator'; - -const amendClientOpts = (opts: ICreateClientOpts): ICreateClientOpts => ({ - ...opts, - store: opts.store ?? new MemoryStore({ localStorage: globalThis.localStorage }), - scheduler: opts.scheduler ?? new MatrixScheduler(), - cryptoStore: opts.cryptoStore ?? new MemoryCryptoStore(), -}); - -// Intentionally avoid importing createClient from matrix-js-sdk/lib/matrix to sidestep -// a production bundling init-order bug involving RoomWidgetClient re-exports. -export const createClient = (opts: ICreateClientOpts): MatrixClient => - new MatrixClient(amendClientOpts(opts)); +export { createClient } from 'matrix-js-sdk/lib/matrix'; export * from 'matrix-js-sdk/lib/models/event'; export * from 'matrix-js-sdk/lib/models/room'; From 9a02d219673838ca783636d3560991ae686138cb Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 2 Mar 2026 21:08:31 -0500 Subject: [PATCH 05/13] enable sliding sync by default --- src/client/initMatrix.ts | 9 +++++---- src/types/matrix-sdk.ts | 9 +++------ 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index e77072a7..2fea56c9 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -280,10 +280,11 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig) disposeSlidingSync(mx); const slidingConfig = config?.slidingSync; const proxyBaseUrl = slidingConfig?.proxyBaseUrl ?? config?.baseUrl; - const canUseSliding = slidingConfig?.enabled === true && typeof proxyBaseUrl === 'string'; + const slidingEnabled = slidingConfig?.enabled !== false; + const canUseSliding = slidingEnabled && typeof proxyBaseUrl === 'string'; syncTransportByClient.set(mx, { transport: 'classic', - slidingConfigured: slidingConfig?.enabled === true, + slidingConfigured: canUseSliding, fallbackFromSliding: false, }); @@ -295,7 +296,7 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig) } const resolvedProxyBaseUrl = proxyBaseUrl; - const manager = new SlidingSyncManager(mx, resolvedProxyBaseUrl, slidingConfig); + const manager = new SlidingSyncManager(mx, resolvedProxyBaseUrl, slidingConfig ?? {}); const supported = await SlidingSyncManager.probe( mx, resolvedProxyBaseUrl, @@ -304,7 +305,7 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig) if (!supported) { syncTransportByClient.set(mx, { transport: 'classic', - slidingConfigured: true, + slidingConfigured: canUseSliding, fallbackFromSliding: true, }); log.warn('Sliding Sync unavailable, falling back to classic sync for', mx.getUserId()); diff --git a/src/types/matrix-sdk.ts b/src/types/matrix-sdk.ts index b4a7d09a..71621d88 100644 --- a/src/types/matrix-sdk.ts +++ b/src/types/matrix-sdk.ts @@ -1,20 +1,17 @@ -import { MatrixClient, ICreateClientOpts } from 'matrix-js-sdk/lib/client'; -import { MatrixScheduler } from 'matrix-js-sdk/lib/scheduler'; -import { MemoryStore } from 'matrix-js-sdk/lib/store/memory'; -import { MemoryCryptoStore } from 'matrix-js-sdk/lib/crypto/store/memory-crypto-store'; - // App-facing Matrix SDK import boundary. // Import Matrix symbols from this module instead of matrix-js-sdk directly. export * from 'matrix-js-sdk/lib/client'; export * from 'matrix-js-sdk/lib/serverCapabilities'; -export * from 'matrix-js-sdk/lib/embedded'; export * from 'matrix-js-sdk/lib/http-api/index'; export * from 'matrix-js-sdk/lib/autodiscovery'; export * from 'matrix-js-sdk/lib/errors'; export * from 'matrix-js-sdk/lib/interactive-auth'; export * from 'matrix-js-sdk/lib/content-repo'; export * from 'matrix-js-sdk/lib/sync'; +export * from 'matrix-js-sdk/lib/sliding-sync'; export * from 'matrix-js-sdk/lib/sync-accumulator'; +export * from 'matrix-js-sdk/lib/scheduler'; +export * from 'matrix-js-sdk/lib/store/memory'; export { createClient } from 'matrix-js-sdk/lib/matrix'; export * from 'matrix-js-sdk/lib/models/event'; From a6c7be6f644fb2440ab8352b1d6c14cf93b0b50a Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 2 Mar 2026 21:36:54 -0500 Subject: [PATCH 06/13] fix sliding sync server requirements --- config.json | 2 +- src/app/features/settings/developer-tools/SyncDiagnostics.tsx | 4 +--- src/client/slidingSync.ts | 3 +++ 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/config.json b/config.json index 5444bfcb..a4f53ec9 100644 --- a/config.json +++ b/config.json @@ -14,7 +14,7 @@ }, "slidingSync": { - "enabled": false + "enabled": true }, "featuredCommunities": { diff --git a/src/app/features/settings/developer-tools/SyncDiagnostics.tsx b/src/app/features/settings/developer-tools/SyncDiagnostics.tsx index 20bee11b..54c0576c 100644 --- a/src/app/features/settings/developer-tools/SyncDiagnostics.tsx +++ b/src/app/features/settings/developer-tools/SyncDiagnostics.tsx @@ -2,7 +2,6 @@ import { useEffect, useState } from 'react'; import { Box, Text } from 'folds'; import { SequenceCard } from '$components/sequence-card'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { useClientConfig } from '$hooks/useClientConfig'; import { getClientSyncDiagnostics } from '$client/initMatrix'; import { Direction, Room } from '$types/matrix-sdk'; import { Membership } from '$types/matrix/room'; @@ -61,7 +60,6 @@ const formatListCoverage = (knownCount: number, rangeEnd: number): string => { export function SyncDiagnostics() { const mx = useMatrixClient(); - const clientConfig = useClientConfig(); const [, setTick] = useState(0); useEffect(() => { @@ -88,7 +86,7 @@ export function SyncDiagnostics() { State: {diagnostics.syncState ?? 'null'} - Sliding configured: {clientConfig.slidingSync?.enabled ? 'yes' : 'no'} + Sliding configured: {diagnostics.slidingConfigured ? 'yes' : 'no'} Room counts: {roomDiagnostics.totalRooms} total, {roomDiagnostics.joinedRooms} joined,{' '} diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 11051d2e..913cc83b 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -74,6 +74,7 @@ const buildLists = ( lists.set(LIST_JOINED, { ranges: [[0, Math.max(0, pageSize - 1)]], timeline_limit: timelineLimit, + required_state: [], slow_get_all_rooms: true, filters: { is_invite: false, @@ -84,6 +85,7 @@ const buildLists = ( lists.set(LIST_INVITES, { ranges: [[0, Math.max(0, pageSize - 1)]], timeline_limit: timelineLimit, + required_state: [], slow_get_all_rooms: true, filters: { is_invite: true, @@ -192,6 +194,7 @@ export class SlidingSyncManager { probe: { ranges: [[0, 0]], timeline_limit: 1, + required_state: [], }, }, timeout: 0, From 305e4c18772503da25fb574e1ea532056f605c87 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Mon, 2 Mar 2026 21:43:12 -0500 Subject: [PATCH 07/13] set sliding sync default to false --- config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config.json b/config.json index a4f53ec9..5444bfcb 100644 --- a/config.json +++ b/config.json @@ -14,7 +14,7 @@ }, "slidingSync": { - "enabled": true + "enabled": false }, "featuredCommunities": { From 0e076485cd8af1efa3387226426afea34e9e7fe4 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 3 Mar 2026 00:05:46 -0500 Subject: [PATCH 08/13] Various fixes for UI/Rendering issues in sliding sync --- .../developer-tools/DevelopTools.tsx | 110 +++++++++++++++++- .../room/message/EncryptedContent.tsx | 7 ++ .../developer-tools/SyncDiagnostics.tsx | 61 +++++++++- src/app/state/room/roomToUnread.ts | 56 +++++++++ src/app/utils/notifications.ts | 12 ++ src/app/utils/room.ts | 29 ++++- src/client/slidingSync.ts | 14 ++- 7 files changed, 280 insertions(+), 9 deletions(-) diff --git a/src/app/features/common-settings/developer-tools/DevelopTools.tsx b/src/app/features/common-settings/developer-tools/DevelopTools.tsx index 7925d44a..1d4c53e0 100644 --- a/src/app/features/common-settings/developer-tools/DevelopTools.tsx +++ b/src/app/features/common-settings/developer-tools/DevelopTools.tsx @@ -1,4 +1,5 @@ -import { useCallback, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useAtomValue } from 'jotai'; import { Box, Text, @@ -12,6 +13,7 @@ import { config, color, } from 'folds'; +import { EventType, NotificationCountType } from '$types/matrix-sdk'; import { Page, PageContent, PageHeader } from '$components/page'; import { SequenceCard } from '$components/sequence-card'; import { SettingTile } from '$components/setting-tile'; @@ -21,6 +23,8 @@ import { copyToClipboard } from '$utils/dom'; import { useRoom } from '$hooks/useRoom'; import { useRoomState } from '$hooks/useRoomState'; import { useRoomAccountData } from '$hooks/useRoomAccountData'; +import { roomToUnreadAtom } from '$state/room/roomToUnread'; +import { isNotificationEvent } from '$utils/room'; import { CutoutCard } from '$components/cutout-card'; import { AccountDataEditor, AccountDataSubmitCallback } from '$components/AccountDataEditor'; import { useMatrixClient } from '$hooks/useMatrixClient'; @@ -46,6 +50,61 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { const [expandAccountData, setExpandAccountData] = useState(false); const [accountDataType, setAccountDataType] = useState(); + const roomToUnread = useAtomValue(roomToUnreadAtom); + const [, setTick] = useState(0); + + useEffect(() => { + const intervalId = window.setInterval(() => setTick((v) => v + 1), 1000); + return () => window.clearInterval(intervalId); + }, []); + + const unreadDiagnostics = useMemo(() => { + const userId = mx.getUserId(); + const liveEvents = room.getLiveTimeline().getEvents(); + const latestLiveEvent = liveEvents[liveEvents.length - 1]; + const latestLiveEventId = latestLiveEvent?.getId() ?? null; + const latestNotificationEvent = [...liveEvents] + .reverse() + .find((event) => isNotificationEvent(event)); + const latestNotificationEventId = latestNotificationEvent?.getId() ?? null; + const fullyReadEventId = + room.getAccountData(EventType.FullyRead)?.getContent<{ event_id?: string }>()?.event_id ?? + null; + const readUpToEventId = userId ? (room.getEventReadUpTo(userId) ?? null) : null; + const sdkUnreadTotal = room.getUnreadNotificationCount(NotificationCountType.Total); + const sdkUnreadHighlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); + const atomUnread = roomToUnread.get(room.roomId); + + return { + roomId: room.roomId, + userId: userId ?? null, + timelineSize: liveEvents.length, + latestLiveEventId, + latestNotificationEventId, + fullyReadEventId, + readUpToEventId, + hasReadLatestLive: !!( + userId && + latestLiveEventId && + room.hasUserReadEvent(userId, latestLiveEventId) + ), + hasReadLatestNotification: !!( + userId && + latestNotificationEventId && + room.hasUserReadEvent(userId, latestNotificationEventId) + ), + sdkUnread: { + total: sdkUnreadTotal, + highlight: sdkUnreadHighlight, + }, + atomUnread: atomUnread + ? { + total: atomUnread.total, + highlight: atomUnread.highlight, + } + : null, + }; + }, [mx, room, roomToUnread]); const handleClose = useCallback(() => { setOpenStateEvent(undefined); @@ -203,6 +262,55 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) { /> {expandState && ( + + + Unread Diagnostics + + + + `readUpTo`: {unreadDiagnostics.readUpToEventId ?? 'null'} + + + `m.fully_read`: {unreadDiagnostics.fullyReadEventId ?? 'null'} + + + Latest live: {unreadDiagnostics.latestLiveEventId ?? 'null'} | read?{' '} + {unreadDiagnostics.hasReadLatestLive ? 'yes' : 'no'} + + + Latest notification:{' '} + {unreadDiagnostics.latestNotificationEventId ?? 'null'} | read?{' '} + {unreadDiagnostics.hasReadLatestNotification ? 'yes' : 'no'} + + + SDK unread: {unreadDiagnostics.sdkUnread.total} total /{' '} + {unreadDiagnostics.sdkUnread.highlight} highlight + + + Atom unread:{' '} + {unreadDiagnostics.atomUnread + ? `${unreadDiagnostics.atomUnread.total} total / ${unreadDiagnostics.atomUnread.highlight} highlight` + : 'none'} + + Events Total: {roomState.size} diff --git a/src/app/features/room/message/EncryptedContent.tsx b/src/app/features/room/message/EncryptedContent.tsx index e0084d08..ddd82db4 100644 --- a/src/app/features/room/message/EncryptedContent.tsx +++ b/src/app/features/room/message/EncryptedContent.tsx @@ -1,6 +1,7 @@ import { MatrixEvent, MatrixEventEvent, MatrixEventHandlerMap } from '$types/matrix-sdk'; import { ReactNode, useEffect, useState } from 'react'; import { MessageEvent } from '$types/matrix/room'; +import { useMatrixClient } from '$hooks/useMatrixClient'; type EncryptedContentProps = { mEvent: MatrixEvent; @@ -8,8 +9,14 @@ type EncryptedContentProps = { }; export function EncryptedContent({ mEvent, children }: EncryptedContentProps) { + const mx = useMatrixClient(); const [, toggleEncrypted] = useState(mEvent.getType() === MessageEvent.RoomMessageEncrypted); + useEffect(() => { + if (mEvent.getType() !== MessageEvent.RoomMessageEncrypted) return; + mx.decryptEventIfNeeded(mEvent).catch(() => undefined); + }, [mx, mEvent]); + useEffect(() => { toggleEncrypted(mEvent.getType() === MessageEvent.RoomMessageEncrypted); const handleDecrypted: MatrixEventHandlerMap[MatrixEventEvent.Decrypted] = (event) => { diff --git a/src/app/features/settings/developer-tools/SyncDiagnostics.tsx b/src/app/features/settings/developer-tools/SyncDiagnostics.tsx index 54c0576c..83c521a5 100644 --- a/src/app/features/settings/developer-tools/SyncDiagnostics.tsx +++ b/src/app/features/settings/developer-tools/SyncDiagnostics.tsx @@ -3,9 +3,10 @@ import { Box, Text } from 'folds'; import { SequenceCard } from '$components/sequence-card'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { getClientSyncDiagnostics } from '$client/initMatrix'; -import { Direction, Room } from '$types/matrix-sdk'; +import { Direction, EventType, NotificationCountType, Room } from '$types/matrix-sdk'; import { Membership } from '$types/matrix/room'; import { SequenceCardStyle } from '$features/settings/styles.css'; +import { isNotificationEvent } from '$utils/room'; type RoomRenderingDiagnostics = { totalRooms: number; @@ -17,6 +18,16 @@ type RoomRenderingDiagnostics = { roomsWithBackPagination: number; }; +type UnreadDriftRoom = { + roomId: string; + roomName: string; + sdkTotal: number; + sdkHighlight: number; + latestNotificationEventId: string | null; + readUpToEventId: string | null; + fullyReadEventId: string | null; +}; + const getRoomRenderingDiagnostics = (rooms: Room[]): RoomRenderingDiagnostics => { let joinedRooms = 0; let inviteRooms = 0; @@ -52,6 +63,45 @@ const getRoomRenderingDiagnostics = (rooms: Room[]): RoomRenderingDiagnostics => }; }; +const getUnreadDriftRooms = (mx: ReturnType): UnreadDriftRoom[] => { + const userId = mx.getUserId(); + if (!userId) return []; + + return mx + .getRooms() + .filter((room) => !room.isSpaceRoom() && room.getMyMembership() === Membership.Join) + .reduce((driftRooms, room) => { + const sdkTotal = room.getUnreadNotificationCount(NotificationCountType.Total); + const sdkHighlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); + if (sdkTotal <= 0 && sdkHighlight <= 0) return driftRooms; + + const latestNotificationEvent = [...room.getLiveTimeline().getEvents()] + .reverse() + .find((event) => !event.isSending() && isNotificationEvent(event)); + const latestNotificationEventId = latestNotificationEvent?.getId() ?? null; + if (!latestNotificationEventId) return driftRooms; + + const hasReadLatestNotification = room.hasUserReadEvent(userId, latestNotificationEventId); + if (!hasReadLatestNotification || sdkHighlight > 0) return driftRooms; + + const readUpToEventId = room.getEventReadUpTo(userId) ?? null; + const fullyReadEventId = + room.getAccountData(EventType.FullyRead)?.getContent<{ event_id?: string }>()?.event_id ?? + null; + + driftRooms.push({ + roomId: room.roomId, + roomName: room.name || room.roomId, + sdkTotal, + sdkHighlight, + latestNotificationEventId, + readUpToEventId, + fullyReadEventId, + }); + return driftRooms; + }, []); +}; + const formatListCoverage = (knownCount: number, rangeEnd: number): string => { if (knownCount <= 0) return '0/0'; const loadedCount = Math.max(0, Math.min(knownCount, rangeEnd + 1)); @@ -69,6 +119,7 @@ export function SyncDiagnostics() { const diagnostics = getClientSyncDiagnostics(mx); const roomDiagnostics = getRoomRenderingDiagnostics(mx.getRooms()); + const unreadDriftRooms = getUnreadDriftRooms(mx); return ( @@ -100,6 +151,14 @@ export function SyncDiagnostics() { Rooms with more history to paginate: {roomDiagnostics.roomsWithBackPagination} + Unread drift rooms: {unreadDriftRooms.length} + {unreadDriftRooms.slice(0, 10).map((room) => ( + + {room.roomName}: sdk {room.sdkTotal}/{room.sdkHighlight} | latest{' '} + {room.latestNotificationEventId ?? 'null'} | readUpTo {room.readUpToEventId ?? 'null'}{' '} + | fullyRead {room.fullyReadEventId ?? 'null'} + + ))} {diagnostics.sliding && ( <> diff --git a/src/app/state/room/roomToUnread.ts b/src/app/state/room/roomToUnread.ts index 38100de6..007e520b 100644 --- a/src/app/state/room/roomToUnread.ts +++ b/src/app/state/room/roomToUnread.ts @@ -9,6 +9,7 @@ import { SyncState, ReceiptContent, ReceiptType, + EventType, } from '$types/matrix-sdk'; import { useCallback, useEffect } from 'react'; import { @@ -134,6 +135,21 @@ export const roomToUnreadAtom = atom + deleteUnreadInfo( + draftRoomToUnread, + getAllParents(get(roomToParentsAtom), unreadInfo.roomId), + unreadInfo.roomId + ) + ) + ); + } + return; + } const currentUnread = get(baseRoomToUnread).get(unreadInfo.roomId); if (currentUnread && unreadEqual(currentUnread, unreadInfoToUnread(unreadInfo))) { // Do not update if unread data has not changes @@ -244,6 +260,46 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo }; }, [mx, setUnreadAtom]); + useEffect(() => { + const handleUnreadNotifications = ( + _notification: unknown, + _threadId: string | undefined, + room: Room + ) => { + if (!room || room.isSpaceRoom()) return; + if (room.getMyMembership() !== Membership.Join) return; + + const unreadInfo = getUnreadInfo(room); + if (unreadInfo.total === 0 && unreadInfo.highlight === 0) { + setUnreadAtom({ type: 'DELETE', roomId: room.roomId }); + return; + } + setUnreadAtom({ type: 'PUT', unreadInfo }); + }; + (mx as any).on(RoomEvent.UnreadNotifications, handleUnreadNotifications); + return () => { + (mx as any).removeListener(RoomEvent.UnreadNotifications, handleUnreadNotifications); + }; + }, [mx, setUnreadAtom]); + + useEffect(() => { + const handleRoomAccountData = (mEvent: MatrixEvent, room: Room) => { + if (room.isSpaceRoom()) return; + if (mEvent.getType() !== EventType.FullyRead) return; + + const unreadInfo = getUnreadInfo(room); + if (unreadInfo.total === 0 && unreadInfo.highlight === 0) { + setUnreadAtom({ type: 'DELETE', roomId: room.roomId }); + return; + } + setUnreadAtom({ type: 'PUT', unreadInfo }); + }; + mx.on(RoomEvent.AccountData, handleRoomAccountData); + return () => { + mx.removeListener(RoomEvent.AccountData, handleRoomAccountData); + }; + }, [mx, setUnreadAtom]); + useEffect(() => { setUnreadAtom({ type: 'RESET', diff --git a/src/app/utils/notifications.ts b/src/app/utils/notifications.ts index 4b25a9e8..a6d47b7a 100644 --- a/src/app/utils/notifications.ts +++ b/src/app/utils/notifications.ts @@ -19,6 +19,18 @@ export async function markAsRead(mx: MatrixClient, roomId: string, privateReceip const latestEvent = getLatestValidEvent(); if (latestEvent === null) return; + const latestEventId = latestEvent.getId(); + if (!latestEventId) return; + + // Update both read receipt and fully-read marker so unread state clears reliably + // across clients and bridge-heavy rooms where hidden events may exist. + if (privateReceipt) { + await mx.setRoomReadMarkers(roomId, latestEventId, undefined, latestEvent); + } else { + await mx.setRoomReadMarkers(roomId, latestEventId, latestEvent); + } + + // Keep legacy receipt path as a safety fallback for homeservers with partial support. await mx.sendReadReceipt( latestEvent, privateReceipt ? ReceiptType.ReadPrivate : ReceiptType.Read diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts index a8cb47e2..78db758f 100644 --- a/src/app/utils/room.ts +++ b/src/app/utils/room.ts @@ -212,6 +212,7 @@ export const roomHaveUnread = (mx: MatrixClient, room: Room) => { const userId = mx.getUserId(); if (!userId) return false; const readUpToId = room.getEventReadUpTo(userId); + if (!readUpToId) return false; const liveEvents = room.getLiveTimeline().getEvents(); if (liveEvents[liveEvents.length - 1]?.getSender() === userId) { @@ -224,12 +225,31 @@ export const roomHaveUnread = (mx: MatrixClient, room: Room) => { if (event.getId() === readUpToId) return false; if (isNotificationEvent(event)) return true; } - return true; + return false; }; export const getUnreadInfo = (room: Room): UnreadInfo => { - const total = room.getUnreadNotificationCount(NotificationCountType.Total); + const userId = room.client.getUserId(); + if (userId) { + // Reconcile known notification-count drift (notably with Sliding Sync / mixed receipts). + room.fixupNotifications(userId); + } + + let total = room.getUnreadNotificationCount(NotificationCountType.Total); const highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); + + // If our latest notification event is confirmed read, clamp stale non-highlight totals. + if (userId && total > 0 && highlight === 0) { + const liveEvents = room.getLiveTimeline().getEvents(); + const latestNotification = [...liveEvents] + .reverse() + .find((event) => !event.isSending() && isNotificationEvent(event)); + const latestNotificationId = latestNotification?.getId(); + if (latestNotificationId && room.hasUserReadEvent(userId, latestNotificationId)) { + total = 0; + } + } + return { roomId: room.roomId, highlight, @@ -244,7 +264,10 @@ export const getUnreadInfos = (mx: MatrixClient): UnreadInfo[] => if (getNotificationType(mx, room.roomId) === NotificationType.Mute) return unread; if (roomHaveNotification(room) || roomHaveUnread(mx, room)) { - unread.push(getUnreadInfo(room)); + const unreadInfo = getUnreadInfo(room); + if (unreadInfo.total > 0 || unreadInfo.highlight > 0) { + unread.push(unreadInfo); + } } return unread; diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index 913cc83b..d4eec8d1 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -68,13 +68,14 @@ const buildDefaultSubscription = (timelineLimit: number): MSC3575RoomSubscriptio const buildLists = ( pageSize: number, timelineLimit: number, - includeInviteList: boolean + includeInviteList: boolean, + requiredState: MSC3575RoomSubscription['required_state'] ): Map => { const lists = new Map(); lists.set(LIST_JOINED, { ranges: [[0, Math.max(0, pageSize - 1)]], timeline_limit: timelineLimit, - required_state: [], + required_state: requiredState, slow_get_all_rooms: true, filters: { is_invite: false, @@ -85,7 +86,7 @@ const buildLists = ( lists.set(LIST_INVITES, { ranges: [[0, Math.max(0, pageSize - 1)]], timeline_limit: timelineLimit, - required_state: [], + required_state: requiredState, slow_get_all_rooms: true, filters: { is_invite: true, @@ -127,7 +128,12 @@ export class SlidingSyncManager { const includeInviteList = config.includeInviteList !== false; const subscription = buildDefaultSubscription(timelineLimit); - const lists = buildLists(listPageSize, timelineLimit, includeInviteList); + const lists = buildLists( + listPageSize, + timelineLimit, + includeInviteList, + subscription.required_state + ); this.listKeys = Array.from(lists.keys()); this.slidingSync = new SlidingSync(proxyBaseUrl, lists, subscription, mx, pollTimeoutMs); From 6250fefc0826d5c1a06d7f61425326861f340a66 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 3 Mar 2026 00:06:03 -0500 Subject: [PATCH 09/13] add build/git hash to about page --- Dockerfile | 3 ++ src/app/features/settings/about/About.tsx | 3 +- src/ext.d.ts | 3 ++ vite.config.ts | 36 +++++++++++++++++++++++ 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index f7884b27..3d2c1f60 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,6 +3,9 @@ FROM --platform=$BUILDPLATFORM node:24.13.1-alpine AS builder WORKDIR /src +ARG VITE_BUILD_HASH +ENV VITE_BUILD_HASH=$VITE_BUILD_HASH + COPY .npmrc package.json package-lock.json /src/ RUN npm ci COPY . /src/ diff --git a/src/app/features/settings/about/About.tsx b/src/app/features/settings/about/About.tsx index 3eb07593..1e83a947 100644 --- a/src/app/features/settings/about/About.tsx +++ b/src/app/features/settings/about/About.tsx @@ -12,6 +12,7 @@ type AboutProps = { }; export function About({ requestClose }: AboutProps) { const mx = useMatrixClient(); + const buildLabel = BUILD_HASH ? ` (${BUILD_HASH})` : ''; return ( @@ -45,7 +46,7 @@ export function About({ requestClose }: AboutProps) { Sable - v1.2.3 + {`v${APP_VERSION}${buildLabel}`} Yet another matrix client fork(ed from cinny). diff --git a/src/ext.d.ts b/src/ext.d.ts index 4d5ff494..2dcdcd1c 100644 --- a/src/ext.d.ts +++ b/src/ext.d.ts @@ -1,5 +1,8 @@ /// +declare const APP_VERSION: string; +declare const BUILD_HASH: string; + declare module 'browser-encrypt-attachment' { export interface EncryptedAttachmentInfo { v: string; diff --git a/vite.config.ts b/vite.config.ts index d99b9184..469890e3 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,5 +1,6 @@ import { defineConfig } from 'vite'; import type { ViteDevServer } from 'vite'; +import { execSync } from 'child_process'; import react from '@vitejs/plugin-react'; import svgr from 'vite-plugin-svgr'; import { wasm } from '@rollup/plugin-wasm'; @@ -13,6 +14,37 @@ import fs from 'fs'; import path from 'path'; import buildConfig from './build.config'; +const packageJson = JSON.parse( + fs.readFileSync(path.resolve(__dirname, 'package.json'), 'utf8') +) as { + version: string; +}; + +const normalizeShortSha = (value?: string): string | undefined => { + if (!value) return undefined; + const normalized = value.trim(); + if (!normalized) return undefined; + return normalized.slice(0, 7); +}; + +const resolveBuildHash = (): string | undefined => { + const envHash = normalizeShortSha( + process.env.VITE_BUILD_HASH ?? + process.env.GITHUB_SHA ?? + process.env.CI_COMMIT_SHA ?? + process.env.SOURCE_VERSION + ); + if (envHash) return envHash; + try { + return normalizeShortSha(execSync('git rev-parse --short HEAD').toString('utf8')); + } catch { + return undefined; + } +}; + +const appVersion = packageJson.version; +const buildHash = resolveBuildHash(); + const copyFiles = { targets: [ { @@ -80,6 +112,10 @@ export default defineConfig({ appType: 'spa', publicDir: false, base: buildConfig.base, + define: { + APP_VERSION: JSON.stringify(appVersion), + BUILD_HASH: JSON.stringify(buildHash ?? ''), + }, resolve: { alias: { $hooks: path.resolve(__dirname, 'src/app/hooks'), From 576255c174469d42acd90237a2f3f44f1c991c95 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 3 Mar 2026 00:18:13 -0500 Subject: [PATCH 10/13] attempt fix for "dancing rooms" --- src/app/pages/client/direct/Direct.tsx | 6 +++++- src/app/pages/client/home/Home.tsx | 6 +++++- src/app/pages/client/space/Space.tsx | 4 +++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/app/pages/client/direct/Direct.tsx b/src/app/pages/client/direct/Direct.tsx index 8915d5f7..7f19df3f 100644 --- a/src/app/pages/client/direct/Direct.tsx +++ b/src/app/pages/client/direct/Direct.tsx @@ -186,8 +186,12 @@ export function Direct() { const sortedDirects = useMemo(() => { const items = Array.from(directs).sort(factoryRoomIdByActivity(mx)); + const hasUnread = (roomId: string) => { + const unread = roomToUnread.get(roomId); + return !!unread && (unread.total > 0 || unread.highlight > 0); + }; if (closedCategories.has(DEFAULT_CATEGORY_ID)) { - return items.filter((rId) => roomToUnread.has(rId) || rId === selectedRoomId); + return items.filter((rId) => hasUnread(rId) || rId === selectedRoomId); } return items; }, [mx, directs, closedCategories, roomToUnread, selectedRoomId]); diff --git a/src/app/pages/client/home/Home.tsx b/src/app/pages/client/home/Home.tsx index fec44d6c..4b3e61c9 100644 --- a/src/app/pages/client/home/Home.tsx +++ b/src/app/pages/client/home/Home.tsx @@ -213,8 +213,12 @@ export function Home() { ? factoryRoomIdByActivity(mx) : factoryRoomIdByAtoZ(mx) ); + const hasUnread = (roomId: string) => { + const unread = roomToUnread.get(roomId); + return !!unread && (unread.total > 0 || unread.highlight > 0); + }; if (closedCategories.has(DEFAULT_CATEGORY_ID)) { - return items.filter((rId) => roomToUnread.has(rId) || rId === selectedRoomId); + return items.filter((rId) => hasUnread(rId) || rId === selectedRoomId); } return items; }, [mx, rooms, closedCategories, roomToUnread, selectedRoomId]); diff --git a/src/app/pages/client/space/Space.tsx b/src/app/pages/client/space/Space.tsx index a774c8fa..d83769dd 100644 --- a/src/app/pages/client/space/Space.tsx +++ b/src/app/pages/client/space/Space.tsx @@ -401,8 +401,10 @@ export function Space() { if (!closedCategories.has(makeNavCategoryId(space.roomId, parentId))) { return false; } + const unread = roomToUnread.get(roomId); + const hasUnread = !!unread && (unread.total > 0 || unread.highlight > 0); const showRoomAnyway = - roomToUnread.has(roomId) || + hasUnread || roomId === selectedRoomId || (isActiveCallReady && activeCallRoomId === roomId); return !showRoomAnyway; From df1826850d690eff83d874bf9bc25fa1e2a601cb Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 3 Mar 2026 00:24:39 -0500 Subject: [PATCH 11/13] add missing required events --- src/client/slidingSync.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index d4eec8d1..b33a06d4 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -9,6 +9,7 @@ import { MSC3575_STATE_KEY_ME, EventType, } from '$types/matrix-sdk'; +import { StateEvent } from '$types/matrix/room'; import { createLogger } from '$utils/debug'; const log = createLogger('slidingSync'); @@ -54,12 +55,19 @@ const buildDefaultSubscription = (timelineLimit: number): MSC3575RoomSubscriptio [EventType.RoomMember, MSC3575_STATE_KEY_LAZY], [EventType.RoomCreate, ''], [EventType.RoomName, ''], + [EventType.RoomTopic, ''], [EventType.RoomAvatar, ''], [EventType.RoomCanonicalAlias, ''], + [EventType.RoomPowerLevels, ''], [EventType.RoomEncryption, ''], [EventType.RoomTombstone, ''], + [EventType.RoomPinnedEvents, ''], [EventType.RoomJoinRules, ''], [EventType.RoomHistoryVisibility, ''], + [StateEvent.PoniesRoomEmotes, '*'], + [StateEvent.RoomWidget, '*'], + [StateEvent.GroupCallPrefix, '*'], + [StateEvent.GroupCallMemberPrefix, '*'], [EventType.SpaceChild, '*'], [EventType.SpaceParent, '*'], ], From 537efcc7c43e9761987abee962f82d2a52ac4d70 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 3 Mar 2026 00:26:22 -0500 Subject: [PATCH 12/13] only delete specific parent-child room mapping updates --- src/app/state/room/roomToParents.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/app/state/room/roomToParents.ts b/src/app/state/room/roomToParents.ts index 0b40eb9c..24059988 100644 --- a/src/app/state/room/roomToParents.ts +++ b/src/app/state/room/roomToParents.ts @@ -28,6 +28,11 @@ export type RoomToParentsAction = parent: string; children: string[]; } + | { + type: 'REMOVE_CHILD'; + parent: string; + child: string; + } | { type: 'DELETE'; roomId: string; @@ -50,6 +55,22 @@ export const roomToParentsAtom = atom { + const parents = draftRoomToParents.get(action.child); + if (!parents) return; + parents.delete(action.parent); + if (parents.size === 0) { + draftRoomToParents.delete(action.child); + } else { + draftRoomToParents.set(action.child, parents); + } + }) + ); + return; + } if (action.type === 'DELETE') { set( baseRoomToParents, @@ -100,7 +121,7 @@ export const useBindRoomToParentsAtom = ( if (isValidChild(mEvent)) { setRoomToParents({ type: 'PUT', parent: roomId, children: [childId] }); } else { - setRoomToParents({ type: 'DELETE', roomId: childId }); + setRoomToParents({ type: 'REMOVE_CHILD', parent: roomId, child: childId }); } } } From 3ef481cbb0dc7563688e933cf24860526874e453 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 3 Mar 2026 00:43:53 -0500 Subject: [PATCH 13/13] fix logic bug (clearing unread receipt on any recipt) --- src/app/state/room/roomToUnread.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/app/state/room/roomToUnread.ts b/src/app/state/room/roomToUnread.ts index 007e520b..e2134db7 100644 --- a/src/app/state/room/roomToUnread.ts +++ b/src/app/state/room/roomToUnread.ts @@ -251,7 +251,12 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo ) ); if (isMyReceipt) { - setUnreadAtom({ type: 'DELETE', roomId: room.roomId }); + const unreadInfo = getUnreadInfo(room); + if (unreadInfo.total === 0 && unreadInfo.highlight === 0) { + setUnreadAtom({ type: 'DELETE', roomId: room.roomId }); + return; + } + setUnreadAtom({ type: 'PUT', unreadInfo }); } }; mx.on(RoomEvent.Receipt, handleReceipt);