: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): add feedback links to AI report deliveries (#62641)
Vasco de Krijger50875c0fdf85
diff --git a/frontend/src/scenes/subscriptions/SubscriptionScene.tsx b/frontend/src/scenes/subscriptions/SubscriptionScene.tsxindex 2e5cd3ad41b5..d222ce42b0f5 100644--- a/frontend/src/scenes/subscriptions/SubscriptionScene.tsx+++ b/frontend/src/scenes/subscriptions/SubscriptionScene.tsx@@ -3,6 +3,7 @@ import { router } from 'kea-router'import { LemonButton, LemonTag } from '@posthog/lemon-ui'import type { SubscriptionApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'+import { ResourceTypeEnumApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'import { NotFound } from 'lib/components/NotFound'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'@@ -80,8 +81,11 @@ export function SubscriptionScene(): JSX.Element {deliveriesPageLoading,deliveringSubscriptionId,deliveryStatusFilter,+ deliveryFeedback,+ recentlyThankedDeliveries,} = useValues(subscriptionSceneLogic)- const { loadDeliveriesPage, deliverSubscription, setDeliveryStatusFilter } = useActions(subscriptionSceneLogic)+ const { loadDeliveriesPage, deliverSubscription, setDeliveryStatusFilter, submitDeliveryFeedback } =+ useActions(subscriptionSceneLogic)const showNotFound = !subscriptionLoading && !subscription@@ -114,6 +118,13 @@ export function SubscriptionScene(): JSX.Element {onDeliveryStatusFilterChange={setDeliveryStatusFilter}onTestDelivery={subscription ? () => deliverSubscription(subscription.id) : undefined}testDeliveryLoading={Boolean(subscription && deliveringSubscriptionId === subscription.id)}+ onDeliveryFeedback={+ subscription?.resource_type === ResourceTypeEnumApi.AiPrompt+ ? (deliveryId, feedback) => submitDeliveryFeedback(deliveryId, feedback, 'in_app')+ : undefined+ }+ deliveryFeedback={deliveryFeedback}+ recentlyThankedDeliveries={recentlyThankedDeliveries}/>) : null}</div>diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.tsxindex 4fca350f271a..a0c28b6178dc 100644--- a/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.tsx+++ b/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.tsx@@ -1,4 +1,4 @@-import { IconSend } from '@posthog/icons'+import { IconSend, IconThumbsDown, IconThumbsUp } from '@posthog/icons'import {LemonButton,LemonDivider,@@ -20,6 +20,7 @@ import {import { TZLabel } from 'lib/components/TZLabel'+import type { DeliveryFeedback } from '../subscriptionSceneLogic'import { SubscriptionDeliveryDestinationCell } from './SubscriptionDestinationCell'import { TARGET_TYPE_LABEL } from './subscriptionLabels'@@ -195,6 +196,55 @@ function buildDeliveryColumns(): LemonTableColumns<SubscriptionDeliveryApi> {const deliveryColumns = buildDeliveryColumns()+function buildFeedbackColumn(+ deliveryFeedback: Record<string, DeliveryFeedback>,+ recentlyThankedDeliveries: Record<string, true>,+ onDeliveryFeedback: (deliveryId: string, feedback: DeliveryFeedback) => void+): LemonTableColumns<SubscriptionDeliveryApi>[number] {+ return {+ title: 'Useful?',+ key: 'feedback',+ className: DELIVERY_TABLE_CELL_CLASS,+ render: (_v, row) => {+ if (row.status !== SubscriptionDeliveryStatusEnumApi.Completed) {+ return <span className="text-secondary">—</span>+ }+ if (recentlyThankedDeliveries[row.id]) {+ return <span className="text-secondary whitespace-nowrap">Thanks!</span>+ }+ // Recorded feedback highlights the chosen side; clicking the other side switches the vote+ // (analysis takes the latest event per person + delivery, so switching just wins).+ const recorded = deliveryFeedback[row.id]+ return (+ <div className="flex items-center gap-1">+ <LemonButton+ size="xsmall"+ icon={<IconThumbsUp />}+ active={recorded === 'positive'}+ tooltip={+ recorded === 'positive' ? 'You marked this report as useful' : 'This report was useful'+ }+ onClick={recorded === 'positive' ? undefined : () => onDeliveryFeedback(row.id, 'positive')}+ data-attr="subscription-delivery-feedback-positive"+ />+ <LemonButton+ size="xsmall"+ icon={<IconThumbsDown />}+ active={recorded === 'negative'}+ tooltip={+ recorded === 'negative'+ ? 'You marked this report as not useful'+ : 'This report was not useful'+ }+ onClick={recorded === 'negative' ? undefined : () => onDeliveryFeedback(row.id, 'negative')}+ data-attr="subscription-delivery-feedback-negative"+ />+ </div>+ )+ },+ }+}+const DELIVERY_STATUS_FILTER_OPTIONS: { label: string; value: DeliveryListStatusFilter | null }[] = [{ label: 'All statuses', value: null },{ label: 'Starting', value: SubscriptionDeliveriesListStatusByValue.Starting },@@ -265,6 +315,12 @@ export type SubscriptionDeliveryHistoryProps = {/** When set, empty table shows this as the primary action (e.g. send a test delivery). */onTestDelivery?: () => voidtestDeliveryLoading?: boolean+ /** When set (AI-prompt subscriptions), completed rows show thumbs up/down feedback buttons. */+ onDeliveryFeedback?: (deliveryId: string, feedback: DeliveryFeedback) => void+ /** Feedback already recorded (persisted per browser), keyed by delivery id — those rows show the chosen option. */+ deliveryFeedback?: Record<string, DeliveryFeedback>+ /** Deliveries thanked moments ago — those rows briefly show "Thanks!" before settling into the chosen option. */+ recentlyThankedDeliveries?: Record<string, true>/*** STORYBOOK-ONLY: delivery ids whose AI summary row should render pre-expanded* on first render. Used exclusively by visual regression tests to capture the@@ -281,6 +337,9 @@ export function SubscriptionDeliveryHistory({onDeliveryStatusFilterChange,onTestDelivery,testDeliveryLoading = false,+ onDeliveryFeedback,+ deliveryFeedback = {},+ recentlyThankedDeliveries = {},__storyOnlyInitiallyExpandedDeliveryIds,}: SubscriptionDeliveryHistoryProps): JSX.Element {const rowCount = deliveriesPage?.results.length ?? 0@@ -293,6 +352,9 @@ export function SubscriptionDeliveryHistory({const showStatusFilter = Boolean(onDeliveryStatusFilterChange)const tableEmptyState = deliveryStatusFilter != null ? 'No deliveries match this filter' : 'No deliveries yet'const expandable = buildExpandable(__storyOnlyInitiallyExpandedDeliveryIds)+ const columns = onDeliveryFeedback+ ? [...deliveryColumns, buildFeedbackColumn(deliveryFeedback, recentlyThankedDeliveries, onDeliveryFeedback)]+ : deliveryColumnsreturn (<>@@ -332,7 +394,7 @@ export function SubscriptionDeliveryHistory({{showTable ? (<LemonTabledataSource={deliveriesPage?.results ?? []}- columns={deliveryColumns}+ columns={columns}loading={deliveriesPageLoading}loadingSkeletonRows={8}rowKey="id"diff --git a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.tsindex 1962dd521568..1f0604591a78 100644--- a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts+++ b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts@@ -1,6 +1,8 @@import { MOCK_TEAM_ID } from 'lib/api.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import {ResourceTypeEnumApi,@@ -75,6 +77,8 @@ describe('subscriptionSceneLogic', () => {beforeEach(() => {deliveriesRequestUrls = []+ // deliveryFeedback persists to localStorage; clear it so recorded feedback can't leak between tests.+ localStorage.clear()})it('includes status in deliveries list request when status filter is set', async () => {@@ -221,4 +225,158 @@ describe('subscriptionSceneLogic', () => {logic.unmount()featureFlagLogic.unmount()})++ it.each([+ ['positive' as const, 'email'],+ ['negative' as const, 'slack'],+ ])('captures ai_report_feedback (%s, %s) from URL params and strips them', async (feedback, source) => {+ useMocks({+ get: {+ [`/api/projects/${MOCK_TEAM_ID}/subscriptions/2/`]: () => [200, MOCK_AI_SUBSCRIPTION],+ },+ })+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], {})+ const captureSpy = jest.spyOn(posthog, 'capture')++ const logic = subscriptionSceneLogic({ id: '2' })+ logic.mount()+ await expectLogic(logic, () => {+ router.actions.push('/subscriptions/2', {+ feedback_delivery: 'd-123',+ feedback,+ feedback_source: source,+ })+ }).toFinishAllListeners()++ expect(captureSpy).toHaveBeenCalledWith('ai_report_feedback', {+ subscription_id: 2,+ delivery_id: 'd-123',+ feedback,+ source,+ previous_feedback: null,+ })+ // The replace must remove the params so a refresh doesn't double-capture.+ expect(router.values.searchParams).toEqual({})+ expect(captureSpy.mock.calls.filter(([event]) => event === 'ai_report_feedback')).toHaveLength(1)++ logic.unmount()+ featureFlagLogic.unmount()+ captureSpy.mockRestore()+ })++ it('does not re-capture from a feedback link for an already-recorded delivery', async () => {+ useMocks({+ get: {+ [`/api/projects/${MOCK_TEAM_ID}/subscriptions/2/`]: () => [200, MOCK_AI_SUBSCRIPTION],+ },+ })+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], {})+ const captureSpy = jest.spyOn(posthog, 'capture')++ const logic = subscriptionSceneLogic({ id: '2' })+ logic.mount()+ await expectLogic(logic, () => {+ logic.actions.submitDeliveryFeedback('d-123', 'positive', 'in_app')+ }).toFinishAllListeners()+ captureSpy.mockClear()++ await expectLogic(logic, () => {+ router.actions.push('/subscriptions/2', {+ feedback_delivery: 'd-123',+ feedback: 'negative',+ feedback_source: 'email',+ })+ }).toFinishAllListeners()++ expect(captureSpy.mock.calls.filter(([event]) => event === 'ai_report_feedback')).toHaveLength(0)+ // Params are still stripped, and the originally recorded feedback wins.+ expect(router.values.searchParams).toEqual({})+ expect(logic.values.deliveryFeedback).toEqual({ 'd-123': 'positive' })++ logic.unmount()+ featureFlagLogic.unmount()+ captureSpy.mockRestore()+ })++ it('persists recorded feedback across remounts', async () => {+ useMocks({+ get: {+ [`/api/projects/${MOCK_TEAM_ID}/subscriptions/2/`]: () => [200, MOCK_AI_SUBSCRIPTION],+ },+ })+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], {})++ let logic = subscriptionSceneLogic({ id: '2' })+ logic.mount()+ await expectLogic(logic, () => {+ logic.actions.submitDeliveryFeedback('d-9', 'positive', 'in_app')+ }).toFinishAllListeners()+ logic.unmount()++ logic = subscriptionSceneLogic({ id: '2' })+ logic.mount()+ expect(logic.values.deliveryFeedback).toEqual({ 'd-9': 'positive' })+ // The thanks flash is transient — after a remount the row goes straight to the recorded option.+ expect(logic.values.recentlyThankedDeliveries).toEqual({})++ logic.unmount()+ featureFlagLogic.unmount()+ })++ it('captures in-app thumbs feedback and records it per delivery', async () => {+ useMocks({+ get: {+ [`/api/projects/${MOCK_TEAM_ID}/subscriptions/2/`]: () => [200, MOCK_AI_SUBSCRIPTION],+ },+ })+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], {})+ const captureSpy = jest.spyOn(posthog, 'capture')++ const logic = subscriptionSceneLogic({ id: '2' })+ logic.mount()+ await expectLogic(logic, () => {+ logic.actions.submitDeliveryFeedback('d-9', 'negative', 'in_app')+ }).toFinishAllListeners()++ expect(captureSpy).toHaveBeenCalledWith('ai_report_feedback', {+ subscription_id: 2,+ delivery_id: 'd-9',+ feedback: 'negative',+ source: 'in_app',+ previous_feedback: null,+ })+ expect(logic.values.deliveryFeedback).toEqual({ 'd-9': 'negative' })+ // Thanks flashes first, then expiry settles the row into the recorded option.+ expect(logic.values.recentlyThankedDeliveries).toEqual({ 'd-9': true })+ await expectLogic(logic, () => {+ logic.actions.expireDeliveryThanks('d-9')+ }).toFinishAllListeners()+ expect(logic.values.recentlyThankedDeliveries).toEqual({})+ expect(logic.values.deliveryFeedback).toEqual({ 'd-9': 'negative' })++ // Switching the vote captures again with the previous value, and the latest one wins.+ await expectLogic(logic, () => {+ logic.actions.submitDeliveryFeedback('d-9', 'positive', 'in_app')+ }).toFinishAllListeners()+ expect(captureSpy).toHaveBeenCalledWith('ai_report_feedback', {+ subscription_id: 2,+ delivery_id: 'd-9',+ feedback: 'positive',+ source: 'in_app',+ previous_feedback: 'negative',+ })+ expect(logic.values.deliveryFeedback).toEqual({ 'd-9': 'positive' })++ logic.unmount()+ featureFlagLogic.unmount()+ captureSpy.mockRestore()+ })})diff --git a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.tsx b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.tsxindex 7108bce7348c..9c2d937f9f07 100644--- a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.tsx+++ b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.tsx@@ -1,6 +1,8 @@import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { router, urlToAction } from 'kea-router'import { subscriptions } from 'kea-subscriptions'+import posthog from 'posthog-js'import {subscriptionsDeliveriesList,@@ -32,6 +34,11 @@ export type SubscriptionSceneLogicProps = {id: string}+export type DeliveryFeedback = 'positive' | 'negative'+export type DeliveryFeedbackSource = 'email' | 'slack' | 'in_app'++export const FEEDBACK_THANKS_DISPLAY_MS = 1000+function parseCursorFromPaginationUrl(url: string | null | undefined): string | undefined {if (!url) {return undefined@@ -57,6 +64,12 @@ export const subscriptionSceneLogic = kea<subscriptionSceneLogicType>([deliverSubscriptionSuccess: true,deliverSubscriptionFailure: true,setDeliveryStatusFilter: (status: SubscriptionsDeliveriesListStatus | null) => ({ status }),+ submitDeliveryFeedback: (deliveryId: string, feedback: DeliveryFeedback, source: DeliveryFeedbackSource) => ({+ deliveryId,+ feedback,+ source,+ }),+ expireDeliveryThanks: (deliveryId: string) => ({ deliveryId }),}),reducers({deliveringSubscriptionId: [@@ -73,6 +86,27 @@ export const subscriptionSceneLogic = kea<subscriptionSceneLogicType>([setDeliveryStatusFilter: (_, { status }) => status,},],+ deliveryFeedback: [+ {} as Record<string, DeliveryFeedback>,+ // localStorage on purpose: feedback is an analytics event, not a DB row — this only keeps+ // the UI honest (and the capture deduped) across reloads on this browser.+ { persist: true },+ {+ submitDeliveryFeedback: (state, { deliveryId, feedback }) => ({ ...state, [deliveryId]: feedback }),+ },+ ],+ // Transient (not persisted): drives the brief "Thanks!" flash before the row settles+ // into showing the recorded option.+ recentlyThankedDeliveries: [+ {} as Record<string, true>,+ {+ submitDeliveryFeedback: (state, { deliveryId }) => ({ ...state, [deliveryId]: true as const }),+ expireDeliveryThanks: (state, { deliveryId }) => {+ const { [deliveryId]: _removed, ...rest } = state+ return rest+ },+ },+ ],}),loaders(({ values, props }) => ({subscription: [@@ -164,7 +198,27 @@ export const subscriptionSceneLogic = kea<subscriptionSceneLogicType>([}},})),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, props, cache, selectors }) => ({+ submitDeliveryFeedback: ({ deliveryId, feedback, source }, _breakpoint, _action, previousState) => {+ posthog.capture('ai_report_feedback', {+ subscription_id: parseInt(props.id, 10),+ delivery_id: deliveryId,+ feedback,+ source,+ // Lets analysis distinguish first votes from switches; consumers take the latest+ // event per person + delivery, so a switched vote simply wins.+ previous_feedback: selectors.deliveryFeedback(previousState)[deliveryId] ?? null,+ })+ // In-app thumbs show a per-row "Thanks" state instead of a toast.+ if (source !== 'in_app') {+ lemonToast.success('Thanks for your feedback')+ }+ // Per-delivery key so spamming replaces the previous timer instead of stacking.+ cache.disposables.add(() => {+ const timerId = setTimeout(() => actions.expireDeliveryThanks(deliveryId), FEEDBACK_THANKS_DISPLAY_MS)+ return () => clearTimeout(timerId)+ }, `deliveryThanks-${deliveryId}`)+ },setDeliveryStatusFilter: () => {if (values.deliveriesEnabled && values.subscription) {void actions.loadDeliveriesPage(null)@@ -219,6 +273,27 @@ export const subscriptionSceneLogic = kea<subscriptionSceneLogicType>([lemonToast.error(typeof detail === 'string' ? detail : 'Could not update subscription')},})),+ urlToAction(({ actions, props, values }) => ({+ // Feedback links in delivered emails/Slack messages land here with these params;+ // capture once, then strip them so a refresh doesn't double-capture.+ [urls.subscription(':id')]: ({ id }, searchParams) => {+ if (id !== props.id) {+ return+ }+ const { feedback_delivery, feedback, feedback_source, ...restSearchParams } = searchParams+ if (!feedback_delivery || (feedback !== 'positive' && feedback !== 'negative')) {+ return+ }+ const deliveryId = String(feedback_delivery)+ if (values.deliveryFeedback[deliveryId]) {+ // Persisted state remembers this delivery — don't re-capture from a re-clicked link.+ lemonToast.info('Your feedback for this report was already recorded')+ } else {+ actions.submitDeliveryFeedback(deliveryId, feedback, feedback_source === 'slack' ? 'slack' : 'email')+ }+ router.actions.replace(router.values.location.pathname, restSearchParams, router.values.hashParams)+ },+ })),afterMount(({ actions }) => {void actions.loadSubscription()}),diff --git a/posthog/templates/email/ai_subscription_report.html b/posthog/templates/email/ai_subscription_report.htmlindex f6b2dcee010c..f2f6eb5c5393 100644--- a/posthog/templates/email/ai_subscription_report.html+++ b/posthog/templates/email/ai_subscription_report.html@@ -11,6 +11,12 @@<a class="button primary" href="{{ subscription_url }}">Manage subscription</a></div>+<p class="text-center">+ Was this report useful?+ <a href="{{ feedback_positive_url }}">👍 Yes</a> ·+ <a href="{{ feedback_negative_url }}">👎 No</a>+</p>+<p class="text-center text-muted"><a href="{{ unsubscribe_url }}">Unsubscribe from this report</a></p>diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.pyindex af3a88f7863e..a4f15d1885c6 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py@@ -260,7 +260,8 @@ async def _deliver_ai_subscription(# delivery, so a missing reference is a wiring bug, not a runtime state.raise ApplicationError(f"AI delivery for subscription {subscription.id} has no delivery_id", non_retryable=True)- markdown = await _load_ai_report(inputs.delivery_id)+ delivery_id = inputs.delivery_id+ markdown = await _load_ai_report(delivery_id)if markdown is None:# Generation persists the report before delivery is scheduled, so a missing report# means the row was lost. Non-retryable: re-running *delivery* can't regenerate the@@ -282,6 +283,7 @@ async def _deliver_ai_subscription(subscription=subscription,markdown=markdown,delivery_run_id=workflow_run_id,+ delivery_id=delivery_id,)return await deliver_email(subscription, inputs, recipient_results, _send_email)@@ -290,7 +292,7 @@ async def _deliver_ai_subscription(subscription,recipient_results,lambda integration: send_slack_ai_subscription_report(- subscription=subscription, markdown=markdown, integration=integration+ subscription=subscription, markdown=markdown, integration=integration, delivery_id=delivery_id),)# `validate_subscription_for_delivery` auto-disables unsupported targets up front,diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.pyindex 5aa6b72edad6..3a6064a93057 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py@@ -1,6 +1,7 @@import re+import uuidfrom datetime import datetime-from urllib.parse import urlparse+from urllib.parse import urlencode, urlparseimport nh3import structlog@@ -172,6 +173,13 @@ async def generate_ai_subscription_markdown(subscription: Subscription) -> str:)+def _build_feedback_url(subscription_url: str, delivery_id: uuid.UUID, feedback: str, source: str) -> str:+ # Lands on the authenticated subscription page; the frontend reads these exact params+ # (feedback_delivery, feedback, feedback_source) and captures an `ai_report_feedback` event.+ params = urlencode({"feedback_delivery": str(delivery_id), "feedback": feedback, "feedback_source": source})+ return f"{subscription_url}?{params}"++def render_ai_email_html(markdown: str) -> str:rendered = _MARKDOWN_RENDERER.render(_strip_external_links_markdown(markdown))return nh3.clean(rendered, tags=_ALLOWED_EMAIL_TAGS, attributes=_ALLOWED_EMAIL_ATTRS)@@ -183,6 +191,7 @@ def send_email_ai_subscription_report(subscription: Subscription,markdown: str,delivery_run_id: str,+ delivery_id: uuid.UUID,) -> None:utm_tags = f"{UTM_TAGS_BASE}&utm_medium=email"html = render_ai_email_html(markdown)@@ -203,6 +212,8 @@ def send_email_ai_subscription_report("rendered_html": html,"subscription_url": f"{subscription_url}?{utm_tags}","unsubscribe_url": unsubscribe_url,+ "feedback_positive_url": _build_feedback_url(subscription_url, delivery_id, "positive", "email"),+ "feedback_negative_url": _build_feedback_url(subscription_url, delivery_id, "negative", "email"),},)message.add_recipient(email=email)@@ -241,7 +252,7 @@ def send_email_ai_subscription_credit_limited(message.send(send_async=False)-def _build_ai_slack_message(subscription: Subscription, markdown: str) -> SlackMessageData:+def _build_ai_slack_message(subscription: Subscription, markdown: str, *, delivery_id: uuid.UUID) -> SlackMessageData:utm_tags = f"{UTM_TAGS_BASE}&utm_medium=slack"channel = subscription.target_value.split("|")[0]sections = _split_text_into_chunks(_SLACK_CONVERTER.convert(_strip_external_links_markdown(markdown)))@@ -260,6 +271,8 @@ def _build_ai_slack_message(subscription: Subscription, markdown: str) -> SlackMsubscription_url = subscription.url or absolute_uri(f"/project/{subscription.team_id}/subscriptions/{subscription.id}")+ feedback_positive_url = _build_feedback_url(subscription_url, delivery_id, "positive", "slack")+ feedback_negative_url = _build_feedback_url(subscription_url, delivery_id, "negative", "slack")blocks.extend([{"type": "divider"},@@ -273,6 +286,18 @@ def _build_ai_slack_message(subscription: Subscription, markdown: str) -> SlackM}],},+ {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": (+ "Was this report useful? "+ f"<{feedback_positive_url}|👍 Yes> · <{feedback_negative_url}|👎 No>"+ ),+ }+ ],+ },])@@ -288,8 +313,9 @@ async def send_slack_ai_subscription_report(subscription: Subscription,markdown: str,integration: Integration,+ delivery_id: uuid.UUID,) -> SlackDeliveryResult:- message_data = _build_ai_slack_message(subscription, markdown)+ message_data = _build_ai_slack_message(subscription, markdown, delivery_id=delivery_id)return await deliver_slack_message_data(integration, subscription, message_data)diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.pyindex 50379b98d0ff..ffe40f176679 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py@@ -1,14 +1,21 @@+import uuid+import pytest-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patchfrom products.exports.backend.temporal.subscriptions.ai_subscription.delivery import (SLACK_MRKDWN_SECTION_LIMIT,_build_ai_slack_message,_split_text_into_chunks,render_ai_email_html,+ send_email_ai_subscription_report,)+from ee.tasks.subscriptions.slack_subscriptions import SlackMessageData+_PARA = "a" * (SLACK_MRKDWN_SECTION_LIMIT - 100)+_DELIVERY_ID = uuid.UUID("12345678-1234-5678-1234-567812345678")+_SUBSCRIPTION_URL = "https://app.posthog.com/project/1/subscriptions/2"class TestSplitTextIntoChunks:@@ -89,64 +96,60 @@ class TestExternalUrlExfilGuard:assert "<img" not in htmldef test_slack_strips_external_link(self) -> None:- message = _build_ai_slack_message(- _mock_subscription(), "See [details](https://attacker.example/exfil?p=secret)"- )+ message = _build_message("See [details](https://attacker.example/exfil?p=secret)")all_text = " ".join(b["text"]["text"] for b in message.blocks if b["type"] == "section")assert "attacker.example" not in all_textassert "details" in all_textdef test_slack_keeps_posthog_link(self) -> None:- message = _build_ai_slack_message(- _mock_subscription(), "Open [dashboard](https://app.posthog.com/insights/abc)"- )+ message = _build_message("Open [dashboard](https://app.posthog.com/insights/abc)")all_text = " ".join(b["text"]["text"] for b in message.blocks if b["type"] == "section")assert "app.posthog.com/insights/abc" in all_textdef test_slack_defangs_bare_external_url(self) -> None:# a bare (non-markdown) URL still gets linkified/unfurled by Slack — must be defanged- message = _build_ai_slack_message(_mock_subscription(), "Visit https://attacker.example/exfil?p=secret now")+ message = _build_message("Visit https://attacker.example/exfil?p=secret now")all_text = " ".join(b["text"]["text"] for b in message.blocks if b["type"] == "section")assert "`https://attacker.example/exfil?p=secret`" in all_textdef test_slack_defangs_autolink(self) -> None:- message = _build_ai_slack_message(_mock_subscription(), "See <https://attacker.example/exfil> here")+ message = _build_message("See <https://attacker.example/exfil> here")all_text = " ".join(b["text"]["text"] for b in message.blocks if b["type"] == "section")assert "`https://attacker.example/exfil`" in all_textdef test_slack_keeps_bare_posthog_url(self) -> None:- message = _build_ai_slack_message(_mock_subscription(), "Open https://app.posthog.com/insights/abc now")+ message = _build_message("Open https://app.posthog.com/insights/abc now")all_text = " ".join(b["text"]["text"] for b in message.blocks if b["type"] == "section")assert "https://app.posthog.com/insights/abc" in all_textassert "`https://app.posthog.com" not in all_text # PostHog hosts stay live, not defangeddef test_slack_defangs_scheme_less_www_url(self) -> None:# Slack also linkifies scheme-less www. URLs — those must be defanged too- message = _build_ai_slack_message(_mock_subscription(), "Visit www.attacker.example/exfil now")+ message = _build_message("Visit www.attacker.example/exfil now")all_text = " ".join(b["text"]["text"] for b in message.blocks if b["type"] == "section")assert "`www.attacker.example/exfil`" in all_textdef test_slack_keeps_www_posthog_url(self) -> None:- message = _build_ai_slack_message(_mock_subscription(), "Docs at www.posthog.com/docs here")+ message = _build_message("Docs at www.posthog.com/docs here")all_text = " ".join(b["text"]["text"] for b in message.blocks if b["type"] == "section")assert "www.posthog.com/docs" in all_textassert "`www.posthog.com" not in all_textdef test_slack_does_not_mangle_email_addresses(self) -> None:- message = _build_ai_slack_message(_mock_subscription(), "Reach [email protected] for access")+ message = _build_message("Reach [email protected] for access")all_text = " ".join(b["text"]["text"] for b in message.blocks if b["type"] == "section")assert "[email protected]" in all_textassert "`www.example.com" not in all_textdef test_slack_defangs_parenthetical_external_url(self) -> None:# a URL inside plain parentheses is preceded by `(` but is not a markdown link — still defang it- message = _build_ai_slack_message(_mock_subscription(), "Revenue event (https://attacker.example/track) spiked")+ message = _build_message("Revenue event (https://attacker.example/track) spiked")all_text = " ".join(b["text"]["text"] for b in message.blocks if b["type"] == "section")assert "`https://attacker.example/track`" in all_textdef test_slack_defangs_uppercase_scheme_autolink(self) -> None:# URL schemes are case-insensitive — an uppercase scheme must not slip past the matcher- message = _build_ai_slack_message(_mock_subscription(), "See <HTTPS://attacker.example/exfil> now")+ message = _build_message("See <HTTPS://attacker.example/exfil> now")all_text = " ".join(b["text"]["text"] for b in message.blocks if b["type"] == "section")assert "`HTTPS://attacker.example/exfil`" in all_text@@ -164,7 +167,7 @@ class TestExternalUrlExfilGuard:def test_disables_slack_unfurl(self) -> None:# belt-and-suspenders to the content stripping: Slack must not auto-fetch any link in the report- message = _build_ai_slack_message(_mock_subscription(), "A short report.")+ message = _build_message("A short report.")assert message.unfurl is False@@ -172,15 +175,19 @@ def _mock_subscription() -> MagicMock:sub = MagicMock()sub.target_value = "C123|#general"sub.title = "Weekly report"- sub.url = "https://app.posthog.com/project/1/subscriptions/2"+ sub.url = _SUBSCRIPTION_URLsub.team_id = 1sub.id = 2return sub+def _build_message(markdown: str) -> SlackMessageData:+ return _build_ai_slack_message(_mock_subscription(), markdown, delivery_id=_DELIVERY_ID)++class TestBuildAISlackMessage:def test_single_section_report_has_no_thread_messages(self) -> None:- message = _build_ai_slack_message(_mock_subscription(), "A short report.")+ message = _build_message("A short report.")assert message.channel == "C123"assert message.thread_messages == []section_texts = [b["text"]["text"] for b in message.blocks if b["type"] == "section"]@@ -188,8 +195,47 @@ class TestBuildAISlackMessage:def test_long_report_overflows_into_thread(self) -> None:long_markdown = ("para\n\n" * 1).join("x" * (SLACK_MRKDWN_SECTION_LIMIT - 50) for _ in range(3))- message = _build_ai_slack_message(_mock_subscription(), long_markdown)+ message = _build_message(long_markdown)assert len(message.thread_messages) >= 1for thread_msg in message.thread_messages:for block in thread_msg["blocks"]:assert block["text"]["text"].strip(), "thread section text must be non-empty"+++def _feedback_url(feedback: str, source: str) -> str:+ return f"{_SUBSCRIPTION_URL}?feedback_delivery={_DELIVERY_ID}&feedback={feedback}&feedback_source={source}"+++class TestFeedbackFooter:+ @pytest.mark.parametrize(+ "feedback,label",+ [("positive", "👍 Yes"), ("negative", "👎 No")],+ )+ def test_slack_footer_links_carry_feedback_params(self, feedback: str, label: str) -> None:+ message = _build_message("A short report.")+ context_blocks = [b for b in message.blocks if b["type"] == "context"]+ assert len(context_blocks) == 1+ text = context_blocks[0]["elements"][0]["text"]+ assert "Was this report useful?" in text+ assert f"<{_feedback_url(feedback, 'slack')}|{label}>" in text++ @pytest.mark.parametrize("feedback", ["positive", "negative"])+ def test_email_context_carries_feedback_urls(self, feedback: str) -> None:+ with (+ patch(+ "products.exports.backend.temporal.subscriptions.ai_subscription.delivery.EmailMessage"+ ) as email_message,+ patch(+ "products.exports.backend.temporal.subscriptions.ai_subscription.delivery.get_unsubscribe_token",+ return_value="tok",+ ),+ ):+ send_email_ai_subscription_report(+ email="[email protected]",+ subscription=_mock_subscription(),+ markdown="Report body",+ delivery_run_id="run-1",+ delivery_id=_DELIVERY_ID,+ )+ context = email_message.call_args.kwargs["template_context"]+ assert context[f"feedback_{feedback}_url"] == _feedback_url(feedback, "email")