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 support ticket links shared in Slack (#67083)

Luke Belton3eb773cd15c5
diff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.py
index 5b6b8923ec18..383ce033f7aa 100644
--- a/products/slack_app/backend/slack_link_unfurl.py
+++ b/products/slack_app/backend/slack_link_unfurl.py
@@ -1,21 +1,29 @@
-"""Slack link unfurling for PostHog insight and dashboard URLs (metadata only)."""
+"""Slack link unfurling for PostHog insight, dashboard, and support ticket URLs (metadata only)."""
from __future__ import annotations
from typing import Literal
from urllib.parse import urlparse
+from uuid import UUID
+
+from django.core.exceptions import ValidationError
import structlog
+from posthog.models import Team
+from posthog.models.comment import Comment
from posthog.models.integration import Integration, SlackIntegration
from posthog.rbac.user_access_control import UserAccessControl, access_level_satisfied_for_resource
+from products.conversations.backend.models.ticket import Ticket
from products.dashboards.backend.models.dashboard import Dashboard
from products.product_analytics.backend.models.insight import Insight
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
# Query `source.kind` / top-level `kind` → short name before " insight" (sync with InsightType / query kinds).
_QUERY_KIND_TO_SHORT_NAME: dict[str, str] = {
@@ -54,11 +62,12 @@ def _truncate(text: str, max_len: int) -> str:
return text[: max_len - 1] + "…"
-def parse_posthog_resource_link(url: str) -> tuple[Literal["insight", "dashboard"], str | int] | None:
+def parse_posthog_resource_link(url: str) -> tuple[Literal["insight", "dashboard", "ticket"], str | int] | None:
"""
Parse a PostHog app URL into (resource kind, reference id).
- Reference is insight short_id (str) or dashboard primary key (int).
+ Reference is insight short_id (str), dashboard primary key (int), or ticket ref (str — ticket
+ number or UUID).
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.
@@ -94,6 +103,12 @@ def parse_posthog_resource_link(url: str) -> tuple[Literal["insight", "dashboard
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)
+
return None
@@ -154,6 +169,62 @@ def _insight_resource_label(insight: Insight) -> str:
return "Insight"
+def _url_team_id(url: str) -> int | None:
+ """The team id from a `/project/:id/...` URL segment, if present (matches middleware behavior)."""
+ parts = [p for p in urlparse(url).path.split("/") if p]
+ if len(parts) >= 2 and parts[0] == "project" and parts[1].isdigit():
+ return int(parts[1])
+ return None
+
+
+def _find_ticket(team_id: int, ref: str) -> Ticket | None:
+ """Resolve a ticket by its human number or UUID, scoped to the team."""
+ if ref.isdigit():
+ return Ticket.objects.filter(team_id=team_id, ticket_number=int(ref)).first()
+ try:
+ return Ticket.objects.filter(team_id=team_id, pk=ref).first()
+ except (ValueError, ValidationError):
+ return None
+
+
+def _escape_mrkdwn(text: str) -> str:
+ """Escape mrkdwn control chars — ticket subjects/messages are customer-authored."""
+ return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+
+
+def _ticket_requester(team: Team, ticket: Ticket) -> str:
+ """Display the ticket's requester using the project's person display-name settings.
+
+ The ticket's ``anonymous_traits`` are the customer-provided person properties, so we pick the
+ first configured display property present (default order prefers email), then fall back.
+ """
+ # Deferred to keep the heavy posthog.api.person module off the Django startup import path.
+ from posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES # noqa: PLC0415
+
+ traits = ticket.anonymous_traits or {}
+ for prop in team.person_display_name_properties or PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES:
+ value = traits.get(prop)
+ if value:
+ return str(value)
+ return ticket.email_from or "Anonymous"
+
+
+def _ticket_opening_message(team_id: int, ticket_id: UUID) -> str | None:
+ """The ticket's opening public message: the earliest non-private, non-deleted conversations_ticket comment.
+
+ Private/internal notes (``item_context.is_private``) and soft-deleted comments are excluded so
+ neither surfaces in Slack.
+ """
+ content = (
+ Comment.objects.filter(team_id=team_id, scope="conversations_ticket", item_id=str(ticket_id), deleted=False)
+ .exclude(item_context__is_private=True)
+ .order_by("created_at")
+ .values_list("content", flat=True)
+ .first()
+ )
+ return _truncate(_escape_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}*"
@@ -162,12 +233,30 @@ def _unfurl_payload(*, resource_label: str, title: str, description: str | None)
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."""
+ 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()}"}
+ ],
+ },
+ ]
+ if opening_message:
+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": f">>> {opening_message}"}})
+ return {"blocks": blocks}
+
+
def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
"""
- Unfurl PostHog insight/dashboard links with title and description for viewers who may access the resource.
+ Unfurl PostHog insight, dashboard, and support ticket links with title and description.
- Scope is always the Slack workspace's connected PostHog project (`integration.team`) and the
- PostHog user resolved from Slack email — never the `/project/:id` segment in pasted URLs.
+ Scope is always the Slack-connected project (`integration.team`); `resolve_slack_user` enforces
+ that the sharer can access it. Insights/dashboards add a per-resource access-control check;
+ tickets have no per-object ACL, but a link naming a different project is refused (ticket numbers
+ are per-project, so resolving by number could otherwise surface the wrong ticket).
"""
slack = SlackIntegration(integration)
channel = event.get("channel")
@@ -226,7 +315,7 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
unfurls[raw_url] = _unfurl_payload(
resource_label=_insight_resource_label(insight), title=title, description=desc
)
- else:
+ elif kind == "dashboard":
if not isinstance(ref, int):
continue
dashboard = Dashboard.objects.filter(pk=ref, team_id=team.pk).first()
@@ -238,6 +327,26 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:
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:
+ continue
+ ticket = _find_ticket(team.pk, ref)
+ if not ticket:
+ continue
+ # Tickets have no per-object ACL — any member of the connected team may view them.
+ unfurls[raw_url] = _ticket_unfurl_payload(
+ url=raw_url,
+ ticket=ticket,
+ requester=_escape_mrkdwn(_ticket_requester(team, ticket)),
+ opening_message=_ticket_opening_message(team.pk, ticket.id),
+ )
if not unfurls:
return
diff --git a/products/slack_app/backend/tests/test_link_unfurl.py b/products/slack_app/backend/tests/test_link_unfurl.py
index d5c211cf141b..bab7c366b19c 100644
--- a/products/slack_app/backend/tests/test_link_unfurl.py
+++ b/products/slack_app/backend/tests/test_link_unfurl.py
@@ -2,8 +2,12 @@ import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from parameterized import parameterized
+
+from posthog.models.comment import Comment
from posthog.models.integration import Integration
+from products.conversations.backend.models.ticket import Ticket
from products.dashboards.backend.models.dashboard import Dashboard
from products.product_analytics.backend.models.insight import Insight
from products.slack_app.backend.slack_link_unfurl import (
@@ -32,6 +36,18 @@ class TestParsePosthogResourceLink:
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_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
@@ -179,3 +195,150 @@ class TestHandlePosthogLinkUnfurl(APIBaseTest):
text = mock_client.chat_unfurl.call_args.kwargs["unfurls"][url]["blocks"][0]["text"]["text"]
assert "Dashboard" in text
assert "Main board" in text
+
+ @staticmethod
+ def _unfurl_text(unfurl: dict) -> str:
+ parts: list[str] = []
+ for block in unfurl["blocks"]:
+ if block["type"] == "section":
+ parts.append(block["text"]["text"])
+ elif block["type"] == "context":
+ parts.extend(element["text"] for element in block["elements"])
+ return "\n".join(parts)
+
+ @patch("products.slack_app.backend.api.resolve_slack_user")
+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
+ def test_unfurls_ticket(self, mock_slack_integration_class: MagicMock, mock_resolve: MagicMock) -> None:
+ ticket = Ticket.objects.create(
+ team=self.team,
+ ticket_number=1,
+ widget_session_id="s1",
+ distinct_id="d1",
+ # Default display-name settings prefer email over name.
+ anonymous_traits={"name": "John Doe", "email": "[email protected]"},
+ )
+ 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}/support/tickets/{ticket.ticket_number}"
+ handle_posthog_link_unfurl(
+ {"channel": "C1", "message_ts": "123.456", "user": "U1", "links": [{"url": url}]},
+ self.integration,
+ )
+
+ 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 "New" in text # default status, humanized
+
+ @patch("products.slack_app.backend.api.resolve_slack_user")
+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
+ def test_skips_ticket_from_another_project(
+ self, mock_slack_integration_class: MagicMock, mock_resolve: MagicMock
+ ) -> None:
+ # ticket_number is per-project — a link naming a different project must not resolve to our #1.
+ ticket = Ticket.objects.create(team=self.team, ticket_number=1, widget_session_id="s9", distinct_id="d9")
+ 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 + 1}/support/tickets/{ticket.ticket_number}"
+ handle_posthog_link_unfurl(
+ {"channel": "C1", "message_ts": "1.2", "user": "U1", "links": [{"url": url}]},
+ self.integration,
+ )
+
+ 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_ticket_requester_follows_display_name_setting(
+ self, mock_slack_integration_class: MagicMock, mock_resolve: MagicMock
+ ) -> None:
+ # A project that displays people by name should show the name, not the email.
+ self.team.person_display_name_properties = ["name", "email"]
+ self.team.save()
+ ticket = Ticket.objects.create(
+ team=self.team,
+ ticket_number=3,
+ widget_session_id="s3",
+ distinct_id="d3",
+ anonymous_traits={"name": "John Doe", "email": "[email protected]"},
+ )
+ mock_resolve.return_value = MagicMock(user=self.user)
+ mock_client = MagicMock()
+ mock_slack_integration_class.return_value.client = mock_client
+
+ url = f"http://testserver/support/tickets/{ticket.ticket_number}"
+ handle_posthog_link_unfurl(
+ {"channel": "C1", "message_ts": "1.2", "user": "U1", "links": [{"url": url}]},
+ self.integration,
+ )
+
+ text = self._unfurl_text(mock_client.chat_unfurl.call_args.kwargs["unfurls"][url])
+ 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")
+ def test_unfurls_ticket_with_opening_message(
+ self, mock_slack_integration_class: MagicMock, mock_resolve: MagicMock
+ ) -> None:
+ ticket = Ticket.objects.create(team=self.team, ticket_number=2, widget_session_id="s2", distinct_id="d2")
+ # bulk_create skips conversations' post_save signals — we only need the row for the lookup.
+ Comment.objects.bulk_create(
+ [
+ Comment(
+ team=self.team, scope="conversations_ticket", item_id=str(ticket.id), content="App crashes on login"
+ )
+ ]
+ )
+ mock_resolve.return_value = MagicMock(user=self.user)
+ mock_client = MagicMock()
+ mock_slack_integration_class.return_value.client = mock_client
+
+ url = f"http://testserver/support/tickets/{ticket.ticket_number}"
+ handle_posthog_link_unfurl(
+ {"channel": "C1", "message_ts": "1.2", "user": "U1", "links": [{"url": url}]},
+ self.integration,
+ )
+
+ text = self._unfurl_text(mock_client.chat_unfurl.call_args.kwargs["unfurls"][url])
+ assert ">>> App crashes on login" in text
+
+ @parameterized.expand(
+ [
+ ("private_note", {"item_context": {"is_private": True}}),
+ ("soft_deleted", {"deleted": True}),
+ ]
+ )
+ @patch("products.slack_app.backend.api.resolve_slack_user")
+ @patch("products.slack_app.backend.slack_link_unfurl.SlackIntegration")
+ def test_ticket_hidden_opening_message_not_surfaced(
+ self, _name: str, overrides: dict, mock_slack_integration_class: MagicMock, mock_resolve: MagicMock
+ ) -> None:
+ ticket = Ticket.objects.create(team=self.team, ticket_number=4, widget_session_id="s4", distinct_id="d4")
+ Comment.objects.bulk_create(
+ [
+ Comment(
+ team=self.team,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ content="internal only",
+ **overrides,
+ )
+ ]
+ )
+ mock_resolve.return_value = MagicMock(user=self.user)
+ mock_client = MagicMock()
+ mock_slack_integration_class.return_value.client = mock_client
+
+ url = f"http://testserver/support/tickets/{ticket.ticket_number}"
+ handle_posthog_link_unfurl(
+ {"channel": "C1", "message_ts": "1.2", "user": "U1", "links": [{"url": url}]},
+ self.integration,
+ )
+
+ text = self._unfurl_text(mock_client.chat_unfurl.call_args.kwargs["unfurls"][url])
+ assert ">>>" not in text
diff --git a/tach.toml b/tach.toml
index 00f8e454e449..ae96625487dc 100644
--- a/tach.toml
+++ b/tach.toml
@@ -615,6 +615,7 @@ layer = "modules"
path = "products.slack_app"
depends_on = [
"posthog",
+ "products.conversations",
"products.dashboards",
"products.product_analytics",
"products.signals",