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/config.json b/config.json index de0f5b09..cfee89f3 100644 --- a/config.json +++ b/config.json @@ -12,6 +12,10 @@ "webPushAppID": "cc.cinny.web" }, + "slidingSync": { + "enabled": false + }, + "featuredCommunities": { "openAsDefault": false, "spaces": [ 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/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/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 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)); + return `${loadedCount}/${knownCount}`; +}; + +export function SyncDiagnostics() { + const mx = useMatrixClient(); + 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()); + const unreadDriftRooms = getUnreadDriftRooms(mx); + + return ( + + Sync Diagnostics + + + + Transport: {diagnostics.transport} + {diagnostics.fallbackFromSliding ? ' (fallback)' : ''} + + State: {diagnostics.syncState ?? 'null'} + + Sliding configured: {diagnostics.slidingConfigured ? '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} + + 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 && ( + <> + 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 b4c6d091..7696d96a 100644 --- a/src/app/hooks/useClientConfig.ts +++ b/src/app/hooks/useClientConfig.ts @@ -19,6 +19,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/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/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/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; 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 }); } } } diff --git a/src/app/state/room/roomToUnread.ts b/src/app/state/room/roomToUnread.ts index 38100de6..e2134db7 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 @@ -235,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); @@ -244,6 +265,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/initMatrix.ts b/src/client/initMatrix.ts index 40f1c283..2fea56c9 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,108 @@ 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 slidingEnabled = slidingConfig?.enabled !== false; + const canUseSliding = slidingEnabled && typeof proxyBaseUrl === 'string'; + syncTransportByClient.set(mx, { + transport: 'classic', + slidingConfigured: canUseSliding, + 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: canUseSliding, + 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 +363,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..b33a06d4 --- /dev/null +++ b/src/client/slidingSync.ts @@ -0,0 +1,225 @@ +import { + MatrixClient, + MSC3575List, + MSC3575RoomSubscription, + SlidingSync, + SlidingSyncEvent, + SlidingSyncState, + MSC3575_STATE_KEY_LAZY, + MSC3575_STATE_KEY_ME, + EventType, +} from '$types/matrix-sdk'; +import { StateEvent } from '$types/matrix/room'; +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.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, '*'], + ], +}); + +const buildLists = ( + pageSize: number, + timelineLimit: number, + 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: requiredState, + 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, + required_state: requiredState, + 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, + subscription.required_state + ); + 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, + required_state: [], + }, + }, + timeout: 0, + clientTimeout: probeTimeoutMs, + }, + proxyBaseUrl + ); + + return typeof response.pos === 'string' && response.pos.length > 0; + } catch { + return false; + } + } +} 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/src/types/matrix-sdk.ts b/src/types/matrix-sdk.ts index 27962809..71621d88 100644 --- a/src/types/matrix-sdk.ts +++ b/src/types/matrix-sdk.ts @@ -8,7 +8,10 @@ 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'; diff --git a/vite.config.ts b/vite.config.ts index 589139fa..2c2f1619 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'),