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): list each broadcast run's recipients inside the run (#105620)

Daniel Marchukbdfaad6d04bf
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c3147938ca60..571d8c5e28e7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11395,7 +11395,7 @@ snapshots:
scenes-app-settings-organization--settings-organization-members--dark:
hash: v1.k794b7964.7728118a93e6616d1a7635d948f2e90a69430386f652f369540bdfe64d9861fb.4j1qbfUUSFXvBSP9MJLHJk2XX7uSiv6HuLnXMlztSug
scenes-app-settings-organization--settings-organization-members--light:
- hash: v1.k794b7964.912f9a1af222d321b17ef4824cccf7ca1b8824766f27725b82d8d64bd256f5f8.QUSx4VxLoA9v96T8UxtoP3b2_Oo7zzT8y-IBd_c87zg
+ hash: v1.k794b7964.c8d32fdaefe419d2ef91af8adb1d737a73ef40252e7e3fc4b82a46a88093afc0.uYBWO-4P_b_XNk9CXW2fJYPVxZbahan-x21BgP7WcVc
scenes-app-settings-organization--settings-organization-proxy--dark:
hash: v1.k794b7964.8d224fe300274548438d00f38a72825c5e8425c42da637eb010efbc6791e6294.ZwYt5atQBiMtka55zyETWNWXpZhyoO2-FGb_nxzZcwE
scenes-app-settings-organization--settings-organization-proxy--light:
diff --git a/products/workflows/backend/api/message_assets.py b/products/workflows/backend/api/message_assets.py
index fbb154bab29a..c94af30bab3e 100644
--- a/products/workflows/backend/api/message_assets.py
+++ b/products/workflows/backend/api/message_assets.py
@@ -192,6 +192,10 @@ def _build_asset(row: tuple) -> MessageAsset:
)
+def _escape_like(value: str) -> str:
+ return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+
+
def fetch_message_assets(
team_id: int,
function_kind: str,
@@ -235,7 +239,7 @@ def fetch_message_assets(
kwargs["distinct_id"] = distinct_id
if search:
where.append("(recipient ILIKE %(search)s OR subject ILIKE %(search)s)")
- kwargs["search"] = f"%{search}%"
+ kwargs["search"] = f"%{_escape_like(search)}%"
if after:
where.append("sent_at >= toDateTime64(%(after)s, 6)")
kwargs["after"] = after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")
@@ -243,6 +247,8 @@ def fetch_message_assets(
where.append("sent_at <= toDateTime64(%(before)s, 6)")
kwargs["before"] = before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")
+ # Sends can share a sent_at down to the millisecond. The (invocation_id, action_id) tiebreak gives
+ # them a stable order, so offset pages neither repeat a send nor skip one at a page boundary.
query = f"""
SELECT {_OUTER_COLUMNS}
FROM (
@@ -252,7 +258,7 @@ def fetch_message_assets(
GROUP BY invocation_id, action_id
)
WHERE latest_is_deleted = 0
- ORDER BY latest_sent_at DESC
+ ORDER BY latest_sent_at DESC, invocation_id, action_id
LIMIT %(limit)s OFFSET %(offset)s
"""
diff --git a/products/workflows/backend/api/test/test_message_assets.py b/products/workflows/backend/api/test/test_message_assets.py
index a0c6db3f5feb..0ff7ff822e8e 100644
--- a/products/workflows/backend/api/test/test_message_assets.py
+++ b/products/workflows/backend/api/test/test_message_assets.py
@@ -136,11 +136,15 @@ class TestMessageAssets(ClickhouseTestMixin, APIBaseTest):
("bob", {"inv-1"}),
("Newsletter", {"inv-2"}),
("example.com", {"inv-1", "inv-2"}),
+ ("first_last", {"inv-3"}),
+ ("50%", {"inv-3"}),
]
)
def test_search_matches_recipient_or_subject(self, term: str, expected_ids: set):
self._seed("inv-1", recipient="[email protected]", subject="Welcome")
self._seed("inv-2", recipient="[email protected]", subject="Newsletter")
+ self._seed("inv-3", recipient="[email protected]", subject="50% off")
+ self._seed("inv-4", recipient="[email protected]", subject="500 offers")
results = self._list({"search": term}).json()
assert {r["invocation_id"] for r in results} == expected_ids
@@ -164,10 +168,13 @@ class TestMessageAssets(ClickhouseTestMixin, APIBaseTest):
assert {r["invocation_id"] for r in results} == {"recent"}
def test_respects_limit_and_offset(self):
+ sent_at = datetime.now(tz=UTC)
for i in range(5):
- self._seed(f"inv-{i}")
+ self._seed(f"inv-{i}", sent_at=sent_at)
assert len(self._list({"limit": 2}).json()) == 2
assert len(self._list({"limit": 2, "offset": 4}).json()) == 1
+ paged = [r["invocation_id"] for offset in (0, 2, 4) for r in self._list({"limit": 2, "offset": offset}).json()]
+ assert sorted(paged) == [f"inv-{i}" for i in range(5)]
def test_content_returns_html_bytes_inline(self):
self._seed("inv-1", action_id="step-a", html="<html><body>Hello Bob</body></html>")
diff --git a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx
index f6a218bc94d3..ce771a3a2db8 100644
--- a/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx
+++ b/products/workflows/frontend/Broadcasts/BroadcastSummary.tsx
@@ -1,22 +1,27 @@
-import { useActions, useValues } from 'kea'
+import { BindLogic, useActions, useValues } from 'kea'
+import { useEffect } from 'react'
-import { IconArrowLeft } from '@posthog/icons'
-import { LemonButton, LemonDialog, LemonTag } from '@posthog/lemon-ui'
+import { IconArrowLeft, IconLetter } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonDivider, LemonInput, LemonTag, LemonTagType } from '@posthog/lemon-ui'
import { appMetricsLogic } from 'lib/components/AppMetrics/appMetricsLogic'
import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'
import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import type { HogFlowBatchJobApi } from 'products/workflows/frontend/generated/api.schemas'
import { EmailMetricsSummary } from '../Workflows/EmailMetricsSummary'
+import { EmailViewerModal } from '../Workflows/EmailViewerModal'
+import type { MessageAsset } from '../Workflows/messageAssetsApi'
+import { broadcastSentLogic } from './broadcastSentLogic'
import { broadcastWizardLogic } from './broadcastWizardLogic'
-const BATCH_JOB_STATUS_TAG: Record<string, 'success' | 'default' | 'warning' | 'danger' | 'muted'> = {
+const BATCH_JOB_STATUS_TAG: Record<string, LemonTagType> = {
waiting: 'default',
queued: 'warning',
active: 'warning',
@@ -25,6 +30,207 @@ const BATCH_JOB_STATUS_TAG: Record<string, 'success' | 'default' | 'warning' | '
failed: 'danger',
}
+/**
+ * The recipients of one run. Each run binds its own broadcastSentLogic (keyed on the run id), so
+ * expanding a second run loads that run's sends instead of replacing the first one's.
+ */
+function RunRecipients({
+ workflowId,
+ runId,
+ runCreatedAt,
+}: {
+ workflowId: string
+ runId: string
+ runCreatedAt: string
+}): JSX.Element {
+ return (
+ <div className="bg-surface-secondary border-t px-4 py-3 w-0 min-w-full">
+ <BindLogic logic={broadcastSentLogic} props={{ id: workflowId || 'new', parentRunId: runId, runCreatedAt }}>
+ <RunRecipientsTable workflowId={workflowId} />
+ </BindLogic>
+ </div>
+ )
+}
+
+function RunRecipientsTable({ workflowId }: { workflowId: string }): JSX.Element {
+ const {
+ sends,
+ sendsLoading,
+ sendsFailed,
+ selectedSend,
+ recipientCount,
+ recipientSearch,
+ hasMoreRecipients,
+ runPastRetention,
+ } = useValues(broadcastSentLogic)
+ const { loadSends, loadMoreSends, selectInvocation, setRecipientSearch } = useActions(broadcastSentLogic)
+
+ useEffect(() => {
+ loadSends()
+ }, [loadSends])
+
+ const noSendsMessage = runPastRetention
+ ? "Recipient details are kept for 30 days after sending, so this run's list is no longer available."
+ : 'No sends recorded for this run yet.'
+
+ const columns: LemonTableColumns<MessageAsset> = [
+ {
+ title: 'Sent',
+ key: 'sent_at',
+ render: (_, row) => <TZLabel time={row.sent_at} />,
+ },
+ {
+ title: 'Subject',
+ key: 'subject',
+ render: (_, row) => <span className="wrap-anywhere">{row.subject || '-'}</span>,
+ },
+ {
+ title: 'Recipient',
+ key: 'recipient',
+ // An address has no break points, so without break-all its full length would widen the
+ // table past the panel and push the View email button out of sight.
+ render: (_, row) => <span className="font-mono text-xs break-all">{row.recipient}</span>,
+ },
+ {
+ title: '',
+ key: 'actions',
+ width: 0,
+ render: (_, row) => (
+ <div className="flex justify-end whitespace-nowrap">
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ icon={<IconLetter />}
+ onClick={() => selectInvocation(row.invocation_id)}
+ data-attr="broadcast-view-recipient-email"
+ >
+ View email
+ </LemonButton>
+ </div>
+ ),
+ },
+ ]
+
+ if (!sendsLoading && recipientCount === 0 && !recipientSearch) {
+ return (
+ <span className="text-sm text-muted">
+ {sendsFailed ? "Couldn't load recipients. Refresh the page to try again." : noSendsMessage}
+ </span>
+ )
+ }
+
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-sm font-semibold whitespace-nowrap">
+ {sendsFailed
+ ? "Couldn't load recipients"
+ : sendsLoading && recipientCount === 0
+ ? 'Loading recipients'
+ : `${humanFriendlyNumber(recipientCount)}${hasMoreRecipients ? '+' : ''} ${
+ recipientCount === 1 ? 'recipient' : 'recipients'
+ }${recipientSearch ? ' matching' : ''}`}
+ </span>
+ <LemonDivider vertical />
+ <LemonInput
+ size="small"
+ type="search"
+ placeholder="Search by email or subject"
+ value={recipientSearch}
+ onChange={setRecipientSearch}
+ className="w-full min-w-40 max-w-64 flex-1"
+ data-attr="broadcast-sent-search"
+ />
+ </div>
+ {/* Each day of sends expires separately. A run that sent over several days still lists its later
+ days after its first day expires, so a non-empty list can be incomplete. */}
+ {runPastRetention && !sendsFailed ? (
+ <span className="text-xs text-muted">
+ Recipient details are kept for 30 days after sending, so this list may not include everyone this run
+ reached.
+ </span>
+ ) : null}
+ <LemonTable
+ // The loader keeps the previous rows on failure, and they no longer match the search.
+ dataSource={sendsFailed ? [] : sends}
+ loading={sendsLoading}
+ rowKey="invocation_id"
+ columns={columns}
+ nouns={['recipient', 'recipients']}
+ emptyState={
+ sendsFailed
+ ? "Couldn't load recipients. Change the search to try again, or refresh the page."
+ : recipientSearch
+ ? 'No recipients match. Clear the search to see everyone.'
+ : noSendsMessage
+ }
+ />
+ {hasMoreRecipients && !sendsFailed ? (
+ <div className="flex justify-center">
+ <LemonButton
+ type="secondary"
+ size="small"
+ loading={sendsLoading}
+ onClick={loadMoreSends}
+ data-attr="broadcast-sent-load-more"
+ >
+ Load more recipients
+ </LemonButton>
+ </div>
+ ) : null}
+ {selectedSend ? (
+ <EmailViewerModal
+ workflowId={workflowId}
+ invocationId={selectedSend.invocation_id}
+ actionId={selectedSend.action_id}
+ isOpen
+ onClose={() => selectInvocation(null)}
+ title={`Email sent to ${selectedSend.recipient}`}
+ description={selectedSend.subject}
+ />
+ ) : null}
+ </div>
+ )
+}
+
+function RunsTable({
+ workflowId,
+ batchJobs,
+ batchJobsLoading,
+ columns,
+}: {
+ workflowId: string
+ batchJobs: HogFlowBatchJobApi[]
+ batchJobsLoading: boolean
+ columns: LemonTableColumns<HogFlowBatchJobApi>
+}): JSX.Element {
+ const { expandedRunIds } = useValues(broadcastWizardLogic)
+ const { expandRun, collapseRun } = useActions(broadcastWizardLogic)
+
+ return (
+ <LemonTable
+ dataSource={batchJobs}
+ loading={batchJobsLoading}
+ rowKey="id"
+ columns={columns}
+ nouns={['run', 'runs']}
+ expandable={{
+ expandedRowRender: (job) => (
+ <RunRecipients workflowId={workflowId} runId={job.id} runCreatedAt={job.created_at} />
+ ),
+ rowExpandable: (job) => !!job.id,
+ // A table inside a table runs out of room first. Dropping the indent cell gives the
+ // recipients back the width the toggle column would otherwise take.
+ noIndent: true,
+ isRowExpanded: (job) => (expandedRunIds.includes(job.id) ? 1 : 0),
+ onRowExpand: (job) => expandRun(job.id),
+ onRowCollapse: (job) => collapseRun(job.id),
+ }}
+ emptyState="No runs yet. Scheduled broadcasts appear here after they send."
+ />
+ )
+}
+
export function BroadcastSummary(): JSX.Element {
const {
broadcast,
@@ -157,13 +363,11 @@ export function BroadcastSummary(): JSX.Element {
<div className="flex flex-col gap-2">
<h2 className="m-0 text-lg font-semibold">Runs</h2>
- <LemonTable
- dataSource={batchJobs}
- loading={batchJobsLoading}
- rowKey="id"
+ <RunsTable
+ workflowId={broadcastId ?? ''}
+ batchJobs={batchJobs}
+ batchJobsLoading={batchJobsLoading}
columns={batchJobColumns}
- nouns={['run', 'runs']}
- emptyState="No runs yet. Scheduled broadcasts appear here after they send."
/>
</div>
</div>
diff --git a/products/workflows/frontend/Broadcasts/broadcastSentLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastSentLogic.test.ts
new file mode 100644
index 000000000000..96e969ad3f22
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/broadcastSentLogic.test.ts
@@ -0,0 +1,122 @@
+import { initKeaTests } from '~/test/init'
+
+import { MessageAsset, MessageAssetsParams, getMessageAssets } from '../Workflows/messageAssetsApi'
+import { broadcastSentLogic } from './broadcastSentLogic'
+
+jest.mock('../Workflows/messageAssetsApi', () => ({ getMessageAssets: jest.fn() }))
+
+const sends = (prefix: string, count: number): MessageAsset[] =>
+ Array.from({ length: count }, (_, i) => ({
+ invocation_id: `${prefix}-${i}`,
+ action_id: 'email',
+ function_id: 'flow-1',
+ function_name: 'Broadcast',
+ parent_run_id: 'run-1',
+ kind: 'email',
+ distinct_id: `${prefix}-${i}`,
+ person_id: `person-${prefix}-${i}`,
+ recipient: `${prefix}-${i}@example.com`,
+ subject: 'Hello',
+ status: 'sent',
+ sent_at: '2026-01-01T00:00:00Z',
+ }))
+
+describe('broadcastSentLogic', () => {
+ let requests: { params: MessageAssetsParams; resolve: (rows: MessageAsset[]) => void }[]
+
+ beforeEach(() => {
+ initKeaTests()
+ requests = []
+ jest.mocked(getMessageAssets).mockImplementation(
+ (_id, params = {}) => new Promise((resolve) => requests.push({ params, resolve }))
+ )
+ })
+
+ it('keeps the new search results when a stale load-more re-enables the button', async () => {
+ jest.useFakeTimers()
+ try {
+ const logic = broadcastSentLogic({ id: 'flow-1', parentRunId: 'run-1', runCreatedAt: null })
+ logic.mount()
+
+ logic.actions.loadSends()
+ requests[0].resolve(sends('all', 500))
+ await jest.advanceTimersByTimeAsync(0)
+
+ logic.actions.loadMoreSends()
+ logic.actions.setRecipientSearch('ada')
+ await jest.advanceTimersByTimeAsync(300)
+ requests[1].resolve(sends('all-page-2', 500))
+ await jest.advanceTimersByTimeAsync(0)
+
+ logic.actions.loadMoreSends()
+ const searchRequest = requests.find((request) => request.params.search === 'ada')
+ searchRequest?.resolve(sends('ada', 1))
+ await jest.advanceTimersByTimeAsync(0)
+ requests
+ .filter((request) => request !== searchRequest)
+ .forEach((request) => request.resolve(sends('stale', 500)))
+ await jest.advanceTimersByTimeAsync(0)
+
+ expect(logic.values.sends.map((send) => send.invocation_id)).toEqual(['ada-0'])
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('sends a search of only spaces as no search', async () => {
+ jest.useFakeTimers()
+ try {
+ const logic = broadcastSentLogic({ id: 'flow-1', parentRunId: 'run-1', runCreatedAt: null })
+ logic.mount()
+
+ logic.actions.setRecipientSearch(' ')
+ await jest.advanceTimersByTimeAsync(300)
+
+ expect(requests).toHaveLength(1)
+ expect(requests[0].params.search).toBeUndefined()
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('loads the full list at once when a search with no matches is cleared', async () => {
+ jest.useFakeTimers()
+ try {
+ const logic = broadcastSentLogic({ id: 'flow-1', parentRunId: 'run-1', runCreatedAt: null })
+ logic.mount()
+
+ logic.actions.setRecipientSearch('nobody')
+ await jest.advanceTimersByTimeAsync(300)
+ requests[0].resolve([])
+ await jest.advanceTimersByTimeAsync(0)
+
+ logic.actions.setRecipientSearch('')
+
+ expect(logic.values.sendsLoading).toBe(true)
+ expect(requests).toHaveLength(2)
+ expect(requests[1].params.search).toBeUndefined()
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it.each([
+ ['on the 29th UTC day after the run started', '2026-01-30T23:59:00Z', false],
+ ['from UTC midnight on the 30th day, before 30 full days pass', '2026-01-31T00:00:00Z', true],
+ ])('marks a late-day run as past retention %s', (_, now, expected) => {
+ jest.useFakeTimers()
+ jest.setSystemTime(new Date(now))
+ try {
+ const logic = broadcastSentLogic({
+ id: 'flow-1',
+ parentRunId: 'run-1',
+ runCreatedAt: '2026-01-01T23:00:00Z',
+ })
+ logic.mount()
+
+ expect(logic.values.runPastRetention).toBe(expected)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+})
diff --git a/products/workflows/frontend/Broadcasts/broadcastSentLogic.ts b/products/workflows/frontend/Broadcasts/broadcastSentLogic.ts
new file mode 100644
index 000000000000..a12259969361
--- /dev/null
+++ b/products/workflows/frontend/Broadcasts/broadcastSentLogic.ts
@@ -0,0 +1,244 @@
+import { MakeLogicType, actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { dayjs } from 'lib/dayjs'
+
+import { MessageAsset, getMessageAssets } from '../Workflows/messageAssetsApi'
+import { BroadcastWizardLogicProps } from './broadcastWizardLogic'
+
+/** How many recipients a page holds. A run can reach far more, so further pages load on request. */
+const SENT_ROW_LIMIT = 500
+
+/** Matches MESSAGE_ASSETS_TTL_DAYS: ClickHouse drops a day's sends at UTC midnight this many days after that day. */
+const SEND_RETENTION_DAYS = 30
+
+interface SendsQuery {
+ search: string
+}
+
+export interface BroadcastSentLogicProps extends BroadcastWizardLogicProps {
+ /** The batch run whose sends to list. Every send of a broadcast belongs to one. */
+ parentRunId: string | null
+ /** When the run started. Its sends go out at or after this time. */
+ runCreatedAt: string | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface broadcastSentLogicValues {
+ hasMoreRecipients: boolean
+ recipientCount: number
+ recipientSearch: string
+ runPastRetention: boolean
+ selectedInvocationId: string | null
+ selectedSend: MessageAsset | null
+ sends: MessageAsset[]
+ sendsFailed: boolean
+ sendsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface broadcastSentLogicActions {
+ loadMoreSends: () => any
+ loadMoreSendsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadMoreSendsSuccess: (
+ sends: MessageAsset[],
+ payload?: any
+ ) => {
+ sends: MessageAsset[]
+ payload?: any
+ }
+ loadSends: (_: void) => void
+ loadSendsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSendsSuccess: (
+ sends: MessageAsset[],
+ payload?: void
+ ) => {
+ sends: MessageAsset[]
+ payload?: void
+ }
+ selectInvocation: (invocationId: string | null) => {
+ invocationId: string | null
+ }
+ setHasMoreRecipients: (hasMore: boolean) => {
+ hasMore: boolean
+ }
+ setRecipientSearch: (search: string) => {
+ search: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface broadcastSentLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ selectedSend: (sends: MessageAsset[], selectedInvocationId: string | null) => MessageAsset | null
+ recipientCount: (sends: MessageAsset[]) => number
+ runPastRetention: (runCreatedAt: string | null) => boolean
+ }
+}
+
+export type broadcastSentLogicType = MakeLogicType<
+ broadcastSentLogicValues,
+ broadcastSentLogicActions,
+ BroadcastSentLogicProps,
+ broadcastSentLogicMeta
+>
+
+export const broadcastSentLogic = kea<broadcastSentLogicType>([
+ path(['products', 'workflows', 'frontend', 'Broadcasts', 'broadcastSentLogic']),
+ props({} as BroadcastSentLogicProps),
+ key((props) => `${props.id}-${props.parentRunId ?? 'none'}`),
+
+ actions({
+ selectInvocation: (invocationId: string | null) => ({ invocationId }),
+ setRecipientSearch: (search: string) => ({ search }),
+ setHasMoreRecipients: (hasMore: boolean) => ({ hasMore }),
+ }),
+
+ loaders(({ props, values, actions, cache }) => {
+ const loadPage = async (query: SendsQuery, offset: number): Promise<MessageAsset[]> => {
+ if (!props.id || props.id === 'new' || !props.parentRunId) {
+ return []
+ }
+ // Scoped to the run rather than the flow: a recurring broadcast has one set of
+ // sends per run, and mixing them would double-count a recipient.
+ const page = await getMessageAssets(props.id, {
+ parent_run_id: props.parentRunId,
+ // Searched and filtered on the server: a run can reach far more people than one page
+ // holds, so filtering the loaded pages would cover only the first slice of them.
+ search: query.search || undefined,
+ limit: SENT_ROW_LIMIT,
+ offset,
+ })
+ return page
+ }
+ return {
+ sends: [
+ [] as MessageAsset[],
+ {
+ loadSends: async (_: void, breakpoint) => {
+ cache.queryVersion = (cache.queryVersion ?? 0) + 1
+ const version = cache.queryVersion
+ // The API trims the search and rejects a blank one, so spaces alone count as no search.
+ const query = { search: values.recipientSearch.trim() }
+ let page: MessageAsset[]
+ try {
+ page = await loadPage(query, 0)
+ } catch (error) {
+ // A newer search has started, so this failure no longer describes what is shown.
+ breakpoint()
+ throw error
+ }
+ // Drops a response that lands after a newer search or filter started.
+ breakpoint()
+ cache.loadedQuery = query
+ cache.loadedVersion = version
+ cache.nextOffset = page.length
+ actions.setHasMoreRecipients(page.length >= SENT_ROW_LIMIT)
+ return page
+ },
+ // Pages the query the shown rows came from, so a search typed since cannot be
+ // appended at an offset that belongs to the previous results. A page that lands
+ // after a newer query started is dropped rather than written over its results.
+ loadMoreSends: async () => {
+ const version = cache.queryVersion
+ // The first page of a newer query has not landed yet, so the shown rows and the
+ // offset still belong to the old query. Any load-more success clears the shared
+ // loading flag, so the button can be clicked in this window.
+ if (cache.loadedVersion !== version) {
+ return values.sends
+ }
+ const shown = values.sends
+ const offset: number = cache.nextOffset ?? shown.length
+ const page = await loadPage(cache.loadedQuery ?? { search: '' }, offset)
+ if (version !== cache.queryVersion) {
+ return values.sends
+ }
+ cache.nextOffset = offset + page.length
+ actions.setHasMoreRecipients(page.length >= SENT_ROW_LIMIT)
+ // A run that is still sending adds rows at the top, which pushes rows from the end
+ // of the shown pages onto this one. Dropping them keeps each recipient listed once.
+ // The offset counts every row the server returned, so it moves past the repeats
+ // instead of fetching them again.
+ const shownKeys = new Set(shown.map((send) => `${send.invocation_id}:${send.action_id}`))
+ return [
+ ...shown,
+ ...page.filter((send) => !shownKeys.has(`${send.invocation_id}:${send.action_id}`)),
+ ]
+ },
+ },
+ ],
+ }
+ }),
+
+ reducers({
+ // An empty list and a failed request both render as no rows, but they mean different things
+ // to someone checking whether a send reached anyone.
+ sendsFailed: [
+ false,
+ {
+ loadSends: () => false,
+ loadSendsSuccess: () => false,
+ loadSendsFailure: () => true,
+ },
+ ],
+ selectedInvocationId: [
+ null as string | null,
+ {
+ selectInvocation: (_, { invocationId }) => invocationId,
+ loadSends: () => null,
+ },
+ ],
+ hasMoreRecipients: [
+ false,
+ {
+ setHasMoreRecipients: (_, { hasMore }) => hasMore,
+ },
+ ],
+ recipientSearch: [
+ '',
+ {
+ setRecipientSearch: (_, { search }) => search,
+ },
+ ],
+ }),
+
+ listeners(({ actions }) => ({
+ setRecipientSearch: async ({ search }, breakpoint) => {
+ // A cleared search loads at once. During a delay the old search's empty results would show
+ // with no search, which reads as a run with no sends and replaces the search input.
+ if (search) {
+ await breakpoint(300)
+ }
+ actions.loadSends()
+ },
+ })),
+
+ selectors({
+ selectedSend: [
+ (s) => [s.sends, s.selectedInvocationId],
+ (sends: MessageAsset[], selectedInvocationId: string | null): MessageAsset | null =>
+ sends.find((send) => send.invocation_id === selectedInvocationId) ?? null,
+ ],
+ recipientCount: [(s) => [s.sends], (sends: MessageAsset[]): number => sends.length],
+ // An empty list for an older run can mean its sends expired, not that it reached nobody.
+ runPastRetention: [
+ (_, p) => [p.runCreatedAt],
+ (runCreatedAt: string | null): boolean =>
+ !!runCreatedAt &&
+ dayjs().isSameOrAfter(dayjs.utc(runCreatedAt).startOf('day').add(SEND_RETENTION_DAYS, 'day')),
+ ],
+ }),
+])
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index 218b8bcf97ca..79fc8a594a1c 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -119,6 +119,8 @@ export interface broadcastWizardLogicValues {
effectiveTimezone: string
email: BroadcastEmailValue
emailRateLimit: HogFlowEmailSendingRateLimitApi | null
+ expandedRunIds: string[]
+ expandedRunOverride: string[] | null
firstInvalidStep: BroadcastWizardStep | null
goalEnabled: boolean
hasHydrated: boolean
@@ -141,9 +143,15 @@ export interface broadcastWizardLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastWizardLogicActions {
+ collapseRun: (runId: string) => {
+ runId: string
+ }
continueStep: () => {
value: true
}
+ expandRun: (runId: string) => {
+ runId: string
+ }
hydrateFromBroadcast: (broadcast: HogFlowApi) => {
broadcast: HogFlowApi
}
@@ -225,6 +233,9 @@ export interface broadcastWizardLogicActions {
setEmailRateLimit: (emailRateLimit: HogFlowEmailSendingRateLimitApi | null) => {
emailRateLimit: HogFlowEmailSendingRateLimitApi | null
}
+ setExpandedRunOverride: (runIds: string[]) => {
+ runIds: string[]
+ }
setGoalEnabled: (enabled: boolean) => {
enabled: boolean
}
@@ -273,6 +284,7 @@ export interface broadcastWizardLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
broadcastId: (broadcast: HogFlowApi | null, id: string) => string | null
+ expandedRunIds: (expandedRunOverride: string[] | null, batchJobs: HogFlowBatchJobApi[]) => string[]
canMoveToDraft: (
broadcast: HogFlowApi | null,
batchJobs: HogFlowBatchJobApi[],
@@ -349,6 +361,9 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
setRecurringRepeating: (repeating: boolean) => ({ repeating }),
hydrateFromBroadcast: (broadcast: HogFlowApi) => ({ broadcast }),
saveBroadcastFinished: (broadcast: HogFlowApi | null) => ({ broadcast }),
+ expandRun: (runId: string) => ({ runId }),
+ collapseRun: (runId: string) => ({ runId }),
+ setExpandedRunOverride: (runIds: string[]) => ({ runIds }),
launchBroadcast: true,
launchBroadcastFinished: true,
moveToDraft: true,
@@ -399,6 +414,13 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
saveBroadcastFinished: (state: HogFlowApi | null, { broadcast }: { broadcast: HogFlowApi | null }) =>
broadcast ?? state,
},
+ // Null until the sender expands or collapses a run; until then the latest run shows open.
+ expandedRunOverride: [
+ null as string[] | null,
+ {
+ setExpandedRunOverride: (_, { runIds }) => runIds,
+ },
+ ],
currentStep: [
'recipients' as BroadcastWizardStep,
{
@@ -568,6 +590,12 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
(s, p) => [s.broadcast, p.id],
(broadcast: HogFlowApi | null, id: string): string | null => broadcast?.id ?? (id !== 'new' ? id : null),
],
+ // The latest run is what a sender opens a sent broadcast to read, so it starts expanded.
+ expandedRunIds: [
+ (s) => [s.expandedRunOverride, s.batchJobs],
+ (override: string[] | null, batchJobs: HogFlowBatchJobApi[]): string[] =>
+ override ?? (batchJobs[0]?.id ? [batchJobs[0].id] : []),
+ ],
canMoveToDraft: [
(s) => [s.broadcast, s.batchJobs, s.hasLoadedBatchJobs],
(broadcast: HogFlowApi | null, batchJobs: HogFlowBatchJobApi[], hasLoadedBatchJobs: boolean): boolean =>
@@ -710,6 +738,12 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}),
listeners(({ actions, values }) => ({
+ expandRun: ({ runId }) => {
+ actions.setExpandedRunOverride([...values.expandedRunIds.filter((id) => id !== runId), runId])
+ },
+ collapseRun: ({ runId }) => {
+ actions.setExpandedRunOverride(values.expandedRunIds.filter((id) => id !== runId))
+ },
setAudienceProperties: async (_, breakpoint) => {
// Debounce so each filter keystroke doesn't fire a preview query.
await breakpoint(500)