: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): add in-app notification preferences settings (#56138)
Yasend13d85b3314a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex eaf0c7e6f881..e2c81ed3b8ba 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5355,9 +5355,9 @@ snapshots:scenes-app-settings-user--settings-user-danger-zone--light:hash: v1.k794b7964.3d9b0b41f9c406648096aeb01948cf090e034f555d22653fc64bf094cb4b1bc7.aHFm6dpLsLadfJcxoXMhbnWez7b8PXOwYb1-pEyXj3Ascenes-app-settings-user--settings-user-notifications--dark:- hash: v1.k794b7964.2b01995610c990c188b0c55d028b1cd04f48b2ab132d1c4a9823976bf1fe628a.UGsb-zjKmoMn66_0x-e6QyplgtdOj7OaAHJEXtDd2WA+ hash: v1.k794b7964.22ead67c438f7cfde18c34715e8dd576c4db349df6dabc0c908560eb3ed91555.lpgYG-de2fQcog1Hh1e4bf4GDHgcPNldNTz9I8x0P0Uscenes-app-settings-user--settings-user-notifications--light:- hash: v1.k794b7964.02972859b3fd20be5cd0529ce60824ce8fc7f51df9452805db83ae4cd612173f.V6L3MCj1GiDQ0Zcz3WIE-pHVVCjjTk-vNNy89xC5AMI+ hash: v1.k794b7964.78be6493f8dc936460b5b091a6b07a8d22668d386c7db0e59a66fbd9c0fd584f.x-p_Brnou1AiPTBD8DNS9UEmYJ2A8SwqaMT5zcaQLBQscenes-app-settings-user--settings-user-profile--dark:hash: v1.k794b7964.3a3874d1b09b3cfda9a6b2c31614c33c6b9dfd8ecb83ba501a5ed3f372a56ea9.XxF7t-2d8ZqMpP1ijBiz8uXefxN_Itz7o2Om6oBC6vgscenes-app-settings-user--settings-user-profile--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 6a20a38e9d4a..5c0ba1b78e2b 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -3051,6 +3051,8 @@ export interface UserApi {readonly onboarding_delegation_accepted_at: string | null/** @nullable */readonly is_organization_first_user: boolean | null+ /** Real-time notification types that currently have a live dispatch site. Drives the in-app notifications settings UI. Read-only. */+ readonly active_realtime_notification_types: readonly string[]readonly pending_invites: readonly PendingInviteApi[]}@@ -3147,6 +3149,8 @@ export interface PatchedUserApi {readonly onboarding_delegation_accepted_at?: string | null/** @nullable */readonly is_organization_first_user?: boolean | null+ /** Real-time notification types that currently have a live dispatch site. Drives the in-app notifications settings UI. Read-only. */+ readonly active_realtime_notification_types?: readonly string[]readonly pending_invites?: readonly PendingInviteApi[]}diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsxindex d6ef13766457..412322b21ffe 100644--- a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx+++ b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx@@ -12,6 +12,33 @@ import { IconOpenInNew } from 'lib/lemon-ui/icons'import { sidePanelNotificationsLogic } from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic'import { InAppNotification } from '~/types'+export const REALTIME_NOTIFICATION_TYPE_META: Record<string, { label: string; description: string }> = {+ comment_mention: {+ label: 'Comment mentions',+ description: 'When someone @mentions you in a discussion',+ },+ alert_firing: {+ label: 'Alerts firing',+ description: 'When an alert you subscribe to triggers',+ },+ approval_requested: {+ label: 'Approvals requested',+ description: 'When a change is awaiting your approval',+ },+ approval_resolved: {+ label: 'Approvals resolved',+ description: 'When an approval you requested is decided',+ },+ pipeline_failure: {+ label: 'Pipeline failures',+ description: 'When a data pipeline or batch export fails',+ },+ issue_assigned: {+ label: 'Issues assigned',+ description: 'When an error tracking issue is assigned to you',+ },+}+export function NotificationRow({notification,onNavigate,diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 6d44e35b01f0..b11bd9cb6ea0 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -145,6 +145,7 @@ import { OptOutCapture } from './user/OptOutCapture'import { PasskeySettings } from './user/PasskeySettings'import { PersonalAPIKeys } from './user/PersonalAPIKeys'import { PersonalIntegrations } from './user/PersonalIntegrations'+import { RealtimeNotificationPreferences } from './user/RealtimeNotificationPreferences'import { SidebarAutoSuggestSetting } from './user/SidebarProductSettings'import { ThemeSwitcher } from './user/ThemeSwitcher'import { TwoFactorSettings } from './user/TwoFactorSettings'@@ -1681,6 +1682,14 @@ export const SETTINGS_MAP: SettingSection[] = [component: <UpdateEmailPreferences />,keywords: ['email', 'notification', 'digest', 'unsubscribe'],},+ {+ id: 'realtime-notifications',+ title: 'In-app notifications',+ description: 'Choose which real-time notifications you receive in the PostHog app, per project.',+ component: <RealtimeNotificationPreferences />,+ flag: 'REAL_TIME_NOTIFICATIONS',+ keywords: ['notification', 'in-app', 'realtime', 'popover', 'mention'],+ },],},{diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex 68cc798ba08a..e1ceca868f93 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -169,6 +169,7 @@ export type SettingId =| 'personal-integrations'| 'personal-api-keys'| 'notifications'+ | 'realtime-notifications'| 'feature-previews'| 'feature-previews-coming-soon'| 'optout'diff --git a/frontend/src/scenes/settings/user/RealtimeNotificationPreferences.test.tsx b/frontend/src/scenes/settings/user/RealtimeNotificationPreferences.test.tsxnew file mode 100644index 000000000000..f08825bd57d2--- /dev/null+++ b/frontend/src/scenes/settings/user/RealtimeNotificationPreferences.test.tsx@@ -0,0 +1,55 @@+import '@testing-library/jest-dom'++import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { expectLogic } from 'kea-test-utils'++import { organizationLogic } from 'scenes/organizationLogic'+import { userLogic } from 'scenes/userLogic'++import { initKeaTests } from '~/test/init'++import { RealtimeNotificationPreferences } from './RealtimeNotificationPreferences'++describe('<RealtimeNotificationPreferences />', () => {+ beforeEach(() => {+ initKeaTests()+ userLogic.mount()+ organizationLogic.mount()+ userLogic.actions.loadUserSuccess({+ active_realtime_notification_types: ['comment_mention'],+ notification_settings: { realtime_notifications_disabled: {} },+ } as any)+ organizationLogic.actions.loadCurrentOrganizationSuccess({+ id: 'org-1',+ name: 'Org',+ teams: [+ { id: 1, name: 'Project A' },+ { id: 2, name: 'Project B' },+ ],+ } as any)+ })++ it('renders one row per active project with the active types as children', () => {+ render(<RealtimeNotificationPreferences />)+ expect(screen.getByText('Project A')).toBeInTheDocument()+ expect(screen.getByText('Project B')).toBeInTheDocument()+ expect(screen.getAllByText('Comment mentions')).toHaveLength(2)+ })++ it('toggling a single type dispatches updateRealtimeNotificationForTeam', async () => {+ render(<RealtimeNotificationPreferences />)+ const checkbox = screen.getAllByRole('checkbox', { name: /Comment mentions/i })[0]+ await expectLogic(userLogic, () => userEvent.click(checkbox)).toDispatchActions([+ userLogic.actionCreators.updateRealtimeNotificationForTeam('comment_mention', 1, false),+ ])+ })++ it('clicking a project parent dispatches updateRealtimeNotificationForProject with disable', async () => {+ render(<RealtimeNotificationPreferences />)+ const projectCheckbox = screen.getAllByRole('checkbox', { name: /Project A/i })[0]+ await expectLogic(userLogic, () => userEvent.click(projectCheckbox)).toDispatchActions([+ userLogic.actionCreators.updateRealtimeNotificationForProject(1, ['comment_mention'], false),+ ])+ })+})diff --git a/frontend/src/scenes/settings/user/RealtimeNotificationPreferences.tsx b/frontend/src/scenes/settings/user/RealtimeNotificationPreferences.tsxnew file mode 100644index 000000000000..3435dd8bf1ce--- /dev/null+++ b/frontend/src/scenes/settings/user/RealtimeNotificationPreferences.tsx@@ -0,0 +1,115 @@+import { useActions, useValues } from 'kea'++import { IconChevronRight } from '@posthog/icons'+import { LemonButton, LemonCheckbox, LemonTag } from '@posthog/lemon-ui'++import { REALTIME_NOTIFICATION_TYPE_META } from 'lib/components/NotificationsMenu/NotificationRow'+import { userLogic } from 'scenes/userLogic'++import { TeamBasicType } from '~/types'++import { realtimeNotificationPreferencesLogic } from './realtimeNotificationPreferencesLogic'++export function RealtimeNotificationPreferences(): JSX.Element {+ const { userLoading } = useValues(userLogic)+ const { updateRealtimeNotificationForTeam, updateRealtimeNotificationForProject, updateAllRealtimeNotifications } =+ useActions(userLogic)+ const { activeTypes, isTypeEnabledForTeam, projectState, teams, teamIds, isProjectExpanded, allOn, allOff } =+ useValues(realtimeNotificationPreferencesLogic)+ const { setProjectExpanded } = useActions(realtimeNotificationPreferencesLogic)++ if (activeTypes.length === 0) {+ return <div className="text-muted text-sm">No real-time notifications are wired up for your account yet.</div>+ }++ return (+ <div className="space-y-3">+ <div className="flex flex-row items-center gap-2">+ <LemonButton+ size="xsmall"+ type="secondary"+ disabled={userLoading || allOn}+ onClick={() => updateAllRealtimeNotifications(teamIds, activeTypes, true)}+ >+ Enable all+ </LemonButton>+ <LemonButton+ size="xsmall"+ type="secondary"+ disabled={userLoading || allOff}+ onClick={() => updateAllRealtimeNotifications(teamIds, activeTypes, false)}+ >+ Disable all+ </LemonButton>+ </div>++ <div className="space-y-2">+ {teams.map((team: TeamBasicType) => {+ const state = projectState(team.id)+ const isOpen = isProjectExpanded(team.id)+ return (+ <div key={team.id}>+ <div className="flex items-center gap-2">+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={+ <IconChevronRight+ className={`transition-transform ${isOpen ? 'rotate-90' : ''}`}+ />+ }+ onClick={() => setProjectExpanded(team.id, !isOpen)}+ />+ <LemonCheckbox+ id={`realtime-project-${team.id}`}+ checked={state === 'partial' ? 'indeterminate' : state === 'on'}+ disabled={userLoading}+ onChange={() =>+ updateRealtimeNotificationForProject(team.id, activeTypes, state === 'off')+ }+ label={+ <div className="flex items-center gap-2">+ <span>{team.name}</span>+ <LemonTag type="muted">id: {String(team.id)}</LemonTag>+ </div>+ }+ />+ </div>+ {isOpen && (+ <div className="ml-16 mt-1 space-y-1">+ {activeTypes.map((type) => {+ const meta = REALTIME_NOTIFICATION_TYPE_META[type] ?? {+ label: type,+ description: '',+ }+ return (+ <LemonCheckbox+ key={`${team.id}-${type}`}+ id={`realtime-${type}-${team.id}`}+ checked={isTypeEnabledForTeam(type, team.id)}+ disabled={userLoading}+ onChange={(checked) =>+ updateRealtimeNotificationForTeam(type, team.id, checked)+ }+ label={+ <div className="flex flex-col">+ <span>{meta.label}</span>+ {meta.description && (+ <span className="text-muted text-xs">+ {meta.description}+ </span>+ )}+ </div>+ }+ />+ )+ })}+ </div>+ )}+ </div>+ )+ })}+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/settings/user/realtimeNotificationPreferencesLogic.test.ts b/frontend/src/scenes/settings/user/realtimeNotificationPreferencesLogic.test.tsnew file mode 100644index 000000000000..5ddb599966e9--- /dev/null+++ b/frontend/src/scenes/settings/user/realtimeNotificationPreferencesLogic.test.ts@@ -0,0 +1,71 @@+import { expectLogic } from 'kea-test-utils'++import { userLogic } from 'scenes/userLogic'++import { initKeaTests } from '~/test/init'++import { realtimeNotificationPreferencesLogic } from './realtimeNotificationPreferencesLogic'++describe('realtimeNotificationPreferencesLogic', () => {+ let logic: ReturnType<typeof realtimeNotificationPreferencesLogic.build>++ beforeEach(() => {+ initKeaTests()+ userLogic.mount()+ logic = realtimeNotificationPreferencesLogic()+ logic.mount()+ })++ it('isTypeEnabledForTeam: defaults to enabled when no entry stored', async () => {+ userLogic.actions.loadUserSuccess({+ notification_settings: { realtime_notifications_disabled: {} },+ } as any)++ await expectLogic(logic).toMatchValues({+ isTypeEnabledForTeam: expect.any(Function),+ })+ expect(logic.values.isTypeEnabledForTeam('comment_mention', 1)).toBe(true)+ })++ it('isTypeEnabledForTeam: returns false when stored as disabled', async () => {+ userLogic.actions.loadUserSuccess({+ notification_settings: { realtime_notifications_disabled: { comment_mention: { '1': true } } },+ } as any)++ expect(logic.values.isTypeEnabledForTeam('comment_mention', 1)).toBe(false)+ })++ it('projectState: returns "off" when every type for the project is disabled', async () => {+ userLogic.actions.loadUserSuccess({+ active_realtime_notification_types: ['comment_mention', 'alert_firing'],+ notification_settings: {+ realtime_notifications_disabled: {+ comment_mention: { '1': true },+ alert_firing: { '1': true },+ },+ },+ } as any)++ expect(logic.values.projectState(1)).toBe('off')+ })++ it('projectState: returns "partial" when some are disabled', async () => {+ userLogic.actions.loadUserSuccess({+ active_realtime_notification_types: ['comment_mention', 'alert_firing'],+ notification_settings: {+ realtime_notifications_disabled: { comment_mention: { '1': true } },+ },+ } as any)++ expect(logic.values.projectState(1)).toBe('partial')+ })++ it('projectState: returns "on" when nothing is disabled', async () => {+ userLogic.actions.loadUserSuccess({+ active_realtime_notification_types: ['comment_mention'],+ notification_settings: { realtime_notifications_disabled: {} },+ } as any)++ expect(logic.values.projectState(1)).toBe('on')+ })+})diff --git a/frontend/src/scenes/settings/user/realtimeNotificationPreferencesLogic.ts b/frontend/src/scenes/settings/user/realtimeNotificationPreferencesLogic.tsnew file mode 100644index 000000000000..31979e8993ce--- /dev/null+++ b/frontend/src/scenes/settings/user/realtimeNotificationPreferencesLogic.ts@@ -0,0 +1,84 @@+import { actions, connect, kea, path, reducers, selectors } from 'kea'++import { organizationLogic } from 'scenes/organizationLogic'+import { userLogic } from 'scenes/userLogic'++import { TeamBasicType } from '~/types'++import type { realtimeNotificationPreferencesLogicType } from './realtimeNotificationPreferencesLogicType'++export type ProjectState = 'on' | 'off' | 'partial'++export const realtimeNotificationPreferencesLogic = kea<realtimeNotificationPreferencesLogicType>([+ path(['scenes', 'settings', 'user', 'realtimeNotificationPreferencesLogic']),+ connect({+ values: [userLogic, ['user'], organizationLogic, ['currentOrganization']],+ }),+ actions({+ setProjectExpanded: (teamId: number, expanded: boolean) => ({ teamId, expanded }),+ }),+ reducers({+ expandedOverrides: [+ {} as Record<number, boolean>,+ {+ setProjectExpanded: (state, { teamId, expanded }) => ({ ...state, [teamId]: expanded }),+ },+ ],+ }),+ selectors(() => ({+ teams: [+ (s) => [s.currentOrganization],+ (currentOrganization): TeamBasicType[] => currentOrganization?.teams ?? [],+ ],+ teamIds: [(s) => [s.teams], (teams: TeamBasicType[]): number[] => teams.map((t) => t.id)],+ activeTypes: [+ () => [userLogic.selectors.user],+ (user): string[] => (user?.active_realtime_notification_types ?? []) as string[],+ ],+ disabledMap: [+ () => [userLogic.selectors.user],+ (user): Record<string, Record<string, boolean>> =>+ user?.notification_settings?.realtime_notifications_disabled ?? {},+ ],+ defaultExpanded: [(s) => [s.teams], (teams: TeamBasicType[]): boolean => teams.length <= 3],+ isProjectExpanded: [+ (s) => [s.expandedOverrides, s.defaultExpanded],+ (overrides: Record<number, boolean>, defaultExpanded: boolean) =>+ (teamId: number): boolean =>+ overrides[teamId] ?? defaultExpanded,+ ],+ isTypeEnabledForTeam: [+ (s) => [s.disabledMap],+ (disabledMap) =>+ (type: string, teamId: number): boolean =>+ !disabledMap[type]?.[String(teamId)],+ ],+ projectState: [+ (s) => [s.activeTypes, s.disabledMap],+ (activeTypes, disabledMap) =>+ (teamId: number): ProjectState => {+ if (activeTypes.length === 0) {+ return 'on'+ }+ const enabledFlags = activeTypes.map((type) => !disabledMap[type]?.[String(teamId)])+ if (enabledFlags.every((v) => v)) {+ return 'on'+ }+ if (enabledFlags.every((v) => !v)) {+ return 'off'+ }+ return 'partial'+ },+ ],+ allOn: [+ (s) => [s.teamIds, s.projectState],+ (teamIds: number[], projectState: (teamId: number) => ProjectState): boolean =>+ teamIds.every((teamId) => projectState(teamId) === 'on'),+ ],+ allOff: [+ (s) => [s.teamIds, s.projectState],+ (teamIds: number[], projectState: (teamId: number) => ProjectState): boolean =>+ teamIds.every((teamId) => projectState(teamId) === 'off'),+ ],+ })),+])diff --git a/frontend/src/scenes/userLogic.test.ts b/frontend/src/scenes/userLogic.test.tsindex 79e3be9d71ff..aff13f342d8f 100644--- a/frontend/src/scenes/userLogic.test.ts+++ b/frontend/src/scenes/userLogic.test.ts@@ -95,4 +95,95 @@ describe('userLogic', () => {}).toMatchValues({ optimisticThemeMode: 'dark' })})})++ describe('realtime notification preferences', () => {+ let updateUserSpy: jest.SpyInstance++ beforeEach(() => {+ updateUserSpy = jest.spyOn(userLogic.actions, 'updateUser')+ })++ afterEach(() => {+ updateUserSpy.mockRestore()+ })++ it('updateRealtimeNotificationForTeam sends a minimal patch toggling one (type, team) pair to disabled', () => {+ userLogic.actions.loadUserSuccess({+ ...MOCK_DEFAULT_USER,+ notification_settings: {+ ...MOCK_DEFAULT_USER.notification_settings,+ realtime_notifications_disabled: {},+ },+ } as any)++ userLogic.actions.updateRealtimeNotificationForTeam('comment_mention', 42, false)++ expect(updateUserSpy).toHaveBeenCalledWith({+ notification_settings: expect.objectContaining({+ realtime_notifications_disabled: { comment_mention: { '42': true } },+ }),+ })+ })++ it('updateRealtimeNotificationForProject sets every passed type to disabled for that team', () => {+ userLogic.actions.loadUserSuccess({+ ...MOCK_DEFAULT_USER,+ notification_settings: {+ ...MOCK_DEFAULT_USER.notification_settings,+ realtime_notifications_disabled: {},+ },+ } as any)++ userLogic.actions.updateRealtimeNotificationForProject(7, ['comment_mention', 'alert_firing'], false)++ expect(updateUserSpy).toHaveBeenCalledWith({+ notification_settings: expect.objectContaining({+ realtime_notifications_disabled: {+ comment_mention: { '7': true },+ alert_firing: { '7': true },+ },+ }),+ })+ })++ it('updateAllRealtimeNotifications disables every (team, type) pair when enabled=false', () => {+ userLogic.actions.loadUserSuccess({+ ...MOCK_DEFAULT_USER,+ notification_settings: {+ ...MOCK_DEFAULT_USER.notification_settings,+ realtime_notifications_disabled: {},+ },+ } as any)++ userLogic.actions.updateAllRealtimeNotifications([1, 2], ['comment_mention'], false)++ expect(updateUserSpy).toHaveBeenCalledWith({+ notification_settings: expect.objectContaining({+ realtime_notifications_disabled: {+ comment_mention: { '1': true, '2': true },+ },+ }),+ })+ })++ it('updateAllRealtimeNotifications clears disabled entries when enabled=true', () => {+ userLogic.actions.loadUserSuccess({+ ...MOCK_DEFAULT_USER,+ notification_settings: {+ ...MOCK_DEFAULT_USER.notification_settings,+ realtime_notifications_disabled: { comment_mention: { '1': true, '2': true } },+ },+ } as any)++ userLogic.actions.updateAllRealtimeNotifications([1, 2], ['comment_mention'], true)++ expect(updateUserSpy).toHaveBeenCalledWith({+ notification_settings: expect.objectContaining({+ realtime_notifications_disabled: {+ comment_mention: { '1': false, '2': false },+ },+ }),+ })+ })+ })})diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.tsindex 15329399b679..81ae4573f603 100644--- a/frontend/src/scenes/userLogic.ts+++ b/frontend/src/scenes/userLogic.ts@@ -93,6 +93,21 @@ export const userLogic = kea<userLogicType>([enabled,}),updateDataPipelineErrorThreshold: (threshold: number) => ({ threshold }),+ updateRealtimeNotificationForTeam: (type: string, teamId: number, enabled: boolean) => ({+ type,+ teamId,+ enabled,+ }),+ updateRealtimeNotificationForProject: (teamId: number, types: string[], enabled: boolean) => ({+ teamId,+ types,+ enabled,+ }),+ updateAllRealtimeNotifications: (teamIds: number[], types: string[], enabled: boolean) => ({+ teamIds,+ types,+ enabled,+ }),})),forms(({ actions }) => ({userDetails: {@@ -446,6 +461,52 @@ export const userLogic = kea<userLogicType>([},})},+ updateRealtimeNotificationForTeam: ({ type, teamId, enabled }) => {+ if (!values.user?.notification_settings) {+ return+ }+ const current = values.user.notification_settings.realtime_notifications_disabled ?? {}+ const typeMap = { ...current[type], [String(teamId)]: !enabled }+ actions.updateUser({+ notification_settings: {+ realtime_notifications_disabled: { ...current, [type]: typeMap },+ } as NotificationSettings,+ })+ },+ updateRealtimeNotificationForProject: ({ teamId, types, enabled }) => {+ if (!values.user?.notification_settings) {+ return+ }+ const current = values.user.notification_settings.realtime_notifications_disabled ?? {}+ const next = { ...current }+ for (const type of types) {+ next[type] = { ...next[type], [String(teamId)]: !enabled }+ }+ actions.updateUser({+ notification_settings: {+ realtime_notifications_disabled: next,+ } as NotificationSettings,+ })+ },+ updateAllRealtimeNotifications: ({ teamIds, types, enabled }) => {+ if (!values.user?.notification_settings) {+ return+ }+ const current = values.user.notification_settings.realtime_notifications_disabled ?? {}+ const next = { ...current }+ for (const type of types) {+ const typeMap = { ...next[type] }+ for (const teamId of teamIds) {+ typeMap[String(teamId)] = !enabled+ }+ next[type] = typeMap+ }+ actions.updateUser({+ notification_settings: {+ realtime_notifications_disabled: next,+ } as NotificationSettings,+ })+ },updateDataPipelineErrorThreshold: async ({ threshold }, breakpoint) => {await breakpoint(500)diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 41610c7d0ef5..a4e37964ecd2 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -327,6 +327,7 @@ export type OnboardingSkippedReason = 'delegated' | 'later' | 'other' | nullexport interface UserType extends UserBaseType {date_joined: stringnotification_settings: NotificationSettings+ active_realtime_notification_types?: readonly string[]events_column_config: ColumnConfiganonymize_data: booleanallow_impersonation: boolean@@ -414,6 +415,7 @@ export interface NotificationSettings {web_analytics_weekly_digest: booleanweb_analytics_weekly_digest_project_enabled?: Record<string, boolean>organization_member_join_email_disabled?: Record<string, boolean>+ realtime_notifications_disabled?: Record<string, Record<string, boolean>>}export interface InAppNotification {diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 5933b22a810b..c52c3c766643 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -213,6 +213,14 @@ class TestUserAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json() == {"a bag": "of data"}+ def test_users_me_includes_active_realtime_notification_types(self):+ self.client.force_login(self.user)+ response = self.client.get("/api/users/@me/")+ assert response.status_code == 200+ body = response.json()+ assert "active_realtime_notification_types" in body+ assert "comment_mention" in body["active_realtime_notification_types"]+def test_can_only_list_yourself(self):"""At this moment only the current user can be retrieved from this endpoint.@@ -1598,6 +1606,7 @@ class TestUserAPI(APIBaseTest):"materialized_view_sync_failed": True,"web_analytics_weekly_digest": True,"organization_member_join_email_disabled": {},+ "realtime_notifications_disabled": {},},)@@ -1616,6 +1625,7 @@ class TestUserAPI(APIBaseTest):"materialized_view_sync_failed": True,"web_analytics_weekly_digest": True,"organization_member_join_email_disabled": {},+ "realtime_notifications_disabled": {},},)@@ -1669,6 +1679,129 @@ class TestUserAPI(APIBaseTest):},)+ def test_notification_settings_default_includes_realtime_disabled_empty_dict(self):+ user = self._create_user("[email protected]")+ assert user.notification_settings["realtime_notifications_disabled"] == {}++ def test_realtime_notifications_disabled_accepts_valid_payload(self):+ self.client.force_login(self.user)+ response = self.client.patch(+ "/api/users/@me/",+ {+ "notification_settings": {+ "realtime_notifications_disabled": {"comment_mention": {str(self.team.id): True}}+ }+ },+ format="json",+ )+ assert response.status_code == 200, response.json()+ self.user.refresh_from_db()+ assert self.user.partial_notification_settings is not None+ assert self.user.partial_notification_settings["realtime_notifications_disabled"] == {+ "comment_mention": {str(self.team.id): True}+ }++ @parameterized.expand(+ [+ ("unknown_type", {"made_up_type": {"1": True}}, "Unknown notification type"),+ ("non_bool_value", {"comment_mention": {"1": "yes"}}, "must be boolean"),+ ("non_dict_top_level", "not_a_dict", "must be a dict"),+ ("non_dict_inner", {"comment_mention": "not_a_dict"}, "must be a dict of team_id"),+ ]+ )+ def test_realtime_notifications_disabled_rejects_invalid_payload(self, _name, payload, expected_message_substr):+ self.client.force_login(self.user)+ response = self.client.patch(+ "/api/users/@me/",+ {"notification_settings": {"realtime_notifications_disabled": payload}},+ format="json",+ )+ assert response.status_code == 400, response.json()+ assert expected_message_substr in response.json()["detail"], response.json()++ def test_realtime_notifications_disabled_false_overwrites_true_for_same_pair(self):+ self.user.partial_notification_settings = {"realtime_notifications_disabled": {"comment_mention": {"1": True}}}+ self.user.save()+ self.client.force_login(self.user)+ response = self.client.patch(+ "/api/users/@me/",+ {"notification_settings": {"realtime_notifications_disabled": {"comment_mention": {"1": False}}}},+ format="json",+ )+ assert response.status_code == 200, response.json()+ self.user.refresh_from_db()+ assert self.user.partial_notification_settings is not None+ assert self.user.partial_notification_settings["realtime_notifications_disabled"] == {+ "comment_mention": {"1": False}+ }++ def test_realtime_notifications_disabled_two_level_merge_preserves_other_pairs(self):+ self.user.partial_notification_settings = {+ "realtime_notifications_disabled": {+ "comment_mention": {"7": True, "8": True},+ "alert_firing": {"7": True},+ }+ }+ self.user.save()+ self.client.force_login(self.user)+ response = self.client.patch(+ "/api/users/@me/",+ {"notification_settings": {"realtime_notifications_disabled": {"comment_mention": {"9": True}}}},+ format="json",+ )+ assert response.status_code == 200, response.json()+ self.user.refresh_from_db()+ assert self.user.partial_notification_settings is not None+ assert self.user.partial_notification_settings["realtime_notifications_disabled"] == {+ "comment_mention": {"7": True, "8": True, "9": True},+ "alert_firing": {"7": True},+ }++ @parameterized.expand(+ [+ ("bool_scalar", "all_weekly_digest_disabled", False),+ ("plugin_disabled_bool", "plugin_disabled", True),+ ("project_dict", "project_weekly_digest_disabled", {"99": True}),+ ("org_dict", "organization_member_join_email_disabled", {"00000000-0000-0000-0000-000000000099": True}),+ ("realtime_two_level_dict", "realtime_notifications_disabled", {"comment_mention": {"99": True}}),+ ("float_threshold", "data_pipeline_error_threshold", 0.99),+ ]+ )+ def test_partial_notification_settings_patch_preserves_unrelated_keys(self, _name, patched_key, patched_value):+ # Pre-seed every key with a non-default value so any clobber is visible.+ pre_seeded = {+ "plugin_disabled": False,+ "error_tracking_issue_assigned": False,+ "discussions_mentioned": False,+ "project_weekly_digest_disabled": {"1": True, "2": True},+ "all_weekly_digest_disabled": True,+ "data_pipeline_error_threshold": 0.42,+ "project_api_key_exposed": False,+ "materialized_view_sync_failed": True,+ "web_analytics_weekly_digest": False,+ "organization_member_join_email_disabled": {"00000000-0000-0000-0000-000000000001": True},+ "realtime_notifications_disabled": {"comment_mention": {"1": True}},+ }+ self.user.partial_notification_settings = pre_seeded+ self.user.save()+ self.client.force_login(self.user)++ response = self.client.patch(+ "/api/users/@me/",+ {"notification_settings": {patched_key: patched_value}},+ format="json",+ )++ assert response.status_code == 200, response.json()+ self.user.refresh_from_db()+ assert self.user.partial_notification_settings is not None+ for unrelated_key, original_value in pre_seeded.items():+ if unrelated_key == patched_key:+ continue+ assert self.user.partial_notification_settings[unrelated_key] == original_value, (+ f"Patching {patched_key!r} clobbered {unrelated_key!r}"+ )+def test_invalid_notification_settings_returns_error(self):response = self.client.patch("/api/users/@me/", {"notification_settings": {"invalid_key": True}})self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)@@ -1720,6 +1853,7 @@ class TestUserAPI(APIBaseTest):"materialized_view_sync_failed": False, # Default value"web_analytics_weekly_digest": True, # Default value"organization_member_join_email_disabled": {}, # Default value+ "realtime_notifications_disabled": {}, # Default value},)diff --git a/posthog/api/user.py b/posthog/api/user.pyindex dcc647fa02f9..ea770a3494b6 100644--- a/posthog/api/user.py+++ b/posthog/api/user.py@@ -106,6 +106,9 @@ from posthog.user_permissions import UserPermissionsfrom posthog.utils import render_templatefrom products.dashboards.backend.models.dashboard import Dashboard+from products.notifications.backend.facade.api import NotificationType++_VALID_NOTIFICATION_TYPE_VALUES: frozenset[str] = frozenset(t.value for t in NotificationType)REDIRECT_TO_SITE_COUNTER = Counter("posthog_redirect_to_site", "Redirect to site")REDIRECT_TO_SITE_FAILED_COUNTER = Counter("posthog_redirect_to_site_failed", "Redirect to site failed")@@ -207,6 +210,12 @@ class UserSerializer(serializers.ModelSerializer):"to scope the 'waiting for teammate' UI to the org where delegation was initiated.",)is_organization_first_user = serializers.SerializerMethodField()+ active_realtime_notification_types = serializers.SerializerMethodField(+ help_text=(+ "Real-time notification types that currently have a live dispatch site. "+ "Drives the in-app notifications settings UI. Read-only."+ ),+ )class Meta:model = User@@ -256,6 +265,7 @@ class UserSerializer(serializers.ModelSerializer):"onboarding_delegated_to_organization_id","onboarding_delegation_accepted_at","is_organization_first_user",+ "active_realtime_notification_types","pending_invites",]@@ -283,6 +293,7 @@ class UserSerializer(serializers.ModelSerializer):"onboarding_delegated_to_organization_id","onboarding_delegation_accepted_at","is_organization_first_user",+ "active_realtime_notification_types","pending_invites",]@@ -385,6 +396,10 @@ class UserSerializer(serializers.ModelSerializer):return Nonereturn membership.invited_by_id is None+ @extend_schema_field({"type": "array", "items": {"type": "string"}})+ def get_active_realtime_notification_types(self, _: User) -> list[str]:+ return [t.value for t in NotificationType]+@extend_schema_field(PendingInviteSerializer(many=True))@tracer.start_as_current_span("user_serializer.pending_invites")def get_pending_invites(self, instance: User) -> list[dict]:@@ -483,6 +498,34 @@ class UserSerializer(serializers.ModelSerializer):code="invalid_input",)current_settings[key] = {**current_settings.get(key, {}), **value}+ elif key == "realtime_notifications_disabled":+ if not isinstance(value, dict):+ raise serializers.ValidationError(+ "realtime_notifications_disabled must be a dict",+ code="invalid_input",+ )+ for type_key, team_map in value.items():+ if type_key not in _VALID_NOTIFICATION_TYPE_VALUES:+ raise serializers.ValidationError(+ f"Unknown notification type {type_key}",+ code="invalid_input",+ )+ if not isinstance(team_map, dict):+ raise serializers.ValidationError(+ f"Per-type value for {type_key} must be a dict of team_id to bool",+ code="invalid_input",+ )+ for _team_id, disabled in team_map.items():+ if not isinstance(disabled, bool):+ raise serializers.ValidationError(+ f"Disabled flag for {type_key} must be boolean, got {type(disabled)}",+ code="invalid_input",+ )+ existing = current_settings.get("realtime_notifications_disabled", {}) or {}+ merged: dict[str, dict[str, bool]] = {**existing}+ for type_key, team_map in value.items():+ merged[type_key] = {**(existing.get(type_key, {}) or {}), **team_map}+ current_settings["realtime_notifications_disabled"] = mergedelif key == "data_pipeline_error_threshold":if not isinstance(value, (int, float)):raise serializers.ValidationError(diff --git a/posthog/models/user.py b/posthog/models/user.pyindex 74f4cf2d4b83..2226730449e4 100644--- a/posthog/models/user.py+++ b/posthog/models/user.py@@ -47,6 +47,9 @@ class Notifications(TypedDict, total=False):organization_member_join_email_disabled: dict[str, bool] # Maps organization ID (str) to disabled status (True = do not email when a new member joins)+ realtime_notifications_disabled: dict[+ str, dict[str, bool]+ ] # Maps notification_type (str) to {team_id (str) -> disabled (True = muted)}. Absence = enabled (opt-out default).NOTIFICATION_DEFAULTS: Notifications = {@@ -61,6 +64,7 @@ NOTIFICATION_DEFAULTS: Notifications = {"materialized_view_sync_failed": False, # Materialized view failure disabled by default"web_analytics_weekly_digest": True, # Web analytics weekly digest enabled by default"organization_member_join_email_disabled": {}, # No per-org opt-out until user configures+ "realtime_notifications_disabled": {}, # No opt-outs by default}# We don't need the following attributes in most cases, so we defer them by defaultdiff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.pyindex 76ca3b1d8672..0ba3976f372c 100644--- a/products/notifications/backend/facade/enums.py+++ b/products/notifications/backend/facade/enums.py@@ -7,11 +7,6 @@ from posthog.scopes import APIScopeObjectclass NotificationType(str, Enum):COMMENT_MENTION = "comment_mention"- ALERT_FIRING = "alert_firing"- APPROVAL_REQUESTED = "approval_requested"- APPROVAL_RESOLVED = "approval_resolved"- PIPELINE_FAILURE = "pipeline_failure"- ISSUE_ASSIGNED = "issue_assigned"class Priority(str, Enum):diff --git a/products/notifications/backend/logic.py b/products/notifications/backend/logic.pyindex 988afcf56292..e0c91a7d0116 100644--- a/products/notifications/backend/logic.py+++ b/products/notifications/backend/logic.py@@ -5,11 +5,15 @@ import posthoganalyticsfrom posthog.kafka_client.routing import get_producerfrom posthog.kafka_client.topics import KAFKA_NOTIFICATION_EVENTS-from posthog.models import Team+from posthog.models import Team, Userfrom products.notifications.backend.cache import invalidate_unread_count_for_usersfrom products.notifications.backend.facade.contracts import NotificationData-from products.notifications.backend.facade.enums import AC_RESOURCE_TYPES, NotificationOnlyResourceType+from products.notifications.backend.facade.enums import (+ AC_RESOURCE_TYPES,+ NotificationOnlyResourceType,+ NotificationType,+)from products.notifications.backend.models import NotificationEventfrom products.notifications.backend.resolvers import RecipientsResolver@@ -42,6 +46,25 @@ def _publish_to_kafka(event: NotificationEvent) -> None:logger.exception("notifications.kafka_publish_failed", event_id=event.id)+def _filter_by_user_preferences(+ user_ids: list[int],+ notification_type: NotificationType,+ team_id: int,+) -> list[int]:+ if not user_ids:+ return user_ids+ rows = User.objects.filter(id__in=user_ids).values_list("id", "partial_notification_settings")+ type_key = notification_type.value+ team_key = str(team_id)++ def _is_disabled(settings: dict | None) -> bool:+ realtime = (settings or {}).get("realtime_notifications_disabled") or {}+ type_map = realtime.get(type_key) or {}+ return bool(type_map.get(team_key, False))++ return [uid for uid, settings in rows if not _is_disabled(settings)]++def create_notification(data: NotificationData) -> NotificationEvent | None:try:team = Team.objects.select_related("organization").get(id=data.team_id)@@ -66,8 +89,19 @@ def create_notification(data: NotificationData) -> NotificationEvent | None:if data.resource_type and str(data.resource_type) in AC_RESOURCE_TYPES:resolved_user_ids = resolver.filter_by_access_control(resolved_user_ids, str(data.resource_type), team)+ # Per-user pref filter must run AFTER AC — prefs cannot override access denials.+ resolved_user_ids = _filter_by_user_preferences(+ resolved_user_ids,+ notification_type=data.notification_type,+ team_id=data.team_id,+ )+if not resolved_user_ids:- logger.warning("notifications.no_recipients", target_type=data.target_type, target_id=data.target_id)+ logger.warning(+ "notifications.no_recipients",+ target_type=data.target_type,+ target_id=data.target_id,+ )return Noneevent = NotificationEvent.objects.create(diff --git a/products/notifications/backend/migrations/0004_alter_notificationevent_notification_type.py b/products/notifications/backend/migrations/0004_alter_notificationevent_notification_type.pynew file mode 100644index 000000000000..36dfdd0855f0--- /dev/null+++ b/products/notifications/backend/migrations/0004_alter_notificationevent_notification_type.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.13 on 2026-05-05 07:30++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notifications", "0003_notificationevent_source_id_and_more"),+ ]++ operations = [+ migrations.AlterField(+ model_name="notificationevent",+ name="notification_type",+ field=models.CharField(choices=[("comment_mention", "COMMENT_MENTION")], max_length=32),+ ),+ ]diff --git a/products/notifications/backend/migrations/max_migration.txt b/products/notifications/backend/migrations/max_migration.txtindex 9f774288a963..88b9410f863b 100644--- a/products/notifications/backend/migrations/max_migration.txt+++ b/products/notifications/backend/migrations/max_migration.txt@@ -1 +1 @@-0003_notificationevent_source_id_and_more+0004_alter_notificationevent_notification_typediff --git a/products/notifications/backend/tests/test_logic.py b/products/notifications/backend/tests/test_logic.pyindex 3eb69246d633..204206df6cf1 100644--- a/products/notifications/backend/tests/test_logic.py+++ b/products/notifications/backend/tests/test_logic.py@@ -4,6 +4,8 @@ from unittest.mock import patchfrom django.core.cache import cache+from parameterized import parameterized+from posthog.constants import AvailableFeaturefrom posthog.models import Organization, Team, User@@ -54,7 +56,7 @@ class TestCreateNotification(BaseTest):data = NotificationData(team_id=self.team.id,- notification_type=NotificationType.ALERT_FIRING,+ notification_type=NotificationType.COMMENT_MENTION,title="Org-wide alert",body="Something happened",target_type=TargetType.ORGANIZATION,@@ -82,7 +84,7 @@ class TestCreateNotification(BaseTest):data = NotificationData(team_id=self.team.id,- notification_type=NotificationType.ALERT_FIRING,+ notification_type=NotificationType.COMMENT_MENTION,title="Cache invalidation test",body="",target_type=TargetType.ORGANIZATION,@@ -150,6 +152,79 @@ class TestCreateNotification(BaseTest):assert event is Noneassert NotificationEvent.objects.count() == 0+ @parameterized.expand(+ [+ (+ "muted_same_team",+ lambda team: {"realtime_notifications_disabled": {"comment_mention": {str(team.id): True}}},+ False,+ ),+ (+ "muted_other_type",+ lambda team: {"realtime_notifications_disabled": {"alert_firing": {str(team.id): True}}},+ True,+ ),+ (+ "muted_other_team",+ lambda team: {"realtime_notifications_disabled": {"comment_mention": {"99999": True}}},+ True,+ ),+ ("settings_none", lambda team: None, True),+ ("realtime_key_none", lambda team: {"realtime_notifications_disabled": None}, True),+ ]+ )+ @patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=True)+ @patch("products.notifications.backend.logic._publish_to_kafka")+ def test_create_notification_respects_per_user_pref(+ self, _name, settings_factory, expect_notified, mock_publish, mock_ff+ ):+ settings = settings_factory(self.team)+ if settings is None:+ self.user.partial_notification_settings = None+ else:+ self.user.partial_notification_settings = settings+ self.user.save()++ data = NotificationData(+ team_id=self.team.id,+ notification_type=NotificationType.COMMENT_MENTION,+ title="Test",+ body="",+ target_type=TargetType.USER,+ target_id=str(self.user.id),+ )+ event = create_notification(data)++ if expect_notified:+ assert event is not None+ assert event.resolved_user_ids == [self.user.id]+ else:+ assert event is None++ @patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=True)+ @patch("products.notifications.backend.logic._publish_to_kafka")+ def test_create_notification_filters_org_target_by_per_user_pref(self, mock_publish, mock_ff):+ user2 = User.objects.create_and_join(self.organization, "[email protected]", "password")+ user2.partial_notification_settings = {+ "realtime_notifications_disabled": {+ "comment_mention": {str(self.team.id): True},+ }+ }+ user2.save()++ data = NotificationData(+ team_id=self.team.id,+ notification_type=NotificationType.COMMENT_MENTION,+ title="Test",+ body="",+ target_type=TargetType.ORGANIZATION,+ target_id=str(self.organization.id),+ )+ event = create_notification(data)++ assert event is not None+ assert set(event.resolved_user_ids) == {self.user.id}+class TestAccessControlFiltering(BaseTest):def setUp(self):@@ -174,7 +249,7 @@ class TestAccessControlFiltering(BaseTest):def test_no_ac_filtering_for_notification_only_resource_types(self, mock_ac_filter, mock_publish, mock_ff):data = NotificationData(team_id=self.team.id,- notification_type=NotificationType.PIPELINE_FAILURE,+ notification_type=NotificationType.COMMENT_MENTION,title="Pipeline failed",body="",target_type=TargetType.USER,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f135f6380121..153b253d7218 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -26028,6 +26028,8 @@ export namespace Schemas {readonly onboarding_delegation_accepted_at: string | null;/** @nullable */readonly is_organization_first_user: boolean | null;+ /** Real-time notification types that currently have a live dispatch site. Drives the in-app notifications settings UI. Read-only. */+ readonly active_realtime_notification_types: readonly string[];readonly pending_invites: readonly PendingInvite[];}@@ -31410,6 +31412,8 @@ export namespace Schemas {readonly onboarding_delegation_accepted_at?: string | null;/** @nullable */readonly is_organization_first_user?: boolean | null;+ /** Real-time notification types that currently have a live dispatch site. Drives the in-app notifications settings UI. Read-only. */+ readonly active_realtime_notification_types?: readonly string[];readonly pending_invites?: readonly PendingInvite[];}