Skip to content

: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.

feat: Allow users to clear notifications (#63042)

Jordan Mryyan30606b95f5af
diff --git a/.agents/skills/sending-notifications/SKILL.md b/.agents/skills/sending-notifications/SKILL.md
index 4815c61e7681..8fc56ce11a6d 100644
--- a/.agents/skills/sending-notifications/SKILL.md
+++ b/.agents/skills/sending-notifications/SKILL.md
@@ -59,13 +59,14 @@ Returns a `NotificationEvent` on success, or `None` if the feature flag is disab
**Optional:**
-| Field | Type | Default | Description |
-| --------------- | ---------------------------------- | -------- | ----------------------------------------------------------------------------------------- |
-| `resource_type` | `NotificationResourceType \| None` | `None` | Access-controlled types (e.g. `"dashboard"`) auto-filter recipients without viewer access |
-| `resource_id` | `str` | `""` | ID of the resource for linking |
-| `source_url` | `str` | `""` | Relative URL path (e.g. `/dashboard/42`), shown as link icon in UI |
-| `priority` | `Priority` | `NORMAL` | `normal` = popover only; `critical` = popover + persistent toast |
-| `resolver` | `RecipientsResolver \| None` | `None` | Custom recipient resolver. Default handles user/team/org/role targeting |
+| Field | Type | Default | Description |
+| --------------- | ---------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `resource_type` | `NotificationResourceType \| None` | `None` | Access-controlled types (e.g. `"dashboard"`) auto-filter recipients without viewer access |
+| `resource_id` | `str` | `""` | ID of the resource for linking |
+| `source_url` | `str` | `""` | Relative URL path (e.g. `/dashboard/42`), shown as link icon in UI |
+| `priority` | `Priority` | `NORMAL` | `normal` = popover only; `critical` = popover + persistent toast |
+| `archivable` | `bool` | `False` | Opt in to a per-recipient "archive" (dismiss) action that moves the notification to the recipient's Archived tab. When `False`, recipients can only mark it read/unread (the default pattern) |
+| `resolver` | `RecipientsResolver \| None` | `None` | Custom recipient resolver. Default handles user/team/org/role targeting |
## Choosing parameters
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 30eda3c58fa2..3ca41473ad2f 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -188,6 +188,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
# --- User preferences with no IDOR risk (read own data only) ---
"FeatureFlagOverride",
"NotificationReadState",
+ "NotificationArchiveState",
"NotificationViewed",
"SessionRecordingPlaylistViewed",
"UserPromptState",
@@ -325,6 +326,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"LogsAlertCheck", # via LogsAlertConfiguration
"LogsAlertEvent", # via LogsAlertConfiguration
"NotificationReadState", # via NotificationEvent
+ "NotificationArchiveState", # via NotificationEvent
"PluginStorage", # via PluginConfig
"ResourceNotebook", # via Notebook
"SchemaPropertyGroupProperty", # via SchemaPropertyGroup
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.ts
index d9b629dff87d..9a011f22b1b8 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
@@ -12,6 +12,7 @@ function makeNotification(overrides: Partial<InAppNotification> = {}): InAppNoti
body: '',
read: false,
read_at: null,
+ archivable: false,
resource_type: null,
resource_id: '',
target_type: 'user',
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.ts
index 2d4f5e2c2d5b..6e994de9abd2 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
@@ -18,6 +18,7 @@ function makeNotification(overrides: Partial<InAppNotification> = {}): InAppNoti
body: '',
read: false,
read_at: null,
+ archivable: false,
resource_type: null,
resource_id: '',
target_type: 'user',
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE.ts
index 469c4846ec42..b18d37fe58df 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/notificationsSSE.ts
@@ -32,7 +32,8 @@ export function connectToNotificationsSSE(
hooks.onFirstMessage?.()
}
try {
- const notification = JSON.parse(event.data) as InAppNotification
+ const parsed = JSON.parse(event.data) as InAppNotification
+ const notification = { ...parsed, archivable: parsed.archivable ?? false }
onNotification(notification)
} catch {
// Ignore malformed messages
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.ts
index 941f29147c3d..824a907a19bc 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.test.ts
@@ -25,6 +25,7 @@ function makeNotification(overrides: Partial<InAppNotification> = {}): InAppNoti
created_at: '2026-05-07T12:00:00Z',
read: false,
read_at: null,
+ archivable: false,
...overrides,
}
}
@@ -195,6 +196,82 @@ describe('sidePanelNotificationsLogic.toggleGroupRead', () => {
})
})
+describe('sidePanelNotificationsLogic.archive', () => {
+ let logic: ReturnType<typeof sidePanelNotificationsLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ // refreshInAppUnreadCount reconciles against the server after each archive.
+ '/api/environments/:tid/notifications/unread_count/': () => [200, { count: 1 }],
+ },
+ post: {
+ '/api/projects/:tid/notifications/:id/archive/': () => [200, { status: 'ok' }],
+ '/api/projects/:tid/notifications/archive_bulk/': () => [200, { updated: 2 }],
+ '/api/projects/:tid/notifications/archive_all/': () => [200, { updated: 2 }],
+ },
+ })
+ initKeaTests()
+ logic = sidePanelNotificationsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => logic.unmount())
+
+ it('removes an archived notification and decrements unread count', async () => {
+ const a = makeNotification({ id: 'a', archivable: true, read: false })
+ const b = makeNotification({ id: 'b', resource_id: 'other' })
+ logic.actions.setInAppNotifications([a, b], false)
+ logic.actions.setInAppUnreadCount(2)
+ await logic.actions.archiveNotification('a')
+ expect(logic.values.inAppNotifications.map((n: InAppNotification) => n.id)).toEqual(['b'])
+ expect(logic.values.inAppUnreadCount).toBe(1)
+ })
+
+ it('does not archive a non-archivable notification', async () => {
+ const a = makeNotification({ id: 'a', archivable: false })
+ logic.actions.setInAppNotifications([a], false)
+ await logic.actions.archiveNotification('a')
+ expect(logic.values.inAppNotifications.map((n: InAppNotification) => n.id)).toEqual(['a'])
+ })
+
+ it('archiveAll removes only archivable notifications', async () => {
+ const a = makeNotification({ id: 'a', archivable: true, resource_id: 'a' })
+ const b = makeNotification({ id: 'b', archivable: false, resource_id: 'b' })
+ logic.actions.setInAppNotifications([a, b], false)
+ await logic.actions.archiveAll()
+ expect(logic.values.inAppNotifications.map((n: InAppNotification) => n.id)).toEqual(['b'])
+ })
+
+ it('archiveAll resyncs the unread count from the server (server value wins)', async () => {
+ // Optimistic decrement alone would land at 9, but the server is the source of truth.
+ const a = makeNotification({ id: 'a', archivable: true, read: false })
+ logic.actions.setInAppNotifications([a], false)
+ logic.actions.setInAppUnreadCount(10)
+ await expectLogic(logic, () => {
+ logic.actions.archiveAll()
+ }).toDispatchActions(['archiveAll', 'refreshInAppUnreadCount', 'setInAppUnreadCount'])
+ expect(logic.values.inAppUnreadCount).toBe(1)
+ })
+
+ it('hasArchivableNotifications reflects presence of an archivable notification', () => {
+ logic.actions.setInAppNotifications([makeNotification({ id: 'a', archivable: true })], false)
+ expect(logic.values.hasArchivableNotifications).toBe(true)
+ logic.actions.setInAppNotifications([makeNotification({ id: 'b', archivable: false })], false)
+ expect(logic.values.hasArchivableNotifications).toBe(false)
+ })
+
+ it('group.has_archivable is true when any child is archivable, even if the representative is not', () => {
+ // Newest (representative) is non-archivable; an older same-group child is archivable.
+ const rep = makeNotification({ id: 'rep', archivable: false, created_at: '2026-05-07T12:00:00Z' })
+ const older = makeNotification({ id: 'older', archivable: true, created_at: '2026-05-07T09:00:00Z' })
+ logic.actions.setInAppNotifications([rep, older], false)
+ const group = logic.values.groups.find((g) => g.count === 2)
+ expect(group?.representative.id).toBe('rep')
+ expect(group?.has_archivable).toBe(true)
+ })
+})
+
describe('sidePanelNotificationsLogic.mainListOffset', () => {
let logic: ReturnType<typeof sidePanelNotificationsLogic.build>
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx
index 2198173478ad..5a8cc4937dd0 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx
@@ -25,6 +25,9 @@ import { ChangesResponse } from '~/layout/navigation-3000/sidepanel/panels/activ
import { InAppNotification, InsightShortId, ResourceEditedEvent } from '~/types'
import {
+ notificationsArchiveAllCreate,
+ notificationsArchiveBulkCreate,
+ notificationsArchiveCreate,
notificationsList,
notificationsMarkAllReadCreate,
notificationsMarkReadBulkCreate,
@@ -73,6 +76,7 @@ export interface NotificationGroup {
last_seen: string
children: InAppNotification[]
has_unread: boolean
+ has_archivable: boolean
full_children_loaded: boolean
}
@@ -83,6 +87,45 @@ export function groupKey(n: InAppNotification): string {
}|${localDay}`
}
+export function buildGroups(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
+ }
+ if (n.archivable) {
+ existing.has_archivable = true
+ }
+ continue
+ }
+ byKey.set(key, {
+ group_key: key,
+ representative: n,
+ count: 1,
+ first_seen: n.created_at,
+ last_seen: n.created_at,
+ children: [n],
+ has_unread: !n.read,
+ has_archivable: n.archivable,
+ full_children_loaded: loadedGroupKeys.has(key),
+ })
+ groups.push(byKey.get(key)!)
+ }
+ return groups
+}
+
export function buildNotificationSourcePath(notification: InAppNotification): string | null {
const toPath = notification.source_type
? SOURCE_TYPE_TO_PATH[notification.source_type as NotificationEventSourceTypeEnumApi]
@@ -144,6 +187,23 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(
notificationReceived: (notification: InAppNotification) => ({ notification }),
markAsRead: (id: string) => ({ id }),
toggleRead: (id: string) => ({ id }),
+ archiveNotification: (id: string) => ({ id }),
+ archiveGroup: (group: NotificationGroup) => ({ group }),
+ archiveAll: true,
+ removeNotifications: (ids: string[]) => ({ ids }),
+ refreshInAppUnreadCount: true,
+ setArchivedNotifications: (notifications: InAppNotification[], hasMore: boolean) => ({
+ notifications,
+ hasMore,
+ }),
+ appendArchivedNotifications: (notifications: InAppNotification[], hasMore: boolean) => ({
+ notifications,
+ hasMore,
+ }),
+ loadArchivedNotifications: true,
+ loadMoreArchived: true,
+ loadMoreArchivedSuccess: (count: number) => ({ count }),
+ loadArchivedGroupChildren: (group: NotificationGroup) => ({ group }),
navigateToNotification: (notification: InAppNotification) => ({ notification }),
loadMoreNotifications: true,
loadMoreNotificationsSuccess: (count: number) => ({ count }),
@@ -184,6 +244,10 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(
return [...state, ...newItems]
},
notificationReceived: (state, { notification }) => [notification, ...state],
+ removeNotifications: (state, { ids }) => {
+ const toRemove = new Set(ids)
+ return state.filter((n) => !toRemove.has(n.id))
+ },
markAsRead: (state, { id }) =>
state.map((n) => (n.id === id ? { ...n, read: true, read_at: new Date().toISOString() } : n)),
toggleRead: (state, { id }) =>
@@ -223,6 +287,46 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(
appendInAppNotifications: () => false,
},
],
+ // Archived notifications are a separate, lazily-loaded data source so the active list is
+ // never polluted. They mirror the main-list reducers (offset cursor, has-more, loading).
+ archivedNotifications: [
+ [] as InAppNotification[],
+ {
+ setArchivedNotifications: (_, { notifications }) => notifications,
+ appendArchivedNotifications: (state, { notifications }) => {
+ const existingIds = new Set(state.map((n) => n.id))
+ const newItems = notifications.filter((n) => !existingIds.has(n.id))
+ return [...state, ...newItems]
+ },
+ },
+ ],
+ archivedLoaded: [
+ false,
+ {
+ setArchivedNotifications: () => true,
+ },
+ ],
+ archivedListOffset: [
+ 0,
+ {
+ setArchivedNotifications: (_, { notifications }) => notifications.length,
+ loadMoreArchivedSuccess: (state, { count }) => state + count,
+ },
+ ],
+ hasMoreArchived: [
+ false,
+ {
+ setArchivedNotifications: (_, { hasMore }) => hasMore,
+ appendArchivedNotifications: (_, { hasMore }) => hasMore,
+ },
+ ],
+ isLoadingMoreArchived: [
+ false,
+ {
+ loadMoreArchived: () => true,
+ appendArchivedNotifications: () => false,
+ },
+ ],
inAppUnreadCount: [
0,
{
@@ -354,7 +458,7 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(
],
})),
listeners(({ actions, values, cache }) => {
- const fetchGroupChildren = async (group: NotificationGroup): Promise<void> => {
+ const fetchGroupChildren = async (group: NotificationGroup, archived = false): Promise<void> => {
if (group.full_children_loaded) {
return
}
@@ -368,6 +472,9 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(
created_before: day.add(1, 'day').toISOString(),
limit: 100,
}
+ if (archived) {
+ params.archived = true
+ }
if (group.representative.resource_type) {
params.resource_type = group.representative.resource_type
}
@@ -376,7 +483,12 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(
}
try {
const resp = await notificationsList((values.currentProjectId ?? '').toString(), params)
- actions.appendInAppNotifications(resp.results as InAppNotification[], values.hasMoreNotifications)
+ const results = resp.results as InAppNotification[]
+ if (archived) {
+ actions.appendArchivedNotifications(results, values.hasMoreArchived)
+ } else {
+ actions.appendInAppNotifications(results, values.hasMoreNotifications)
+ }
actions.markGroupChildrenLoaded(group.group_key)
} catch {
// Swallow
@@ -621,6 +733,110 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(
// Swallow
}
},
+ refreshInAppUnreadCount: async () => {
+ try {
+ const countResp = await api.get<{ count: number }>(
+ `api/environments/${values.currentProjectId}/notifications/unread_count/`
+ )
+ actions.setInAppUnreadCount(countResp.count)
+ } catch {
+ // Swallow
+ }
+ },
+ archiveNotification: async ({ id }) => {
+ const notification = values.inAppNotifications.find((n) => n.id === id)
+ if (!notification || !notification.archivable) {
+ return
+ }
+ actions.removeNotifications([id])
+ if (!notification.read) {
+ actions.setInAppUnreadCount(Math.max(0, values.inAppUnreadCount - 1))
+ }
+ try {
+ await notificationsArchiveCreate((values.currentProjectId ?? '').toString(), id)
+ } catch {
+ // Swallow
+ }
+ // Reconcile against the server: the optimistic decrement above only covers the
+ // loaded page, so resync the authoritative count.
+ await actions.refreshInAppUnreadCount()
+ },
+ archiveGroup: 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 archivable = refreshed.children.filter((c) => c.archivable)
+ const ids = archivable.map((c) => c.id)
+ if (ids.length === 0) {
+ return
+ }
+ const unreadArchived = archivable.filter((c) => !c.read).length
+ actions.removeNotifications(ids)
+ if (unreadArchived > 0) {
+ actions.setInAppUnreadCount(Math.max(0, values.inAppUnreadCount - unreadArchived))
+ }
+ try {
+ await notificationsArchiveBulkCreate((values.currentProjectId ?? '').toString(), {
+ notification_ids: ids,
+ })
+ } catch {
+ // Swallow
+ }
+ await actions.refreshInAppUnreadCount()
+ },
+ archiveAll: async () => {
+ const archivable = values.inAppNotifications.filter((n) => n.archivable)
+ const ids = archivable.map((n) => n.id)
+ if (ids.length === 0) {
+ return
+ }
+ const unreadArchived = archivable.filter((n) => !n.read).length
+ actions.removeNotifications(ids)
+ if (unreadArchived > 0) {
+ actions.setInAppUnreadCount(Math.max(0, values.inAppUnreadCount - unreadArchived))
+ }
+ try {
+ await notificationsArchiveAllCreate((values.currentProjectId ?? '').toString())
+ } catch {
+ // Swallow
+ }
+ await actions.refreshInAppUnreadCount()
+ },
+ loadArchivedNotifications: async () => {
+ try {
+ const resp = await notificationsList((values.currentProjectId ?? '').toString(), {
+ limit: 20,
+ archived: true,
+ })
+ actions.setArchivedNotifications(resp.results as InAppNotification[], !!resp.next)
+ } catch {
+ // Swallow
+ }
+ },
+ loadMoreArchived: async () => {
+ if (!values.hasMoreArchived) {
+ return
+ }
+ try {
+ const resp = await notificationsList((values.currentProjectId ?? '').toString(), {
+ limit: 20,
+ offset: values.archivedListOffset,
+ archived: true,
+ })
+ const results = resp.results as InAppNotification[]
+ actions.appendArchivedNotifications(results, !!resp.next)
+ actions.loadMoreArchivedSuccess(results.length)
+ } catch {
+ // Swallow
+ }
+ },
+ loadArchivedGroupChildren: async ({ group }) => {
+ await fetchGroupChildren(group, true)
+ },
loadCurrentTeamSuccess: () => {
if (values.realTimeNotificationsEnabled && !cache.sseConnection) {
cache.nextStartReason = 'team_reload'
@@ -681,6 +897,10 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(
(s) => [s.featureFlags],
(featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.REAL_TIME_NOTIFICATIONS],
],
+ archivingEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.CLEARABLE_NOTIFICATIONS],
+ ],
legacyNotifications: [
(s) => [s.importantChanges],
(importantChanges): HumanizedActivityLogItem[] => {
@@ -749,6 +969,10 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(
},
],
hasNotifications: [(s) => [s.notifications], (notifications) => !!notifications.length],
+ hasArchivableNotifications: [
+ (s) => [s.inAppNotifications],
+ (inAppNotifications): boolean => inAppNotifications.some((n) => n.archivable),
+ ],
unreadCount: [
(s) => [s.realTimeNotificationsEnabled, s.legacyNotifications, s.inAppUnreadCount],
(realTimeEnabled, legacyNotifications, inAppUnreadCount): number => {
@@ -793,41 +1017,13 @@ export const sidePanelNotificationsLogic = kea<sidePanelNotificationsLogicType>(
],
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
- },
+ (notifications: InAppNotification[], loadedGroupKeys: Set<string>): NotificationGroup[] =>
+ buildGroups(notifications, loadedGroupKeys),
+ ],
+ archivedGroups: [
+ (s) => [s.archivedNotifications, s.loadedGroupKeys],
+ (notifications: InAppNotification[], loadedGroupKeys: Set<string>): NotificationGroup[] =>
+ buildGroups(notifications, loadedGroupKeys),
],
}),
afterMount(({ cache, actions, values }) => {
diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationActionButton.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationActionButton.tsx
new file mode 100644
index 000000000000..60979731ca15
--- /dev/null
+++ b/frontend/src/lib/components/NotificationsMenu/NotificationActionButton.tsx
@@ -0,0 +1,57 @@
+import { ReactNode } from 'react'
+
+import { IconCheckCircle } from '@posthog/icons'
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { IconRadioButtonUnchecked } from 'lib/lemon-ui/icons'
+
+export const ROW_ACTION_REVEAL_CLASSES =
+ 'opacity-0 group-hover/row:opacity-100 group-focus-within/row:opacity-100 transition-opacity'
+
+export function ReadToggleIcon({ read }: { read: boolean }): JSX.Element {
+ if (read) {
+ return <IconCheckCircle className="size-4 text-success" />
+ }
+ return (
+ <>
+ <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" />
+ </>
+ )
+}
+
+export function NotificationActionButton({
+ icon,
+ tooltip,
+ onClick,
+ tone = 'default',
+ ariaLabel,
+ className,
+}: {
+ icon: ReactNode
+ tooltip?: string
+ onClick: (e: React.MouseEvent) => void
+ tone?: 'default' | 'danger'
+ ariaLabel?: string
+ className?: string
+}): JSX.Element {
+ const toneClasses =
+ tone === 'danger'
+ ? 'text-secondary hover:text-danger hover:bg-fill-error-highlight'
+ : 'text-secondary hover:text-primary hover:bg-fill-highlight-200'
+
+ const button = (
+ <button
+ type="button"
+ aria-label={ariaLabel ?? tooltip}
+ className={`min-w-[26px] min-h-[26px] flex items-center justify-center rounded cursor-pointer ${toneClasses} ${
+ className ?? ''
+ }`}
+ onClick={onClick}
+ >
+ {icon}
+ </button>
+ )
+
+ return tooltip ? <Tooltip title={tooltip}>{button}</Tooltip> : button
+}
diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationGroupRow.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationGroupRow.tsx
index 7d20edfbec1b..7f4455bd73ca 100644
--- a/frontend/src/lib/components/NotificationsMenu/NotificationGroupRow.tsx
+++ b/frontend/src/lib/components/NotificationsMenu/NotificationGroupRow.tsx
@@ -1,7 +1,11 @@
import { useActions, useValues } from 'kea'
-import { IconChevronRight } from '@posthog/icons'
+import { IconArchive, IconChevronRight } from '@posthog/icons'
+import {
+ NotificationActionButton,
+ ROW_ACTION_REVEAL_CLASSES,
+} from 'lib/components/NotificationsMenu/NotificationActionButton'
import {
NotificationReadToggle,
NotificationRow,
@@ -19,19 +23,34 @@ function NotificationGroupControls({
count,
allRead,
expanded,
+ readOnly,
+ hasArchivable,
onToggleRead,
onToggleExpand,
+ onArchive,
}: {
count: number
allRead: boolean
expanded: boolean
+ readOnly: boolean
+ hasArchivable: boolean
onToggleRead: (e: React.MouseEvent) => void
onToggleExpand: (e: React.MouseEvent) => void
+ onArchive: (e: React.MouseEvent) => void
}): JSX.Element {
return (
<div className="shrink-0 flex items-center gap-1">
<span className="text-[10px] text-muted bg-fill-highlight-100 px-1.5 py-px rounded">{count}</span>
- <NotificationReadToggle read={allRead} onToggle={onToggleRead} target="group" />
+ {!readOnly && hasArchivable && (
+ <NotificationActionButton
+ icon={<IconArchive className="size-4" />}
+ tooltip="Archive group"
+ onClick={onArchive}
+ tone="danger"
+ className={ROW_ACTION_REVEAL_CLASSES}
+ />
+ )}
+ {!readOnly && <NotificationReadToggle read={allRead} onToggle={onToggleRead} target="group" />}
<button
className="shrink-0 flex size-5 items-center justify-center rounded text-secondary hover:bg-fill-highlight-200 hover:text-primary"
onClick={onToggleExpand}
@@ -46,12 +65,16 @@ function NotificationGroupControls({
export function NotificationGroupRow({
group,
onNavigate,
+ readOnly = false,
}: {
group: NotificationGroup
onNavigate?: () => void
+ readOnly?: boolean
}): JSX.Element {
- const { expandedGroupKeys, loadingGroupKeys, manuallyToggledIds } = useValues(sidePanelNotificationsLogic)
- const { toggleGroupExpanded, loadGroupChildren, toggleGroupRead } = useActions(sidePanelNotificationsLogic)
+ const { expandedGroupKeys, loadingGroupKeys, manuallyToggledIds, archivingEnabled } =
+ useValues(sidePanelNotificationsLogic)
+ const { toggleGroupExpanded, loadGroupChildren, loadArchivedGroupChildren, toggleGroupRead, archiveGroup } =
+ useActions(sidePanelNotificationsLogic)
const isExpanded = expandedGroupKeys.has(group.group_key)
const isLoading = loadingGroupKeys.has(group.group_key)
@@ -66,13 +89,17 @@ export function NotificationGroupRow({
)
if (group.count === 1) {
- return <NotificationRow notification={group.representative} onNavigate={onNavigate} />
+ return <NotificationRow notification={group.representative} onNavigate={onNavigate} readOnly={readOnly} />
}
const handleExpand = (e: React.MouseEvent): void => {
e.stopPropagation()
if (!group.full_children_loaded && !isExpanded) {
- void loadGroupChildren(group)
+ if (readOnly) {
+ void loadArchivedGroupChildren(group)
+ } else {
+ void loadGroupChildren(group)
+ }
}
toggleGroupExpanded(group.group_key)
}
@@ -82,13 +109,18 @@ export function NotificationGroupRow({
toggleGroupRead(group)
}
+ const handleArchive = (e: React.MouseEvent): void => {
+ e.stopPropagation()
+ archiveGroup(group)
+ }
+
const allRead = !group.has_unread
return (
<div className="flex flex-col">
<div
ref={autoMarkRef}
- className={`flex items-start gap-2 p-2 rounded cursor-pointer transition-colors ${
+ className={`group/row flex items-start gap-2 p-2 rounded cursor-pointer transition-colors ${
allRead ? 'hover:bg-fill-highlight-100' : 'bg-fill-highlight-50 hover:bg-fill-highlight-100'
}`}
onClick={handleExpand}
@@ -106,15 +138,23 @@ export function NotificationGroupRow({
count={group.count}
allRead={allRead}
expanded={isExpanded}
+ readOnly={readOnly}
+ hasArchivable={archivingEnabled && group.has_archivable}
onToggleRead={handleToggleRead}
onToggleExpand={handleExpand}
+ onArchive={handleArchive}
/>
</div>
{isExpanded && (
<div className="ml-3 pl-3 flex flex-col gap-1 border-l-2 border-fill-highlight-100 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} />
+ <NotificationRow
+ key={child.id}
+ notification={child}
+ onNavigate={onNavigate}
+ readOnly={readOnly}
+ />
))}
</div>
)}
diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx
index 46696fccf1d6..451ccc0b57d7 100644
--- a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx
+++ b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx
@@ -1,8 +1,12 @@
import { useActions, useValues } from 'kea'
-import { IconCheckCircle } from '@posthog/icons'
+import { IconArchive, IconCheckCircle } from '@posthog/icons'
import { Tooltip } from '@posthog/lemon-ui'
+import {
+ NotificationActionButton,
+ ROW_ACTION_REVEAL_CLASSES,
+} from 'lib/components/NotificationsMenu/NotificationActionButton'
import { getNotificationDescriber } from 'lib/components/NotificationsMenu/notificationDescribers'
import { getNotificationIcon } from 'lib/components/NotificationsMenu/notificationToasts'
import { useAutoMarkRead } from 'lib/components/NotificationsMenu/useAutoMarkRead'
@@ -119,12 +123,15 @@ export function NotificationReadToggle({
export function NotificationRow({
notification,
onNavigate,
+ readOnly = false,
}: {
notification: InAppNotification
onNavigate?: () => void
+ readOnly?: boolean
}): JSX.Element {
- const { navigateToNotification, toggleRead, markAsRead } = useActions(sidePanelNotificationsLogic)
- const { projectNameForNotification, sourcePathForNotification, manuallyToggledIds } =
+ const { navigateToNotification, toggleRead, markAsRead, archiveNotification } =
+ useActions(sidePanelNotificationsLogic)
+ const { projectNameForNotification, sourcePathForNotification, manuallyToggledIds, archivingEnabled } =
useValues(sidePanelNotificationsLogic)
// Don't auto-mark a notification the user deliberately toggled this session — respect their intent.
@@ -154,6 +161,11 @@ export function NotificationRow({
toggleRead(notification.id)
}
+ const handleArchive = (e: React.MouseEvent): void => {
+ e.stopPropagation()
+ archiveNotification(notification.id)
+ }
+
const handleNavigate = (e: React.MouseEvent): void => {
e.stopPropagation()
handleOpen()
@@ -201,8 +213,16 @@ export function NotificationRow({
)}
</div>
</div>
- <div className="absolute bottom-1.5 right-1.5 opacity-0 transition-opacity group-hover/row:opacity-100">
- <NotificationReadToggle read={notification.read} onToggle={handleToggleRead} />
+ <div className={`absolute bottom-1.5 right-1.5 flex items-center gap-1 ${ROW_ACTION_REVEAL_CLASSES}`}>
+ {archivingEnabled && !readOnly && notification.archivable && (
+ <NotificationActionButton
+ icon={<IconArchive className="size-4" />}
+ tooltip="Archive"
+ onClick={handleArchive}
+ tone="danger"
+ />
+ )}
+ {!readOnly && <NotificationReadToggle read={notification.read} onToggle={handleToggleRead} />}
</div>
</div>
)
diff --git a/frontend/src/lib/components/NotificationsMenu/NotificationsPanel.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationsPanel.tsx
index e3d8d5204fd6..a8240661e4cf 100644
--- a/frontend/src/lib/components/NotificationsMenu/NotificationsPanel.tsx
+++ b/frontend/src/lib/components/NotificationsMenu/NotificationsPanel.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { IconNotification } from '@posthog/icons'
+import { IconArchive, IconArrowRight, IconNotification } from '@posthog/icons'
import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableShadows'
@@ -20,16 +20,28 @@ export function NotificationsPanel(): JSX.Element {
const { setActiveTab } = useActions(notificationsMenuLogic)
const {
groups,
+ archivedGroups,
+ archivedLoaded,
loadedUnreadCount,
inAppUnreadCount,
importantChangesLoading,
hasMoreNotifications,
+ hasMoreArchived,
isLoadingMore,
+ isLoadingMoreArchived,
+ hasArchivableNotifications,
+ archivingEnabled,
} = useValues(sidePanelNotificationsLogic)
- const { markAllAsRead, loadMoreNotifications } = useActions(sidePanelNotificationsLogic)
+ const { markAllAsRead, loadMoreNotifications, loadMoreArchived, archiveAll } =
+ useActions(sidePanelNotificationsLogic)
const { closePanel } = useActions(panelLayoutLogic)
- const filteredGroups = activeTab === 'unread' ? groups.filter((g: NotificationGroup) => g.has_unread) : groups
+ const isArchivedTab = archivingEnabled && activeTab === 'archived'
+ const filteredGroups = isArchivedTab
+ ? archivedGroups
+ : activeTab === 'unread'
+ ? groups.filter((g: NotificationGroup) => g.has_unread)
+ : groups
const header = (
<div className="flex items-center gap-2 flex-1 min-w-0">
@@ -56,10 +68,15 @@ export function NotificationsPanel(): JSX.Element {
<span className="ml-1 text-[10px] text-danger font-bold">{loadedUnreadCount}</span>
)}
</button>
+ {isArchivedTab && (
+ <span className="px-2 py-1 text-xs font-medium rounded bg-fill-highlight-100 text-primary">
+ Archived
+ </span>
+ )}
</div>
{/* Only surface "Mark all read" when unread items sit on not-yet-loaded pages — the ones
already loaded get cleared by the 3s auto-mark-on-view as the user scrolls. */}
- {hasMoreNotifications && inAppUnreadCount > loadedUnreadCount && (
+ {!isArchivedTab && hasMoreNotifications && inAppUnreadCount > loadedUnreadCount && (
<LemonButton
size="xsmall"
type="secondary"
@@ -73,30 +90,73 @@ export function NotificationsPanel(): JSX.Element {
</div>
)
+ const panelActions =
+ !archivingEnabled || isArchivedTab
+ ? undefined
+ : [
+ {
+ 'data-attr': 'notifications-view-archived',
+ onClick: () => setActiveTab('archived'),
+ children: (
+ <>
+ <IconArrowRight />
+ View archived
+ </>
+ ),
+ },
+ hasArchivableNotifications
+ ? {
+ 'data-attr': 'notifications-archive-all',
+ onClick: () => archiveAll(),
+ children: (
+ <>
+ <IconArchive />
+ Archive all
+ </>
+ ),
+ }
+ : null,
+ ]
+
return (
- <PanelLayoutPanel searchField={header}>
+ <PanelLayoutPanel searchField={header} panelActionsNewSceneLayout={panelActions}>
<ScrollableShadows
direction="vertical"
styledScrollbars
className="flex-1 overflow-hidden"
innerClassName="p-1"
>
- {importantChangesLoading && groups.length === 0 ? (
+ {(isArchivedTab ? !archivedLoaded : importantChangesLoading && groups.length === 0) ? (
<div className="p-2">
<LemonSkeleton className="h-10 my-1" repeat={5} fade />
</div>
) : filteredGroups.length > 0 ? (
<>
- <div className="flex flex-col gap-1">
+ <div className="flex flex-col gap-px">
{filteredGroups.map((group: NotificationGroup) => (
<NotificationGroupRow
key={group.group_key}
group={group}
onNavigate={() => closePanel()}
+ readOnly={isArchivedTab}
/>
))}
</div>
- {hasMoreNotifications && activeTab === 'all' && (
+ {isArchivedTab && hasMoreArchived && (
+ <div className="p-2">
+ <LemonButton
+ type="secondary"
+ fullWidth
+ center
+ size="small"
+ loading={isLoadingMoreArchived}
+ onClick={() => loadMoreArchived()}
+ >
+ Load more
+ </LemonButton>
+ </div>
+ )}
+ {!isArchivedTab && hasMoreNotifications && activeTab === 'all' && (
<div className="p-2">
<LemonButton
type="secondary"
@@ -115,7 +175,11 @@ export function NotificationsPanel(): JSX.Element {
<div className="flex flex-col items-center justify-center p-6 text-center">
<IconNotification className="size-8 text-muted mb-2" />
<span className="text-sm text-secondary">
- {activeTab === 'unread' ? "You're all caught up!" : 'No notifications yet'}
+ {isArchivedTab
+ ? 'No archived notifications'
+ : activeTab === 'unread'
+ ? "You're all caught up!"
+ : 'No notifications yet'}
</span>
</div>
)}
diff --git a/frontend/src/lib/components/NotificationsMenu/notificationsMenuLogic.tsx b/frontend/src/lib/components/NotificationsMenu/notificationsMenuLogic.tsx
index 946190841175..951033c01fd5 100644
--- a/frontend/src/lib/components/NotificationsMenu/notificationsMenuLogic.tsx
+++ b/frontend/src/lib/components/NotificationsMenu/notificationsMenuLogic.tsx
@@ -1,15 +1,21 @@
import { actions, connect, kea, listeners, path, reducers } from 'kea'
+import { sidePanelNotificationsLogic } from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic'
import { panelLayoutLogic } from '~/layout/panel-layout/panelLayoutLogic'
import type { notificationsMenuLogicType } from './notificationsMenuLogicType'
-export type NotificationTab = 'all' | 'unread'
+export type NotificationTab = 'all' | 'unread' | 'archived'
export const notificationsMenuLogic = kea<notificationsMenuLogicType>([
path(['lib', 'components', 'NotificationsMenu', 'notificationsMenuLogic']),
connect(() => ({
- actions: [panelLayoutLogic, ['setActivePanelIdentifier', 'showLayoutPanel']],
+ actions: [
+ sidePanelNotificationsLogic,
+ ['loadArchivedNotifications'],
+ panelLayoutLogic,
+ ['setActivePanelIdentifier', 'showLayoutPanel'],
+ ],
})),
actions({
setNotificationsMenuOpen: (isOpen: boolean) => ({ isOpen }),
@@ -35,6 +41,13 @@ export const notificationsMenuLogic = kea<notificationsMenuLogicType>([
],
}),
listeners(({ actions }) => ({
+ setActiveTab: ({ tab }) => {
+ // Archived notifications are a separate data source loaded on demand. Refetch every time
+ // the tab is opened so items just archived from the other tabs always show up.
+ if (tab === 'archived') {
+ actions.loadArchivedNotifications()
+ }
+ },
openToUnread: () => {
// The Notifications side panel's visibility is owned by panelLayoutLogic, so opening it
// (e.g. from a critical-notification toast button) has to go through these actions.
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 43206ae2c8d2..6718cedd12d2 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -262,6 +262,7 @@ export const FEATURE_FLAGS = {
CDP_NEW_PRICING: 'cdp-new-pricing', // owner: #team-workflows
CDP_PERSON_UPDATES: 'cdp-person-updates', // owner: #team-workflows-cdp
CDP_VERCEL_LOG_DRAIN: 'cdp-vercel-log-drain', // owner: #team-workflows-cdp
+ CLEARABLE_NOTIFICATIONS: 'clearable-notifications', // owner: @jordanm-posthog #team-web-analytics
COHORT_INLINE_CALCULATION: 'inline-cohort-calculation', // owner: #team-analytics-platform, inlines fast dynamic cohort queries instead of using precomputed cohortpeople table
COHORTS_TAXONOMIC_BASIC_LIST: 'cohorts-taxonomic-basic-list', // owner: @adamleith, picker sends ?basic=true to the cohorts list endpoint (trimmed payload: no filters/query/groups)
CONDENSED_FILTER_BAR: 'condensed_filter_bar', // owner: @jordanm-posthog #team-web-analytics
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 3d5b815761a0..79554cc376a0 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -472,6 +472,7 @@ export interface InAppNotification {
body: string
read: boolean
read_at: string | null
+ archivable: boolean
resource_type: string | null
resource_id: string
target_type: string
diff --git a/products/notifications/backend/facade/contracts.py b/products/notifications/backend/facade/contracts.py
index e92bae31e8ae..028b8fb0106e 100644
--- a/products/notifications/backend/facade/contracts.py
+++ b/products/notifications/backend/facade/contracts.py
@@ -31,5 +31,6 @@ class NotificationData:
source_type: SourceType | None = None
source_id: str | None = None
priority: Priority = Priority.NORMAL
+ archivable: bool = False
metadata: dict[str, Any] | None = None
resolver: RecipientsResolver | None = field(default=None, compare=False)
diff --git a/products/notifications/backend/logic.py b/products/notifications/backend/logic.py
index ac74170c75f6..f8856121de8a 100644
--- a/products/notifications/backend/logic.py
+++ b/products/notifications/backend/logic.py
@@ -39,6 +39,7 @@ def _publish_to_kafka(event: NotificationEvent) -> None:
"source_url": event.source_url,
"source_type": event.source_type,
"source_id": event.source_id,
+ "archivable": event.archivable,
"resolved_user_ids": event.resolved_user_ids,
"created_at": event.created_at.isoformat(),
},
@@ -215,6 +216,7 @@ def create_notification(data: NotificationData) -> NotificationEvent | None:
source_id=data.source_id,
target_type=data.target_type,
target_id=data.target_id,
+ archivable=data.archivable,
resolved_user_ids=resolved_user_ids,
metadata=data.metadata,
)
diff --git a/products/notifications/backend/migrations/0017_notificationevent_archivable_notificationarchivestate.py b/products/notifications/backend/migrations/0017_notificationevent_archivable_notificationarchivestate.py
new file mode 100644
index 000000000000..f0a946a51272
--- /dev/null
+++ b/products/notifications/backend/migrations/0017_notificationevent_archivable_notificationarchivestate.py
@@ -0,0 +1,62 @@
+# Generated by Django 5.2.14 on 2026-06-11 15:45
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("notifications", "0016_alter_notificationevent_notification_type"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="notificationevent",
+ name="archivable",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ migrations.CreateModel(
+ name="NotificationArchiveState",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "notification_event",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="archive_states",
+ to="notifications.notificationevent",
+ ),
+ ),
+ (
+ "user",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="notification_archive_states",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("notification_event", "user"),
+ name="unique_archive_state_per_user",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/notifications/backend/migrations/max_migration.txt b/products/notifications/backend/migrations/max_migration.txt
index e3841da58bdf..7d36f23444ee 100644
--- a/products/notifications/backend/migrations/max_migration.txt
+++ b/products/notifications/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0016_alter_notificationevent_notification_type
+0017_notificationevent_archivable_notificationarchivestate
diff --git a/products/notifications/backend/models.py b/products/notifications/backend/models.py
index b85412d392bf..f17823ef3c3a 100644
--- a/products/notifications/backend/models.py
+++ b/products/notifications/backend/models.py
@@ -20,6 +20,7 @@ class NotificationEvent(UUIDModel):
target_type = models.CharField(max_length=16, choices=[(t.value, t.name) for t in TargetType])
target_id = models.CharField(max_length=64)
resolved_user_ids = models.JSONField(default=list)
+ archivable = models.BooleanField(default=False, db_default=False)
metadata = models.JSONField(null=True, blank=True, default=None)
created_at = models.DateTimeField(auto_now_add=True)
@@ -50,3 +51,26 @@ class NotificationReadState(UUIDModel):
name="unique_read_state_per_user",
),
]
+
+
+class NotificationArchiveState(UUIDModel):
+ notification_event = models.ForeignKey(
+ NotificationEvent,
+ on_delete=models.CASCADE,
+ related_name="archive_states",
+ )
+ user = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.CASCADE,
+ db_constraint=False,
+ related_name="notification_archive_states",
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=["notification_event", "user"],
+ name="unique_archive_state_per_user",
+ ),
+ ]
diff --git a/products/notifications/backend/presentation/serializers.py b/products/notifications/backend/presentation/serializers.py
index 9e5355f43988..b4cedd985bdc 100644
--- a/products/notifications/backend/presentation/serializers.py
+++ b/products/notifications/backend/presentation/serializers.py
@@ -19,6 +19,10 @@ class NotificationEventSerializer(serializers.Serializer):
body = serializers.CharField()
read = serializers.BooleanField()
read_at = serializers.DateTimeField(allow_null=True)
+ archivable = serializers.BooleanField(
+ help_text="Whether this notification opted in to being archived (dismissed) by the recipient. "
+ "When false, the notification only supports read/unread."
+ )
target_type = serializers.CharField()
target_id = serializers.CharField()
resource_type = serializers.CharField(allow_null=True)
diff --git a/products/notifications/backend/presentation/views.py b/products/notifications/backend/presentation/views.py
index 1bd44c456d54..e8d9b8e36b43 100644
--- a/products/notifications/backend/presentation/views.py
+++ b/products/notifications/backend/presentation/views.py
@@ -22,7 +22,7 @@ from posthog.rbac.user_access_control import UserAccessControl
from products.notifications.backend.cache import get_unread_count, invalidate_unread_count, set_unread_count
from products.notifications.backend.facade.enums import AC_RESOURCE_TYPES
-from products.notifications.backend.models import NotificationEvent, NotificationReadState
+from products.notifications.backend.models import NotificationArchiveState, NotificationEvent, NotificationReadState
from products.notifications.backend.presentation.serializers import NotificationEventSerializer
_BULK_NOTIFICATION_IDS_MAX = 500
@@ -90,6 +90,12 @@ class NotificationsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
user_id=user.id,
).values("created_at")[:1]
),
+ archived=Exists(
+ NotificationArchiveState.objects.filter(
+ notification_event_id=OuterRef("id"),
+ user_id=user.id,
+ )
+ ),
)
.order_by("-created_at")
)
@@ -199,13 +205,22 @@ class NotificationsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
required=False,
description="ISO 8601 timestamp; only events strictly before this time",
),
+ OpenApiParameter(
+ name="archived",
+ type=bool,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="When true, return only notifications the recipient has archived; "
+ "otherwise return only non-archived notifications (the default)",
+ ),
]
)
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()
+ archived = request.query_params.get("archived", "").lower() in ("true", "1")
+ queryset = self._get_base_queryset().filter(archived=archived)
queryset = self._apply_filters(queryset, request)
queryset = self._filter_by_access_control(queryset)
page = self.paginate_queryset(queryset)
@@ -224,7 +239,7 @@ class NotificationsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
org_id = self.team.organization_id
count = get_unread_count(user.id, org_id)
if count is None:
- queryset = self._get_base_queryset()
+ queryset = self._get_base_queryset().filter(archived=False)
queryset = self._filter_by_access_control(queryset)
count = queryset.filter(read=False).count()
set_unread_count(user.id, org_id, count)
@@ -237,7 +252,7 @@ class NotificationsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
return Response({"status": "ok"})
user = self._get_user()
- queryset = self._get_base_queryset().filter(read=False)
+ queryset = self._get_base_queryset().filter(read=False, archived=False)
event_ids = list(queryset.values_list("id", flat=True))
if event_ids:
read_states = [NotificationReadState(notification_event_id=eid, user=user) for eid in event_ids]
@@ -340,3 +355,56 @@ class NotificationsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
).delete()
invalidate_unread_count(user.id, self.team.organization_id)
return Response({"updated": len(eligible_ids)})
+
+ @extend_schema(request=None)
+ @action(methods=["POST"], detail=True, url_path="archive")
+ def archive(self, request: Request, **kwargs) -> Response:
+ if not self._is_feature_enabled():
+ return Response({"status": "ok"})
+
+ user = self._get_user()
+ event = self._get_recipient_event_or_404()
+ if event.archivable:
+ NotificationArchiveState.objects.get_or_create(notification_event=event, user=user)
+ 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="archive_bulk")
+ def archive_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})
+
+ 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],
+ archivable=True,
+ ).values_list("id", flat=True)
+ )
+ if eligible_ids:
+ archive_states = [NotificationArchiveState(notification_event_id=eid, user=user) for eid in eligible_ids]
+ NotificationArchiveState.objects.bulk_create(archive_states, ignore_conflicts=True)
+ invalidate_unread_count(user.id, self.team.organization_id)
+ return Response({"updated": len(eligible_ids)})
+
+ @extend_schema(request=None)
+ @action(methods=["POST"], detail=False, url_path="archive_all")
+ def archive_all(self, request: Request, **kwargs) -> Response:
+ if not self._is_feature_enabled():
+ return Response({"updated": 0})
+
+ user = self._get_user()
+ queryset = self._get_base_queryset().filter(archivable=True, archived=False)
+ event_ids = list(queryset.values_list("id", flat=True))
+ if event_ids:
+ archive_states = [NotificationArchiveState(notification_event_id=eid, user=user) for eid in event_ids]
+ NotificationArchiveState.objects.bulk_create(archive_states, ignore_conflicts=True)
+ invalidate_unread_count(user.id, self.team.organization_id)
+ return Response({"updated": len(event_ids)})
diff --git a/products/notifications/backend/tests/test_api.py b/products/notifications/backend/tests/test_api.py
index 8bb110226e8c..f78fb4543e99 100644
--- a/products/notifications/backend/tests/test_api.py
+++ b/products/notifications/backend/tests/test_api.py
@@ -12,7 +12,7 @@ from rest_framework.test import APIClient
from posthog.models import Organization, Team, User
from products.notifications.backend.cache import _unread_count_cache_key
-from products.notifications.backend.models import NotificationEvent, NotificationReadState
+from products.notifications.backend.models import NotificationArchiveState, NotificationEvent, NotificationReadState
class TestNotificationsAPI(BaseTest):
@@ -420,6 +420,140 @@ class TestNotificationsAPI(BaseTest):
)
assert resp.status_code == 400
+ def _create_archivable(self, title: str = "Archivable") -> NotificationEvent:
+ return NotificationEvent.objects.create(
+ organization=self.organization,
+ team=self.team,
+ notification_type="alert_firing",
+ title=title,
+ body="",
+ target_type="user",
+ target_id=str(self.user.id),
+ resolved_user_ids=[self.user.id],
+ archivable=True,
+ )
+
+ def test_serializer_exposes_archivable(self):
+ self._create_archivable()
+ resp = self.client.get(f"/api/environments/{self.team.id}/notifications/")
+ by_title = {r["title"]: r for r in resp.json()["results"]}
+ assert by_title["Archivable"]["archivable"] is True
+ assert by_title["Test notification"]["archivable"] is False
+
+ def test_archive_archivable_notification(self):
+ event = self._create_archivable()
+ resp = self.client.post(f"/api/environments/{self.team.id}/notifications/{event.id}/archive/")
+ assert resp.status_code == 200
+ assert NotificationArchiveState.objects.filter(notification_event=event, user=self.user).exists()
+
+ def test_archive_is_noop_for_non_archivable(self):
+ resp = self.client.post(f"/api/environments/{self.team.id}/notifications/{self.event.id}/archive/")
+ assert resp.status_code == 200
+ assert not NotificationArchiveState.objects.filter(notification_event=self.event, user=self.user).exists()
+
+ def test_archived_notification_excluded_from_list(self):
+ event = self._create_archivable()
+ NotificationArchiveState.objects.create(notification_event=event, user=self.user)
+ resp = self.client.get(f"/api/environments/{self.team.id}/notifications/")
+ ids = {r["id"] for r in resp.json()["results"]}
+ assert str(event.id) not in ids
+ assert str(self.event.id) in ids
+
+ def test_archived_list_returns_only_archived(self):
+ archived = self._create_archivable("Archived item")
+ NotificationArchiveState.objects.create(notification_event=archived, user=self.user)
+ active = self._create_archivable("Still active")
+ resp = self.client.get(f"/api/environments/{self.team.id}/notifications/?archived=true")
+ ids = {r["id"] for r in resp.json()["results"]}
+ assert str(archived.id) in ids
+ assert str(active.id) not in ids
+ assert str(self.event.id) not in ids
+
+ def test_archived_notification_excluded_from_unread_count(self):
+ event = self._create_archivable()
+ NotificationArchiveState.objects.create(notification_event=event, user=self.user)
+ resp = self.client.get(f"/api/environments/{self.team.id}/notifications/unread_count/")
+ assert resp.json()["count"] == 1
+
+ def test_archive_invalidates_cache(self):
+ event = self._create_archivable()
+ cache_key = _unread_count_cache_key(self.user.id, self.organization.id)
+ cache.set(cache_key, 5, 60)
+ self.client.post(f"/api/environments/{self.team.id}/notifications/{event.id}/archive/")
+ assert cache.get(cache_key) is None
+
+ def test_archive_bulk_only_archives_archivable(self):
+ archivable = self._create_archivable("Bulk archivable")
+ resp = self.client.post(
+ f"/api/environments/{self.team.id}/notifications/archive_bulk/",
+ {"notification_ids": [str(archivable.id), str(self.event.id)]},
+ format="json",
+ )
+ assert resp.status_code == 200
+ assert resp.json()["updated"] == 1
+ assert NotificationArchiveState.objects.filter(notification_event=archivable, user=self.user).exists()
+ assert not NotificationArchiveState.objects.filter(notification_event=self.event, user=self.user).exists()
+
+ def test_archive_bulk_skips_non_recipient(self):
+ other_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=[],
+ archivable=True,
+ )
+ resp = self.client.post(
+ f"/api/environments/{self.team.id}/notifications/archive_bulk/",
+ {"notification_ids": [str(other_event.id)]},
+ format="json",
+ )
+ assert resp.status_code == 200
+ assert resp.json()["updated"] == 0
+ assert not NotificationArchiveState.objects.filter(notification_event=other_event, user=self.user).exists()
+
+ def test_archive_detail_skips_non_recipient(self):
+ other_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=[],
+ archivable=True,
+ )
+ resp = self.client.post(f"/api/environments/{self.team.id}/notifications/{other_event.id}/archive/")
+ assert resp.status_code == 404
+ assert not NotificationArchiveState.objects.filter(notification_event=other_event, user=self.user).exists()
+
+ def test_archive_all_only_archives_archivable(self):
+ a1 = self._create_archivable("A1")
+ a2 = self._create_archivable("A2")
+ resp = self.client.post(f"/api/environments/{self.team.id}/notifications/archive_all/")
+ assert resp.status_code == 200
+ assert resp.json()["updated"] == 2
+ assert NotificationArchiveState.objects.filter(user=self.user).count() == 2
+ assert not NotificationArchiveState.objects.filter(notification_event=self.event, user=self.user).exists()
+ for ev in (a1, a2):
+ assert NotificationArchiveState.objects.filter(notification_event=ev, user=self.user).exists()
+
+ def test_archive_is_per_user(self):
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ event = self._create_archivable()
+ NotificationEvent.objects.filter(pk=event.pk).update(resolved_user_ids=[self.user.id, other_user.id])
+ self.client.post(f"/api/environments/{self.team.id}/notifications/{event.id}/archive/")
+
+ other_client = APIClient()
+ other_client.force_authenticate(user=other_user)
+ resp = other_client.get(f"/api/environments/{self.team.id}/notifications/")
+ ids = {r["id"] for r in resp.json()["results"]}
+ assert str(event.id) in ids
+
class TestNotificationsAPIFeatureFlagDisabled(BaseTest):
def setUp(self):
diff --git a/products/notifications/backend/tests/test_logic.py b/products/notifications/backend/tests/test_logic.py
index 3ff59bae868c..8908345dc66a 100644
--- a/products/notifications/backend/tests/test_logic.py
+++ b/products/notifications/backend/tests/test_logic.py
@@ -47,8 +47,27 @@ class TestCreateNotification(BaseTest):
assert event.resolved_user_ids == [self.user.id]
assert event.organization_id == self.organization.id
assert event.notification_type == "comment_mention"
+ assert event.archivable is False
assert NotificationEvent.objects.count() == 1
+ @patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=True)
+ @patch("products.notifications.backend.logic._publish_to_kafka")
+ def test_create_notification_archivable(self, mock_publish, mock_ff):
+ data = NotificationData(
+ team_id=self.team.id,
+ notification_type=NotificationType.COMMENT_MENTION,
+ title="Archivable notification",
+ body="Test body",
+ target_type=TargetType.USER,
+ target_id=str(self.user.id),
+ archivable=True,
+ )
+ event = create_notification(data)
+
+ assert event is not None
+ assert event.archivable is True
+ assert NotificationEvent.objects.get(id=event.id).archivable is True
+
@patch("products.notifications.backend.logic.posthoganalytics.feature_enabled", return_value=True)
@patch("products.notifications.backend.logic._publish_to_kafka")
def test_create_notification_for_organization(self, mock_publish, mock_ff):
diff --git a/products/notifications/frontend/generated/api.schemas.ts b/products/notifications/frontend/generated/api.schemas.ts
index c73edc69677f..94779ec6d436 100644
--- a/products/notifications/frontend/generated/api.schemas.ts
+++ b/products/notifications/frontend/generated/api.schemas.ts
@@ -50,6 +50,8 @@ export interface NotificationEventApi {
read: boolean
/** @nullable */
read_at: string | null
+ /** Whether this notification opted in to being archived (dismissed) by the recipient. When false, the notification only supports read/unread. */
+ archivable: boolean
target_type: string
target_id: string
/** @nullable */
@@ -85,6 +87,10 @@ export interface BulkNotificationIdsRequestApi {
}
export type NotificationsListParams = {
+ /**
+ * When true, return only notifications the recipient has archived; otherwise return only non-archived notifications (the default)
+ */
+ archived?: boolean
/**
* ISO 8601 timestamp; only events at or after this time
*/
diff --git a/products/notifications/frontend/generated/api.ts b/products/notifications/frontend/generated/api.ts
index 84e60c3beb66..447dcef7adba 100644
--- a/products/notifications/frontend/generated/api.ts
+++ b/products/notifications/frontend/generated/api.ts
@@ -41,6 +41,21 @@ export const notificationsList = async (
})
}
+export const getNotificationsArchiveCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/notifications/${id}/archive/`
+}
+
+export const notificationsArchiveCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getNotificationsArchiveCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getNotificationsMarkReadCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/notifications/${id}/mark_read/`
}
@@ -71,6 +86,34 @@ export const notificationsMarkUnreadCreate = async (
})
}
+export const getNotificationsArchiveAllCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/notifications/archive_all/`
+}
+
+export const notificationsArchiveAllCreate = async (projectId: string, options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getNotificationsArchiveAllCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getNotificationsArchiveBulkCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/notifications/archive_bulk/`
+}
+
+export const notificationsArchiveBulkCreate = async (
+ projectId: string,
+ bulkNotificationIdsRequestApi: BulkNotificationIdsRequestApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getNotificationsArchiveBulkCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(bulkNotificationIdsRequestApi),
+ })
+}
+
export const getNotificationsMarkAllReadCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/notifications/mark_all_read/`
}
diff --git a/products/notifications/frontend/generated/api.zod.ts b/products/notifications/frontend/generated/api.zod.ts
index 2cef6c8603b4..e622f5377ad5 100644
--- a/products/notifications/frontend/generated/api.zod.ts
+++ b/products/notifications/frontend/generated/api.zod.ts
@@ -9,6 +9,17 @@
*/
import * as zod from 'zod'
+export const notificationsArchiveBulkCreateBodyNotificationIdsMax = 500
+
+export const NotificationsArchiveBulkCreateBody = /* @__PURE__ */ zod.object({
+ notification_ids: zod
+ .array(zod.uuid())
+ .max(notificationsArchiveBulkCreateBodyNotificationIdsMax)
+ .describe(
+ 'UUIDs of notification events to mark in bulk (max 500). Events the user is not a recipient of are silently skipped.'
+ ),
+})
+
export const notificationsMarkReadBulkCreateBodyNotificationIdsMax = 500
export const NotificationsMarkReadBulkCreateBody = /* @__PURE__ */ zod.object({
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0cddbdf21ba1..07576d536fff 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -32795,6 +32795,8 @@ export namespace Schemas {
read: boolean;
/** @nullable */
read_at: string | null;
+ /** Whether this notification opted in to being archived (dismissed) by the recipient. When false, the notification only supports read/unread. */
+ archivable: boolean;
target_type: string;
target_id: string;
/** @nullable */
@@ -63761,6 +63763,10 @@ export namespace Schemas {
};
export type EnvironmentsNotificationsListParams = {
+ /**
+ * When true, return only notifications the recipient has archived; otherwise return only non-archived notifications (the default)
+ */
+ archived?: boolean;
/**
* ISO 8601 timestamp; only events at or after this time
*/
@@ -71221,6 +71227,10 @@ export namespace Schemas {
};
export type NotificationsListParams = {
+ /**
+ * When true, return only notifications the recipient has archived; otherwise return only non-archived notifications (the default)
+ */
+ archived?: boolean;
/**
* ISO 8601 timestamp; only events at or after this time
*/