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): unfurl task artifact download links (#118349)

Vojta Bartoš29c62205d249
diff --git a/products/exports/backend/facade/api.py b/products/exports/backend/facade/api.py
index 7af01c3110c4..4687d4e80520 100644
--- a/products/exports/backend/facade/api.py
+++ b/products/exports/backend/facade/api.py
@@ -1,14 +1,17 @@
"""Public Python interface for creating and retrieving one-off exports."""
+import io
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
+from django.utils.timezone import now
import structlog
from asgiref.sync import async_to_sync
+from PIL import Image, UnidentifiedImageError
from temporalio.common import WorkflowIDReusePolicy
from posthog.hogql.constants import LimitContext
@@ -24,6 +27,7 @@ from products.exports.backend.models.exported_asset import (
DATASET_EXPORT_KIND as DATASET_EXPORT_KIND,
ExportedAsset,
get_content_response,
+ save_content as _save_content,
save_content_from_file as _save_content_from_file,
)
from products.exports.backend.models.subscription import Subscription
@@ -40,6 +44,8 @@ JSONL_EXPORT_FORMAT = ExportedAsset.ExportFormat.JSONL
# Caps the whole workflow including retries; callers block on this, so it must stay
# well under the web tier's request timeout.
RENDER_TIMEOUT = timedelta(seconds=90)
+_MAX_IMAGE_PIXELS = 25_000_000
+_PNG_MODES = frozenset({"1", "L", "LA", "I", "I;16", "P", "RGB", "RGBA"})
EXPORT_WORKFLOW_TIMEOUT = timedelta(minutes=35)
@@ -209,6 +215,47 @@ def get_delivery_image_url(
return asset.get_subscription_delivery_content_url(expiry_delta=expiry_delta)
+def create_png_delivery_url(
+ *, team_id: int, created_by_id: int, content: bytes, filename: str, url_ttl: timedelta, asset_ttl: timedelta
+) -> str | None:
+ """Store image bytes as a PNG export and mint a delivery url for it. None when the bytes are not an image.
+
+ The url opens without a login, so the caller must check that the user may see the image.
+ """
+ png = _as_png(content)
+ if png is None:
+ return None
+ asset = ExportedAsset.objects.create(
+ team_id=team_id,
+ created_by_id=created_by_id,
+ export_format=ExportedAsset.ExportFormat.PNG,
+ export_context={"filename": filename},
+ expires_after=now() + asset_ttl,
+ )
+ _save_content(asset, png)
+ return asset.get_subscription_delivery_content_url(expiry_delta=url_ttl)
+
+
+def _as_png(content: bytes) -> bytes | None:
+ try:
+ with Image.open(io.BytesIO(content)) as image:
+ # A small compressed file can decode to a very large bitmap.
+ if image.width * image.height > _MAX_IMAGE_PIXELS:
+ return None
+ if image.format == "PNG":
+ image.verify()
+ return content
+ image.load()
+ png_ready: Image.Image = image
+ if image.mode not in _PNG_MODES:
+ png_ready = image.convert("RGBA" if "A" in image.getbands() else "RGB")
+ output = io.BytesIO()
+ png_ready.save(output, format="PNG")
+ return output.getvalue()
+ except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError):
+ return None
+
+
def _create_png_export_asset(
*,
team: Team,
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 62e1f556e136..c645f39a9f1d 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -4543,11 +4543,13 @@ def _link_shared_url_region(event: dict[str, Any]) -> str | None:
def _link_shared_url_team_ids(event: dict[str, Any]) -> set[int]:
- """Team ids named by ``/project/:id`` in the event's unfurlable links."""
+ """Team ids named by ``/project/:id`` or ``/api/projects/:id`` in the event's unfurlable links."""
team_ids: set[int] = set()
for url in _link_shared_resource_urls(event):
parts = [part for part in urlparse(url).path.split("/") if part]
- if len(parts) >= 2 and parts[0] == "project":
+ if parts[:2] == ["api", "projects"]:
+ parts = parts[1:]
+ if len(parts) >= 2 and parts[0] in ("project", "projects"):
try:
team_ids.add(int(parts[1]))
except ValueError:
diff --git a/products/slack_app/backend/logic/link_unfurl_charts.py b/products/slack_app/backend/logic/link_unfurl_charts.py
index 9f4d7cb6c67f..247390e525eb 100644
--- a/products/slack_app/backend/logic/link_unfurl_charts.py
+++ b/products/slack_app/backend/logic/link_unfurl_charts.py
@@ -9,6 +9,7 @@ from __future__ import annotations
from datetime import timedelta
from typing import TYPE_CHECKING, Any
+from urllib.parse import urlparse
from django.conf import settings
@@ -39,6 +40,9 @@ _MAX_ALT_TEXT_CHARS = 2000
_DEBUG_PLACEHOLDER_IMAGE_URL = (
"https://raw.githubusercontent.com/PostHog/posthog/master/frontend/public/icons/android-chrome-512x512.png"
)
+# Slack fetches image_url again after the unfurl is posted, so the token must outlive the post.
+UNFURL_IMAGE_URL_TTL = timedelta(days=30)
+UNFURL_IMAGE_ASSET_TTL = timedelta(days=31)
# 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"}
@@ -58,7 +62,12 @@ def chat_unfurl_kwargs(
return kwargs
-def _has_project_access(user: User, team: Team) -> bool:
+def slack_fetchable_image_url(url: str) -> str:
+ local = settings.DEBUG and urlparse(url).hostname in ("localhost", "127.0.0.1")
+ return _DEBUG_PLACEHOLDER_IMAGE_URL if local else url
+
+
+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 user.is_active and UserPermissions(user=user, team=team).current_team.effective_membership_level is not None
@@ -74,7 +83,7 @@ class UnfurlChartTargets:
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):
+ if not has_project_access(user, team):
return UnfurlChartTargets(team=team, user=user, charts=[])
# Two links to the same chart in one message share one render.
unique: dict[str, SlackUnfurlChartRequest] = {}
@@ -131,7 +140,7 @@ def post_unfurl_charts(post: SlackAppUnfurlChartsPostInput, *, image_urls_by_key
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):
+ 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.
@@ -144,7 +153,7 @@ def post_unfurl_charts(post: SlackAppUnfurlChartsPostInput, *, image_urls_by_key
if key not in allowed:
allowed[key] = _can_view_chart(team, user, chart, access)
if allowed[key]:
- image_urls[chart.url] = _DEBUG_PLACEHOLDER_IMAGE_URL if settings.DEBUG else image_urls_by_key[key]
+ image_urls[chart.url] = slack_fetchable_image_url(image_urls_by_key[key])
adhoc_urls = {chart.url for chart in request.charts if chart.query is not None}
if image_urls:
diff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.py
index 335c0bd752ac..a4a5ccce502d 100644
--- a/products/slack_app/backend/slack_link_unfurl.py
+++ b/products/slack_app/backend/slack_link_unfurl.py
@@ -46,6 +46,7 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.error_tracking.backend.facade import api as error_tracking_facade
from products.experiments.backend.models.experiment import Experiment
+from products.exports.backend.facade import api as exports_facade
from products.feature_flags.backend.facade.config import ConfigFormatError
from products.feature_flags.backend.facade.filters import condition_rollout_percentage
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -54,7 +55,14 @@ from products.product_analytics.backend.facade.models import Insight
from products.signals.backend.models import SignalReport
from products.signals.backend.report_access import may_read_reports
from products.slack_app.backend.analytics import capture_slack_event
-from products.slack_app.backend.logic.link_unfurl_charts import chat_unfurl_kwargs
+from products.slack_app.backend.logic.link_unfurl_charts import (
+ UNFURL_IMAGE_ASSET_TTL,
+ UNFURL_IMAGE_URL_TTL,
+ chat_unfurl_kwargs,
+ has_project_access,
+ slack_fetchable_image_url,
+ with_chart_images,
+)
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.slack_app.backend.temporal.slack_app_unfurl_charts import (
@@ -81,6 +89,13 @@ _CHART_WIDTH = 20
_CHART_LABEL_CHARS = 16
ADHOC_INSIGHT_KIND = "adhoc_insight"
+TASK_ARTIFACT_KIND = "task_artifact"
+
+_SLACK_IMAGE_CONTENT_TYPES = frozenset({"image/png", "image/jpeg", "image/gif"})
+_MAX_ARTIFACT_IMAGE_BYTES = 5 * 1024 * 1024
+_TASK_ARTIFACT_PATH = re.compile(
+ r"/api/projects/(?P<project>[^/]+)/tasks/(?P<task>[^/]+)/runs/(?P<run>[^/]+)/artifacts/(?P<artifact>[^/]+)/"
+)
_UNFURL_TEMPLATES: dict[str, tuple[str, ...]] = {
"insight": (*OBJECT_URL_TEMPLATES["insight"], "/bi/{id}"),
@@ -102,6 +117,7 @@ _KIND_EMOJI: dict[str, str] = {
"dashboard": "📊",
"ticket": "🎫",
"task": "🤖",
+ TASK_ARTIFACT_KIND: "📎",
"canvas": "🎨",
"notebook": "📓",
"flag": "🚩",
@@ -215,6 +231,9 @@ def parse_posthog_resource_link(url: str) -> ObjectRef | None:
return None
if _is_adhoc_insight_url(url):
return ObjectRef(kind=ADHOC_INSIGHT_KIND, id="new")
+ artifact_ref = _task_artifact_ref(url)
+ if artifact_ref is not None:
+ return ObjectRef(kind=TASK_ARTIFACT_KIND, id=artifact_ref.artifact_id or artifact_ref.name or "")
return object_ref_for_url(url, _UNFURL_TEMPLATES)
@@ -339,6 +358,45 @@ class _CardButton:
url: str
+@frozen
+class _TaskArtifactRef:
+ project_id: int | None
+ task_id: UUID
+ run_id: UUID | None = None
+ artifact_id: str | None = None
+ name: str | None = None
+
+
+def _task_artifact_ref(url: str) -> _TaskArtifactRef | None:
+ """A task artifact named by its download link, or by its place in the task's Artifacts tab."""
+ parsed = urlparse(url)
+ match = _TASK_ARTIFACT_PATH.search(parsed.path)
+ if match:
+ task_id, run_id = _uuid(match["task"]), _uuid(match["run"])
+ if task_id is None or run_id is None:
+ return None
+ project = match["project"]
+ return _TaskArtifactRef(
+ project_id=int(project) if project.isdigit() else None,
+ task_id=task_id,
+ run_id=run_id,
+ artifact_id=match["artifact"],
+ )
+ segments = [segment for segment in parsed.path.split("/") if segment]
+ params = parse_qs(parsed.query)
+ if (segments[2:] if segments[:1] == ["project"] else segments) != ["ai"] or "artifact" not in params:
+ return None
+ task_id = _uuid(params.get("task", [""])[0])
+ if task_id is None:
+ return None
+ return _TaskArtifactRef(
+ project_id=_url_team_id(url),
+ task_id=task_id,
+ artifact_id=params.get("artifact_version", [None])[0],
+ name=params["artifact"][0],
+ )
+
+
@frozen
class _UnfurlCard:
label: str
@@ -353,6 +411,9 @@ class _UnfurlCard:
chart_insight_id: int | None = None
# Set for an ad hoc insight. Its card goes out only together with its chart.
chart_query: dict | None = None
+ artifact_image: bool = False
+ # Set when the shared link is not the page that shows the resource, such as a file download.
+ open_url: str | None = None
def _tracked_url(url: str, kind: str) -> str:
@@ -377,7 +438,7 @@ def _card_summary(card: _UnfurlCard, *, compact: bool) -> str:
def _card_blocks(card: _UnfurlCard, *, kind: str, url: str, compact: bool) -> list[dict]:
- link = _tracked_url(url, kind)
+ link = _tracked_url(card.open_url or url, kind)
title = f"{_KIND_EMOJI[kind]} *<{link}|{escape_slack_mrkdwn(_truncate(card.title, _MAX_TITLE_CHARS))}>*"
blocks: list[dict] = [
{"type": "section", "text": {"type": "mrkdwn", "text": title}},
@@ -448,7 +509,7 @@ def _build_unfurl_invite(integration: Integration, kind: str, channel: str) -> d
integration,
utm_tags=_INVITE_UTM_TAGS,
ai_enabled=ai_enabled,
- subject=f"this {kind}",
+ subject=f"this {kind.replace('_', ' ')}",
)
@@ -761,10 +822,16 @@ def _ticket_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _Skip
)
+def _may_read_tasks(uac: UserAccessControl) -> bool:
+ return uac.check_access_level_for_resource("task", "viewer")
+
+
def _task_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
url_team_id = _url_team_id(url)
if url_team_id is not None and url_team_id != ctx.team.pk:
return "other_project"
+ if not _may_read_tasks(ctx.uac):
+ return "no_access"
task = tasks_facade.get_task_for_slack_unfurl(ref, ctx.team.pk, ctx.user.id) if _uuid(ref) else None
if task is None:
return "not_found_or_no_access"
@@ -792,6 +859,56 @@ def _task_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipRe
)
+def _file_size(size: int) -> str:
+ if size < 1024:
+ return f"{size} B"
+ value = size / 1024
+ for unit in ("KB", "MB"):
+ if value < 1024:
+ return f"{value:.1f} {unit}"
+ value /= 1024
+ return f"{value:.1f} GB"
+
+
+def _task_artifact_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
+ artifact_ref = _task_artifact_ref(url)
+ if artifact_ref is None:
+ return "not_found"
+ if artifact_ref.project_id is not None and artifact_ref.project_id != ctx.team.pk:
+ return "other_project"
+ if not _may_read_tasks(ctx.uac):
+ return "no_access"
+ artifact = tasks_facade.get_task_artifact_for_slack_unfurl(
+ task_id=artifact_ref.task_id,
+ team_id=ctx.team.pk,
+ user_id=ctx.user.id,
+ run_id=artifact_ref.run_id,
+ artifact_id=artifact_ref.artifact_id,
+ name=artifact_ref.name,
+ )
+ if artifact is None:
+ return "not_found_or_no_access"
+ origin = f"{urlparse(url).scheme}://{urlparse(url).netloc}"
+ artifacts_tab = urlencode(
+ {"task": artifact.task_id, "artifact": artifact.name, "artifact_version": artifact.artifact_id}
+ )
+ size = _file_size(artifact.size) if artifact.size is not None else None
+ return _UnfurlCard(
+ label="Task artifact",
+ title=artifact.name,
+ details=(*filter(None, [size]), f"Task: {artifact.task_title}"),
+ timestamp=artifact.uploaded_at,
+ timestamp_label="Uploaded",
+ button=_CardButton(label="Download", url=f"{origin}{artifact.download_path}"),
+ open_url=f"{origin}/project/{ctx.team.pk}/ai?{artifacts_tab}",
+ artifact_image=(
+ artifact.content_type in _SLACK_IMAGE_CONTENT_TYPES
+ and artifact.size is not None
+ and artifact.size <= _MAX_ARTIFACT_IMAGE_BYTES
+ ),
+ )
+
+
def _canvas_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
summary = canvas_access.live_canvas_summary(team_id=ctx.team.pk, canvas_id=ref) if _uuid(ref) else None
if summary is None:
@@ -972,6 +1089,7 @@ _CARD_BUILDERS: dict[str, Callable[[_UnfurlContext, str, str], _UnfurlCard | _Sk
"dashboard": _dashboard_card,
"ticket": _ticket_card,
"task": _task_card,
+ TASK_ARTIFACT_KIND: _task_artifact_card,
"canvas": _canvas_card,
"notebook": _notebook_card,
"flag": _flag_card,
@@ -1089,6 +1207,105 @@ def _queue_unfurl_charts(
return True
+def _queue_unfurl_artifact_image(
+ *, integration: Integration, user: User, event: dict, unfurls: dict[str, dict], url: str, title: str
+) -> bool:
+ """Reading and storing the file is too slow for the webhook's ack budget, so it runs on Celery."""
+ # noqa reason: the task module imports api, which imports this module at load time.
+ from products.slack_app.backend.tasks import add_slack_unfurl_artifact_image # noqa: PLC0415
+
+ try:
+ add_slack_unfurl_artifact_image.delay(
+ team_id=integration.team_id,
+ integration_id=integration.id,
+ user_id=user.pk,
+ event=event,
+ unfurls=unfurls,
+ url=url,
+ title=title,
+ )
+ except Exception:
+ logger.warning("slack_app_unfurl_artifact_image_queue_failed", team_id=integration.team_id, exc_info=True)
+ return False
+ return True
+
+
+_ImageFailure = Literal["public_sharing_disabled", "no_access", "unavailable", "not_an_image", "unfurl_failed"]
+
+
+@frozen
+class _ImageLink:
+ url: str | None = None
+ failure: _ImageFailure | None = None
+
+
+def _artifact_image_link(*, integration: Integration, user: User, url: str, title: str) -> _ImageLink:
+ # The link opens without a PostHog login, so it follows the public sharing setting like chart images do.
+ team = integration.team
+ if not team.organization.allow_publicly_shared_resources:
+ return _ImageLink(failure="public_sharing_disabled")
+ # Access can change while the job waits in the queue, and the link it publishes needs no login.
+ if not has_project_access(user, team) or not _may_read_tasks(UserAccessControl(user, team=team)):
+ return _ImageLink(failure="no_access")
+ artifact_ref = _task_artifact_ref(url)
+ content = (
+ tasks_facade.read_task_artifact_for_slack_unfurl(
+ task_id=artifact_ref.task_id,
+ team_id=integration.team_id,
+ user_id=user.pk,
+ max_bytes=_MAX_ARTIFACT_IMAGE_BYTES,
+ run_id=artifact_ref.run_id,
+ artifact_id=artifact_ref.artifact_id,
+ name=artifact_ref.name,
+ )
+ if artifact_ref
+ else None
+ )
+ if content is None:
+ return _ImageLink(failure="unavailable")
+ image_url = exports_facade.create_png_delivery_url(
+ team_id=integration.team_id,
+ created_by_id=user.pk,
+ content=content,
+ filename=title,
+ url_ttl=UNFURL_IMAGE_URL_TTL,
+ asset_ttl=UNFURL_IMAGE_ASSET_TTL,
+ )
+ if image_url is None:
+ return _ImageLink(failure="not_an_image")
+ return _ImageLink(url=slack_fetchable_image_url(image_url))
+
+
+def add_artifact_image_to_unfurl(
+ *, integration: Integration, user: User, event: dict, unfurls: dict[str, dict], url: str, title: str
+) -> None:
+ """Post a task artifact card again with its image. Best effort: a failure keeps the text card."""
+ link = _artifact_image_link(integration=integration, user=user, url=url, title=title)
+ failure = link.failure
+ error: str | None = None
+ if link.url is not None:
+ error = _post_unfurls(
+ SlackIntegration(integration), event, with_chart_images(unfurls, {url: link.url}, {url: title})
+ )
+ failure = "unfurl_failed" if error else None
+ logger.info(
+ "slack_app_unfurl_artifact_image_result",
+ team_id=integration.team_id,
+ channel=event.get("channel"),
+ failure=failure,
+ error=error,
+ )
+ capture_slack_event(
+ integration,
+ "slack app link unfurl artifact image",
+ slack_user_id=event["user"],
+ posthog_user=user,
+ shown=failure is None,
+ failure=failure,
+ error=error,
+ )
+
+
def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
"""
Unfurl supported PostHog resource links with metadata.
@@ -1237,6 +1454,15 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
unfurls=unfurls,
charts=chart_requests,
)
+ # A card is full size, and can carry an image, only when it is the only link.
+ first_url, (_, first_card) = next(iter(cards.items()))
+ artifact_image_queued = (
+ not compact
+ and first_card.artifact_image
+ and _queue_unfurl_artifact_image(
+ integration=integration, user=user, event=event, unfurls=unfurls, url=first_url, title=first_card.title
+ )
+ )
capture_slack_event(
integration,
"slack app link unfurled",
@@ -1248,4 +1474,5 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
skipped_count=len(skipped),
followup_invite_shown=invite is not None,
charts_queued=charts_queued,
+ artifact_image_queued=artifact_image_queued,
)
diff --git a/products/slack_app/backend/tasks.py b/products/slack_app/backend/tasks.py
index 7afa6efb0dbe..4b45b802dec9 100644
--- a/products/slack_app/backend/tasks.py
+++ b/products/slack_app/backend/tasks.py
@@ -18,7 +18,7 @@ from products.slack_app.backend.api import (
does_other_region_claim_workspace,
send_region_proxy_request,
)
-from products.slack_app.backend.slack_link_unfurl import start_unfurl_charts
+from products.slack_app.backend.slack_link_unfurl import add_artifact_image_to_unfurl, start_unfurl_charts
from products.slack_app.backend.temporal.types import SlackUnfurlChartRequest
@@ -85,3 +85,31 @@ def start_slack_unfurl_charts(
unfurls=unfurls,
charts=[SlackUnfurlChartRequest(**chart) for chart in charts],
)
+
+
+@shared_task(ignore_result=True)
+@with_team_scope()
+def add_slack_unfurl_artifact_image(
+ *,
+ team_id: int,
+ integration_id: int,
+ user_id: int,
+ event: dict[str, Any],
+ unfurls: dict[str, Any],
+ url: str,
+ title: str,
+) -> 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
+ add_artifact_image_to_unfurl(
+ integration=integration,
+ user=user,
+ event=event,
+ unfurls=unfurls,
+ url=url,
+ title=title,
+ )
diff --git a/products/slack_app/backend/temporal/activities/unfurl_charts.py b/products/slack_app/backend/temporal/activities/unfurl_charts.py
index 464fed37df1e..94ea31947a9b 100644
--- a/products/slack_app/backend/temporal/activities/unfurl_charts.py
+++ b/products/slack_app/backend/temporal/activities/unfurl_charts.py
@@ -1,11 +1,16 @@
-from datetime import UTC, datetime, timedelta
+from datetime import UTC, datetime
from temporalio import activity
from posthog.temporal.common.utils import close_db_connections
from products.exports.backend.facade.api import create_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
+from products.slack_app.backend.logic.link_unfurl_charts import (
+ UNFURL_IMAGE_ASSET_TTL,
+ UNFURL_IMAGE_URL_TTL,
+ post_unfurl_charts,
+ unfurl_chart_targets,
+)
from products.slack_app.backend.temporal.types import (
SlackAppUnfurlChartsPostInput,
SlackAppUnfurlChartsPrepared,
@@ -13,17 +18,13 @@ from products.slack_app.backend.temporal.types import (
SlackUnfurlChartAsset,
)
-# 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)
-
@activity.defn
@close_db_connections
def prepare_slack_unfurl_charts_activity(inputs: SlackAppUnfurlChartsWorkflowInputs) -> SlackAppUnfurlChartsPrepared:
targets = unfurl_chart_targets(inputs)
assets: list[SlackUnfurlChartAsset] = []
- expires_after = datetime.now(UTC) + _CHART_ASSET_TTL
+ expires_after = datetime.now(UTC) + UNFURL_IMAGE_ASSET_TTL
for chart in targets.charts:
try:
asset_id = create_png_export(
@@ -54,7 +55,7 @@ def post_slack_unfurl_charts_activity(post: SlackAppUnfurlChartsPostInput) -> No
image_url = get_delivery_image_url(
team_id=request.team_id,
asset_id=asset.asset_id,
- expiry_delta=_CHART_URL_TTL,
+ expiry_delta=UNFURL_IMAGE_URL_TTL,
created_by_id=request.user_id,
)
if image_url is not None:
diff --git a/products/slack_app/backend/tests/test_link_unfurl.py b/products/slack_app/backend/tests/test_link_unfurl.py
index 9f4d9bbf1f50..c77742178709 100644
--- a/products/slack_app/backend/tests/test_link_unfurl.py
+++ b/products/slack_app/backend/tests/test_link_unfurl.py
@@ -1,5 +1,6 @@
+import io
import json
-from urllib.parse import quote
+from urllib.parse import quote, urlparse
import pytest
from posthog.test.base import APIBaseTest
@@ -11,6 +12,7 @@ from django.test.client import RequestFactory
from django.utils import timezone
from parameterized import parameterized
+from PIL import Image
from slack_sdk.errors import SlackApiError
from slack_sdk.models.blocks import Block
from slack_sdk.web.slack_response import SlackResponse
@@ -25,6 +27,7 @@ from posthog.models.scoping import team_scope
from posthog.models.team.team import Team
from posthog.models.user_integration import UserIntegration
from posthog.object_tags.kinds import ObjectRef
+from posthog.storage import object_storage
from products.access_control.backend.models.access_control import AccessControl
from products.canvas.backend.facade import testing as canvas_testing
@@ -53,13 +56,52 @@ 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.slack_app.backend.tasks import add_slack_unfurl_artifact_image, start_slack_unfurl_charts
from products.surveys.backend.models import Survey
from products.tasks.backend.models import Channel, Task, TaskRun
_TASK_ID = "c76f58f4-4c64-4cd7-825d-4ef89f6dd4ac"
_CHANNEL_ID = "0192f0a0-0000-4000-8000-000000000001"
_CANVAS_ID = "0192f0a0-0000-4000-8000-000000000002"
+_RUN_ID = "0192f0a0-0000-4000-8000-000000000003"
+
+
+def _create_task_artifact(
+ team: Team,
+ user: User,
+ run_state: dict | None = None,
+ project_id: int | None = None,
+ name: str = "report.md",
+ content_type: str = "text/markdown",
+ artifacts_tab_link: bool = False,
+) -> str:
+ task = Task.objects.create(
+ team=team,
+ created_by=user,
+ title="Fix checkout",
+ description="",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ run = TaskRun.objects.create(
+ task=task,
+ team=team,
+ state=run_state or {},
+ artifacts=[
+ {
+ "id": "file-1",
+ "name": name,
+ "type": "artifact",
+ "size": 2048,
+ "content_type": content_type,
+ "storage_path": f"tasks/artifacts/run_1/file-1_{name}",
+ "uploaded_at": "2026-10-01T12:00:00+00:00",
+ }
+ ],
+ )
+ project = project_id or team.pk
+ if artifacts_tab_link:
+ return f"http://testserver/project/{project}/ai?task={task.id}&artifact={name}"
+ return f"http://testserver/api/projects/{project}/tasks/{task.id}/runs/{run.id}/artifacts/file-1/download/"
class TestParsePosthogResourceLink:
@@ -81,6 +123,24 @@ class TestParsePosthogResourceLink:
("desktop_task", f"https://us.posthog.com/code/task/{_TASK_ID}", "task", _TASK_ID),
("space_task", f"https://us.posthog.com/code/channel/{_CHANNEL_ID}/tasks/{_TASK_ID}", "task", _TASK_ID),
("ai_task", f"https://us.posthog.com/project/42/ai?task={_TASK_ID}", "task", _TASK_ID),
+ (
+ "task_artifact",
+ f"https://us.posthog.com/api/projects/42/tasks/{_TASK_ID}/runs/{_RUN_ID}/artifacts/file-1/download/",
+ "task_artifact",
+ "file-1",
+ ),
+ (
+ "task_artifacts_tab",
+ f"https://us.posthog.com/project/42/ai?task={_TASK_ID}&artifact=report.md",
+ "task_artifact",
+ "report.md",
+ ),
+ (
+ "task_artifacts_tab_version",
+ f"https://us.posthog.com/project/42/ai?task={_TASK_ID}&artifact=report.md&artifact_version=file-1",
+ "task_artifact",
+ "file-1",
+ ),
("canvas", f"https://us.posthog.com/project/42/canvases/{_CANVAS_ID}", "canvas", _CANVAS_ID),
("desktop_canvas", f"https://us.posthog.com/code/canvas/{_CHANNEL_ID}/{_CANVAS_ID}", "canvas", _CANVAS_ID),
("notebook", "https://us.posthog.com/project/42/notebooks/Xy12", "notebook", "Xy12"),
@@ -806,6 +866,22 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
"*Completed*",
"View pull request",
]
+ case "task_artifacts_tab":
+ return _create_task_artifact(self.team, self.user, artifacts_tab_link=True), [
+ "report.md",
+ "Task: Fix checkout",
+ "artifact_version=file-1",
+ "Download",
+ ]
+ case "task_artifact":
+ return _create_task_artifact(self.team, self.user), [
+ "report.md",
+ "2.0 KB",
+ "Task: Fix checkout",
+ "/ai?task=",
+ "artifact=report.md",
+ "Download",
+ ]
case "report":
report = SignalReport.objects.create(
team=self.team,
@@ -821,10 +897,86 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
]
raise ValueError(kind)
+ @parameterized.expand([("deactivated", "user"), ("task_access_removed", "access_control")])
+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
+ def test_artifact_image_job_rechecks_access(
+ self, _name: str, revoke: str, mock_slack_integration_class: MagicMock
+ ) -> None:
+ url = _create_task_artifact(self.team, self.user, name="chart.png", content_type="image/png")
+ member = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ Task.objects.filter(team=self.team).update(created_by=member)
+ if revoke == "user":
+ member.is_active = False
+ member.save()
+ else:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ AccessControl.objects.create(resource="task", team=self.team, access_level="none")
+
+ with patch("posthog.storage.object_storage.read_bytes") as mock_read_bytes:
+ add_slack_unfurl_artifact_image(
+ team_id=self.team.pk,
+ integration_id=self.integration.id,
+ user_id=member.pk,
+ event={"channel": "C1", "message_ts": "123.456", "user": "U1"},
+ unfurls={url: {"blocks": []}},
+ url=url,
+ title="chart.png",
+ )
+
+ mock_read_bytes.assert_not_called()
+ mock_slack_integration_class.return_value.client.chat_unfurl.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("task_hidden_from_sharer", None, None, True),
+ ("run_with_analytics_context", {"analytics_query_context": {"kind": "metric"}}, None, False),
+ ("other_project", None, 999999, False),
+ ]
+ )
+ @patch("products.slack_app.backend.api.resolve_slack_user")
+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
+ def test_skips_task_artifact_the_sharer_cannot_download(
+ self,
+ _name: str,
+ run_state: dict | None,
+ project_id: int | None,
+ shared_by_other_member: bool,
+ mock_slack_integration_class: MagicMock,
+ mock_resolve: MagicMock,
+ ) -> None:
+ url = _create_task_artifact(self.team, self.user, run_state, project_id)
+ sharer = (
+ User.objects.create_and_join(self.organization, "[email protected]", "password")
+ if shared_by_other_member
+ else self.user
+ )
+ mock_resolve.return_value = MagicMock(user=sharer)
+ mock_client = MagicMock()
+ mock_slack_integration_class.return_value.client = mock_client
+
+ self._unfurl_links([url])
+
+ mock_client.chat_unfurl.assert_not_called()
+
@parameterized.expand(
[
(kind,)
- for kind in ("canvas", "notebook", "flag", "experiment", "survey", "cohort", "error", "report", "task")
+ for kind in (
+ "canvas",
+ "notebook",
+ "flag",
+ "experiment",
+ "survey",
+ "cohort",
+ "error",
+ "report",
+ "task",
+ "task_artifact",
+ "task_artifacts_tab",
+ )
]
)
@patch("products.slack_app.backend.api.resolve_slack_user")
@@ -852,6 +1004,8 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
("cohort", "cohort"),
("error", "error_tracking"),
("report", "task"),
+ ("task", "task"),
+ ("task_artifact", "task"),
]
)
@patch("products.slack_app.backend.api.resolve_slack_user")
@@ -1146,6 +1300,88 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
assert "internal only" not in text
+# Kept apart from TestHandlePosthogLinkUnfurl: that class builds a TrendsQuery in setUp, and the
+# model-crossing invariant counts it as run by any test in the class that calls the test client.
+class TestTaskArtifactImageUnfurl(APIBaseTest):
+ 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"},
+ )
+
+ @parameterized.expand(
+ [
+ ("png", "chart.png", "image/png", "PNG", True, True),
+ ("jpeg_shown_as_png", "photo.jpg", "image/jpeg", "JPEG", True, True),
+ ("cmyk_jpeg_shown_as_png", "print.jpg", "image/jpeg", "CMYK", True, True),
+ ("bytes_are_not_an_image", "chart.png", "image/png", None, True, False),
+ ("public_sharing_off", "chart.png", "image/png", "PNG", False, False),
+ ("file_type_is_not_an_image", "report.md", "text/markdown", None, True, False),
+ ]
+ )
+ @override_settings(SITE_URL="https://app.example.com", OBJECT_STORAGE_ENABLED=False)
+ @patch("products.slack_app.backend.tasks.add_slack_unfurl_artifact_image.delay")
+ @patch("products.slack_app.backend.api.resolve_slack_user")
+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
+ def test_task_artifact_image_shows_in_its_card(
+ self,
+ _name: str,
+ name: str,
+ content_type: str,
+ image_format: str | None,
+ public_sharing: bool,
+ expect_image: bool,
+ mock_slack_integration_class: MagicMock,
+ mock_resolve: MagicMock,
+ mock_delay: MagicMock,
+ ) -> None:
+ # Runs the queued task in process, through JSON like the Celery broker.
+ mock_delay.side_effect = lambda **kwargs: add_slack_unfurl_artifact_image(**json.loads(json.dumps(kwargs)))
+ self.organization.allow_publicly_shared_resources = public_sharing
+ self.organization.save()
+ content = b"<html>not an image</html>"
+ if image_format:
+ buffer = io.BytesIO()
+ mode = "CMYK" if image_format == "CMYK" else "RGB"
+ Image.new(mode, (4, 4)).save(buffer, format="JPEG" if image_format == "CMYK" else image_format)
+ content = buffer.getvalue()
+ url = _create_task_artifact(self.team, self.user, name=name, content_type=content_type)
+ mock_resolve.return_value = MagicMock(user=self.user)
+ mock_client = mock_slack_integration_class.return_value.client
+ read_bytes = object_storage.read_bytes
+
+ with patch(
+ "posthog.storage.object_storage.read_bytes",
+ side_effect=lambda path, *args, **kwargs: (
+ content if path.startswith("tasks/artifacts/") else read_bytes(path, *args, **kwargs)
+ ),
+ ):
+ handle_posthog_link_unfurl(
+ {"channel": "C1", "message_ts": "123.456", "user": "U1", "links": [{"url": url}]},
+ self.integration,
+ )
+
+ if not expect_image:
+ mock_client.chat_unfurl.assert_called_once()
+ return
+ unfurl = mock_client.chat_unfurl.call_args.kwargs["unfurls"][url]
+ TestHandlePosthogLinkUnfurl._assert_slack_accepts(unfurl)
+ types = [block["type"] for block in unfurl["blocks"]]
+ assert types.index("image") == types.index("actions") - 1
+ image_url = urlparse(unfurl["blocks"][types.index("image")]["image_url"])
+ assert image_url.netloc == "app.example.com"
+ self.client.logout()
+ response = self.client.get(f"{image_url.path}?{image_url.query}")
+
+ assert response.status_code == 200
+ with Image.open(io.BytesIO(response.getvalue())) as served:
+ assert served.format == "PNG"
+
+
@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
class TestLinkUnfurlChannelGate(TestCase):
SLACK_TEAM_ID = "TGate01"
diff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
index 46f518ec7557..ea7483f7ce75 100644
--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py
+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
@@ -926,10 +926,19 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
passed_integration = mock_unfurl.call_args[0][1]
assert passed_integration.id == self.posthog_code_integration.id
+ @parameterized.expand(
+ [
+ ("task_link", "https://us.posthog.com/project/{team}/tasks/{task}"),
+ (
+ "artifact_download_link",
+ "https://us.posthog.com/api/projects/{team}/tasks/{task}/runs/{task}/artifacts/a1/download/",
+ ),
+ ]
+ )
@patch("products.slack_app.backend.api.handle_posthog_link_unfurl")
@patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=False)
@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
- def test_link_shared_routes_to_project_integration(self, mock_claims, mock_unfurl):
+ def test_link_shared_routes_to_project_integration(self, _name, url_template, mock_claims, mock_unfurl):
other_team = Team.objects.create(organization=self.organization, name="Other")
other_integration = Integration.objects.create(
team=other_team,
@@ -942,7 +951,7 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
event = {
"type": "link_shared",
"channel": "C001",
- "links": [{"url": f"https://us.posthog.com/project/{other_team.id}/tasks/{task_id}"}],
+ "links": [{"url": url_template.format(team=other_team.id, task=task_id)}],
}
from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index caf5b46a88b2..d1fa6786831d 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -767,6 +767,105 @@ def get_task_for_slack_unfurl(task_id: str | UUID, team_id: int, user_id: int) -
)
+@frozen
+class _SlackUnfurlArtifact:
+ task: Task
+ run_id: UUID
+ entry: dict[str, Any]
+
+
+def _slack_unfurl_artifact_entry(
+ *,
+ task_id: str | UUID,
+ team_id: int,
+ user_id: int,
+ run_id: str | UUID | None,
+ artifact_id: str | None,
+ name: str | None,
+) -> _SlackUnfurlArtifact | None:
+ """The downloadable artifact the user may see, by its id or by its file name (newest upload wins).
+
+ A run with analytics context is refused. The download endpoint checks the caller's access to
+ that context against the request, and an unfurl has no request, so it fails closed.
+ """
+ task = _visible_task_qs(team_id, user_id).filter(id=task_id, internal=False).only("id", "title").first()
+ if task is None or (artifact_id is None and name is None):
+ return None
+ runs = TaskRun.objects.filter(team_id=team_id, task_id=task.id)
+ if run_id is not None:
+ runs = runs.filter(pk=run_id)
+ if runs.filter(state__has_key="analytics_query_context").exists():
+ return None
+ matches = [
+ (run_pk, entry)
+ for run_pk, artifacts in runs.values_list("id", "artifacts")
+ for entry in artifacts or []
+ if entry.get("storage_path") and (entry.get("id") == artifact_id if artifact_id else entry.get("name") == name)
+ ]
+ if not matches:
+ return None
+ run_pk, entry = max(matches, key=lambda match: str(match[1].get("uploaded_at") or ""))
+ return _SlackUnfurlArtifact(task=task, run_id=run_pk, entry=entry)
+
+
+def get_task_artifact_for_slack_unfurl(
+ *,
+ task_id: str | UUID,
+ team_id: int,
+ user_id: int,
+ run_id: str | UUID | None = None,
+ artifact_id: str | None = None,
+ name: str | None = None,
+) -> contracts.TaskArtifactSlackUnfurlDTO | None:
+ found = _slack_unfurl_artifact_entry(
+ task_id=task_id, team_id=team_id, user_id=user_id, run_id=run_id, artifact_id=artifact_id, name=name
+ )
+ if found is None:
+ return None
+ entry = found.entry
+ size = entry.get("size")
+ uploaded_at = entry.get("uploaded_at")
+ try:
+ uploaded = datetime.fromisoformat(uploaded_at) if isinstance(uploaded_at, str) else None
+ except ValueError:
+ uploaded = None
+ return contracts.TaskArtifactSlackUnfurlDTO(
+ name=str(entry.get("name") or "artifact"),
+ content_type=str(entry.get("content_type") or ""),
+ size=size if isinstance(size, int) else None,
+ uploaded_at=uploaded,
+ task_id=found.task.id,
+ task_title=found.task.title,
+ run_id=found.run_id,
+ artifact_id=str(entry["id"]),
+ download_path=_artifact_download_path(team_id, found.task.id, found.run_id, str(entry["id"])),
+ )
+
+
+def read_task_artifact_for_slack_unfurl(
+ *,
+ task_id: str | UUID,
+ team_id: int,
+ user_id: int,
+ max_bytes: int,
+ run_id: str | UUID | None = None,
+ artifact_id: str | None = None,
+ name: str | None = None,
+) -> bytes | None:
+ """The artifact's bytes, with the same access checks as ``get_task_artifact_for_slack_unfurl``."""
+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path
+
+ found = _slack_unfurl_artifact_entry(
+ task_id=task_id, team_id=team_id, user_id=user_id, run_id=run_id, artifact_id=artifact_id, name=name
+ )
+ if found is None:
+ return None
+ size = found.entry.get("size")
+ if not isinstance(size, int) or size > max_bytes:
+ return None
+ return object_storage.read_bytes(found.entry["storage_path"], missing_ok=True)
+
+
_StateEntryResult = TypeVar("_StateEntryResult")
@@ -4141,8 +4240,18 @@ def _build_artifact_storage_path(run: TaskRun, artifact_id: str, name: str) -> t
return safe_name, f"{prefix}/{artifact_id[:8]}_{safe_name}"
+def _downloadable_artifact_entry(artifacts: list[dict[str, Any]] | None, artifact_id: str) -> dict[str, Any] | None:
+ entry = next((a for a in artifacts or [] if a.get("id") == artifact_id), None)
+ # Reference entries carry no file, so there is nothing to download for them.
+ return entry if entry is not None and entry.get("storage_path") else None
+
+
+def _artifact_download_path(team_id: int, task_id: UUID, run_id: UUID, artifact_id: str) -> str:
+ return f"/api/projects/{team_id}/tasks/{task_id}/runs/{run_id}/artifacts/{artifact_id}/download/"
+
+
def _build_artifact_download_path(run: TaskRun, artifact_id: str) -> str:
- return f"/api/projects/{run.team_id}/tasks/{run.task_id}/runs/{run.id}/artifacts/{artifact_id}/download/"
+ return _artifact_download_path(run.team_id, run.task_id, run.id, artifact_id)
def _tag_artifact_object(run: TaskRun, storage_path: str) -> None:
@@ -4921,9 +5030,8 @@ def presign_task_run_artifact_download(
if run is None:
return None, None
- entry = next((a for a in run.artifacts or [] if a.get("id") == artifact_id), None)
- # Reference entries carry no file, so there is nothing to download for them.
- if entry is None or not entry.get("storage_path"):
+ entry = _downloadable_artifact_entry(run.artifacts, artifact_id)
+ if entry is None:
return None, "not_found"
filename = str(entry.get("name") or "artifact")
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 9cfc10848d7b..c719fc21f5b6 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -232,6 +232,21 @@ class TaskSlackUnfurlDTO:
latest_run_status: str | None
+@dataclass(frozen=True)
+class TaskArtifactSlackUnfurlDTO:
+ """The task run artifact metadata needed to build a Slack unfurl."""
+
+ name: str
+ content_type: str
+ size: int | None
+ uploaded_at: datetime | None
+ task_id: UUID
+ task_title: str
+ run_id: UUID
+ artifact_id: str
+ download_path: str
+
+
@dataclass(frozen=True)
class TaskDetailDTO:
"""The HTTP detail representation of a task.