From 5372e36153e177ad1ce5c6476f6d1710ebcf378c Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 00:51:02 -0500 Subject: [PATCH 1/4] feat(notifications): in-app notification banner, account unread counts, and Discord-style floating pill --- .vscode/settings.json | 3 + .../NotificationBanner.css.ts | 154 +++++++++++++++ .../NotificationBanner.tsx | 181 ++++++++++++++++++ .../components/notification-banner/index.ts | 1 + .../pages/client/BackgroundNotifications.tsx | 113 ++++++++--- src/app/pages/client/ClientNonUIFeatures.tsx | 135 +++++++------ .../client/sidebar/AccountSwitcherTab.tsx | 46 +++-- src/app/state/sessions.ts | 35 +++- 8 files changed, 565 insertions(+), 103 deletions(-) create mode 100644 src/app/components/notification-banner/NotificationBanner.css.ts create mode 100644 src/app/components/notification-banner/NotificationBanner.tsx create mode 100644 src/app/components/notification-banner/index.ts diff --git a/.vscode/settings.json b/.vscode/settings.json index 29e56e92..7984494d 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -7,5 +7,8 @@ }, "[json]": { "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "chat.tools.terminal.autoApprove": { + "npx tsc": true } } diff --git a/src/app/components/notification-banner/NotificationBanner.css.ts b/src/app/components/notification-banner/NotificationBanner.css.ts new file mode 100644 index 00000000..80c3617f --- /dev/null +++ b/src/app/components/notification-banner/NotificationBanner.css.ts @@ -0,0 +1,154 @@ +import { keyframes, style } from '@vanilla-extract/css'; +import { color, config, toRem } from 'folds'; + +const slideIn = keyframes({ + from: { + opacity: 0, + transform: 'translateY(-100%)', + }, + to: { + opacity: 1, + transform: 'translateY(0)', + }, +}); + +const slideOut = keyframes({ + from: { + opacity: 1, + transform: 'translateY(0)', + }, + to: { + opacity: 0, + transform: 'translateY(-100%)', + }, +}); + +// Floats at the top of the chat area, starting after the icon sidebar. +export const BannerContainer = style({ + position: 'fixed', + top: 0, + // 66px = sidebar icon strip width — overridden to 0 on mobile below + left: toRem(66), + right: 0, + zIndex: 9999, + display: 'flex', + flexDirection: 'column', + gap: config.space.S200, + padding: config.space.S400, + pointerEvents: 'none', + alignItems: 'stretch', + + '@media': { + // On narrow screens the sidebar collapses, so span the full width. + '(max-width: 768px)': { + left: 0, + }, + }, +}); + +export const Banner = style({ + position: 'relative', + overflow: 'hidden', + pointerEvents: 'all', + display: 'flex', + alignItems: 'center', + gap: config.space.S300, + backgroundColor: color.Surface.Container, + color: color.Surface.OnContainer, + border: `${config.borderWidth.B300} solid ${color.Surface.ContainerLine}`, + borderRadius: toRem(16), + padding: `${config.space.S300} ${config.space.S400}`, + boxShadow: `0 ${toRem(8)} ${toRem(32)} rgba(0, 0, 0, 0.45), 0 ${toRem(2)} ${toRem(8)} rgba(0, 0, 0, 0.3)`, + cursor: 'pointer', + width: '100%', + animationName: slideIn, + animationDuration: '260ms', + animationTimingFunction: 'cubic-bezier(0.22, 0.8, 0.6, 1)', + animationFillMode: 'both', + + selectors: { + '&:hover': { + backgroundColor: color.Surface.ContainerHover, + }, + '&[data-dismissing=true]': { + animationName: slideOut, + animationDuration: '200ms', + animationTimingFunction: 'cubic-bezier(0.4, 0, 1, 1)', + animationFillMode: 'both', + }, + }, +}); + +export const BannerIcon = style({ + width: toRem(44), + height: toRem(44), + objectFit: 'cover', + borderRadius: config.radii.R300, + flexShrink: 0, +}); + +export const BannerContent = style({ + flex: 1, + minWidth: 0, + display: 'flex', + flexDirection: 'column', + gap: toRem(2), +}); + +export const BannerTitle = style({ + fontWeight: 700, +}); + +export const BannerSubtitle = style({ + fontWeight: 400, + opacity: 0.7, +}); + +export const BannerRoomName = style({ + color: color.Primary.Main, + fontWeight: 600, +}); + +// Caps tall previews and fades the bottom edge when content overflows. +export const BannerBody = style({ + position: 'relative', + maxHeight: toRem(56), + overflow: 'hidden', + + selectors: { + '&[data-overflow=true]::after': { + content: '""', + position: 'absolute', + bottom: 0, + left: 0, + right: 0, + height: toRem(28), + background: `linear-gradient(to bottom, transparent, ${color.Surface.Container})`, + pointerEvents: 'none', + }, + '&[data-overflow=true][data-hovered=true]::after': { + background: `linear-gradient(to bottom, transparent, ${color.Surface.ContainerHover})`, + }, + }, +}); + +export const ProgressBar = style({ + position: 'absolute', + bottom: 0, + left: 0, + height: toRem(3), + borderBottomLeftRadius: toRem(16), + backgroundColor: color.Primary.Main, + animationName: keyframes({ + from: { width: '100%' }, + to: { width: '0%' }, + }), + animationTimingFunction: 'linear', + animationFillMode: 'both', + + selectors: { + '&[data-paused=true]': { + animationPlayState: 'paused', + }, + }, +}); diff --git a/src/app/components/notification-banner/NotificationBanner.tsx b/src/app/components/notification-banner/NotificationBanner.tsx new file mode 100644 index 00000000..6732a1fe --- /dev/null +++ b/src/app/components/notification-banner/NotificationBanner.tsx @@ -0,0 +1,181 @@ +import { useAtom } from 'jotai'; +import { useCallback, useEffect, useRef, useState } from 'react'; +import { Box, Icon, IconButton, Icons, Text } from 'folds'; +import { inAppBannerAtom, InAppBannerNotification } from '$state/sessions'; +import * as css from './NotificationBanner.css'; + +const BANNER_DURATION_MS = 5000; + +// Renders body text capped at a max height with a gradient fade when it overflows. +function BodyText({ text, hovered }: { text: string; hovered: boolean }) { + const ref = useRef(null); + const [overflow, setOverflow] = useState(false); + + useEffect(() => { + const el = ref.current; + if (!el) return; + setOverflow(el.scrollHeight > el.clientHeight); + }, [text]); + + return ( +
+ + {text} + +
+ ); +} + +type BannerItemProps = { + notification: InAppBannerNotification; + onDismiss: (id: string) => void; +}; + +function BannerItem({ notification, onDismiss }: BannerItemProps) { + const [dismissing, setDismissing] = useState(false); + const [paused, setPaused] = useState(false); + const dismissedRef = useRef(false); + const dismissAnimTimerRef = useRef | null>(null); + const elapsedRef = useRef(0); + + // Use a ref to guard against double-dismiss without creating a new callback identity. + const dismiss = useCallback(() => { + if (dismissedRef.current) return; + dismissedRef.current = true; + setDismissing(true); + dismissAnimTimerRef.current = setTimeout(() => onDismiss(notification.id), 200); + }, [notification.id, onDismiss]); + + // Auto-dismiss timer — only runs when not paused. + useEffect(() => { + if (paused) return undefined; + const remaining = BANNER_DURATION_MS - elapsedRef.current; + if (remaining <= 0) { + dismiss(); + return undefined; + } + const startedAt = Date.now(); + const t = setTimeout(dismiss, remaining); + return () => { + clearTimeout(t); + // Accumulate time spent un-paused so we can resume from the right point. + elapsedRef.current += Date.now() - startedAt; + }; + }, [paused, dismiss]); + + useEffect( + () => () => { + if (dismissAnimTimerRef.current) clearTimeout(dismissAnimTimerRef.current); + }, + [] + ); + + const handleClick = () => { + notification.onClick(); + dismiss(); + }; + + // When hovering, pause the auto-dismiss timer. + const handleMouseEnter = () => setPaused(true); + const handleMouseLeave = () => setPaused(false); + + return ( +
{ + if (e.key === 'Enter' || e.key === ' ') handleClick(); + if (e.key === 'Escape') dismiss(); + }} + onMouseEnter={handleMouseEnter} + onMouseLeave={handleMouseLeave} + > + {notification.icon && ( + { + (e.currentTarget as HTMLImageElement).style.display = 'none'; + }} + /> + )} +
+ + {notification.senderName ?? notification.title} + {(notification.roomName || notification.serverName) && ( + + {' (​'} + {notification.roomName && `#${notification.roomName}`} + {notification.roomName && notification.serverName && ', '} + {notification.serverName} + {')'} + + )} + + {notification.body && } +
+ + { + e.stopPropagation(); + dismiss(); + }} + aria-label="Dismiss notification" + > + + + +
+
+ ); +} + +/** + * Renders the in-app notification banner stack. + * Mount this once near the root of the client layout. + */ +export function NotificationBanner() { + // We store an array locally so multiple rapid notifications stack briefly. + const [banner, setBanner] = useAtom(inAppBannerAtom); + const [queue, setQueue] = useState([]); + + // Push new notifications into the local queue. + useEffect(() => { + if (!banner) return; + setQueue((prev) => { + // De-duplicate by id + if (prev.some((n) => n.id === banner.id)) return prev; + // Keep at most 3 visible at once — drop the oldest if over limit. + const next = [...prev, banner]; + return next.length > 3 ? next.slice(next.length - 3) : next; + }); + // Clear the atom so the same notification doesn't re-enqueue on re-render. + setBanner(null); + }, [banner, setBanner]); + + const handleDismiss = (id: string) => { + setQueue((prev) => prev.filter((n) => n.id !== id)); + }; + + if (queue.length === 0) return null; + + return ( +
+ {queue.map((n) => ( + + ))} +
+ ); +} diff --git a/src/app/components/notification-banner/index.ts b/src/app/components/notification-banner/index.ts new file mode 100644 index 00000000..75a031d6 --- /dev/null +++ b/src/app/components/notification-banner/index.ts @@ -0,0 +1 @@ +export { NotificationBanner } from './NotificationBanner'; diff --git a/src/app/pages/client/BackgroundNotifications.tsx b/src/app/pages/client/BackgroundNotifications.tsx index a4f90bc6..1b1f89ec 100644 --- a/src/app/pages/client/BackgroundNotifications.tsx +++ b/src/app/pages/client/BackgroundNotifications.tsx @@ -9,8 +9,15 @@ import { SyncState, PushProcessor, } from '$types/matrix-sdk'; -import { useAtomValue, useSetAtom } from 'jotai'; -import { sessionsAtom, activeSessionIdAtom, Session, sessionsHighlightAtom } from '$state/sessions'; +import { useAtom, useAtomValue, useSetAtom } from 'jotai'; +import { + sessionsAtom, + activeSessionIdAtom, + Session, + pendingNotificationAtom, + backgroundUnreadCountsAtom, + inAppBannerAtom, +} from '$state/sessions'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix'; @@ -77,7 +84,7 @@ const waitForSync = (mx: MatrixClient): Promise => export function BackgroundNotifications() { const clientConfig = useClientConfig(); const sessions = useAtomValue(sessionsAtom); - const activeSessionId = useAtomValue(activeSessionIdAtom); + const [activeSessionId, setActiveSessionId] = useAtom(activeSessionIdAtom); const [showNotifications] = useSetting(settingsAtom, 'useInAppNotifications'); const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications'); const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds'); @@ -101,7 +108,14 @@ export function BackgroundNotifications() { showEncryptedMessageContentRef.current = showEncryptedMessageContent; const clientsRef = useRef>(new Map()); const notifiedEventsRef = useRef>(new Set()); - const setHighlights = useSetAtom(sessionsHighlightAtom); + const setPending = useSetAtom(pendingNotificationAtom); + const setBackgroundUnreads = useSetAtom(backgroundUnreadCountsAtom); + const setInAppBanner = useSetAtom(inAppBannerAtom); + // Stable setter refs so async handleTimeline closures never go stale. + const setBackgroundUnreadsRef = useRef(setBackgroundUnreads); + setBackgroundUnreadsRef.current = setBackgroundUnreads; + const setInAppBannerRef = useRef(setInAppBanner); + setInAppBannerRef.current = setInAppBanner; const inactiveSessions = sessions.filter( (s) => s.userId !== (activeSessionId ?? sessions[0]?.userId) @@ -122,6 +136,9 @@ export function BackgroundNotifications() { * Must include { type, room_id, event_id, user_id } so the SW notificationclick * handler can route the tap through HandleNotificationClick for account switching. */ data?: unknown; + /** Optional callback invoked when the user clicks the notification (window.Notification + * fallback path only; the SW path routes via its own notificationclick handler). */ + onClick?: () => void; } useEffect(() => { @@ -151,14 +168,19 @@ export function BackgroundNotifications() { } } if ('Notification' in window && window.Notification.permission === 'granted') { - // eslint-disable-next-line no-new - new window.Notification(opts.title, { + const noti = new window.Notification(opts.title, { icon: opts.icon, badge: opts.badge, body: opts.body, silent: opts.silent ?? false, data: opts.data, }); + if (opts.onClick) { + noti.onclick = () => { + opts.onClick?.(); + noti.close(); + }; + } } } @@ -167,8 +189,8 @@ export function BackgroundNotifications() { log.log('stopping background client for', userId); stopClient(mx); current.delete(userId); - // Clear the highlight badge when this session is no longer a background account. - setHighlights((prev) => { + // Clear the background unread badge when this session is no longer a background account. + setBackgroundUnreads((prev) => { const next = { ...prev }; delete next[userId]; return next; @@ -226,6 +248,23 @@ export function BackgroundNotifications() { : LogoSVG; const loudByRule = Boolean(pushActions.tweaks?.sound); + + // Track background unread count for every notifiable event (loud or silent). + const isHighlight = Boolean(pushActions.tweaks?.highlight); + setBackgroundUnreadsRef.current((prev) => { + const cur = prev[session.userId] ?? { total: 0, highlight: 0 }; + return { + ...prev, + [session.userId]: { + total: cur.total + 1, + highlight: isHighlight ? cur.highlight + 1 : cur.highlight, + }, + }; + }); + + // Silent-rule events: unread badge updated above; no OS notification or sound. + if (!loudByRule && !isHighlight) return; + const isEncryptedRoom = !!getStateEvent(room, StateEvent.RoomEncryption); notifiedEventsRef.current.add(dedupeId); @@ -235,14 +274,6 @@ export function BackgroundNotifications() { if (first) notifiedEventsRef.current.delete(first); } - // Track highlight count for the account switcher badge. - if (pushActions.tweaks?.highlight) { - setHighlights((prev) => ({ - ...prev, - [session.userId]: (prev[session.userId] ?? 0) + 1, - })); - } - // This component handles ONLY background (inactive) accounts. // SW push covers the active account when the app is backgrounded. // When the page is hidden, iOS suspends JS entirely — nothing to do here. @@ -275,14 +306,38 @@ export function BackgroundNotifications() { }, }); - sendNotification({ - title: notificationPayload.title, - icon: notificationPayload.options.icon, - badge: notificationPayload.options.badge, - body: notificationPayload.options.body, - silent: notificationPayload.options.silent ?? undefined, - data: notificationPayload.options.data, - }); + const notifOnClick = () => { + window.focus(); + // Always switch to the background account – jotai ignores no-op updates + setActiveSessionId(session.userId); + setPending({ roomId: room.roomId, eventId, targetSessionId: session.userId }); + }; + + if (document.visibilityState === 'visible') { + // App is in the foreground on a different account — show the themed in-app banner. + setInAppBannerRef.current({ + id: dedupeId, + title: notificationPayload.title, + roomName: room.name ?? room.getCanonicalAlias() ?? undefined, + senderName, + body: notificationPayload.options.body, + icon: notificationPayload.options.icon, + onClick: notifOnClick, + }); + } else if (loudByRule) { + // App is backgrounded — fire an OS notification only for loud (sound-tweak) rules. + // Highlight-only events are silently counted in the badge; OS noise is left to the + // user's own push rules for that account. + sendNotification({ + title: notificationPayload.title, + icon: notificationPayload.options.icon, + badge: notificationPayload.options.badge, + body: notificationPayload.options.body, + silent: notificationPayload.options.silent ?? undefined, + data: notificationPayload.options.data, + onClick: notifOnClick, + }); + } }; mx.on(RoomEvent.Timeline, handleTimeline as unknown as (...args: unknown[]) => void); @@ -296,7 +351,15 @@ export function BackgroundNotifications() { current.forEach((mx) => stopClient(mx)); current.clear(); }; - }, [clientConfig.slidingSync, inactiveSessions, shouldRunBackgroundNotifications, setHighlights]); + }, [ + clientConfig.slidingSync, + inactiveSessions, + shouldRunBackgroundNotifications, + setActiveSessionId, + setPending, + setBackgroundUnreads, + setInAppBanner, + ]); return null; } diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index d8e81e35..e067c2ce 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom'; import { EventType, PushProcessor, RoomEvent, RoomEventHandlerMap } from '$types/matrix-sdk'; import { roomToUnreadAtom } from '$state/room/roomToUnread'; import LogoSVG from '$public/res/svg/cinny.svg'; +import { NotificationBanner } from '$components/notification-banner'; import LogoUnreadSVG from '$public/res/svg/cinny-unread.svg'; import LogoHighlightSVG from '$public/res/svg/cinny-highlight.svg'; import NotificationSound from '$public/sound/notification.ogg'; @@ -27,7 +28,7 @@ import { useSelectedRoom } from '$hooks/router/useSelectedRoom'; import { useInboxNotificationsSelected } from '$hooks/router/useInbox'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { registrationAtom } from '$state/serviceWorkerRegistration'; -import { activeSessionIdAtom, pendingNotificationAtom } from '$state/sessions'; +import { activeSessionIdAtom, pendingNotificationAtom, inAppBannerAtom } from '$state/sessions'; import { buildRoomMessageNotification, resolveNotificationPreviewText, @@ -187,7 +188,6 @@ function InviteNotifications() { function MessageNotifications() { const audioRef = useRef(null); - const notifRef = useRef(); const notifiedEventsRef = useRef>(new Set()); const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -204,51 +204,10 @@ function MessageNotifications() { nicknamesRef.current = nicknames; const setPending = useSetAtom(pendingNotificationAtom); + const setInAppBanner = useSetAtom(inAppBannerAtom); const selectedRoomId = useSelectedRoom(); const notificationSelected = useInboxNotificationsSelected(); - const notify = useCallback( - ({ - roomName, - roomAvatar, - username, - roomId, - eventId, - previewText, - silent, - }: { - roomName: string; - roomAvatar?: string; - username: string; - roomId: string; - eventId: string; - previewText: string; - silent: boolean; - }) => { - const payload = buildRoomMessageNotification({ - roomName, - roomAvatar, - username, - previewText, - silent, - eventId, - }); - const noti = new window.Notification(payload.title, payload.options); - - noti.onclick = () => { - window.focus(); - setPending({ roomId, eventId, targetSessionId: mx.getUserId() ?? undefined }); - - noti.close(); - notifRef.current = undefined; - }; - - notifRef.current?.close(); - notifRef.current = noti; - }, - [mx, setPending] - ); - const playSound = useCallback(() => { const audioElement = audioRef.current; audioElement?.play(); @@ -279,32 +238,86 @@ function MessageNotifications() { const sender = mEvent.getSender(); const eventId = mEvent.getId(); if (!sender || !eventId || mEvent.getSender() === mx.getUserId()) return; + + // Deduplicate: don't show a second banner if this event fires twice + // (e.g., decrypted events re-emitted by the SDK). + if (notifiedEventsRef.current.has(eventId)) return; + const pushActions = pushProcessor.actionsForEvent(mEvent); if (!pushActions?.notify) return; const loudByRule = Boolean(pushActions.tweaks?.sound); + const isHighlightByRule = Boolean(pushActions.tweaks?.highlight); - // Deduplicate: never fire the same notification twice for the same event. - if (notifiedEventsRef.current.has(eventId)) return; + // If neither a loud nor a highlight rule matches, nothing to show. + if (!isHighlightByRule && !loudByRule) return; + + // Page hidden: SW (push) handles the OS notification. Nothing to do in-app. + if (document.visibilityState !== 'visible') return; + + // Record as notified to prevent duplicate banners (e.g. re-emitted decrypted events). notifiedEventsRef.current.add(eventId); if (notifiedEventsRef.current.size > 200) { const first = notifiedEventsRef.current.values().next().value; if (first) notifiedEventsRef.current.delete(first); } - // Page hidden: if push is enabled, SW handles the OS notification. If not, nothing to do. - if (document.visibilityState !== 'visible') return; + // Page is visible — show the themed in-app notification banner for any + // highlighted message (mention / keyword) or loud push rule. + if ((isHighlightByRule || loudByRule) && showNotifications) { + const isEncryptedRoom = !!getStateEvent(room, StateEvent.RoomEncryption); + const avatarMxc = + room.getAvatarFallbackMember()?.getMxcAvatarUrl() ?? room.getMxcAvatarUrl(); + const roomAvatar = avatarMxc + ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined) + : undefined; + const resolvedSenderName = + getMemberDisplayName(room, sender, nicknamesRef.current) ?? + getMxIdLocalPart(sender) ?? + sender; + const previewText = resolveNotificationPreviewText({ + content: mEvent.getContent(), + eventType: mEvent.getType(), + isEncryptedRoom, + showMessageContent, + showEncryptedMessageContent, + }); + const payload = buildRoomMessageNotification({ + roomName: room.name ?? 'Unknown', + roomAvatar, + username: resolvedSenderName, + previewText, + silent: !notificationSound, + eventId, + }); + const { roomId } = room; + const capturedEventId = eventId; + const capturedUserId = mx.getUserId() ?? undefined; + const canonicalAlias = room.getCanonicalAlias(); + const serverName = + canonicalAlias?.split(':')[1] ?? room.roomId.split(':')[1] ?? undefined; + setInAppBanner({ + id: eventId, + title: payload.title, + roomName: room.name ?? undefined, + serverName, + senderName: resolvedSenderName, + body: previewText, + icon: roomAvatar, + onClick: () => { + window.focus(); + setPending({ roomId, eventId: capturedEventId, targetSessionId: capturedUserId }); + }, + }); + } - // Page is visible — show in-app experience. - // On mobile with push: iOS-style — play sound only, no OS notification (SW is silent when - // the app is visible on mobile, matching foreground behaviour of native chat apps). - // On desktop with push: SW skipped (saw a visible client), so we show the OS notification. - // Without push: always show OS notification when page is visible. + // On desktop without push: also fire an OS notification as a secondary fallback + // so the user is alerted even if the browser window is minimised. const isVisibleMobileWithPush = usePushNotifications && mobileOrTablet(); if (!isVisibleMobileWithPush && showNotifications && notificationPermission('granted')) { const isEncryptedRoom = !!getStateEvent(room, StateEvent.RoomEncryption); const avatarMxc = room.getAvatarFallbackMember()?.getMxcAvatarUrl() ?? room.getMxcAvatarUrl(); - notify({ + const osPayload = buildRoomMessageNotification({ roomName: room.name ?? 'Unknown', roomAvatar: avatarMxc ? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined) @@ -313,8 +326,6 @@ function MessageNotifications() { getMemberDisplayName(room, sender, nicknamesRef.current) ?? getMxIdLocalPart(sender) ?? sender, - roomId: room.roomId, - eventId, previewText: resolveNotificationPreviewText({ content: mEvent.getContent(), eventType: mEvent.getType(), @@ -324,7 +335,15 @@ function MessageNotifications() { }), // Play sound only if the push rule requests it and the user has sounds enabled. silent: !notificationSound || !loudByRule, + eventId, }); + const noti = new window.Notification(osPayload.title, osPayload.options); + const { roomId } = room; + noti.onclick = () => { + window.focus(); + setPending({ roomId, eventId, targetSessionId: mx.getUserId() ?? undefined }); + noti.close(); + }; } if (notificationSound && loudByRule) { @@ -344,7 +363,8 @@ function MessageNotifications() { showEncryptedMessageContent, usePushNotifications, playSound, - notify, + setInAppBanner, + setPending, selectedRoomId, useAuthentication, ]); @@ -470,6 +490,7 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) { + {children} ); diff --git a/src/app/pages/client/sidebar/AccountSwitcherTab.tsx b/src/app/pages/client/sidebar/AccountSwitcherTab.tsx index 50ff707a..61058d95 100644 --- a/src/app/pages/client/sidebar/AccountSwitcherTab.tsx +++ b/src/app/pages/client/sidebar/AccountSwitcherTab.tsx @@ -17,14 +17,18 @@ import { import FocusTrap from 'focus-trap-react'; import { useAtom, useAtomValue, useSetAtom } from 'jotai'; import { useNavigate } from 'react-router-dom'; -import { sessionsAtom, activeSessionIdAtom, Session, sessionsHighlightAtom } from '$state/sessions'; +import { + sessionsAtom, + activeSessionIdAtom, + Session, + backgroundUnreadCountsAtom, +} 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'; @@ -39,6 +43,7 @@ import { Settings } from '$features/settings'; import { Modal500 } from '$components/Modal500'; import { createLogger } from '$utils/debug'; import { useClientConfig } from '$hooks/useClientConfig'; +import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge'; const log = createLogger('AccountSwitcherTab'); @@ -48,7 +53,7 @@ function AccountRow({ displayName, avatarUrl, isBusy, - highlightCount, + unread, onSwitch, onSignOut, }: { @@ -57,7 +62,7 @@ function AccountRow({ displayName?: string; avatarUrl?: string; isBusy?: boolean; - highlightCount?: number; + unread?: { total: number; highlight: number }; onSwitch: (session: Session) => void; onSignOut: (session: Session) => void; }) { @@ -85,8 +90,10 @@ function AccountRow({ } after={ - {!isActive && highlightCount != null && highlightCount > 0 && ( - + {!isActive && unread && unread.total > 0 && ( + + 0} count={unread.total} /> + )} {isActive && ( @@ -137,8 +144,17 @@ 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 backgroundUnreads = useAtomValue(backgroundUnreadCountsAtom); + const setBackgroundUnreads = useSetAtom(backgroundUnreadCountsAtom); + + // Total unread count across all background sessions (for the sidebar badge). + const totalBackgroundUnread = Object.entries(backgroundUnreads) + .filter(([uid]) => uid !== (activeSessionId ?? sessions[0]?.userId)) + .reduce((acc, [, u]) => acc + u.total, 0); + const anyBackgroundHighlight = Object.entries(backgroundUnreads) + .filter(([uid]) => uid !== (activeSessionId ?? sessions[0]?.userId)) + .some(([, u]) => u.highlight > 0); const [menuAnchor, setMenuAnchor] = useState(); const [busyUserIds, setBusyUserIds] = useState>(new Set()); @@ -173,14 +189,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) => { + // Clear the unread badge for the account we're now switching into. + setBackgroundUnreads((prev) => { const next = { ...prev }; delete next[session.userId]; return next; }); }, - [navigate, setActiveSessionId, setSessionHighlights] + [navigate, setActiveSessionId, setBackgroundUnreads] ); const handleSignOut = useCallback( @@ -237,10 +253,6 @@ 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 ( @@ -262,9 +274,9 @@ export function AccountSwitcherTab() { )} - {inactiveHighlightTotal > 0 && ( + {totalBackgroundUnread > 0 && ( - + )} @@ -310,7 +322,7 @@ export function AccountSwitcherTab() { displayName={rowDisplayName} avatarUrl={rowAvatarUrl} isBusy={busyUserIds.has(session.userId)} - highlightCount={sessionHighlights[session.userId]} + unread={!isActive ? backgroundUnreads[session.userId] : undefined} onSwitch={handleSwitch} onSignOut={handleSignOut} /> diff --git a/src/app/state/sessions.ts b/src/app/state/sessions.ts index fc833c33..10a4ff3b 100644 --- a/src/app/state/sessions.ts +++ b/src/app/state/sessions.ts @@ -171,9 +171,36 @@ export type PendingNotification = { export const pendingNotificationAtom = atom(null); +// ─── In-app notification banner ──────────────────────────────────────────── + +export type InAppBannerNotification = { + /** Unique id; used to deduplicate rapid-fire events. */ + id: string; + /** Primary title line – kept for backwards-compat (background accounts). */ + title: string; + /** Room display name (used as the #channel part of the subtitle). */ + roomName?: string; + /** Homeserver extracted from the canonical alias or room ID (e.g. matrix.org). */ + serverName?: string; + /** Display name of the sender. */ + senderName?: string; + body?: string; + /** URL of an avatar or room icon to display inside the banner. */ + icon?: string; + onClick: () => void; +}; + +export const inAppBannerAtom = atom(null); + +// ─── Per-background-account unread counts ────────────────────────────────── + +export type BackgroundUnread = { + total: number; + highlight: number; +}; + /** - * 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. + * Keyed by userId. Counts accumulate while a session is in the background + * and are cleared when the user switches to that account. */ -export const sessionsHighlightAtom = atom>({}); +export const backgroundUnreadCountsAtom = atom>({}); From 12cc25e49d1a2db81f7b4d444e7f14baab9a09ef Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 00:53:16 -0500 Subject: [PATCH 2/4] revert settings changes --- .vscode/settings.json | 3 --- 1 file changed, 3 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 7984494d..29e56e92 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -7,8 +7,5 @@ }, "[json]": { "editor.defaultFormatter": "esbenp.prettier-vscode" - }, - "chat.tools.terminal.autoApprove": { - "npx tsc": true } } From f6cf0d13b7a2655dc7e81df874fdf3f2b5899384 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 00:57:08 -0500 Subject: [PATCH 3/4] fix: resolve lint and formatting issues for quality checks --- src/app/components/notification-banner/NotificationBanner.tsx | 3 +-- src/app/pages/client/ClientNonUIFeatures.tsx | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/app/components/notification-banner/NotificationBanner.tsx b/src/app/components/notification-banner/NotificationBanner.tsx index 6732a1fe..ad0ba026 100644 --- a/src/app/components/notification-banner/NotificationBanner.tsx +++ b/src/app/components/notification-banner/NotificationBanner.tsx @@ -111,8 +111,7 @@ function BannerItem({ notification, onDismiss }: BannerItemProps) { {' (​'} {notification.roomName && `#${notification.roomName}`} {notification.roomName && notification.serverName && ', '} - {notification.serverName} - {')'} + {notification.serverName}) )} diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index e067c2ce..f3bbfb26 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -293,8 +293,7 @@ function MessageNotifications() { const capturedEventId = eventId; const capturedUserId = mx.getUserId() ?? undefined; const canonicalAlias = room.getCanonicalAlias(); - const serverName = - canonicalAlias?.split(':')[1] ?? room.roomId.split(':')[1] ?? undefined; + const serverName = canonicalAlias?.split(':')[1] ?? room.roomId.split(':')[1] ?? undefined; setInAppBanner({ id: eventId, title: payload.title, From 368124c294d38442e692b4ea9d0a7fff9067f576 Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Thu, 5 Mar 2026 13:18:09 -0500 Subject: [PATCH 4/4] Document change --- .changeset/notification_pull_unread_background_badge.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/notification_pull_unread_background_badge.md diff --git a/.changeset/notification_pull_unread_background_badge.md b/.changeset/notification_pull_unread_background_badge.md new file mode 100644 index 00000000..0559d03a --- /dev/null +++ b/.changeset/notification_pull_unread_background_badge.md @@ -0,0 +1,5 @@ +--- +sable: patch +--- + +Adds a new message pill and background app highlighted unread count.