: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(subscriptions): show per-recipient and per-item delivery outcomes (#76086)
Matt Puaf2459f2f9af3
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex 77c272266ab8..577d95d30482 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -1285,6 +1285,11 @@ class SubscriptionDeliverySerializer(serializers.ModelSerializer):# nullable). Single source of truth — keep in sync when adding AI-derived delivery fields.# ai_report_prompt is user-authored (not query-derived) and already readable on the parent# subscription, so it is intentionally not scrubbed.+ # recipient_results is also intentionally not scrubbed: its human_readable_error values are+ # audience-independent delivery failure reasons (auto-disable causes, prompt rejections, Slack+ # thread-failure counts) that carry no query-derived data. New producers of+ # recipient_results[].human_readable_error must keep that invariant — never route a+ # query/executor-derived message through it, since query-restricted viewers can read it.AI_REPORT_SCRUBBED: ClassVar[dict[str, object | None]] = {"content_snapshot": {},"change_summary": None,diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.pyindex 7e2aa8fcd407..ada5e3915f8e 100644--- a/posthog/temporal/tests/test_subscriptions_workflows.py+++ b/posthog/temporal/tests/test_subscriptions_workflows.py@@ -595,6 +595,7 @@ async def test_process_subscription_records_missing_slack_integration_failure("message": "Slack integration disconnected","type": "missing_integration",},+ "human_readable_error": "Slack integration disconnected",}]mock_get_slack.assert_not_called()diff --git a/products/exports/backend/temporal/subscriptions/activities.py b/products/exports/backend/temporal/subscriptions/activities.pyindex ef4a600862da..2ca6166f6182 100644--- a/products/exports/backend/temporal/subscriptions/activities.py+++ b/products/exports/backend/temporal/subscriptions/activities.py@@ -59,6 +59,11 @@ LOGGER = get_logger(__name__)# Used only as the recipient_results error message — `no_assets` doesn't auto-disable# (it indicates a transient resolve failure that retries can recover from).NO_ASSETS_REASON = "No assets to deliver — likely a transient export pipeline failure; will retry on next schedule"+# Plain-English twin of NO_ASSETS_REASON for the delivery-history UI: "assets" and "export pipeline"+# are internal jargon subscribers won't parse.+NO_ASSETS_HUMAN_READABLE_REASON = (+ "Nothing could be generated to send this time. We'll try again on the next scheduled run."+)class NoExportableInsightsError(Exception):@@ -240,6 +245,7 @@ async def validate_subscription_for_delivery(subscription_id: int) -> Subscriptirecipient=subscription.target_value,status="failed",error={"message": reason.description, "type": reason.key},+ human_readable_error=reason.description,))@@ -475,6 +481,7 @@ async def _deliver_insight_dashboard_subscription(recipient=subscription.target_value,status="failed",error={"message": NO_ASSETS_REASON, "type": "no_assets"},+ human_readable_error=NO_ASSETS_HUMAN_READABLE_REASON,))# Plain Exception — `_capture_delivery_failed_event` only reads `str(e)` anddiff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.pyindex 33e33d4a5f5b..9d0681222669 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py@@ -283,11 +283,13 @@ async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> Gen# Seed a recipient result with the exception detail first — it carries planner# context that the disable reason (appended next by `auto_disable_and_return`)# doesn't.+ # PromptRejectedError messages are handcrafted rejections (empty/too long/no creator), safe to show.recipient_results = [RecipientResult(recipient=subscription.target_value,status="failed",error={"message": str(exc), "type": "PromptRejectedError"},+ human_readable_error=str(exc),)]aborted = await auto_disable_and_return(subscription, AI_PROMPT_INVALID_DISABLE_REASON, recipient_results)diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.pyindex 32c44c922191..b4e1a4c22a08 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py@@ -10,7 +10,7 @@ import structlogfrom posthog.schema import AssistantHogQLQuery-from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError, ResolutionError+from posthog.hogql.errors import ExposedHogQLError, InternalHogQLErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team, User@@ -45,6 +45,7 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generabuild_enriched_prompt,build_frozen_prompt,)+from products.exports.backend.temporal.subscriptions.types import safe_error_messagefrom ee.hogai.context.insight.query_executor import AssistantQueryExecutorfrom ee.hogai.llm import MaxChatOpenAI@@ -103,22 +104,6 @@ def _all_queries_failed_notice(total_steps: int) -> str:)-def _safe_error_message(exc: BaseException) -> Optional[str]:- # HogQL/ClickHouse error text can echo team-scoped identifiers, so only the query-structure error- # classes (which describe the field/property the planner referenced) are safe to surface to the- # subscription owner — the same trust boundary the HogQL repair loop uses when forwarding to the- # fixer. Everything else stays type-only. Executors often wrap a resolution/exposed error in a- # generic Exception, so walk the __cause__/__context__ chain and surface the wrapped safe message.- seen: set[int] = set()- current: Optional[BaseException] = exc- while current is not None and id(current) not in seen:- if isinstance(current, (ExposedHogQLError, ResolutionError)):- return str(current)- seen.add(id(current))- current = current.__cause__ or current.__context__- return None--class ReportStage(StrEnum):PLANNER = "planner"QUERY = "query"@@ -448,7 +433,7 @@ async def _run_steps(original_hogql=current_hogql,# Forward the safe message (exposed/resolution errors describe the field/property the# planner referenced, which is what the fixer needs); fall back to the type name.- error_message=_safe_error_message(exc) or type(exc).__name__,+ error_message=safe_error_message(exc) or type(exc).__name__,step_description=safe_description,# The planner's project schema (event/property names) — a schema-blind fixer just# re-guesses the wrong name, so give it the same grounding the planner had.@@ -480,7 +465,7 @@ async def _run_steps(hogql=window.render_window_filter(current_hogql),ok=False,error_type=type_name,- human_readable_error=_safe_error_message(last_exc) if last_exc is not None else None,+ human_readable_error=safe_error_message(last_exc) if last_exc is not None else None,),)diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.pyindex 09215a02bde7..561f3694b07b 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py@@ -15,7 +15,6 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipe_arequest_hogql_fix,_plan_to_freeze,_run_steps,- _safe_error_message,generate_ai_report,)from products.exports.backend.temporal.subscriptions.ai_subscription.schemas import (@@ -30,6 +29,7 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generaReportWindow,StoredPlanInvalidError,)+from products.exports.backend.temporal.subscriptions.types import safe_error_message_RP = "products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline"_SG = "products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator"@@ -399,7 +399,26 @@ def _wrap(],)def test_safe_error_message_only_surfaces_query_structure_errors(exc, expected):- assert _safe_error_message(exc) == expected+ assert safe_error_message(exc) == expected+++def test_safe_error_message_respects_suppressed_context():+ # `raise ... from None` (__suppress_context__) is the author explicitly severing the chain — an+ # internal error they meant to hide must not surface via the wider insight-snapshot path.+ inner = ResolutionError("internal resolution detail")+ try:+ try:+ raise inner+ except ResolutionError:+ raise ValueError("sanitized outer") from None+ except ValueError as outer:+ assert safe_error_message(outer) is None+++def test_safe_error_message_strips_null_bytes():+ # Persisted to jsonb, which rejects NUL — the safe field gets the same scrub as the raw message.+ exc = ExposedHogQLError("bad\x00field")+ assert safe_error_message(exc) == "badfield"def _frozen_plan() -> dict:diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.pyindex e171418244ce..226a4672bb30 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_spec_generator.py@@ -67,6 +67,26 @@ class TestSanitizePrompt:def test_strips_html_tags_from_valid_prompt(self) -> None:assert sanitize_prompt("Show <script>alert(1)</script> pageviews") == "Show alert(1) pageviews"++class TestPromptRejectionOwnerSafe:+ """`PromptRejectedError` text is rendered verbatim in the delivery-history UI+ (`RecipientResult.human_readable_error`), so it must stay free of planner/LLM/user detail. This+ guard fails CI if a raise site starts interpolating into the message."""++ def test_rejection_messages_are_static_and_audience_safe(self) -> None:+ for raw, expected in [+ (None, "Prompt is empty."),+ (" ", "Prompt is empty."),+ ("x" * (PROMPT_MAX_LENGTH + 1), f"Prompt exceeds {PROMPT_MAX_LENGTH} characters."),+ ("<system></system>", "Prompt is empty."),+ ]:+ with pytest.raises(PromptRejectedError) as exc_info:+ sanitize_prompt(raw)+ # Exact match, not a substring — an interpolated detail (event names, query text) would+ # break the equality and trip this test.+ assert str(exc_info.value) == expected+ assert exc_info.value.args == (expected,)+def test_returns_cleaned_prompt(self) -> None:assert sanitize_prompt(" Weekly pageviews summary ") == "Weekly pageviews summary"diff --git a/products/exports/backend/temporal/subscriptions/delivery_common.py b/products/exports/backend/temporal/subscriptions/delivery_common.pyindex 59f4540eefbf..c99f2d8f41ba 100644--- a/products/exports/backend/temporal/subscriptions/delivery_common.py+++ b/products/exports/backend/temporal/subscriptions/delivery_common.py@@ -66,6 +66,7 @@ async def auto_disable_and_return(recipient=subscription.target_value,status="failed",error={"message": reason.description, "type": reason.key},+ human_readable_error=reason.description,))# `_capture_delivery_failed_event` only reads `str(e)` and `type(e).__name__`,@@ -120,7 +121,10 @@ async def deliver_email(_capture_delivery_failed_event(subscription, exc)recipient_results.append(RecipientResult(- recipient=email, status="failed", error={"message": str(exc), "type": type(exc).__name__}+ recipient=email,+ status="failed",+ error={"message": str(exc), "type": type(exc).__name__},+ human_readable_error=None,))failures.append((email, exc))@@ -223,14 +227,14 @@ async def deliver_slack(failed_thread_count=len(result.failed_thread_message_indices),total_thread_count=result.total_thread_messages,)+ failed_count = len(result.failed_thread_message_indices)+ partial_message = f"{failed_count} thread message{'s' if failed_count != 1 else ''} failed"recipient_results.append(RecipientResult(recipient=subscription.target_value,status="partial",- error={- "message": f"{len(result.failed_thread_message_indices)} thread message(s) failed",- "type": "partial_thread_failure",- },+ error={"message": partial_message, "type": "partial_thread_failure"},+ human_readable_error=partial_message,))return DeliverSubscriptionResult(recipient_results=recipient_results)diff --git a/products/exports/backend/temporal/subscriptions/insight_snapshot.py b/products/exports/backend/temporal/subscriptions/insight_snapshot.pyindex 399b2e3d8ba5..6fee9ed6d7a1 100644--- a/products/exports/backend/temporal/subscriptions/insight_snapshot.py+++ b/products/exports/backend/temporal/subscriptions/insight_snapshot.py@@ -29,6 +29,7 @@ from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.exports.backend.models.subscription import Subscriptionfrom products.exports.backend.temporal.subscriptions.delivery_common import strip_null_bytes+from products.exports.backend.temporal.subscriptions.types import safe_error_messagefrom products.product_analytics.backend.models.insight import Insightlogger = structlog.get_logger(__name__)@@ -207,8 +208,13 @@ def _execute_and_serialize_insight_query(return {"query_results": None,"cache_key": None,- # str(e) can echo offending query data, so scrub it like the result payload.- "query_error": {"type": type(e).__name__, "message": strip_null_bytes(str(e))},+ # str(e) can echo offending query data, so scrub it like the result payload. The UI+ # renders human_readable_error (safe subset) instead of message.+ "query_error": {+ "type": type(e).__name__,+ "message": strip_null_bytes(str(e)),+ "human_readable_error": safe_error_message(e),+ },}if isinstance(insight_result, NothingInCacheResult):@@ -217,6 +223,8 @@ def _execute_and_serialize_insight_query("query_error": {"type": "cache_miss","message": "No synchronous result (async or cache-only response)",+ # Static, audience-safe: a cold cache is a routine condition, not an internal error.+ "human_readable_error": "No cached result was available for this insight.",},}if insight_result.cache_key:@@ -259,6 +267,7 @@ def build_insight_delivery_snapshot(base["query_error"] = {"type": "missing_query","message": "Insight has no query or convertible filters",+ "human_readable_error": "This insight has no query to run.",}base["comparison_enabled"] = Falsebase["value_format"] = Nonediff --git a/products/exports/backend/temporal/subscriptions/types.py b/products/exports/backend/temporal/subscriptions/types.pyindex e207802de7f8..013401bef026 100644--- a/products/exports/backend/temporal/subscriptions/types.py+++ b/products/exports/backend/temporal/subscriptions/types.py@@ -2,9 +2,37 @@ import uuidimport typingimport dataclasses+from posthog.hogql.errors import ExposedHogQLError, ResolutionError+from posthog.slo.types import SloConfig+def safe_error_message(exc: BaseException) -> typing.Optional[str]:+ """Owner-safe snippet of an exception, or None when the text may carry team-scoped data.++ HogQL/ClickHouse error text can echo team-scoped identifiers (query data, internal+ names), so only the query-structure error classes (which describe the field/property the+ query referenced) are safe to surface to the subscription owner — the same trust boundary+ the HogQL repair loop uses when forwarding to the fixer. Everything else returns None so+ the caller falls back to a generic message. Executors often wrap a resolution/exposed+ error in a generic Exception, so walk the __cause__/__context__ chain for a wrapped safe+ message.++ The result is persisted to Postgres jsonb columns, so NUL bytes are stripped (Postgres+ rejects them); callers of the sibling raw "message" field already expect this scrub. The+ walk honours ``raise ... from None`` (``__suppress_context__``) — a deliberately severed+ chain stays severed, so an internal error the author meant to hide is never surfaced.+ """+ seen: set[int] = set()+ current: typing.Optional[BaseException] = exc+ while current is not None and id(current) not in seen:+ if isinstance(current, (ExposedHogQLError, ResolutionError)):+ return str(current).replace("\x00", "")+ seen.add(id(current))+ current = current.__cause__ or (None if current.__suppress_context__ else current.__context__)+ return None++class DeliveryStatus:"""Mirrors SubscriptionDelivery.Status choices for use in Temporal workflows.@@ -190,6 +218,9 @@ class RecipientResult:recipient: strstatus: RecipientResultStatuserror: typing.Optional[dict[str, str]] = None # {"message": str, "type": str}+ # Owner-safe failure reason; None when the raw error may carry team-scoped/internal detail.+ # The UI renders this (or a generic fallback), never error.message.+ human_readable_error: typing.Optional[str] = None@dataclasses.dataclassdiff --git a/products/exports/backend/temporal/subscriptions/workflows.py b/products/exports/backend/temporal/subscriptions/workflows.pyindex fdbf8743a087..0b82d0e3bfcd 100644--- a/products/exports/backend/temporal/subscriptions/workflows.py+++ b/products/exports/backend/temporal/subscriptions/workflows.py@@ -2,7 +2,6 @@ import jsonimport uuidimport asyncioimport datetime as dt-import dataclassesfrom collections.abc import Callable, Coroutinefrom typing import Any@@ -64,7 +63,12 @@ from products.exports.backend.temporal.subscriptions.types import (def _to_recipient_dicts(recipient_results: list[RecipientResult]) -> list[dict]:return [- {"recipient": r.recipient, "status": r.status, **({"error": r.error} if r.error else {})}+ {+ "recipient": r.recipient,+ "status": r.status,+ **({"error": r.error} if r.error else {}),+ **({"human_readable_error": r.human_readable_error} if r.human_readable_error else {}),+ }for r in recipient_results]@@ -246,7 +250,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):if abort_info is not None:# Just-disabled → FAILED with reason. Already-disabled (no failed_recipient) → SKIPPED default.if abort_info.failed_recipient is not None:- delivery_recipient_results = [dataclasses.asdict(abort_info.failed_recipient)]+ delivery_recipient_results = _to_recipient_dicts([abort_info.failed_recipient])final_status = DeliveryStatus.FAILEDreturn@@ -529,7 +533,7 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):# Just-disabled → FAILED with reason. Already-disabled (no failed_recipient)# → SKIPPED default (idempotency redispatch). Matches ProcessSubscriptionWorkflow.if abort_info.failed_recipient is not None:- delivery_recipient_results = [dataclasses.asdict(abort_info.failed_recipient)]+ delivery_recipient_results = _to_recipient_dicts([abort_info.failed_recipient])final_status = DeliveryStatus.FAILEDreturndiff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsxindex 237f8ba84e4e..ff73594770d5 100644--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'import { IconChevronLeft } from '@posthog/icons'-import { LemonCheckbox, LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'+import { LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'import { FlaggedFeature } from 'lib/components/FlaggedFeature'@@ -474,7 +474,7 @@ function EditSubscriptionForm({</LemonField><LemonField name="enabled" className="pb-2">{({ value, onChange }) => (- <LemonCheckbox+ <LemonSwitchchecked={value !== false}onChange={onChange}data-attr="subscription-enabled"diff --git a/products/subscriptions/frontend/scenes/SubscriptionScene.tsx b/products/subscriptions/frontend/scenes/SubscriptionScene.tsxindex 5d083f1efb77..165257099471 100644--- a/products/subscriptions/frontend/scenes/SubscriptionScene.tsx+++ b/products/subscriptions/frontend/scenes/SubscriptionScene.tsx@@ -1,9 +1,10 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import { LemonButton, LemonTag } from '@posthog/lemon-ui'+import { LemonButton } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'+import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { getCurrentTeamId } from 'lib/utils/getAppContext'import { SceneExport } from 'scenes/sceneTypes'@@ -46,17 +47,13 @@ function SubscriptionDetailActions({ sub }: { sub: SubscriptionApi }): JSX.Elemereturn (<div className="flex flex-wrap items-center gap-2">- <LemonTag type={enabled ? 'success' : 'danger'} data-attr="subscription-status-tag">- {enabled ? 'Enabled' : 'Disabled'}- </LemonTag>- <LemonButton- type="secondary"- onClick={() => setEnabled({ enabled: !enabled })}+ <LemonSwitch+ checked={enabled}+ onChange={(newEnabled) => setEnabled({ enabled: newEnabled })}loading={subscriptionLoading}+ label={enabled ? 'Enabled' : 'Disabled'}data-attr="subscription-toggle-enabled"- >- {enabled ? 'Disable subscription' : 'Enable subscription'}- </LemonButton>+ />{editHref ? (<LemonButton type="secondary" onClick={() => push(editHref)}>Edit subscription@@ -113,7 +110,7 @@ export function SubscriptionScene(): JSX.Element {actions={subscription ? <SubscriptionDetailActions sub={subscription} /> : undefined}/>{subscription ? (- // Mute the body when the subscription is paused — the LemonTag in the+ // Mute the body when the subscription is disabled — the switch in the// header is the explicit signal; this is the at-a-glance reinforcement.<div className={isSubscriptionEnabled(subscription) ? '' : 'opacity-60'}><SubscriptionSummary sub={subscription} />diff --git a/products/subscriptions/frontend/scenes/SubscriptionsScene.tsx b/products/subscriptions/frontend/scenes/SubscriptionsScene.tsxindex e8ad94dbe932..d97157d4b36b 100644--- a/products/subscriptions/frontend/scenes/SubscriptionsScene.tsx+++ b/products/subscriptions/frontend/scenes/SubscriptionsScene.tsx@@ -7,6 +7,7 @@ import { LemonButton, LemonMenu, LemonModal, Link } from '@posthog/lemon-ui'import { pngHoggie } from 'lib/brand/hoggies'import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'+import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'import { Spinner } from 'lib/lemon-ui/Spinner'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'@@ -33,14 +34,28 @@ import { SubscriptionsTab, subscriptionsSceneLogic } from './subscriptionsSceneLconst HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)+function SubscriptionEnabledSwitch({ sub }: { sub: SubscriptionApi }): JSX.Element {+ const { setSubscriptionEnabled } = useActions(subscriptionsSceneLogic)+ const { togglingEnabledIds } = useValues(subscriptionsSceneLogic)+ const enabled = isSubscriptionEnabled(sub)+ return (+ <LemonSwitch+ checked={enabled}+ onChange={(newEnabled) => setSubscriptionEnabled(sub.id, newEnabled)}+ loading={Boolean(togglingEnabledIds[sub.id])}+ aria-label={`${enabled ? 'Disable' : 'Enable'} ${subscriptionName(sub)}`}+ data-attr="subscription-row-toggle-enabled"+ />+ )+}+function SubscriptionsRowActions({ sub }: { sub: SubscriptionApi }): JSX.Element {const { push } = useActions(router)- const { deleteSubscriptionSuccess, deliverSubscription, setSubscriptionEnabled } =- useActions(subscriptionsSceneLogic)- const { deliveringSubscriptionId, togglingEnabledId } = useValues(subscriptionsSceneLogic)+ const { deleteSubscriptionSuccess, deliverSubscription } = useActions(subscriptionsSceneLogic)+ const { deliveringSubscriptionId, togglingEnabledIds } = useValues(subscriptionsSceneLogic)const href = subscriptionEditHref(sub)const isDelivering = deliveringSubscriptionId === sub.id- const isToggling = togglingEnabledId === sub.id+ const isToggling = Boolean(togglingEnabledIds[sub.id])const enabled = isSubscriptionEnabled(sub)return (@@ -54,12 +69,6 @@ function SubscriptionsRowActions({ sub }: { sub: SubscriptionApi }): JSX.Element},]: []),- {- label: enabled ? 'Disable subscription' : 'Enable subscription',- 'data-attr': 'subscription-list-item-toggle-enabled',- disabledReason: isToggling ? 'Updating…' : null,- onClick: () => setSubscriptionEnabled(sub.id, !enabled),- },...(enabled? [{@@ -191,6 +200,7 @@ export function SubscriptionsScene(): JSX.Element {sorting={subscriptionsSorting}onSort={setSubscriptionsSorting}renderRowActions={(sub) => <SubscriptionsRowActions sub={sub} />}+ renderEnabledToggle={(sub) => <SubscriptionEnabledSwitch sub={sub} />}/></>)}diff --git a/products/subscriptions/frontend/scenes/components/SubscriptionAiReportDelivery.tsx b/products/subscriptions/frontend/scenes/components/SubscriptionAiReportDelivery.tsxindex ecb43619c3a6..70fae8e468b3 100644--- a/products/subscriptions/frontend/scenes/components/SubscriptionAiReportDelivery.tsx+++ b/products/subscriptions/frontend/scenes/components/SubscriptionAiReportDelivery.tsx@@ -1,3 +1,5 @@+import { useMemo } from 'react'+import { LemonCollapse, LemonTag, Tooltip } from '@posthog/lemon-ui'import { CodeSnippet, Language } from 'lib/components/CodeSnippet'@@ -73,15 +75,262 @@ function diagnosticsSummary(diagnostics: readonly AIReportQueryDiagnosticApi[]):const failedIndexes = (diagnostics: readonly AIReportQueryDiagnosticApi[]): number[] =>diagnostics.map((d, i) => (d.ok === false ? i : -1)).filter((i) => i >= 0)-/** Whether a delivery row has any AI-generated detail to expand: an AI summary, the generating prompt,- * the delivered report, or per-query diagnostics. Single source of truth for the table's `rowExpandable`- * and `ExpandedDeliveryRow`'s early return, so the two can't disagree on which rows are expandable. */-export function deliveryRowHasExpandableContent(row: SubscriptionDeliveryApi): boolean {+/* ------------------------------------------------------------------ */+/* Per-recipient results */+/* ------------------------------------------------------------------ */++type DeliveryRecipientStatus = 'success' | 'failed' | 'partial'++interface DeliveryRecipientResult {+ recipient: string+ status: DeliveryRecipientStatus+ error: { message?: string } | null+ /** Owner-safe failure reason from the backend; never the raw exception text in `error.message`. */+ human_readable_error: string | null+}++/** Narrow the API's untyped `recipient_results` JSON into a typed list. Anything that doesn't match the+ * expected shape is dropped rather than erroring, so a partially-formed payload still shows what it can. */+function parseRecipientResults(raw: SubscriptionDeliveryApi['recipient_results']): DeliveryRecipientResult[] {+ if (!Array.isArray(raw)) {+ return []+ }+ return raw+ .map((r): DeliveryRecipientResult | null => {+ if (typeof r !== 'object' || r === null) {+ return null+ }+ const recipient = typeof (r as any).recipient === 'string' ? (r as any).recipient : null+ const status = (r as any).status+ if (!recipient || (status !== 'success' && status !== 'failed' && status !== 'partial')) {+ return null+ }+ const error = typeof (r as any).error === 'object' && (r as any).error !== null ? (r as any).error : null+ const humanReadable =+ typeof (r as any).human_readable_error === 'string' ? (r as any).human_readable_error : null+ return { recipient, status, error, human_readable_error: humanReadable }+ })+ .filter((r): r is DeliveryRecipientResult => r !== null)+}++/** What to show for a failed recipient: the backend's safe human_readable_error when present, else a+ * generic note. We deliberately never surface the raw exception text in error.message. */+function recipientFailureReason(r: Pick<DeliveryRecipientResult, 'human_readable_error'>): string {+ return r.human_readable_error || 'Delivery to this destination failed due to an internal error.'+}++function recipientStatusTag(status: DeliveryRecipientStatus): JSX.Element {+ if (status === 'success') {+ return <LemonTag type="success">Success</LemonTag>+ }+ if (status === 'failed') {+ return <LemonTag type="danger">Failed</LemonTag>+ }+ return <LemonTag type="warning">Partial</LemonTag>+}++/** Summary line for a recipients list. Null when every row shares one status — a tag per row already says+ * that, so a count would be redundant. Only the mixed outcome spells out the split. */+function recipientResultsSummary(results: readonly DeliveryRecipientResult[]): string | null {+ const total = results.length+ const succeeded = results.filter((r) => r.status === 'success').length+ const partial = results.filter((r) => r.status === 'partial').length+ const failed = results.filter((r) => r.status === 'failed').length+ const distinctStatuses = [succeeded > 0, partial > 0, failed > 0].filter(Boolean).length+ if (distinctStatuses < 2) {+ return null+ }+ const noun = total === 1 ? 'recipient' : 'recipients'+ const parts: string[] = []+ if (succeeded > 0) {+ parts.push(`${succeeded} succeeded`)+ }+ if (partial > 0) {+ parts.push(`${partial} partial`)+ }+ if (failed > 0) {+ parts.push(`${failed} failed`)+ }+ return `${total} ${noun} · ${parts.join(' · ')}`+}++// Success first, then partial, then failed — so failures sink to the bottom where they're easy to act on.+const RECIPIENT_STATUS_ORDER: Record<DeliveryRecipientStatus, number> = { success: 0, partial: 1, failed: 2 }++function DeliveryRecipients({ results }: { results: readonly DeliveryRecipientResult[] }): JSX.Element {+ const sorted = useMemo(+ () => [...results].sort((a, b) => RECIPIENT_STATUS_ORDER[a.status] - RECIPIENT_STATUS_ORDER[b.status]),+ [results]+ )+ const summary = recipientResultsSummary(results)return (- Boolean(row.change_summary) ||- Boolean(row.ai_report) ||- Boolean(row.ai_report_prompt) ||- (row.ai_report_diagnostics ?? []).length > 0+ <div className="flex flex-col gap-2">+ {summary ? <div className="text-secondary">{summary}</div> : null}+ <div className="flex flex-col divide-y rounded border bg-bg-light">+ {sorted.map((r, index) => (+ // Index in the key: the abort path can legitimately record two results for one recipient+ // (planner-rejection detail + disable reason), so recipient alone isn't unique.+ <div key={`${r.recipient}-${index}`} className="flex flex-col gap-1 px-3 py-2">+ <div className="flex items-center gap-2">+ {recipientStatusTag(r.status)}+ <span className="font-medium break-all">{r.recipient}</span>+ </div>+ {r.status === 'failed' || r.status === 'partial' ? (+ <div className={r.status === 'failed' ? 'text-danger text-xs' : 'text-warning text-xs'}>+ {recipientFailureReason(r)}+ </div>+ ) : null}+ </div>+ ))}+ </div>+ </div>+ )+}++/* ------------------------------------------------------------------ */+/* Per-insight items (dashboard / insight exports) */+/* ------------------------------------------------------------------ */++interface DeliveryInsightItem {+ key: string+ name: string+ /** True only when a query_error is present. Absence of query_error AND query_results means the item is a+ * pre-execution skeleton (a stuck/interrupted run) that never computed — rendered as pending, not success. */+ failed: boolean+ /** True when neither results nor an error were recorded, so the query never ran. */+ pending: boolean+ /** Owner-safe failure reason from the backend (never the raw exception text). */+ humanReadableError: string | null+}++/** Narrow the API's untyped `content_snapshot.insights[]` into a typed list. Each insight entry carries an+ * id/short_id/name plus an optional `query_error` marking that specific item's failure. */+function parseContentSnapshotInsights(raw: SubscriptionDeliveryApi['content_snapshot']): DeliveryInsightItem[] {+ if (typeof raw !== 'object' || raw === null) {+ return []+ }+ const insights = (raw as any).insights+ if (!Array.isArray(insights)) {+ return []+ }+ return insights+ .map((ins, index): DeliveryInsightItem | null => {+ if (typeof ins !== 'object' || ins === null) {+ return null+ }+ const name =+ typeof ins.name === 'string' && ins.name+ ? ins.name+ : typeof ins.short_id === 'string' && ins.short_id+ ? ins.short_id+ : `Insight ${index + 1}`+ const queryError = typeof ins.query_error === 'object' && ins.query_error !== null ? ins.query_error : null+ const hasResults = typeof ins.query_results === 'object' && ins.query_results !== null+ const humanReadableError =+ queryError && typeof queryError.human_readable_error === 'string'+ ? queryError.human_readable_error+ : null+ const key =+ ins.id != null+ ? `id:${ins.id}`+ : typeof ins.short_id === 'string'+ ? `short:${ins.short_id}`+ : `idx:${index}`+ return {+ key,+ name,+ failed: queryError !== null,+ pending: queryError === null && !hasResults,+ humanReadableError,+ }+ })+ .filter((i): i is DeliveryInsightItem => i !== null)+}++/** Summary line for a content list. Null when there's nothing to break down (no failures and no pending items —+ * the per-item tags already say "Computed"). Only surfaces when some item didn't cleanly compute. */+function insightItemsSummary(items: readonly DeliveryInsightItem[]): string | null {+ const total = items.length+ const failed = items.filter((i) => i.failed).length+ const pending = items.filter((i) => i.pending).length+ const computed = total - failed - pending+ if (failed === 0 && pending === 0) {+ return null+ }+ const noun = total === 1 ? 'item' : 'items'+ const parts: string[] = []+ if (computed > 0) {+ parts.push(`${computed} computed`)+ }+ if (pending > 0) {+ parts.push(`${pending} did not run`)+ }+ if (failed > 0) {+ parts.push(`${failed} failed to compute`)+ }+ return `${total} ${noun} · ${parts.join(' · ')}`+}++// Computed first, then pending, then failed — actionable failures sink to the bottom.+const INSIGHT_ITEM_ORDER = (item: DeliveryInsightItem): number => (item.failed ? 2 : item.pending ? 1 : 0)++function insightItemTag(item: DeliveryInsightItem): JSX.Element {+ if (item.failed) {+ return <LemonTag type="danger">Failed</LemonTag>+ }+ if (item.pending) {+ return <LemonTag type="default">Did not run</LemonTag>+ }+ return <LemonTag type="success">Computed</LemonTag>+}++function DeliveryInsightItems({ items }: { items: readonly DeliveryInsightItem[] }): JSX.Element {+ const sorted = useMemo(() => [...items].sort((a, b) => INSIGHT_ITEM_ORDER(a) - INSIGHT_ITEM_ORDER(b)), [items])+ const summary = insightItemsSummary(items)+ return (+ <div className="flex flex-col gap-2">+ {summary ? <div className="text-secondary">{summary}</div> : null}+ <div className="flex flex-col divide-y rounded border bg-bg-light">+ {sorted.map((item) => (+ <div key={item.key} className="flex flex-col gap-1 px-3 py-2">+ <div className="flex items-center gap-2">+ {insightItemTag(item)}+ <span className="font-medium break-all">{item.name}</span>+ </div>+ {item.failed ? (+ <div className="text-danger text-xs">+ {item.humanReadableError || 'This item failed to run due to an internal error.'}+ </div>+ ) : null}+ </div>+ ))}+ </div>+ </div>+ )+}++/** Whether a delivery row has any detail to expand: AI-generated content (summary, prompt, report, per-query+ * diagnostics) or per-item delivery detail (recipients / exported insights). Single source of truth for the+ * table's `rowExpandable` and `ExpandedDeliveryRow`'s early return, so the two can't disagree on which rows+ * are expandable. */+export function deliveryRowHasExpandableContent(row: SubscriptionDeliveryApi): boolean {+ if (row.change_summary || row.ai_report || row.ai_report_prompt || (row.ai_report_diagnostics ?? []).length > 0) {+ return true+ }+ if (Array.isArray(row.recipient_results) && row.recipient_results.length > 0) {+ return true+ }+ // Skeleton-only snapshots (stuck runs where every insight is still pending) have nothing actionable+ // to show — don't offer an expand chevron for them. The full parse happens in ExpandedDeliveryRow.+ if (!row.content_snapshot || typeof row.content_snapshot !== 'object') {+ return false+ }+ const insights = (row.content_snapshot as { insights?: unknown }).insights+ if (!Array.isArray(insights)) {+ return false+ }+ return insights.some(+ (ins) => typeof ins === 'object' && ins !== null && ('query_results' in ins || 'query_error' in ins))}@@ -127,12 +376,15 @@ function GeneratedQueries({ diagnostics }: { diagnostics: readonly AIReportQuery)}-/** Expanded detail for a delivery row: the AI summary, the prompt at generation time, the delivered report,- * and the per-query accordion. Returns null when there's nothing AI-generated to show. */+/** Expanded detail for a delivery row: AI summary, prompt at generation time, delivered report, per-query+ * accordion, plus per-recipient and per-insight delivery outcomes. Returns null when there's nothing to show. */export function ExpandedDeliveryRow({ row }: { row: SubscriptionDeliveryApi }): JSX.Element | null {const diagnostics = row.ai_report_diagnostics ?? []const report = row.ai_reportconst prompt = row.ai_report_prompt+ // Memoized: payloads can be large for dashboard exports and this row re-renders with the table.+ const recipients = useMemo(() => parseRecipientResults(row.recipient_results), [row.recipient_results])+ const insights = useMemo(() => parseContentSnapshotInsights(row.content_snapshot), [row.content_snapshot])if (!deliveryRowHasExpandableContent(row)) {return null}@@ -162,6 +414,18 @@ export function ExpandedDeliveryRow({ row }: { row: SubscriptionDeliveryApi }):</div></div>) : null}+ {recipients.length > 0 ? (+ <div className="flex flex-col gap-2">+ <div className="text-xs font-semibold uppercase tracking-wide text-secondary">Delivery</div>+ <DeliveryRecipients results={recipients} />+ </div>+ ) : null}+ {insights.length > 0 ? (+ <div className="flex flex-col gap-2">+ <div className="text-xs font-semibold uppercase tracking-wide text-secondary">Content</div>+ <DeliveryInsightItems items={insights} />+ </div>+ ) : null}{diagnostics.length > 0 ? (<div className="flex flex-col gap-2"><div className="text-xs font-semibold uppercase tracking-wide text-secondary">diff --git a/products/subscriptions/frontend/scenes/components/SubscriptionsTable.tsx b/products/subscriptions/frontend/scenes/components/SubscriptionsTable.tsxindex b1d1752e7fb7..74cbc4ba6b4f 100644--- a/products/subscriptions/frontend/scenes/components/SubscriptionsTable.tsx+++ b/products/subscriptions/frontend/scenes/components/SubscriptionsTable.tsx@@ -86,7 +86,10 @@ export function subscriptionResourceLabel(sub: SubscriptionApi, mode: Subscriptireturn '—'}-function buildColumns(renderRowActions: (sub: SubscriptionApi) => JSX.Element): LemonTableColumns<SubscriptionApi> {+function buildColumns(+ renderRowActions: (sub: SubscriptionApi) => JSX.Element,+ renderEnabledToggle?: (sub: SubscriptionApi) => JSX.Element+): LemonTableColumns<SubscriptionApi> {return [{title: 'Name',@@ -228,11 +231,14 @@ function buildColumns(renderRowActions: (sub: SubscriptionApi) => JSX.Element):sorter: true,},{- title: 'Status',+ title: 'Enabled',key: 'enabled',dataIndex: 'enabled',+ width: '5rem',render: (_value: unknown, sub: SubscriptionApi) =>- isSubscriptionEnabled(sub) ? (+ renderEnabledToggle ? (+ renderEnabledToggle(sub)+ ) : isSubscriptionEnabled(sub) ? (<LemonTag type="success">Enabled</LemonTag>) : (<LemonTag type="danger">Disabled</LemonTag>@@ -254,6 +260,8 @@ export interface SubscriptionsTableProps {sorting?: Sorting | nullonSort?: (sorting: Sorting | null) => voidrenderRowActions: (sub: SubscriptionApi) => JSX.Element+ /** Overrides the "Enabled" column with an interactive control (a LemonSwitch). Omit for a read-only tag. */+ renderEnabledToggle?: (sub: SubscriptionApi) => JSX.Element}export function SubscriptionsTable({@@ -263,8 +271,9 @@ export function SubscriptionsTable({sorting,onSort,renderRowActions,+ renderEnabledToggle,}: SubscriptionsTableProps): JSX.Element {- const columns = buildColumns(renderRowActions)+ const columns = buildColumns(renderRowActions, renderEnabledToggle)return (<LemonTablediff --git a/products/subscriptions/frontend/scenes/subscriptionsSceneLogic.tsx b/products/subscriptions/frontend/scenes/subscriptionsSceneLogic.tsxindex 8b922cdedf67..2a2b5a22873f 100644--- a/products/subscriptions/frontend/scenes/subscriptionsSceneLogic.tsx+++ b/products/subscriptions/frontend/scenes/subscriptionsSceneLogic.tsx@@ -175,6 +175,12 @@ function subscriptionsListStateEqual()}+function omitKey(state: Record<number, true>, id: number): Record<number, true> {+ const next = { ...state }+ delete next[id]+ return next+}+/** LemonTable columnKey → DRF `ordering` field (see SubscriptionViewSet.ordering_fields). */function buildSubscriptionsListOrdering(sorting: Sorting | null): string {if (!sorting) {@@ -223,7 +229,7 @@ export interface subscriptionsSceneLogicValues {subscriptionsResponseLoading: booleansubscriptionsSorting: Sorting | nulltargetTypeFilter: SubscriptionsListTargetType | null- togglingEnabledId: number | null+ togglingEnabledIds: Record<number, true>}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -283,11 +289,11 @@ export interface subscriptionsSceneLogicActions {enabled: booleanid: number}- setSubscriptionEnabledFailure: () => {- value: true+ setSubscriptionEnabledFailure: (id: number) => {+ id: number}- setSubscriptionEnabledSuccess: () => {- value: true+ setSubscriptionEnabledSuccess: (id: number) => {+ id: number}setSubscriptionModalId: (id: number | 'new' | null) => {id: number | 'new' | null@@ -358,8 +364,8 @@ export const subscriptionsSceneLogic = kea<subscriptionsSceneLogicType>([deliverSubscriptionSuccess: true,deliverSubscriptionFailure: true,setSubscriptionEnabled: (id: number, enabled: boolean) => ({ id, enabled }),- setSubscriptionEnabledSuccess: true,- setSubscriptionEnabledFailure: true,+ setSubscriptionEnabledSuccess: (id: number) => ({ id }),+ setSubscriptionEnabledFailure: (id: number) => ({ id }),}),reducers({search: [@@ -439,14 +445,15 @@ export const subscriptionsSceneLogic = kea<subscriptionsSceneLogicType>([deliverSubscriptionFailure: () => null,},],- // Tracks the subscription whose Pause/Resume PATCH is in flight so the row's- // menu item can show a busy state and prevent double-clicks.- togglingEnabledId: [- null as number | null,+ // Tracks the subscriptions whose Pause/Resume PATCH is in flight so each row's+ // switch can show its own busy state. A set (not a single id) so concurrent toggles+ // on different rows don't clobber each other.+ togglingEnabledIds: [+ {} as Record<number, true>,{- setSubscriptionEnabled: (_, { id }) => id,- setSubscriptionEnabledSuccess: () => null,- setSubscriptionEnabledFailure: () => null,+ setSubscriptionEnabled: (state, { id }) => ({ ...state, [id]: true }),+ setSubscriptionEnabledSuccess: (state, { id }) => omitKey(state, id),+ setSubscriptionEnabledFailure: (state, { id }) => omitKey(state, id),},],}),@@ -579,9 +586,9 @@ export const subscriptionsSceneLogic = kea<subscriptionsSceneLogicType>([setSubscriptionEnabled: async ({ id, enabled }) => {const ok = await toggleSubscriptionEnabled(id, enabled)if (ok) {- actions.setSubscriptionEnabledSuccess()+ actions.setSubscriptionEnabledSuccess(id)} else {- actions.setSubscriptionEnabledFailure()+ actions.setSubscriptionEnabledFailure(id)}},setSubscriptionEnabledSuccess: () => actions.loadSubscriptions(),