: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(alerts): add alert type tabs and controls (#72306)
Matt Puaf92ed7fe73dd
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 20e08f609b86..221f6a7be26c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5231,13 +5231,17 @@ snapshots:scenes-app-aigateway--page--light:hash: v1.k794b7964.46e268c8c95189b2c120d6fafd639efb84a8700c5536e489c3f7e81f84ffb666.ZIHYAvfqLGq4DXFRUA5bvAayBpUSO6FmKj5R4OJpH4Ascenes-app-alerts--empty-state--dark:- hash: v1.k794b7964.e66f9962b3c5d120c82f545d716e07a7c9644e4fab36d2cc09fda6de6c410081.WPBfaj7sH1IFlap3aPqRbB2apbcD41QSyUUGYWKavCY+ hash: v1.k794b7964.b419d15fe1d77892d0bc6aa978baa0075f2b64e597b8b457b59daaf7d3268f1a.aIWM8EZJ8vEV7F2XucSkuXRwOe84IJEKVrSFrVSoyrMscenes-app-alerts--empty-state--light:- hash: v1.k794b7964.eaf84b29246ea9f44b4c2a4d8b4820dfffdfb11463c22ae71aa566b7e5ba2365.Pf6-wlII8xGri8slp1TFugyVBh3Cd6dwk4qVIElZg7E+ hash: v1.k794b7964.68282b46c2d253c95ece0fc855088e130c3866b9c96a857f3175656d4a2356e9.XxMMtzs1kUZ0vOjdqOnjR-2f5JG8O-CyjJlV37dGjN4scenes-app-alerts--list-view--dark:- hash: v1.k794b7964.d55cbfa35826b65769f114209c63c9404f7ea95ee2c84912cbdc907b9ce79006.mXilZnVvoV87E4EYbFGW36fSwZx3Ot84FOKnFJ82cv8+ hash: v1.k794b7964.4c020e0ebe744218e314df1ea31cd8de37bf7a02b3b809739c8f750b660666ed.YMrLxDq9FEQdAKC8xGXZC-oOT7jXWGUPF2TxasONlToscenes-app-alerts--list-view--light:- hash: v1.k794b7964.aa194b211ec00772d41862df4913e73047029cf01c7e75ed37169d3e6356627c.V_tvnWYMT2FcEc1F9lXQsAAQdZw15TWPff0YOrrI3Xc+ hash: v1.k794b7964.2725e031fe77d1eb8578762f3429cdc48bfcffe083a6864efa5c48cf77ff04b0.nblDx2dCBdOD9ws2ACxbDLVXCk0llg63ZLuDaV8eMmI+ scenes-app-alerts--log-alerts--dark:+ hash: v1.k794b7964.a40d931748bcafd0f7c04fc6c49b822be8354406f51a94a8dacf611bac3d2427.D3wB42FmYwzDpfwnYcqpL7RhNd1PlNBZU4LXJSaDf8s+ scenes-app-alerts--log-alerts--light:+ hash: v1.k794b7964.202760c4cc733d6ef4fee0ad7bee733d15f170e87ef01e64d481a954dcf5a0d3.iPzAqTj0a5NYLsyQjR4gZVE1hSbkWPJGXAD7oCjFCKQscenes-app-annotations--annotations--dark:hash: v1.k794b7964.ee361eed99f04232ba32af0b7b7e38eb803860ee2faee52e094cf4fd126c30b1.ljX92vC8uyiUAdMxYyoQCDb2U9lqekhny9AhNrfVLpgscenes-app-annotations--annotations--light:diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 8763dccaf720..0891eaf2d0c3 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -939,7 +939,7 @@ export const productUrls = {runId ? `/ai-observability/clusters/${encodeURIComponent(runId)}` : '/ai-observability/clusters',aiObservabilityCluster: (runId: string, clusterId: number | string): string =>`/ai-observability/clusters/${encodeURIComponent(runId)}/${clusterId}`,- alert: (alertId: string): string => `/alerts?alert_id=${alertId}`,+ alert: (alertId: string): string => `/alerts?alert_type=insights&alert_id=${alertId}`,alerts: (): string => '/alerts',businessKnowledge: (): string => '/business-knowledge',transformations: (): string => '/transformations',diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsxindex 7d793a39fccd..e6d4b746eb6e 100644--- a/frontend/src/scenes/sceneLogic.test.tsx+++ b/frontend/src/scenes/sceneLogic.test.tsx@@ -106,7 +106,7 @@ describe('sceneLogic', () => {})})- it('denies the alerts scene without insight access', async () => {+ it('does not blanket deny the combined alerts scene without insight access', async () => {const priorAppContext = window.POSTHOG_APP_CONTEXTtry {window.POSTHOG_APP_CONTEXT = {@@ -121,7 +121,7 @@ describe('sceneLogic', () => {await expectLogic(logic).toMatchValues({sceneId: Scene.Alerts,- activeSceneId: Scene.ErrorAccessDenied,+ activeSceneId: Scene.Alerts,})} finally {window.POSTHOG_APP_CONTEXT = priorAppContextdiff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex b207edc71810..1b3604eb47c8 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -323,8 +323,6 @@ export const sceneToAccessControlResourceType: Partial<Record<Scene, AccessContr[Scene.DashboardTemplateCopy]: AccessControlResourceType.Dashboard,// Insights- // TODO: Add an Alerts access control resource instead of inheriting Insight permissions.- [Scene.Alerts]: AccessControlResourceType.Insight,[Scene.Insight]: AccessControlResourceType.Insight,[Scene.SavedInsights]: AccessControlResourceType.Insight,diff --git a/products/alerts/frontend/AlertsScene.stories.tsx b/products/alerts/frontend/AlertsScene.stories.tsxindex 03af4161fc72..4048a1158c21 100644--- a/products/alerts/frontend/AlertsScene.stories.tsx+++ b/products/alerts/frontend/AlertsScene.stories.tsx@@ -1,5 +1,6 @@import { Meta, StoryObj } from '@storybook/react'+import { FEATURE_FLAGS } from 'lib/constants'import { App } from 'scenes/App'import { urls } from 'scenes/urls'@@ -12,6 +13,8 @@ import {InsightThresholdType,} from '~/queries/schema/schema-general'+import type { LogsAlertConfigurationApi } from 'products/logs/frontend/generated/api.schemas'+import { AlertType } from './types'const createdBy = {@@ -20,6 +23,7 @@ const createdBy = {distinct_id: 'storybook-user',first_name: 'Hedge Hog',email: '[email protected]',+ hedgehog_config: null,}const makeAlert = (overrides: Partial<AlertType>): AlertType =>@@ -85,6 +89,81 @@ const alerts: AlertType[] = [}),]+const logAlerts = [+ {+ id: '019abcde-1234-7000-8000-000000000101',+ name: 'Checkout errors',+ enabled: true,+ filters: { severityLevels: ['error'], serviceNames: ['checkout-api'] },+ threshold_count: 25,+ threshold_operator: 'above',+ window_minutes: 5,+ check_interval_minutes: 5,+ state: 'firing',+ evaluation_periods: 1,+ datapoints_to_alarm: 1,+ cooldown_minutes: 30,+ snooze_until: null,+ next_check_at: '2026-07-16T17:00:00Z',+ last_notified_at: '2026-07-16T16:55:00Z',+ last_checked_at: '2026-07-16T16:55:00Z',+ consecutive_failures: 0,+ last_error_message: null,+ state_timeline: [+ {+ start: '2026-07-15T17:00:00Z',+ end: '2026-07-16T16:30:00Z',+ state: 'not_firing',+ enabled: true,+ },+ {+ start: '2026-07-16T16:30:00Z',+ end: '2026-07-16T17:00:00Z',+ state: 'firing',+ enabled: true,+ },+ ],+ destination_types: ['slack'],+ first_enabled_at: '2026-07-10T15:00:00Z',+ created_at: '2026-07-10T14:45:00Z',+ created_by: createdBy,+ updated_at: '2026-07-16T16:55:00Z',+ },+ {+ id: '019abcde-1234-7000-8000-000000000102',+ name: 'No payment logs',+ enabled: true,+ filters: { serviceNames: ['payments-worker'] },+ threshold_count: 1,+ threshold_operator: 'below',+ window_minutes: 15,+ check_interval_minutes: 5,+ state: 'not_firing',+ evaluation_periods: 3,+ datapoints_to_alarm: 2,+ cooldown_minutes: 60,+ snooze_until: null,+ next_check_at: '2026-07-16T17:00:00Z',+ last_notified_at: null,+ last_checked_at: '2026-07-16T16:55:00Z',+ consecutive_failures: 0,+ last_error_message: null,+ state_timeline: [+ {+ start: '2026-07-15T17:00:00Z',+ end: '2026-07-16T17:00:00Z',+ state: 'not_firing',+ enabled: true,+ },+ ],+ destination_types: [],+ first_enabled_at: '2026-07-12T10:00:00Z',+ created_at: '2026-07-12T09:45:00Z',+ created_by: createdBy,+ updated_at: '2026-07-16T16:55:00Z',+ },+] satisfies LogsAlertConfigurationApi[]+const meta: Meta = {component: App,title: 'Scenes-App/Alerts',@@ -92,7 +171,8 @@ const meta: Meta = {layout: 'fullscreen',viewMode: 'story',mockDate: '2026-07-16',- pageUrl: urls.alerts(),+ pageUrl: `${urls.alerts()}?alert_type=insights`,+ featureFlags: [FEATURE_FLAGS.LOGS_ALERTING],testOptions: { viewport: { width: 1300, height: 900 } },},decorators: [@@ -119,3 +199,19 @@ export const EmptyState: Story = {}),],}++export const LogAlerts: Story = {+ parameters: {+ pageUrl: `${urls.alerts()}?alert_type=logs`,+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/logs/alerts/': [+ 200,+ { count: logAlerts.length, next: null, previous: null, results: logAlerts },+ ],+ },+ }),+ ],+}diff --git a/products/alerts/frontend/logic/alertsLogic.test.ts b/products/alerts/frontend/logic/alertsLogic.test.tsnew file mode 100644index 000000000000..49fce6e0099f--- /dev/null+++ b/products/alerts/frontend/logic/alertsLogic.test.ts@@ -0,0 +1,108 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'++import { AlertState } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { AlertType } from '../types'+import { alertsLogic } from './alertsLogic'++const alert = {+ id: 'alert-1',+ name: 'Checkout conversion dropped',+ calculation_interval: 'daily',+ condition: {},+ config: {},+ enabled: true,+ insight: { id: 1 },+ state: AlertState.NOT_FIRING,+ subscribed_users: [],+ threshold: { configuration: {} },+} as unknown as AlertType++describe('alertsLogic', () => {+ let deleteSpy: jest.SpyInstance+ let listSpy: jest.SpyInstance+ let updateSpy: jest.SpyInstance++ beforeEach(() => {+ initKeaTests()+ listSpy = jest.spyOn(api.alerts, 'list').mockResolvedValue({ results: [alert], count: 1 })+ })++ afterEach(() => {+ deleteSpy?.mockRestore()+ listSpy.mockRestore()+ updateSpy?.mockRestore()+ })++ it('deletes an alert and reloads the list', async () => {+ deleteSpy = jest.spyOn(api.alerts, 'delete').mockResolvedValue()++ const logic = alertsLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => logic.actions.deleteAlert(alert)).toFinishAllListeners()++ expect(deleteSpy).toHaveBeenCalledWith(alert.id)+ expect(listSpy).toHaveBeenCalledTimes(2)++ logic.unmount()+ })++ it('keeps the delete action disabled while deleting', async () => {+ let resolveDelete: () => void = () => {}+ const deletePromise = new Promise<void>((resolve) => {+ resolveDelete = resolve+ })+ deleteSpy = jest.spyOn(api.alerts, 'delete').mockReturnValue(deletePromise)++ const logic = alertsLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.deleteAlert(alert)+ expect(logic.values.deletingAlertIds).toEqual(new Set([alert.id]))++ resolveDelete()++ await expectLogic(logic).toFinishAllListeners().toMatchValues({ deletingAlertIds: new Set() })+ logic.unmount()+ })++ it('keeps the alert toggle loading and patches the latest alert list', async () => {+ let resolveUpdate: (updatedAlert: AlertType) => void = () => {}+ const updatePromise = new Promise<AlertType>((resolve) => {+ resolveUpdate = resolve+ })+ updateSpy = jest.spyOn(api.alerts, 'update').mockReturnValue(updatePromise)++ const logic = alertsLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.toggleAlertEnabled(alert)++ expect(updateSpy).toHaveBeenCalledWith(alert.id, { enabled: false })+ expect(logic.values.togglingAlertIds).toEqual(new Set([alert.id]))++ const alertFromNewerList = { ...alert, id: 'alert-2', name: 'Newer filtered result' }+ logic.actions.loadAlertsSuccess({ results: [alert, alertFromNewerList], count: 2 })++ resolveUpdate({ ...alert, enabled: false })++ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({+ alertsResponse: {+ results: [{ ...alert, enabled: false }, alertFromNewerList],+ count: 2,+ },+ togglingAlertIds: new Set(),+ })++ logic.unmount()+ })+})diff --git a/products/alerts/frontend/logic/alertsLogic.ts b/products/alerts/frontend/logic/alertsLogic.tsindex 47ec9b05ac7d..03ccc18e7950 100644--- a/products/alerts/frontend/logic/alertsLogic.ts+++ b/products/alerts/frontend/logic/alertsLogic.ts@@ -4,6 +4,7 @@ import { loaders } from 'kea-loaders'import { PaginationManual } from '@posthog/lemon-ui'import api from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { objectClean } from 'lib/utils/objects'import { AlertState } from '~/queries/schema/schema-general'@@ -35,14 +36,19 @@ export interface alertsLogicValues {}alertsResponseLoading: booleanalertsSortedByState: AlertType[]+ deletingAlertIds: Set<string>filters: AlertsFiltersisFiltering: booleanpage: numberpagination: PaginationManual+ togglingAlertIds: Set<string>}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface alertsLogicActions {+ deleteAlert: (alert: AlertType) => {+ alert: AlertType+ }loadAlerts: () => anyloadAlertsFailure: (error: string,@@ -64,12 +70,32 @@ export interface alertsLogicActions {}payload?: any}+ setAlertDeleting: (+ alertId: string,+ isDeleting: boolean+ ) => {+ alertId: string+ isDeleting: boolean+ }+ setAlertToggling: (+ alertId: string,+ isToggling: boolean+ ) => {+ alertId: string+ isToggling: boolean+ }setFilters: (filters: Partial<AlertsFilters>) => {filters: Partial<AlertsFilters>}setPage: (page: number) => {page: number}+ toggleAlertEnabled: (alert: AlertType) => {+ alert: AlertType+ }+ updateAlertInList: (alert: AlertType) => {+ alert: AlertType+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -87,19 +113,60 @@ export type alertsLogicType = MakeLogicType<alertsLogicValues, alertsLogicActionexport const alertsLogic = kea<alertsLogicType>([path(['lib', 'components', 'Alerts', 'alertsLogic']),-actions({setPage: (page: number) => ({ page }),setFilters: (filters: Partial<AlertsFilters>) => ({ filters }),+ setAlertToggling: (alertId: string, isToggling: boolean) => ({ alertId, isToggling }),+ deleteAlert: (alert: AlertType) => ({ alert }),+ setAlertDeleting: (alertId: string, isDeleting: boolean) => ({ alertId, isDeleting }),+ toggleAlertEnabled: (alert: AlertType) => ({ alert }),+ updateAlertInList: (alert: AlertType) => ({ alert }),}),reducers({+ alertsResponse: [+ { results: [], count: 0 } as { results: AlertType[]; count: number },+ {+ updateAlertInList: (state, { alert }) => ({+ ...state,+ results: state.results.map((currentAlert) => (currentAlert.id === alert.id ? alert : currentAlert)),+ }),+ },+ ],page: [1,{setPage: (_, { page }) => page,},],+ deletingAlertIds: [+ new Set<string>(),+ {+ setAlertDeleting: (state, { alertId, isDeleting }) => {+ const nextState = new Set(state)+ if (isDeleting) {+ nextState.add(alertId)+ } else {+ nextState.delete(alertId)+ }+ return nextState+ },+ },+ ],+ togglingAlertIds: [+ new Set<string>(),+ {+ setAlertToggling: (state, { alertId, isToggling }) => {+ const nextState = new Set(state)+ if (isToggling) {+ nextState.add(alertId)+ } else {+ nextState.delete(alertId)+ }+ return nextState+ },+ },+ ],filters: [DEFAULT_ALERTS_FILTERS,{@@ -165,6 +232,18 @@ export const alertsLogic = kea<alertsLogicType>([})),listeners(({ actions, values }) => ({+ deleteAlert: async ({ alert }) => {+ actions.setAlertDeleting(alert.id, true)+ try {+ await api.alerts.delete(alert.id)+ actions.loadAlerts()+ lemonToast.success(`${alert.name || 'Unnamed alert'} has been deleted`)+ } catch {+ lemonToast.error("Couldn't delete the alert. Try again.")+ } finally {+ actions.setAlertDeleting(alert.id, false)+ }+ },setPage: () => {actions.loadAlerts()},@@ -178,6 +257,17 @@ export const alertsLogic = kea<alertsLogicType>([actions.loadAlerts()}},+ toggleAlertEnabled: async ({ alert }) => {+ actions.setAlertToggling(alert.id, true)+ try {+ const updatedAlert = await api.alerts.update(alert.id, { enabled: !alert.enabled })+ actions.updateAlertInList(updatedAlert)+ } catch {+ lemonToast.error('Failed to update alert')+ } finally {+ actions.setAlertToggling(alert.id, false)+ }+ },})),afterMount(({ actions }) => actions.loadAlerts()),diff --git a/products/alerts/frontend/utils.test.ts b/products/alerts/frontend/utils.test.tsnew file mode 100644index 000000000000..081697bff50d--- /dev/null+++ b/products/alerts/frontend/utils.test.ts@@ -0,0 +1,40 @@+import { AlertsTab, getActiveAlertsTab } from './utils'++describe('getActiveAlertsTab', () => {+ it.each([+ {+ name: 'defaults to log alerts for a logs-only user',+ alertId: null,+ requestedTab: undefined,+ canViewInsightAlerts: false,+ canViewLogAlerts: true,+ expected: AlertsTab.LOGS,+ },+ {+ name: 'denies access when neither alert type is available',+ alertId: null,+ requestedTab: undefined,+ canViewInsightAlerts: false,+ canViewLogAlerts: false,+ expected: null,+ },+ {+ name: 'denies an insight alert deep link for a logs-only user',+ alertId: 'alert-id',+ requestedTab: undefined,+ canViewInsightAlerts: false,+ canViewLogAlerts: true,+ expected: null,+ },+ {+ name: 'falls back to insight alerts when log alerts are unavailable',+ alertId: null,+ requestedTab: AlertsTab.LOGS,+ canViewInsightAlerts: true,+ canViewLogAlerts: false,+ expected: AlertsTab.INSIGHTS,+ },+ ])('$name', ({ name: _, expected, ...state }) => {+ expect(getActiveAlertsTab(state)).toBe(expected)+ })+})diff --git a/products/alerts/frontend/utils.ts b/products/alerts/frontend/utils.tsnew file mode 100644index 000000000000..6639bf04220a--- /dev/null+++ b/products/alerts/frontend/utils.ts@@ -0,0 +1,51 @@+export enum AlertsTab {+ INSIGHTS = 'insights',+ LOGS = 'logs',+}++interface AlertsAccessState {+ alertId: string | null+ requestedTab: string | undefined+ canViewInsightAlerts: boolean+ canViewLogAlerts: boolean+}++interface AlertsTabsState {+ canViewInsightAlerts: boolean+ canViewLogAlerts: boolean+}++export function getActiveAlertsTab({+ alertId,+ requestedTab,+ canViewInsightAlerts,+ canViewLogAlerts,+}: AlertsAccessState): AlertsTab | null {+ if (alertId !== null) {+ return canViewInsightAlerts ? AlertsTab.INSIGHTS : null+ }+ if (requestedTab === AlertsTab.LOGS && canViewLogAlerts) {+ return AlertsTab.LOGS+ }+ if (canViewInsightAlerts) {+ return AlertsTab.INSIGHTS+ }+ if (canViewLogAlerts) {+ return AlertsTab.LOGS+ }+ return null+}++export function getAlertsTabs({+ canViewInsightAlerts,+ canViewLogAlerts,+}: AlertsTabsState): { key: AlertsTab; label: string }[] {+ const tabs: { key: AlertsTab; label: string }[] = []+ if (canViewInsightAlerts) {+ tabs.push({ key: AlertsTab.INSIGHTS, label: 'Insight alerts' })+ }+ if (canViewLogAlerts) {+ tabs.push({ key: AlertsTab.LOGS, label: 'Log alerts' })+ }+ return tabs+}diff --git a/products/alerts/frontend/views/Alerts.tsx b/products/alerts/frontend/views/Alerts.tsxindex 856028739688..9717766b620d 100644--- a/products/alerts/frontend/views/Alerts.tsx+++ b/products/alerts/frontend/views/Alerts.tsx@@ -1,202 +1,73 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'+import { Suspense } from 'react'-import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass'-import { LemonTag, Link, Tooltip } from '@posthog/lemon-ui'+import { LemonTabs, SpinnerOverlay } from '@posthog/lemon-ui'-import { pngHoggie } from 'lib/brand/hoggies'-import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'-import { TZLabel } from 'lib/components/TZLabel'-import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'-import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'-import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'+import { AccessDenied } from 'lib/components/AccessDenied'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { getAppContext } from 'lib/utils/getAppContext'+import { lazyWithRetry } from 'lib/utils/retryImport'import { urls } from 'scenes/urls'-import { ProductKey } from '~/queries/schema/schema-general'-import { AlertState } from '~/queries/schema/schema-general'+import { AccessControlLevel, AccessControlResourceType } from '~/types'-import { alertIntervalDisplayLabel } from 'products/alerts/frontend/logic/alertIntervalHelpers'--import { AlertsFiltersBar } from '../components/AlertsFiltersBar'-import { alertLogic } from '../logic/alertLogic'-import { alertsLogic } from '../logic/alertsLogic'import { AlertType } from '../types'-import { EditAlertModal } from './EditAlertModal'-import { AlertStateIndicator } from './ManageAlertsModal'+import { AlertsTab, getActiveAlertsTab, getAlertsTabs } from '../utils'++const InsightAlerts = lazyWithRetry(() =>+ import('./InsightAlerts').then((module) => ({+ default: module.InsightAlerts,+ }))+)-const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)+const LogsAlertingSection = lazyWithRetry(() =>+ import('products/logs/frontend/components/LogsAlerting/LogsAlertingSection').then((module) => ({+ default: module.LogsAlertingSection,+ }))+)interface AlertsProps {alertId: AlertType['id'] | null}+function hasEffectiveResourceAccess(resourceType: AccessControlResourceType): boolean {+ return getAppContext()?.effective_resource_access_control?.[resourceType] !== AccessControlLevel.None+}+export function Alerts({ alertId }: AlertsProps): JSX.Element {const { push } = useActions(router)- const logic = alertsLogic()- const { loadAlerts } = useActions(logic)- const { alertsSortedByState, alertsResponseLoading, pagination, alertsCount, isFiltering } = useValues(logic)+ const { searchParams } = useValues(router)+ const showLogAlerts = useFeatureFlag('LOGS_ALERTING')+ const canViewInsightAlerts = hasEffectiveResourceAccess(AccessControlResourceType.Insight)+ const canViewLogAlerts = showLogAlerts && hasEffectiveResourceAccess(AccessControlResourceType.Logs)- const { alert } = useValues(alertLogic({ alertId }))+ const activeTab = getActiveAlertsTab({+ alertId,+ requestedTab: typeof searchParams.alert_type === 'string' ? searchParams.alert_type : undefined,+ canViewInsightAlerts,+ canViewLogAlerts,+ })- const columns: LemonTableColumns<AlertType> = [- {- key: 'id',- width: 32,- },- {- title: 'Name',- dataIndex: 'name',- key: 'name',- render: function renderName(name: any, alert) {- return (- <>- <LemonTableLink- to={urls.alert(alert.id)}- className={alert.enabled ? '' : 'text-muted'}- title={- <div className="flex flex-row gap-3 items-center">- <div>{name}</div>- </div>- }- />- </>- )- },- },- {- title: 'Status',- dataIndex: 'state',- render: function renderStateIndicator(_, alert: AlertType) {- return alert.enabled ? <AlertStateIndicator alert={alert} /> : null- },- },- {- title: 'Interval',- dataIndex: 'calculation_interval',- key: 'calculation_interval',- render: function renderInterval(_, alert: AlertType) {- return <div className="whitespace-nowrap">{alertIntervalDisplayLabel(alert.calculation_interval)}</div>- },- },- {- title: 'Last checked',- sorter: true,- defaultSortOrder: -1,- dataIndex: 'last_checked_at',- render: function renderLastChecked(_, alert: AlertType) {- return (- <div className="whitespace-nowrap">- {alert.last_checked_at ? (- <TZLabel time={alert.last_checked_at} />- ) : (- <span className="text-muted">N/A</span>- )}- </div>- )- },- },- {- title: 'Last notified',- sorter: true,- defaultSortOrder: -1,- dataIndex: 'last_notified_at',- render: function renderLastModified(_, alert: AlertType) {- return (- <div className="whitespace-nowrap">- {alert.last_notified_at ? (- <TZLabel time={alert.last_notified_at} />- ) : (- <span className="text-muted">N/A</span>- )}- </div>- )- },- },- createdByColumn() as LemonTableColumn<AlertType, keyof AlertType | undefined>,- {- title: 'Insight',- dataIndex: 'insight',- key: 'insight',- render: function renderInsightLink(insight: any) {- return (- <LemonTableLink- to={urls.insightView(insight.short_id)}- title={- <Tooltip title={insight.name}>- <div>{insight.name || insight.derived_name}</div>- </Tooltip>- }- />- )- },- },- {- title: 'Enabled',- dataIndex: 'enabled',- key: 'enabled',- render: (enabled: any) =>- enabled ? <LemonTag type="success">ENABLED</LemonTag> : <LemonTag type="danger">DISABLED</LemonTag>,- },- ]+ if (activeTab === null) {+ return <AccessDenied />+ }- const isEmpty = alertsCount === 0 && !alertsResponseLoading && !isFiltering- // TODO: add info here to sign up for alerts early access- return (- <>- {isEmpty && (- <ProductIntroduction- productName="Alerts"- productKey={ProductKey.ALERTS}- thingName="alert"- description="Alerts enable you to monitor your insight and notify you when certain conditions are met."- isEmpty- customHog={HedgehogMagnifyingGlass}- actionElementOverride={- <span className="italic">- To get started, visit a <Link to={urls.insights()}>trends insight</Link>, visit the- 'Actions' in the sidebar and click 'Alerts'- </span>- }- mcpSurfaceKey="alerts.create"- />- )}+ const tabs = getAlertsTabs({ canViewInsightAlerts, canViewLogAlerts })- {alert && (- <EditAlertModal- onClose={() => push(urls.alerts())}- isOpen- alertId={alert.id}- insightShortId={alert.insight.short_id}- insightId={alert.insight.id}- insightLogicProps={{ dashboardItemId: alert.insight.short_id }}- onEditSuccess={() => {- loadAlerts()- push(urls.alerts())- }}- />- )}+ const switchTab = (tab: AlertsTab): void => {+ const nextSearchParams = { ...searchParams }+ delete nextSearchParams.alert_id+ nextSearchParams.alert_type = tab+ push(urls.alerts(), nextSearchParams)+ }- {isEmpty ? null : (- <>- <AlertsFiltersBar />- <LemonTable- loading={alertsResponseLoading}- columns={columns}- dataSource={alertsSortedByState}- noSortingCancellation- rowKey="id"- loadingSkeletonRows={5}- nouns={['alert', 'alerts']}- pagination={pagination}- rowClassName={(alert) => (alert.state === AlertState.NOT_FIRING ? null : 'highlighted')}- emptyState={- isFiltering ? (- <div className="py-8 text-center text-secondary">No alerts match your filters</div>- ) : undefined- }- />- </>- )}+ return (+ <>+ <LemonTabs<AlertsTab> activeKey={activeTab} onChange={switchTab} tabs={tabs} sceneInset />+ <Suspense fallback={<SpinnerOverlay />}>+ {activeTab === AlertsTab.LOGS ? <LogsAlertingSection /> : <InsightAlerts alertId={alertId} />}+ </Suspense></>)}diff --git a/products/alerts/frontend/views/InsightAlerts.tsx b/products/alerts/frontend/views/InsightAlerts.tsxnew file mode 100644index 000000000000..314c2630fdfb--- /dev/null+++ b/products/alerts/frontend/views/InsightAlerts.tsx@@ -0,0 +1,260 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'++import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass'+import { IconEllipsis } from '@posthog/icons'+import { LemonButton, LemonDialog, LemonSwitch, Link, Tooltip } from '@posthog/lemon-ui'++import { pngHoggie } from 'lib/brand/hoggies'+import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'+import { TZLabel } from 'lib/components/TZLabel'+import { LemonTable, LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'+import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from 'lib/ui/quill'+import { urls } from 'scenes/urls'++import { AlertState, ProductKey } from '~/queries/schema/schema-general'++import { AlertsFiltersBar } from '../components/AlertsFiltersBar'+import { alertIntervalDisplayLabel } from '../logic/alertIntervalHelpers'+import { alertLogic } from '../logic/alertLogic'+import { alertsLogic } from '../logic/alertsLogic'+import { AlertType } from '../types'+import { EditAlertModal } from './EditAlertModal'+import { AlertStateIndicator } from './ManageAlertsModal'++const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)++interface InsightAlertsProps {+ alertId: AlertType['id'] | null+}++export function InsightAlerts({ alertId }: InsightAlertsProps): JSX.Element {+ const { push } = useActions(router)+ const logic = alertsLogic()+ const { deleteAlert, loadAlerts, toggleAlertEnabled } = useActions(logic)+ const {+ alertsSortedByState,+ alertsResponseLoading,+ deletingAlertIds,+ pagination,+ alertsCount,+ isFiltering,+ togglingAlertIds,+ } = useValues(logic)++ const { alert } = useValues(alertLogic({ alertId }))++ const columns: LemonTableColumns<AlertType> = [+ {+ key: 'id',+ width: 32,+ },+ {+ title: 'Name',+ dataIndex: 'name',+ key: 'name',+ render: function renderName(name: any, alert) {+ return (+ <>+ <LemonTableLink+ to={urls.alert(alert.id)}+ className={alert.enabled ? '' : 'text-muted'}+ title={+ <div className="flex flex-row gap-3 items-center">+ <div>{name}</div>+ </div>+ }+ />+ </>+ )+ },+ },+ {+ title: 'Status',+ dataIndex: 'state',+ render: function renderStateIndicator(_, alert: AlertType) {+ return alert.enabled ? <AlertStateIndicator alert={alert} /> : null+ },+ },+ {+ title: 'Interval',+ dataIndex: 'calculation_interval',+ key: 'calculation_interval',+ render: function renderInterval(_, alert: AlertType) {+ return <div className="whitespace-nowrap">{alertIntervalDisplayLabel(alert.calculation_interval)}</div>+ },+ },+ {+ title: 'Last checked',+ sorter: true,+ defaultSortOrder: -1,+ dataIndex: 'last_checked_at',+ render: function renderLastChecked(_, alert: AlertType) {+ return (+ <div className="whitespace-nowrap">+ {alert.last_checked_at ? (+ <TZLabel time={alert.last_checked_at} />+ ) : (+ <span className="text-muted">N/A</span>+ )}+ </div>+ )+ },+ },+ {+ title: 'Last notified',+ sorter: true,+ defaultSortOrder: -1,+ dataIndex: 'last_notified_at',+ render: function renderLastModified(_, alert: AlertType) {+ return (+ <div className="whitespace-nowrap">+ {alert.last_notified_at ? (+ <TZLabel time={alert.last_notified_at} />+ ) : (+ <span className="text-muted">N/A</span>+ )}+ </div>+ )+ },+ },+ createdByColumn() as LemonTableColumn<AlertType, keyof AlertType | undefined>,+ {+ title: 'Insight',+ dataIndex: 'insight',+ key: 'insight',+ render: function renderInsightLink(insight: any) {+ return (+ <LemonTableLink+ to={urls.insightView(insight.short_id)}+ title={+ <Tooltip title={insight.name}>+ <div>{insight.name || insight.derived_name}</div>+ </Tooltip>+ }+ />+ )+ },+ },+ {+ title: 'Enabled',+ dataIndex: 'enabled',+ key: 'enabled',+ render: (_, alert) => (+ <LemonSwitch+ checked={alert.enabled}+ onChange={() => toggleAlertEnabled(alert)}+ loading={togglingAlertIds.has(alert.id)}+ aria-label={`${alert.enabled ? 'Disable' : 'Enable'} ${alert.name}`}+ data-attr="insight-alert-row-toggle"+ />+ ),+ },+ {+ title: '',+ render: (_, alert) => (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconEllipsis />}+ aria-label={`More options for ${alert.name}`}+ />+ }+ />+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ variant="destructive"+ data-attr="insight-alert-row-delete"+ disabled={deletingAlertIds.has(alert.id)}+ onClick={() => {+ LemonDialog.open({+ title: `Delete "${alert.name}"?`,+ description:+ 'This alert will be permanently deleted. This action cannot be undone.',+ primaryButton: {+ children: 'Delete',+ type: 'primary',+ status: 'danger',+ onClick: () => deleteAlert(alert),+ 'data-attr': 'insight-alert-delete-confirm',+ },+ secondaryButton: {+ children: 'Cancel',+ },+ })+ }}+ >+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ),+ },+ ]++ const isEmpty = alertsCount === 0 && !alertsResponseLoading && !isFiltering+ // TODO: add info here to sign up for alerts early access+ return (+ <>+ {isEmpty && (+ <ProductIntroduction+ productName="Alerts"+ productKey={ProductKey.ALERTS}+ thingName="alert"+ description="Alerts enable you to monitor your insight and notify you when certain conditions are met."+ isEmpty+ customHog={HedgehogMagnifyingGlass}+ actionElementOverride={+ <span className="italic">+ To get started, open a <Link to={urls.insights()}>saved insight</Link>, then select Alerts+ from the Actions sidebar.+ </span>+ }+ mcpSurfaceKey="alerts.create"+ />+ )}++ {alert && (+ <EditAlertModal+ onClose={() => push(urls.alerts())}+ isOpen+ alertId={alert.id}+ insightShortId={alert.insight.short_id}+ insightId={alert.insight.id}+ insightLogicProps={{ dashboardItemId: alert.insight.short_id }}+ onEditSuccess={() => {+ loadAlerts()+ push(urls.alerts())+ }}+ />+ )}++ {isEmpty ? null : (+ <>+ <AlertsFiltersBar />+ <LemonTable+ loading={alertsResponseLoading}+ columns={columns}+ dataSource={alertsSortedByState}+ noSortingCancellation+ rowKey="id"+ loadingSkeletonRows={5}+ nouns={['alert', 'alerts']}+ pagination={pagination}+ rowClassName={(alert) => (alert.state === AlertState.NOT_FIRING ? null : 'highlighted')}+ emptyState={+ isFiltering ? (+ <div className="py-8 text-center text-secondary">No alerts match your filters</div>+ ) : undefined+ }+ />+ </>+ )}+ </>+ )+}diff --git a/products/alerts/manifest.tsx b/products/alerts/manifest.tsxindex 59144f75e77f..2236bfdb4457 100644--- a/products/alerts/manifest.tsx+++ b/products/alerts/manifest.tsx@@ -15,7 +15,7 @@ export const manifest: ProductManifest = {'/alerts': ['Alerts', 'alerts'],},urls: {- alert: (alertId: string): string => `/alerts?alert_id=${alertId}`,+ alert: (alertId: string): string => `/alerts?alert_type=insights&alert_id=${alertId}`,alerts: (): string => '/alerts',},fileSystemTypes: {},diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.pyindex b793144c0a31..99779c09b48f 100644--- a/products/logs/backend/presentation/views/alerts_api.py+++ b/products/logs/backend/presentation/views/alerts_api.py@@ -9,7 +9,7 @@ from django.db.models import F, OuterRef, Prefetch, Q, QuerySet, Subqueryfrom django.shortcuts import get_object_or_404from django.utils import timezone-from drf_spectacular.utils import extend_schema, extend_schema_field+from drf_spectacular.utils import extend_schema, extend_schema_field, extend_schema_viewfrom pydantic import ValidationError as PydanticValidationErrorfrom rest_framework import serializers, viewsetsfrom rest_framework.decorators import action@@ -79,6 +79,15 @@ UNCAPPED_ALERT_TEAM_IDS: frozenset[int] = frozenset()MAX_SIMULATE_LOOKBACK_DAYS = 30MAX_SIMULATE_BUCKETS = 15_000+++class LogsAlertListQuerySerializer(serializers.Serializer):+ created_by = serializers.UUIDField(+ required=False,+ help_text="Only return log alerts created by the user with this UUID.",+ )++STATE_TIMELINE_LOOKBACK_HOURS = 24# Mirrors LogsAlertConfiguration.check_interval_minutes' default — used as the# simulate endpoint's default cadence so it matches production when callers@@ -805,6 +814,7 @@ def _fill_empty_buckets(return result+@extend_schema_view(list=extend_schema(parameters=[LogsAlertListQuerySerializer]))class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):scope_object = "logs"queryset = LogsAlertConfiguration.objects.all().order_by("-created_at")@@ -814,6 +824,13 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):permission_classes = [PostHogFeatureFlagPermission]def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:+ if self.action == "list":+ query_serializer = LogsAlertListQuerySerializer(data=self.request.query_params)+ query_serializer.is_valid(raise_exception=True)+ created_by = query_serializer.validated_data.get("created_by")+ if created_by:+ queryset = queryset.filter(created_by__uuid=created_by)+# Correlated subquery so list/retrieve can surface `last_error_message` in a# single round-trip instead of one extra query per alert.latest_error = (diff --git a/products/logs/backend/test/test_alerts_api.py b/products/logs/backend/test/test_alerts_api.pyindex 88e94230ec3c..dcc5448c83f7 100644--- a/products/logs/backend/test/test_alerts_api.py+++ b/products/logs/backend/test/test_alerts_api.py@@ -16,6 +16,7 @@ from posthog.cdp.templates.microsoft_teams.template_microsoft_teams import templfrom posthog.cdp.templates.slack.template_slack import template as template_slackfrom posthog.clickhouse.client import sync_executefrom posthog.models.team.team import Team+from posthog.models.user import Userfrom products.cdp.backend.models.hog_function_template import HogFunctionTemplatefrom products.cdp.backend.models.hog_functions.hog_function import HogFunction@@ -97,6 +98,27 @@ class TestLogsAlertAPI(APIBaseTest):assert results[0]["name"] == "Alert 2"assert results[1]["name"] == "Alert 1"+ def test_list_filters_by_created_by(self):+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ self._create_via_api(name="My alert")+ other_alert = LogsAlertConfiguration.objects.create(+ team=self.team,+ name="Other user's alert",+ threshold_count=5,+ created_by=other_user,+ filters={"severityLevels": ["error"]},+ )++ response = self.client.get(self.base_url, {"created_by": str(other_user.uuid)})++ assert response.status_code == status.HTTP_200_OK+ assert [result["id"] for result in response.json()["results"]] == [str(other_alert.id)]++ def test_list_rejects_invalid_created_by(self):+ response = self.client.get(self.base_url, {"created_by": "not-a-uuid"})++ assert response.status_code == status.HTTP_400_BAD_REQUEST+def test_retrieve(self):created = self._create_via_api()diff --git a/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx b/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsxindex 801fd902f929..8eb9dad2e327 100644--- a/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx+++ b/products/logs/frontend/components/LogsAlerting/LogsAlertList.tsx@@ -1,20 +1,30 @@import { useActions, useValues } from 'kea'-import { IconBell } from '@posthog/icons'+import { IconBell, IconEllipsis } from '@posthog/icons'import {LemonButton,LemonDialog,LemonSwitch,LemonTable,+ LemonTableColumn,LemonTableColumns,LemonTag,SpinnerOverlay,} from '@posthog/lemon-ui'+import { MemberSelect } from 'lib/components/MemberSelect'import { TZLabel } from 'lib/components/TZLabel'-import { More } from 'lib/lemon-ui/LemonButton/More'-import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'+import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'import { Tooltip } from 'lib/lemon-ui/Tooltip'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from 'lib/ui/quill'import { urls } from 'scenes/urls'import IconMicrosoftTeams from 'public/services/microsoft-teams.png'@@ -62,9 +72,10 @@ export function LogsAlertDestinationTags({}export function LogsAlertList(): JSX.Element {- const { alerts, alertsLoading, resettingAlertIds, creatingAlert } = useValues(logsAlertingLogic)+ const { alerts, alertsLoading, resettingAlertIds, creatingAlert, createdByFilter } = useValues(logsAlertingLogic)const {setEditingAlert,+ setCreatedByFilter,deleteAlert,toggleAlertEnabled,resetAlert,@@ -174,15 +185,10 @@ export function LogsAlertList(): JSX.Element {)},},- {- title: 'Created by',- dataIndex: 'created_by',- render: (_, alert) => (- <span className="text-muted text-xs">- {alert.created_by?.first_name || alert.created_by?.email || '—'}- </span>- ),- },+ createdByColumn() as unknown as LemonTableColumn<+ LogsAlertConfigurationApi,+ keyof LogsAlertConfigurationApi | undefined+ >,{title: 'Enabled',dataIndex: 'enabled',@@ -201,69 +207,75 @@ export function LogsAlertList(): JSX.Element {},{title: '',- render: (_, alert) => (- <More- overlay={- <LemonMenuOverlay- items={[- {- label: 'Edit',- onClick: () => setEditingAlert(alert),- },- {- label: 'View history',- onClick: () => setViewingHistoryAlert(alert),- },- alert.state === LogsAlertConfigurationStateEnumApi.Snoozed- ? {- label: 'Unsnooze',- onClick: () => unsnoozeAlert(alert.id),- }- : {- label: 'Snooze',- items: SNOOZE_DURATIONS.map((d) => ({- label: d.label,- onClick: () => snoozeAlert(alert.id, d.minutes),- })),- },- ...(alert.state === LogsAlertConfigurationStateEnumApi.Broken- ? [- {- label: resettingAlertIds.has(alert.id) ? 'Resetting…' : 'Reset alert',- onClick: () => resetAlert(alert.id),- disabledReason: resettingAlertIds.has(alert.id)- ? 'Reset in progress'- : undefined,- },- ]- : []),- {- 'data-attr': 'logs-alert-row-delete',- label: 'Delete',- status: 'danger',- onClick: () => {- LemonDialog.open({- title: `Delete "${alert.name}"?`,- description:- 'This alert will be permanently deleted. This action cannot be undone.',- primaryButton: {- children: 'Delete',- type: 'primary',- status: 'danger',- onClick: () => deleteAlert(alert.id),- 'data-attr': 'logs-alert-delete-confirm',- },- secondaryButton: {- children: 'Cancel',- },- })- },- },- ]}+ render: (_, alert) => {+ const isResetting = resettingAlertIds.has(alert.id)++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconEllipsis />}+ aria-label={`More options for ${alert.name}`}+ />+ }/>- }- />- ),+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => setEditingAlert(alert)}>Edit</DropdownMenuItem>+ <DropdownMenuItem onClick={() => setViewingHistoryAlert(alert)}>+ View history+ </DropdownMenuItem>+ {alert.state === LogsAlertConfigurationStateEnumApi.Snoozed ? (+ <DropdownMenuItem onClick={() => unsnoozeAlert(alert.id)}>Unsnooze</DropdownMenuItem>+ ) : (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>Snooze</DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ {SNOOZE_DURATIONS.map((duration) => (+ <DropdownMenuItem+ key={duration.minutes}+ onClick={() => snoozeAlert(alert.id, duration.minutes)}+ >+ {duration.label}+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )}+ {alert.state === LogsAlertConfigurationStateEnumApi.Broken ? (+ <DropdownMenuItem disabled={isResetting} onClick={() => resetAlert(alert.id)}>+ {isResetting ? 'Resetting…' : 'Reset alert'}+ </DropdownMenuItem>+ ) : null}+ <DropdownMenuItem+ variant="destructive"+ data-attr="logs-alert-row-delete"+ onClick={() => {+ LemonDialog.open({+ title: `Delete "${alert.name}"?`,+ description:+ 'This alert will be permanently deleted. This action cannot be undone.',+ primaryButton: {+ children: 'Delete',+ type: 'primary',+ status: 'danger',+ onClick: () => deleteAlert(alert.id),+ 'data-attr': 'logs-alert-delete-confirm',+ },+ secondaryButton: {+ children: 'Cancel',+ },+ })+ }}+ >+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )+ },},]@@ -273,7 +285,11 @@ export function LogsAlertList(): JSX.Element {return (<div className="space-y-2">- <div className="flex justify-end">+ <div className="flex justify-end gap-2 flex-wrap">+ <div className="flex items-center gap-2">+ <span>Created by:</span>+ <MemberSelect value={createdByFilter} onChange={(user) => setCreatedByFilter(user?.uuid ?? null)} />+ </div><LemonButtontype="primary"size="small"@@ -289,7 +305,7 @@ export function LogsAlertList(): JSX.Element {dataSource={alerts}rowKey="id"loading={alertsLoading}- emptyState="No alerts configured yet."+ emptyState={createdByFilter ? 'No alerts match this filter.' : 'No alerts configured yet.'}size="small"pagination={{ pageSize: 30 }}nouns={['alert', 'alerts']}diff --git a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.tsindex ef256d51c7d3..6c2eab2b2a6a 100644--- a/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts+++ b/products/logs/frontend/components/LogsAlerting/__tests__/logsAlertingLogic.test.ts@@ -1,7 +1,11 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'+import { expectLogic } from 'kea-test-utils'import { lemonToast } from '@posthog/lemon-ui'+import { teamLogic } from 'scenes/teamLogic'+import { initKeaTests } from '~/test/init'import { logsAlertsList, logsAlertsResetCreate } from 'products/logs/frontend/generated/api'@@ -28,6 +32,14 @@ jest.mock('@posthog/lemon-ui', () => ({const mockReset = logsAlertsResetCreate as jest.MockedFunction<typeof logsAlertsResetCreate>const mockList = logsAlertsList as jest.MockedFunction<typeof logsAlertsList>+function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {+ let resolve!: (value: T) => void+ const promise = new Promise<T>((resolvePromise) => {+ resolve = resolvePromise+ })+ return { promise, resolve }+}+describe('logsAlertingLogic', () => {beforeEach(() => {initKeaTests()@@ -35,6 +47,80 @@ describe('logsAlertingLogic', () => {mockList.mockResolvedValue({ results: [] } as any)})+ describe('createdByFilter', () => {+ it('reloads alerts with the selected creator UUID', async () => {+ const logic = logsAlertingLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ mockList.mockClear()++ await expectLogic(logic, () => {+ logic.actions.setCreatedByFilter('019abcde-1234-7000-8000-000000000001')+ }).toFinishAllListeners()++ expect(mockList).toHaveBeenCalledWith(expect.any(String), {+ limit: 500,+ created_by: '019abcde-1234-7000-8000-000000000001',+ })++ logic.unmount()+ })++ it('clears the selected creator when the project changes', async () => {+ const logic = logsAlertingLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.setCreatedByFilter('019abcde-1234-7000-8000-000000000001')+ }).toFinishAllListeners()+ mockList.mockClear()++ const nextTeamId = MOCK_DEFAULT_TEAM.id + 1+ await expectLogic(logic, () => {+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, id: nextTeamId })+ })+ .toFinishAllListeners()+ .toMatchValues({ createdByFilter: null })++ expect(mockList).toHaveBeenCalledWith(String(nextTeamId), { limit: 500 })++ logic.unmount()+ })++ it('discards alerts returned for the previous project', async () => {+ const logic = logsAlertingLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ const previousProjectResponse = deferred<Awaited<ReturnType<typeof logsAlertsList>>>()+ const currentProjectAlerts = [{ id: 'current-project-alert' }] as any+ const nextTeamId = MOCK_DEFAULT_TEAM.id + 1+ mockList.mockImplementation((projectId) => {+ if (projectId === String(MOCK_DEFAULT_TEAM.id)) {+ return previousProjectResponse.promise+ }+ return Promise.resolve({ results: currentProjectAlerts } as any)+ })+ await expectLogic(logic, () => {+ logic.actions.setCreatedByFilter('019abcde-1234-7000-8000-000000000001')+ }).toDispatchActions(['loadAlerts'])++ await expectLogic(logic, () => {+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, id: nextTeamId })+ }).toDispatchActions(['loadAlerts', 'loadAlertsSuccess'])+ expect(logic.values.alerts).toEqual(currentProjectAlerts)++ previousProjectResponse.resolve({ results: [{ id: 'previous-project-alert' }] } as any)+ await Promise.resolve()+ await Promise.resolve()++ expect(logic.values.alerts).toEqual(currentProjectAlerts)++ logic.unmount()+ })+ })+describe('resetAlert', () => {it('calls the reset endpoint, reloads the list, and surfaces a success toast', async () => {mockReset.mockResolvedValue(undefined as any)diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.tsindex f28f2101fdc5..0969b7249c1b 100644--- a/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts+++ b/products/logs/frontend/components/LogsAlerting/logsAlertFormLogic.ts@@ -105,7 +105,7 @@ export interface logsAlertFormLogicActions {createPendingHogFunctions: (alertId: string) => {alertId: string} // logsAlertNotificationLogic- loadAlerts: () => any // logsAlertingLogic+ loadAlerts: (_?: any) => any // logsAlertingLogicsetEditingAlert: (alert: LogsAlertConfigurationApi | null) => {alert: LogsAlertConfigurationApi | null} // logsAlertingLogicdiff --git a/products/logs/frontend/components/LogsAlerting/logsAlertingLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertingLogic.tsindex 0800ede1d0d1..fc23f1f7fe0d 100644--- a/products/logs/frontend/components/LogsAlerting/logsAlertingLogic.ts+++ b/products/logs/frontend/components/LogsAlerting/logsAlertingLogic.ts@@ -1,6 +1,7 @@import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'import { loaders } from 'kea-loaders'import { router } from 'kea-router'+import { subscriptions } from 'kea-subscriptions'import { lemonToast } from '@posthog/lemon-ui'@@ -26,6 +27,7 @@ export interface logsAlertingLogicValues {currentTeamId: number | null // teamLogicalerts: LogsAlertConfigurationApi[]alertsLoading: boolean+ createdByFilter: string | nullcreatingAlert: booleaneditingAlert: LogsAlertConfigurationApi | nullisCreating: boolean@@ -41,7 +43,7 @@ export interface logsAlertingLogicActions {deleteAlert: (id: string) => {id: string}- loadAlerts: () => any+ loadAlerts: (_?: any) => anyloadAlertsFailure: (error: string,errorObject?: any@@ -59,6 +61,9 @@ export interface logsAlertingLogicActions {resetAlert: (id: string) => {id: string}+ setCreatedByFilter: (createdByFilter: string | null) => {+ createdByFilter: string | null+ }setCreatingAlert: (creating: boolean) => {creating: boolean}@@ -104,6 +109,7 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([actions({setEditingAlert: (alert: LogsAlertConfigurationApi | null) => ({ alert }),+ setCreatedByFilter: (createdByFilter: string | null) => ({ createdByFilter }),setIsCreating: (isCreating: boolean) => ({ isCreating }),deleteAlert: (id: string) => ({ id }),toggleAlertEnabled: (alert: LogsAlertConfigurationApi) => ({ alert }),@@ -117,6 +123,12 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([}),reducers({+ createdByFilter: [+ null as string | null,+ {+ setCreatedByFilter: (_, { createdByFilter }) => createdByFilter,+ },+ ],editingAlert: [null as LogsAlertConfigurationApi | null,{@@ -156,9 +168,13 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([alerts: [[] as LogsAlertConfigurationApi[],{- loadAlerts: async () => {+ loadAlerts: async (_ = null, breakpoint) => {const projectId = String(values.currentTeamId)- const response = await logsAlertsList(projectId, { limit: 500 })+ const response = await logsAlertsList(projectId, {+ limit: 500,+ ...(values.createdByFilter ? { created_by: values.createdByFilter } : {}),+ })+ breakpoint()return response.results},},@@ -166,6 +182,7 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([})),listeners(({ actions, values }) => ({+ setCreatedByFilter: () => actions.loadAlerts(),deleteAlert: async ({ id }) => {const projectId = String(values.currentTeamId)try {@@ -255,6 +272,14 @@ export const logsAlertingLogic = kea<logsAlertingLogicType>([},})),+ subscriptions(({ actions }) => ({+ currentTeamId: (currentTeamId, previousTeamId) => {+ if (previousTeamId !== null && currentTeamId !== previousTeamId) {+ actions.setCreatedByFilter(null)+ }+ },+ })),+afterMount(({ actions, values, cache }) => {actions.loadAlerts()cache.disposables.add(() => {diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 93d004997b5c..eaa40a97ff98 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1902,6 +1902,10 @@ export interface PatchedLogsViewApi {}export type LogsAlertsListParams = {+ /**+ * Only return log alerts created by the user with this UUID.+ */+ created_by?: string/*** Number of results to return per page.*/diff --git a/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts b/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.tsindex 16ea85b033bf..bead6b2bfa67 100644--- a/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts+++ b/products/logs/frontend/scenes/LogsAlertDetailScene/logsAlertDetailSceneLogic.ts@@ -98,7 +98,7 @@ export interface logsAlertDetailSceneLogicActions {destinationsChanged: () => {value: true} // logsAlertNotificationLogic- loadAlerts: () => any // logsAlertingLogic+ loadAlerts: (_?: any) => any // logsAlertingLogicapplyEnabledChange: (enabled: boolean) => {enabled: boolean}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 994dfd2424e3..763224932cee 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -69041,6 +69041,10 @@ export namespace Schemas {};export type EnvironmentsLogsAlertsListParams = {+ /**+ * Only return log alerts created by the user with this UUID.+ */+ created_by?: string;/*** Number of results to return per page.*/@@ -76867,6 +76871,10 @@ export namespace Schemas {};export type LogsAlertsListParams = {+ /**+ * Only return log alerts created by the user with this UUID.+ */+ created_by?: string;/*** Number of results to return per page.*/diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.tsindex 25947c233c88..46b754367309 100644--- a/services/mcp/src/generated/logs/api.ts+++ b/services/mcp/src/generated/logs/api.ts@@ -17,6 +17,7 @@ export const LogsAlertsListParams = /* @__PURE__ */ zod.object({})export const LogsAlertsListQueryParams = /* @__PURE__ */ zod.object({+ created_by: zod.string().optional().describe('Only return log alerts created by the user with this UUID.'),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),})diff --git a/services/mcp/src/tools/generated/logs.ts b/services/mcp/src/tools/generated/logs.tsindex d84fdd89b651..540bcf677dd2 100644--- a/services/mcp/src/tools/generated/logs.ts+++ b/services/mcp/src/tools/generated/logs.ts@@ -244,6 +244,7 @@ const logsAlertsList = (): ToolBase<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/alerts/`,query: {+ created_by: params.created_by,limit: params.limit,offset: params.offset,},