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(slack-app): show chart images in insight link unfurls (#116815)

Vojta Bartoš4bc9f0af4784
diff --git a/posthog/temporal/ai/__init__.py b/posthog/temporal/ai/__init__.py
index ca8c6116abf2..1623cd4c7156 100644
--- a/posthog/temporal/ai/__init__.py
+++ b/posthog/temporal/ai/__init__.py
@@ -13,6 +13,7 @@ from posthog.temporal.ai.slack_app.posthog_code_slack_mention_command import Pos
from posthog.temporal.ai.slack_app.posthog_slack_inbox_onboarding import PostHogSlackInboxOnboardingWorkflow
from posthog.temporal.ai.slack_app.slack_app_fork import SlackAppForkThreadWorkflow
from posthog.temporal.ai.slack_app.slack_app_mention import SlackAppMentionWorkflow
+from posthog.temporal.ai.slack_app.slack_app_unfurl_charts import SlackAppUnfurlChartsWorkflow
from products.posthog_ai.backend.temporal.activities import mirror_conversation_to_task_activity
from products.posthog_ai.backend.temporal.workflows import ConversationMirrorWorkflow
@@ -40,6 +41,7 @@ POSTHOG_CODE_SLACK_WORKFLOWS = [
PostHogCodeSlackMentionCommandWorkflow,
SlackAppForkThreadWorkflow,
PostHogSlackInboxOnboardingWorkflow,
+ SlackAppUnfurlChartsWorkflow,
]
POSTHOG_CODE_SLACK_ACTIVITIES = [*SLACK_APP_ACTIVITIES]
diff --git a/posthog/temporal/ai/slack_app/__init__.py b/posthog/temporal/ai/slack_app/__init__.py
index 6fe8dd083441..f47ea53f3540 100644
--- a/posthog/temporal/ai/slack_app/__init__.py
+++ b/posthog/temporal/ai/slack_app/__init__.py
@@ -31,6 +31,8 @@ from posthog.temporal.ai.slack_app.activities import (
post_posthog_code_no_repos_activity,
post_posthog_code_picker_timeout_activity,
post_posthog_code_repo_picker_activity,
+ post_slack_unfurl_charts_activity,
+ prepare_slack_unfurl_charts_activity,
process_slack_app_fork_thread_activity,
request_untagged_followup_confirmation_activity,
resolve_posthog_code_slack_command_user_activity,
@@ -79,6 +81,8 @@ SLACK_APP_ACTIVITIES = [
mark_slack_app_message_processing_activity,
mark_slack_app_message_queued_activity,
run_posthog_slack_inbox_onboarding_activity,
+ prepare_slack_unfurl_charts_activity,
+ post_slack_unfurl_charts_activity,
]
__all__ = [
@@ -127,4 +131,6 @@ __all__ = [
"resolve_posthog_code_slack_command_user_activity",
"classify_slack_app_model_router_activity",
"run_posthog_slack_inbox_onboarding_activity",
+ "post_slack_unfurl_charts_activity",
+ "prepare_slack_unfurl_charts_activity",
]
diff --git a/posthog/temporal/ai/slack_app/activities/__init__.py b/posthog/temporal/ai/slack_app/activities/__init__.py
index 55dd136687ee..2447944332f8 100644
--- a/posthog/temporal/ai/slack_app/activities/__init__.py
+++ b/posthog/temporal/ai/slack_app/activities/__init__.py
@@ -42,6 +42,10 @@ from posthog.temporal.ai.slack_app.activities.task_creation import (
forward_posthog_code_followup_activity,
)
from posthog.temporal.ai.slack_app.activities.thread import collect_posthog_code_thread_messages_activity
+from posthog.temporal.ai.slack_app.activities.unfurl_charts import (
+ post_slack_unfurl_charts_activity,
+ prepare_slack_unfurl_charts_activity,
+)
from posthog.temporal.ai.slack_app.activities.user_resolution import resolve_posthog_code_slack_command_user_activity
__all__ = [
@@ -78,4 +82,6 @@ __all__ = [
"classify_slack_app_model_router_activity",
"run_posthog_slack_inbox_onboarding",
"run_posthog_slack_inbox_onboarding_activity",
+ "post_slack_unfurl_charts_activity",
+ "prepare_slack_unfurl_charts_activity",
]
diff --git a/posthog/temporal/ai/slack_app/activities/unfurl_charts.py b/posthog/temporal/ai/slack_app/activities/unfurl_charts.py
new file mode 100644
index 000000000000..87fef5c82839
--- /dev/null
+++ b/posthog/temporal/ai/slack_app/activities/unfurl_charts.py
@@ -0,0 +1,65 @@
+from datetime import UTC, datetime, timedelta
+
+from temporalio import activity
+
+from posthog.temporal.ai.slack_app.types import (
+ SlackAppUnfurlChartsPostInput,
+ SlackAppUnfurlChartsPrepared,
+ SlackAppUnfurlChartsWorkflowInputs,
+ SlackUnfurlChartAsset,
+)
+from posthog.temporal.common.utils import close_db_connections
+
+from products.exports.backend.facade.api import (
+ create_insight_png_export,
+ get_delivery_image_url,
+ png_export_has_content,
+)
+from products.slack_app.backend.logic.link_unfurl_charts import post_unfurl_charts, unfurl_chart_targets
+
+# The export calls live here and not in the Slack app, because the exports product already
+# depends on the Slack app and the Slack app must not depend back on it.
+
+# Slack fetches image_url again after the unfurl is posted, so the token must outlive the post.
+_CHART_URL_TTL = timedelta(days=30)
+_CHART_ASSET_TTL = timedelta(days=31)
+
+
+@close_db_connections
+def prepare_slack_unfurl_charts_activity(inputs: SlackAppUnfurlChartsWorkflowInputs) -> SlackAppUnfurlChartsPrepared:
+ targets = unfurl_chart_targets(inputs)
+ assets: list[SlackUnfurlChartAsset] = []
+ for insight_id in targets.insight_ids:
+ try:
+ asset_id = create_insight_png_export(
+ team=targets.team,
+ created_by=targets.user,
+ insight_id=insight_id,
+ is_system=True,
+ expires_after=datetime.now(UTC) + _CHART_ASSET_TTL,
+ )
+ except ValueError:
+ continue
+ assets.append(SlackUnfurlChartAsset(insight_id=insight_id, asset_id=asset_id))
+ return SlackAppUnfurlChartsPrepared(distinct_id=str(targets.user.distinct_id), assets=assets)
+
+
+@close_db_connections
+def post_slack_unfurl_charts_activity(post: SlackAppUnfurlChartsPostInput) -> None:
+ request = post.request
+ image_urls_by_insight: dict[int, str] = {}
+ for asset in post.rendered:
+ if not png_export_has_content(team_id=request.team_id, asset_id=asset.asset_id):
+ continue
+ # created_by_id ties the asset to the sharer who rendered it.
+ image_url = get_delivery_image_url(
+ team_id=request.team_id,
+ asset_id=asset.asset_id,
+ expiry_delta=_CHART_URL_TTL,
+ created_by_id=request.user_id,
+ )
+ if image_url is not None:
+ image_urls_by_insight[asset.insight_id] = image_url
+ post_unfurl_charts(post, image_urls_by_insight=image_urls_by_insight)
diff --git a/posthog/temporal/ai/slack_app/slack_app_unfurl_charts.py b/posthog/temporal/ai/slack_app/slack_app_unfurl_charts.py
new file mode 100644
index 000000000000..c2539518edd5
--- /dev/null
+++ b/posthog/temporal/ai/slack_app/slack_app_unfurl_charts.py
@@ -0,0 +1,82 @@
+import json
+import asyncio
+from datetime import timedelta
+
+from temporalio import workflow
+from temporalio.common import RetryPolicy
+
+from posthog.temporal.ai.slack_app.activities.unfurl_charts import (
+ post_slack_unfurl_charts_activity,
+ prepare_slack_unfurl_charts_activity,
+)
+from posthog.temporal.ai.slack_app.types import (
+ SlackAppUnfurlChartsPostInput,
+ SlackAppUnfurlChartsWorkflowInputs,
+ SlackUnfurlChartAsset,
+)
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.exports.workflows import ExportAssetWorkflow, ExportAssetWorkflowInputs
+
+from products.exports.backend.facade.api import RENDER_TIMEOUT
+
+SLACK_APP_UNFURL_CHARTS_WORKFLOW_TIMEOUT = timedelta(minutes=5)
+_ACTIVITY_TIMEOUT = timedelta(seconds=30)
+_ACTIVITY_RETRY_POLICY = RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=2))
+
+
[email protected](name="slack-app-unfurl-charts")
+class SlackAppUnfurlChartsWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> SlackAppUnfurlChartsWorkflowInputs:
+ return SlackAppUnfurlChartsWorkflowInputs(**json.loads(inputs[0]))
+
+ @workflow.run
+ async def run(self, inputs: SlackAppUnfurlChartsWorkflowInputs) -> None:
+ prepared = await workflow.execute_activity(
+ prepare_slack_unfurl_charts_activity,
+ inputs,
+ start_to_close_timeout=_ACTIVITY_TIMEOUT,
+ retry_policy=_ACTIVITY_RETRY_POLICY,
+ )
+ results = await asyncio.gather(
+ *(self._render(inputs, prepared.distinct_id, asset) for asset in prepared.assets),
+ return_exceptions=True,
+ )
+ rendered = []
+ for asset, result in zip(prepared.assets, results):
+ if isinstance(result, BaseException):
+ workflow.logger.warning(
+ "slack_app_unfurl_chart_render_failed",
+ extra={"asset_id": asset.asset_id, "error": str(result)},
+ )
+ else:
+ rendered.append(asset)
+
+ await workflow.execute_activity(
+ post_slack_unfurl_charts_activity,
+ SlackAppUnfurlChartsPostInput(
+ request=inputs,
+ rendered=rendered,
+ elapsed_ms=int((workflow.now() - workflow.info().start_time).total_seconds() * 1000),
+ ),
+ start_to_close_timeout=_ACTIVITY_TIMEOUT,
+ retry_policy=_ACTIVITY_RETRY_POLICY,
+ )
+
+ async def _render(
+ self,
+ inputs: SlackAppUnfurlChartsWorkflowInputs,
+ distinct_id: str,
+ asset: SlackUnfurlChartAsset,
+ ) -> None:
+ await workflow.execute_child_workflow(
+ ExportAssetWorkflow.run,
+ ExportAssetWorkflowInputs(
+ exported_asset_id=asset.asset_id,
+ team_id=inputs.team_id,
+ distinct_id=distinct_id,
+ ),
+ id=f"export-asset-{asset.asset_id}",
+ task_queue=inputs.export_task_queue,
+ execution_timeout=RENDER_TIMEOUT,
+ )
diff --git a/posthog/temporal/ai/slack_app/types.py b/posthog/temporal/ai/slack_app/types.py
index 864eaed16ed2..a17686142999 100644
--- a/posthog/temporal/ai/slack_app/types.py
+++ b/posthog/temporal/ai/slack_app/types.py
@@ -18,6 +18,50 @@ class PostHogSlackInboxOnboardingInputs:
integration_id: int
+@frozen
+class SlackUnfurlChartRequest:
+ url: str
+ insight_id: int
+ title: str
+
+
+@frozen
+class SlackAppUnfurlChartsWorkflowInputs:
+ team_id: int
+ integration_id: int
+ user_id: int
+ slack_user_id: str
+ channel: str
+ message_ts: str
+ unfurl_id: str | None
+ source: str | None
+ # The cards the webhook already posted, keyed by url. chat.unfurl replaces the unfurls it is
+ # given, so the charts go out together with the cards from the first call.
+ unfurls: dict[str, Any]
+ charts: list[SlackUnfurlChartRequest]
+ # Read from settings by the starter, because a workflow body must not read settings.
+ export_task_queue: str
+
+
+@frozen
+class SlackUnfurlChartAsset:
+ insight_id: int
+ asset_id: int
+
+
+@frozen
+class SlackAppUnfurlChartsPrepared:
+ distinct_id: str
+ assets: list[SlackUnfurlChartAsset]
+
+
+@frozen
+class SlackAppUnfurlChartsPostInput:
+ request: SlackAppUnfurlChartsWorkflowInputs
+ rendered: list[SlackUnfurlChartAsset]
+ elapsed_ms: int
+
+
@frozen
class SlackAppForkThreadInputs:
"""The Slack interactivity payload behind a "Fork to DM" click, verbatim.
diff --git a/posthog/temporal/tests/ai/slack_app/test_slack_app_unfurl_charts_workflow.py b/posthog/temporal/tests/ai/slack_app/test_slack_app_unfurl_charts_workflow.py
new file mode 100644
index 000000000000..94e2d737387b
--- /dev/null
+++ b/posthog/temporal/tests/ai/slack_app/test_slack_app_unfurl_charts_workflow.py
@@ -0,0 +1,93 @@
+import uuid
+import logging
+from datetime import timedelta
+
+import pytest
+
+from temporalio import activity, workflow
+from temporalio.client import Client
+from temporalio.exceptions import ApplicationError
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from posthog.temporal.ai.slack_app.slack_app_unfurl_charts import SlackAppUnfurlChartsWorkflow
+from posthog.temporal.ai.slack_app.types import (
+ SlackAppUnfurlChartsPostInput,
+ SlackAppUnfurlChartsPrepared,
+ SlackAppUnfurlChartsWorkflowInputs,
+ SlackUnfurlChartAsset,
+)
+from posthog.temporal.exports.workflows import ExportAssetWorkflowInputs
+
+_RENDERED_ASSET_ID = 2
+_FAILING_ASSET_ID = 3
+
+rendered_asset_ids: list[int] = []
+posted: list[SlackAppUnfurlChartsPostInput] = []
+
+
[email protected](name="prepare_slack_unfurl_charts_activity")
+async def _fake_prepare(inputs: SlackAppUnfurlChartsWorkflowInputs) -> SlackAppUnfurlChartsPrepared:
+ return SlackAppUnfurlChartsPrepared(
+ distinct_id="user-1",
+ assets=[
+ SlackUnfurlChartAsset(insight_id=asset_id, asset_id=asset_id)
+ for asset_id in (_RENDERED_ASSET_ID, _FAILING_ASSET_ID)
+ ],
+ )
+
+
[email protected](name="post_slack_unfurl_charts_activity")
+async def _fake_post(post: SlackAppUnfurlChartsPostInput) -> None:
+ posted.append(post)
+
+
[email protected](name="export-asset")
+class _FakeExportAssetWorkflow:
+ @workflow.run
+ async def run(self, inputs: ExportAssetWorkflowInputs) -> None:
+ rendered_asset_ids.append(inputs.exported_asset_id)
+ if inputs.exported_asset_id == _FAILING_ASSET_ID:
+ raise ApplicationError("render failed", non_retryable=True)
+
+
+async def test_a_failed_render_still_posts_the_other_charts(
+ temporal_client: Client, caplog: pytest.LogCaptureFixture
+) -> None:
+ caplog.set_level(logging.INFO, logger="temporalio.workflow")
+ caplog.set_level(logging.INFO, logger="temporalio.activity")
+ rendered_asset_ids.clear()
+ posted.clear()
+ task_queue = f"test-unfurl-charts-{uuid.uuid4()}"
+ inputs = SlackAppUnfurlChartsWorkflowInputs(
+ team_id=1,
+ integration_id=1,
+ user_id=1,
+ slack_user_id="U1",
+ channel="C1",
+ message_ts="123.456",
+ unfurl_id=None,
+ source=None,
+ unfurls={},
+ charts=[],
+ export_task_queue=task_queue,
+ )
+
+ async with Worker(
+ temporal_client,
+ task_queue=task_queue,
+ workflows=[SlackAppUnfurlChartsWorkflow, _FakeExportAssetWorkflow],
+ activities=[_fake_prepare, _fake_post],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ await temporal_client.execute_workflow(
+ SlackAppUnfurlChartsWorkflow.run,
+ inputs,
+ id=f"test-unfurl-charts-{uuid.uuid4()}",
+ task_queue=task_queue,
+ execution_timeout=timedelta(seconds=30),
+ )
+
+ assert sorted(rendered_asset_ids) == [_RENDERED_ASSET_ID, _FAILING_ASSET_ID]
+ assert len(posted) == 1
+ assert [asset.asset_id for asset in posted[0].rendered] == [_RENDERED_ASSET_ID]
diff --git a/posthog/temporal/tests/ai/slack_app/test_unfurl_charts_activities.py b/posthog/temporal/tests/ai/slack_app/test_unfurl_charts_activities.py
new file mode 100644
index 000000000000..285a8a83e0c5
--- /dev/null
+++ b/posthog/temporal/tests/ai/slack_app/test_unfurl_charts_activities.py
@@ -0,0 +1,62 @@
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.models.integration import Integration
+from posthog.temporal.ai.slack_app.activities.unfurl_charts import post_slack_unfurl_charts_activity
+from posthog.temporal.ai.slack_app.types import (
+ SlackAppUnfurlChartsPostInput,
+ SlackAppUnfurlChartsWorkflowInputs,
+ SlackUnfurlChartAsset,
+ SlackUnfurlChartRequest,
+)
+
+from products.exports.backend.models.exported_asset import ExportedAsset
+from products.product_analytics.backend.facade.models import Insight
+
+_URL = "https://us.posthog.com/project/1/insights/abc123"
+
+
+class TestPostSlackUnfurlChartsActivity(BaseTest):
+ @parameterized.expand([("rendered", None, True), ("render_failed", "Export failed", False)])
+ @patch("products.slack_app.backend.logic.link_unfurl_charts.SlackIntegration")
+ def test_posts_a_chart_only_for_a_render_that_stored_its_png(
+ self, _name: str, exception: str | None, expect_unfurl: bool, mock_slack: MagicMock
+ ) -> None:
+ integration = Integration.objects.create(
+ team=self.team, kind="slack", integration_id="TSlack01", sensitive_config={"access_token": "xoxb-test"}
+ )
+ insight = Insight.objects.create(team=self.team, short_id="abc123", name="Weekly active users", saved=True)
+ asset = ExportedAsset.objects.create(
+ team=self.team,
+ created_by=self.user,
+ export_format=ExportedAsset.ExportFormat.PNG,
+ insight=insight,
+ content=None if exception else b"png",
+ exception=exception,
+ )
+ request = SlackAppUnfurlChartsWorkflowInputs(
+ team_id=self.team.pk,
+ integration_id=integration.id,
+ user_id=self.user.pk,
+ slack_user_id="U1",
+ channel="C1",
+ message_ts="123.456",
+ unfurl_id=None,
+ source=None,
+ unfurls={_URL: {"blocks": [{"type": "section", "text": {"type": "mrkdwn", "text": "*Weekly*"}}]}},
+ charts=[SlackUnfurlChartRequest(url=_URL, insight_id=insight.id, title="Weekly active users")],
+ export_task_queue="unused",
+ )
+
+ post_slack_unfurl_charts_activity(
+ SlackAppUnfurlChartsPostInput(
+ request=request,
+ rendered=[SlackUnfurlChartAsset(insight_id=insight.id, asset_id=asset.id)],
+ elapsed_ms=1,
+ )
+ )
+
+ chat_unfurl = mock_slack.return_value.client.chat_unfurl
+ assert chat_unfurl.called is expect_unfurl
diff --git a/products/exports/backend/facade/api.py b/products/exports/backend/facade/api.py
index e553062811ae..10f504fe4292 100644
--- a/products/exports/backend/facade/api.py
+++ b/products/exports/backend/facade/api.py
@@ -4,6 +4,7 @@ from collections.abc import Collection
from datetime import datetime, timedelta
from django.conf import settings
+from django.db.models import Q
from django.http.response import HttpResponseBase
import structlog
@@ -207,7 +208,7 @@ def get_delivery_image_url(
return asset.get_subscription_delivery_content_url(expiry_delta=expiry_delta)
-def render_png_export(
+def _create_png_export_asset(
*,
team: Team,
created_by: User,
@@ -217,17 +218,7 @@ def render_png_export(
dashboard_id: int | None = None,
is_system: bool = False,
expires_after: datetime | None = None,
-) -> tuple[ExportedAsset, bytes | None]:
- """Render a PNG export synchronously and return the asset together with its content bytes.
-
- Blocks until the export workflow finishes (typically a few seconds). On failure the
- returned bytes are None and ``asset.exception`` carries the error.
-
- ``is_system`` marks the asset as created by an internal process, which excludes it from
- the user's export listings and the per-team export quota. ``expires_after`` overrides
- the format's default TTL; pass it when the render backs a short-lived delivery URL so
- the stored bytes do not outlive their only consumer by months.
- """
+) -> ExportedAsset:
if created_by is None:
# Access control below resolves against created_by; a principal-less render would
# silently skip it, so service callers must attribute the render to a real user.
@@ -267,6 +258,63 @@ def render_png_export(
# None keeps the model's format-default TTL (see ExportedAsset.save).
expires_after=expires_after,
)
+ return asset
+
+
+def create_insight_png_export(
+ *, team: Team, created_by: User, insight_id: int, is_system: bool = False, expires_after: datetime | None = None
+) -> int:
+ """Check access and create the PNG asset that ``ExportAssetWorkflow`` renders, without rendering it.
+
+ Returns the asset id. For a caller that is itself a Temporal workflow: it runs the export as a
+ child workflow instead of blocking a worker on ``render_png_export``. The access rules and the
+ ``is_system`` and ``expires_after`` arguments are the same as for ``render_png_export``.
+ """
+ return _create_png_export_asset(
+ team=team, created_by=created_by, insight_id=insight_id, is_system=is_system, expires_after=expires_after
+ ).id
+
+
+def png_export_has_content(*, team_id: int, asset_id: int) -> bool:
+ return (
+ ExportedAsset.objects.filter(team_id=team_id, id=asset_id, export_format=ExportedAsset.ExportFormat.PNG)
+ .filter(Q(exception__isnull=True) | Q(exception=""))
+ .filter(Q(content__isnull=False) | (Q(content_location__isnull=False) & ~Q(content_location="")))
+ .exists()
+ )
+
+
+def render_png_export(
+ *,
+ team: Team,
+ created_by: User,
+ export_context: dict | None = None,
+ insight_id: int | None = None,
+ insight_short_id: str | None = None,
+ dashboard_id: int | None = None,
+ is_system: bool = False,
+ expires_after: datetime | None = None,
+) -> tuple[ExportedAsset, bytes | None]:
+ """Render a PNG export synchronously and return the asset together with its content bytes.
+
+ Blocks until the export workflow finishes (typically a few seconds). On failure the
+ returned bytes are None and ``asset.exception`` carries the error.
+
+ ``is_system`` marks the asset as created by an internal process, which excludes it from
+ the user's export listings and the per-team export quota. ``expires_after`` overrides
+ the format's default TTL; pass it when the render backs a short-lived delivery URL so
+ the stored bytes do not outlive their only consumer by months.
+ """
+ asset = _create_png_export_asset(
+ team=team,
+ created_by=created_by,
+ export_context=export_context,
+ insight_id=insight_id,
+ insight_short_id=insight_short_id,
+ dashboard_id=dashboard_id,
+ is_system=is_system,
+ expires_after=expires_after,
+ )
async def _run() -> None:
client = await async_connect()
diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.py
index a294a9f96dac..e4fffb5db365 100644
--- a/products/slack_app/backend/feature_flags.py
+++ b/products/slack_app/backend/feature_flags.py
@@ -49,6 +49,7 @@ SLACK_APP_AGENT_DESIGN_FLAG = "slack-app-agent-design"
SLACK_APP_FORKING_FLAG = "slack-app-forking"
SLACK_APP_PROJECT_PICKER_FLAG = "slack-app-project-picker"
SLACK_APP_MODEL_ROUTER_FLAG = "slack-app-model-router"
+SLACK_APP_INSIGHT_UNFURL_CHARTS_FLAG = "slack-app-insight-unfurl-charts"
# Linking a Slack identity to a PostHog user resolves the Slack profile and its email.
@@ -148,6 +149,19 @@ def is_slack_app_model_router_enabled(integration: Integration, distinct_id: str
)
+def is_slack_app_insight_unfurl_charts_enabled(integration: Integration, distinct_id: str | None = None) -> bool:
+ """Gate for the chart image in an insight link unfurl. The image block refers to a
+ PostHog-hosted url, so it needs no scope beyond the ones the text unfurl already uses.
+
+ ``distinct_id`` identifies the PostHog user who shared the link."""
+ return _workspace_flag_enabled(
+ SLACK_APP_INSIGHT_UNFURL_CHARTS_FLAG,
+ integration,
+ failure_log_key="slack_app_insight_unfurl_charts_feature_flag_check_failed",
+ distinct_id=distinct_id,
+ )
+
+
def is_slack_app_assistant_enabled(integration: Integration) -> bool:
"""Gate for the DM assistant: the install must hold the scopes the DM surface
calls — ``im:history`` in particular, without which the assistant would answer
diff --git a/products/slack_app/backend/logic/link_unfurl_charts.py b/products/slack_app/backend/logic/link_unfurl_charts.py
new file mode 100644
index 000000000000..0176446312f2
--- /dev/null
+++ b/products/slack_app/backend/logic/link_unfurl_charts.py
@@ -0,0 +1,157 @@
+"""Chart images for insight link unfurls.
+
+The webhook posts the text card at once, because Slack expects an ack within three seconds and a
+render takes longer. ``SlackAppUnfurlChartsWorkflow`` then renders each insight and calls
+``chat.unfurl`` again with cards that carry the chart.
+"""
+
+from __future__ import annotations
+
+from datetime import timedelta
+from typing import Any
+
+from django.conf import settings
+
+import structlog
+from slack_sdk.errors import SlackApiError
+from temporalio.exceptions import ApplicationError
+
+from posthog.dataclasses import frozen
+from posthog.models import Team, User
+from posthog.models.integration import Integration, SlackIntegration
+from posthog.temporal.ai.slack_app.types import SlackAppUnfurlChartsPostInput, SlackAppUnfurlChartsWorkflowInputs
+from posthog.user_permissions import UserPermissions
+
+from products.product_analytics.backend.facade.api import user_can_view_insight
+from products.slack_app.backend.analytics import capture_slack_event
+
+_MAX_ALT_TEXT_CHARS = 2000
+# A local render has a localhost URL that Slack cannot fetch, and Slack then rejects the whole
+# unfurl with cannot_parse_attachment. The same placeholder as subscriptions use in DEBUG.
+_DEBUG_PLACEHOLDER_IMAGE_URL = (
+ "https://raw.githubusercontent.com/PostHog/posthog/master/frontend/public/icons/android-chrome-512x512.png"
+)
+# Slack errors that a later attempt can fix. Any other error means Slack rejects the payload itself.
+_TRANSIENT_SLACK_ERRORS = frozenset(
+ {"ratelimited", "internal_error", "fatal_error", "service_unavailable", "request_timeout"}
+)
+
+logger = structlog.get_logger(__name__)
+
+
+def chat_unfurl_kwargs(
+ *, channel: str, ts: str, unfurls: dict[str, Any], unfurl_id: str | None, source: str | None
+) -> dict[str, Any]:
+ kwargs: dict[str, Any] = {"channel": channel, "ts": ts, "unfurls": unfurls}
+ if unfurl_id:
+ kwargs["unfurl_id"] = unfurl_id
+ if source:
+ kwargs["source"] = source
+ return kwargs
+
+
+def _has_project_access(user: User, team: Team) -> bool:
+ # The insight check alone is not enough, because it can fall back to the default access level
+ # in a project that denies the user. The webhook checks project access the same way.
+ return UserPermissions(user=user, team=team).current_team.effective_membership_level is not None
+
+
+@frozen
+class UnfurlChartTargets:
+ team: Team
+ user: User
+ insight_ids: list[int]
+
+
+def unfurl_chart_targets(inputs: SlackAppUnfurlChartsWorkflowInputs) -> UnfurlChartTargets:
+ team = Team.objects.get(id=inputs.team_id)
+ user = User.objects.get(id=inputs.user_id)
+ if not _has_project_access(user, team):
+ return UnfurlChartTargets(team=team, user=user, insight_ids=[])
+ # Two links to the same insight in one message share one render.
+ insight_ids = list(dict.fromkeys(chart.insight_id for chart in inputs.charts))
+ return UnfurlChartTargets(team=team, user=user, insight_ids=insight_ids)
+
+
+def with_chart_images(unfurls: dict[str, Any], image_urls: dict[str, str], titles: dict[str, str]) -> dict[str, Any]:
+ """The unfurls with an image block under the title of each card that has a chart."""
+ result: dict[str, Any] = {}
+ for url, payload in unfurls.items():
+ blocks = list(payload.get("blocks") or [])
+ image_url = image_urls.get(url)
+ if image_url is not None:
+ alt_text = (titles.get(url) or "Insight chart")[:_MAX_ALT_TEXT_CHARS]
+ blocks.insert(1, {"type": "image", "image_url": image_url, "alt_text": alt_text})
+ result[url] = {**payload, "blocks": blocks}
+ return result
+
+
+def _raise_if_transient(error: SlackApiError) -> None:
+ response = error.response
+ code = response.get("error") if response is not None else None
+ if code == "ratelimited" and response is not None:
+ retry_after = int(response.headers.get("Retry-After", 0) or 0)
+ # The fixed retry interval is often shorter than the wait that Slack asks for.
+ raise ApplicationError(
+ "Slack rate limited chat.unfurl", next_retry_delay=timedelta(seconds=max(retry_after, 1))
+ ) from error
+ if code in _TRANSIENT_SLACK_ERRORS or (response is not None and response.status_code >= 500):
+ raise error
+
+
+def post_unfurl_charts(post: SlackAppUnfurlChartsPostInput, *, image_urls_by_insight: dict[int, str]) -> None:
+ """Post the rendered charts. ``image_urls_by_insight`` holds a delivery url for each insight that rendered."""
+ request = post.request
+ integration = Integration.objects.select_related("team__organization").get(
+ id=request.integration_id, team_id=request.team_id
+ )
+ team = integration.team
+ user = User.objects.filter(id=request.user_id).first()
+ failure_reason: str | None = None
+ image_urls: dict[str, str] = {}
+ if user is None:
+ failure_reason = "user_missing"
+ elif not team.organization.allow_publicly_shared_resources:
+ # The image url opens without a PostHog login.
+ failure_reason = "public_sharing_disabled"
+ elif not _has_project_access(user, team):
+ failure_reason = "no_project_access"
+ else:
+ # Checked again because the sharer's access can change while the chart renders.
+ allowed = {
+ insight_id: _DEBUG_PLACEHOLDER_IMAGE_URL if settings.DEBUG else url
+ for insight_id, url in image_urls_by_insight.items()
+ if user_can_view_insight(team=team, user=user, insight_id=insight_id)
+ }
+ image_urls = {chart.url: allowed[chart.insight_id] for chart in request.charts if chart.insight_id in allowed}
+
+ if image_urls:
+ titles = {chart.url: chart.title for chart in request.charts}
+ try:
+ SlackIntegration(integration).client.chat_unfurl(
+ **chat_unfurl_kwargs(
+ channel=request.channel,
+ ts=request.message_ts,
+ unfurls=with_chart_images(request.unfurls, image_urls, titles),
+ unfurl_id=request.unfurl_id,
+ source=request.source,
+ )
+ )
+ except SlackApiError as e:
+ _raise_if_transient(e)
+ error = e.response.get("error") if e.response is not None else None
+ logger.warning("slack_app_unfurl_charts_rejected", team_id=team.pk, error=error)
+ failure_reason = error or "slack_api_error"
+ image_urls = {}
+
+ capture_slack_event(
+ integration,
+ "slack app link unfurl charts",
+ slack_user_id=request.slack_user_id,
+ posthog_user=user,
+ charts_requested=len(request.charts),
+ charts_shown=len(image_urls),
+ charts_failed=len(request.charts) - len(image_urls),
+ duration_ms=post.elapsed_ms,
+ failure_reason=failure_reason,
+ )
diff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.py
index a401019b2fa4..89ae4fba987e 100644
--- a/products/slack_app/backend/slack_link_unfurl.py
+++ b/products/slack_app/backend/slack_link_unfurl.py
@@ -1,24 +1,34 @@
-"""Slack link unfurling for PostHog resource URLs (metadata only).
+"""Slack link unfurling for PostHog resource URLs.
Ticket subjects and messages are customer-authored, so every one goes through `escape_slack_mrkdwn`.
"""
from __future__ import annotations
+import asyncio
+import dataclasses
from typing import Literal
from urllib.parse import parse_qs, urlparse
from uuid import UUID
+from django.conf import settings
from django.core.exceptions import ValidationError
import structlog
+from temporalio.exceptions import WorkflowAlreadyStartedError
-from posthog.models import Team
+from posthog.models import Team, User
from posthog.models.comment import Comment
from posthog.models.integration import Integration, SlackIntegration
from posthog.models.user_integration import UserIntegration
from posthog.redis import get_client
from posthog.slack.formatting import escape_slack_mrkdwn
+from posthog.temporal.ai.slack_app.slack_app_unfurl_charts import (
+ SLACK_APP_UNFURL_CHARTS_WORKFLOW_TIMEOUT,
+ SlackAppUnfurlChartsWorkflow,
+)
+from posthog.temporal.ai.slack_app.types import SlackAppUnfurlChartsWorkflowInputs, SlackUnfurlChartRequest
+from posthog.temporal.common.client import sync_connect
from posthog.utils import get_instance_region
from products.access_control.backend.facade.user_access_control import (
@@ -29,6 +39,8 @@ from products.conversations.backend.models.ticket import Ticket
from products.dashboards.backend.models.dashboard import Dashboard
from products.product_analytics.backend.facade.models import Insight
from products.slack_app.backend.analytics import capture_slack_event
+from products.slack_app.backend.feature_flags import is_slack_app_insight_unfurl_charts_enabled
+from products.slack_app.backend.logic.link_unfurl_charts import chat_unfurl_kwargs
from products.slack_app.backend.services.followup_invite import build_followup_invite
from products.slack_app.backend.services.slack_messages import UNFURL_OPT_OUT_PARAM
from products.tasks.backend.facade import api as tasks_facade
@@ -47,6 +59,9 @@ _INVITE_THROTTLE_SECONDS = 24 * 60 * 60
# The throttle must fail fast rather than correctly: it sits inside the webhook's ack budget.
_INVITE_REDIS_TIMEOUT_SECONDS = 0.3
+# Each chart is a render, so one message with many insight links gets charts for the first few.
+_MAX_UNFURL_CHARTS = 3
+
# Query `source.kind` / top-level `kind` → short name before " insight" (sync with InsightType / query kinds).
_QUERY_KIND_TO_SHORT_NAME: dict[str, str] = {
"TrendsQuery": "Trends",
@@ -439,6 +454,84 @@ def _attach_public_slack_thread_reference(
)
+def start_unfurl_charts(
+ *,
+ integration: Integration,
+ user: User,
+ event: dict,
+ unfurls: dict[str, dict],
+ charts: list[SlackUnfurlChartRequest],
+) -> None:
+ """Start the workflow that adds chart images to the posted cards. Best effort: a failure keeps the text cards.
+
+ The image url opens without a PostHog login, so an organization that turns off public
+ sharing gets no charts.
+ """
+ if not integration.team.organization.allow_publicly_shared_resources:
+ return
+ if not is_slack_app_insight_unfurl_charts_enabled(integration, distinct_id=str(user.distinct_id)):
+ return
+ channel = event["channel"]
+ message_ts = event["message_ts"]
+ inputs = SlackAppUnfurlChartsWorkflowInputs(
+ team_id=integration.team_id,
+ integration_id=integration.id,
+ user_id=user.pk,
+ slack_user_id=event["user"],
+ channel=channel,
+ message_ts=message_ts,
+ unfurl_id=event.get("unfurl_id"),
+ source=event.get("source"),
+ unfurls=unfurls,
+ charts=charts[:_MAX_UNFURL_CHARTS],
+ export_task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,
+ )
+ try:
+ client = sync_connect()
+ asyncio.run(
+ client.start_workflow(
+ SlackAppUnfurlChartsWorkflow.run,
+ inputs,
+ id=f"slack-app-unfurl-charts-{integration.integration_id}:{channel}:{message_ts}",
+ task_queue=settings.TASKS_TASK_QUEUE,
+ execution_timeout=SLACK_APP_UNFURL_CHARTS_WORKFLOW_TIMEOUT,
+ )
+ )
+ except WorkflowAlreadyStartedError:
+ # Slack sent the event again while the first run is still rendering.
+ pass
+ except Exception:
+ logger.warning("slack_app_unfurl_charts_dispatch_failed", team_id=integration.team_id, exc_info=True)
+
+
+def _queue_unfurl_charts(
+ *,
+ integration: Integration,
+ user: User,
+ event: dict,
+ unfurls: dict[str, dict],
+ charts: list[SlackUnfurlChartRequest],
+) -> bool:
+ """Queue ``start_unfurl_charts`` on Celery. The flag check and the Temporal start make network
+ calls, and the webhook must ack within Slack's three-second budget."""
+ # noqa reason: the task module imports api, which imports this module at load time.
+ from products.slack_app.backend.tasks import start_slack_unfurl_charts # noqa: PLC0415
+
+ try:
+ start_slack_unfurl_charts.delay(
+ team_id=integration.team_id,
+ integration_id=integration.id,
+ user_id=user.pk,
+ event=event,
+ unfurls=unfurls,
+ charts=[dataclasses.asdict(chart) for chart in charts],
+ )
+ except Exception:
+ logger.warning("slack_app_unfurl_charts_queue_failed", team_id=integration.team_id, exc_info=True)
+ return False
+ return True
+
+
def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
"""
Unfurl supported PostHog resource links with metadata.
@@ -493,6 +586,7 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
# Every resource we recognized but chose not to unfurl, so a report of "no unfurl appeared"
# can be answered from logs instead of by re-deriving the path by hand.
skipped: list[dict[str, str]] = []
+ chart_requests: list[SlackUnfurlChartRequest] = []
for link_obj in links:
raw_url = link_obj.get("url")
@@ -530,6 +624,7 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
unfurls[raw_url] = _unfurl_payload(
resource_label=_insight_resource_label(insight), title=title, description=desc
)
+ chart_requests.append(SlackUnfurlChartRequest(url=raw_url, insight_id=insight.id, title=title))
elif kind == "dashboard":
if not isinstance(ref, int):
continue
@@ -620,17 +715,20 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
if invite:
unfurls[invite_url]["blocks"].append(invite)
- unfurl_kwargs: dict = {"channel": channel, "ts": message_ts, "unfurls": unfurls}
- if unfurl_id:
- unfurl_kwargs["unfurl_id"] = unfurl_id
- if source:
- unfurl_kwargs["source"] = source
-
try:
- slack.client.chat_unfurl(**unfurl_kwargs)
+ slack.client.chat_unfurl(
+ **chat_unfurl_kwargs(channel=channel, ts=message_ts, unfurls=unfurls, unfurl_id=unfurl_id, source=source)
+ )
except Exception:
logger.exception("slack_link_unfurl_chat_unfurl_failed", team_id=team.pk)
else:
+ charts_queued = bool(chart_requests) and _queue_unfurl_charts(
+ integration=integration,
+ user=user,
+ event=event,
+ unfurls=unfurls,
+ charts=chart_requests,
+ )
capture_slack_event(
integration,
"slack app link unfurled",
@@ -640,4 +738,5 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
unfurled_count=len(unfurls),
skipped_count=len(skipped),
followup_invite_shown=invite is not None,
+ charts_queued=charts_queued,
)
diff --git a/products/slack_app/backend/tasks.py b/products/slack_app/backend/tasks.py
index 6492a018fb87..69ee77de8f7e 100644
--- a/products/slack_app/backend/tasks.py
+++ b/products/slack_app/backend/tasks.py
@@ -1,12 +1,20 @@
"""Celery tasks for the Slack app product."""
+from typing import Any
+
from celery import shared_task
+from posthog.models import User
+from posthog.models.integration import Integration
+from posthog.models.scoping import with_team_scope
+from posthog.temporal.ai.slack_app.types import SlackUnfurlChartRequest
+
from products.slack_app.backend.api import (
SLACK_INTEGRATION_KIND,
does_other_region_claim_workspace,
send_region_proxy_request,
)
+from products.slack_app.backend.slack_link_unfurl import start_unfurl_charts
@shared_task(ignore_result=True)
@@ -29,3 +37,29 @@ def mirror_slack_message_event(
# The body rides as text because Celery serializes arguments to JSON. Slack signs the raw
# bytes, and the payload is UTF-8 JSON, so the decode/encode round trip is byte-exact.
send_region_proxy_request(method="POST", target_url=target_url, headers=headers, body=body.encode("utf-8"))
+
+
+@shared_task(ignore_result=True)
+@with_team_scope()
+def start_slack_unfurl_charts(
+ *,
+ team_id: int,
+ integration_id: int,
+ user_id: int,
+ event: dict[str, Any],
+ unfurls: dict[str, Any],
+ charts: list[dict[str, Any]],
+) -> None:
+ integration = (
+ Integration.objects.select_related("team__organization").filter(id=integration_id, team_id=team_id).first()
+ )
+ user = User.objects.filter(id=user_id).first()
+ if integration is None or user is None:
+ return
+ start_unfurl_charts(
+ integration=integration,
+ user=user,
+ event=event,
+ unfurls=unfurls,
+ charts=[SlackUnfurlChartRequest(**chart) for chart in charts],
+ )
diff --git a/products/slack_app/backend/tests/logic/__init__.py b/products/slack_app/backend/tests/logic/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/slack_app/backend/tests/logic/test_link_unfurl_charts.py b/products/slack_app/backend/tests/logic/test_link_unfurl_charts.py
new file mode 100644
index 000000000000..79956b9d1124
--- /dev/null
+++ b/products/slack_app/backend/tests/logic/test_link_unfurl_charts.py
@@ -0,0 +1,167 @@
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from slack_sdk.errors import SlackApiError
+from slack_sdk.web.slack_response import SlackResponse
+from temporalio.exceptions import ApplicationError
+
+from posthog.constants import AvailableFeature
+from posthog.models import User
+from posthog.models.integration import Integration
+from posthog.temporal.ai.slack_app.types import (
+ SlackAppUnfurlChartsPostInput,
+ SlackAppUnfurlChartsWorkflowInputs,
+ SlackUnfurlChartAsset,
+ SlackUnfurlChartRequest,
+)
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.product_analytics.backend.facade.models import Insight
+from products.slack_app.backend.logic.link_unfurl_charts import post_unfurl_charts, unfurl_chart_targets
+
+_URL = "https://us.posthog.com/project/1/insights/abc123"
+_SHORT_URL = "https://us.posthog.com/i/abc123"
+_TEXT_CARD = {"type": "section", "text": {"type": "mrkdwn", "text": "*Weekly active users • Trends insight*"}}
+
+
+def _slack_error(code: str, status_code: int) -> SlackApiError:
+ response = SlackResponse(
+ client=None,
+ http_verb="POST",
+ api_url="https://slack.com/api/chat.unfurl",
+ req_args={},
+ data={"ok": False, "error": code},
+ headers={"Retry-After": "30"},
+ status_code=status_code,
+ )
+ return SlackApiError(code, response)
+
+
+class TestLinkUnfurlCharts(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.integration = Integration.objects.create(
+ team=self.team, kind="slack", integration_id="TSlack01", sensitive_config={"access_token": "xoxb-test"}
+ )
+ self.insight = Insight.objects.create(
+ team=self.team,
+ short_id="abc123",
+ name="Weekly active users",
+ saved=True,
+ query={"kind": "InsightVizNode", "source": {"kind": "TrendsQuery"}},
+ )
+
+ def _inputs(self, urls: tuple[str, ...] = (_URL,), user: User | None = None) -> SlackAppUnfurlChartsWorkflowInputs:
+ return SlackAppUnfurlChartsWorkflowInputs(
+ team_id=self.team.pk,
+ integration_id=self.integration.id,
+ user_id=(user or self.user).pk,
+ slack_user_id="U1",
+ channel="C1",
+ message_ts="123.456",
+ unfurl_id=None,
+ source=None,
+ unfurls={url: {"blocks": [_TEXT_CARD]} for url in urls},
+ charts=[
+ SlackUnfurlChartRequest(url=url, insight_id=self.insight.id, title="Weekly active users")
+ for url in urls
+ ],
+ export_task_queue="unused",
+ )
+
+ def _deny_project_access(self) -> User:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ AccessControl.objects.create(
+ team=self.team, resource="project", resource_id=str(self.team.id), access_level="none"
+ )
+ return User.objects.create_and_join(self.organization, "[email protected]", "password")
+
+ def _post(self, inputs: SlackAppUnfurlChartsWorkflowInputs) -> None:
+ post_unfurl_charts(
+ SlackAppUnfurlChartsPostInput(
+ request=inputs,
+ rendered=[SlackUnfurlChartAsset(insight_id=self.insight.id, asset_id=1)],
+ elapsed_ms=1,
+ ),
+ image_urls_by_insight={self.insight.id: "https://example.com/chart.png"},
+ )
+
+ @parameterized.expand([("project_access", True), ("project_access_revoked", False)])
+ def test_targets_render_each_insight_once_and_only_with_project_access(
+ self, _name: str, project_access: bool
+ ) -> None:
+ user = self.user if project_access else self._deny_project_access()
+
+ targets = unfurl_chart_targets(self._inputs(urls=(_URL, _SHORT_URL), user=user))
+
+ assert targets.insight_ids == ([self.insight.id] if project_access else [])
+
+ @parameterized.expand(
+ [
+ ("allowed", True, True, True),
+ ("public_sharing_turned_off", False, True, False),
+ ("project_access_revoked", True, False, False),
+ ]
+ )
+ @patch("products.slack_app.backend.logic.link_unfurl_charts.SlackIntegration")
+ def test_post_adds_the_chart_under_the_title_only_when_allowed(
+ self,
+ _name: str,
+ public_sharing: bool,
+ project_access: bool,
+ expect_unfurl: bool,
+ mock_slack: MagicMock,
+ ) -> None:
+ self.organization.allow_publicly_shared_resources = public_sharing
+ self.organization.save()
+ user = self.user if project_access else self._deny_project_access()
+
+ self._post(self._inputs(user=user))
+
+ chat_unfurl = mock_slack.return_value.client.chat_unfurl
+ if not expect_unfurl:
+ chat_unfurl.assert_not_called()
+ return
+ blocks = chat_unfurl.call_args.kwargs["unfurls"][_URL]["blocks"]
+ assert blocks[0] == _TEXT_CARD
+ assert blocks[1]["type"] == "image"
+ assert blocks[1]["alt_text"] == "Weekly active users"
+ assert blocks[1]["image_url"].startswith("http")
+
+ @parameterized.expand(
+ [
+ ("rejected_payload", "cannot_parse_attachment", 200, None),
+ ("rate_limited", "ratelimited", 429, ApplicationError),
+ ("slack_outage", "internal_error", 500, SlackApiError),
+ ]
+ )
+ @patch("products.slack_app.backend.logic.link_unfurl_charts.capture_slack_event")
+ @patch("products.slack_app.backend.logic.link_unfurl_charts.SlackIntegration")
+ def test_post_retries_only_a_transient_slack_error(
+ self,
+ _name: str,
+ slack_error: str,
+ status_code: int,
+ expected_raise: type[Exception] | None,
+ mock_slack: MagicMock,
+ mock_capture: MagicMock,
+ ) -> None:
+ mock_slack.return_value.client.chat_unfurl.side_effect = _slack_error(slack_error, status_code)
+ inputs = self._inputs()
+
+ if expected_raise is not None:
+ with pytest.raises(expected_raise) as raised:
+ self._post(inputs)
+ if isinstance(raised.value, ApplicationError):
+ assert raised.value.next_retry_delay is not None
+ assert raised.value.next_retry_delay.total_seconds() == 30
+ mock_capture.assert_not_called()
+ return
+ self._post(inputs)
+ assert mock_capture.call_args.kwargs["charts_shown"] == 0
+ assert mock_capture.call_args.kwargs["failure_reason"] == slack_error
diff --git a/products/slack_app/backend/tests/test_link_unfurl.py b/products/slack_app/backend/tests/test_link_unfurl.py
index dce0eb127c9f..a3e57373a3c6 100644
--- a/products/slack_app/backend/tests/test_link_unfurl.py
+++ b/products/slack_app/backend/tests/test_link_unfurl.py
@@ -1,6 +1,8 @@
+import json
+
import pytest
from posthog.test.base import APIBaseTest
-from unittest.mock import MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase, override_settings
@@ -31,6 +33,7 @@ from products.slack_app.backend.slack_link_unfurl import (
handle_posthog_link_unfurl,
parse_posthog_resource_link,
)
+from products.slack_app.backend.tasks import start_slack_unfurl_charts
from products.tasks.backend.models import Task
@@ -160,6 +163,54 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
assert "Weekly active users" in text
assert "A test description" in text
+ @parameterized.expand(
+ [
+ ("allowed", True, True, True),
+ ("flag_off", False, True, False),
+ ("public_sharing_off", True, False, False),
+ ]
+ )
+ @patch("products.slack_app.backend.tasks.start_slack_unfurl_charts.delay")
+ @patch("products.slack_app.backend.slack_link_unfurl.sync_connect")
+ @patch("products.slack_app.backend.slack_link_unfurl.is_slack_app_insight_unfurl_charts_enabled")
+ @patch("products.slack_app.backend.api.resolve_slack_user")
+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
+ def test_insight_unfurl_starts_the_chart_workflow_only_when_allowed(
+ self,
+ _name: str,
+ flag_on: bool,
+ public_sharing: bool,
+ expect_started: bool,
+ mock_slack_integration_class: MagicMock,
+ mock_resolve: MagicMock,
+ mock_flag: MagicMock,
+ mock_sync_connect: MagicMock,
+ mock_delay: MagicMock,
+ ) -> None:
+ # Runs the queued task in process, through JSON like the Celery broker.
+ mock_delay.side_effect = lambda **kwargs: start_slack_unfurl_charts(**json.loads(json.dumps(kwargs)))
+ self.organization.allow_publicly_shared_resources = public_sharing
+ self.organization.save()
+ mock_resolve.return_value = MagicMock(user=self.user)
+ mock_flag.return_value = flag_on
+ mock_sync_connect.return_value.start_workflow = AsyncMock()
+ url = f"http://testserver/project/{self.team.pk}/insights/{self.insight.short_id}"
+
+ handle_posthog_link_unfurl(
+ {"channel": "C1", "message_ts": "123.456", "user": "U1", "links": [{"url": url}]},
+ self.integration,
+ )
+
+ start_workflow = mock_sync_connect.return_value.start_workflow
+ if not expect_started:
+ start_workflow.assert_not_called()
+ return
+ inputs = start_workflow.call_args.args[1]
+ assert [chart.insight_id for chart in inputs.charts] == [self.insight.id]
+ assert (
+ inputs.unfurls == mock_slack_integration_class.return_value.client.chat_unfurl.call_args.kwargs["unfurls"]
+ )
+
@patch("products.slack_app.backend.api.resolve_slack_user")
@patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
def test_unfurls_task_and_attaches_public_thread_once(