Merge branch '7w1:dev' into fix-settings-consistency

This commit is contained in:
Felice D'Angelo authored and GitHub committed 2026-03-03 16:40:48 +01:00
commit e10dcbc539
17 files changed
+387 -112

No files matched your search

+5 -1
View File
@@ -1,9 +1,13 @@
# Sable Client Changelog
## 1.3.1 - 3/3/2026
- Important sliding sync config patches, notifications fixes, and client side toggle ([#85](https://github.com/7w1/sable/pull/85))
## 1.3.0 - 3/2/2026
- Mobile push notifications! ([#44](https://github.com/7w1/sable/issues/44), [#49](https://github.com/7w1/sable/pull/49)) - [Evie Gauthier](https://github.com/Just-Insane)
- Beta Simplified Sliding Sync support ([#67](https://github.com/7w1/sable/pull/67), ([#75](https://github.com/7w1/sable/pull/75)) - [Evie Gauthier](https://github.com/Just-Insane)
- Beta Simplified Sliding Sync support ([#67](https://github.com/7w1/sable/pull/67), [#75](https://github.com/7w1/sable/pull/75)) - [Evie Gauthier](https://github.com/Just-Insane)
- Codebase cleanups, CI improvements, and docker builds ([#26](https://github.com/7w1/sable/pull/26), [#35](https://github.com/7w1/sable/pull/35), [#62](https://github.com/7w1/sable/pull/62), [#64](https://github.com/7w1/sable/pull/64), [#65](https://github.com/7w1/sable/pull/65)) - [haz](https://github.com/hazre)
- Add room/space specific pronouns, when enabled by room/space admin. ([#30](https://github.com/7w1/sable/issues/30))
- Add validation to timezones before rendering.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "sable",
"version": "1.3.0",
"version": "1.3.1",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "sable",
"version": "1.3.0",
"version": "1.3.1",
"license": "AGPL-3.0-only",
"dependencies": {
"@atlaskit/pragmatic-drag-and-drop": "^1.7.7",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "sable",
"version": "1.3.0",
"version": "1.3.1",
"description": "Yet another matrix client fork",
"type": "module",
"packageManager": "[email protected]",
@@ -20,10 +20,13 @@ import { SettingTile } from '$components/setting-tile';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { copyToClipboard } from '$utils/dom';
import { getClientSyncDiagnostics } from '$client/initMatrix';
import { useRoom } from '$hooks/useRoom';
import { useRoomState } from '$hooks/useRoomState';
import { useRoomAccountData } from '$hooks/useRoomAccountData';
import { roomToUnreadAtom } from '$state/room/roomToUnread';
import { allRoomsAtom } from '$state/room-list/roomList';
import { allInvitesAtom } from '$state/room-list/inviteList';
import { isNotificationEvent } from '$utils/room';
import { CutoutCard } from '$components/cutout-card';
import { AccountDataEditor, AccountDataSubmitCallback } from '$components/AccountDataEditor';
@@ -44,6 +47,8 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
const accountData = useRoomAccountData(room);
const [expandState, setExpandState] = useState(false);
const [expandUnreadDiagnostics, setExpandUnreadDiagnostics] = useState(false);
const [expandSlidingDiagnostics, setExpandSlidingDiagnostics] = useState(false);
const [expandStateType, setExpandStateType] = useState<string>();
const [openStateEvent, setOpenStateEvent] = useState<StateEventInfo>();
const [composeEvent, setComposeEvent] = useState<{ type?: string; stateKey?: string }>();
@@ -51,6 +56,8 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
const [expandAccountData, setExpandAccountData] = useState(false);
const [accountDataType, setAccountDataType] = useState<string | null>();
const roomToUnread = useAtomValue(roomToUnreadAtom);
const allRooms = useAtomValue(allRoomsAtom);
const allInvites = useAtomValue(allInvitesAtom);
const [, setTick] = useState(0);
useEffect(() => {
@@ -60,9 +67,15 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
const unreadDiagnostics = useMemo(() => {
const userId = mx.getUserId();
const clientSyncState = mx.getSyncState();
const liveEvents = room.getLiveTimeline().getEvents();
const latestLiveEvent = liveEvents[liveEvents.length - 1];
const latestLiveEventId = latestLiveEvent?.getId() ?? null;
const latestTimelineEvent = liveEvents[liveEvents.length - 1];
const latestTimelineEventId = latestTimelineEvent?.getId() ?? null;
const latestMessageEvent = [...liveEvents].reverse().find((event) => {
const type = event.getType();
return type === 'm.room.message' || type === 'm.room.encrypted' || type === 'm.sticker';
});
const latestMessageEventId = latestMessageEvent?.getId() ?? null;
const latestNotificationEvent = [...liveEvents]
.reverse()
.find((event) => isNotificationEvent(event));
@@ -78,15 +91,20 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
return {
roomId: room.roomId,
userId: userId ?? null,
clientSyncState,
roomMembership: room.getMyMembership(),
roomInJoinedListAtom: allRooms.includes(room.roomId),
roomInInviteListAtom: allInvites.includes(room.roomId),
timelineSize: liveEvents.length,
latestLiveEventId,
latestTimelineEventId,
latestMessageEventId,
latestNotificationEventId,
fullyReadEventId,
readUpToEventId,
hasReadLatestLive: !!(
userId &&
latestLiveEventId &&
room.hasUserReadEvent(userId, latestLiveEventId)
latestTimelineEventId &&
room.hasUserReadEvent(userId, latestTimelineEventId)
),
hasReadLatestNotification: !!(
userId &&
@@ -104,7 +122,9 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
}
: null,
};
}, [mx, room, roomToUnread]);
}, [mx, room, roomToUnread, allRooms, allInvites]);
const syncDiagnostics = useMemo(() => getClientSyncDiagnostics(mx), [mx]);
const handleClose = useCallback(() => {
setOpenStateEvent(undefined);
@@ -270,46 +290,148 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
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 direction="Column" gap="100">
<Box justifyContent="SpaceBetween" alignItems="Center">
<Text size="L400">Unread Diagnostics</Text>
<Button
onClick={() => setExpandUnreadDiagnostics(!expandUnreadDiagnostics)}
variant="Secondary"
fill="Soft"
size="300"
radii="300"
outlined
before={
<Icon
src={
expandUnreadDiagnostics
? Icons.ChevronTop
: Icons.ChevronBottom
}
size="100"
filled
/>
}
>
<Text size="B300">
{expandUnreadDiagnostics ? 'Collapse' : 'Expand'}
</Text>
</Button>
</Box>
{expandUnreadDiagnostics && (
<Box direction="Column" gap="100">
<Button
onClick={() =>
copyToClipboard(JSON.stringify(unreadDiagnostics, null, 2))
}
variant="Secondary"
fill="Soft"
size="300"
radii="300"
outlined
>
<Text size="B300">Copy JSON</Text>
</Button>
<Text size="T200">
Client sync: {unreadDiagnostics.clientSyncState ?? 'null'} |
membership: {unreadDiagnostics.roomMembership}
</Text>
<Text size="T200">
In room atoms: joined{' '}
{unreadDiagnostics.roomInJoinedListAtom ? 'yes' : 'no'} | invite{' '}
{unreadDiagnostics.roomInInviteListAtom ? 'yes' : 'no'}
</Text>
<Text size="T200">
`readUpTo`: {unreadDiagnostics.readUpToEventId ?? 'null'}
</Text>
<Text size="T200">
`m.fully_read`: {unreadDiagnostics.fullyReadEventId ?? 'null'}
</Text>
<Text size="T200">
Latest timeline event:{' '}
{unreadDiagnostics.latestTimelineEventId ?? 'null'} | read?{' '}
{unreadDiagnostics.hasReadLatestLive ? 'yes' : 'no'}
</Text>
<Text size="T200">
Latest message event:{' '}
{unreadDiagnostics.latestMessageEventId ?? 'null'}
</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>
<Box direction="Column" gap="100">
<Box justifyContent="SpaceBetween" alignItems="Center">
<Text size="L400">Sliding Sync Diagnostics</Text>
<Button
onClick={() =>
setExpandSlidingDiagnostics(!expandSlidingDiagnostics)
}
variant="Secondary"
fill="Soft"
size="300"
radii="300"
outlined
before={
<Icon
src={
expandSlidingDiagnostics
? Icons.ChevronTop
: Icons.ChevronBottom
}
size="100"
filled
/>
}
>
<Text size="B300">
{expandSlidingDiagnostics ? 'Collapse' : 'Expand'}
</Text>
</Button>
</Box>
{expandSlidingDiagnostics && (
<Box direction="Column" gap="100">
<Text size="T200">
Transport: {syncDiagnostics.transport}
{syncDiagnostics.fallbackFromSliding ? ' (fallback)' : ''}
</Text>
<Text size="T200">
Sliding configured:{' '}
{syncDiagnostics.slidingConfigured ? 'yes' : 'no'}
</Text>
<Text size="T200">
Client sync state: {syncDiagnostics.syncState ?? 'null'}
</Text>
{syncDiagnostics.sliding ? (
<>
<Text size="T200">
Proxy: {syncDiagnostics.sliding.proxyBaseUrl}
</Text>
<Text size="T200">
Timeline limit: {syncDiagnostics.sliding.timelineLimit} | page
size: {syncDiagnostics.sliding.listPageSize} | adaptive:{' '}
{syncDiagnostics.sliding.adaptiveTimeline ? 'yes' : 'no'}
</Text>
</>
) : (
<Text size="T200">Sliding manager: not attached</Text>
)}
</Box>
)}
</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>
+25 -5
View File
@@ -122,6 +122,7 @@ import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { useImagePackRooms } from '$hooks/useImagePackRooms';
import { useComposingCheck } from '$hooks/useComposingCheck';
import { useSableCosmetics } from '$hooks/useSableCosmetics';
import { createLogger } from '$utils/debug';
import { CommandAutocomplete } from './CommandAutocomplete';
import {
getAudioMsgContent,
@@ -146,6 +147,8 @@ const getReplyContent = (replyDraft: IReplyDraft | undefined): IEventRelation =>
}
return relatesTo;
};
const log = createLogger('RoomInput');
interface ReplyEventContent {
'm.relates_to'?: IEventRelation;
}
@@ -348,10 +351,17 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setReplyDraft(undefined);
}
contents.forEach((content) => mx.sendMessage(roomId, content as any));
await Promise.all(
contents.map((content) =>
mx.sendMessage(roomId, content as any).catch((error: unknown) => {
log.error('failed to send uploaded message', { roomId }, error);
throw error;
})
)
);
};
const submit = useCallback(() => {
const submit = useCallback(async () => {
uploadBoardHandlers.current?.handleSend();
const commandName = getBeginCommand(editor);
@@ -417,9 +427,17 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
}
if (replyDraft) {
content['m.relates_to'] = getReplyContent(replyDraft);
}
try {
await mx.sendMessage(roomId, content as any);
} catch (error) {
log.error('failed to send message', { roomId }, error);
return;
}
if (replyDraft) {
setReplyDraft(undefined);
}
mx.sendMessage(roomId, content as any);
resetEditor(editor);
resetEditorHistory(editor);
@@ -436,7 +454,9 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
!isComposing(evt)
) {
evt.preventDefault();
submit();
submit().catch((error) => {
log.error('submit failed', { roomId }, error);
});
}
if (isKeyHotkey('escape', evt)) {
evt.preventDefault();
@@ -447,7 +467,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setReplyDraft(undefined);
}
},
[submit, setReplyDraft, enterForNewline, autocompleteQuery, isComposing]
[submit, roomId, setReplyDraft, enterForNewline, autocompleteQuery, isComposing]
);
const handleKeyUp: KeyboardEventHandler = useCallback(
+11 -2
View File
@@ -728,12 +728,21 @@ export function RoomTimeline({
useLiveTimelineRefresh(
room,
useCallback(() => {
if (liveTimelineLinked) {
if (liveTimelineLinked || timeline.linkedTimelines.length === 0) {
setTimeline(getInitialTimeline(room));
}
}, [room, liveTimelineLinked])
}, [room, liveTimelineLinked, timeline.linkedTimelines.length])
);
// Recover from transient empty timeline state when the live timeline
// already has events (can happen when opening by event id, then fallbacking).
useEffect(() => {
if (eventId) return;
if (timeline.linkedTimelines.length > 0) return;
if (getLiveTimeline(room).getEvents().length === 0) return;
setTimeline(getInitialTimeline(room));
}, [eventId, room, timeline.linkedTimelines.length]);
// Stay at bottom when room editor resize
useResizeObserver(
useMemo(() => {
@@ -24,6 +24,7 @@ import {
Text,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { useAtomValue, useSetAtom } from 'jotai';
import { Page, PageContent, PageHeader } from '$components/page';
import { SequenceCard } from '$components/sequence-card';
import { useSetting } from '$state/hooks/settings';
@@ -42,6 +43,9 @@ import { useMessageLayoutItems } from '$hooks/useMessageLayout';
import { useMessageSpacingItems } from '$hooks/useMessageSpacing';
import { useDateFormatItems } from '$hooks/useDateFormat';
import { SequenceCardStyle } from '$features/settings/styles.css';
import { sessionsAtom, activeSessionIdAtom } from '$state/sessions';
import { useClientConfig } from '$hooks/useClientConfig';
import { resolveSlidingEnabled } from '$client/initMatrix';
type DateHintProps = {
hasChanges: boolean;
@@ -776,6 +780,58 @@ function Messages() {
);
}
function Sync() {
const clientConfig = useClientConfig();
const sessions = useAtomValue(sessionsAtom);
const activeSessionId = useAtomValue(activeSessionIdAtom);
const setSessions = useSetAtom(sessionsAtom);
const activeSession = sessions.find((s) => s.userId === activeSessionId) ?? sessions[0];
const serverSlidingEnabled = resolveSlidingEnabled(clientConfig.slidingSync?.enabled);
const useSlidingSync = activeSession?.slidingSyncOptIn === true;
const handleSetSlidingSync = (value: boolean) => {
if (!activeSession) return;
setSessions({
type: 'PUT',
session: {
...activeSession,
slidingSyncOptIn: value,
},
});
window.location.reload();
};
return (
<Box direction="Column" gap="100">
<Text size="L400">Sync</Text>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
style={{ opacity: serverSlidingEnabled ? 1 : 0.5 }}
>
<SettingTile
title="Use Sliding Sync"
description={
serverSlidingEnabled
? 'Enable Sliding Sync for this current login/session.'
: 'Unavailable: this server config has Sliding Sync disabled.'
}
after={
<Switch
variant="Primary"
value={useSlidingSync}
onChange={handleSetSlidingSync}
disabled={!serverSlidingEnabled}
/>
}
/>
</SequenceCard>
</Box>
);
}
type GeneralProps = {
requestClose: () => void;
};
@@ -801,6 +857,7 @@ export function General({ requestClose }: GeneralProps) {
<PageContent>
<Box direction="Column" gap="700">
<DateAndTime />
<Sync />
<Gestures isMobile={mobileOrTablet()} />
<Editor isMobile={mobileOrTablet()} />
<Messages />
+1 -1
View File
@@ -14,7 +14,7 @@ export function AuthFooter() {
target="_blank"
rel="noreferrer"
>
v1.3.0
v1.3.1
</Text>
<Text as="a" size="T300" href="https://twitter.com/cinnyapp" target="_blank" rel="noreferrer">
Twitter
@@ -46,6 +46,7 @@ const startBackgroundClient = async (
await startClient(mx, {
baseUrl: session.baseUrl,
slidingSync: slidingSyncConfig,
sessionSlidingSyncOptIn: session.slidingSyncOptIn,
});
return mx;
};
+13 -2
View File
@@ -48,6 +48,9 @@ import { SpecVersions } from './SpecVersions';
const log = createLogger('ClientRoot');
const isClientReady = (syncState: string | null): boolean =>
syncState === 'PREPARED' || syncState === 'SYNCING' || syncState === 'CATCHUP';
function ClientRootLoading() {
return (
<SplashScreen>
@@ -197,8 +200,9 @@ export function ClientRoot({ children }: ClientRootProps) {
startClient(m, {
baseUrl: activeSession?.baseUrl,
slidingSync: clientConfig.slidingSync,
sessionSlidingSyncOptIn: activeSession?.slidingSyncOptIn,
}),
[activeSession?.baseUrl, clientConfig.slidingSync]
[activeSession?.baseUrl, activeSession?.slidingSyncOptIn, clientConfig.slidingSync]
)
);
@@ -259,10 +263,17 @@ export function ClientRoot({ children }: ClientRootProps) {
}
}, [mx, startMatrix]);
useEffect(() => {
if (!mx) return;
if (isClientReady(mx.getSyncState())) {
setLoading(false);
}
}, [mx]);
useSyncState(
mx,
useCallback((state: string) => {
if (state === 'PREPARED') {
if (isClientReady(state)) {
setLoading(false);
}
}, [])
+1 -1
View File
@@ -19,7 +19,7 @@ export function WelcomePage() {
<span>
Yet another matrix client fork.{' '}
<a href="https://github.com/7w1/sable" target="_blank" rel="noreferrer noopener">
v1.3.0
v1.3.1
</a>
</span>
}
+4 -13
View File
@@ -116,6 +116,7 @@ const groupNotifications = (
): RoomNotificationsGroup[] => {
const groups: RoomNotificationsGroup[] = [];
notifications.forEach((notification) => {
if (notification.event.type === StateEvent.RoomMember) return;
if (!allowRooms.has(notification.room_id)) return;
const groupIndex = groups.length - 1;
@@ -560,7 +561,7 @@ const useNotificationsSearchParams = (
[searchParams]
);
const DEFAULT_REFRESH_MS = 7000;
const FAST_REFRESH_MS = 2500;
export function Notifications() {
const mx = useMatrixClient();
@@ -578,7 +579,6 @@ export function Notifications() {
const notificationsSearchParams = useNotificationsSearchParams(searchParams);
const scrollRef = useRef<HTMLDivElement>(null);
const scrollTopAnchorRef = useRef<HTMLDivElement>(null);
const [refreshIntervalTime, setRefreshIntervalTime] = useState(DEFAULT_REFRESH_MS);
const onlyHighlight = notificationsSearchParams.only === 'highlight';
const setOnlyHighlighted = (highlight: boolean) => {
@@ -611,12 +611,7 @@ export function Notifications() {
useCallback(() => {
silentReloadTimeline();
}, [silentReloadTimeline]),
refreshIntervalTime
);
const handleScrollTopVisibility = useCallback(
(onTop: boolean) => setRefreshIntervalTime(onTop ? DEFAULT_REFRESH_MS : -1),
[]
FAST_REFRESH_MS
);
useEffect(() => {
@@ -689,11 +684,7 @@ export function Notifications() {
</Chip>
</Box>
</Box>
<ScrollTopContainer
scrollRef={scrollRef}
anchorRef={scrollTopAnchorRef}
onVisibilityChange={handleScrollTopVisibility}
>
<ScrollTopContainer scrollRef={scrollRef} anchorRef={scrollTopAnchorRef}>
<IconButton
onClick={() => virtualizer.scrollToOffset(0)}
variant="SurfaceVariant"
+24 -16
View File
@@ -30,6 +30,7 @@ import {
import { useStateEventCallback } from '$hooks/useStateEventCallback';
import { useSyncState } from '$hooks/useSyncState';
import { useRoomsNotificationPreferencesContext } from '$hooks/useRoomsNotificationPreferences';
import { getClientSyncDiagnostics } from '$client/initMatrix';
import { roomToParentsAtom } from './roomToParents';
export type RoomToUnreadAction =
@@ -187,13 +188,17 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo
const setUnreadAtom = useSetAtom(unreadAtom);
const roomsNotificationPreferences = useRoomsNotificationPreferencesContext();
const spaceChildResetTimerRef = useRef<number | null>(null);
const shouldApplyUnreadFixup = useCallback(
() => getClientSyncDiagnostics(mx).transport === 'sliding',
[mx]
);
useEffect(() => {
setUnreadAtom({
type: 'RESET',
unreadInfos: getUnreadInfos(mx),
unreadInfos: getUnreadInfos(mx, { applyFixup: shouldApplyUnreadFixup() }),
});
}, [mx, setUnreadAtom]);
}, [mx, setUnreadAtom, shouldApplyUnreadFixup]);
useSyncState(
mx,
@@ -205,11 +210,11 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo
) {
setUnreadAtom({
type: 'RESET',
unreadInfos: getUnreadInfos(mx),
unreadInfos: getUnreadInfos(mx, { applyFixup: shouldApplyUnreadFixup() }),
});
}
},
[mx, setUnreadAtom]
[mx, setUnreadAtom, shouldApplyUnreadFixup]
)
);
@@ -231,13 +236,16 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo
}
if (mEvent.getSender() === mx.getUserId()) return;
setUnreadAtom({ type: 'PUT', unreadInfo: getUnreadInfo(room) });
setUnreadAtom({
type: 'PUT',
unreadInfo: getUnreadInfo(room, { applyFixup: shouldApplyUnreadFixup() }),
});
};
mx.on(RoomEvent.Timeline, handleTimelineEvent);
return () => {
mx.removeListener(RoomEvent.Timeline, handleTimelineEvent);
};
}, [mx, setUnreadAtom]);
}, [mx, setUnreadAtom, shouldApplyUnreadFixup]);
useEffect(() => {
const handleReceipt = (mEvent: MatrixEvent, room: Room) => {
@@ -252,7 +260,7 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo
)
);
if (isMyReceipt) {
const unreadInfo = getUnreadInfo(room);
const unreadInfo = getUnreadInfo(room, { applyFixup: shouldApplyUnreadFixup() });
if (unreadInfo.total === 0 && unreadInfo.highlight === 0) {
setUnreadAtom({ type: 'DELETE', roomId: room.roomId });
return;
@@ -264,7 +272,7 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo
return () => {
mx.removeListener(RoomEvent.Receipt, handleReceipt);
};
}, [mx, setUnreadAtom]);
}, [mx, setUnreadAtom, shouldApplyUnreadFixup]);
useEffect(() => {
const handleUnreadNotifications = (
@@ -275,7 +283,7 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo
if (!room || room.isSpaceRoom()) return;
if (room.getMyMembership() !== Membership.Join) return;
const unreadInfo = getUnreadInfo(room);
const unreadInfo = getUnreadInfo(room, { applyFixup: shouldApplyUnreadFixup() });
if (unreadInfo.total === 0 && unreadInfo.highlight === 0) {
setUnreadAtom({ type: 'DELETE', roomId: room.roomId });
return;
@@ -286,14 +294,14 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo
return () => {
(mx as any).removeListener(RoomEvent.UnreadNotifications, handleUnreadNotifications);
};
}, [mx, setUnreadAtom]);
}, [mx, setUnreadAtom, shouldApplyUnreadFixup]);
useEffect(() => {
const handleRoomAccountData = (mEvent: MatrixEvent, room: Room) => {
if (room.isSpaceRoom()) return;
if (mEvent.getType() !== EventType.FullyRead) return;
const unreadInfo = getUnreadInfo(room);
const unreadInfo = getUnreadInfo(room, { applyFixup: shouldApplyUnreadFixup() });
if (unreadInfo.total === 0 && unreadInfo.highlight === 0) {
setUnreadAtom({ type: 'DELETE', roomId: room.roomId });
return;
@@ -304,14 +312,14 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo
return () => {
mx.removeListener(RoomEvent.AccountData, handleRoomAccountData);
};
}, [mx, setUnreadAtom]);
}, [mx, setUnreadAtom, shouldApplyUnreadFixup]);
useEffect(() => {
setUnreadAtom({
type: 'RESET',
unreadInfos: getUnreadInfos(mx),
unreadInfos: getUnreadInfos(mx, { applyFixup: shouldApplyUnreadFixup() }),
});
}, [mx, setUnreadAtom, roomsNotificationPreferences]);
}, [mx, setUnreadAtom, roomsNotificationPreferences, shouldApplyUnreadFixup]);
useEffect(() => {
const handleMembershipChange = (room: Room, membership: string) => {
@@ -354,13 +362,13 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo
spaceChildResetTimerRef.current = window.setTimeout(() => {
setUnreadAtom({
type: 'RESET',
unreadInfos: getUnreadInfos(mx),
unreadInfos: getUnreadInfos(mx, { applyFixup: shouldApplyUnreadFixup() }),
});
spaceChildResetTimerRef.current = null;
}, 150);
}
},
[mx, setUnreadAtom]
[mx, setUnreadAtom, shouldApplyUnreadFixup]
)
);
};
+1
View File
@@ -16,6 +16,7 @@ export type Session = {
expiresInMs?: number;
refreshToken?: string;
fallbackSdkStores?: boolean;
slidingSyncOptIn?: boolean;
};
export type Sessions = Session[];
+20 -6
View File
@@ -228,15 +228,20 @@ export const roomHaveUnread = (mx: MatrixClient, room: Room) => {
return false;
};
export const getUnreadInfo = (room: Room): UnreadInfo => {
type UnreadInfoOptions = {
applyFixup?: boolean;
};
export const getUnreadInfo = (room: Room, options?: UnreadInfoOptions): UnreadInfo => {
const userId = room.client.getUserId();
if (userId) {
if (userId && options?.applyFixup) {
// 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);
let highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight);
let syntheticDotUnread = false;
// If our latest notification event is confirmed read, clamp stale non-highlight totals.
if (userId && total > 0 && highlight === 0) {
@@ -250,21 +255,30 @@ export const getUnreadInfo = (room: Room): UnreadInfo => {
}
}
// Fallback for cases where SDK counters are stale/zero but unread-by-receipt state still exists.
// Represent as a dot badge (count=0) rather than a numeric badge.
if (total === 0 && highlight === 0 && roomHaveUnread(room.client, room)) {
highlight = 1;
syntheticDotUnread = true;
}
const resolvedTotal = syntheticDotUnread ? total : Math.max(total, highlight);
return {
roomId: room.roomId,
highlight,
total: highlight > total ? highlight : total,
total: resolvedTotal,
};
};
export const getUnreadInfos = (mx: MatrixClient): UnreadInfo[] =>
export const getUnreadInfos = (mx: MatrixClient, options?: UnreadInfoOptions): UnreadInfo[] =>
mx.getRooms().reduce<UnreadInfo[]>((unread, room) => {
if (room.isSpaceRoom()) return unread;
if (room.getMyMembership() !== 'join') return unread;
if (getNotificationType(mx, room.roomId) === NotificationType.Mute) return unread;
if (roomHaveNotification(room) || roomHaveUnread(mx, room)) {
const unreadInfo = getUnreadInfo(room);
const unreadInfo = getUnreadInfo(room, options);
if (unreadInfo.total > 0 || unreadInfo.highlight > 0) {
unread.push(unreadInfo);
}
+53 -16
View File
@@ -21,6 +21,7 @@ import { SlidingSyncConfig, SlidingSyncDiagnostics, SlidingSyncManager } from '.
const log = createLogger('initMatrix');
const slidingSyncByClient = new WeakMap<MatrixClient, SlidingSyncManager>();
const FAST_SYNC_POLL_TIMEOUT_MS = 10000;
type SyncTransport = 'classic' | 'sliding';
type SyncTransportMeta = {
transport: SyncTransport;
@@ -29,6 +30,17 @@ type SyncTransportMeta = {
};
const syncTransportByClient = new WeakMap<MatrixClient, SyncTransportMeta>();
export const resolveSlidingEnabled = (enabled: SlidingSyncConfig['enabled']): boolean => {
if (enabled === undefined) return false;
if (typeof enabled === 'boolean') return enabled;
const normalized = String(enabled).trim().toLowerCase();
if (normalized === 'false' || normalized === '0' || normalized === 'off' || normalized === 'no')
return false;
if (normalized === 'true' || normalized === '1' || normalized === 'on' || normalized === 'yes')
return true;
return false;
};
const deleteDatabase = (name: string): Promise<void> =>
new Promise((resolve) => {
const req = window.indexedDB.deleteDatabase(name);
@@ -256,6 +268,7 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
export type StartClientConfig = {
baseUrl?: string;
slidingSync?: SlidingSyncConfig;
sessionSlidingSyncOptIn?: boolean;
};
export type ClientSyncDiagnostics = SyncTransportMeta & {
@@ -279,39 +292,63 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig)
log.log('startClient', mx.getUserId());
disposeSlidingSync(mx);
const slidingConfig = config?.slidingSync;
const slidingEnabledOnServer = resolveSlidingEnabled(slidingConfig?.enabled);
const slidingRequested = slidingEnabledOnServer && config?.sessionSlidingSyncOptIn === true;
const proxyBaseUrl = slidingConfig?.proxyBaseUrl ?? config?.baseUrl;
const slidingEnabled = false; // temporary
const canUseSliding = slidingEnabled && typeof proxyBaseUrl === 'string';
syncTransportByClient.set(mx, {
transport: 'classic',
slidingConfigured: canUseSliding,
fallbackFromSliding: false,
const hasSlidingProxy = typeof proxyBaseUrl === 'string' && proxyBaseUrl.trim().length > 0;
log.log('startClient sliding config', {
userId: mx.getUserId(),
enabled: slidingConfig?.enabled,
enabledOnServer: slidingEnabledOnServer,
sessionOptIn: config?.sessionSlidingSyncOptIn === true,
requestedEnabled: slidingRequested,
proxyBaseUrl,
hasSlidingProxy,
});
if (!canUseSliding) {
const startClassicSync = async (fallbackFromSliding: boolean) => {
syncTransportByClient.set(mx, {
transport: 'classic',
slidingConfigured: slidingEnabledOnServer,
fallbackFromSliding,
});
await mx.startClient({
lazyLoadMembers: true,
pollTimeout: FAST_SYNC_POLL_TIMEOUT_MS,
});
};
if (!slidingEnabledOnServer || !slidingRequested) {
await startClassicSync(false);
return;
}
if (!hasSlidingProxy) {
await startClassicSync(false);
return;
}
const resolvedProxyBaseUrl = proxyBaseUrl;
const manager = new SlidingSyncManager(mx, resolvedProxyBaseUrl, slidingConfig ?? {});
const manager = new SlidingSyncManager(mx, resolvedProxyBaseUrl, {
...(slidingConfig ?? {}),
includeInviteList: true,
pollTimeoutMs: slidingConfig?.pollTimeoutMs ?? FAST_SYNC_POLL_TIMEOUT_MS,
});
const supported = await SlidingSyncManager.probe(
mx,
resolvedProxyBaseUrl,
manager.probeTimeoutMs
);
log.log('startClient sliding probe result', {
userId: mx.getUserId(),
requestedEnabled: slidingRequested,
hasSlidingProxy,
proxyBaseUrl: resolvedProxyBaseUrl,
supported,
});
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,
});
await startClassicSync(true);
return;
}
+1 -1
View File
@@ -21,7 +21,7 @@ const DEFAULT_TIMELINE_LIMIT = 30;
const TIMELINE_LIMIT_LOW = 10;
const TIMELINE_LIMIT_MEDIUM = 15;
const TIMELINE_LIMIT_HIGH = 30;
const DEFAULT_POLL_TIMEOUT_MS = 30000;
const DEFAULT_POLL_TIMEOUT_MS = 10000;
const DEFAULT_MAX_ROOMS = 5000;
export type SlidingSyncConfig = {