Merge pull request #67 from CloudHub-Social/sliding-sync

Add optional beta Sliding Sync support
This commit is contained in:
7w1 authored and GitHub committed 2026-03-02 23:54:41 -06:00
commit 3a8ed931e3
23 files changed
+849 -26

No files matched your search

+3
View File
@@ -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/
+4
View File
@@ -12,6 +12,10 @@
"webPushAppID": "cc.cinny.web"
},
"slidingSync": {
"enabled": false
},
"featuredCommunities": {
"openAsDefault": false,
"spaces": [
@@ -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<string | null>();
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 && (
<Box direction="Column" gap="100">
<Box
direction="Column"
gap="100"
style={{
paddingInline: config.space.S400,
paddingBottom: config.space.S300,
}}
>
<Box justifyContent="SpaceBetween" alignItems="Center">
<Text size="L400">Unread Diagnostics</Text>
<Button
onClick={() =>
copyToClipboard(JSON.stringify(unreadDiagnostics, null, 2))
}
variant="Secondary"
fill="Soft"
size="300"
radii="300"
outlined
>
<Text size="B300">Copy JSON</Text>
</Button>
</Box>
<Text size="T200">
`readUpTo`: {unreadDiagnostics.readUpToEventId ?? 'null'}
</Text>
<Text size="T200">
`m.fully_read`: {unreadDiagnostics.fullyReadEventId ?? 'null'}
</Text>
<Text size="T200">
Latest live: {unreadDiagnostics.latestLiveEventId ?? 'null'} | read?{' '}
{unreadDiagnostics.hasReadLatestLive ? 'yes' : 'no'}
</Text>
<Text size="T200">
Latest notification:{' '}
{unreadDiagnostics.latestNotificationEventId ?? 'null'} | read?{' '}
{unreadDiagnostics.hasReadLatestNotification ? 'yes' : 'no'}
</Text>
<Text size="T200">
SDK unread: {unreadDiagnostics.sdkUnread.total} total /{' '}
{unreadDiagnostics.sdkUnread.highlight} highlight
</Text>
<Text size="T200">
Atom unread:{' '}
{unreadDiagnostics.atomUnread
? `${unreadDiagnostics.atomUnread.total} total / ${unreadDiagnostics.atomUnread.highlight} highlight`
: 'none'}
</Text>
</Box>
<Box justifyContent="SpaceBetween">
<Text size="L400">Events</Text>
<Text size="L400">Total: {roomState.size}</Text>
@@ -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) => {
+2 -1
View File
@@ -12,6 +12,7 @@ type AboutProps = {
};
export function About({ requestClose }: AboutProps) {
const mx = useMatrixClient();
const buildLabel = BUILD_HASH ? ` (${BUILD_HASH})` : '';
return (
<Page>
@@ -45,7 +46,7 @@ export function About({ requestClose }: AboutProps) {
<Box direction="Column" gap="100">
<Box gap="100" alignItems="End">
<Text size="H3">Sable</Text>
<Text size="T200">v1.2.3</Text>
<Text size="T200">{`v${APP_VERSION}${buildLabel}`}</Text>
</Box>
<Text>Yet another matrix client fork(ed from cinny).</Text>
</Box>
@@ -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) {
</SequenceCard>
)}
</Box>
{developerTools && <SyncDiagnostics />}
{developerTools && (
<AccountData
expand={expand}
@@ -0,0 +1,177 @@
import { useEffect, useState } from 'react';
import { Box, Text } from 'folds';
import { SequenceCard } from '$components/sequence-card';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { getClientSyncDiagnostics } from '$client/initMatrix';
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;
joinedRooms: number;
inviteRooms: number;
roomsMissingName: number;
roomsMissingAvatar: number;
roomsWithoutLiveEvents: number;
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;
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<typeof useMatrixClient>): UnreadDriftRoom[] => {
const userId = mx.getUserId();
if (!userId) return [];
return mx
.getRooms()
.filter((room) => !room.isSpaceRoom() && room.getMyMembership() === Membership.Join)
.reduce<UnreadDriftRoom[]>((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 (
<Box direction="Column" gap="100">
<Text size="L400">Sync Diagnostics</Text>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="100"
>
<Box direction="Column" gap="100" style={{ padding: '12px' }}>
<Text size="T300">
Transport: {diagnostics.transport}
{diagnostics.fallbackFromSliding ? ' (fallback)' : ''}
</Text>
<Text size="T300">State: {diagnostics.syncState ?? 'null'}</Text>
<Text size="T300">
Sliding configured: {diagnostics.slidingConfigured ? 'yes' : 'no'}
</Text>
<Text size="T300">
Room counts: {roomDiagnostics.totalRooms} total, {roomDiagnostics.joinedRooms} joined,{' '}
{roomDiagnostics.inviteRooms} invites
</Text>
<Text size="T300">Rooms missing name: {roomDiagnostics.roomsMissingName}</Text>
<Text size="T300">Rooms missing avatar: {roomDiagnostics.roomsMissingAvatar}</Text>
<Text size="T300">
Rooms without live events: {roomDiagnostics.roomsWithoutLiveEvents}
</Text>
<Text size="T300">
Rooms with more history to paginate: {roomDiagnostics.roomsWithBackPagination}
</Text>
<Text size="T300">Unread drift rooms: {unreadDriftRooms.length}</Text>
{unreadDriftRooms.slice(0, 10).map((room) => (
<Text key={room.roomId} size="T200" priority="300">
{room.roomName}: sdk {room.sdkTotal}/{room.sdkHighlight} | latest{' '}
{room.latestNotificationEventId ?? 'null'} | readUpTo {room.readUpToEventId ?? 'null'}{' '}
| fullyRead {room.fullyReadEventId ?? 'null'}
</Text>
))}
{diagnostics.sliding && (
<>
<Text size="T300">Sliding proxy: {diagnostics.sliding.proxyBaseUrl}</Text>
{diagnostics.sliding.lists.map((list) => (
<Text size="T300" key={list.key}>
List `{list.key}` coverage: {formatListCoverage(list.knownCount, list.rangeEnd)}
</Text>
))}
</>
)}
</Box>
</SequenceCard>
</Box>
);
}
+11
View File
@@ -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[];
@@ -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<MatrixClient> => {
const startBackgroundClient = async (
session: Session,
slidingSyncConfig: ReturnType<typeof useClientConfig>['slidingSync']
): Promise<MatrixClient> => {
const mx = createClient({
baseUrl: session.baseUrl,
accessToken: session.accessToken,
@@ -38,7 +43,10 @@ const startBackgroundClient = async (session: Session): Promise<MatrixClient> =>
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<void> =>
});
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,
+14 -4
View File
@@ -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<void, Error, [MatrixClient]>(
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]
+5 -1
View File
@@ -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]);
+5 -1
View File
@@ -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]);
@@ -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);
};
+3 -1
View File
@@ -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;
+22 -1
View File
@@ -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<RoomToParents, [RoomToParentsAction], unde
);
return;
}
if (action.type === 'REMOVE_CHILD') {
set(
baseRoomToParents,
produce(get(baseRoomToParents), (draftRoomToParents) => {
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 });
}
}
}
+62 -1
View File
@@ -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<RoomToUnread, [RoomToUnreadAction], undefin
}
if (action.type === 'PUT') {
const { unreadInfo } = action;
if (unreadInfo.total <= 0 && unreadInfo.highlight <= 0) {
if (get(baseRoomToUnread).has(unreadInfo.roomId)) {
set(
baseRoomToUnread,
produce(get(baseRoomToUnread), (draftRoomToUnread) =>
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',
+12
View File
@@ -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
+26 -3
View File
@@ -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;
+101 -5
View File
@@ -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<MatrixClient, SlidingSyncManager>();
type SyncTransport = 'classic' | 'sliding';
type SyncTransportMeta = {
transport: SyncTransport;
slidingConfigured: boolean;
fallbackFromSliding: boolean;
};
const syncTransportByClient = new WeakMap<MatrixClient, SyncTransportMeta>();
const deleteDatabase = (name: string): Promise<void> =>
new Promise((resolve) => {
@@ -244,21 +253,108 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
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 {
+225
View File
@@ -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<string, MSC3575List> => {
const lists = new Map<string, MSC3575List>();
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<boolean> {
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;
}
}
}
+3
View File
@@ -1,5 +1,8 @@
/// <reference types="vite/client" />
declare const APP_VERSION: string;
declare const BUILD_HASH: string;
declare module 'browser-encrypt-attachment' {
export interface EncryptedAttachmentInfo {
v: string;
+3
View File
@@ -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';
+36
View File
@@ -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'),