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(tasks): compose Slack answers with chart cards on delivery (#75260)

Sam Penningtonf738e8c2e53b
diff --git a/products/exports/backend/facade/api.py b/products/exports/backend/facade/api.py
index 96b3f22d7b4a..36b841d7526a 100644
--- a/products/exports/backend/facade/api.py
+++ b/products/exports/backend/facade/api.py
@@ -108,6 +108,24 @@ def _validate_adhoc_export_context(export_context: dict) -> None:
raise ValueError("export_context.source must be an InsightVizNode-wrapped query")
+def get_delivery_image_url(*, team_id: int, asset_id: int, expiry_delta: timedelta) -> str | None:
+ """Mint a delivery-purposed url for one of the team's own rendered images.
+
+ The token authenticates anonymously and bypasses the org's publicly-shared-resources
+ setting, so it is minted on demand rather than stored anywhere a lower-privileged
+ reader could reach. Callers are responsible for only passing an ``asset_id`` they
+ established server-side; the format and team filters bound the damage if one leaks —
+ an image url can never be turned into a CSV or XLSX download. The manager also
+ excludes assets past their TTL.
+ """
+ asset = ExportedAsset.objects.filter(
+ team_id=team_id, id=asset_id, export_format=ExportedAsset.ExportFormat.PNG
+ ).first()
+ if asset is None:
+ return None
+ return asset.get_subscription_delivery_content_url(expiry_delta=expiry_delta)
+
+
def render_png_export(
*,
team: Team,
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index c098d24e56f6..962e3bb2e021 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -463,8 +463,9 @@ class SlackThreadHandler:
def post_footer(self) -> None:
"""Post the footer alone, for an answer with no message of its own to close.
- Only the file-delivery path needs this: the answer rode along as a file upload's
- initial comment, which takes no blocks, so the footer has nothing to attach to.
+ Only the composed chart delivery needs this: the answer rode along in the message
+ carrying the chart cards, whose blocks are built during delivery, so the footer
+ has nothing to attach to.
"""
footer = self._footer_block()
if not footer:
diff --git a/products/tasks/backend/logic/services/living_artifacts.py b/products/tasks/backend/logic/services/living_artifacts.py
index b4b751c9f21e..4e9c3958abbc 100644
--- a/products/tasks/backend/logic/services/living_artifacts.py
+++ b/products/tasks/backend/logic/services/living_artifacts.py
@@ -3,23 +3,32 @@ from __future__ import annotations
import io
import os
import json
+import time
import uuid
import zipfile
import mimetypes
from abc import ABC, abstractmethod
+from collections.abc import Callable
from dataclasses import dataclass, replace
+from datetime import timedelta
from typing import Any
+from urllib.parse import urlparse
from uuid import UUID
from django.db import transaction
+from django.db.models import QuerySet
from django.utils import timezone
import requests
import structlog
from slack_sdk.errors import SlackApiError
+from posthog.event_usage import groups
+from posthog.ph_client import ph_scoped_capture
from posthog.storage import object_storage
+from posthog.utils import absolute_uri
+from products.exports.backend.facade.api import get_delivery_image_url
from products.tasks.backend.models import TaskArtifact, TaskRun
logger = structlog.get_logger(__name__)
@@ -119,7 +128,12 @@ def create_living_artifact(
selected_adapter = _resolve_adapter(run, adapter, artifact_type)
artifact_id = uuid.uuid4()
commit = selected_adapter.create(
- run=run, name=name, artifact_type=artifact_type, content=content_payload, artifact_id=str(artifact_id)
+ run=run,
+ name=name,
+ artifact_type=artifact_type,
+ content=content_payload,
+ artifact_id=str(artifact_id),
+ export_asset_id=export_asset_id,
)
with transaction.atomic():
@@ -449,6 +463,7 @@ class LivingArtifactAdapter(ABC):
artifact_type: str,
content: ArtifactContent,
artifact_id: str | None = None,
+ export_asset_id: int | None = None,
) -> ArtifactCommit:
return self.commit(
artifact=None,
@@ -461,6 +476,7 @@ class LivingArtifactAdapter(ABC):
content_type=content.content_type,
content_bytes=content.content_bytes,
source_artifact=content.source_artifact,
+ export_asset_id=export_asset_id,
)
@abstractmethod
@@ -484,6 +500,7 @@ class LivingArtifactAdapter(ABC):
content_type: str | None = None,
content_bytes: bytes | None = None,
source_artifact: dict[str, Any] | None = None,
+ export_asset_id: int | None = None,
) -> ArtifactCommit:
raise NotImplementedError
@@ -516,6 +533,7 @@ class DocumentConnectorArtifactAdapter(LivingArtifactAdapter):
content_type: str | None = None,
content_bytes: bytes | None = None,
source_artifact: dict[str, Any] | None = None,
+ export_asset_id: int | None = None,
) -> ArtifactCommit:
connector = _document_connector_adapter_for_run(run)
if connector is not None:
@@ -531,6 +549,7 @@ class DocumentConnectorArtifactAdapter(LivingArtifactAdapter):
content_type=content_type,
content_bytes=content_bytes,
source_artifact=source_artifact,
+ export_asset_id=export_asset_id,
)
except DocumentConnectorUnavailable as exc:
logger.info("task_run.document_connector_unavailable", run_id=str(run.id))
@@ -565,6 +584,7 @@ class SlackMessageArtifactAdapter(LivingArtifactAdapter):
content_type: str | None = None,
content_bytes: bytes | None = None,
source_artifact: dict[str, Any] | None = None,
+ export_asset_id: int | None = None,
) -> ArtifactCommit:
mapping = _get_slack_mapping(run)
text = content.strip() or name
@@ -626,6 +646,7 @@ class SlackCanvasArtifactAdapter(LivingArtifactAdapter):
content_type: str | None = None,
content_bytes: bytes | None = None,
source_artifact: dict[str, Any] | None = None,
+ export_asset_id: int | None = None,
) -> ArtifactCommit:
mapping = _get_slack_mapping(run)
if not _canvas_file_artifacts_enabled(mapping):
@@ -703,6 +724,34 @@ class SlackCanvasArtifactAdapter(LivingArtifactAdapter):
)
+# Slack re-fetches image_url after the message is posted, so the token has to outlive the
+# post. Scoped to the artifact's own 30-day storage TTL rather than the 365-day default.
+_CHART_IMAGE_URL_TTL = timedelta(days=30)
+
+
+def _delivery_image_url(team_id: int, export_asset_id: int | None) -> str | None:
+ """Mint the url delivery references for a chart image, or None when there is no export.
+
+ The url is trustworthy because it is minted here from the export link the chart
+ endpoint set server-side (a dedicated column callers can never write).
+ """
+ if export_asset_id is None:
+ return None
+ return get_delivery_image_url(team_id=team_id, asset_id=export_asset_id, expiry_delta=_CHART_IMAGE_URL_TTL)
+
+
+def _is_url_backed_image(content_type: str, *, team_id: int, export_asset_id: int | None) -> bool:
+ """Whether delivery can post this version as an image block instead of an upload.
+
+ Reads only the link being written with this version, so an edit (which always drops
+ the export link) needs files:write for its new bytes rather than passing on the
+ strength of the old render.
+ """
+ if not content_type.startswith("image/"):
+ return False
+ return _delivery_image_url(team_id, export_asset_id) is not None
+
+
class SlackFileArtifactAdapter(LivingArtifactAdapter):
adapter = TaskArtifact.Adapter.SLACK_FILE
@@ -722,6 +771,7 @@ class SlackFileArtifactAdapter(LivingArtifactAdapter):
content_type: str | None = None,
content_bytes: bytes | None = None,
source_artifact: dict[str, Any] | None = None,
+ export_asset_id: int | None = None,
) -> ArtifactCommit:
mapping = _get_slack_mapping(run)
if not _canvas_file_artifacts_enabled(mapping):
@@ -730,14 +780,19 @@ class SlackFileArtifactAdapter(LivingArtifactAdapter):
"Use adapter=slack_message and summarize the result as text instead."
)
slack_integration = _slack_integration_for_mapping(mapping)
- missing_scopes = slack_integration.missing_scopes(frozenset({SLACK_FILE_SCOPE}))
- if missing_scopes:
+ resolved_content_type = content_type or _guess_content_type(name)
+ # Chart images deliver as image blocks referencing a PostHog-hosted url, which needs no
+ # upload and therefore no files:write. Everything else (non-images, and images with no
+ # resolvable export) goes out as an upload, so it needs the scope up front — accepting it
+ # here would leave the artifact pending forever with the agent believing it was delivered.
+ if not _is_url_backed_image(resolved_content_type, team_id=run.team_id, export_asset_id=export_asset_id) and (
+ slack_integration.missing_scopes(frozenset({SLACK_FILE_SCOPE}))
+ ):
raise ValueError(
"Slack file delivery is unavailable: the Slack integration is missing the files:write scope, "
"so you do not have this capability. Use adapter=slack_message and summarize the result as text instead."
)
- resolved_content_type = content_type or _guess_content_type(name)
payload = content_bytes if content_bytes is not None else content.encode("utf-8")
artifact_key = str(artifact.id) if artifact is not None else artifact_id or uuid.uuid4().hex
storage_path = build_living_artifact_storage_path(run, artifact_key, version, name)
@@ -789,69 +844,168 @@ def has_pending_slack_file_artifacts(run: TaskRun) -> bool:
return any(_pending_slack_file_version(artifact) is not None for artifact in artifacts)
-def deliver_pending_slack_file_artifacts(run: TaskRun, *, initial_comment: str) -> int:
+# Mutable: delivery accumulates into it as each card is posted.
+@dataclass(frozen=False)
+class SlackFileDeliveryResult:
+ answer_posted: bool = False
+ delivered_count: int = 0
+
+
+def has_pending_slack_image_artifacts(run: TaskRun) -> bool:
+ for artifact in _pending_slack_file_queryset(run):
+ pending = _pending_slack_file_version(artifact)
+ if pending is None:
+ continue
+ content_type = _pending_slack_content_type(artifact, pending[1])
+ if content_type.startswith("image/"):
+ return True
+ return False
+
+
+def deliver_pending_slack_file_artifacts(
+ run: TaskRun, *, answer_sections: list[str] | None = None
+) -> SlackFileDeliveryResult:
+ """Deliver pending slack_file artifacts to the mapped thread.
+
+ Images compose into a single chat message together with ``answer_sections``
+ (the relay's converted answer text): text sections first, then one card per
+ chart (title, image block, "Open in PostHog" button). Chart images reference a
+ url minted here from their export asset — Slack's image proxy fetches the PNG
+ from us, so no file upload (and no files:write scope) is involved; other images
+ upload without a channel share and are referenced by file id. chat.postMessage
+ is synchronous, so the whole answer lands atomically — unlike channel file
+ shares, which Slack materializes asynchronously. Non-image files still deliver
+ as channel shares (these do need files:write), after the composed message.
+ ``answer_posted`` tells the caller whether the answer text went out in the
+ composed message so it isn't posted twice.
+ """
+ result = SlackFileDeliveryResult()
mapping = _get_slack_mapping(run, raise_if_missing=False)
if mapping is None:
- return 0
+ return result
if not _living_artifacts_enabled_for_mapping(mapping):
logger.warning("task_artifact.slack_living_artifacts_disabled", task_run_id=str(run.id))
- return 0
+ return result
if not _canvas_file_artifacts_enabled(mapping):
logger.warning("task_artifact.slack_file_delivery_disabled", task_run_id=str(run.id))
- return 0
+ return result
slack_integration = _slack_integration_for_mapping(mapping)
- missing_scopes = slack_integration.missing_scopes(frozenset({SLACK_FILE_SCOPE}))
- if missing_scopes:
- logger.warning(
- "task_artifact.slack_file_delivery_missing_scope",
- task_run_id=str(run.id),
- missing_scopes=sorted(missing_scopes),
- )
- return 0
+ has_file_scope = not slack_integration.missing_scopes(frozenset({SLACK_FILE_SCOPE}))
+
+ # The relay activity's start_to_close_timeout is a minute; a self-inflicted timeout would
+ # replay it and repost everything, so budget all Slack I/O — uploads included — and stop
+ # rather than run past it. Whatever misses the budget stays pending for the next relay.
+ deadline = time.monotonic() + _SLACK_POST_BUDGET_S
- artifacts = list(
- TaskArtifact.objects.for_team(run.team_id)
- .filter(
- task_id=run.task_id,
- adapter=TaskArtifact.Adapter.SLACK_FILE,
- status=TaskArtifact.Status.ACTIVE,
- )
- .order_by("created_at", "id")
- )
slack = slack_integration.client
- delivered_count = 0
- next_initial_comment = initial_comment.strip()
- for artifact in artifacts:
+ pending_files: list[tuple[TaskArtifact, dict[str, Any], str]] = []
+ for artifact in _pending_slack_file_queryset(run):
pending = _pending_slack_file_version(artifact)
if pending is None:
continue
-
_version_index, version_payload = pending
- raw_location = version_payload.get("location")
- location = raw_location if isinstance(raw_location, dict) else {}
- storage_path = str(location.get("storage_path") or (artifact.location or {}).get("storage_path") or "")
- if not storage_path:
- logger.warning("task_artifact.slack_file_missing_storage_path", artifact_id=str(artifact.id))
+ pending_files.append((artifact, version_payload, _pending_slack_content_type(artifact, version_payload)))
+
+ image_files = [f for f in pending_files if f[2].startswith("image/")]
+ other_files = [f for f in pending_files if not f[2].startswith("image/")]
+
+ # (artifact, failure_reason or None, delivery_mode) for chart artifacts only —
+ # export_asset_id marks an image as chart-endpoint output.
+ chart_outcomes: list[tuple[TaskArtifact, str | None, str | None]] = []
+
+ def _record_chart(artifact: TaskArtifact, failure_reason: str | None, delivery_mode: str | None = None) -> None:
+ if artifact.export_asset_id is not None:
+ chart_outcomes.append((artifact, failure_reason, delivery_mode))
+
+ image_cards: list[_SlackImageCard] = []
+ for artifact, version_payload, content_type in image_files:
+ # Slack fetches the image from the url in the card — nothing to upload. An artifact
+ # whose export can't be resolved for this team falls through to the upload path,
+ # which posts the stored bytes instead.
+ image_url = _delivery_image_url(run.team_id, artifact.export_asset_id)
+ if image_url is not None:
+ image_cards.append(_SlackImageCard(artifact, version_payload, image_url=image_url))
continue
-
- payload = object_storage.read_bytes(storage_path, missing_ok=True)
- if payload is None:
+ if artifact.export_asset_id is not None:
+ logger.warning("task_artifact.chart_export_asset_unresolved", artifact_id=str(artifact.id))
+ if not has_file_scope:
logger.warning(
- "task_artifact.slack_file_pending_content_missing",
+ "task_artifact.slack_file_delivery_missing_scope",
artifact_id=str(artifact.id),
- storage_path=storage_path,
+ missing_scopes=[SLACK_FILE_SCOPE],
)
+ _record_chart(artifact, "missing_scope")
continue
-
- content_type = str(
- version_payload.get("content_type")
- or location.get("content_type")
- or (artifact.location or {}).get("content_type")
- or _guess_content_type(artifact.name)
+ if time.monotonic() >= deadline:
+ logger.warning("task_artifact.slack_post_budget_exhausted", artifact_id=str(artifact.id))
+ _record_chart(artifact, "budget_exhausted")
+ continue
+ payload = _read_pending_slack_file_bytes(artifact, version_payload)
+ if payload is None:
+ _record_chart(artifact, "payload_missing")
+ continue
+ try:
+ file_id, file_response = _upload_slack_file(
+ slack, channel=None, thread_ts=None, name=artifact.name, content=payload, content_type=content_type
+ )
+ except Exception:
+ logger.warning("task_artifact.slack_file_delivery_failed", artifact_id=str(artifact.id), exc_info=True)
+ _record_chart(artifact, "upload_failed")
+ continue
+ image_cards.append(_SlackImageCard(artifact, version_payload, file_id=file_id, file_response=file_response))
+
+ if image_cards:
+ # Only cards that actually reached the thread are delivered — an unposted image
+ # is invisible (it uploaded with no channel share), so marking it delivered
+ # would lose it permanently instead of leaving it pending for the next relay.
+ delivered_artifact_ids: set[UUID] = set()
+
+ def _mark_card_delivered(card: _SlackImageCard) -> None:
+ if _mark_slack_file_artifact_delivered(
+ artifact=card.artifact,
+ version_number=int(card.version_payload.get("version") or card.artifact.current_version or 0),
+ file_id=card.file_id,
+ file_response=card.file_response,
+ ):
+ result.delivered_count += 1
+ delivered_artifact_ids.add(card.artifact.id)
+ _record_chart(card.artifact, None, "url" if card.image_url else "file_upload")
+
+ result.answer_posted = _post_composed_answer_message(
+ slack,
+ mapping=mapping,
+ image_cards=image_cards,
+ answer_sections=answer_sections or [],
+ mark_delivered=_mark_card_delivered,
+ deadline=deadline,
)
+ for card in image_cards:
+ if card.artifact.id not in delivered_artifact_ids:
+ _record_chart(card.artifact, "message_not_posted")
+ elif answer_sections is not None:
+ # Compose was requested but every image upload failed: the answer text must
+ # still land — and before the non-image shares below, to keep thread order.
+ sections = [section for section in answer_sections if section.strip()]
+ posted = [_post_thread_text(slack, mapping=mapping, text=section) for section in sections]
+ result.answer_posted = bool(sections) and all(posted)
+
+ for artifact, version_payload, content_type in other_files:
+ if not has_file_scope:
+ logger.warning(
+ "task_artifact.slack_file_delivery_missing_scope",
+ artifact_id=str(artifact.id),
+ missing_scopes=[SLACK_FILE_SCOPE],
+ )
+ continue
+ if time.monotonic() >= deadline:
+ logger.warning("task_artifact.slack_post_budget_exhausted", artifact_id=str(artifact.id))
+ continue
+ payload = _read_pending_slack_file_bytes(artifact, version_payload)
+ if payload is None:
+ continue
try:
file_id, file_response = _upload_slack_file(
slack,
@@ -860,22 +1014,341 @@ def deliver_pending_slack_file_artifacts(run: TaskRun, *, initial_comment: str)
name=artifact.name,
content=payload,
content_type=content_type,
- initial_comment=next_initial_comment,
)
except Exception:
logger.warning("task_artifact.slack_file_delivery_failed", artifact_id=str(artifact.id), exc_info=True)
continue
-
- next_initial_comment = ""
if _mark_slack_file_artifact_delivered(
artifact=artifact,
version_number=int(version_payload.get("version") or artifact.current_version or 0),
file_id=file_id,
file_response=file_response,
):
- delivered_count += 1
+ result.delivered_count += 1
+
+ _capture_chart_delivery_events(run, chart_outcomes)
+ return result
- return delivered_count
+
+def _capture_chart_delivery_events(run: TaskRun, outcomes: list[tuple[TaskArtifact, str | None, str | None]]) -> None:
+ """Emit one analytics event per chart delivery attempt. Runs in the Temporal
+ worker, where the global posthoganalytics client drops events — hence the
+ scoped client."""
+ if not outcomes:
+ return
+ try:
+ team = run.team
+ with ph_scoped_capture() as capture:
+ for artifact, failure_reason, delivery_mode in outcomes:
+ capture(
+ distinct_id=str(artifact.created_by.distinct_id if artifact.created_by else team.uuid),
+ event="task_chart_slack_delivery_failed" if failure_reason else "task_chart_slack_delivered",
+ properties={
+ "artifact_id": str(artifact.id),
+ "task_id": str(artifact.task_id),
+ "run_id": str(run.id),
+ "export_asset_id": artifact.export_asset_id,
+ "delivery_mode": delivery_mode,
+ "failure_reason": failure_reason,
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.warning("task_artifact.chart_delivery_capture_failed", task_run_id=str(run.id), exc_info=True)
+
+
+def _pending_slack_file_queryset(run: TaskRun) -> QuerySet[TaskArtifact]:
+ return (
+ TaskArtifact.objects.for_team(run.team_id)
+ .filter(
+ task_id=run.task_id,
+ adapter=TaskArtifact.Adapter.SLACK_FILE,
+ status=TaskArtifact.Status.ACTIVE,
+ )
+ .order_by("created_at", "id")
+ )
+
+
+def _read_pending_slack_file_bytes(artifact: TaskArtifact, version_payload: dict[str, Any]) -> bytes | None:
+ raw_location = version_payload.get("location")
+ location = raw_location if isinstance(raw_location, dict) else {}
+ storage_path = str(location.get("storage_path") or (artifact.location or {}).get("storage_path") or "")
+ if not storage_path:
+ logger.warning("task_artifact.slack_file_missing_storage_path", artifact_id=str(artifact.id))
+ return None
+ payload = object_storage.read_bytes(storage_path, missing_ok=True)
+ if payload is None:
+ logger.warning(
+ "task_artifact.slack_file_pending_content_missing",
+ artifact_id=str(artifact.id),
+ storage_path=storage_path,
+ )
+ return None
+ return payload
+
+
+def _pending_slack_content_type(artifact: TaskArtifact, version_payload: dict[str, Any]) -> str:
+ raw_location = version_payload.get("location")
+ location = raw_location if isinstance(raw_location, dict) else {}
+ return str(
+ version_payload.get("content_type")
+ or location.get("content_type")
+ or (artifact.location or {}).get("content_type")
+ or _guess_content_type(artifact.name)
+ )
+
+
+# Slack caps a message at 50 blocks; leading answer sections spill into plain
+# messages when a message would exceed it.
+_SLACK_MESSAGE_BLOCK_LIMIT = 50
+
+
+@dataclass(frozen=True)
+class _SlackImageCard:
+ artifact: TaskArtifact
+ version_payload: dict[str, Any]
+ # A card carries either a minted image_url (nothing uploaded) or an uploaded file id.
+ image_url: str | None = None
+ file_id: str | None = None
+ file_response: dict[str, Any] | None = None
+
+
+def _post_composed_answer_message(
+ slack: Any,
+ *,
+ mapping: Any,
+ image_cards: list[_SlackImageCard],
+ answer_sections: list[str],
+ mark_delivered: Callable[[_SlackImageCard], None],
+ deadline: float,
+) -> bool:
+ """Post answer text and chart cards, composed into one message when possible.
+
+ Returns whether the answer text fully reached the thread — a partial post returns
+ False so the caller reposts the whole answer (a duplicated chunk beats silently
+ losing the rest). ``mark_delivered`` is called for each card as soon as its own
+ post succeeds, so an activity that dies part-way through doesn't replay the cards
+ that already landed."""
+ sections = [section for section in answer_sections if section.strip()]
+ section_blocks = _section_blocks(sections)
+ card_blocks: list[dict[str, Any]] = []
+ for card in image_cards:
+ card_blocks.extend(_chart_card_blocks(card))
+
+ spill_count = max(len(section_blocks) - max(_SLACK_MESSAGE_BLOCK_LIMIT - len(card_blocks), 0), 0)
+ posted_blocks = 0
+ for block in section_blocks[:spill_count]:
+ posted_blocks += 1 if _post_thread_text(slack, mapping=mapping, text=block["text"]["text"]) else 0
+ kept = section_blocks[spill_count:]
+
+ # Cards alone can exceed the block cap (17+ charts) — composing would then fail
+ # deterministically as invalid_blocks, so go straight to the per-card path.
+ if len(kept) + len(card_blocks) <= _SLACK_MESSAGE_BLOCK_LIMIT:
+ fallback_text = sections[0] if sections else _artifact_fallback_text(image_cards[0].artifact)
+ try:
+ _post_blocks_with_processing_retry(
+ slack,
+ channel=mapping.channel,
+ thread_ts=mapping.thread_ts,
+ text=fallback_text,
+ blocks=[*kept, *card_blocks],
+ deadline=deadline,
+ )
+ for card in image_cards:
+ mark_delivered(card)
+ posted_blocks += len(kept)
+ return bool(section_blocks) and posted_blocks == len(section_blocks)
+ except Exception:
+ logger.warning("task_artifact.slack_composed_message_failed", exc_info=True)
+
+ # Degraded path: the answer must not be lost — post the text plainly, then each
+ # card on its own so one bad card can't sink the others.
+ for block in kept:
+ posted_blocks += 1 if _post_thread_text(slack, mapping=mapping, text=block["text"]["text"]) else 0
+ for card in image_cards:
+ try:
+ _post_blocks_with_processing_retry(
+ slack,
+ channel=mapping.channel,
+ thread_ts=mapping.thread_ts,
+ text=_artifact_fallback_text(card.artifact),
+ blocks=_chart_card_blocks(card),
+ attempts=_IMAGE_BLOCK_FALLBACK_ATTEMPTS,
+ deadline=deadline,
+ )
+ mark_delivered(card)
+ except Exception:
+ logger.warning("task_artifact.slack_file_delivery_failed", artifact_id=str(card.artifact.id), exc_info=True)
+ return bool(section_blocks) and posted_blocks == len(section_blocks)
+
+
+# Section blocks hard-cap at 3000 chars. The relay pre-splits at 2900 before conversion,
+# but the mention prefix and mrkdwn expansion (table column padding, escapes) can push a
+# section past that — re-split after conversion, preferring whitespace so the cut doesn't
+# land inside a converted mrkdwn entity like `<url|text>`. Tables convert to fenced blocks,
+# so a cut inside one is closed and reopened to keep each block self-contained.
+_SLACK_SECTION_BLOCK_CHAR_LIMIT = 3000
+_SLACK_CODE_FENCE = "```"
+
+
+def _section_blocks(sections: list[str]) -> list[dict[str, Any]]:
+ blocks: list[dict[str, Any]] = []
+ for section in sections:
+ for piece in _split_section_text(section):
+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": piece}})
+ return blocks
+
+
+def _split_section_text(section: str) -> list[str]:
+ pieces: list[str] = []
+ remaining = section
+ reopen = ""
+ while True:
+ candidate = reopen + remaining
+ if len(candidate) <= _SLACK_SECTION_BLOCK_CHAR_LIMIT:
+ if candidate.strip():
+ pieces.append(candidate)
+ return pieces
+ limit = _SLACK_SECTION_BLOCK_CHAR_LIMIT
+ if candidate[:limit].count(_SLACK_CODE_FENCE) % 2:
+ limit -= len(f"\n{_SLACK_CODE_FENCE}")
+ window = candidate[:limit]
+ cut = max(window.rfind("\n"), window.rfind(" "))
+ # A cut inside the reopen prefix would emit just "```" and never consume any of
+ # remaining — an infinite loop when a fenced block wraps whitespace-free content.
+ if cut <= len(reopen):
+ cut = limit
+ piece = candidate[:cut]
+ remaining = candidate[cut:].lstrip(" \n")
+ reopen = ""
+ if piece.count(_SLACK_CODE_FENCE) % 2:
+ piece += f"\n{_SLACK_CODE_FENCE}"
+ reopen = f"{_SLACK_CODE_FENCE}\n"
+ if piece.strip():
+ pieces.append(piece)
+
+
+def _post_thread_text(slack: Any, *, mapping: Any, text: str) -> bool:
+ """Post one plain text message, reporting whether it landed — callers use this to decide
+ whether the answer still needs a fallback, so a swallowed failure must not read as sent."""
+ try:
+ slack.chat_postMessage(channel=mapping.channel, thread_ts=mapping.thread_ts, text=text)
+ return True
+ except Exception:
+ logger.warning("task_artifact.slack_thread_text_failed", exc_info=True)
+ return False
+
+
+# A freshly completed upload can't be referenced in blocks until Slack finishes
+# processing it — chat.postMessage returns invalid_blocks ("invalid slack file")
+# for a second or two. Verified empirically; retry until the reference resolves.
+_IMAGE_BLOCK_POST_ATTEMPTS = 8
+# The per-card fallback runs once per chart after the composed attempt already burned
+# its budget; keep it short so the relay activity stays within its timeout.
+_IMAGE_BLOCK_FALLBACK_ATTEMPTS = 3
+_IMAGE_BLOCK_POST_RETRY_INTERVAL_S = 1.0
+_RATE_LIMIT_MAX_WAIT_S = 10.0
+# Total wall-clock budget for all Slack I/O in one delivery (uploads and posts), under
+# the relay activity's start_to_close_timeout of 1 minute.
+_SLACK_POST_BUDGET_S = 45.0
+# Slack rejects button urls over 3000 chars, and an ad-hoc chart url embeds the whole
+# encoded query JSON — a fat multi-series query can exceed it.
+_SLACK_BUTTON_URL_MAX_CHARS = 3000
+
+
+def _is_posthog_origin_url(url: str) -> bool:
+ try:
+ candidate = urlparse(url)
+ expected = urlparse(absolute_uri("/"))
+ except ValueError:
+ return False
+ return candidate.scheme == expected.scheme and candidate.netloc == expected.netloc
+
+
+def _artifact_display_title(artifact: TaskArtifact) -> str:
+ # The artifact name is a filename (the chart endpoint appends .png); Slack titles
+ # and notification previews are display copy, so drop the extension there.
+ return os.path.splitext(artifact.name)[0] or artifact.name
+
+
+def _artifact_fallback_text(artifact: TaskArtifact) -> str:
+ # Slack parses a message's top-level text as mrkdwn, so an artifact named `<@U…>` or
+ # `<!channel>` would notify from the PostHog bot — escape it like the title block does.
+ return _escape_slack_mrkdwn_text(_artifact_display_title(artifact))
+
+
+def _chart_card_blocks(card: _SlackImageCard) -> list[dict[str, Any]]:
+ artifact = card.artifact
+ metadata = artifact.metadata or {}
+ title = _artifact_display_title(artifact)
+ if card.image_url is not None:
+ image_block: dict[str, Any] = {"type": "image", "image_url": card.image_url, "alt_text": title}
+ else:
+ image_block = {"type": "image", "slack_file": {"id": card.file_id}, "alt_text": title}
+ blocks: list[dict[str, Any]] = [
+ {"type": "section", "text": {"type": "mrkdwn", "text": f"*{_escape_slack_mrkdwn_text(title)}*"}},
+ image_block,
+ ]
+ posthog_url = metadata.get("posthog_url")
+ if isinstance(posthog_url, str) and posthog_url and not _is_posthog_origin_url(posthog_url):
+ # Metadata is caller-writable through the generic living-artifact create/edit APIs, so an
+ # unchecked url would let a task writer publish a phishing button as the PostHog bot.
+ logger.warning(
+ "task_artifact.chart_url_untrusted_origin",
+ artifact_id=str(artifact.id),
+ )
+ elif isinstance(posthog_url, str) and 0 < len(posthog_url) <= _SLACK_BUTTON_URL_MAX_CHARS:
+ blocks.append(
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "Open in PostHog", "emoji": True},
+ "url": posthog_url,
+ }
+ ],
+ }
+ )
+ elif isinstance(posthog_url, str) and posthog_url:
+ logger.warning(
+ "task_artifact.chart_url_too_long_for_button",
+ artifact_id=str(artifact.id),
+ url_length=len(posthog_url),
+ )
+ return blocks
+
+
+def _post_blocks_with_processing_retry(
+ slack: Any,
+ *,
+ channel: str,
+ thread_ts: str,
+ text: str,
+ blocks: list[dict[str, Any]],
+ attempts: int = _IMAGE_BLOCK_POST_ATTEMPTS,
+ deadline: float | None = None,
+) -> None:
+ for attempt in range(1, attempts + 1):
+ try:
+ slack.chat_postMessage(channel=channel, thread_ts=thread_ts, text=text, blocks=blocks)
+ return
+ except SlackApiError as e:
+ error = e.response.get("error")
+ if attempt == attempts or error not in ("invalid_blocks", "ratelimited"):
+ raise
+ if error == "ratelimited":
+ headers = getattr(e.response, "headers", None) or {}
+ try:
+ retry_after = float(headers.get("Retry-After") or _IMAGE_BLOCK_POST_RETRY_INTERVAL_S)
+ except (TypeError, ValueError):
+ retry_after = _IMAGE_BLOCK_POST_RETRY_INTERVAL_S
+ wait = min(retry_after, _RATE_LIMIT_MAX_WAIT_S)
+ else:
+ wait = _IMAGE_BLOCK_POST_RETRY_INTERVAL_S
+ if deadline is not None and time.monotonic() + wait >= deadline:
+ raise
+ time.sleep(wait)
def _pending_slack_file_version(artifact: TaskArtifact) -> tuple[int, dict[str, Any]] | None:
@@ -908,9 +1381,11 @@ def _mark_slack_file_artifact_delivered(
*,
artifact: TaskArtifact,
version_number: int,
- file_id: str,
- file_response: dict[str, Any],
+ file_id: str | None,
+ file_response: dict[str, Any] | None,
) -> bool:
+ """``file_id``/``file_response`` are None for url-referenced images, which post
+ without a Slack file upload."""
with transaction.atomic():
locked = TaskArtifact.objects.for_team(artifact.team_id).select_for_update().get(pk=artifact.pk)
pending = _pending_slack_file_version(locked)
@@ -921,28 +1396,20 @@ def _mark_slack_file_artifact_delivered(
if int(version_payload.get("version") or 0) != version_number:
return False
- file_title = str(file_response.get("title") or locked.name)
- file_permalink = file_response.get("permalink")
- delivered_location = {
- **(locked.location or {}),
- "file_id": file_id,
- "delivery_status": "delivered",
- }
- delivered_version = {
- **version_payload,
- "slack_file_id": file_id,
- "slack_file_title": file_title,
- "delivery_status": "delivered",
- }
- delivered_metadata = {
- **(locked.metadata or {}),
- "slack_file_id": file_id,
- "slack_file_title": file_title,
- "delivery_status": "delivered",
- }
- if file_permalink:
- delivered_version["slack_file_permalink"] = file_permalink
- delivered_metadata["slack_file_permalink"] = file_permalink
+ delivered_location = {**(locked.location or {}), "delivery_status": "delivered"}
+ delivered_version = {**version_payload, "delivery_status": "delivered"}
+ delivered_metadata = {**(locked.metadata or {}), "delivery_status": "delivered"}
+ if file_id:
+ file_title = str((file_response or {}).get("title") or locked.name)
+ file_permalink = (file_response or {}).get("permalink")
+ delivered_location["file_id"] = file_id
+ delivered_version["slack_file_id"] = file_id
+ delivered_version["slack_file_title"] = file_title
+ delivered_metadata["slack_file_id"] = file_id
+ delivered_metadata["slack_file_title"] = file_title
+ if file_permalink:
+ delivered_version["slack_file_permalink"] = file_permalink
+ delivered_metadata["slack_file_permalink"] = file_permalink
versions = list(locked.versions or [])
versions[version_index] = delivered_version
@@ -1043,12 +1510,11 @@ def _slack_integration_for_mapping(mapping: Any):
def _upload_slack_file(
slack: Any,
*,
- channel: str,
- thread_ts: str,
+ channel: str | None,
+ thread_ts: str | None,
name: str,
content: bytes,
content_type: str,
- initial_comment: str | None = None,
) -> tuple[str, dict[str, Any]]:
upload_response = slack.api_call(
"files.getUploadURLExternal",
@@ -1067,14 +1533,11 @@ def _upload_slack_file(
)
response.raise_for_status()
- complete_payload = {
- "files": json.dumps([{"id": file_id, "title": name}]),
- "channel_id": channel,
- "thread_ts": thread_ts,
- }
- if initial_comment:
- complete_payload["initial_comment"] = initial_comment
-
+ complete_payload = {"files": json.dumps([{"id": file_id, "title": name}])}
+ if channel:
+ complete_payload["channel_id"] = channel
+ if thread_ts:
+ complete_payload["thread_ts"] = thread_ts
complete_response = slack.api_call("files.completeUploadExternal", data=complete_payload)
files = complete_response.get("files") or []
file_response = files[0] if files and isinstance(files[0], dict) else {"id": file_id, "title": name}
diff --git a/products/tasks/backend/logic/services/tests/test_living_artifacts.py b/products/tasks/backend/logic/services/tests/test_living_artifacts.py
index 1d8844f8e106..9bb33da0b336 100644
--- a/products/tasks/backend/logic/services/tests/test_living_artifacts.py
+++ b/products/tasks/backend/logic/services/tests/test_living_artifacts.py
@@ -1,10 +1,11 @@
import io
+import time
import zipfile
from typing import Any, ClassVar
from unittest.mock import MagicMock, patch
-from django.test import TestCase
+from django.test import SimpleTestCase, TestCase, override_settings
from parameterized import parameterized
@@ -13,11 +14,18 @@ from posthog.models.organization import Organization
from posthog.models.team.team import Team
from posthog.models.user import User
+from products.exports.backend.models.exported_asset import ExportedAsset
from products.slack_app.backend.models import SlackThreadTaskMapping
from products.tasks.backend.logic.services.living_artifacts import (
+ _SLACK_CODE_FENCE,
+ _SLACK_MESSAGE_BLOCK_LIMIT,
DEFAULT_DOCUMENT_CONTENT_TYPE,
ArtifactCommit,
DocumentConnectorUnavailable,
+ _chart_card_blocks,
+ _post_composed_answer_message,
+ _section_blocks,
+ _SlackImageCard,
create_living_artifact,
deliver_pending_slack_file_artifacts,
edit_living_artifact,
@@ -54,6 +62,7 @@ class FakeDocumentConnectorAdapter:
content_type: str | None = None,
content_bytes: bytes | None = None,
source_artifact: dict[str, Any] | None = None,
+ export_asset_id: int | None = None,
) -> ArtifactCommit:
document_id = (artifact.location or {}).get("document_id") if artifact is not None else artifact_id
location = {
@@ -529,6 +538,87 @@ class TestLivingArtifacts(TestCase):
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
+ def _create_scopeless_mapping(self, mock_integration_for_mapping) -> None:
+ integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T123", config={})
+ SlackThreadTaskMapping.objects.create(
+ team=self.team,
+ integration=integration,
+ slack_workspace_id="T123",
+ channel="C123",
+ thread_ts="1111.1",
+ task=self.task,
+ task_run=self.task_run,
+ mentioning_slack_user_id="U123",
+ )
+ slack_integration = MagicMock()
+ slack_integration.missing_scopes.return_value = {"files:write"}
+ mock_integration_for_mapping.return_value = slack_integration
+
+ @override_settings(SITE_URL="http://localhost:8010")
+ @patch("products.tasks.backend.logic.services.living_artifacts._canvas_file_artifacts_enabled", return_value=True)
+ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")
+ def test_slack_file_adapter_allows_chart_images_with_own_export_without_file_scope(
+ self, mock_integration_for_mapping, _mock_flag
+ ):
+ # Chart images deliver as image blocks pointing at a PostHog-hosted url — no upload,
+ # no files:write.
+ self._create_scopeless_mapping(mock_integration_for_mapping)
+ asset = ExportedAsset.objects.create(team=self.team, export_format=ExportedAsset.ExportFormat.PNG)
+
+ artifact = create_living_artifact(
+ run=self.task_run,
+ name="Signups by week.png",
+ artifact_type=TaskArtifact.ArtifactType.FILE,
+ adapter=TaskArtifact.Adapter.SLACK_FILE,
+ content_bytes=b"png-bytes",
+ content_type="image/png",
+ export_asset_id=asset.id,
+ )
+
+ self.assertEqual(artifact.adapter, TaskArtifact.Adapter.SLACK_FILE)
+ self.assertEqual(artifact.location["delivery_status"], "pending")
+ self.assertEqual(artifact.export_asset_id, asset.id)
+ # The delivery token bypasses the org's publicly-shared-resources setting and metadata
+ # is readable with only task:read, so it must never be stored — delivery mints it.
+ self.assertNotIn("image_url", artifact.metadata)
+
+ def _foreign_team_asset_id(self) -> int:
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+ return ExportedAsset.objects.create(team=other_team, export_format=ExportedAsset.ExportFormat.PNG).id
+
+ def _non_image_asset_id(self) -> int:
+ return ExportedAsset.objects.create(team=self.team, export_format=ExportedAsset.ExportFormat.CSV).id
+
+ @parameterized.expand(
+ [
+ ("no_export_asset", lambda _self: None),
+ ("unknown_export_asset", lambda _self: 987654),
+ ("export_asset_from_another_team", lambda self: self._foreign_team_asset_id()),
+ # An image block is the only thing delivery posts, so a non-image asset must not
+ # mint either — otherwise a leaked reference could pull down a CSV.
+ ("export_asset_that_is_not_an_image", lambda self: self._non_image_asset_id()),
+ ]
+ )
+ @patch("products.tasks.backend.logic.services.living_artifacts._canvas_file_artifacts_enabled", return_value=True)
+ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")
+ def test_slack_file_adapter_rejects_images_without_a_resolvable_export(
+ self, _name, asset_id_factory, mock_integration_for_mapping, _mock_flag
+ ):
+ self._create_scopeless_mapping(mock_integration_for_mapping)
+
+ with self.assertRaisesRegex(ValueError, "files:write"):
+ create_living_artifact(
+ run=self.task_run,
+ name="screenshot.png",
+ artifact_type=TaskArtifact.ArtifactType.FILE,
+ adapter=TaskArtifact.Adapter.SLACK_FILE,
+ content_bytes=b"png-bytes",
+ content_type="image/png",
+ export_asset_id=asset_id_factory(self),
+ )
+
+ self.assertFalse(TaskArtifact.objects.for_team(self.team.id).exists())
+
def _create_mapping_with_full_scopes(self) -> None:
# Scopes granted (the DEV-install shape) so these tests prove the feature flag
# gates canvas/file delivery even where the in-review scopes are available.
@@ -680,9 +770,118 @@ class TestLivingArtifacts(TestCase):
current_version=1,
)
- delivered = deliver_pending_slack_file_artifacts(self.task_run, initial_comment="done")
+ delivery = deliver_pending_slack_file_artifacts(self.task_run)
- self.assertEqual(delivered, 0)
+ self.assertFalse(delivery.answer_posted)
+ self.assertEqual(delivery.delivered_count, 0)
mock_integration_for_mapping.assert_not_called()
artifact.refresh_from_db()
self.assertEqual(artifact.versions[0]["delivery_status"], "pending")
+
+
+@override_settings(SITE_URL="http://localhost:8010")
+class TestChartCardBlockBuilders(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("url_within_limit", "http://localhost:8010/project/1/insights/abc", ["section", "image", "actions"]),
+ (
+ "url_over_slack_button_cap",
+ "http://localhost:8010/project/1/insights/new#q=" + "x" * 3000,
+ ["section", "image"],
+ ),
+ # Artifact metadata is caller-writable, so an off-origin url must not become a button
+ # the PostHog bot appears to vouch for.
+ ("url_off_posthog_origin", "https://phishing.example/project/1/insights/abc", ["section", "image"]),
+ ]
+ )
+ def test_button_only_added_for_trusted_url_within_slack_cap(self, _name, url, expected_block_types):
+ artifact = TaskArtifact(name="Chart", metadata={"posthog_url": url})
+ blocks = _chart_card_blocks(_SlackImageCard(artifact, {}, file_id="F123"))
+ self.assertEqual([b["type"] for b in blocks], expected_block_types)
+
+ def test_oversized_sections_split_below_block_char_cap(self):
+ blocks = _section_blocks(["a" * 6500, "short"])
+ self.assertEqual([len(b["text"]["text"]) for b in blocks], [3000, 3000, 500, 5])
+ self.assertEqual(blocks[-1]["text"]["text"], "short")
+
+ def test_oversized_sections_split_at_whitespace_so_mrkdwn_entities_survive(self):
+ # A hard character slice can cut a converted entity like `<url|text>` in half;
+ # the split must land on whitespace when any is available in the window.
+ words = "word " * 1300 # 6500 chars of 5-char words
+ blocks = _section_blocks([words.strip()])
+ self.assertGreater(len(blocks), 1)
+ for block in blocks:
+ text = block["text"]["text"]
+ self.assertLessEqual(len(text), 3000)
+ self.assertEqual(set(text.split(" ")), {"word"})
+
+ def test_oversized_fenced_section_is_closed_and_reopened_around_the_split(self):
+ # Tables convert to fenced blocks before this re-split, so a cut inside one would
+ # leave an unclosed fence in one block and a stray closer in the next.
+ table = "| cell | cell |\n" * 250
+ blocks = _section_blocks([f"{_SLACK_CODE_FENCE}\n{table}{_SLACK_CODE_FENCE}"])
+ self.assertGreater(len(blocks), 1)
+ for block in blocks:
+ text = block["text"]["text"]
+ self.assertLessEqual(len(text), 3000)
+ self.assertEqual(text.count(_SLACK_CODE_FENCE) % 2, 0)
+ self.assertTrue(text.startswith(_SLACK_CODE_FENCE))
+ self.assertTrue(text.endswith(_SLACK_CODE_FENCE))
+
+ def test_fenced_whitespace_free_content_terminates_and_stays_balanced(self):
+ # After a fence is closed and reopened, the only whitespace in the window can be
+ # the reopen prefix's own newline — cutting there consumes nothing of the content.
+ section = f"{_SLACK_CODE_FENCE}\n{'x' * 8000}\n{_SLACK_CODE_FENCE}"
+ blocks = _section_blocks([section])
+ self.assertGreater(len(blocks), 1)
+ for block in blocks:
+ text = block["text"]["text"]
+ self.assertLessEqual(len(text), 3000)
+ self.assertEqual(text.count(_SLACK_CODE_FENCE) % 2, 0)
+ self.assertIn(
+ "x" * 8000,
+ "".join(b["text"]["text"] for b in blocks)
+ .replace(f"\n{_SLACK_CODE_FENCE}", "")
+ .replace(f"{_SLACK_CODE_FENCE}\n", ""),
+ )
+
+ def test_card_without_a_minted_url_references_the_uploaded_file(self):
+ card = _SlackImageCard(TaskArtifact(name="Chart"), {}, file_id="F123")
+ blocks = _chart_card_blocks(card)
+ self.assertEqual(blocks[1], {"type": "image", "slack_file": {"id": "F123"}, "alt_text": "Chart"})
+
+ def test_card_with_a_minted_url_references_it_directly(self):
+ image_url = "http://localhost:8010/exporter/export-1.png?token=abc"
+ card = _SlackImageCard(TaskArtifact(name="Chart"), {}, image_url=image_url)
+ blocks = _chart_card_blocks(card)
+ self.assertEqual(blocks[1], {"type": "image", "image_url": image_url, "alt_text": "Chart"})
+
+ @parameterized.expand(
+ [
+ ("composed", 1),
+ # Two blocks per card, so this many cards overflows the cap and takes the per-card path.
+ ("per_card", _SLACK_MESSAGE_BLOCK_LIMIT // 2 + 1),
+ ]
+ )
+ def test_mention_shaped_artifact_name_is_escaped_in_message_text(self, _name, card_count):
+ # Artifact names are task-controlled and Slack parses a message's top-level text as
+ # mrkdwn, so an unescaped name could notify a channel as the PostHog bot.
+ slack = MagicMock()
+ slack.chat_postMessage.return_value = {"ok": True, "ts": "1111.2"}
+ cards = [
+ _SlackImageCard(TaskArtifact(name="<!channel> spike.png"), {}, file_id=f"F{index}")
+ for index in range(card_count)
+ ]
+
+ _post_composed_answer_message(
+ slack,
+ mapping=MagicMock(channel="C123", thread_ts="1111.1"),
+ image_cards=cards,
+ answer_sections=[],
+ mark_delivered=lambda card: None,
+ deadline=time.monotonic() + 30,
+ )
+
+ self.assertEqual(slack.chat_postMessage.call_count, 1 if card_count == 1 else card_count)
+ for call in slack.chat_postMessage.call_args_list:
+ self.assertEqual(call.kwargs["text"], "&lt;!channel&gt; spike")
diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.py
index fa9494ab9e4e..b192016d2031 100644
--- a/products/tasks/backend/temporal/slack_relay/activities.py
+++ b/products/tasks/backend/temporal/slack_relay/activities.py
@@ -11,6 +11,7 @@ from posthog.temporal.common.utils import close_db_connections
from products.tasks.backend.logic.services.living_artifacts import (
deliver_pending_slack_file_artifacts,
has_pending_slack_file_artifacts,
+ has_pending_slack_image_artifacts,
)
logger = get_logger(__name__)
@@ -239,6 +240,10 @@ def _strip_inline_markdown(cell: str) -> str:
# splitting at 3500 leaves comfortable headroom for the mention prefix and code-fence overhead.
SLACK_MESSAGE_TEXT_LIMIT = 3500
+# Section blocks in a composed answer+charts message cap at 3000 characters — tighter
+# than plain message text; headroom for the mention prefix.
+SLACK_SECTION_TEXT_LIMIT = 2900
+
_FENCED_CODE_RE = re.compile(r"```([^\n]*)\n([\s\S]*?)\n```")
@@ -403,11 +408,17 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
origin_product=mapping.task.origin_product,
)
+ # Pending chart images compose into a single Slack message together with the answer
+ # text (section blocks cap at 3000 chars, tighter than plain messages), so pick the
+ # chunk limit before splitting.
+ compose_with_charts = has_pending_slack_files and has_pending_slack_image_artifacts(task_run)
+ chunk_limit = SLACK_SECTION_TEXT_LIMIT if compose_with_charts else SLACK_MESSAGE_TEXT_LIMIT
+
# Split the raw markdown first, then convert each chunk independently. Converting
# per-chunk means an inline span broken by a hard char split (e.g. ``**bold**``
# halved) stays literal in the output instead of leaving dangling Slack-mrkdwn
# markers that would garble the rendering of surrounding text.
- chunks = [_markdown_to_slack_mrkdwn(chunk) for chunk in _split_markdown_for_slack(text)]
+ chunks = [_markdown_to_slack_mrkdwn(chunk) for chunk in _split_markdown_for_slack(text, limit=chunk_limit)]
context = SlackThreadContext(
integration_id=mapping.integration_id,
@@ -434,25 +445,26 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
if input.delete_progress:
handler.delete_progress()
- delivered_file_count = 0
- chunks_to_post = chunks
- if has_pending_slack_files and chunks:
- delivered_file_count = deliver_pending_slack_file_artifacts(
- task_run,
- initial_comment=f"{mention_prefix}{chunks[0]}",
- )
- if delivered_file_count:
- chunks_to_post = chunks[1:]
-
- for index, chunk in enumerate(chunks_to_post):
- prefix = mention_prefix if delivered_file_count == 0 and index == 0 else ""
- # This relay carries one agent answer, split only to fit Slack's length cap, so
- # the last chunk is where the turn ends and the footer belongs.
- handler.post_thread_message(f"{prefix}{chunk}", with_footer=index == len(chunks_to_post) - 1)
- if delivered_file_count and not chunks_to_post:
- # A short answer went out whole as the file's initial comment, which takes no
- # blocks, so the footer follows it rather than being dropped.
- handler.post_footer()
+ answer_posted = False
+ if compose_with_charts:
+ sections = list(chunks)
+ if sections:
+ sections[0] = f"{mention_prefix}{sections[0]}"
+ answer_posted = deliver_pending_slack_file_artifacts(task_run, answer_sections=sections).answer_posted
+ if answer_posted:
+ # The answer went out inside the composed message, whose blocks are the text
+ # sections and the chart cards, so the footer follows it as its own message.
+ handler.post_footer()
+
+ if not answer_posted:
+ for index, chunk in enumerate(chunks):
+ prefix = mention_prefix if index == 0 else ""
+ # This relay carries one agent answer, split only to fit Slack's length cap, so
+ # the last chunk is where the turn ends and the footer belongs.
+ handler.post_thread_message(f"{prefix}{chunk}", with_footer=index == len(chunks) - 1)
+ if has_pending_slack_files and not compose_with_charts:
+ deliver_pending_slack_file_artifacts(task_run)
+
if input.reaction_emoji is not None:
handler.update_reaction(input.reaction_emoji)
diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
index 02fc4f531c12..9d78dbe9db81 100644
--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
@@ -1,11 +1,13 @@
+from datetime import timedelta
from typing import ClassVar
import unittest
from unittest.mock import patch
-from django.test import TestCase
+from django.test import TestCase, override_settings
from parameterized import parameterized
+from slack_sdk.errors import SlackApiError
from posthog.models.integration import Integration
from posthog.models.organization import Organization
@@ -13,6 +15,7 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from products.slack_app.backend.models import SlackThreadTaskMapping
+from products.tasks.backend.logic.services.living_artifacts import SlackFileDeliveryResult
from products.tasks.backend.models import Task, TaskArtifact, TaskRun
from products.tasks.backend.temporal.slack_relay.activities import (
SLACK_MESSAGE_TEXT_LIMIT,
@@ -244,35 +247,16 @@ class TestRelaySlackMessage(TestCase):
assert "tasks/artifacts/report.pdf" not in posted
assert "no file was attached to Slack for this run" in posted
- @patch(
- "products.tasks.backend.logic.services.living_artifacts._living_artifacts_enabled_for_mapping",
- return_value=True,
- )
- @patch("products.tasks.backend.logic.services.living_artifacts._canvas_file_artifacts_enabled", return_value=True)
- @patch("products.tasks.backend.logic.services.living_artifacts.requests.post")
- @patch("products.tasks.backend.logic.services.living_artifacts.object_storage.read_bytes")
- @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")
- @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.update_reaction")
- @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
- @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")
- def test_pending_slack_file_upload_uses_final_message(
- self,
- mock_delete_progress,
- mock_post,
- _mock_update,
- mock_integration_for_mapping,
- mock_read_bytes,
- mock_requests_post,
- _mock_canvas_file_flag,
- _mock_living_artifacts_flag,
- ):
- storage_path = f"tasks/artifacts/team_{self.team.id}/task_{self.task.id}/run_{self.task_run.id}/report.v1.xlsx"
+ def _create_pending_slack_file_artifact(
+ self, *, name: str, filename: str, content_type: str, metadata: dict, export_asset_id: int | None = None
+ ) -> tuple[TaskArtifact, str]:
+ storage_path = f"tasks/artifacts/team_{self.team.id}/task_{self.task.id}/run_{self.task_run.id}/{filename}"
location = {
"kind": "slack_file",
"integration_id": self.integration.id,
"channel": "C123",
"thread_ts": "1111.1",
- "content_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ "content_type": content_type,
"storage_path": storage_path,
"delivery_status": "pending",
}
@@ -281,34 +265,70 @@ class TestRelaySlackMessage(TestCase):
task=self.task,
task_run=self.task_run,
created_by=self.user,
- name="report.xlsx",
- artifact_type=TaskArtifact.ArtifactType.SPREADSHEET,
+ name=name,
+ artifact_type=TaskArtifact.ArtifactType.FILE,
adapter=TaskArtifact.Adapter.SLACK_FILE,
status=TaskArtifact.Status.ACTIVE,
location=location,
- metadata={"delivery_status": "pending"},
+ metadata={"delivery_status": "pending", **metadata},
+ export_asset_id=export_asset_id,
versions=[
{
"version": 1,
"run_id": str(self.task_run.id),
"adapter": TaskArtifact.Adapter.SLACK_FILE,
"location": location,
- "content_type": location["content_type"],
+ "content_type": content_type,
"size": 14,
"delivery_status": "pending",
}
],
current_version=1,
)
+ return artifact, storage_path
+
+ @staticmethod
+ def _mock_slack_upload(mock_integration_for_mapping, *, file_id: str = "F123", title: str = "report.xlsx"):
slack = unittest.mock.MagicMock()
slack.api_call.side_effect = [
- {"upload_url": "https://files.slack.test/upload", "file_id": "F123"},
- {"files": [{"id": "F123", "title": "report.xlsx", "permalink": "https://slack.test/files/F123"}]},
+ {"upload_url": "https://files.slack.test/upload", "file_id": file_id},
+ {"files": [{"id": file_id, "title": title, "permalink": f"https://slack.test/files/{file_id}"}]},
]
slack_integration = unittest.mock.MagicMock()
slack_integration.client = slack
slack_integration.missing_scopes.return_value = set()
mock_integration_for_mapping.return_value = slack_integration
+ return slack
+
+ @patch(
+ "products.tasks.backend.logic.services.living_artifacts._living_artifacts_enabled_for_mapping",
+ return_value=True,
+ )
+ @patch("products.tasks.backend.logic.services.living_artifacts._canvas_file_artifacts_enabled", return_value=True)
+ @patch("products.tasks.backend.logic.services.living_artifacts.requests.post")
+ @patch("products.tasks.backend.logic.services.living_artifacts.object_storage.read_bytes")
+ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.update_reaction")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")
+ def test_pending_slack_file_upload_posts_text_then_file(
+ self,
+ mock_delete_progress,
+ mock_post,
+ _mock_update,
+ mock_integration_for_mapping,
+ mock_read_bytes,
+ mock_requests_post,
+ _mock_canvas_file_flag,
+ _mock_living_artifacts_flag,
+ ):
+ artifact, storage_path = self._create_pending_slack_file_artifact(
+ name="report.xlsx",
+ filename="report.v1.xlsx",
+ content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ metadata={},
+ )
+ slack = self._mock_slack_upload(mock_integration_for_mapping)
mock_read_bytes.return_value = b"workbook bytes"
relay_slack_message(
@@ -320,14 +340,14 @@ class TestRelaySlackMessage(TestCase):
)
mock_delete_progress.assert_called_once()
- mock_post.assert_not_called()
+ mock_post.assert_called_once()
+ self.assertIn("<@U123> Done. report.xlsx is attached.", mock_post.call_args.args[0])
mock_read_bytes.assert_called_once_with(storage_path, missing_ok=True)
self.assertEqual(mock_requests_post.call_args.kwargs["data"], b"workbook bytes")
complete_payload = slack.api_call.call_args_list[1].kwargs["data"]
self.assertEqual(complete_payload["channel_id"], "C123")
self.assertEqual(complete_payload["thread_ts"], "1111.1")
- self.assertIn("<@U123> Done. report.xlsx is attached.", complete_payload["initial_comment"])
- self.assertNotIn("no file was attached to Slack", complete_payload["initial_comment"])
+ self.assertNotIn("initial_comment", complete_payload)
artifact.refresh_from_db()
self.assertEqual(artifact.location["delivery_status"], "delivered")
@@ -336,6 +356,208 @@ class TestRelaySlackMessage(TestCase):
self.assertEqual(artifact.versions[0]["delivery_status"], "delivered")
self.assertEqual(artifact.versions[0]["slack_file_id"], "F123")
+ @patch(
+ "products.tasks.backend.logic.services.living_artifacts._living_artifacts_enabled_for_mapping",
+ return_value=True,
+ )
+ @patch("products.tasks.backend.logic.services.living_artifacts._canvas_file_artifacts_enabled", return_value=True)
+ @patch("products.tasks.backend.logic.services.living_artifacts.requests.post")
+ @patch("products.tasks.backend.logic.services.living_artifacts.object_storage.read_bytes")
+ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.update_reaction")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")
+ @patch(
+ "products.tasks.backend.logic.services.living_artifacts.get_delivery_image_url",
+ return_value="http://localhost:8010/exporter/export-chart.png?token=abc",
+ )
+ @override_settings(SITE_URL="http://localhost:8010")
+ def test_chart_composes_single_message_with_answer_image_and_button(
+ self,
+ mock_delivery_url,
+ _mock_delete_progress,
+ mock_post,
+ _mock_update,
+ mock_integration_for_mapping,
+ mock_read_bytes,
+ _mock_requests_post,
+ _mock_flag,
+ _mock_living_artifacts_flag,
+ ):
+ # posthog_url must be SITE_URL-origin, or it is treated as untrusted caller metadata
+ # and no button is added.
+ chart_url = "http://localhost:8010/project/1/insights/abc123"
+ artifact, _storage_path = self._create_pending_slack_file_artifact(
+ name="Signups by week",
+ filename="signups.v1.png",
+ content_type="image/png",
+ metadata={"posthog_url": chart_url},
+ export_asset_id=321,
+ )
+ slack = unittest.mock.MagicMock()
+ slack_integration = unittest.mock.MagicMock()
+ slack_integration.client = slack
+ # No files:write — url-referenced charts must deliver without any file scope.
+ slack_integration.missing_scopes.return_value = {"files:write"}
+ mock_integration_for_mapping.return_value = slack_integration
+ # First post rejected transiently to exercise the retry.
+ slack.chat_postMessage.side_effect = [
+ SlackApiError("invalid_blocks", {"ok": False, "error": "invalid_blocks"}),
+ {"ok": True, "ts": "1111.2"},
+ ]
+
+ with patch("products.tasks.backend.logic.services.living_artifacts.time.sleep") as mock_sleep:
+ relay_slack_message(
+ RelaySlackMessageInput(
+ run_id=str(self.task_run.id),
+ relay_id="relay-with-chart",
+ text="Here's the trend.",
+ )
+ )
+ mock_sleep.assert_called_once()
+
+ # url-referenced images involve no upload at all: no files.* API calls, no
+ # object storage read — Slack fetches the PNG from the url in the block.
+ slack.api_call.assert_not_called()
+ mock_read_bytes.assert_not_called()
+ self.assertEqual(slack.chat_postMessage.call_count, 2)
+ composed_call = slack.chat_postMessage.call_args
+ self.assertEqual(composed_call.kwargs["channel"], "C123")
+ self.assertEqual(composed_call.kwargs["thread_ts"], "1111.1")
+ answer_block, header_block, image_block, actions_block = composed_call.kwargs["blocks"]
+ self.assertEqual(answer_block["text"]["text"], "<@U123> Here's the trend.")
+ self.assertEqual(header_block["text"]["text"], "*Signups by week*")
+ self.assertEqual(
+ image_block,
+ {
+ "type": "image",
+ "image_url": "http://localhost:8010/exporter/export-chart.png?token=abc",
+ "alt_text": "Signups by week",
+ },
+ )
+ # Minted from the stored reference at post time, scoped to this run's team.
+ self.assertEqual(
+ mock_delivery_url.call_args.kwargs,
+ {"team_id": self.team.id, "asset_id": 321, "expiry_delta": timedelta(days=30)},
+ )
+ button = actions_block["elements"][0]
+ self.assertEqual(button["url"], chart_url)
+ self.assertEqual(button["text"]["text"], "Open in PostHog")
+
+ # The composed message carries the answer text — nothing posted via the handler.
+ mock_post.assert_not_called()
+
+ artifact.refresh_from_db()
+ self.assertEqual(artifact.location["delivery_status"], "delivered")
+ self.assertNotIn("slack_file_id", artifact.versions[0])
+ self.assertEqual(artifact.versions[0]["delivery_status"], "delivered")
+
+ @patch(
+ "products.tasks.backend.logic.services.living_artifacts._living_artifacts_enabled_for_mapping",
+ return_value=True,
+ )
+ @patch("products.tasks.backend.logic.services.living_artifacts._canvas_file_artifacts_enabled", return_value=True)
+ @patch("products.tasks.backend.logic.services.living_artifacts.requests.post")
+ @patch("products.tasks.backend.logic.services.living_artifacts.object_storage.read_bytes")
+ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.update_reaction")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")
+ @override_settings(SITE_URL="http://localhost:8010")
+ def test_chart_without_image_url_uploads_privately_then_references_the_file(
+ self,
+ _mock_delete_progress,
+ mock_post,
+ _mock_update,
+ mock_integration_for_mapping,
+ mock_read_bytes,
+ _mock_requests_post,
+ _mock_flag,
+ _mock_living_artifacts_flag,
+ ):
+ artifact, _storage_path = self._create_pending_slack_file_artifact(
+ name="Signups by week",
+ filename="signups.v1.png",
+ content_type="image/png",
+ metadata={"posthog_url": "http://localhost:8010/project/1/insights/abc123"},
+ )
+ slack = self._mock_slack_upload(mock_integration_for_mapping, title="Signups by week")
+ slack.chat_postMessage.return_value = {"ok": True, "ts": "1111.2"}
+ mock_read_bytes.return_value = b"png bytes"
+
+ relay_slack_message(
+ RelaySlackMessageInput(
+ run_id=str(self.task_run.id),
+ relay_id="relay-chart-upload",
+ text="Here's the trend.",
+ )
+ )
+
+ # Sharing the upload to the channel would make Slack materialize a second copy
+ # alongside the image block in the composed message.
+ complete_payload = slack.api_call.call_args_list[1].kwargs["data"]
+ self.assertNotIn("channel_id", complete_payload)
+ self.assertNotIn("thread_ts", complete_payload)
+
+ slack.chat_postMessage.assert_called_once()
+ _answer_block, _header_block, image_block, _actions_block = slack.chat_postMessage.call_args.kwargs["blocks"]
+ self.assertEqual(image_block, {"type": "image", "slack_file": {"id": "F123"}, "alt_text": "Signups by week"})
+ mock_post.assert_not_called()
+
+ artifact.refresh_from_db()
+ self.assertEqual(artifact.location["delivery_status"], "delivered")
+ self.assertEqual(artifact.versions[0]["delivery_status"], "delivered")
+ self.assertEqual(artifact.versions[0]["slack_file_id"], "F123")
+
+ @patch(
+ "products.tasks.backend.logic.services.living_artifacts._living_artifacts_enabled_for_mapping",
+ return_value=True,
+ )
+ @patch("products.tasks.backend.logic.services.living_artifacts._canvas_file_artifacts_enabled", return_value=True)
+ @patch("products.tasks.backend.logic.services.living_artifacts.requests.post")
+ @patch("products.tasks.backend.logic.services.living_artifacts.object_storage.read_bytes")
+ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.update_reaction")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")
+ def test_failed_chart_post_leaves_artifact_pending(
+ self,
+ _mock_delete_progress,
+ mock_post,
+ _mock_update,
+ mock_integration_for_mapping,
+ mock_read_bytes,
+ _mock_requests_post,
+ _mock_flag,
+ _mock_living_artifacts_flag,
+ ):
+ artifact, _storage_path = self._create_pending_slack_file_artifact(
+ name="Signups by week",
+ filename="signups.v1.png",
+ content_type="image/png",
+ metadata={"posthog_url": "https://us.posthog.com/project/1/insights/abc123"},
+ )
+ slack = self._mock_slack_upload(mock_integration_for_mapping, title="Signups by week")
+ # A non-retryable post failure must leave the artifact pending for the next
+ # relay — marking it delivered would lose the chart (it was never shared).
+ slack.chat_postMessage.side_effect = SlackApiError(
+ "channel_not_found", {"ok": False, "error": "channel_not_found"}
+ )
+ mock_read_bytes.return_value = b"png bytes"
+
+ relay_slack_message(
+ RelaySlackMessageInput(
+ run_id=str(self.task_run.id),
+ relay_id="relay-chart-post-fails",
+ text="Here's the trend.",
+ )
+ )
+
+ artifact.refresh_from_db()
+ self.assertEqual(artifact.versions[0]["delivery_status"], "pending")
+ self.assertEqual(artifact.location["delivery_status"], "pending")
+ mock_post.assert_called_once_with("<@U123> Here's the trend.", with_footer=True)
+
class TestMarkdownToSlackMrkdwn(unittest.TestCase):
@parameterized.expand(
@@ -728,25 +950,28 @@ class TestRelaySlackMessageChunking(TestCase):
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_footer")
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")
+ @patch("products.tasks.backend.temporal.slack_relay.activities.has_pending_slack_image_artifacts")
@patch("products.tasks.backend.temporal.slack_relay.activities.deliver_pending_slack_file_artifacts")
@patch("products.tasks.backend.temporal.slack_relay.activities.has_pending_slack_file_artifacts")
- def test_answer_consumed_by_a_file_upload_still_gets_its_footer(
+ def test_answer_composed_with_charts_still_gets_its_footer(
self,
mock_has_files,
mock_deliver,
+ mock_has_images,
mock_delete_progress,
mock_post,
mock_post_footer,
):
- # A short answer rides out whole as the file's initial comment, leaving no message
- # to close — without this the reply would carry no provenance at all.
+ # The answer rides out inside the composed chart message, leaving no message of its
+ # own to close — without this the reply would carry no provenance at all.
mock_has_files.return_value = True
- mock_deliver.return_value = 1
+ mock_has_images.return_value = True
+ mock_deliver.return_value = SlackFileDeliveryResult(answer_posted=True, delivered_count=1)
relay_slack_message(
RelaySlackMessageInput(
run_id=str(self.task_run.id),
- relay_id="relay-file-only",
+ relay_id="relay-composed-charts",
text="Here you go.",
user_message_ts="1234.5",
)
@@ -754,3 +979,36 @@ class TestRelaySlackMessageChunking(TestCase):
mock_post.assert_not_called()
mock_post_footer.assert_called_once()
+
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_footer")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")
+ @patch("products.tasks.backend.temporal.slack_relay.activities.has_pending_slack_image_artifacts")
+ @patch("products.tasks.backend.temporal.slack_relay.activities.deliver_pending_slack_file_artifacts")
+ @patch("products.tasks.backend.temporal.slack_relay.activities.has_pending_slack_file_artifacts")
+ def test_answer_falls_back_to_plain_messages_when_compose_does_not_post(
+ self,
+ mock_has_files,
+ mock_deliver,
+ mock_has_images,
+ mock_delete_progress,
+ mock_post,
+ mock_post_footer,
+ ):
+ # Compose was attempted but the message never landed, so the answer is posted the
+ # ordinary way and closes itself — a second standalone footer would duplicate it.
+ mock_has_files.return_value = True
+ mock_has_images.return_value = True
+ mock_deliver.return_value = SlackFileDeliveryResult(answer_posted=False)
+
+ relay_slack_message(
+ RelaySlackMessageInput(
+ run_id=str(self.task_run.id),
+ relay_id="relay-compose-failed",
+ text="Here you go.",
+ user_message_ts="1234.5",
+ )
+ )
+
+ mock_post.assert_called_once_with("<@U456> Here you go.", with_footer=True)
+ mock_post_footer.assert_not_called()