Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(slack-app): standard link unfurl cards for more posthog objects (#116920)

Shy Alter0335bef1cc19
diff --git a/posthog/object_tags/kinds.py b/posthog/object_tags/kinds.py
index d5bdcb5bd557..a9f2c822ce49 100644
--- a/posthog/object_tags/kinds.py
+++ b/posthog/object_tags/kinds.py
@@ -19,8 +19,9 @@ Python consumers import this module directly.
"""
import re
+from collections.abc import Mapping
from functools import cache
-from urllib.parse import quote
+from urllib.parse import parse_qs, quote, unquote, urlsplit
from posthog.dataclasses import frozen
@@ -175,3 +176,46 @@ def object_web_path(spec: ObjectKindSpec, object_id: str) -> str | None:
if spec.id_pattern is not None and not _compiled_pattern(spec.id_pattern).match(object_id):
return None
return spec.path_template.replace("{id}", quote(object_id, safe=""))
+
+
+@frozen
+class ObjectRef:
+ kind: str
+ id: str
+
+
+OBJECT_URL_TEMPLATES: dict[str, tuple[str, ...]] = {
+ name: tuple(template for template in (spec.path_template, *spec.url_aliases) if template and "#" not in template)
+ for name, spec in OBJECT_KINDS.items()
+}
+
+
+def _template_match(template: str, segments: list[str], params: dict[str, list[str]]) -> str | None:
+ path, _, query = template.partition("?")
+ expected = [segment for segment in path.split("/") if segment]
+ if query:
+ values = params.get(query.partition("=")[0])
+ return values[0] if values and segments == expected else None
+ if len(segments) < len(expected):
+ return None
+ if any(want != got and not want.startswith("{") for want, got in zip(expected, segments)):
+ return None
+ return segments[expected.index("{id}")]
+
+
+def object_ref_for_url(url: str, templates: Mapping[str, tuple[str, ...]] = OBJECT_URL_TEMPLATES) -> ObjectRef | None:
+ parsed = urlsplit(url)
+ segments = [unquote(segment) for segment in parsed.path.split("/") if segment]
+ if segments[:1] == ["project"]:
+ segments = segments[2:]
+ params = parse_qs(parsed.query)
+ for kind, kind_templates in templates.items():
+ spec = OBJECT_KINDS.get(kind)
+ for template in kind_templates:
+ object_id = _template_match(template, segments, params)
+ if not object_id or object_id in RESERVED_URL_IDS:
+ continue
+ if spec and spec.id_pattern and not _compiled_pattern(spec.id_pattern).match(object_id):
+ continue
+ return ObjectRef(kind=kind, id=object_id)
+ return None
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 2160514d12d9..00ea3ce9d6f1 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -4223,8 +4223,7 @@ def _link_shared_resource_refs(event: dict[str, Any]) -> list[dict[str, str]]:
continue
parsed = parse_posthog_resource_link(url)
if parsed:
- resource_type, resource_ref = parsed
- resources.append({"type": resource_type, "ref": str(resource_ref)})
+ resources.append({"type": parsed.kind, "ref": parsed.id})
return resources
diff --git a/products/slack_app/backend/logic/link_unfurl_charts.py b/products/slack_app/backend/logic/link_unfurl_charts.py
index 0176446312f2..271cc31f94f7 100644
--- a/products/slack_app/backend/logic/link_unfurl_charts.py
+++ b/products/slack_app/backend/logic/link_unfurl_charts.py
@@ -53,7 +53,7 @@ def chat_unfurl_kwargs(
def _has_project_access(user: User, team: Team) -> bool:
# The insight check alone is not enough, because it can fall back to the default access level
# in a project that denies the user. The webhook checks project access the same way.
- return UserPermissions(user=user, team=team).current_team.effective_membership_level is not None
+ return user.is_active and UserPermissions(user=user, team=team).current_team.effective_membership_level is not None
@frozen
@@ -74,14 +74,15 @@ def unfurl_chart_targets(inputs: SlackAppUnfurlChartsWorkflowInputs) -> UnfurlCh
def with_chart_images(unfurls: dict[str, Any], image_urls: dict[str, str], titles: dict[str, str]) -> dict[str, Any]:
- """The unfurls with an image block under the title of each card that has a chart."""
+ """The unfurls with an image block above the buttons of each card that has a chart."""
result: dict[str, Any] = {}
for url, payload in unfurls.items():
blocks = list(payload.get("blocks") or [])
image_url = image_urls.get(url)
if image_url is not None:
alt_text = (titles.get(url) or "Insight chart")[:_MAX_ALT_TEXT_CHARS]
- blocks.insert(1, {"type": "image", "image_url": image_url, "alt_text": alt_text})
+ position = next((i for i, block in enumerate(blocks) if block.get("type") == "actions"), len(blocks))
+ blocks.insert(position, {"type": "image", "image_url": image_url, "alt_text": alt_text})
result[url] = {**payload, "blocks": blocks}
return result
diff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.py
index 89ae4fba987e..e5afafe7d582 100644
--- a/products/slack_app/backend/slack_link_unfurl.py
+++ b/products/slack_app/backend/slack_link_unfurl.py
@@ -5,22 +5,30 @@ Ticket subjects and messages are customer-authored, so every one goes through `e
from __future__ import annotations
+import re
import asyncio
import dataclasses
-from typing import Literal
-from urllib.parse import parse_qs, urlparse
+from collections.abc import Callable
+from datetime import datetime
+from typing import Literal, cast
+from urllib.parse import parse_qs, parse_qsl, urlencode, urlparse, urlsplit, urlunsplit
from uuid import UUID
from django.conf import settings
from django.core.exceptions import ValidationError
+from django.db.models.functions import Substr
+from django.utils import timezone
import structlog
+from slack_sdk.errors import SlackApiError
from temporalio.exceptions import WorkflowAlreadyStartedError
+from posthog.dataclasses import frozen
from posthog.models import Team, User
from posthog.models.comment import Comment
from posthog.models.integration import Integration, SlackIntegration
from posthog.models.user_integration import UserIntegration
+from posthog.object_tags.kinds import OBJECT_URL_TEMPLATES, ObjectRef, object_ref_for_url
from posthog.redis import get_client
from posthog.slack.formatting import escape_slack_mrkdwn
from posthog.temporal.ai.slack_app.slack_app_unfurl_charts import (
@@ -35,22 +43,78 @@ from products.access_control.backend.facade.user_access_control import (
UserAccessControl,
access_level_satisfied_for_resource,
)
+from products.canvas.backend.facade import access as canvas_access
+from products.cohorts.backend.models.cohort import Cohort
from products.conversations.backend.models.ticket import Ticket
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.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
+from products.notebooks.backend.models import Notebook
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.feature_flags import is_slack_app_insight_unfurl_charts_enabled
from products.slack_app.backend.logic.link_unfurl_charts import chat_unfurl_kwargs
from products.slack_app.backend.services.followup_invite import build_followup_invite
from products.slack_app.backend.services.slack_messages import UNFURL_OPT_OUT_PARAM
+from products.surveys.backend.models import Survey
from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.facade.contracts import TaskSlackUnfurlDTO
logger = structlog.get_logger(__name__)
-_MAX_DESCRIPTION_CHARS = 2800
# Keep title + status + message under Slack's 3000-char section limit; the client shows "Show more".
-_MAX_OPENING_MESSAGE_CHARS = 2000
+_MAX_BODY_CHARS = 200
+_MAX_TITLE_CHARS = 150
+_MAX_DETAIL_CHARS = 100
+_MAX_LINK_CHARS = 1000
+_MAX_CHART_LINES = 4
+_DATE_RANGE_UNITS = {"h": "hour", "d": "day", "w": "week", "m": "month", "y": "year"}
+_NAMED_DATE_RANGES = {"dStart": "Today", "mStart": "This month", "yStart": "This year", "all": "All time"}
+_MAX_GRID_TILES = 6
+_CHART_WIDTH = 20
+_CHART_LABEL_CHARS = 16
+
+_UNFURL_TEMPLATES: dict[str, tuple[str, ...]] = {
+ "insight": (*OBJECT_URL_TEMPLATES["insight"], "/bi/{id}"),
+ "dashboard": OBJECT_URL_TEMPLATES["dashboard"],
+ "ticket": OBJECT_URL_TEMPLATES["ticket"],
+ "task": ("/tasks/{id}", "/code/task/{id}", "/code/channel/{channel}/tasks/{id}", "/ai?task={id}"),
+ "canvas": ("/canvases/{id}", "/code/canvas/{channel}/{id}"),
+ "notebook": ("/notebooks/{id}",),
+ "flag": OBJECT_URL_TEMPLATES["flag"],
+ "experiment": OBJECT_URL_TEMPLATES["experiment"],
+ "survey": OBJECT_URL_TEMPLATES["survey"],
+ "cohort": OBJECT_URL_TEMPLATES["cohort"],
+ "error": OBJECT_URL_TEMPLATES["error"],
+ "report": ("/inbox/{tab}/{id}", *OBJECT_URL_TEMPLATES["report"]),
+}
+
+_KIND_EMOJI: dict[str, str] = {
+ "insight": "📈",
+ "dashboard": "📊",
+ "ticket": "🎫",
+ "task": "🤖",
+ "canvas": "🎨",
+ "notebook": "📓",
+ "flag": "🚩",
+ "experiment": "🧪",
+ "survey": "📝",
+ "cohort": "👥",
+ "error": "🐞",
+ "report": "📥",
+}
+
+_SkipReason = Literal["not_found", "no_access", "other_project", "not_found_or_no_access"]
+
+_REJECTED_PAYLOAD_ERRORS = frozenset(
+ {"cannot_parse_attachment", "invalid_unfurls_format", "invalid_arguments", "invalid_array_arg", "invalid_blocks"}
+)
_INVITE_UTM_TAGS = "utm_source=slack&utm_medium=unfurl&utm_campaign=link_unfurl_followup"
# A channel that shares PostHog links all day would otherwise carry the invite on every unfurl,
@@ -59,9 +123,6 @@ _INVITE_THROTTLE_SECONDS = 24 * 60 * 60
# The throttle must fail fast rather than correctly: it sits inside the webhook's ack budget.
_INVITE_REDIS_TIMEOUT_SECONDS = 0.3
-# Each chart is a render, so one message with many insight links gets charts for the first few.
-_MAX_UNFURL_CHARTS = 3
-
# Query `source.kind` / top-level `kind` → short name before " insight" (sync with InsightType / query kinds).
_QUERY_KIND_TO_SHORT_NAME: dict[str, str] = {
"TrendsQuery": "Trends",
@@ -97,7 +158,9 @@ _LEGACY_FILTER_INSIGHT_TO_SHORT_NAME: dict[str, str] = {
def _truncate(text: str, max_len: int) -> str:
if len(text) <= max_len:
return text
- return text[: max_len - 1] + "…"
+ cut = text[: max_len - 1]
+ word_end = cut.rfind(" ")
+ return (cut[:word_end] if word_end > max_len // 2 else cut).rstrip(" ,.;:") + "…"
# App hosts that name a Cloud region. `app.posthog.com` is the legacy alias for US Cloud; a bare
@@ -114,68 +177,19 @@ def link_url_region(url: str) -> str | None:
return _APP_HOST_REGIONS.get(urlparse(url).hostname or "")
-def parse_posthog_resource_link(
- url: str,
-) -> tuple[Literal["insight", "dashboard", "ticket", "task"], str | int] | None:
+def parse_posthog_resource_link(url: str) -> ObjectRef | None:
"""
- Parse a PostHog app URL into (resource kind, reference id).
-
- Reference is insight short_id (str), dashboard primary key (int), or ticket ref (str — ticket
- number or UUID).
+ Parse a PostHog app URL into the object a card can unfurl.
A URL carrying `?unfurl=false` is not a resource here: links we post ourselves already
sit beside the detail a card would add, so they opt out rather than repeat it.
If the path includes `/project/:id`, that segment is ignored — lookup is always scoped to the
Slack-connected project and the resolved PostHog user, not to any project id in the URL.
-
- Related: `removeProjectIdIfPresent` + `urlToResource` (`router-utils.ts`, `urls.ts`); legacy paths in `get_target_queryset` (`middleware.py`).
"""
- parsed = urlparse(url)
- if "false" in parse_qs(parsed.query).get(UNFURL_OPT_OUT_PARAM, []):
+ if "false" in parse_qs(urlparse(url).query).get(UNFURL_OPT_OUT_PARAM, []):
return None
- parts = [p for p in parsed.path.split("/") if p]
- if not parts:
- return None
-
- idx = 0
- if len(parts) >= 2 and parts[0] == "project":
- # Skip project/{anything} — do not use for authorization (see handle_posthog_link_unfurl).
- idx = 2
-
- if len(parts) > idx and parts[idx] == "i" and len(parts) > idx + 1:
- short_id = parts[idx + 1]
- if short_id == "new":
- return None
- return ("insight", short_id)
-
- if len(parts) > idx and parts[idx] == "insights" and len(parts) > idx + 1:
- short_id = parts[idx + 1]
- if short_id in ("new", "options"):
- return None
- return ("insight", short_id)
-
- if len(parts) > idx and parts[idx] == "dashboard" and len(parts) > idx + 1:
- try:
- dashboard_id = int(parts[idx + 1])
- except ValueError:
- return None
- return ("dashboard", dashboard_id)
-
- if len(parts) > idx + 2 and parts[idx] == "support" and parts[idx + 1] == "tickets":
- ref = parts[idx + 2]
- if ref == "new":
- return None
- return ("ticket", ref)
-
- if len(parts) > idx and parts[idx] == "tasks" and len(parts) > idx + 1:
- try:
- task_id = UUID(parts[idx + 1])
- except ValueError:
- return None
- return ("task", str(task_id))
-
- return None
+ return object_ref_for_url(url, _UNFURL_TEMPLATES)
def _extract_query_source_kind(query: dict) -> str | None:
@@ -283,31 +297,73 @@ def _ticket_opening_message(team_id: int, ticket_id: UUID) -> str | None:
.values_list("content", flat=True)
.first()
)
- return _truncate(escape_slack_mrkdwn((content or "").strip()), _MAX_OPENING_MESSAGE_CHARS) or None
-
-
-def _unfurl_payload(*, resource_label: str, title: str, description: str | None) -> dict:
- title = title or "Untitled"
- body = f"*{title} • {resource_label}*"
- if description:
- body += "\n\n" + _truncate(description.strip(), _MAX_DESCRIPTION_CHARS)
- return {"blocks": [{"type": "section", "text": {"type": "mrkdwn", "text": body}}]}
-
-
-def _ticket_unfurl_payload(*, url: str, ticket: Ticket, requester: str, opening_message: str | None) -> dict:
- """A linked title, a requester/status context line, and (optionally) the quoted opening message."""
+ return content
+
+
+@frozen
+class _CardButton:
+ label: str
+ url: str
+
+
+@frozen
+class _UnfurlCard:
+ label: str
+ title: str
+ status: str | None = None
+ details: tuple[str, ...] = ()
+ body: str | None = None
+ chart: str | None = None
+ timestamp: datetime | None = None
+ timestamp_label: str = "Updated"
+ button: _CardButton | None = None
+ chart_insight_id: int | None = None
+
+
+def _tracked_url(url: str, kind: str) -> str:
+ parts = urlsplit(url)
+ for trimmed in ("fragment", "query"):
+ if len(urlunsplit(parts)) > _MAX_LINK_CHARS:
+ parts = parts._replace(**{trimmed: ""})
+ params = [*parse_qsl(parts.query), ("utm_source", "slack"), ("utm_medium", "unfurl"), ("utm_content", kind)]
+ return urlunsplit(parts._replace(query=urlencode(params)))
+
+
+def _card_summary(card: _UnfurlCard, *, compact: bool) -> str:
+ parts = [escape_slack_mrkdwn(card.label)]
+ if card.status:
+ parts.append(f"*{escape_slack_mrkdwn(card.status)}*")
+ if not compact:
+ parts.extend(escape_slack_mrkdwn(_truncate(detail, _MAX_DETAIL_CHARS)) for detail in card.details)
+ if card.timestamp:
+ label = card.timestamp_label
+ parts.append(f"<!date^{int(card.timestamp.timestamp())}^{label} {{ago}}|{label} {card.timestamp:%Y-%m-%d}>")
+ return " · ".join(parts)
+
+
+def _card_blocks(card: _UnfurlCard, *, kind: str, url: str, compact: bool) -> list[dict]:
+ link = _tracked_url(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": f"<{url}|*Support Ticket #{ticket.ticket_number}*>"}},
- {
- "type": "context",
- "elements": [
- {"type": "mrkdwn", "text": f"*Requested by:* {requester} • *Status:* {ticket.get_status_display()}"}
- ],
- },
+ {"type": "section", "text": {"type": "mrkdwn", "text": title}},
+ {"type": "context", "elements": [{"type": "mrkdwn", "text": _card_summary(card, compact=compact)}]},
]
- if opening_message:
- blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": f">>> {opening_message}"}})
- return {"blocks": blocks}
+ if compact:
+ return blocks
+ if card.chart:
+ chart = f"```{escape_slack_mrkdwn(card.chart)}```"
+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": chart}})
+ body = (card.body or "").strip()
+ if body:
+ text = _truncate(escape_slack_mrkdwn(body), _MAX_BODY_CHARS)
+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": text}})
+ buttons = [{"type": "button", "text": {"type": "plain_text", "text": "Open in PostHog"}, "url": link}]
+ if card.button:
+ buttons.append(
+ {"type": "button", "text": {"type": "plain_text", "text": card.button.label}, "url": card.button.url}
+ )
+ blocks.append({"type": "actions", "elements": buttons})
+ return blocks
def _claim_invite_slot(slack_team_id: str, channel: str) -> bool:
@@ -454,6 +510,455 @@ def _attach_public_slack_thread_reference(
)
+@frozen
+class _UnfurlContext:
+ slack: SlackIntegration
+ integration: Integration
+ team: Team
+ user: User
+ uac: UserAccessControl
+ event: dict
+ public_channel_cache: dict[str, bool] = dataclasses.field(default_factory=dict)
+ owner_access_cache: dict[str, bool] = dataclasses.field(default_factory=dict)
+
+
+def _count(value: int, noun: str) -> str:
+ return f"{value:,} {noun}{'' if value == 1 else 's'}"
+
+
+def _humanize(value: str) -> str:
+ return value.replace("_", " ").capitalize()
+
+
+def _uuid(value: str) -> UUID | None:
+ try:
+ return UUID(value)
+ except ValueError:
+ return None
+
+
+def _bar(fraction: float) -> str:
+ filled = round(min(max(fraction, 0.0), 1.0) * _CHART_WIDTH)
+ return "█" * filled + "░" * (_CHART_WIDTH - filled)
+
+
+def _chart_label(value: object, max_len: int = _CHART_LABEL_CHARS) -> str:
+ return _truncate(str(value or "").replace("`", "'"), max_len)
+
+
+def _capped_lines(lines: list[str]) -> list[str]:
+ if len(lines) <= _MAX_CHART_LINES:
+ return lines
+ kept = _MAX_CHART_LINES - 1
+ return [*lines[:kept], f"+ {len(lines) - kept} more"]
+
+
+@frozen
+class _ChartRow:
+ label: str
+ bar: str
+ value: str
+
+
+def _chart_rows(rows: list[_ChartRow]) -> str | None:
+ if not rows:
+ return None
+ width = max(len(row.label) for row in rows)
+ lines = [f"{row.label.ljust(width)} {row.bar} {row.value}".rstrip() for row in rows]
+ return "\n".join(_capped_lines(lines))
+
+
+def _tile_grid(names: list[str]) -> str | None:
+ if not names:
+ return None
+ width = _CHART_WIDTH + 2
+ cells = [f"▪ {_chart_label(name, width)}" for name in names[:_MAX_GRID_TILES]]
+ rows = [cells[index : index + 2] for index in range(0, len(cells), 2)]
+ lines = [" ".join(cell.ljust(width + 2) for cell in row).rstrip() for row in rows]
+ if len(names) > _MAX_GRID_TILES:
+ lines.append(f"+ {len(names) - _MAX_GRID_TILES} more")
+ return "\n".join(lines)
+
+
+def _question_list(questions: object) -> str | None:
+ if not isinstance(questions, list):
+ return None
+ texts = [str(question.get("question") or "").strip() for question in questions if isinstance(question, dict)]
+ lines = [f"{index}. {_truncate(text, 60)}" for index, text in enumerate(texts, 1)]
+ return "\n".join(_capped_lines(lines)) or None
+
+
+def _by(user: User | None) -> tuple[str, ...]:
+ return (f"By {user.first_name}",) if user and user.first_name else ()
+
+
+def _user(user_id: int | None) -> User | None:
+ return User.objects.filter(id=user_id).only("first_name").first() if user_id else None
+
+
+def _date_range(query: object) -> str | None:
+ source = query.get("source") if isinstance(query, dict) else None
+ date_range = source.get("dateRange") if isinstance(source, dict) else None
+ date_from = date_range.get("date_from") if isinstance(date_range, dict) else None
+ if not isinstance(date_from, str):
+ return None
+ if date_from in _NAMED_DATE_RANGES:
+ return _NAMED_DATE_RANGES[date_from]
+ match = re.fullmatch(r"-(\d+)([hdwmy])", date_from)
+ if not match:
+ return None
+ amount, unit = int(match[1]), _DATE_RANGE_UNITS[match[2]]
+ return f"Last {unit}" if amount == 1 else f"Last {_count(amount, unit)}"
+
+
+def _primary_metric(metrics: object) -> str | None:
+ first = metrics[0] if isinstance(metrics, list) and metrics else None
+ name = first.get("name") if isinstance(first, dict) else None
+ return name if isinstance(name, str) and name else None
+
+
+def _variant_rows(variants: list[dict]) -> list[_ChartRow]:
+ return [
+ _ChartRow(
+ label=_chart_label(variant["key"]),
+ bar=_bar(variant["rollout_percentage"] / 100),
+ value=f"{variant['rollout_percentage']}%",
+ )
+ for variant in variants
+ ]
+
+
+def _flag_variants(flag: FeatureFlag) -> list[dict]:
+ try:
+ return flag.variants
+ except ConfigFormatError:
+ return []
+
+
+def _insight_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
+ insight = Insight.objects.filter(team_id=ctx.team.pk, short_id=ref).first()
+ if not insight:
+ return "not_found"
+ level = ctx.uac.get_user_access_level(insight)
+ if not level or not access_level_satisfied_for_resource("insight", level, "viewer"):
+ return "no_access"
+ return _UnfurlCard(
+ label=_insight_resource_label(insight),
+ title=insight.name or insight.derived_name or "Untitled",
+ details=(*filter(None, [_date_range(insight.query)]), *_by(insight.created_by)),
+ body=insight.description,
+ timestamp=insight.last_modified_at,
+ chart_insight_id=insight.id,
+ )
+
+
+def _dashboard_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
+ dashboard = Dashboard.objects.filter(pk=ref, team_id=ctx.team.pk).first() if ref.isdigit() else None
+ if not dashboard:
+ return "not_found"
+ level = ctx.uac.get_user_access_level(dashboard)
+ if not level or not access_level_satisfied_for_resource("dashboard", level, "viewer"):
+ return "no_access"
+ tiles = (
+ DashboardTile.objects.filter(dashboard=dashboard, insight__isnull=False, insight__deleted=False)
+ .exclude(deleted=True)
+ .select_related("insight")
+ .order_by("id")
+ )
+ insights = [tile.insight for tile in tiles if tile.insight]
+ ctx.uac.preload_object_access_controls(cast(list, insights))
+ names = [
+ insight.name or insight.derived_name or "Untitled"
+ for insight in insights
+ if ctx.uac.check_access_level_for_object(insight, required_level="viewer")
+ ]
+ return _UnfurlCard(
+ label="Dashboard",
+ title=dashboard.name or "Untitled",
+ details=(_count(len(names), "insight"), *_by(dashboard.created_by)),
+ chart=_tile_grid(names),
+ body=dashboard.description,
+ )
+
+
+def _ticket_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
+ # Ticket numbers are per-project sequential, so the same number exists in every project.
+ # Unlike insights/dashboards (globally-unique ids, safe to resolve within the connected
+ # project), a link that names a different project must not resolve to our project's ticket
+ # of the same number — refuse rather than show the wrong ticket.
+ url_team_id = _url_team_id(url)
+ if url_team_id is not None and url_team_id != ctx.team.pk:
+ return "other_project"
+ ticket = _find_ticket(ctx.team.pk, ref)
+ if not ticket:
+ return "not_found"
+ if not ctx.uac.check_access_level_for_object(ticket, required_level="viewer"):
+ return "no_access"
+ return _UnfurlCard(
+ label="Support ticket",
+ title=f"Ticket #{ticket.ticket_number}",
+ status=ticket.get_status_display(),
+ details=(
+ f"Requested by {_ticket_requester(ctx.team, ticket)}",
+ *((f"{ticket.get_priority_display()} priority",) if ticket.priority else ()),
+ ),
+ body=_ticket_opening_message(ctx.team.pk, ticket.id),
+ timestamp=ticket.created_at,
+ timestamp_label="Opened",
+ )
+
+
+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"
+ 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"
+ try:
+ _attach_public_slack_thread_reference(
+ slack=ctx.slack,
+ integration=ctx.integration,
+ task=task,
+ event=ctx.event,
+ shared_by_slack_user_id=ctx.event["user"],
+ public_channel_cache=ctx.public_channel_cache,
+ owner_access_cache=ctx.owner_access_cache,
+ )
+ except Exception:
+ logger.exception("slack_task_reference_attach_failed", task_id=str(task.id), team_id=ctx.team.pk)
+ pr_url = tasks_facade.get_latest_pr_url_by_task([task.id]).get(str(task.id))
+ dto = next(iter(tasks_facade.get_tasks_by_ids([task.id], [ctx.team.pk])), None)
+ return _UnfurlCard(
+ label="Task",
+ title=task.title,
+ status=task.latest_run_status,
+ details=(*((dto.repository,) if dto and dto.repository else ()), *_by(_user(task.created_by_id))),
+ button=_CardButton(label="View pull request", url=pr_url) if pr_url else None,
+ timestamp=dto.updated_at if dto else None,
+ )
+
+
+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:
+ return "not_found"
+ if not canvas_access.canvas_is_visible(team_id=ctx.team.pk, canvas_id=ref, user_id=ctx.user.id):
+ return "no_access"
+ owner = _user(canvas_access.canvas_owner_id(team_id=ctx.team.pk, canvas_id=ref))
+ return _UnfurlCard(label="Canvas", title=summary.name, details=(f"Space: {summary.channel_name}", *_by(owner)))
+
+
+def _notebook_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
+ notebook = (
+ Notebook.objects.filter(team_id=ctx.team.pk, short_id=ref, deleted=False)
+ .exclude(visibility=Notebook.Visibility.INTERNAL)
+ .defer("content", "text_content")
+ .annotate(excerpt=Substr("text_content", 1, _MAX_BODY_CHARS + 1))
+ .first()
+ )
+ if not notebook:
+ return "not_found"
+ if not ctx.uac.check_access_level_for_object(notebook, required_level="viewer"):
+ return "no_access"
+ return _UnfurlCard(
+ label="Notebook",
+ title=notebook.title or "Untitled",
+ details=_by(notebook.created_by),
+ body=notebook.excerpt,
+ timestamp=notebook.last_modified_at,
+ )
+
+
+def _flag_chart(conditions: list[dict], variants: list[dict]) -> str | None:
+ rows = _variant_rows(variants)
+ if len(conditions) == 1 and not conditions[0].get("properties"):
+ rollout = condition_rollout_percentage(conditions[0])
+ rows.insert(0, _ChartRow(label="Rollout", bar=_bar(rollout / 100), value=f"{rollout}% of users"))
+ return _chart_rows(rows)
+
+
+def _flag_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
+ flag = FeatureFlag.objects.filter(team_id=ctx.team.pk, pk=ref, deleted=False).first()
+ if not flag:
+ return "not_found"
+ if not ctx.uac.check_access_level_for_object(flag, required_level="viewer"):
+ return "no_access"
+ try:
+ conditions: list[dict] | None = flag.conditions
+ except ConfigFormatError:
+ conditions = None
+ condition_count = _count(len(conditions), "release condition") if conditions is not None else None
+ return _UnfurlCard(
+ label="Feature flag",
+ title=flag.key,
+ status="Active" if flag.active else "Disabled",
+ details=(*filter(None, [condition_count]), *_by(flag.created_by)),
+ chart=_flag_chart(conditions or [], _flag_variants(flag)),
+ body=flag.name,
+ timestamp=flag.updated_at,
+ )
+
+
+def _experiment_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
+ experiment = (
+ Experiment.objects.filter(team_id=ctx.team.pk, pk=ref, deleted=False).select_related("feature_flag").first()
+ if ref.isdigit()
+ else None
+ )
+ if not experiment:
+ return "not_found"
+ if not ctx.uac.check_access_level_for_object(experiment, required_level="viewer"):
+ return "no_access"
+ details: list[str] = []
+ if experiment.start_date:
+ days = ((experiment.end_date or timezone.now()) - experiment.start_date).days + 1
+ details.append(f"Ran {_count(days, 'day')}" if experiment.end_date else f"Day {days}")
+ metric = _primary_metric(experiment.metrics)
+ if metric:
+ details.append(f"Metric: {metric}")
+ return _UnfurlCard(
+ label="Experiment",
+ title=experiment.name,
+ status=_humanize(experiment.status_label),
+ details=tuple(details),
+ chart=_chart_rows(_variant_rows(_flag_variants(experiment.feature_flag))),
+ body=experiment.description,
+ timestamp=experiment.updated_at,
+ )
+
+
+def _survey_status(survey: Survey) -> str:
+ if survey.archived:
+ return "Archived"
+ if survey.end_date:
+ return "Completed"
+ if survey.start_date and survey.start_date > timezone.now():
+ return "Scheduled"
+ return "Running" if survey.start_date else "Draft"
+
+
+def _survey_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
+ survey = Survey.objects.filter(team_id=ctx.team.pk, pk=ref).first() if _uuid(ref) else None
+ if not survey:
+ return "not_found"
+ if not ctx.uac.check_access_level_for_object(survey, required_level="viewer"):
+ return "no_access"
+ return _UnfurlCard(
+ label="Survey",
+ title=survey.name,
+ status=_survey_status(survey),
+ details=(_count(len(survey.questions or []), "question"), *_by(survey.created_by)),
+ chart=_question_list(survey.questions),
+ body=survey.description,
+ timestamp=survey.updated_at,
+ )
+
+
+def _cohort_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
+ cohort = Cohort.objects.filter(team_id=ctx.team.pk, pk=ref, deleted=False).first() if ref.isdigit() else None
+ if not cohort:
+ return "not_found"
+ if not ctx.uac.check_access_level_for_object(cohort, required_level="viewer"):
+ return "no_access"
+ return _UnfurlCard(
+ label="Static cohort" if cohort.is_static else "Cohort",
+ title=cohort.name or "Untitled",
+ details=(*((_count(cohort.count, "person"),) if cohort.count is not None else ()), *_by(cohort.created_by)),
+ body=cohort.description,
+ timestamp=cohort.last_calculation,
+ timestamp_label="Calculated",
+ )
+
+
+def _error_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
+ issue_id = _uuid(ref)
+ if issue_id is None:
+ return "not_found"
+ try:
+ issue = error_tracking_facade.get_issue(issue_id, ctx.team.pk)
+ except error_tracking_facade.IssueNotFoundError:
+ return "not_found"
+ access = ctx.uac.access_level_for_resource("error_tracking")
+ if not access or not access_level_satisfied_for_resource("error_tracking", access.access_level, "viewer"):
+ return "no_access"
+ return _UnfurlCard(
+ label="Error issue",
+ title=issue.name or "Untitled issue",
+ status=_humanize(issue.status),
+ details=(f"{issue.severity.capitalize()} severity",) if issue.severity else (),
+ body=issue.description,
+ timestamp=issue.first_seen,
+ timestamp_label="First seen",
+ )
+
+
+def _report_card(ctx: _UnfurlContext, ref: str, url: str) -> _UnfurlCard | _SkipReason:
+ report = (
+ SignalReport.objects.filter(team_id=ctx.team.pk, pk=ref).exclude(status=SignalReport.Status.DELETED).first()
+ if _uuid(ref)
+ else None
+ )
+ if not report:
+ return "not_found"
+ if not may_read_reports(user=ctx.user, team=ctx.team):
+ return "no_access"
+ return _UnfurlCard(
+ label="Inbox report",
+ title=report.title or "Untitled report",
+ status=_humanize(report.status),
+ details=(_count(report.signal_count, "signal"),),
+ body=report.summary,
+ timestamp=report.updated_at,
+ )
+
+
+_CARD_BUILDERS: dict[str, Callable[[_UnfurlContext, str, str], _UnfurlCard | _SkipReason]] = {
+ "insight": _insight_card,
+ "dashboard": _dashboard_card,
+ "ticket": _ticket_card,
+ "task": _task_card,
+ "canvas": _canvas_card,
+ "notebook": _notebook_card,
+ "flag": _flag_card,
+ "experiment": _experiment_card,
+ "survey": _survey_card,
+ "cohort": _cohort_card,
+ "error": _error_card,
+ "report": _report_card,
+}
+
+
+def _unfurls(cards: dict[str, tuple[str, _UnfurlCard]], *, compact: bool, invite: dict | None) -> dict[str, dict]:
+ unfurls = {
+ url: {"blocks": _card_blocks(card, kind=kind, url=url, compact=compact)} for url, (kind, card) in cards.items()
+ }
+ if invite:
+ next(iter(unfurls.values()))["blocks"].append(invite)
+ return unfurls
+
+
+def _post_unfurls(slack: SlackIntegration, event: dict, unfurls: dict[str, dict]) -> str | None:
+ try:
+ slack.client.chat_unfurl(
+ **chat_unfurl_kwargs(
+ channel=event["channel"],
+ ts=event["message_ts"],
+ unfurls=unfurls,
+ unfurl_id=event.get("unfurl_id"),
+ source=event.get("source"),
+ )
+ )
+ except SlackApiError as e:
+ error = (e.response.get("error") if e.response is not None else None) or "slack_api_error"
+ logger.warning("slack_link_unfurl_chat_unfurl_failed", channel=event["channel"], error=error)
+ return error
+ except Exception:
+ logger.exception("slack_link_unfurl_chat_unfurl_failed", channel=event["channel"])
+ return "unknown"
+ return None
+
+
def start_unfurl_charts(
*,
integration: Integration,
@@ -483,7 +988,7 @@ def start_unfurl_charts(
unfurl_id=event.get("unfurl_id"),
source=event.get("source"),
unfurls=unfurls,
- charts=charts[:_MAX_UNFURL_CHARTS],
+ charts=charts,
export_task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,
)
try:
@@ -537,19 +1042,15 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
Unfurl supported PostHog resource links with metadata.
Scope is always the Slack-connected project (`integration.team`); `resolve_slack_user` enforces
- that the sharer can access it. Insights, dashboards, and tickets add a per-resource
- access-control check. Ticket links naming a different project are also refused because ticket
- numbers are per-project and could otherwise resolve to the wrong ticket.
+ that the sharer can access it. Each resource adds its own access check. Ticket and task links
+ naming a different project are also refused because ticket numbers are per-project and could
+ otherwise resolve to the wrong ticket.
"""
slack = SlackIntegration(integration)
channel = event.get("channel")
message_ts = event.get("message_ts")
slack_user_id = event.get("user")
- unfurl_id = event.get("unfurl_id")
- source = event.get("source")
links = event.get("links") or []
- public_channel_cache: dict[str, bool] = {}
- owner_access_cache: dict[str, bool] = {}
if not channel or not message_ts or not slack_user_id or not links:
logger.info("slack_link_unfurl_skip_missing_fields", has_channel=bool(channel), has_ts=bool(message_ts))
@@ -577,166 +1078,102 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
user = user_context.user
team = integration.team
- uac = UserAccessControl(user, team=team)
+ ctx = _UnfurlContext(
+ slack=slack,
+ integration=integration,
+ team=team,
+ user=user,
+ uac=UserAccessControl(user, team=team),
+ event=event,
+ )
- unfurls: dict[str, dict] = {}
- unfurled_kinds: list[str] = []
- # Carries the kind alongside the url so the invite never has to guess which payload is first.
- first_unfurled: tuple[str, str] | None = None
+ cards: dict[str, tuple[str, _UnfurlCard]] = {}
# Every resource we recognized but chose not to unfurl, so a report of "no unfurl appeared"
# can be answered from logs instead of by re-deriving the path by hand.
skipped: list[dict[str, str]] = []
- chart_requests: list[SlackUnfurlChartRequest] = []
for link_obj in links:
raw_url = link_obj.get("url")
if not raw_url:
continue
- parsed = parse_posthog_resource_link(raw_url)
- if not parsed:
+ ref = parse_posthog_resource_link(raw_url)
+ if not ref:
+ known = object_ref_for_url(raw_url)
+ if known and known.kind not in _CARD_BUILDERS:
+ skipped.append({"kind": known.kind, "reason": "unsupported"})
continue
- kind, ref = parsed
-
# Resource ids repeat across regions, so a link for the other region would otherwise resolve
# to whatever local resource carries the same id and unfurl the wrong thing. Routing sends
# single-region messages to the region that owns them; this catches the leftover case of one
# message carrying links for both.
url_region = link_url_region(raw_url)
if url_region is not None and url_region != get_instance_region():
- skipped.append({"kind": kind, "ref": str(ref), "reason": "other_region"})
+ skipped.append({"kind": ref.kind, "ref": ref.id, "reason": "other_region"})
continue
- if kind == "insight":
- if not isinstance(ref, str):
- continue
- insight = Insight.objects.filter(team_id=team.pk, short_id=ref).first()
- if not insight:
- skipped.append({"kind": kind, "ref": ref, "reason": "not_found"})
- continue
- level = uac.get_user_access_level(insight)
- if not level or not access_level_satisfied_for_resource("insight", level, "viewer"):
- skipped.append({"kind": kind, "ref": ref, "reason": "no_access"})
- continue
- title = insight.name or insight.derived_name or "Untitled"
- desc = (insight.description or "").strip() or None
- unfurls[raw_url] = _unfurl_payload(
- resource_label=_insight_resource_label(insight), title=title, description=desc
- )
- chart_requests.append(SlackUnfurlChartRequest(url=raw_url, insight_id=insight.id, title=title))
- elif kind == "dashboard":
- if not isinstance(ref, int):
- continue
- dashboard = Dashboard.objects.filter(pk=ref, team_id=team.pk).first()
- if not dashboard:
- skipped.append({"kind": kind, "ref": str(ref), "reason": "not_found"})
- continue
- level = uac.get_user_access_level(dashboard)
- if not level or not access_level_satisfied_for_resource("dashboard", level, "viewer"):
- skipped.append({"kind": kind, "ref": str(ref), "reason": "no_access"})
- continue
- title = dashboard.name or "Untitled"
- desc = (dashboard.description or "").strip() or None
- unfurls[raw_url] = _unfurl_payload(resource_label="Dashboard", title=title, description=desc)
- elif kind == "ticket":
- if not isinstance(ref, str):
- continue
- # Ticket numbers are per-project sequential, so the same number exists in every project.
- # Unlike insights/dashboards (globally-unique ids, safe to resolve within the connected
- # project), a link that names a different project must not resolve to our project's ticket
- # of the same number — refuse rather than show the wrong ticket.
- url_team_id = _url_team_id(raw_url)
- if url_team_id is not None and url_team_id != team.pk:
- skipped.append({"kind": kind, "ref": ref, "reason": "other_project"})
- continue
- ticket = _find_ticket(team.pk, ref)
- if not ticket:
- skipped.append({"kind": kind, "ref": ref, "reason": "not_found"})
- continue
- if not uac.check_access_level_for_object(ticket, required_level="viewer"):
- skipped.append({"kind": kind, "ref": ref, "reason": "no_access"})
- continue
- unfurls[raw_url] = _ticket_unfurl_payload(
- url=raw_url,
- ticket=ticket,
- requester=escape_slack_mrkdwn(_ticket_requester(team, ticket)),
- opening_message=_ticket_opening_message(team.pk, ticket.id),
- )
- elif kind == "task":
- if not isinstance(ref, str):
- continue
- url_team_id = _url_team_id(raw_url)
- if url_team_id is not None and url_team_id != team.pk:
- skipped.append({"kind": kind, "ref": ref, "reason": "other_project"})
- continue
- task = tasks_facade.get_task_for_slack_unfurl(ref, team.pk, user.id)
- if task is None:
- skipped.append({"kind": kind, "ref": ref, "reason": "not_found_or_no_access"})
- continue
- label = "Task" if task.latest_run_status is None else f"Task · {task.latest_run_status}"
- unfurls[raw_url] = _unfurl_payload(
- resource_label=label, title=escape_slack_mrkdwn(task.title), description=None
- )
- try:
- _attach_public_slack_thread_reference(
- slack=slack,
- integration=integration,
- task=task,
- event=event,
- shared_by_slack_user_id=slack_user_id,
- public_channel_cache=public_channel_cache,
- owner_access_cache=owner_access_cache,
- )
- except Exception:
- logger.exception("slack_task_reference_attach_failed", task_id=str(task.id), team_id=team.pk)
-
- if raw_url in unfurls:
- unfurled_kinds.append(kind)
- if first_unfurled is None:
- first_unfurled = (raw_url, kind)
+ card = _CARD_BUILDERS[ref.kind](ctx, ref.id, raw_url)
+ if isinstance(card, str):
+ skipped.append({"kind": ref.kind, "ref": ref.id, "reason": card})
+ continue
+ cards[raw_url] = (ref.kind, card)
logger.info(
"slack_app_link_unfurl_result",
team_id=team.pk,
integration_id=integration.id,
channel=channel,
- unfurled=len(unfurls),
+ unfurled=len(cards),
skipped=skipped,
)
- if not unfurls:
+ if not cards:
return
- invite = None
- if first_unfurled is not None:
- invite_url, invite_kind = first_unfurled
- invite = _build_unfurl_invite(integration, invite_kind, channel)
- if invite:
- unfurls[invite_url]["blocks"].append(invite)
-
- try:
- slack.client.chat_unfurl(
- **chat_unfurl_kwargs(channel=channel, ts=message_ts, unfurls=unfurls, unfurl_id=unfurl_id, source=source)
- )
- except Exception:
- logger.exception("slack_link_unfurl_chat_unfurl_failed", team_id=team.pk)
- else:
- charts_queued = bool(chart_requests) and _queue_unfurl_charts(
- integration=integration,
- user=user,
- event=event,
- unfurls=unfurls,
- charts=chart_requests,
- )
+ invite_kind, _ = next(iter(cards.values()))
+ invite = _build_unfurl_invite(integration, invite_kind, channel)
+ kinds = sorted({kind for kind, _ in cards.values()})
+ for compact in (True,) if len(cards) > 1 else (False, True):
+ unfurls = _unfurls(cards, compact=compact, invite=invite)
+ error = _post_unfurls(slack, event, unfurls)
+ if error is None:
+ break
capture_slack_event(
integration,
- "slack app link unfurled",
+ "slack app link unfurl failed",
slack_user_id=slack_user_id,
posthog_user=user,
- kinds=sorted(set(unfurled_kinds)),
- unfurled_count=len(unfurls),
- skipped_count=len(skipped),
- followup_invite_shown=invite is not None,
- charts_queued=charts_queued,
+ kinds=kinds,
+ compact=compact,
+ error=error,
)
+ if error not in _REJECTED_PAYLOAD_ERRORS:
+ return
+ else:
+ return
+
+ chart_requests = [
+ SlackUnfurlChartRequest(url=url, insight_id=card.chart_insight_id, title=card.title)
+ for url, (_, card) in cards.items()
+ if card.chart_insight_id is not None and not compact
+ ]
+ charts_queued = bool(chart_requests) and _queue_unfurl_charts(
+ integration=integration,
+ user=user,
+ event=event,
+ unfurls=unfurls,
+ charts=chart_requests,
+ )
+ capture_slack_event(
+ integration,
+ "slack app link unfurled",
+ slack_user_id=slack_user_id,
+ posthog_user=user,
+ kinds=kinds,
+ unfurled_count=len(unfurls),
+ compact=compact,
+ skipped_count=len(skipped),
+ followup_invite_shown=invite is not None,
+ charts_queued=charts_queued,
+ )
diff --git a/products/slack_app/backend/tests/logic/test_link_unfurl_charts.py b/products/slack_app/backend/tests/logic/test_link_unfurl_charts.py
index 79956b9d1124..dbb1eecd92d7 100644
--- a/products/slack_app/backend/tests/logic/test_link_unfurl_charts.py
+++ b/products/slack_app/backend/tests/logic/test_link_unfurl_charts.py
@@ -23,7 +23,8 @@ from products.slack_app.backend.logic.link_unfurl_charts import post_unfurl_char
_URL = "https://us.posthog.com/project/1/insights/abc123"
_SHORT_URL = "https://us.posthog.com/i/abc123"
-_TEXT_CARD = {"type": "section", "text": {"type": "mrkdwn", "text": "*Weekly active users • Trends insight*"}}
+_TITLE = {"type": "section", "text": {"type": "mrkdwn", "text": "📈 *<https://us.posthog.com|Weekly active users>*"}}
+_BUTTONS = {"type": "actions", "elements": []}
def _slack_error(code: str, status_code: int) -> SlackApiError:
@@ -63,7 +64,7 @@ class TestLinkUnfurlCharts(BaseTest):
message_ts="123.456",
unfurl_id=None,
source=None,
- unfurls={url: {"blocks": [_TEXT_CARD]} for url in urls},
+ unfurls={url: {"blocks": [_TITLE, _BUTTONS]} for url in urls},
charts=[
SlackUnfurlChartRequest(url=url, insight_id=self.insight.id, title="Weekly active users")
for url in urls
@@ -91,35 +92,46 @@ class TestLinkUnfurlCharts(BaseTest):
image_urls_by_insight={self.insight.id: "https://example.com/chart.png"},
)
- @parameterized.expand([("project_access", True), ("project_access_revoked", False)])
- def test_targets_render_each_insight_once_and_only_with_project_access(
- self, _name: str, project_access: bool
+ def _sharer(self, kind: str) -> User:
+ if kind == "project_access_revoked":
+ return self._deny_project_access()
+ if kind == "deactivated":
+ self.user.is_active = False
+ self.user.save()
+ return self.user
+
+ @parameterized.expand(
+ [("member", True), ("project_access_revoked", False), ("deactivated", False)],
+ )
+ def test_targets_render_each_insight_once_and_only_for_an_active_member(
+ self, sharer: str, expect_render: bool
) -> None:
- user = self.user if project_access else self._deny_project_access()
+ user = self._sharer(sharer)
targets = unfurl_chart_targets(self._inputs(urls=(_URL, _SHORT_URL), user=user))
- assert targets.insight_ids == ([self.insight.id] if project_access else [])
+ assert targets.insight_ids == ([self.insight.id] if expect_render else [])
@parameterized.expand(
[
- ("allowed", True, True, True),
- ("public_sharing_turned_off", False, True, False),
- ("project_access_revoked", True, False, False),
+ ("allowed", True, "member", True),
+ ("public_sharing_turned_off", False, "member", False),
+ ("project_access_revoked", True, "project_access_revoked", False),
+ ("deactivated", True, "deactivated", False),
]
)
@patch("products.slack_app.backend.logic.link_unfurl_charts.SlackIntegration")
- def test_post_adds_the_chart_under_the_title_only_when_allowed(
+ def test_post_adds_the_chart_above_the_buttons_only_when_allowed(
self,
_name: str,
public_sharing: bool,
- project_access: bool,
+ sharer: str,
expect_unfurl: bool,
mock_slack: MagicMock,
) -> None:
self.organization.allow_publicly_shared_resources = public_sharing
self.organization.save()
- user = self.user if project_access else self._deny_project_access()
+ user = self._sharer(sharer)
self._post(self._inputs(user=user))
@@ -128,7 +140,7 @@ class TestLinkUnfurlCharts(BaseTest):
chat_unfurl.assert_not_called()
return
blocks = chat_unfurl.call_args.kwargs["unfurls"][_URL]["blocks"]
- assert blocks[0] == _TEXT_CARD
+ assert [blocks[0], blocks[2]] == [_TITLE, _BUTTONS]
assert blocks[1]["type"] == "image"
assert blocks[1]["alt_text"] == "Weekly active users"
assert blocks[1]["image_url"].startswith("http")
diff --git a/products/slack_app/backend/tests/test_link_unfurl.py b/products/slack_app/backend/tests/test_link_unfurl.py
index e1e36a9a9d79..669039dc3c76 100644
--- a/products/slack_app/backend/tests/test_link_unfurl.py
+++ b/products/slack_app/backend/tests/test_link_unfurl.py
@@ -10,6 +10,9 @@ from django.test.client import RequestFactory
from django.utils import timezone
from parameterized import parameterized
+from slack_sdk.errors import SlackApiError
+from slack_sdk.models.blocks import Block
+from slack_sdk.web.slack_response import SlackResponse
from structlog.testing import capture_logs
from posthog.constants import AvailableFeature
@@ -17,69 +20,82 @@ from posthog.models import User
from posthog.models.comment import Comment
from posthog.models.integration import Integration
from posthog.models.organization import Organization
+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 products.access_control.backend.models.access_control import AccessControl
+from products.canvas.backend.facade import testing as canvas_testing
+from products.cohorts.backend.models.cohort import Cohort
from products.conversations.backend.models.ticket import Ticket
from products.dashboards.backend.models.dashboard import Dashboard
+from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.error_tracking.backend.facade import testing as error_tracking_testing
+from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.facade.models import Insight
+from products.signals.backend.models import SignalReport
from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region
from products.slack_app.backend.models import SlackChannel
from products.slack_app.backend.services.slack_auth import write_auth_state_ok
from products.slack_app.backend.services.slack_scopes import REQUIRED_SLACK_SCOPES
from products.slack_app.backend.slack_link_unfurl import (
+ _card_blocks,
+ _date_range,
+ _flag_chart,
_insight_resource_label,
+ _question_list,
+ _tile_grid,
+ _UnfurlCard,
handle_posthog_link_unfurl,
parse_posthog_resource_link,
)
from products.slack_app.backend.tasks import start_slack_unfurl_charts
-from products.tasks.backend.models import Task
+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"
-class TestParsePosthogResourceLink:
- def test_project_insight(self):
- assert parse_posthog_resource_link("https://us.posthog.com/project/42/insights/abc123") == ("insight", "abc123")
-
- def test_project_insight_with_subpath(self):
- assert parse_posthog_resource_link("https://eu.posthog.com/project/42/insights/abc123/edit") == (
- "insight",
- "abc123",
- )
-
- def test_short_insight_path(self):
- assert parse_posthog_resource_link("https://app.posthog.com/i/xyz789") == ("insight", "xyz789")
-
- def test_project_dashboard(self):
- assert parse_posthog_resource_link("https://us.posthog.com/project/3/dashboard/99") == ("dashboard", 99)
-
- def test_skips_insight_new(self):
- assert parse_posthog_resource_link("https://x.com/project/1/insights/new") is None
-
- def test_support_ticket_by_number(self):
- assert parse_posthog_resource_link("https://us.posthog.com/project/42/support/tickets/123") == ("ticket", "123")
-
- def test_support_ticket_by_uuid_ignores_fragment(self):
- assert parse_posthog_resource_link("https://app.posthog.com/support/tickets/abc-uuid#panel=discussion") == (
- "ticket",
- "abc-uuid",
- )
- def test_task(self):
- task_id = "c76f58f4-4c64-4cd7-825d-4ef89f6dd4ac"
- assert parse_posthog_resource_link(f"https://us.posthog.com/project/42/tasks/{task_id}") == (
- "task",
- task_id,
- )
-
- def test_rejects_invalid_task_id(self):
- assert parse_posthog_resource_link("https://us.posthog.com/project/42/tasks/not-a-uuid") is None
-
- def test_skips_ticket_new(self):
- assert parse_posthog_resource_link("https://x.com/support/tickets/new") is None
-
- def test_unrelated_url(self):
- assert parse_posthog_resource_link("https://example.com/foo") is None
+class TestParsePosthogResourceLink:
+ @parameterized.expand(
+ [
+ ("project_insight", "https://us.posthog.com/project/42/insights/abc123", "insight", "abc123"),
+ ("insight_subpath", "https://eu.posthog.com/project/42/insights/abc123/edit", "insight", "abc123"),
+ ("short_insight", "https://app.posthog.com/i/xyz789", "insight", "xyz789"),
+ ("bi_worksheet", "https://us.posthog.com/project/42/bi/xyz789", "insight", "xyz789"),
+ ("dashboard", "https://us.posthog.com/project/3/dashboard/99", "dashboard", "99"),
+ ("ticket", "https://us.posthog.com/project/42/support/tickets/123", "ticket", "123"),
+ (
+ "ticket_fragment",
+ "https://app.posthog.com/support/tickets/abc-uuid#panel=discussion",
+ "ticket",
+ "abc-uuid",
+ ),
+ ("task", f"https://us.posthog.com/project/42/tasks/{_TASK_ID}", "task", _TASK_ID),
+ ("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),
+ ("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"),
+ ("flag", "https://us.posthog.com/project/42/feature_flags/412", "flag", "412"),
+ ("inbox_report", f"https://us.posthog.com/project/42/inbox/reports/{_TASK_ID}", "report", _TASK_ID),
+ ("insight_new", "https://x.com/project/1/insights/new", None, None),
+ ("ticket_new", "https://x.com/support/tickets/new", None, None),
+ ("flag_by_key", "https://us.posthog.com/project/42/feature_flags/my-flag", None, None),
+ ("replay", "https://us.posthog.com/project/42/replay/0192f0a0", None, None),
+ ("opted_out", "https://us.posthog.com/project/42/insights/abc123?unfurl=false", None, None),
+ ("unrelated", "https://example.com/foo", None, None),
+ ]
+ )
+ def test_parse(self, _name: str, url: str, kind: str | None, object_id: str | None) -> None:
+ expected = ObjectRef(kind=kind, id=object_id) if kind and object_id else None
+ assert parse_posthog_resource_link(url) == expected
class TestInsightResourceLabel:
@@ -114,6 +130,92 @@ class TestInsightResourceLabel:
assert _insight_resource_label(insight) == "Insight"
+class TestCardText:
+ @parameterized.expand([("full", False), ("compact", True)])
+ def test_card_blocks_stay_within_slack_text_limits(self, _name: str, compact: bool) -> None:
+ card = _UnfurlCard(label="Insight", title="T" * 5000, details=("D" * 5000,))
+ url = "https://us.posthog.com/project/2/insights/abc123?dashboard=1#q=" + "x" * 5000
+
+ blocks = _card_blocks(card, kind="insight", url=url, compact=compact)
+
+ texts = [block["text"]["text"] for block in blocks if "text" in block]
+ texts += [element["text"] for block in blocks if block["type"] == "context" for element in block["elements"]]
+ links = [element["url"] for block in blocks if block["type"] == "actions" for element in block["elements"]]
+ assert all(len(text) <= 3000 for text in texts)
+ assert "/insights/abc123?dashboard=1&utm_source=slack" in texts[0]
+ assert all(len(link) <= 3000 and "/insights/abc123" in link for link in links)
+
+ @parameterized.expand(
+ [
+ (
+ "simple_rollout",
+ {"groups": [{"properties": [], "rollout_percentage": 25}]},
+ ["Rollout █████░░░░░░░░░░░░░░░ 25% of users"],
+ ),
+ (
+ "multivariate",
+ {
+ "groups": [{"properties": [], "rollout_percentage": None}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ [
+ "Rollout ████████████████████ 100% of users",
+ "control ██████████░░░░░░░░░░ 50%",
+ "test ██████████░░░░░░░░░░ 50%",
+ ],
+ ),
+ ("conditions_only", {"groups": [{"properties": [{"key": "email"}], "rollout_percentage": 50}]}, None),
+ ]
+ )
+ def test_chart(self, _name: str, filters: dict, expected_lines: list[str] | None) -> None:
+ chart = _flag_chart(filters["groups"], filters.get("multivariate", {}).get("variants", []))
+ assert (chart.splitlines() if chart else None) == expected_lines
+
+ @parameterized.expand(
+ [
+ (
+ "odd_count",
+ ["Signups", "Activation", "Revenue"],
+ ["▪ Signups ▪ Activation", "▪ Revenue"],
+ ),
+ (
+ "more_than_shown",
+ [f"Tile {index}" for index in range(8)],
+ "+ 2 more",
+ ),
+ ("empty", [], None),
+ ]
+ )
+ def test_tile_grid(self, _name: str, names: list[str], expected: list[str] | str | None) -> None:
+ grid = _tile_grid(names)
+ if isinstance(expected, str):
+ assert grid is not None and grid.splitlines()[-1] == expected
+ else:
+ assert (grid.splitlines() if grid else None) == expected
+
+ @parameterized.expand(
+ [
+ ("relative_days", "-30d", "Last 30 days"),
+ ("single_month", "-1m", "Last month"),
+ ("named", "mStart", "This month"),
+ ("absolute_date", "2026-01-01", None),
+ ("missing", None, None),
+ ]
+ )
+ def test_date_range(self, _name: str, date_from: str | None, expected: str | None) -> None:
+ query = {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "dateRange": {"date_from": date_from}}}
+ assert _date_range(query) == expected
+
+ def test_question_list_numbers_and_caps_questions(self) -> None:
+ questions = [{"question": f"Question {index}"} for index in range(7)]
+ assert _question_list(questions) == "1. Question 0\n2. Question 1\n3. Question 2\n+ 4 more"
+
+
@pytest.mark.django_db
class TestHandlePosthogLinkUnfurl(APIBaseTest):
def setUp(self) -> None:
@@ -158,10 +260,12 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
mock_client.chat_unfurl.assert_called_once()
call_kw = mock_client.chat_unfurl.call_args.kwargs
assert url in call_kw["unfurls"]
- text = call_kw["unfurls"][url]["blocks"][0]["text"]["text"]
+ text = self._unfurl_text(call_kw["unfurls"][url])
assert "Trends insight" in text
assert "Weekly active users" in text
assert "A test description" in text
+ actions = next(block for block in call_kw["unfurls"][url]["blocks"] if block["type"] == "actions")
+ assert actions["elements"][0]["url"] == f"{url}?utm_source=slack&utm_medium=unfurl&utm_content=insight"
@parameterized.expand(
[
@@ -473,7 +577,11 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
],
)
- assert len(mock_client.chat_unfurl.call_args.kwargs["unfurls"]) == 2
+ unfurls = mock_client.chat_unfurl.call_args.kwargs["unfurls"]
+ assert len(unfurls) == 2
+ for unfurl in unfurls.values():
+ self._assert_slack_accepts(unfurl)
+ assert not [block for payload in unfurls.values() for block in payload["blocks"] if block["type"] == "actions"]
assert len(self._invite_blocks(mock_client)) == 1
@patch("products.slack_app.backend.api.resolve_slack_user")
@@ -496,6 +604,7 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
{"url": f"http://testserver/project/{self.team.pk}/insights/nosuchid"},
{"url": f"http://testserver/project/{self.team.pk}/dashboard/424242"},
{"url": "https://example.com/somewhere-else"},
+ {"url": f"http://testserver/project/{self.team.pk}/sql?open_query=SELECT%20secret"},
],
},
self.integration,
@@ -507,6 +616,7 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
assert result["skipped"] == [
{"kind": "insight", "ref": "nosuchid", "reason": "not_found"},
{"kind": "dashboard", "ref": "424242", "reason": "not_found"},
+ {"kind": "hogql", "reason": "unsupported"},
]
@patch("products.slack_app.backend.api.resolve_slack_user")
@@ -555,18 +665,235 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
)
mock_client.chat_unfurl.assert_called_once()
- text = mock_client.chat_unfurl.call_args.kwargs["unfurls"][url]["blocks"][0]["text"]["text"]
+ text = self._unfurl_text(mock_client.chat_unfurl.call_args.kwargs["unfurls"][url])
assert "Dashboard" in text
assert "Main board" in text
+ def _create_object(self, kind: str) -> tuple[str, list[str]]:
+ base = f"http://testserver/project/{self.team.pk}"
+ match kind:
+ case "canvas":
+ with team_scope(self.team.pk):
+ channel = Channel.objects.create(team=self.team, name="Growth")
+ canvas_id = canvas_testing.create_canvas(
+ team_id=self.team.pk, channel_id=channel.id, name="Launch board", created_by_id=self.user.id
+ )
+ return f"{base}/canvases/{canvas_id}", ["Launch board", "Space: Growth"]
+ case "notebook":
+ notebook = Notebook.objects.create(
+ team=self.team, title="Activation dip", text_content="Activation fell", created_by=self.user
+ )
+ return f"{base}/notebooks/{notebook.short_id}", ["Activation dip", "Activation fell"]
+ case "flag":
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="new-checkout",
+ created_by=self.user,
+ filters={"groups": [{"properties": [], "rollout_percentage": 25}]},
+ )
+ return f"{base}/feature_flags/{flag.pk}", ["new-checkout", "*Active*", "25% of users"]
+ case "experiment":
+ flag = FeatureFlag.objects.create(team=self.team, key="button-color", created_by=self.user)
+ experiment = Experiment.objects.create(team=self.team, name="Button color", feature_flag=flag)
+ return f"{base}/experiments/{experiment.pk}", ["Button color", "*Draft*"]
+ case "survey":
+ survey = Survey.objects.create(
+ team=self.team,
+ name="Checkout NPS",
+ type="popover",
+ questions=[{"type": "open", "question": "Why?"}],
+ )
+ return f"{base}/surveys/{survey.pk}", ["Checkout NPS", "*Draft*", "1 question", "1. Why?"]
+ case "cohort":
+ cohort = Cohort.objects.create(team=self.team, name="Power users", count=1200)
+ return f"{base}/cohorts/{cohort.pk}", ["Power users", "1,200 persons"]
+ case "error":
+ issue_id = error_tracking_testing.create_issue(
+ team_id=self.team.pk, name="TypeError", description="Cannot read id"
+ )
+ return f"{base}/error_tracking/{issue_id}", ["TypeError", "*Active*", "Cannot read id"]
+ case "task":
+ task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="Fix checkout",
+ description="",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ TaskRun.objects.create(
+ task=task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_url": "https://github.com/example/repo/pull/7"},
+ )
+ return f"http://testserver/code/task/{task.id}", [
+ "Fix checkout",
+ "*Completed*",
+ "View pull request",
+ ]
+ case "report":
+ report = SignalReport.objects.create(
+ team=self.team,
+ title="Checkout drop",
+ summary="Fewer orders",
+ status=SignalReport.Status.IN_PROGRESS,
+ )
+ return f"{base}/inbox/reports/{report.pk}", [
+ "Checkout drop",
+ "*In progress*",
+ "0 signals",
+ "Fewer orders",
+ ]
+ raise ValueError(kind)
+
+ @parameterized.expand(
+ [
+ (kind,)
+ for kind in ("canvas", "notebook", "flag", "experiment", "survey", "cohort", "error", "report", "task")
+ ]
+ )
+ @patch("products.slack_app.backend.api.resolve_slack_user")
+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
+ def test_unfurls_kind(self, kind: str, mock_slack_integration_class: MagicMock, mock_resolve: MagicMock) -> None:
+ url, expected = self._create_object(kind)
+ mock_resolve.return_value = MagicMock(user=self.user)
+ mock_client = MagicMock()
+ mock_slack_integration_class.return_value.client = mock_client
+
+ self._unfurl_links([url])
+
+ unfurl = mock_client.chat_unfurl.call_args.kwargs["unfurls"][url]
+ self._assert_slack_accepts(unfurl)
+ text = self._unfurl_text(unfurl)
+ for snippet in expected:
+ assert snippet in text
+
+ @parameterized.expand(
+ [
+ ("notebook", "notebook"),
+ ("flag", "feature_flag"),
+ ("experiment", "experiment"),
+ ("survey", "survey"),
+ ("cohort", "cohort"),
+ ("error", "error_tracking"),
+ ("report", "task"),
+ ]
+ )
+ @patch("products.slack_app.backend.api.resolve_slack_user")
+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
+ def test_skips_kind_without_viewer_access(
+ self, kind: str, resource: str, mock_slack_integration_class: MagicMock, mock_resolve: MagicMock
+ ) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ member = User.objects.create_and_join(self.organization, f"restricted-{kind}@posthog.com", "password")
+ url, _ = self._create_object(kind)
+ AccessControl.objects.create(resource=resource, team=self.team, access_level="none")
+ mock_resolve.return_value = MagicMock(user=member)
+ mock_client = MagicMock()
+ mock_slack_integration_class.return_value.client = mock_client
+
+ self._unfurl_links([url])
+
+ mock_client.chat_unfurl.assert_not_called()
+
+ @patch("products.slack_app.backend.api.resolve_slack_user")
+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
+ def test_dashboard_card_lists_only_insights_the_sharer_can_view(
+ self, mock_slack_integration_class: MagicMock, mock_resolve: MagicMock
+ ) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ member = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ dashboard = Dashboard.objects.create(team=self.team, name="Growth review")
+ visible = Insight.objects.create(team=self.team, name="Visible tile", saved=True)
+ hidden = Insight.objects.create(team=self.team, name="Hidden tile", saved=True)
+ DashboardTile.objects.create(dashboard=dashboard, insight=visible)
+ DashboardTile.objects.create(dashboard=dashboard, insight=hidden)
+ AccessControl.objects.create(
+ team=self.team, resource="insight", resource_id=str(hidden.id), access_level="none"
+ )
+ mock_resolve.return_value = MagicMock(user=member)
+ mock_client = MagicMock()
+ mock_slack_integration_class.return_value.client = mock_client
+ url = f"http://testserver/project/{self.team.pk}/dashboard/{dashboard.pk}"
+
+ self._unfurl_links([url])
+
+ text = self._unfurl_text(mock_client.chat_unfurl.call_args.kwargs["unfurls"][url])
+ assert "Visible tile" in text
+ assert "1 insight" in text
+ assert "Hidden tile" not in text
+
+ @patch("products.slack_app.backend.api.resolve_slack_user")
+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
+ def test_experiment_card_shows_a_paused_experiment_as_paused(
+ self, mock_slack_integration_class: MagicMock, mock_resolve: MagicMock
+ ) -> None:
+ flag = FeatureFlag.objects.create(team=self.team, key="paused-test", created_by=self.user, active=False)
+ experiment = Experiment.objects.create(
+ team=self.team, name="Paused test", feature_flag=flag, start_date=timezone.now(), status="running"
+ )
+ mock_resolve.return_value = MagicMock(user=self.user)
+ mock_client = MagicMock()
+ mock_slack_integration_class.return_value.client = mock_client
+ url = f"http://testserver/project/{self.team.pk}/experiments/{experiment.pk}"
+
+ self._unfurl_links([url])
+
+ text = self._unfurl_text(mock_client.chat_unfurl.call_args.kwargs["unfurls"][url])
+ assert "*Paused*" in text
+
+ @staticmethod
+ def _assert_slack_accepts(unfurl: dict) -> None:
+ for block in unfurl["blocks"]:
+ parsed = Block.parse(block)
+ assert parsed is not None
+ parsed.validate_json()
+
+ @patch("products.slack_app.backend.slack_link_unfurl.capture_slack_event")
+ @patch("products.slack_app.backend.api.resolve_slack_user")
+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
+ def test_rejected_card_falls_back_to_compact(
+ self, mock_slack_integration_class: MagicMock, mock_resolve: MagicMock, mock_capture: MagicMock
+ ) -> None:
+ mock_resolve.return_value = MagicMock(user=self.user)
+ mock_client = MagicMock()
+ rejection = SlackResponse(
+ client=None,
+ http_verb="POST",
+ api_url="https://slack.com/api/chat.unfurl",
+ req_args={},
+ data={"ok": False, "error": "cannot_parse_attachment"},
+ headers={},
+ status_code=200,
+ )
+ mock_client.chat_unfurl.side_effect = [SlackApiError("rejected", rejection), None]
+ mock_slack_integration_class.return_value.client = mock_client
+ url = f"http://testserver/project/{self.team.pk}/insights/{self.insight.short_id}"
+
+ self._unfurl_links([url])
+
+ retried = mock_client.chat_unfurl.call_args.kwargs["unfurls"][url]["blocks"]
+ assert mock_client.chat_unfurl.call_count == 2
+ assert [block["type"] for block in retried if block["type"] != "context"] == ["section"]
+ failure = next(c for c in mock_capture.call_args_list if c.args[1] == "slack app link unfurl failed")
+ assert failure.kwargs["error"] == "cannot_parse_attachment"
+
@staticmethod
def _unfurl_text(unfurl: dict) -> str:
parts: list[str] = []
for block in unfurl["blocks"]:
if block["type"] == "section":
- parts.append(block["text"]["text"])
+ parts.extend(field["text"] for field in [block.get("text"), *block.get("fields", [])] if field)
elif block["type"] == "context":
parts.extend(element["text"] for element in block["elements"])
+ elif block["type"] == "actions":
+ parts.extend(element["text"]["text"] for element in block["elements"])
return "\n".join(parts)
@patch("products.slack_app.backend.api.resolve_slack_user")
@@ -592,8 +919,8 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
mock_client.chat_unfurl.assert_called_once()
text = self._unfurl_text(mock_client.chat_unfurl.call_args.kwargs["unfurls"][url])
- assert "Support Ticket #1" in text
- assert "Requested by:* [email protected]" in text
+ assert "Ticket #1" in text
+ assert "Requested by [email protected]" in text
assert "New" in text # default status, humanized
@parameterized.expand([("resource",), ("object",)])
@@ -678,7 +1005,7 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
)
text = self._unfurl_text(mock_client.chat_unfurl.call_args.kwargs["unfurls"][url])
- assert "Requested by:* John Doe" in text
+ assert "Requested by John Doe" in text
@patch("products.slack_app.backend.api.resolve_slack_user")
@patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
@@ -705,7 +1032,7 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
)
text = self._unfurl_text(mock_client.chat_unfurl.call_args.kwargs["unfurls"][url])
- assert ">>> App crashes on login" in text
+ assert "App crashes on login" in text
@parameterized.expand(
[
@@ -741,7 +1068,7 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
)
text = self._unfurl_text(mock_client.chat_unfurl.call_args.kwargs["unfurls"][url])
- assert ">>>" not in text
+ assert "internal only" not in text
@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
diff --git a/tach.toml b/tach.toml
index 1f84fc936d1f..fbc41806039e 100644
--- a/tach.toml
+++ b/tach.toml
@@ -938,10 +938,17 @@ path = "products.slack_app"
depends_on = [
"posthog",
"products.alerts",
+ "products.canvas",
+ "products.cohorts",
"products.conversations",
"products.dashboards",
+ "products.error_tracking",
+ "products.experiments",
+ "products.feature_flags",
+ "products.notebooks",
"products.product_analytics",
"products.signals",
+ "products.surveys",
"products.tasks", "products.access_control",
# Slack triggers emit internal events through products.cdp.backend.internal_events.
"products.cdp",