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(workflows): add server-side search to opt-out and suppression lists (#87639)

Meikel Ratzc576f19b7938
diff --git a/products/messaging/backend/api/message_preferences.py b/products/messaging/backend/api/message_preferences.py
index f8408c8e6576..5cc1264d63f2 100644
--- a/products/messaging/backend/api/message_preferences.py
+++ b/products/messaging/backend/api/message_preferences.py
@@ -13,6 +13,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.documentation import _FallbackSerializer
+from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.streaming import streaming_response
from posthog.plugins import plugin_server_api
@@ -108,6 +109,22 @@ class MessagingErrorSerializer(serializers.Serializer):
error = serializers.CharField(help_text="Human-readable description of what went wrong.")
+class OptOutsListQuerySerializer(serializers.Serializer):
+ # allow_blank preserves the pre-serializer behavior: an empty category_key reads as "no
+ # category" (the global list) rather than a 400.
+ category_key = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Message category key to list opt-outs for. If omitted, lists recipients opted out of all marketing messages.",
+ )
+ search = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=512,
+ help_text="Case-insensitive substring match on the recipient identifier.",
+ )
+
+
class PaginatedOptOutsSerializer(serializers.Serializer):
"""OpenAPI shape for the paginated opt-outs response, so the generated clients get the
{count, next, previous, results} envelope instead of an untyped object."""
@@ -187,30 +204,24 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
if not self.user_access_control.check_access_level_for_resource("hog_flow", required_level):
raise PermissionDenied(message)
- @extend_schema(
+ @validated_request(
+ query_serializer=OptOutsListQuerySerializer,
parameters=[
- OpenApiParameter(
- name="category_key",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Message category key to list opt-outs for. If omitted, lists recipients opted out of all marketing messages.",
- ),
OpenApiParameter(name="page", type=OpenApiTypes.INT, location=OpenApiParameter.QUERY, required=False),
OpenApiParameter(name="page_size", type=OpenApiTypes.INT, location=OpenApiParameter.QUERY, required=False),
],
responses={
- 200: PaginatedOptOutsSerializer,
+ 200: OpenApiResponse(response=PaginatedOptOutsSerializer),
404: OpenApiResponse(response=MessagingErrorSerializer),
},
summary="List recipients opted out of a message category",
)
@action(detail=False, methods=["get"])
- def opt_outs(self, request: Request, **kwargs: Any) -> Response:
+ def opt_outs(self, request: ValidatedRequest, **kwargs: Any) -> Response:
"""Get opt-outs filtered by category or overall opt-outs if no category specified"""
self._require_resource_access("viewer", "You need hog_flow viewer access to view the opt-out list.")
- category_key = request.query_params.get("category_key")
+ category_key = request.validated_query_data.get("category_key")
# Find recipients who have opted out of this specific category, or use the derived $all category if no specific category is provided
preference_key = ALL_MESSAGE_PREFERENCE_CATEGORY_ID
@@ -223,7 +234,13 @@ class MessagePreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
opt_outs = MessageRecipientPreference.objects.filter(
team_id=self.team_id,
**{f"preferences__{preference_key}": PreferenceStatus.OPTED_OUT.value},
- ).order_by("-updated_at") # Order by most recently updated first
+ )
+
+ search = request.validated_query_data.get("search")
+ if search:
+ opt_outs = opt_outs.filter(identifier__icontains=search)
+
+ opt_outs = opt_outs.order_by("-updated_at") # Order by most recently updated first
# Apply pagination
paginator = OptOutsPagination()
diff --git a/products/messaging/backend/api/message_suppression.py b/products/messaging/backend/api/message_suppression.py
index 04e22c37a628..f69458a06859 100644
--- a/products/messaging/backend/api/message_suppression.py
+++ b/products/messaging/backend/api/message_suppression.py
@@ -4,7 +4,7 @@ from django.db.models import F
from django.db.models.functions import Coalesce, Now
from django.utils import timezone
-from drf_spectacular.utils import OpenApiParameter, extend_schema
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied
@@ -13,6 +13,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.documentation import _FallbackSerializer
+from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from products.messaging.backend.models.message_suppression import MessageSuppression, SuppressionSource
@@ -79,6 +80,15 @@ class PaginatedMessageSuppressionSerializer(serializers.Serializer):
results = MessageSuppressionSerializer(many=True)
+class SuppressionsListQuerySerializer(serializers.Serializer):
+ search = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=512,
+ help_text="Case-insensitive substring match on the recipient email address.",
+ )
+
+
class AddSuppressionRequestSerializer(serializers.Serializer):
identifier = serializers.CharField(
max_length=512,
@@ -101,12 +111,13 @@ class MessageSuppressionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
scope_object_write_actions = ["add_suppression", "remove_suppression"]
serializer_class = _FallbackSerializer
- @extend_schema(
+ @validated_request(
+ query_serializer=SuppressionsListQuerySerializer,
parameters=[
OpenApiParameter(name="page", type=int, location=OpenApiParameter.QUERY, required=False),
OpenApiParameter(name="page_size", type=int, location=OpenApiParameter.QUERY, required=False),
],
- responses={200: PaginatedMessageSuppressionSerializer},
+ responses={200: OpenApiResponse(response=PaginatedMessageSuppressionSerializer)},
summary="List suppressed email addresses for the team",
)
# The rows carry recipient email addresses and their SMTP diagnostics, so reading them is
@@ -115,7 +126,7 @@ class MessageSuppressionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
# could enumerate who a team emails, and probe whether a given address is known by paging for
# it. The UI uses session auth, which skips scope checks, so the suppression list is unaffected.
@action(detail=False, methods=["get"], required_scopes=["hog_flow:read", "person:read"])
- def suppressions(self, request: Request, **kwargs: Any) -> Response:
+ def suppressions(self, request: ValidatedRequest, **kwargs: Any) -> Response:
"""List suppressed recipients for the team, most recently updated first."""
# Resource-level check: `AccessControlPermission` only guarantees the caller has some
# hog_flow object access. Since this endpoint returns team-wide data (every suppressed
@@ -125,11 +136,13 @@ class MessageSuppressionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
if not self.user_access_control.check_access_level_for_resource("hog_flow", "viewer"):
raise PermissionDenied("You need hog_flow viewer access to view the suppression list.")
- suppressions = (
- MessageSuppression.objects.for_team(self.team_id)
- .filter(suppressed=True, deleted=False)
- .order_by("-updated_at")
- )
+ suppressions = MessageSuppression.objects.for_team(self.team_id).filter(suppressed=True, deleted=False)
+
+ search = request.validated_query_data.get("search")
+ if search:
+ suppressions = suppressions.filter(identifier__icontains=search)
+
+ suppressions = suppressions.order_by("-updated_at")
paginator = SuppressionPagination()
page = paginator.paginate_queryset(suppressions, request)
diff --git a/products/messaging/backend/api/test/test_message_preferences.py b/products/messaging/backend/api/test/test_message_preferences.py
index 7c21f97ed2ae..76d891447cac 100644
--- a/products/messaging/backend/api/test/test_message_preferences.py
+++ b/products/messaging/backend/api/test/test_message_preferences.py
@@ -599,6 +599,35 @@ class TestMessagePreferencesAPIViewSet(APIBaseTest):
self.assertEqual(len(data["results"]), 1)
self.assertEqual(data["results"][0]["identifier"], "[email protected]")
+ def test_opt_outs_search_filters_by_identifier(self):
+ MessageRecipientPreference.objects.create(
+ team=self.team,
+ identifier=identifier,
+ preferences={ALL_MESSAGE_PREFERENCE_CATEGORY_ID: PreferenceStatus.OPTED_OUT.value},
+ )
+ # Opted out of a category only, so a global-list search must not surface them
+ MessageRecipientPreference.objects.create(
+ team=self.team,
+ identifier="[email protected]",
+ preferences={str(self.category.id): PreferenceStatus.OPTED_OUT.value},
+ )
+
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/messaging_preferences/opt_outs/", {"search": "ALICE"}
+ )
+ self.assertEqual(response.status_code, 200)
+ data = response.json()
+ self.assertEqual(data["count"], 2)
+ identifiers = {item["identifier"] for item in data["results"]}
+ self.assertEqual(identifiers, {"[email protected]", "[email protected]"})
+
+ def test_opt_outs_search_term_too_long(self):
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/messaging_preferences/opt_outs/", {"search": "a" * 513}
+ )
+ self.assertEqual(response.status_code, 400)
+
def test_add_opt_out_global(self):
response = self.client.post(
f"/api/environments/{self.team.id}/messaging_preferences/add_opt_out/",
diff --git a/products/messaging/backend/api/test/test_message_suppression.py b/products/messaging/backend/api/test/test_message_suppression.py
index d5198e107639..bce4af96182c 100644
--- a/products/messaging/backend/api/test/test_message_suppression.py
+++ b/products/messaging/backend/api/test/test_message_suppression.py
@@ -66,6 +66,40 @@ class TestSuppressionListPersonalAPIKeyAccess(APIBaseTest):
assert set(response.json()) == {"count", "next", "previous", "results"}
+class TestSuppressionListSearch(APIBaseTest):
+ def test_search_filters_by_identifier_within_suppressed_rows(self) -> None:
+ for identifier in ["[email protected]", "[email protected]"]:
+ MessageSuppression.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ identifier=identifier,
+ source=SuppressionSource.MANUAL,
+ suppressed=True,
+ )
+ # Bounce-counting row that hasn't crossed the threshold: matches the search term but must
+ # stay off the list because it isn't suppressed
+ MessageSuppression.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ identifier="[email protected]",
+ source=SuppressionSource.BOUNCE,
+ suppressed=False,
+ )
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/messaging_suppressions/suppressions/", {"search": "ALICE"}
+ )
+
+ assert response.status_code == 200, response.json()
+ data = response.json()
+ assert data["count"] == 1
+ assert data["results"][0]["identifier"] == "[email protected]"
+
+ def test_search_term_too_long(self) -> None:
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/messaging_suppressions/suppressions/", {"search": "a" * 513}
+ )
+ assert response.status_code == 400
+
+
class TestRemoveSuppressionResetsSource(APIBaseTest):
"""
Guards against a regression where remove_suppression keeps source='MANUAL' on the removed row.
diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.ts
index ec6a368b7b04..84f5b33a4eb9 100644
--- a/products/messaging/frontend/generated/api.schemas.ts
+++ b/products/messaging/frontend/generated/api.schemas.ts
@@ -515,11 +515,21 @@ export type MessagingPreferencesOptOutsRetrieveParams = {
category_key?: string
page?: number
page_size?: number
+ /**
+ * Case-insensitive substring match on the recipient identifier.
+ * @maxLength 512
+ */
+ search?: string
}
export type MessagingSuppressionsSuppressionsRetrieveParams = {
page?: number
page_size?: number
+ /**
+ * Case-insensitive substring match on the recipient email address.
+ * @maxLength 512
+ */
+ search?: string
}
export type MessagingTemplatesListParams = {
diff --git a/products/workflows/frontend/OptOuts/OptOutList.tsx b/products/workflows/frontend/OptOuts/OptOutList.tsx
index 7f43e5b5aa74..243e0c2ee309 100644
--- a/products/workflows/frontend/OptOuts/OptOutList.tsx
+++ b/products/workflows/frontend/OptOuts/OptOutList.tsx
@@ -41,6 +41,7 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.El
importCsv,
exportCsv,
clearCsvImportResult,
+ setSearchTerm,
} = useActions(logic)
const {
selectedIdentifier,
@@ -59,6 +60,7 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.El
csvImportResult,
csvImportResultLoading,
csvExportLoading,
+ searchTerm,
} = useValues(logic)
const handleShowPersons = (identifier: string): void => {
@@ -136,7 +138,15 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.El
return (
<>
- <div className="flex justify-end gap-2 mb-2 mt-[-3rem]">
+ <div className="flex flex-wrap justify-end gap-2 mb-2">
+ <LemonInput
+ type="search"
+ size="small"
+ placeholder="Search recipients"
+ value={searchTerm}
+ onChange={setSearchTerm}
+ className="w-60"
+ />
<LemonButton
icon={<IconPlus />}
size="small"
@@ -171,7 +181,7 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.El
icon={<IconRefresh />}
size="small"
type="secondary"
- onClick={loadOptOutPersons}
+ onClick={() => loadOptOutPersons()}
loading={optOutPersonsLoading}
>
Reload
@@ -184,7 +194,11 @@ export function OptOutList({ category }: { category?: MessageCategory }): JSX.El
loading={optOutPersonsLoading}
loadingSkeletonRows={3}
rowKey="identifier"
- emptyState={`No opt-outs found${category?.name ? ` for ${category.name}` : ''}`}
+ emptyState={
+ searchTerm.trim()
+ ? 'No opt-outs match your search'
+ : `No opt-outs found${category?.name ? ` for ${category.name}` : ''}`
+ }
size="small"
/>
</div>
diff --git a/products/workflows/frontend/OptOuts/optOutListLogic.ts b/products/workflows/frontend/OptOuts/optOutListLogic.ts
index 8dd371bf7d39..37b1b7e9fefb 100644
--- a/products/workflows/frontend/OptOuts/optOutListLogic.ts
+++ b/products/workflows/frontend/OptOuts/optOutListLogic.ts
@@ -1,4 +1,16 @@
-import { MakeLogicType, actions, afterMount, connect, kea, key, path, props, reducers } from 'kea'
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ isBreakpoint,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+} from 'kea'
import { loaders } from 'kea-loaders'
import Papa from 'papaparse'
@@ -51,7 +63,10 @@ export interface optOutListLogicValues {
csvExport: null
csvExportLoading: boolean
csvFile: File | null
- csvImportProgress: { processed: number; total: number } | null
+ csvImportProgress: {
+ processed: number
+ total: number
+ } | null
csvImportResult: BulkAddOptOutsResultApi | null
csvImportResultLoading: boolean
currentPage: number
@@ -63,6 +78,7 @@ export interface optOutListLogicValues {
personsModalOpen: boolean
removeOptOut: string | null
removeOptOutLoading: boolean
+ searchTerm: string
selectedIdentifier: string | null
showAddOptOutModal: boolean
showImportCsvModal: boolean
@@ -134,25 +150,9 @@ export interface optOutListLogicActions {
loadNextPage: () => {
value: true
}
- loadNextPageFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadNextPageSuccess: (
- optOutPersons: PaginatedOptOutsApi,
- payload?: {
- value: true
- }
- ) => {
- optOutPersons: PaginatedOptOutsApi
- payload?: {
- value: true
- }
+ loadOptOutPersons: (page?: number) => {
+ page: number
}
- loadOptOutPersons: () => any
loadOptOutPersonsFailure: (
error: string,
errorObject?: any
@@ -161,33 +161,19 @@ export interface optOutListLogicActions {
errorObject?: any
}
loadOptOutPersonsSuccess: (
- optOutPersons: PaginatedOptOutsApi,
- payload?: any
- ) => {
- optOutPersons: PaginatedOptOutsApi
- payload?: any
- }
- loadPreviousPage: () => {
- value: true
- }
- loadPreviousPageFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadPreviousPageSuccess: (
optOutPersons: PaginatedOptOutsApi,
payload?: {
- value: true
+ page: number
}
) => {
optOutPersons: PaginatedOptOutsApi
payload?: {
- value: true
+ page: number
}
}
+ loadPreviousPage: () => {
+ value: true
+ }
loadUnsubscribeLink: () => {
value: true
}
@@ -209,8 +195,16 @@ export interface optOutListLogicActions {
setCsvFile: (file: File | null) => {
file: File | null
}
- setCsvImportProgress: (progress: { processed: number; total: number } | null) => {
- progress: { processed: number; total: number } | null
+ setCsvImportProgress: (
+ progress: {
+ processed: number
+ total: number
+ } | null
+ ) => {
+ progress: {
+ processed: number
+ total: number
+ } | null
}
setCurrentPage: (page: number) => {
page: number
@@ -224,6 +218,9 @@ export interface optOutListLogicActions {
setPersonsModalOpen: (open: boolean) => {
open: boolean
}
+ setSearchTerm: (searchTerm: string) => {
+ searchTerm: string
+ }
setSelectedIdentifier: (identifier: string | null) => {
identifier: string | null
}
@@ -260,7 +257,9 @@ export const optOutListLogic = kea<optOutListLogicType>([
setPersonsModalOpen: (open: boolean) => ({ open }),
setManagePreferencesModalOpen: (open: boolean) => ({ open }),
setSelectedIdentifier: (identifier: string | null) => ({ identifier }),
+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),
setCurrentPage: (page: number) => ({ page }),
+ loadOptOutPersons: (page?: number) => ({ page: page ?? 1 }),
loadNextPage: true,
loadPreviousPage: true,
setShowAddOptOutModal: (show: boolean) => ({ show }),
@@ -300,13 +299,19 @@ export const optOutListLogic = kea<optOutListLogicType>([
setSelectedIdentifier: (_, { identifier }) => identifier,
},
],
+ searchTerm: [
+ '',
+ {
+ setSearchTerm: (_, { searchTerm }) => searchTerm,
+ },
+ ],
currentPage: [
1,
{
setCurrentPage: (_, { page }) => page,
- loadOptOutPersonsSuccess: () => 1, // Reset to page 1 on initial load
- loadNextPageSuccess: (state) => state + 1,
- loadPreviousPageSuccess: (state) => Math.max(1, state - 1),
+ // Track the page that actually loaded, so a discarded stale response can't
+ // desync the label from the rows.
+ loadOptOutPersonsSuccess: (state, { payload }) => payload?.page ?? state,
},
],
showAddOptOutModal: [
@@ -367,6 +372,7 @@ export const optOutListLogic = kea<optOutListLogicType>([
}
return await messagingPreferencesOptOutsRetrieve(String(values.currentProjectId), {
category_key: props.category?.key,
+ search: values.searchTerm.trim() || undefined,
page,
})
}
@@ -414,33 +420,25 @@ export const optOutListLogic = kea<optOutListLogicType>([
},
optOutPersons: {
__default: EMPTY_OPT_OUTS,
- loadOptOutPersons: async (): Promise<PaginatedOptOutsApi> => {
+ // Single loader for every page fetch (initial, search, next, prev) so overlapping
+ // requests share one action key and the breakpoint can discard the stale one — a
+ // pagination response resolving after a search reload must not overwrite it.
+ loadOptOutPersons: async ({ page }, breakpoint): Promise<PaginatedOptOutsApi> => {
try {
- return await fetchPage(1)
+ const result = await fetchPage(page)
+ breakpoint()
+ return result
} catch (e) {
- lemonToast.error('Failed to load opt-out persons')
+ if (isBreakpoint(e as Error)) {
+ throw e
+ }
+ lemonToast.error('Failed to load opt-outs')
// Rethrow so kea-loaders emits a *Failure action: optOutPersons keeps its
// previous value instead of rendering a failed fetch as "no opt-outs found",
// and the currentPage reducer (which only moves on *Success) stays put.
throw e
}
},
- loadNextPage: async (): Promise<PaginatedOptOutsApi> => {
- try {
- return await fetchPage(values.currentPage + 1)
- } catch (e) {
- lemonToast.error('Failed to load next page')
- throw e
- }
- },
- loadPreviousPage: async (): Promise<PaginatedOptOutsApi> => {
- try {
- return await fetchPage(Math.max(1, values.currentPage - 1))
- } catch (e) {
- lemonToast.error('Failed to load previous page')
- throw e
- }
- },
},
csvExport: {
__default: null as null,
@@ -524,6 +522,14 @@ export const optOutListLogic = kea<optOutListLogicType>([
},
}
}),
+ listeners(({ actions, values }) => ({
+ setSearchTerm: async (_, breakpoint) => {
+ await breakpoint(300)
+ actions.loadOptOutPersons()
+ },
+ loadNextPage: () => actions.loadOptOutPersons(values.currentPage + 1),
+ loadPreviousPage: () => actions.loadOptOutPersons(Math.max(1, values.currentPage - 1)),
+ })),
afterMount(({ props, actions }) => {
// If no category is provided or it's a marketing category, load opt-out persons
if (!props.category?.id || props.category?.category_type === 'marketing') {
diff --git a/products/workflows/frontend/Suppression/SuppressionList.tsx b/products/workflows/frontend/Suppression/SuppressionList.tsx
index 58310bf0101e..46d5e8be2e64 100644
--- a/products/workflows/frontend/Suppression/SuppressionList.tsx
+++ b/products/workflows/frontend/Suppression/SuppressionList.tsx
@@ -21,6 +21,7 @@ export function SuppressionList(): JSX.Element {
setNewIdentifier,
addSuppression,
removeSuppression,
+ setSearchTerm,
} = useActions(suppressionListLogic)
const {
suppressions,
@@ -30,6 +31,7 @@ export function SuppressionList(): JSX.Element {
addSuppressionLoading,
removeSuppressionLoading,
newIdentifier,
+ searchTerm,
} = useValues(suppressionListLogic)
const columns: LemonTableColumns<MessageSuppressionApi> = [
@@ -92,7 +94,15 @@ export function SuppressionList(): JSX.Element {
return (
<>
- <div className="flex justify-end gap-2 mb-2">
+ <div className="flex flex-wrap justify-end gap-2 mb-2">
+ <LemonInput
+ type="search"
+ size="small"
+ placeholder="Search addresses"
+ value={searchTerm}
+ onChange={setSearchTerm}
+ className="w-60"
+ />
<LemonButton icon={<IconPlus />} size="small" type="secondary" onClick={() => setShowAddModal(true)}>
Add address
</LemonButton>
@@ -100,7 +110,7 @@ export function SuppressionList(): JSX.Element {
icon={<IconRefresh />}
size="small"
type="secondary"
- onClick={loadSuppressions}
+ onClick={() => loadSuppressions()}
loading={suppressionsLoading}
>
Reload
@@ -112,7 +122,11 @@ export function SuppressionList(): JSX.Element {
loading={suppressionsLoading}
loadingSkeletonRows={3}
rowKey="identifier"
- emptyState="No suppressed addresses. Addresses land here automatically after repeated soft bounces, or when you add them manually."
+ emptyState={
+ searchTerm.trim()
+ ? 'No suppressed addresses match your search'
+ : 'No suppressed addresses. Addresses land here automatically after repeated soft bounces, or when you add them manually.'
+ }
size="small"
/>
{suppressions.count > PAGE_SIZE && (
diff --git a/products/workflows/frontend/Suppression/suppressionListLogic.test.ts b/products/workflows/frontend/Suppression/suppressionListLogic.test.ts
index ff5e7fb3b2f9..2bcae00e9671 100644
--- a/products/workflows/frontend/Suppression/suppressionListLogic.test.ts
+++ b/products/workflows/frontend/Suppression/suppressionListLogic.test.ts
@@ -3,9 +3,24 @@ import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
import * as messagingApi from 'products/messaging/frontend/generated/api'
+import type { PaginatedMessageSuppressionApi } from 'products/messaging/frontend/generated/api.schemas'
import { suppressionListLogic } from './suppressionListLogic'
+const suppressionRow = (identifier: string): any => ({
+ id: identifier,
+ identifier,
+ source: 'MANUAL',
+ reason: '',
+ transient_bounce_count: 0,
+ last_bounce_at: null,
+ last_bounce_diagnostic: null,
+ suppressed: true,
+ suppressed_at: null,
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+})
+
describe('suppressionListLogic', () => {
beforeEach(() => {
initKeaTests()
@@ -13,17 +28,20 @@ describe('suppressionListLogic', () => {
describe('page-state failure isolation', () => {
// Guards against the "silent-swallow catch returns previous rows -> kea-loaders treats it as
- // success -> currentPage still increments" bug. On a failed loadNextPage the counter must
+ // success -> currentPage still increments" bug. On a failed page fetch the counter must
// stay put; otherwise the UI shows the wrong page number over old data, then permanently
// skips the page it thought it advanced to.
it('does not advance currentPage when loadNextPage fails', async () => {
jest.spyOn(messagingApi, 'messagingSuppressionsSuppressionsRetrieve').mockRejectedValue(new Error('boom'))
const logic = suppressionListLogic()
logic.mount()
+ // Let the mount-time load fail first, so the assertion below can only match the
+ // pagination fetch's own failure.
+ await expectLogic(logic).toFinishAllListeners()
await expectLogic(logic, () => {
logic.actions.loadNextPage()
- }).toDispatchActions(['loadNextPageFailure'])
+ }).toDispatchActions(['loadSuppressionsFailure'])
expect(logic.values.currentPage).toBe(1)
})
@@ -32,13 +50,63 @@ describe('suppressionListLogic', () => {
jest.spyOn(messagingApi, 'messagingSuppressionsSuppressionsRetrieve').mockRejectedValue(new Error('boom'))
const logic = suppressionListLogic()
logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
logic.actions.setCurrentPage(3)
await expectLogic(logic, () => {
logic.actions.loadPreviousPage()
- }).toDispatchActions(['loadPreviousPageFailure'])
+ }).toDispatchActions(['loadSuppressionsFailure'])
expect(logic.values.currentPage).toBe(3)
})
})
+
+ describe('overlapping request isolation', () => {
+ // Guards the loader breakpoint: a pagination fetch that resolves after a newer reload
+ // (e.g. a debounced search) must be discarded, not overwrite the newer rows and desync
+ // currentPage from what the table shows.
+ it('discards a stale pagination response that resolves after a newer reload', async () => {
+ let resolveStalePage: (value: PaginatedMessageSuppressionApi) => void = () => {}
+ const stalePagePromise = new Promise<PaginatedMessageSuppressionApi>((resolve) => {
+ resolveStalePage = resolve
+ })
+ const initialResult: PaginatedMessageSuppressionApi = {
+ count: 1,
+ next: null,
+ previous: null,
+ results: [suppressionRow('[email protected]')],
+ }
+ const freshResult: PaginatedMessageSuppressionApi = {
+ count: 1,
+ next: null,
+ previous: null,
+ results: [suppressionRow('[email protected]')],
+ }
+ jest.spyOn(messagingApi, 'messagingSuppressionsSuppressionsRetrieve')
+ .mockResolvedValueOnce(initialResult)
+ .mockImplementationOnce(() => stalePagePromise)
+ .mockResolvedValueOnce(freshResult)
+
+ const logic = suppressionListLogic()
+ logic.mount()
+ // Let the mount-time load settle so the mocks line up with the two racing requests.
+ await expectLogic(logic).toDispatchActions(['loadSuppressionsSuccess'])
+
+ logic.actions.loadNextPage()
+ await expectLogic(logic, () => {
+ logic.actions.loadSuppressions()
+ }).toDispatchActions(['loadSuppressionsSuccess'])
+
+ resolveStalePage({
+ count: 100,
+ next: 'next-url',
+ previous: null,
+ results: [suppressionRow('[email protected]')],
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.suppressions).toEqual(freshResult)
+ expect(logic.values.currentPage).toBe(1)
+ })
+ })
})
diff --git a/products/workflows/frontend/Suppression/suppressionListLogic.ts b/products/workflows/frontend/Suppression/suppressionListLogic.ts
index 19f616b899d4..c77938e024c5 100644
--- a/products/workflows/frontend/Suppression/suppressionListLogic.ts
+++ b/products/workflows/frontend/Suppression/suppressionListLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, afterMount, connect, kea, path, reducers } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, isBreakpoint, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
@@ -26,6 +26,7 @@ export interface suppressionListLogicValues {
newIdentifier: string
removeSuppression: string | null
removeSuppressionLoading: boolean
+ searchTerm: string
showAddModal: boolean
suppressions: PaginatedMessageSuppressionApi
suppressionsLoading: boolean
@@ -51,60 +52,30 @@ export interface suppressionListLogicActions {
loadNextPage: () => {
value: true
}
- loadNextPageFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadNextPageSuccess: (
- suppressions: PaginatedMessageSuppressionApi,
- payload?: {
- value: true
- }
- ) => {
- suppressions: PaginatedMessageSuppressionApi
- payload?: {
- value: true
- }
- }
loadPreviousPage: () => {
value: true
}
- loadPreviousPageFailure: (
+ loadSuppressions: (page?: number) => {
+ page: number
+ }
+ loadSuppressionsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
- loadPreviousPageSuccess: (
+ loadSuppressionsSuccess: (
suppressions: PaginatedMessageSuppressionApi,
payload?: {
- value: true
+ page: number
}
) => {
suppressions: PaginatedMessageSuppressionApi
payload?: {
- value: true
+ page: number
}
}
- loadSuppressions: () => any
- loadSuppressionsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadSuppressionsSuccess: (
- suppressions: PaginatedMessageSuppressionApi,
- payload?: any
- ) => {
- suppressions: PaginatedMessageSuppressionApi
- payload?: any
- }
removeSuppression: (identifier: string) => string
removeSuppressionFailure: (
error: string,
@@ -126,6 +97,9 @@ export interface suppressionListLogicActions {
setNewIdentifier: (identifier: string) => {
identifier: string
}
+ setSearchTerm: (searchTerm: string) => {
+ searchTerm: string
+ }
setShowAddModal: (show: boolean) => {
show: boolean
}
@@ -133,11 +107,18 @@ export interface suppressionListLogicActions {
export type suppressionListLogicType = MakeLogicType<suppressionListLogicValues, suppressionListLogicActions>
-const fetchPage = async (projectId: number | null, page: number): Promise<PaginatedMessageSuppressionApi> => {
+const fetchPage = async (
+ projectId: number | null,
+ page: number,
+ search: string
+): Promise<PaginatedMessageSuppressionApi> => {
if (projectId === null) {
return EMPTY_SUPPRESSIONS
}
- return await messagingSuppressionsSuppressionsRetrieve(String(projectId), { page })
+ return await messagingSuppressionsSuppressionsRetrieve(String(projectId), {
+ search: search.trim() || undefined,
+ page,
+ })
}
export const suppressionListLogic = kea<suppressionListLogicType>([
@@ -147,19 +128,21 @@ export const suppressionListLogic = kea<suppressionListLogicType>([
})),
actions({
setCurrentPage: (page: number) => ({ page }),
+ loadSuppressions: (page?: number) => ({ page: page ?? 1 }),
loadNextPage: true,
loadPreviousPage: true,
setShowAddModal: (show: boolean) => ({ show }),
setNewIdentifier: (identifier: string) => ({ identifier }),
+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),
}),
reducers({
currentPage: [
1,
{
setCurrentPage: (_, { page }) => page,
- loadSuppressionsSuccess: () => 1,
- loadNextPageSuccess: (state) => state + 1,
- loadPreviousPageSuccess: (state) => Math.max(1, state - 1),
+ // Track the page that actually loaded, so a discarded stale response can't
+ // desync the label from the rows.
+ loadSuppressionsSuccess: (state, { payload }) => payload?.page ?? state,
},
],
showAddModal: [
@@ -177,37 +160,35 @@ export const suppressionListLogic = kea<suppressionListLogicType>([
setShowAddModal: (state, { show }) => (show ? state : ''),
},
],
+ searchTerm: [
+ '',
+ {
+ setSearchTerm: (_, { searchTerm }) => searchTerm,
+ },
+ ],
}),
loaders(({ values, actions }) => ({
suppressions: {
__default: EMPTY_SUPPRESSIONS,
- loadSuppressions: async (): Promise<PaginatedMessageSuppressionApi> => {
+ // Single loader for every page fetch (initial, search, next, prev) so overlapping
+ // requests share one action key and the breakpoint can discard the stale one — a
+ // pagination response resolving after a search reload must not overwrite it.
+ loadSuppressions: async ({ page }, breakpoint): Promise<PaginatedMessageSuppressionApi> => {
try {
- return await fetchPage(values.currentProjectId, 1)
+ const result = await fetchPage(values.currentProjectId, page, values.searchTerm)
+ breakpoint()
+ return result
} catch (e) {
+ if (isBreakpoint(e as Error)) {
+ throw e
+ }
lemonToast.error('Failed to load suppression list')
// Rethrow so kea-loaders emits loadSuppressionsFailure and the currentPage reducer
- // (which only advances on *Success) stays put — otherwise a failed page fetch would
+ // (which only moves on *Success) stays put — otherwise a failed page fetch would
// still tick currentPage and skip pages permanently.
throw e
}
},
- loadNextPage: async (): Promise<PaginatedMessageSuppressionApi> => {
- try {
- return await fetchPage(values.currentProjectId, values.currentPage + 1)
- } catch (e) {
- lemonToast.error('Failed to load next page')
- throw e
- }
- },
- loadPreviousPage: async (): Promise<PaginatedMessageSuppressionApi> => {
- try {
- return await fetchPage(values.currentProjectId, Math.max(1, values.currentPage - 1))
- } catch (e) {
- lemonToast.error('Failed to load previous page')
- throw e
- }
- },
},
addSuppression: {
__default: null as MessageSuppressionApi | null,
@@ -246,6 +227,14 @@ export const suppressionListLogic = kea<suppressionListLogicType>([
},
},
})),
+ listeners(({ actions, values }) => ({
+ setSearchTerm: async (_, breakpoint) => {
+ await breakpoint(300)
+ actions.loadSuppressions()
+ },
+ loadNextPage: () => actions.loadSuppressions(values.currentPage + 1),
+ loadPreviousPage: () => actions.loadSuppressions(Math.max(1, values.currentPage - 1)),
+ })),
afterMount(({ actions }) => {
actions.loadSuppressions()
}),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 09cbe1d509be..9d4db3d5b4fc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -93066,11 +93066,21 @@ export namespace Schemas {
category_key?: string;
page?: number;
page_size?: number;
+ /**
+ * Case-insensitive substring match on the recipient identifier.
+ * @maxLength 512
+ */
+ search?: string;
};
export type MessagingSuppressionsSuppressionsRetrieveParams = {
page?: number;
page_size?: number;
+ /**
+ * Case-insensitive substring match on the recipient email address.
+ * @maxLength 512
+ */
+ search?: string;
};
export type MessagingTemplatesListParams = {
diff --git a/services/mcp/src/generated/messaging/api.ts b/services/mcp/src/generated/messaging/api.ts
index 9c985c754dcf..d054c731e3a8 100644
--- a/services/mcp/src/generated/messaging/api.ts
+++ b/services/mcp/src/generated/messaging/api.ts
@@ -57,6 +57,8 @@ export const MessagingPreferencesOptOutsRetrieveParams = /* @__PURE__ */ zod.obj
),
})
+export const messagingPreferencesOptOutsRetrieveQuerySearchMax = 512
+
export const MessagingPreferencesOptOutsRetrieveQueryParams = /* @__PURE__ */ zod.object({
category_key: zod
.string()
@@ -66,6 +68,11 @@ export const MessagingPreferencesOptOutsRetrieveQueryParams = /* @__PURE__ */ zo
),
page: zod.number().optional(),
page_size: zod.number().optional(),
+ search: zod
+ .string()
+ .max(messagingPreferencesOptOutsRetrieveQuerySearchMax)
+ .optional()
+ .describe('Case-insensitive substring match on the recipient identifier.'),
})
/**
diff --git a/services/mcp/src/tools/generated/messaging.ts b/services/mcp/src/tools/generated/messaging.ts
index 18187db02d2d..295e9eb20e6a 100644
--- a/services/mcp/src/tools/generated/messaging.ts
+++ b/services/mcp/src/tools/generated/messaging.ts
@@ -46,6 +46,7 @@ const optOutsList = (): ToolBase<typeof OptOutsListSchema, Schemas.PaginatedOptO
category_key: params.category_key,
page: params.page,
page_size: params.page_size,
+ search: params.search,
},
})
return result
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-list.json
index 5ff56fd25f14..0a0372d22fb9 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/opt-outs-list.json
@@ -10,6 +10,11 @@
},
"page_size": {
"type": "number"
+ },
+ "search": {
+ "description": "Case-insensitive substring match on the recipient identifier.",
+ "maxLength": 512,
+ "type": "string"
}
},
"type": "object"