diff --git a/src/app/pages/client/sidebar/AccountSwitcherTab.tsx b/src/app/pages/client/sidebar/AccountSwitcherTab.tsx index 86605515..50ff707a 100644 --- a/src/app/pages/client/sidebar/AccountSwitcherTab.tsx +++ b/src/app/pages/client/sidebar/AccountSwitcherTab.tsx @@ -17,8 +17,14 @@ import { import FocusTrap from 'focus-trap-react'; import { useAtom, useAtomValue, useSetAtom } from 'jotai'; import { useNavigate } from 'react-router-dom'; -import { sessionsAtom, activeSessionIdAtom, Session } from '$state/sessions'; -import { SidebarItem, SidebarItemTooltip, SidebarAvatar } from '$components/sidebar'; +import { sessionsAtom, activeSessionIdAtom, Session, sessionsHighlightAtom } from '$state/sessions'; +import { + SidebarItem, + SidebarItemTooltip, + SidebarAvatar, + SidebarItemBadge, +} from '$components/sidebar'; +import { UnreadBadge } from '$components/unread-badge'; import { UserAvatar } from '$components/user-avatar'; import { nameInitials } from '$utils/common'; import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix'; @@ -42,6 +48,7 @@ function AccountRow({ displayName, avatarUrl, isBusy, + highlightCount, onSwitch, onSignOut, }: { @@ -50,6 +57,7 @@ function AccountRow({ displayName?: string; avatarUrl?: string; isBusy?: boolean; + highlightCount?: number; onSwitch: (session: Session) => void; onSignOut: (session: Session) => void; }) { @@ -77,6 +85,9 @@ function AccountRow({ } after={ + {!isActive && highlightCount != null && highlightCount > 0 && ( + + )} {isActive && ( )} @@ -126,6 +137,7 @@ export function AccountSwitcherTab() { const sessions = useAtomValue(sessionsAtom); const [activeSessionId, setActiveSessionId] = useAtom(activeSessionIdAtom); const setSessions = useSetAtom(sessionsAtom); + const [sessionHighlights, setSessionHighlights] = useAtom(sessionsHighlightAtom); const useAuthentication = useMediaAuthentication(); const [menuAnchor, setMenuAnchor] = useState(); @@ -161,8 +173,14 @@ export function AccountSwitcherTab() { setMenuAnchor(undefined); navigate(getHomePath(), { replace: true }); setActiveSessionId(session.userId); + // Clear the highlight badge for the account we're switching to. + setSessionHighlights((prev) => { + const next = { ...prev }; + delete next[session.userId]; + return next; + }); }, - [navigate, setActiveSessionId] + [navigate, setActiveSessionId, setSessionHighlights] ); const handleSignOut = useCallback( @@ -219,6 +237,10 @@ export function AccountSwitcherTab() { getMxIdLocalPart(activeSession?.userId ?? '') ?? activeSession?.userId ?? ''; const label = activeDisplayName ?? activeLocalPart; + const inactiveHighlightTotal = sessions + .filter((s) => s.userId !== (activeSessionId ?? sessions[0]?.userId)) + .reduce((sum, s) => sum + (sessionHighlights[s.userId] ?? 0), 0); + if (!activeSession) return null; return ( @@ -240,6 +262,11 @@ export function AccountSwitcherTab() { )} + {inactiveHighlightTotal > 0 && ( + + + + )} diff --git a/src/app/state/room/roomToUnread.ts b/src/app/state/room/roomToUnread.ts index 706b4bd7..cf006438 100644 --- a/src/app/state/room/roomToUnread.ts +++ b/src/app/state/room/roomToUnread.ts @@ -10,6 +10,7 @@ import { ReceiptContent, ReceiptType, EventType, + ClientEvent, } from '$types/matrix-sdk'; import { useCallback, useEffect, useRef } from 'react'; import { @@ -32,7 +33,6 @@ import { useSyncState } from '$hooks/useSyncState'; import { useRoomsNotificationPreferencesContext } from '$hooks/useRoomsNotificationPreferences'; import { getClientSyncDiagnostics } from '$client/initMatrix'; import { roomToParentsAtom } from './roomToParents'; -import { mDirectAtom } from '../mDirectList'; export type RoomToUnreadAction = | { @@ -123,14 +123,13 @@ const baseRoomToUnread = atom(new Map()); export const roomToUnreadAtom = atom( (get) => get(baseRoomToUnread), (get, set, action) => { - const dmRoomIds = get(mDirectAtom); - const getEffectiveParents = (roomId: string): Set => - dmRoomIds.has(roomId) ? new Set() : getAllParents(get(roomToParentsAtom), roomId); + const allParentsOf = (roomId: string): Set => + getAllParents(get(roomToParentsAtom), roomId); if (action.type === 'RESET') { const draftRoomToUnread: RoomToUnread = new Map(); action.unreadInfos.forEach((unreadInfo) => { - putUnreadInfo(draftRoomToUnread, getEffectiveParents(unreadInfo.roomId), unreadInfo); + putUnreadInfo(draftRoomToUnread, allParentsOf(unreadInfo.roomId), unreadInfo); }); set(baseRoomToUnread, draftRoomToUnread); return; @@ -144,7 +143,7 @@ export const roomToUnreadAtom = atom deleteUnreadInfo( draftRoomToUnread, - getEffectiveParents(unreadInfo.roomId), + allParentsOf(unreadInfo.roomId), unreadInfo.roomId ) ) @@ -154,14 +153,14 @@ export const roomToUnreadAtom = atom - putUnreadInfo(draftRoomToUnread, getEffectiveParents(unreadInfo.roomId), unreadInfo) + putUnreadInfo(draftRoomToUnread, allParentsOf(unreadInfo.roomId), unreadInfo) ) ); return; @@ -170,7 +169,7 @@ export const roomToUnreadAtom = atom - deleteUnreadInfo(draftRoomToUnread, getEffectiveParents(action.roomId), action.roomId) + deleteUnreadInfo(draftRoomToUnread, allParentsOf(action.roomId), action.roomId) ) ); } @@ -329,6 +328,25 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo }; }, [mx, setUnreadAtom]); + // Seed badge state immediately when a room is first registered with the client + // (e.g. after joining or receiving an invite that gets auto-accepted). + // This avoids the brief window after refresh where badges are invisible until + // the next timeline event arrives. Notifications are NOT triggered here — + // ClientNonUIFeatures handles live notification pop-ups via its own listener. + useEffect(() => { + const handleRoomAdded = (room: Room) => { + if (room.isSpaceRoom() || room.getMyMembership() !== Membership.Join) return; + const unreadInfo = getUnreadInfo(room, { applyFixup: shouldApplyUnreadFixup() }); + if (unreadInfo.total > 0 || unreadInfo.highlight > 0) { + setUnreadAtom({ type: 'PUT', unreadInfo }); + } + }; + mx.on(ClientEvent.Room, handleRoomAdded as (room: Room) => void); + return () => { + mx.removeListener(ClientEvent.Room, handleRoomAdded as (room: Room) => void); + }; + }, [mx, setUnreadAtom, shouldApplyUnreadFixup]); + useEffect( () => () => { if (spaceChildResetTimerRef.current !== null) { diff --git a/src/app/state/sessions.ts b/src/app/state/sessions.ts index 5b02e841..fc833c33 100644 --- a/src/app/state/sessions.ts +++ b/src/app/state/sessions.ts @@ -165,8 +165,15 @@ export const activeSessionIdAtom = atom(null); + +/** + * Tracks the count of highlight-level (mention/keyword) notifications received + * by each background (inactive) session. Keyed by userId. + * Cleared when a session becomes active or is signed out. + */ +export const sessionsHighlightAtom = atom>({}); diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts index aed17e84..49577421 100644 --- a/src/app/utils/room.ts +++ b/src/app/utils/room.ts @@ -13,6 +13,7 @@ import { MatrixEvent, MsgType, NotificationCountType, + PushProcessor, RelationType, Room, RoomMember, @@ -240,18 +241,24 @@ export const getUnreadInfo = (room: Room, options?: UnreadInfoOptions): UnreadIn } let total = room.getUnreadNotificationCount(NotificationCountType.Total); - let highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); - let syntheticDotUnread = false; + const highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight); // If our latest main-timeline notification event is confirmed read, clamp its stale count. // Only apply to the room (non-thread) portion so thread reply counts are preserved. - if (userId && total > 0 && highlight === 0) { + // Guard: only clamp when the room has NO receipt-confirmed unread events; if roomHaveUnread + // is true then there genuinely are unread messages and the SDK count is not fully stale. + if (userId && total > 0 && highlight === 0 && !roomHaveUnread(room.client, room)) { const roomTotal = room.getRoomUnreadNotificationCount(NotificationCountType.Total); if (roomTotal > 0) { const liveEvents = room.getLiveTimeline().getEvents(); + // Exclude the user's own messages: own sent events are always "read" (hasUserReadEvent + // returns true for them), which would cause the clamp to fire incorrectly. const latestNotification = [...liveEvents] .reverse() - .find((event) => !event.isSending() && isNotificationEvent(event)); + .find( + (event) => + !event.isSending() && event.getSender() !== userId && isNotificationEvent(event) + ); const latestNotificationId = latestNotification?.getId(); if (latestNotificationId && room.hasUserReadEvent(userId, latestNotificationId)) { // Subtract only the stale main-timeline count; thread totals remain intact. @@ -260,19 +267,34 @@ export const getUnreadInfo = (room: Room, options?: UnreadInfoOptions): UnreadIn } } - // 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; + // Fallback: SDK counters are stale/zero but there are receipt-confirmed unread + // messages. Walk the live timeline to compute real counts so the badge number + // and highlight colour reflect actual state rather than a hard-coded stub. + if (total === 0 && highlight === 0 && userId && roomHaveUnread(room.client, room)) { + const readUpToId = room.getEventReadUpTo(userId); + const liveEvents = room.getLiveTimeline().getEvents(); + let fallbackTotal = 0; + let fallbackHighlight = 0; + const pushProcessor = new PushProcessor(room.client); + for (let i = liveEvents.length - 1; i >= 0; i -= 1) { + const event = liveEvents[i]; + if (!event) break; + if (event.getId() === readUpToId) break; + if (isNotificationEvent(event) && event.getSender() !== userId) { + fallbackTotal += 1; + const pushActions = pushProcessor.actionsForEvent(event); + if (pushActions?.tweaks?.highlight) fallbackHighlight += 1; + } + } + if (fallbackTotal > 0) { + return { roomId: room.roomId, highlight: fallbackHighlight, total: fallbackTotal }; + } } - const resolvedTotal = syntheticDotUnread ? total : Math.max(total, highlight); - return { roomId: room.roomId, highlight, - total: resolvedTotal, + total: Math.max(total, highlight), }; };