:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notifications): group runs of identical events in the bell sidebar (#58011)
Yasene1f41adb95cd
diff --git a/frontend/jest.config.ts b/frontend/jest.config.tsindex a90860b731b4..087ee8a7a217 100644--- a/frontend/jest.config.ts+++ b/frontend/jest.config.ts@@ -140,6 +140,10 @@ const config: Config = {'^.+\\.sql\\?raw$': '<rootDir>/src/test/mocks/rawFileMock.js','^~/(.*)$': '<rootDir>/src/$1','^@posthog/hogql-parser$': '<rootDir>/node_modules/@posthog/hogql-parser/dist/index.cjs',+ // @posthog/hogvm ships as ESM-only; map to the TS source so Jest (Sucrase) can handle it.+ // Required for sidePanelNotificationsLogic.test.ts and other tests with a transitive+ // import chain through src/lib/hog.ts.+ '^@posthog/hogvm$': '<rootDir>/node_modules/@posthog/hogvm/src/index.ts','^@posthog/lemon-ui(|/.*)$': '<rootDir>/@posthog/lemon-ui/src/$1','^lib/(.*)$': '<rootDir>/src/lib/$1','^react-markdown$': '<rootDir>/src/test/mocks/reactMarkdownMock.js',diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/buildNotificationSourcePath.test.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/buildNotificationSourcePath.test.tsindex f5fa17cf58f1..f76632d8b179 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/buildNotificationSourcePath.test.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/buildNotificationSourcePath.test.ts@@ -13,6 +13,9 @@ function makeNotification(overrides: Partial<InAppNotification> = {}): InAppNotiread: false,read_at: null,resource_type: null,+ resource_id: '',+ target_type: 'user',+ target_id: '1',source_url: '',source_type: null,source_id: null,diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE.test.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE.test.tsindex 695256e95e71..800bd3aebe31 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE.test.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE.test.ts@@ -19,6 +19,9 @@ function makeNotification(overrides: Partial<InAppNotification> = {}): InAppNotiread: false,read_at: null,resource_type: null,+ resource_id: '',+ target_type: 'user',+ target_id: '1',source_url: '',source_type: null,source_id: null,diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.tsnew file mode 100644index 000000000000..ad68a727b4df--- /dev/null+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.ts@@ -0,0 +1,228 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { InAppNotification } from '~/types'++import { groupKey, NotificationGroup, sidePanelNotificationsLogic } from './sidePanelNotificationsLogic'++function makeNotification(overrides: Partial<InAppNotification> = {}): InAppNotification {+ return {+ id: 'n1',+ team_id: 1,+ notification_type: 'alert_firing',+ priority: 'normal',+ title: 't',+ body: '',+ resource_type: 'insight',+ resource_id: 'abc',+ source_url: '',+ source_type: null,+ source_id: null,+ target_type: 'user',+ target_id: '42',+ created_at: '2026-05-07T12:00:00Z',+ read: false,+ read_at: null,+ ...overrides,+ }+}++describe('groupKey', () => {+ it('combines all dimensions with day bucket', () => {+ const key = groupKey(makeNotification())+ expect(key).toContain('alert_firing')+ expect(key).toContain('user:42')+ expect(key).toContain('insight:abc')+ })++ it('treats missing resource fields as empty', () => {+ const key = groupKey(makeNotification({ resource_type: null, resource_id: '' }))+ expect(key).toContain('|:|')+ })++ it('different notification_type breaks the group', () => {+ const a = makeNotification({ notification_type: 'alert_firing' })+ const b = makeNotification({ notification_type: 'comment_mention' })+ expect(groupKey(a)).not.toEqual(groupKey(b))+ })++ it('different target_id breaks the group', () => {+ const a = makeNotification({ target_id: '42' })+ const b = makeNotification({ target_id: '43' })+ expect(groupKey(a)).not.toEqual(groupKey(b))+ })++ it('different resource_id breaks the group', () => {+ const a = makeNotification({ resource_id: 'abc' })+ const b = makeNotification({ resource_id: 'def' })+ expect(groupKey(a)).not.toEqual(groupKey(b))+ })+})++describe('sidePanelNotificationsLogic.groups selector', () => {+ let logic: ReturnType<typeof sidePanelNotificationsLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = sidePanelNotificationsLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('returns empty array when no notifications', () => {+ expect(logic.values.groups).toEqual([])+ })++ it('groups two events with identical dimensions on the same day', () => {+ const a = makeNotification({ id: 'a', created_at: '2026-05-07T12:00:00Z' })+ const b = makeNotification({ id: 'b', created_at: '2026-05-07T08:00:00Z' })+ logic.actions.setInAppNotifications([a, b], false)+ const groups = logic.values.groups+ expect(groups).toHaveLength(1)+ expect(groups[0].count).toBe(2)+ expect(groups[0].representative.id).toBe('a')+ expect(groups[0].children.map((c: InAppNotification) => c.id)).toEqual(['a', 'b'])+ })++ it('separates events with different group keys', () => {+ const a = makeNotification({ id: 'a', resource_id: 'x' })+ const b = makeNotification({ id: 'b', resource_id: 'y' })+ logic.actions.setInAppNotifications([a, b], false)+ const groups = logic.values.groups+ expect(groups).toHaveLength(2)+ expect(groups.every((g: NotificationGroup) => g.count === 1)).toBe(true)+ })++ it('sets has_unread true if any child unread', () => {+ const a = makeNotification({ id: 'a', read: true })+ const b = makeNotification({ id: 'b', read: false })+ logic.actions.setInAppNotifications([a, b], false)+ expect(logic.values.groups[0].has_unread).toBe(true)+ })++ it('sets has_unread false when every child read', () => {+ const a = makeNotification({ id: 'a', read: true })+ const b = makeNotification({ id: 'b', read: true })+ logic.actions.setInAppNotifications([a, b], false)+ expect(logic.values.groups[0].has_unread).toBe(false)+ })+})++describe('sidePanelNotificationsLogic.loadGroupChildren', () => {+ let logic: ReturnType<typeof sidePanelNotificationsLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:tid/notifications/': () => [+ 200,+ {+ results: [makeNotification({ id: 'child-1' }), makeNotification({ id: 'child-2' })],+ next: null,+ },+ ],+ },+ })+ initKeaTests()+ logic = sidePanelNotificationsLogic()+ logic.mount()+ })++ afterEach(() => logic.unmount())++ it('marks the group full_children_loaded after fetch', async () => {+ const seed = makeNotification({ id: 'child-1' })+ logic.actions.setInAppNotifications([seed], false)+ await expectLogic(logic, () => {+ logic.actions.loadGroupChildren(logic.values.groups[0])+ }).toDispatchActions(['markGroupChildrenLoaded'])+ expect(logic.values.groups[0].full_children_loaded).toBe(true)+ expect(logic.values.groups[0].count).toBe(2)+ })++ it('toggleGroupExpanded flips state', () => {+ const seed = makeNotification({ id: 'a' })+ logic.actions.setInAppNotifications([seed], false)+ const key = logic.values.groups[0].group_key+ expect(logic.values.expandedGroupKeys.has(key)).toBe(false)+ logic.actions.toggleGroupExpanded(key)+ expect(logic.values.expandedGroupKeys.has(key)).toBe(true)+ logic.actions.toggleGroupExpanded(key)+ expect(logic.values.expandedGroupKeys.has(key)).toBe(false)+ })+})++describe('sidePanelNotificationsLogic.toggleGroupRead', () => {+ let logic: ReturnType<typeof sidePanelNotificationsLogic.build>++ beforeEach(() => {+ useMocks({+ post: {+ '/api/environments/:tid/notifications/mark_read_bulk/': () => [200, { updated: 2 }],+ '/api/environments/:tid/notifications/mark_unread_bulk/': () => [200, { updated: 2 }],+ },+ })+ initKeaTests()+ logic = sidePanelNotificationsLogic()+ logic.mount()+ })++ afterEach(() => logic.unmount())++ it('marks all children read when group has unread', async () => {+ const a = makeNotification({ id: 'a', read: false })+ const b = makeNotification({ id: 'b', read: false })+ logic.actions.setInAppNotifications([a, b], false)+ const key = logic.values.groups[0].group_key+ logic.actions.markGroupChildrenLoaded(key)+ await logic.actions.toggleGroupRead(logic.values.groups[0])+ expect(logic.values.groups[0].has_unread).toBe(false)+ })++ it('marks all children unread when group fully read', async () => {+ const a = makeNotification({ id: 'a', read: true })+ const b = makeNotification({ id: 'b', read: true })+ logic.actions.setInAppNotifications([a, b], false)+ const key = logic.values.groups[0].group_key+ logic.actions.markGroupChildrenLoaded(key)+ await logic.actions.toggleGroupRead(logic.values.groups[0])+ expect(logic.values.groups[0].has_unread).toBe(true)+ })+})++describe('sidePanelNotificationsLogic.mainListOffset', () => {+ let logic: ReturnType<typeof sidePanelNotificationsLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = sidePanelNotificationsLogic()+ logic.mount()+ })++ afterEach(() => logic.unmount())++ it('resets to notifications.length on setInAppNotifications', () => {+ const seed = Array.from({ length: 20 }, (_, i) => makeNotification({ id: `n${i}` }))+ logic.actions.setInAppNotifications(seed, true)+ expect(logic.values.mainListOffset).toBe(20)+ })++ it('is not bumped by appendInAppNotifications (group-children path)', () => {+ const seed = Array.from({ length: 20 }, (_, i) => makeNotification({ id: `n${i}` }))+ logic.actions.setInAppNotifications(seed, true)+ const children = [makeNotification({ id: 'child-1' }), makeNotification({ id: 'child-2' })]+ logic.actions.appendInAppNotifications(children, true)+ expect(logic.values.mainListOffset).toBe(20)+ })++ it('bumps by the returned page size on loadMoreNotificationsSuccess', () => {+ const seed = Array.from({ length: 20 }, (_, i) => makeNotification({ id: `n${i}` }))+ logic.actions.setInAppNotifications(seed, true)+ logic.actions.loadMoreNotificationsSuccess(20)+ expect(logic.values.mainListOffset).toBe(40)+ })+})diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsxindex 2f1096ab3634..920fee5c4c25 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx@@ -23,7 +23,18 @@ import { connectToNotificationsSSE } from '~/layout/navigation-3000/sidepanel/paimport { ChangesResponse } from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelActivityLogic'import { InAppNotification, InsightShortId } from '~/types'-import { NotificationEventSourceTypeEnumApi } from 'products/notifications/frontend/generated/api.schemas'+import {+ notificationsList,+ notificationsMarkAllReadCreate,+ notificationsMarkReadBulkCreate,+ notificationsMarkReadCreate,+ notificationsMarkUnreadBulkCreate,+ notificationsMarkUnreadCreate,+} from 'products/notifications/frontend/generated/api'+import {+ NotificationEventSourceTypeEnumApi,+ NotificationsListParams,+} from 'products/notifications/frontend/generated/api.schemas'import { sidePanelContextLogic } from '../../sidePanelContextLogic'import { sidePanelStateLogic } from '../../sidePanelStateLogic'@@ -45,6 +56,24 @@ const SOURCE_TYPE_TO_PATH: Record<NotificationEventSourceTypeEnumApi, (id: strinerror_tracking: (id) => urls.errorTrackingIssue(id),}+export interface NotificationGroup {+ group_key: string+ representative: InAppNotification+ count: number+ first_seen: string+ last_seen: string+ children: InAppNotification[]+ has_unread: boolean+ full_children_loaded: boolean+}++export function groupKey(n: InAppNotification): string {+ const localDay = dayjs(n.created_at).format('YYYY-MM-DD')+ return `${n.notification_type}|${n.target_type}:${n.target_id}|${n.resource_type ?? ''}:${+ n.resource_id ?? ''+ }|${localDay}`+}+export function buildNotificationSourcePath(notification: InAppNotification): string | null {if (notification.source_type && notification.source_id && notification.source_type in SOURCE_TYPE_TO_PATH) {return SOURCE_TYPE_TO_PATH[notification.source_type as NotificationEventSourceTypeEnumApi](@@ -98,6 +127,13 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(toggleRead: (id: string) => ({ id }),navigateToNotification: (notification: InAppNotification) => ({ notification }),loadMoreNotifications: true,+ loadMoreNotificationsSuccess: (count: number) => ({ count }),+ loadGroupChildren: (group: NotificationGroup) => ({ group }),+ markGroupChildrenLoaded: (groupKey: string) => ({ groupKey }),+ setGroupLoading: (groupKey: string, loading: boolean) => ({ groupKey, loading }),+ toggleGroupExpanded: (groupKey: string) => ({ groupKey }),+ toggleGroupRead: (group: NotificationGroup) => ({ group }),+ setGroupChildrenRead: (groupKey: string, read: boolean) => ({ groupKey, read }),initialLoadDone: true,startSSE: true,stopSSE: true,@@ -137,13 +173,21 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(),markAllAsRead: (state) =>state.map((n) => (n.read ? n : { ...n, read: true, read_at: new Date().toISOString() })),+ setGroupChildrenRead: (state, { groupKey: key, read }) =>+ state.map((n) =>+ groupKey(n) === key ? { ...n, read, read_at: read ? new Date().toISOString() : null } : n+ ),},],- loadedFromApiCount: [+ // Tracks how many items the main list has consumed from the server, used as the+ // offset for `loadMoreNotifications`. Kept distinct from `inAppNotifications.length`+ // because expanding a group adds children via `appendInAppNotifications` and those+ // must not advance the main-list cursor (or `loadMoreNotifications` would skip a page).+ mainListOffset: [0,{setInAppNotifications: (_, { notifications }) => notifications.length,- appendInAppNotifications: (state, { notifications }) => state + notifications.length,+ loadMoreNotificationsSuccess: (state, { count }) => state + count,},],hasMoreNotifications: [@@ -170,6 +214,44 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(markAllAsRead: () => 0,},],+ loadedGroupKeys: [+ new Set<string>() as Set<string>,+ {+ markGroupChildrenLoaded: (state, { groupKey: key }) => {+ const next = new Set(state)+ next.add(key)+ return next+ },+ },+ ],+ expandedGroupKeys: [+ new Set<string>() as Set<string>,+ {+ toggleGroupExpanded: (state, { groupKey: key }) => {+ const next = new Set(state)+ if (next.has(key)) {+ next.delete(key)+ } else {+ next.add(key)+ }+ return next+ },+ },+ ],+ loadingGroupKeys: [+ new Set<string>() as Set<string>,+ {+ setGroupLoading: (state, { groupKey: key, loading }) => {+ const next = new Set(state)+ if (loading) {+ next.add(key)+ } else {+ next.delete(key)+ }+ return next+ },+ },+ ],}),lazyLoaders(({ actions, values, cache }) => ({importantChanges: [@@ -202,7 +284,7 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(},markAllAsRead: async () => {if (values.realTimeNotificationsEnabled) {- await api.create(`api/environments/${values.currentProjectId}/notifications/mark_all_read/`, {})+ await notificationsMarkAllReadCreate((values.currentProjectId ?? '').toString())return values.importantChanges}@@ -235,250 +317,320 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(},],})),- listeners(({ actions, values, cache }) => ({- togglePolling: ({ pageIsVisible }) => {- if (values.realTimeNotificationsEnabled) {+ listeners(({ actions, values, cache }) => {+ const fetchGroupChildren = async (group: NotificationGroup): Promise<void> => {+ if (group.full_children_loaded) {return}- if (pageIsVisible) {- actions.loadImportantChanges()- } else {- cache.disposables.dispose('pollTimeout')+ actions.setGroupLoading(group.group_key, true)+ const day = dayjs(group.last_seen).startOf('day')+ const params: NotificationsListParams = {+ notification_type: group.representative.notification_type,+ target_type: group.representative.target_type,+ target_id: group.representative.target_id,+ created_after: day.toISOString(),+ created_before: day.add(1, 'day').toISOString(),+ limit: 100,}- },- startSSE: () => {- // The SSE connection is managed by a disposable named 'sseConnection' so the- // kea-disposables plugin auto-aborts it when the tab is hidden and reopens it- // on visibilitychange. This keeps an idle background tab from holding a- // long-lived streaming Response — that was accumulating in Blink's- // partition_alloc/buffer + blink_gc/<unspecified> on production tabs.- // Reconnect from focus-on-give-up still uses a separate 'sseFocusReconnect'- // disposable so users who stay on a foreground tab past max-attempts retry on- // window refocus.- //- // Lifecycle telemetry now fires on every visibility cycle (the disposable's- // setup/teardown run on resume/pause), so we tag each capture with a `reason`- // so existing dashboards can still distinguish initial connects, team-driven- // reloads, focus-reconnects, and pure visibility transitions.- // `cache.nextStartReason` / `cache.nextStopReason` carry the caller's intent- // into the factory + teardown; the disposable plugin's pause/resume cycle- // doesn't go through this action so the cache values default to- // 'visibility_resume' / 'visibility_pause'.- const startReason = cache.nextStartReason ?? 'initial'- cache.nextStartReason = null- cache.nextStopReason = 'replaced'- cache.disposables.dispose('sseFocusReconnect')- cache.disposables.dispose('sseConnection')- cache.nextStopReason = null- cache.nextStartReason = startReason-- cache.disposables.add(- () => {- const reason = cache.nextStartReason ?? 'visibility_resume'- cache.nextStartReason = null- // TEMPORARY: lifecycle tracking for /notifications SSE connection.- // Remove together with livestream_401_debug once root cause is known.- posthog.capture('livestream_sse_startsse_called', {- reason,- flag_enabled: values.realTimeNotificationsEnabled,- has_token: !!values.currentTeam?.live_events_token,- has_host: !!liveEventsHostOrigin(),- had_prior_connection: !!cache.sseConnection,- })+ if (group.representative.resource_type) {+ params.resource_type = group.representative.resource_type+ }+ if (group.representative.resource_id) {+ params.resource_id = group.representative.resource_id+ }+ try {+ const resp = await notificationsList((values.currentProjectId ?? '').toString(), params)+ actions.appendInAppNotifications(resp.results as InAppNotification[], values.hasMoreNotifications)+ actions.markGroupChildrenLoaded(group.group_key)+ } catch {+ // Swallow+ } finally {+ actions.setGroupLoading(group.group_key, false)+ }+ }- if (!values.realTimeNotificationsEnabled) {- posthog.capture('livestream_sse_startsse_skipped', { reason: 'flag_disabled' })- return () => {}- }+ return {+ togglePolling: ({ pageIsVisible }) => {+ if (values.realTimeNotificationsEnabled) {+ return+ }+ if (pageIsVisible) {+ actions.loadImportantChanges()+ } else {+ cache.disposables.dispose('pollTimeout')+ }+ },+ startSSE: () => {+ // The SSE connection is managed by a disposable named 'sseConnection' so the+ // kea-disposables plugin auto-aborts it when the tab is hidden and reopens it+ // on visibilitychange. This keeps an idle background tab from holding a+ // long-lived streaming Response — that was accumulating in Blink's+ // partition_alloc/buffer + blink_gc/<unspecified> on production tabs.+ // Reconnect from focus-on-give-up still uses a separate 'sseFocusReconnect'+ // disposable so users who stay on a foreground tab past max-attempts retry on+ // window refocus.+ //+ // Lifecycle telemetry now fires on every visibility cycle (the disposable's+ // setup/teardown run on resume/pause), so we tag each capture with a `reason`+ // so existing dashboards can still distinguish initial connects, team-driven+ // reloads, focus-reconnects, and pure visibility transitions.+ // `cache.nextStartReason` / `cache.nextStopReason` carry the caller's intent+ // into the factory + teardown; the disposable plugin's pause/resume cycle+ // doesn't go through this action so the cache values default to+ // 'visibility_resume' / 'visibility_pause'.+ const startReason = cache.nextStartReason ?? 'initial'+ cache.nextStartReason = null+ cache.nextStopReason = 'replaced'+ cache.disposables.dispose('sseFocusReconnect')+ cache.disposables.dispose('sseConnection')+ cache.nextStopReason = null+ cache.nextStartReason = startReason++ cache.disposables.add(+ () => {+ const reason = cache.nextStartReason ?? 'visibility_resume'+ cache.nextStartReason = null+ // TEMPORARY: lifecycle tracking for /notifications SSE connection.+ // Remove together with livestream_401_debug once root cause is known.+ posthog.capture('livestream_sse_startsse_called', {+ reason,+ flag_enabled: values.realTimeNotificationsEnabled,+ has_token: !!values.currentTeam?.live_events_token,+ has_host: !!liveEventsHostOrigin(),+ had_prior_connection: !!cache.sseConnection,+ })- const token = values.currentTeam?.live_events_token- if (!token) {- posthog.capture('livestream_sse_startsse_skipped', { reason: 'no_token' })- return () => {}- }+ if (!values.realTimeNotificationsEnabled) {+ posthog.capture('livestream_sse_startsse_skipped', { reason: 'flag_disabled' })+ return () => {}+ }- const host = liveEventsHostOrigin()- if (!host) {- posthog.capture('livestream_sse_startsse_skipped', { reason: 'no_host' })- return () => {}- }+ const token = values.currentTeam?.live_events_token+ if (!token) {+ posthog.capture('livestream_sse_startsse_skipped', { reason: 'no_token' })+ return () => {}+ }- const url = `${host}/notifications`+ const host = liveEventsHostOrigin()+ if (!host) {+ posthog.capture('livestream_sse_startsse_skipped', { reason: 'no_host' })+ return () => {}+ }- const abortController = new AbortController()- cache.sseConnection = abortController- cache.firstMessageLogged = false+ const url = `${host}/notifications`- posthog.capture('livestream_sse_connecting', { url, reason })+ const abortController = new AbortController()+ cache.sseConnection = abortController+ cache.firstMessageLogged = false- void retryWithBackoff(- () =>- connectToNotificationsSSE(- url,- token,- abortController.signal,- (notification) => {- if (!values.isInitialLoadComplete) {- return+ posthog.capture('livestream_sse_connecting', { url, reason })++ void retryWithBackoff(+ () =>+ connectToNotificationsSSE(+ url,+ token,+ abortController.signal,+ (notification) => {+ if (!values.isInitialLoadComplete) {+ return+ }+ actions.notificationReceived(notification)+ if (notification.priority === 'critical') {+ showCriticalNotificationToast(notification)+ }+ },+ {+ // TEMPORARY: livestream SSE lifecycle tracking.+ onFirstMessage: () => {+ if (!cache.firstMessageLogged) {+ cache.firstMessageLogged = true+ posthog.capture('livestream_sse_first_message', { url })+ }+ },+ onError: (error) => {+ posthog.capture('livestream_sse_error', {+ url,+ error_name: (error as Error | undefined)?.name,+ error_message: (error as Error | undefined)?.message,+ })+ },}- actions.notificationReceived(notification)- if (notification.priority === 'critical') {- showCriticalNotificationToast(notification)+ ),+ {+ maxAttempts: SSE_RETRY_ATTEMPTS,+ initialDelayMs: SSE_RETRY_INITIAL_DELAY_MS,+ backoffMultiplier: SSE_RETRY_BACKOFF_MULTIPLIER,+ signal: abortController.signal,+ }+ ).catch((error) => {+ // retryWithBackoff rejects with AbortError on clean shutdown+ // (including when the disposable is paused for visibilitychange);+ // only re-arm when it actually gave up.+ if (error instanceof DOMException && error.name === 'AbortError') {+ return+ }+ // TEMPORARY: livestream SSE lifecycle tracking.+ posthog.capture('livestream_sse_max_errors', {+ url,+ max_attempts: SSE_RETRY_ATTEMPTS,+ })+ // Re-arm SSE the next time the user focuses the window. pauseOnPageHidden must be false+ // so the listener stays attached while the tab is backgrounded — that's exactly when we want it.+ cache.disposables.add(+ () => {+ const onFocus = (): void => {+ posthog.capture('livestream_sse_refocus_reconnect', { url })+ cache.nextStartReason = 'focus_reconnect'+ actions.startSSE()}+ window.addEventListener('focus', onFocus, { once: true })+ return () => window.removeEventListener('focus', onFocus)},- {- // TEMPORARY: livestream SSE lifecycle tracking.- onFirstMessage: () => {- if (!cache.firstMessageLogged) {- cache.firstMessageLogged = true- posthog.capture('livestream_sse_first_message', { url })- }- },- onError: (error) => {- posthog.capture('livestream_sse_error', {- url,- error_name: (error as Error | undefined)?.name,- error_message: (error as Error | undefined)?.message,- })- },- }- ),- {- maxAttempts: SSE_RETRY_ATTEMPTS,- initialDelayMs: SSE_RETRY_INITIAL_DELAY_MS,- backoffMultiplier: SSE_RETRY_BACKOFF_MULTIPLIER,- signal: abortController.signal,- }- ).catch((error) => {- // retryWithBackoff rejects with AbortError on clean shutdown- // (including when the disposable is paused for visibilitychange);- // only re-arm when it actually gave up.- if (error instanceof DOMException && error.name === 'AbortError') {- return- }- // TEMPORARY: livestream SSE lifecycle tracking.- posthog.capture('livestream_sse_max_errors', {- url,- max_attempts: SSE_RETRY_ATTEMPTS,+ 'sseFocusReconnect',+ { pauseOnPageHidden: false }+ )})- // Re-arm SSE the next time the user focuses the window. pauseOnPageHidden must be false- // so the listener stays attached while the tab is backgrounded — that's exactly when we want it.- cache.disposables.add(- () => {- const onFocus = (): void => {- posthog.capture('livestream_sse_refocus_reconnect', { url })- cache.nextStartReason = 'focus_reconnect'- actions.startSSE()- }- window.addEventListener('focus', onFocus, { once: true })- return () => window.removeEventListener('focus', onFocus)- },- 'sseFocusReconnect',- { pauseOnPageHidden: false }- )- })- return () => {- // TEMPORARY: livestream SSE lifecycle tracking. `reason` tags- // whether this teardown was an explicit stop, a replacement by- // a later startSSE call, or the disposable pausing for a- // hidden tab so dashboards can still distinguish them.- const stopReason = cache.nextStopReason ?? 'visibility_pause'- cache.nextStopReason = null- posthog.capture('livestream_sse_stopped', {- reason: stopReason,- had_connection: !!cache.sseConnection,- })- abortController.abort()- if (cache.sseConnection === abortController) {- cache.sseConnection = null+ return () => {+ // TEMPORARY: livestream SSE lifecycle tracking. `reason` tags+ // whether this teardown was an explicit stop, a replacement by+ // a later startSSE call, or the disposable pausing for a+ // hidden tab so dashboards can still distinguish them.+ const stopReason = cache.nextStopReason ?? 'visibility_pause'+ cache.nextStopReason = null+ posthog.capture('livestream_sse_stopped', {+ reason: stopReason,+ had_connection: !!cache.sseConnection,+ })+ abortController.abort()+ if (cache.sseConnection === abortController) {+ cache.sseConnection = null+ }}+ },+ 'sseConnection',+ { pauseOnPageHidden: true }+ )+ },+ stopSSE: () => {+ cache.nextStopReason = 'explicit_stop'+ cache.disposables.dispose('sseFocusReconnect')+ cache.disposables.dispose('sseConnection')+ cache.nextStopReason = null+ },+ navigateToNotification: ({ notification }) => {+ const path = values.sourcePathForNotification(notification)+ if (!path) {+ return+ }+ const isOtherProject = notification.team_id !== null && notification.team_id !== values.currentTeamId+ if (!isOtherProject) {+ if (!notification.read) {+ actions.markAsRead(notification.id)}- },- 'sseConnection',- { pauseOnPageHidden: true }- )- },- stopSSE: () => {- cache.nextStopReason = 'explicit_stop'- cache.disposables.dispose('sseFocusReconnect')- cache.disposables.dispose('sseConnection')- cache.nextStopReason = null- },- navigateToNotification: ({ notification }) => {- const path = values.sourcePathForNotification(notification)- if (!path) {- return- }- const isOtherProject = notification.team_id !== null && notification.team_id !== values.currentTeamId- if (!isOtherProject) {- if (!notification.read) {- actions.markAsRead(notification.id)+ router.actions.push(path)+ return}- router.actions.push(path)- return- }- const targetProjectName = values.projectNameForNotification(notification)- LemonDialog.open({- title: 'Leave current project?',- description: `This notification is in ${targetProjectName ? `"${targetProjectName}"` : 'another project'}. Opening it will reload the page and you'll lose any unsaved work.`,- primaryButton: {- children: 'Open',-- onClick: async () => {- if (!notification.read) {- await actions.markAsRead(notification.id)- }- window.location.href = urls.project(notification.team_id!, path)+ const targetProjectName = values.projectNameForNotification(notification)+ LemonDialog.open({+ title: 'Leave current project?',+ description: `This notification is in ${targetProjectName ? `"${targetProjectName}"` : 'another project'}. Opening it will reload the page and you'll lose any unsaved work.`,+ primaryButton: {+ children: 'Open',++ onClick: async () => {+ if (!notification.read) {+ await actions.markAsRead(notification.id)+ }+ window.location.href = urls.project(notification.team_id!, path)+ },},- },- secondaryButton: {- children: 'Stay here',- },- })- },- markAsRead: async ({ id }) => {- try {- await api.create(`api/environments/${values.currentProjectId}/notifications/${id}/mark_read/`, {})- } catch {- // Swallow- }- },- toggleRead: async ({ id }) => {- const notification = values.inAppNotifications.find((n) => n.id === id)- if (!notification) {- return- }- const endpoint = notification.read ? 'mark_read' : 'mark_unread'- try {- await api.create(`api/environments/${values.currentProjectId}/notifications/${id}/${endpoint}/`, {})- } catch {- // Swallow- }- },- loadCurrentTeamSuccess: () => {- if (values.realTimeNotificationsEnabled && !cache.sseConnection) {- cache.nextStartReason = 'team_reload'- actions.startSSE()- }- },- loadMoreNotifications: async () => {- if (!values.hasMoreNotifications) {- return- }- try {- const resp = await api.get<{- results: InAppNotification[]- next: string | null- }>(- `api/environments/${values.currentProjectId}/notifications/?limit=20&offset=${values.loadedFromApiCount}`- )- actions.appendInAppNotifications(resp.results, !!resp.next)- } catch {- // Swallow- }- },- })),+ secondaryButton: {+ children: 'Stay here',+ },+ })+ },+ markAsRead: async ({ id }) => {+ try {+ await notificationsMarkReadCreate((values.currentProjectId ?? '').toString(), id)+ } catch {+ // Swallow+ }+ },+ toggleRead: async ({ id }) => {+ // `notification.read` here is the *target* state — the toggleRead reducer above+ // has already flipped it, so we call the endpoint matching the new state.+ const notification = values.inAppNotifications.find((n) => n.id === id)+ if (!notification) {+ return+ }+ const projectId = (values.currentProjectId ?? '').toString()+ try {+ if (notification.read) {+ await notificationsMarkReadCreate(projectId, id)+ } else {+ await notificationsMarkUnreadCreate(projectId, id)+ }+ } catch {+ // Swallow+ }+ },+ loadCurrentTeamSuccess: () => {+ if (values.realTimeNotificationsEnabled && !cache.sseConnection) {+ cache.nextStartReason = 'team_reload'+ actions.startSSE()+ }+ },+ loadMoreNotifications: async () => {+ if (!values.hasMoreNotifications) {+ return+ }+ try {+ const resp = await notificationsList((values.currentProjectId ?? '').toString(), {+ limit: 20,+ offset: values.mainListOffset,+ })+ const results = resp.results as InAppNotification[]+ actions.appendInAppNotifications(results, !!resp.next)+ actions.loadMoreNotificationsSuccess(results.length)+ } catch {+ // Swallow+ }+ },+ loadGroupChildren: async ({ group }) => {+ await fetchGroupChildren(group)+ },+ toggleGroupRead: async ({ group }) => {+ if (!group.full_children_loaded) {+ await fetchGroupChildren(group)+ }+ const refreshed = values.groups.find((g) => g.group_key === group.group_key)+ if (!refreshed) {+ return+ }+ const ids = refreshed.children.map((c) => c.id)+ const targetRead = refreshed.has_unread+ const unreadDelta = targetRead+ ? -refreshed.children.filter((c) => !c.read).length+ : refreshed.children.filter((c) => c.read).length+ actions.setGroupChildrenRead(refreshed.group_key, targetRead)+ if (unreadDelta !== 0) {+ actions.setInAppUnreadCount(Math.max(0, values.inAppUnreadCount + unreadDelta))+ }+ const projectId = (values.currentProjectId ?? '').toString()+ try {+ if (targetRead) {+ await notificationsMarkReadBulkCreate(projectId, { notification_ids: ids })+ } else {+ await notificationsMarkUnreadBulkCreate(projectId, { notification_ids: ids })+ }+ } catch {+ // Swallow; selector reflects optimistic state+ }+ },+ }+ }),selectors({realTimeNotificationsEnabled: [(s) => [s.featureFlags],@@ -576,16 +728,51 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>((notification: InAppNotification): string | null =>buildNotificationSourcePath(notification),],+ groups: [+ (s) => [s.inAppNotifications, s.loadedGroupKeys],+ (notifications: InAppNotification[], loadedGroupKeys: Set<string>): NotificationGroup[] => {+ const groups: NotificationGroup[] = []+ const byKey = new Map<string, NotificationGroup>()+ for (const n of notifications) {+ const key = groupKey(n)+ const existing = byKey.get(key)+ if (existing) {+ existing.children.push(n)+ existing.count = existing.children.length+ if (dayjs(n.created_at).isBefore(existing.first_seen)) {+ existing.first_seen = n.created_at+ }+ if (dayjs(n.created_at).isAfter(existing.last_seen)) {+ existing.last_seen = n.created_at+ }+ if (!n.read) {+ existing.has_unread = true+ }+ continue+ }+ const group: NotificationGroup = {+ group_key: key,+ representative: n,+ count: 1,+ first_seen: n.created_at,+ last_seen: n.created_at,+ children: [n],+ has_unread: !n.read,+ full_children_loaded: loadedGroupKeys.has(key),+ }+ byKey.set(key, group)+ groups.push(group)+ }+ return groups+ },+ ],}),afterMount(({ cache, actions, values }) => {if (values.realTimeNotificationsEnabled) {void (async () => {try {- const resp = await api.get<{- results: InAppNotification[]- next: string | null- }>(`api/environments/${values.currentProjectId}/notifications/?limit=20`)- actions.setInAppNotifications(resp.results, !!resp.next)+ const resp = await notificationsList((values.currentProjectId ?? '').toString(), { limit: 20 })+ actions.setInAppNotifications(resp.results as InAppNotification[], !!resp.next)} catch {// Swallow}diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationGroupRow.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationGroupRow.tsxnew file mode 100644index 000000000000..8affa0d8b182--- /dev/null+++ b/frontend/src/lib/components/NotificationsMenu/NotificationGroupRow.tsx@@ -0,0 +1,106 @@+import { useActions, useValues } from 'kea'++import { IconCheckCircle, IconChevronRight } from '@posthog/icons'+import { Tooltip } from '@posthog/lemon-ui'++import { NotificationRow } from 'lib/components/NotificationsMenu/NotificationRow'+import { getNotificationIcon } from 'lib/components/NotificationsMenu/notificationToasts'+import { dayjs } from 'lib/dayjs'+import { IconRadioButtonUnchecked } from 'lib/lemon-ui/icons'++import {+ NotificationGroup,+ sidePanelNotificationsLogic,+} from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic'++export function NotificationGroupRow({+ group,+ onNavigate,+}: {+ group: NotificationGroup+ onNavigate?: () => void+}): JSX.Element {+ const { expandedGroupKeys, loadingGroupKeys } = useValues(sidePanelNotificationsLogic)+ const { toggleGroupExpanded, loadGroupChildren, toggleGroupRead } = useActions(sidePanelNotificationsLogic)+ const isExpanded = expandedGroupKeys.has(group.group_key)+ const isLoading = loadingGroupKeys.has(group.group_key)++ if (group.count === 1) {+ return <NotificationRow notification={group.representative} onNavigate={onNavigate} />+ }++ const handleExpand = (e: React.MouseEvent): void => {+ e.stopPropagation()+ if (!group.full_children_loaded && !isExpanded) {+ void loadGroupChildren(group)+ }+ toggleGroupExpanded(group.group_key)+ }++ const handleToggleRead = (e: React.MouseEvent): void => {+ e.stopPropagation()+ toggleGroupRead(group)+ }++ const allRead = !group.has_unread++ return (+ <div className="flex flex-col">+ <div+ className={`flex items-start gap-2.5 p-2 rounded cursor-pointer transition-colors ${+ allRead ? 'hover:bg-fill-highlight-100' : 'bg-fill-highlight-50 hover:bg-fill-highlight-100'+ }`}+ onClick={handleExpand}+ >+ <div className="shrink-0 mt-0.5">{getNotificationIcon(group.representative.notification_type)}</div>+ <div className="flex-1 min-w-0">+ <div className="flex items-start justify-between gap-1">+ <span className={`text-xs leading-snug ${allRead ? 'text-secondary' : 'font-semibold'}`}>+ {group.representative.title}+ </span>+ <div className="flex items-center gap-1 shrink-0">+ <span className="text-[10px] text-muted bg-fill-highlight-100 px-1.5 py-px rounded">+ {group.count}+ </span>+ <Tooltip title={allRead ? 'Mark group as unread' : 'Mark group as read'}>+ <button+ className="group/read min-w-[26px] min-h-[26px] flex items-center justify-center rounded hover:bg-fill-highlight-200 cursor-pointer"+ onClick={handleToggleRead}+ >+ {allRead ? (+ <IconCheckCircle className="size-4 text-success" />+ ) : (+ <>+ <IconRadioButtonUnchecked className="size-4 text-muted opacity-40 group-hover/read:hidden" />+ <IconCheckCircle className="size-4 text-muted opacity-60 hidden group-hover/read:block" />+ </>+ )}+ </button>+ </Tooltip>+ <button+ className="min-w-[26px] min-h-[26px] flex items-center justify-center rounded hover:bg-fill-highlight-200 text-secondary hover:text-primary"+ onClick={handleExpand}+ aria-label={isExpanded ? 'Collapse group' : 'Expand group'}+ >+ <IconChevronRight+ className={`size-4 transition-transform ${isExpanded ? 'rotate-90' : ''}`}+ />+ </button>+ </div>+ </div>+ <div className="text-xs text-secondary mt-0.5 line-clamp-1">+ {group.count} notifications · latest {dayjs(group.last_seen).fromNow()}+ </div>+ </div>+ </div>+ {isExpanded && (+ <div className="pl-6 pr-1 flex flex-col gap-px border-l-2 border-fill-highlight-100 ml-3 my-1">+ {isLoading && !group.full_children_loaded && <div className="text-xs text-muted p-2">Loading…</div>}+ {group.children.map((child) => (+ <NotificationRow key={child.id} notification={child} onNavigate={onNavigate} />+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationsPanel.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationsPanel.tsxindex 07c1f5396909..18d97b339d41 100644--- a/frontend/src/lib/components/NotificationsMenu/NotificationsPanel.tsx+++ b/frontend/src/lib/components/NotificationsMenu/NotificationsPanel.tsx@@ -5,24 +5,25 @@ import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'-import { sidePanelNotificationsLogic } from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic'+import {+ NotificationGroup,+ sidePanelNotificationsLogic,+} from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic'import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'import { PanelLayoutPanel } from '~/layout/panel-layout/PanelLayoutPanel'-import { InAppNotification } from '~/types'-import { NotificationRow } from './NotificationRow'+import { NotificationGroupRow } from './NotificationGroupRow'import { notificationsMenuLogic } from './notificationsMenuLogic'export function NotificationsPanel(): JSX.Element {const { activeTab } = useValues(notificationsMenuLogic)const { setActiveTab } = useActions(notificationsMenuLogic)- const { inAppNotifications, inAppUnreadCount, importantChangesLoading, hasMoreNotifications, isLoadingMore } =+ const { groups, inAppUnreadCount, importantChangesLoading, hasMoreNotifications, isLoadingMore } =useValues(sidePanelNotificationsLogic)const { markAllAsRead, loadMoreNotifications } = useActions(sidePanelNotificationsLogic)const { closePanel } = useActions(panelLayoutLogic)- const filteredNotifications =- activeTab === 'unread' ? inAppNotifications.filter((n: InAppNotification) => !n.read) : inAppNotifications+ const filteredGroups = activeTab === 'unread' ? groups.filter((g: NotificationGroup) => g.has_unread) : groupsconst header = (<div className="flex items-center gap-2 flex-1 min-w-0">@@ -66,17 +67,17 @@ export function NotificationsPanel(): JSX.Element {className="flex-1 overflow-hidden"innerClassName="p-1">- {importantChangesLoading && inAppNotifications.length === 0 ? (+ {importantChangesLoading && groups.length === 0 ? (<div className="p-2"><LemonSkeleton className="h-10 my-1" repeat={5} fade /></div>- ) : filteredNotifications.length > 0 ? (+ ) : filteredGroups.length > 0 ? (<><div className="flex flex-col gap-px">- {filteredNotifications.map((notification: InAppNotification) => (- <NotificationRow- key={notification.id}- notification={notification}+ {filteredGroups.map((group: NotificationGroup) => (+ <NotificationGroupRow+ key={group.group_key}+ group={group}onNavigate={() => closePanel()}/>))}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex bc1a9152f0ae..190236a89191 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -428,6 +428,9 @@ export interface InAppNotification {read: booleanread_at: string | nullresource_type: string | null+ resource_id: string+ target_type: string+ target_id: stringsource_url: stringsource_type: string | nullsource_id: string | nulldiff --git a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambrindex c25967db6894..aed233c5a547 100644--- a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr+++ b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr@@ -1360,6 +1360,44 @@LIMIT 21'''# ---+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.39+ '''+ SELECT "posthog_organization"."id",+ "posthog_organization"."name",+ "posthog_organization"."slug",+ "posthog_organization"."logo_media_id",+ "posthog_organization"."created_at",+ "posthog_organization"."updated_at",+ "posthog_organization"."is_active",+ "posthog_organization"."is_not_active_reason",+ "posthog_organization"."session_cookie_age",+ "posthog_organization"."is_member_join_email_enabled",+ "posthog_organization"."is_ai_data_processing_approved",+ "posthog_organization"."enforce_2fa",+ "posthog_organization"."members_can_invite",+ "posthog_organization"."members_can_use_personal_api_keys",+ "posthog_organization"."allow_publicly_shared_resources",+ "posthog_organization"."default_role_id",+ "posthog_organization"."plugins_access_level",+ "posthog_organization"."for_internal_metrics",+ "posthog_organization"."default_experiment_stats_method",+ "posthog_organization"."default_anonymize_ips",+ "posthog_organization"."is_hipaa",+ "posthog_organization"."is_pending_deletion",+ "posthog_organization"."customer_id",+ "posthog_organization"."available_product_features",+ "posthog_organization"."usage",+ "posthog_organization"."never_drop_data",+ "posthog_organization"."customer_trust_scores",+ "posthog_organization"."setup_section_2_completed",+ "posthog_organization"."personalization",+ "posthog_organization"."domain_whitelist",+ "posthog_organization"."is_platform"+ FROM "posthog_organization"+ WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid+ LIMIT 21+ '''+# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.4'''SELECT "posthog_organization"."id",diff --git a/products/notifications/backend/presentation/serializers.py b/products/notifications/backend/presentation/serializers.pyindex 53b3144ad075..f5c16107108d 100644--- a/products/notifications/backend/presentation/serializers.py+++ b/products/notifications/backend/presentation/serializers.py@@ -12,6 +12,8 @@ class NotificationEventSerializer(serializers.Serializer):body = serializers.CharField()read = serializers.BooleanField()read_at = serializers.DateTimeField(allow_null=True)+ target_type = serializers.CharField()+ target_id = serializers.CharField()resource_type = serializers.CharField(allow_null=True)resource_id = serializers.CharField()source_url = serializers.CharField()diff --git a/products/notifications/backend/presentation/views.py b/products/notifications/backend/presentation/views.pyindex 1e32d988d190..cbf1e69d8976 100644--- a/products/notifications/backend/presentation/views.py+++ b/products/notifications/backend/presentation/views.py@@ -1,14 +1,19 @@+from datetime import datetimefrom typing import castfrom django.db.models import Exists, OuterRef, QuerySet, Subquery+from django.utils.dateparse import parse_datetimeimport posthoganalytics-from drf_spectacular.utils import extend_schema+from drf_spectacular.utils import OpenApiParameter, extend_schema+from rest_framework import serializers as drf_serializers+from rest_framework.exceptions import ValidationErrorfrom rest_framework.pagination import LimitOffsetPaginationfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.viewsets import GenericViewSet+from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import actionfrom posthog.models import User@@ -19,6 +24,19 @@ from products.notifications.backend.facade.enums import AC_RESOURCE_TYPESfrom products.notifications.backend.models import NotificationEvent, NotificationReadStatefrom products.notifications.backend.presentation.serializers import NotificationEventSerializer+_BULK_NOTIFICATION_IDS_MAX = 500+++class BulkNotificationIdsRequestSerializer(drf_serializers.Serializer):+ notification_ids = drf_serializers.ListField(+ child=drf_serializers.UUIDField(),+ max_length=_BULK_NOTIFICATION_IDS_MAX,+ help_text=(+ f"UUIDs of notification events to mark in bulk (max {_BULK_NOTIFICATION_IDS_MAX}). "+ "Events the user is not a recipient of are silently skipped."+ ),+ )+class NotificationPagination(LimitOffsetPagination):default_limit = 20@@ -101,11 +119,93 @@ class NotificationsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):return queryset+ def _apply_filters(self, queryset: QuerySet, request: Request) -> QuerySet:+ # Explicit per-field filters (no dict-unpack) so semgrep's no-request-param-orm-filter+ # taint analysis is satisfied — every field name is hard-coded at the call site.+ params = request.query_params+ if value := params.get("notification_type"):+ queryset = queryset.filter(notification_type=value)+ if value := params.get("target_type"):+ queryset = queryset.filter(target_type=value)+ if value := params.get("target_id"):+ queryset = queryset.filter(target_id=value)+ if value := params.get("resource_type"):+ queryset = queryset.filter(resource_type=value)+ if value := params.get("resource_id"):+ queryset = queryset.filter(resource_id=value)++ def _parse_iso(raw: str, field: str) -> datetime:+ # Django decodes "+" timezone offsets in query strings as " "; restore before parsing.+ parsed = parse_datetime(raw.replace(" ", "+"))+ if parsed is None:+ raise ValidationError({field: f"Invalid ISO 8601 timestamp: {raw}"})+ return parsed++ if raw := params.get("created_after"):+ queryset = queryset.filter(created_at__gte=_parse_iso(raw, "created_after"))+ if raw := params.get("created_before"):+ queryset = queryset.filter(created_at__lt=_parse_iso(raw, "created_before"))+ return queryset++ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="notification_type",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Filter by notification type",+ ),+ OpenApiParameter(+ name="target_type",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Filter by recipient target type (e.g. `user`, `team`)",+ ),+ OpenApiParameter(+ name="target_id",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Filter by recipient target ID (e.g. a user ID)",+ ),+ OpenApiParameter(+ name="resource_type",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Filter by the type of the resource the notification refers to (e.g. `insight`, `dashboard`)",+ ),+ OpenApiParameter(+ name="resource_id",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Filter by the ID of the resource the notification refers to",+ ),+ OpenApiParameter(+ name="created_after",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description="ISO 8601 timestamp; only events at or after this time",+ ),+ OpenApiParameter(+ name="created_before",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description="ISO 8601 timestamp; only events strictly before this time",+ ),+ ]+ )def list(self, request: Request, *args, **kwargs) -> Response:if not self._is_feature_enabled():return Response({"results": [], "next": None, "previous": None, "count": 0})queryset = self._get_base_queryset()+ queryset = self._apply_filters(queryset, request)queryset = self._filter_by_access_control(queryset)page = self.paginate_queryset(queryset)if page is not None:@@ -169,3 +269,61 @@ class NotificationsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):NotificationReadState.objects.filter(notification_event=event, user=user).delete()invalidate_unread_count(user.id, self.team.organization_id)return Response({"status": "ok"})++ @validated_request(request_serializer=BulkNotificationIdsRequestSerializer)+ @action(methods=["POST"], detail=False, url_path="mark_read_bulk")+ def mark_read_bulk(self, request: ValidatedRequest, **kwargs) -> Response:+ if not self._is_feature_enabled():+ return Response({"updated": 0})++ user = self._get_user()+ ids = request.validated_data["notification_ids"]+ if not ids:+ return Response({"updated": 0})++ # NotificationEvent is org-scoped + user-targeted (notifications can span teams within an org),+ # not team-scoped. The (organization_id, resolved_user_ids__contains=[user.id]) pair already+ # ensures the caller can only touch notifications they were a recipient of — adding team_id+ # would silently drop notifications addressed to this user but with a different team_id.+ eligible_ids = list(+ NotificationEvent.objects.filter( # nosemgrep: idor-lookup-without-team+ id__in=ids, # nosemgrep: idor-taint-user-input-to-model-get+ organization_id=self.team.organization_id,+ resolved_user_ids__contains=[user.id],+ ).values_list("id", flat=True)+ )+ if eligible_ids:+ read_states = [NotificationReadState(notification_event_id=eid, user=user) for eid in eligible_ids]+ NotificationReadState.objects.bulk_create(read_states, ignore_conflicts=True)+ invalidate_unread_count(user.id, self.team.organization_id)+ return Response({"updated": len(eligible_ids)})++ @validated_request(request_serializer=BulkNotificationIdsRequestSerializer)+ @action(methods=["POST"], detail=False, url_path="mark_unread_bulk")+ def mark_unread_bulk(self, request: ValidatedRequest, **kwargs) -> Response:+ if not self._is_feature_enabled():+ return Response({"updated": 0})++ user = self._get_user()+ ids = request.validated_data["notification_ids"]+ if not ids:+ return Response({"updated": 0})++ # NotificationEvent is org-scoped + user-targeted (notifications can span teams within an org),+ # not team-scoped. The (organization_id, resolved_user_ids__contains=[user.id]) pair already+ # ensures the caller can only touch notifications they were a recipient of — adding team_id+ # would silently drop notifications addressed to this user but with a different team_id.+ eligible_ids = list(+ NotificationEvent.objects.filter( # nosemgrep: idor-lookup-without-team+ id__in=ids, # nosemgrep: idor-taint-user-input-to-model-get+ organization_id=self.team.organization_id,+ resolved_user_ids__contains=[user.id],+ ).values_list("id", flat=True)+ )+ if eligible_ids:+ NotificationReadState.objects.filter(+ notification_event_id__in=eligible_ids,+ user=user,+ ).delete()+ invalidate_unread_count(user.id, self.team.organization_id)+ return Response({"updated": len(eligible_ids)})diff --git a/products/notifications/backend/tests/test_api.py b/products/notifications/backend/tests/test_api.pyindex e81071d4ebc2..0bf86064a4d5 100644--- a/products/notifications/backend/tests/test_api.py+++ b/products/notifications/backend/tests/test_api.py@@ -1,7 +1,11 @@+import uuid+from datetime import timedelta+from posthog.test.base import BaseTestfrom unittest.mock import patchfrom django.core.cache import cache+from django.utils import timezonefrom rest_framework.test import APIClient@@ -134,6 +138,242 @@ class TestNotificationsAPI(BaseTest):resp = self.client.get(f"/api/environments/{self.team.id}/notifications/")assert len(resp.json()["results"]) == 1+ def test_list_filter_by_notification_type(self):+ NotificationEvent.objects.create(+ organization=self.organization,+ team=self.team,+ notification_type="alert_firing",+ title="Alert",+ body="",+ target_type="user",+ target_id=str(self.user.id),+ resolved_user_ids=[self.user.id],+ )+ resp = self.client.get(f"/api/environments/{self.team.id}/notifications/?notification_type=alert_firing")+ assert resp.status_code == 200+ results = resp.json()["results"]+ assert len(results) == 1+ assert results[0]["notification_type"] == "alert_firing"++ def test_list_filter_by_target(self):+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")+ NotificationEvent.objects.create(+ organization=self.organization,+ team=self.team,+ notification_type="alert_firing",+ title="Other",+ body="",+ target_type="user",+ target_id=str(other_user.id),+ resolved_user_ids=[self.user.id],+ )+ resp = self.client.get(+ f"/api/environments/{self.team.id}/notifications/?target_type=user&target_id={self.user.id}"+ )+ assert resp.status_code == 200+ results = resp.json()["results"]+ assert len(results) == 1+ assert results[0]["target_id"] == str(self.user.id)++ def test_list_filter_by_resource(self):+ NotificationEvent.objects.create(+ organization=self.organization,+ team=self.team,+ notification_type="alert_firing",+ title="With resource",+ body="",+ target_type="user",+ target_id=str(self.user.id),+ resolved_user_ids=[self.user.id],+ resource_type="insight",+ resource_id="abc123",+ )+ resp = self.client.get(+ f"/api/environments/{self.team.id}/notifications/?resource_type=insight&resource_id=abc123"+ )+ assert resp.status_code == 200+ results = resp.json()["results"]+ assert len(results) == 1+ assert results[0]["resource_id"] == "abc123"++ def test_list_filter_invalid_datetime_returns_400(self):+ resp = self.client.get(f"/api/environments/{self.team.id}/notifications/?created_after=not-a-date")+ assert resp.status_code == 400++ def test_list_filter_combines_with_and(self):+ # event with type=alert_firing but different resource — should not match+ NotificationEvent.objects.create(+ organization=self.organization,+ team=self.team,+ notification_type="alert_firing",+ title="Other resource",+ body="",+ target_type="user",+ target_id=str(self.user.id),+ resolved_user_ids=[self.user.id],+ resource_type="insight",+ resource_id="other",+ )+ # event matching both filters+ match = NotificationEvent.objects.create(+ organization=self.organization,+ team=self.team,+ notification_type="alert_firing",+ title="Match",+ body="",+ target_type="user",+ target_id=str(self.user.id),+ resolved_user_ids=[self.user.id],+ resource_type="insight",+ resource_id="abc",+ )+ resp = self.client.get(+ f"/api/environments/{self.team.id}/notifications/"+ f"?notification_type=alert_firing&resource_type=insight&resource_id=abc"+ )+ assert resp.status_code == 200+ ids = [r["id"] for r in resp.json()["results"]]+ assert ids == [str(match.id)]++ def test_list_filter_by_created_window(self):+ old = NotificationEvent.objects.create(+ organization=self.organization,+ team=self.team,+ notification_type="alert_firing",+ title="Old",+ body="",+ target_type="user",+ target_id=str(self.user.id),+ resolved_user_ids=[self.user.id],+ )+ NotificationEvent.objects.filter(pk=old.pk).update(created_at=timezone.now() - timedelta(days=2))++ cutoff = (timezone.now() - timedelta(days=1)).isoformat()+ resp = self.client.get(f"/api/environments/{self.team.id}/notifications/?created_after={cutoff}")+ assert resp.status_code == 200+ ids = {r["id"] for r in resp.json()["results"]}+ assert str(old.id) not in ids+ assert str(self.event.id) in ids++ def test_mark_read_bulk(self):+ e2 = NotificationEvent.objects.create(+ organization=self.organization,+ team=self.team,+ notification_type="alert_firing",+ title="Two",+ body="",+ target_type="user",+ target_id=str(self.user.id),+ resolved_user_ids=[self.user.id],+ )+ e3 = NotificationEvent.objects.create(+ organization=self.organization,+ team=self.team,+ notification_type="alert_firing",+ title="Three",+ body="",+ target_type="user",+ target_id=str(self.user.id),+ resolved_user_ids=[self.user.id],+ )+ resp = self.client.post(+ f"/api/environments/{self.team.id}/notifications/mark_read_bulk/",+ {"notification_ids": [str(self.event.id), str(e2.id), str(e3.id)]},+ format="json",+ )+ assert resp.status_code == 200+ assert resp.json()["updated"] == 3+ for ev in (self.event, e2, e3):+ assert NotificationReadState.objects.filter(notification_event=ev, user=self.user).exists()++ def test_mark_read_bulk_skips_non_recipient(self):+ other_user_event = NotificationEvent.objects.create(+ organization=self.organization,+ team=self.team,+ notification_type="alert_firing",+ title="Other",+ body="",+ target_type="user",+ target_id="999",+ resolved_user_ids=[],+ )+ resp = self.client.post(+ f"/api/environments/{self.team.id}/notifications/mark_read_bulk/",+ {"notification_ids": [str(other_user_event.id), str(self.event.id)]},+ format="json",+ )+ assert resp.status_code == 200+ assert resp.json()["updated"] == 1+ assert not NotificationReadState.objects.filter(notification_event=other_user_event, user=self.user).exists()++ def test_mark_unread_bulk(self):+ NotificationReadState.objects.create(notification_event=self.event, user=self.user)+ resp = self.client.post(+ f"/api/environments/{self.team.id}/notifications/mark_unread_bulk/",+ {"notification_ids": [str(self.event.id)]},+ format="json",+ )+ assert resp.status_code == 200+ assert resp.json()["updated"] == 1+ assert not NotificationReadState.objects.filter(notification_event=self.event, user=self.user).exists()++ def test_mark_read_bulk_empty(self):+ resp = self.client.post(+ f"/api/environments/{self.team.id}/notifications/mark_read_bulk/",+ {"notification_ids": []},+ format="json",+ )+ assert resp.status_code == 200+ assert resp.json()["updated"] == 0++ def test_mark_unread_bulk_skips_non_recipient(self):+ other_user_event = NotificationEvent.objects.create(+ organization=self.organization,+ team=self.team,+ notification_type="alert_firing",+ title="Other",+ body="",+ target_type="user",+ target_id="999",+ resolved_user_ids=[],+ )+ # Pre-create a read state for the user's own event so it has something to delete+ NotificationReadState.objects.create(notification_event=self.event, user=self.user)+ resp = self.client.post(+ f"/api/environments/{self.team.id}/notifications/mark_unread_bulk/",+ {"notification_ids": [str(other_user_event.id), str(self.event.id)]},+ format="json",+ )+ assert resp.status_code == 200+ assert resp.json()["updated"] == 1+ assert not NotificationReadState.objects.filter(notification_event=self.event, user=self.user).exists()++ def test_mark_read_bulk_non_list_returns_400(self):+ resp = self.client.post(+ f"/api/environments/{self.team.id}/notifications/mark_read_bulk/",+ {"notification_ids": "not-a-list"},+ format="json",+ )+ assert resp.status_code == 400++ def test_mark_read_bulk_too_many_ids_returns_400(self):+ ids = [str(uuid.uuid4()) for _ in range(501)]+ resp = self.client.post(+ f"/api/environments/{self.team.id}/notifications/mark_read_bulk/",+ {"notification_ids": ids},+ format="json",+ )+ assert resp.status_code == 400++ def test_mark_unread_bulk_too_many_ids_returns_400(self):+ ids = [str(uuid.uuid4()) for _ in range(501)]+ resp = self.client.post(+ f"/api/environments/{self.team.id}/notifications/mark_unread_bulk/",+ {"notification_ids": ids},+ format="json",+ )+ assert resp.status_code == 400+class TestNotificationsAPIFeatureFlagDisabled(BaseTest):def setUp(self):diff --git a/products/notifications/frontend/generated/api.schemas.ts b/products/notifications/frontend/generated/api.schemas.tsindex a2644f98c7fc..496c8a77b66c 100644--- a/products/notifications/frontend/generated/api.schemas.ts+++ b/products/notifications/frontend/generated/api.schemas.ts@@ -42,6 +42,8 @@ export interface NotificationEventApi {read: boolean/** @nullable */read_at: string | null+ target_type: string+ target_id: string/** @nullable */resource_type: string | nullresource_id: string@@ -61,13 +63,49 @@ export interface PaginatedNotificationEventListApi {results: NotificationEventApi[]}+export interface BulkNotificationIdsRequestApi {+ /**+ * UUIDs of notification events to mark in bulk (max 500). Events the user is not a recipient of are silently skipped.+ * @maxItems 500+ */+ notification_ids: string[]+}+export type NotificationsListParams = {+ /**+ * ISO 8601 timestamp; only events at or after this time+ */+ created_after?: string+ /**+ * ISO 8601 timestamp; only events strictly before this time+ */+ created_before?: string/*** Number of results to return per page.*/limit?: number+ /**+ * Filter by notification type+ */+ notification_type?: string/*** The initial index from which to return the results.*/offset?: number+ /**+ * Filter by the ID of the resource the notification refers to+ */+ resource_id?: string+ /**+ * Filter by the type of the resource the notification refers to (e.g. `insight`, `dashboard`)+ */+ resource_type?: string+ /**+ * Filter by recipient target ID (e.g. a user ID)+ */+ target_id?: string+ /**+ * Filter by recipient target type (e.g. `user`, `team`)+ */+ target_type?: string}diff --git a/products/notifications/frontend/generated/api.ts b/products/notifications/frontend/generated/api.tsindex a506afab095d..1f9b9eaaa3ed 100644--- a/products/notifications/frontend/generated/api.ts+++ b/products/notifications/frontend/generated/api.ts@@ -8,7 +8,11 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* PostHog API - generated* OpenAPI spec version: 1.0.0*/-import type { NotificationsListParams, PaginatedNotificationEventListApi } from './api.schemas'+import type {+ BulkNotificationIdsRequestApi,+ NotificationsListParams,+ PaginatedNotificationEventListApi,+} from './api.schemas'export const getNotificationsListUrl = (projectId: string, params?: NotificationsListParams) => {const normalizedParams = new URLSearchParams()@@ -78,6 +82,40 @@ export const notificationsMarkAllReadCreate = async (projectId: string, options?})}+export const getNotificationsMarkReadBulkCreateUrl = (projectId: string) => {+ return `/api/environments/${projectId}/notifications/mark_read_bulk/`+}++export const notificationsMarkReadBulkCreate = async (+ projectId: string,+ bulkNotificationIdsRequestApi: BulkNotificationIdsRequestApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getNotificationsMarkReadBulkCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(bulkNotificationIdsRequestApi),+ })+}++export const getNotificationsMarkUnreadBulkCreateUrl = (projectId: string) => {+ return `/api/environments/${projectId}/notifications/mark_unread_bulk/`+}++export const notificationsMarkUnreadBulkCreate = async (+ projectId: string,+ bulkNotificationIdsRequestApi: BulkNotificationIdsRequestApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getNotificationsMarkUnreadBulkCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(bulkNotificationIdsRequestApi),+ })+}+export const getNotificationsUnreadCountRetrieveUrl = (projectId: string) => {return `/api/environments/${projectId}/notifications/unread_count/`}diff --git a/products/notifications/frontend/generated/api.zod.ts b/products/notifications/frontend/generated/api.zod.tsindex e8a15d4e1b52..2cef6c8603b4 100644--- a/products/notifications/frontend/generated/api.zod.ts+++ b/products/notifications/frontend/generated/api.zod.ts@@ -7,3 +7,26 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+import * as zod from 'zod'++export const notificationsMarkReadBulkCreateBodyNotificationIdsMax = 500++export const NotificationsMarkReadBulkCreateBody = /* @__PURE__ */ zod.object({+ notification_ids: zod+ .array(zod.uuid())+ .max(notificationsMarkReadBulkCreateBodyNotificationIdsMax)+ .describe(+ 'UUIDs of notification events to mark in bulk (max 500). Events the user is not a recipient of are silently skipped.'+ ),+})++export const notificationsMarkUnreadBulkCreateBodyNotificationIdsMax = 500++export const NotificationsMarkUnreadBulkCreateBody = /* @__PURE__ */ zod.object({+ notification_ids: zod+ .array(zod.uuid())+ .max(notificationsMarkUnreadBulkCreateBodyNotificationIdsMax)+ .describe(+ 'UUIDs of notification events to mark in bulk (max 500). Events the user is not a recipient of are silently skipped.'+ ),+})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 01fa6b9895d9..78c0eac013ea 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -6340,6 +6340,14 @@ export namespace Schemas {DeviceId: 'device_id',} as const;+ export interface BulkNotificationIdsRequest {+ /**+ * UUIDs of notification events to mark in bulk (max 500). Events the user is not a recipient of are silently skipped.+ * @maxItems 500+ */+ notification_ids: string[];+ }+export interface BulkUpdateTagsError {id: number;reason: string;@@ -20851,6 +20859,8 @@ export namespace Schemas {read: boolean;/** @nullable */read_at: string | null;+ target_type: string;+ target_id: string;/** @nullable */resource_type: string | null;resource_id: string;@@ -39818,14 +39828,42 @@ export namespace Schemas {};export type NotificationsListParams = {+ /**+ * ISO 8601 timestamp; only events at or after this time+ */+ created_after?: string;+ /**+ * ISO 8601 timestamp; only events strictly before this time+ */+ created_before?: string;/*** Number of results to return per page.*/limit?: number;+ /**+ * Filter by notification type+ */+ notification_type?: string;/*** The initial index from which to return the results.*/offset?: number;+ /**+ * Filter by the ID of the resource the notification refers to+ */+ resource_id?: string;+ /**+ * Filter by the type of the resource the notification refers to (e.g. `insight`, `dashboard`)+ */+ resource_type?: string;+ /**+ * Filter by recipient target ID (e.g. a user ID)+ */+ target_id?: string;+ /**+ * Filter by recipient target type (e.g. `user`, `team`)+ */+ target_type?: string;};export type QuickFiltersListParams = {