: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(slack_app): render agent object tags as links and SQL in Slack replies (#89836)
Andrew Maguire0671dbeaef59
diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.pyindex ca25fd8e495c..63ac91126d1c 100644--- a/products/slack_app/backend/services/slack_messages.py+++ b/products/slack_app/backend/services/slack_messages.py@@ -639,6 +639,11 @@ def personal_integrations_url(team_id: int) -> str:return _public_url(f"/project/{team_id}/settings/user-personal-integrations")+def project_web_url(team_id: int) -> str:+ """Absolute ``/project/<id>`` base for links into this project's PostHog app."""+ return _public_url(f"/project/{team_id}")++def _task_url(team_id: int, task_id: UUID, run_id: UUID) -> str:# `unfurl=false` asks our own link unfurler to leave this one alone: the footer already# says what the card would, right next to the link.diff --git a/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py b/products/tasks/backend/temporal/process_task/activities/slack_agent_design.pyindex de32e8a90968..2896a9277e00 100644--- a/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py+++ b/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py@@ -11,9 +11,12 @@ from typing import Any, Optionalfrom temporalio import activity+from posthog.models.integration import Integrationfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.common.utils import close_db_connections+from products.tasks.backend.temporal.slack_relay.object_tags import rewrite_object_tags_for_slack+logger = get_logger(__name__)@@ -59,6 +62,20 @@ class StopSlackAgentDesignStreamInput:run_id: Optional[str] = None+def _rewrite_object_tags(text: Optional[str], integration_id: int) -> Optional[str]:+ """Turn agent object tags into Slack-renderable markdown before the text is streamed.++ Streamed replies never pass through the relay activity, so its rewrite has to happen here+ too. A tag split across two streamed chunks stays as written; the final answer arrives whole.+ """+ from products.slack_app.backend.services.slack_messages import project_web_url++ if not text or "<" not in text:+ return text+ team_id = Integration.objects.only("team_id").get(id=integration_id).team_id+ return rewrite_object_tags_for_slack(text, project_url=project_web_url(team_id))++@activity.defn@close_db_connectionsdef start_slack_agent_design_stream(input: StartSlackAgentDesignStreamInput) -> Optional[str]:@@ -72,7 +89,7 @@ def start_slack_agent_design_stream(input: StartSlackAgentDesignStreamInput) ->first_task_id=input.first_task_id,first_task_title=input.first_task_title,first_task_details=input.first_task_details,- first_markdown_text=input.first_markdown_text,+ first_markdown_text=_rewrite_object_tags(input.first_markdown_text, context.integration_id),)except Exception as e:logger.warning("slack_app_start_agent_design_stream_failed", error=str(e))@@ -92,7 +109,7 @@ def append_slack_agent_design_steps(input: AppendSlackAgentDesignStepsInput) ->task_updates=[{"id": t.id, "title": t.title, "status": t.status, "details": t.details} for t in input.task_updates],- markdown_text=input.markdown_text,+ markdown_text=_rewrite_object_tags(input.markdown_text, context.integration_id),)except Exception as e:logger.warning("slack_app_append_agent_design_steps_failed", error=str(e))@@ -117,7 +134,7 @@ def stop_slack_agent_design_stream(input: StopSlackAgentDesignStreamInput) -> Nocomplete_task_id=input.complete_task_id,complete_task_title=input.complete_task_title,complete_task_details=input.complete_task_details,- final_markdown=input.final_markdown,+ final_markdown=_rewrite_object_tags(input.final_markdown, context.integration_id),)except Exception as e:logger.warning("slack_app_stop_agent_design_stream_failed", error=str(e))diff --git a/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py b/products/tasks/backend/temporal/process_task/slack_agent_design_relay.pyindex 49de4b1e11b3..67dc30fa5163 100644--- a/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py+++ b/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py@@ -25,6 +25,8 @@ from temporalio.common import RetryPolicyfrom posthog.temporal.common.base import PostHogWorkflowwith workflow.unsafe.imports_passed_through():+ from products.tasks.backend.temporal.slack_relay.object_tags import split_incomplete_tag_suffix+from .activities.slack_agent_design import (AppendSlackAgentDesignStepsInput,StartSlackAgentDesignStreamInput,@@ -71,6 +73,8 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):self._current_task_title: Optional[str] = Noneself._current_task_details: Optional[str] = Noneself._last_dispatched_at: float = 0.0+ # Length of a narrative held back whole (an unfinished tag); a flush waits for it to grow.+ self._held_length: int = 0self._turn_complete: bool = False@workflow.signal@@ -180,10 +184,32 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):if not self._has_seen_tool_call:# Phase 1: stream narrative as markdown_text.- to_stream = self._current_narrative- if not to_stream:+ if not self._current_narrative:continue- self._current_narrative = ""+ if workflow.patched("slack-agent-design-hold-split-tags-2026-08"):+ # An object tag or code fence cut by the flush boundary would post as+ # raw XML; keep its start for the next flush. Patched because a history+ # recorded before this branch cleared the narrative here and then waited.+ split = split_incomplete_tag_suffix(self._current_narrative)+ if not split.sendable:+ self._held_length = len(self._current_narrative)+ try:+ await workflow.wait_condition(+ lambda: len(self._current_narrative) != self._held_length or self._turn_complete,+ timeout=timedelta(minutes=TURN_IDLE_TIMEOUT_MINUTES),+ )+ except TimeoutError:+ workflow.logger.warning(+ "slack_app_agent_design_relay_idle_timeout",+ extra={"workflow_id": workflow.info().workflow_id},+ )+ return+ continue+ to_stream = split.sendable+ self._current_narrative = split.held+ else:+ to_stream = self._current_narrative+ self._current_narrative = ""self._last_dispatched_at = workflow.now().timestamp()if self._stream_ts is None:diff --git a/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.py b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.pynew file mode 100644index 000000000000..dfbc385b00cc--- /dev/null+++ b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.py@@ -0,0 +1,44 @@+from typing import ClassVar++from unittest.mock import patch++from django.test import TestCase, override_settings++from posthog.models.integration import Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team++from products.tasks.backend.temporal.process_task.activities.slack_agent_design import (+ StopSlackAgentDesignStreamInput,+ stop_slack_agent_design_stream,+)+++@override_settings(SITE_URL="https://us.posthog.com")+class TestSlackAgentDesignStream(TestCase):+ org: ClassVar[Organization]+ team: ClassVar[Team]+ integration: ClassVar[Integration]++ @classmethod+ def setUpTestData(cls) -> None:+ cls.org = Organization.objects.create(name="TestOrg")+ cls.team = Team.objects.create(organization=cls.org, name="TestTeam")+ cls.integration = Integration.objects.create(team=cls.team, kind="slack", integration_id="T123", config={})++ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.footer_enabled", return_value=False)+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.stop_status_stream")+ def test_streamed_final_answer_has_object_tags_rewritten(self, mock_stop, _mock_footer) -> None:+ stop_slack_agent_design_stream(+ StopSlackAgentDesignStreamInput(+ slack_thread_context={"integration_id": self.integration.id, "channel": "C1", "thread_ts": "1.0"},+ ts="2.0",+ final_markdown='The <insight id="9pQx3">checkout funnel</insight> dropped.',+ )+ )++ mock_stop.assert_called_once()+ final_markdown = mock_stop.call_args.kwargs["final_markdown"]+ assert final_markdown == (+ f"The [checkout funnel](https://us.posthog.com/project/{self.team.id}/insights/9pQx3?unfurl=false) dropped."+ )diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.pyindex bea219155abb..e119ec265f2e 100644--- a/products/tasks/backend/temporal/slack_relay/activities.py+++ b/products/tasks/backend/temporal/slack_relay/activities.py@@ -13,6 +13,7 @@ from products.tasks.backend.logic.services.living_artifacts import (has_pending_slack_file_artifacts,has_pending_slack_image_artifacts,)+from products.tasks.backend.temporal.slack_relay.object_tags import rewrite_object_tags_for_slacklogger = get_logger(__name__)@@ -365,7 +366,11 @@ class RelaySlackMessageInput:@close_db_connectionsdef relay_slack_message(input: RelaySlackMessageInput) -> None:from products.slack_app.backend.models import SlackThreadTaskMapping- from products.slack_app.backend.services.slack_messages import load_run_footer, normalize_labeled_mentions_to_bare+ from products.slack_app.backend.services.slack_messages import (+ load_run_footer,+ normalize_labeled_mentions_to_bare,+ project_web_url,+ )from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandlerfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.temporal.process_task.utils import get_message_actor@@ -397,6 +402,11 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:# is shorter (never enlarges a chunk) and the mrkdwn converter passes it through untouched.text = normalize_labeled_mentions_to_bare(text)+ # Object tags (``<insight id="…">``, ``<hogql display="block">``) are what the desktop renders+ # as chips and chart cards; Slack would show them as escaped XML. Rewritten to links and+ # fenced SQL before splitting so chunk sizes account for the markdown they become.+ text = rewrite_object_tags_for_slack(text, project_url=project_web_url(task_run.team_id))+# Living-artifacts gating lives in the service: has_pending_slack_file_artifacts# (and deliver_pending_slack_file_artifacts below) return falsy when the# workspace's living-artifacts flag is off. Run-manifest artifacts are internaldiff --git a/products/tasks/backend/temporal/slack_relay/object_tags.py b/products/tasks/backend/temporal/slack_relay/object_tags.pynew file mode 100644index 000000000000..fecdf1173bad--- /dev/null+++ b/products/tasks/backend/temporal/slack_relay/object_tags.py@@ -0,0 +1,398 @@+"""Rewrite agent object tags into markdown Slack can show.++Agents cite PostHog objects with XML-style tags (``<insight id="9pQx3">checkout funnel</insight>``,+``<hogql display="block" title="DAU">SELECT ...</hogql>``). The desktop and web task views parse+those into chips and chart cards; Slack has no renderer, so a raw tag reaches the thread as+escaped XML. This module runs before markdown conversion and turns each tag into the closest+thing Slack has: a link to the object, a fenced SQL block, or just the label.++The kind registry mirrors the desktop one (``products/desktop/packages/core/src/inbox/objectTags.ts``).+Keep the two in sync when a kind or path changes.+"""++import re+from collections.abc import Callable+from urllib.parse import quote++from posthog.dataclasses import frozen++# Slack keeps a link's URL out of the message text limit, but the chat API rejects URLs past+# this size, and a SQL editor deep link carries the whole query in the query string.+_MAX_LINK_URL_LENGTH = 2000++# Links we post ourselves carry this so PostHog's own unfurler leaves inline references alone;+# a block-display reference keeps unfurling on because the unfurl card is the nearest thing+# Slack has to the chart card the desktop renders.+_UNFURL_OPT_OUT_QUERY = "unfurl=false"++_RE_OPEN_TAG = re.compile(r"<([a-z][\w-]*)((?:\s+[a-z][\w-]*\s*=\s*\"[^\"]*\")*)\s*(/>|>)")+_RE_CLOSE_TAG = re.compile(r"</([a-z][\w-]*)\s*>")+_RE_ATTR = re.compile(r"([a-z][\w-]*)\s*=\s*\"([^\"]*)\"")+_RE_FENCE_LINE = re.compile(r"^ {0,3}(`{3,}|~{3,})")+_RE_BACKTICK_RUN = re.compile(r"`+")+_RE_UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f-]{27,}$", re.IGNORECASE)+_RE_LABEL_UNSAFE = re.compile(r"[\[\]|]")+_LABEL_ANGLE_ENTITIES = {"<": "<", ">": ">"}+_RE_NUMERIC = re.compile(r"^\d+$")+_RE_BARE_ID = re.compile(r"^[\w$.:-]{1,64}$")+++@frozen+class _ObjectKind:+ label: str+ # Project-relative path for an id, or None when the id has no page of its own.+ web_path: Callable[[str], str | None]+++def _plain_path(prefix: str) -> Callable[[str], str | None]:+ return lambda object_id: f"{prefix}/{quote(object_id, safe='')}"+++def _flag_path(object_id: str) -> str | None:+ # Flag pages resolve by numeric id only; a flag cited by key has no direct page.+ return f"/feature_flags/{object_id}" if _RE_NUMERIC.match(object_id) else None+++def _event_path(object_id: str) -> str | None:+ # Event definition pages resolve by uuid; an event cited by name has no direct page.+ return f"/data-management/events/{quote(object_id, safe='')}" if _RE_UUID.match(object_id) else None+++def _sql_editor_path(sql: str) -> str | None:+ return f"/sql?open_query={quote(sql, safe='')}"+++_HOGQL_KIND = _ObjectKind(label="SQL query", web_path=_sql_editor_path)++_OBJECT_KINDS: dict[str, _ObjectKind] = {+ "insight": _ObjectKind(label="Insight", web_path=_plain_path("/insights")),+ "hogql": _HOGQL_KIND,+ "dashboard": _ObjectKind(label="Dashboard", web_path=_plain_path("/dashboard")),+ "error": _ObjectKind(label="Error issue", web_path=_plain_path("/error_tracking")),+ "replay": _ObjectKind(label="Session replay", web_path=_plain_path("/replay")),+ "flag": _ObjectKind(label="Feature flag", web_path=_flag_path),+ "experiment": _ObjectKind(label="Experiment", web_path=_plain_path("/experiments")),+ "survey": _ObjectKind(label="Survey", web_path=_plain_path("/surveys")),+ "ticket": _ObjectKind(label="Support ticket", web_path=_plain_path("/support/tickets")),+ "trace": _ObjectKind(label="LLM trace", web_path=_plain_path("/ai-observability/traces")),+ "eval": _ObjectKind(label="Evaluation", web_path=_plain_path("/ai-evals/evaluations")),+ "event": _ObjectKind(label="Event", web_path=_event_path),+ "cohort": _ObjectKind(label="Cohort", web_path=_plain_path("/cohorts")),+ "action": _ObjectKind(label="Action", web_path=_plain_path("/data-management/actions")),+ "person": _ObjectKind(label="Person", web_path=_plain_path("/persons")),+}++_OBJECT_KIND_ALIASES: dict[str, str] = {+ "session-replay": "replay",+ "recording": "replay",+ "session_replay": "replay",+ "feature-flag": "flag",+ "feature_flag": "flag",+ "sql": "hogql",+}+++# Only the five entities the desktop composer's XML serializer emits (``escapeXmlAttr``); the full+# HTML entity table would rewrite SQL literals such as ``'©'``.+_XML_ENTITIES = {""": '"', "'": "'", "<": "<", ">": ">", "&": "&"}+_RE_XML_ENTITY = re.compile("|".join(re.escape(entity) for entity in _XML_ENTITIES))+++def _unescape_xml(value: str) -> str:+ return _RE_XML_ENTITY.sub(lambda match: _XML_ENTITIES[match.group(0)], value)+++@frozen+class _Span:+ start: int+ end: int++ def contains(self, position: int) -> bool:+ return self.start <= position < self.end+++@frozen+class _Tag:+ name: str+ attrs: dict[str, str]+ body: str+ start: int+ end: int+++def _resolve_kind(name: str) -> _ObjectKind | None:+ return _OBJECT_KINDS.get(_OBJECT_KIND_ALIASES.get(name, name))+++def _parse_attrs(raw: str) -> dict[str, str]:+ return {match.group(1): _unescape_xml(match.group(2)) for match in _RE_ATTR.finditer(raw)}+++def _inline_code_spans(line: str, offset: int) -> list[_Span]:+ """CommonMark inline code on one line: a run of N backticks closes on the next run of exactly N."""+ runs = list(_RE_BACKTICK_RUN.finditer(line))+ spans: list[_Span] = []+ index = 0+ while index < len(runs):+ opener = runs[index]+ length = opener.end() - opener.start()+ closer_index = next(+ (i for i in range(index + 1, len(runs)) if runs[i].end() - runs[i].start() == length),+ None,+ )+ if closer_index is None:+ index += 1+ continue+ spans.append(_Span(start=offset + opener.start(), end=offset + runs[closer_index].end()))+ index = closer_index + 1+ return spans+++def _code_spans(text: str) -> list[_Span]:+ """Fenced blocks and inline code, found in one pass over the lines.++ Mirrors the desktop renderer's fence rules: a backtick or tilde fence of three or more, closed+ only by a run of the same character at least as long with nothing else on the line, and an+ unclosed fence runs to the end of the text.+ """+ spans: list[_Span] = []+ fence_char = ""+ fence_length = 0+ fence_start = 0+ offset = 0+ for line in text.split("\n"):+ fence = _RE_FENCE_LINE.match(line)+ if fence_char:+ closes = (+ fence is not None+ and fence.group(1)[0] == fence_char+ and len(fence.group(1)) >= fence_length+ and line[fence.end() :].strip() == ""+ )+ if closes:+ spans.append(_Span(start=fence_start, end=offset + len(line)))+ fence_char = ""+ elif fence:+ fence_char = fence.group(1)[0]+ fence_length = len(fence.group(1))+ fence_start = offset+ else:+ spans.extend(_inline_code_spans(line, offset))+ offset += len(line) + 1+ if fence_char:+ spans.append(_Span(start=fence_start, end=len(text)))+ return spans+++def _scan_tags(text: str, skip_spans: list[_Span]) -> list[_Tag]:+ """Find complete tags in ``text`` in order, without overlaps.++ Openers that start inside ``skip_spans`` (code) are not tags. A tag whose closer never+ arrives is not a tag either: the text stays as it was, which matches the desktop renderer+ leaving an unterminated tag alone. Closers are indexed up front so each opener costs one+ cursor advance instead of a scan to the end of the message.+ """+ closers: dict[str, list[re.Match[str]]] = {}+ for close in _RE_CLOSE_TAG.finditer(text):+ closers.setdefault(close.group(1), []).append(close)+ cursors: dict[str, int] = {}+ tags: list[_Tag] = []+ next_allowed = 0+ span_cursor = 0+ for match in _RE_OPEN_TAG.finditer(text):+ start = match.start()+ # Openers and spans are both in text order, so the span cursor only moves forward.+ while span_cursor < len(skip_spans) and skip_spans[span_cursor].end <= start:+ span_cursor += 1+ if start < next_allowed or (span_cursor < len(skip_spans) and skip_spans[span_cursor].contains(start)):+ continue+ name = match.group(1)+ attrs = _parse_attrs(match.group(2))+ open_end = match.end()+ if match.group(3) == "/>":+ tags.append(_Tag(name=name, attrs=attrs, body="", start=start, end=open_end))+ next_allowed = open_end+ continue+ candidates = closers.get(name, [])+ cursor = cursors.get(name, 0)+ while cursor < len(candidates) and candidates[cursor].start() < open_end:+ cursor += 1+ cursors[name] = cursor+ if cursor >= len(candidates):+ continue+ close = candidates[cursor]+ tags.append(_Tag(name=name, attrs=attrs, body=text[open_end : close.start()], start=start, end=close.end()))+ next_allowed = close.end()+ return tags+++def _safe_label(label: str) -> str:+ # The label ends up inside a Slack ``<url|label>`` link, where ``|`` and ``>`` end the link+ # early, and inside a markdown ``[label](url)`` on the way there, where brackets do. Angle+ # brackets are common in titles (``Error rate > 1%``), so they become the entities Slack+ # renders back as the characters.+ collapsed = " ".join(_RE_LABEL_UNSAFE.sub(" ", label).split())+ return "".join(_LABEL_ANGLE_ENTITIES.get(char, char) for char in collapsed)+++def _link(label: str, url: str | None) -> str:+ if url is None or len(url) > _MAX_LINK_URL_LENGTH:+ return label+ return f"[{label}]({url})"+++def _object_url(project_url: str, kind: _ObjectKind, object_id: str, *, unfurl: bool) -> str | None:+ path = kind.web_path(object_id)+ if path is None:+ return None+ if unfurl:+ return f"{project_url}{path}"+ separator = "&" if "?" in path else "?"+ return f"{project_url}{path}{separator}{_UNFURL_OPT_OUT_QUERY}"+++def _render_hogql(tag: _Tag, project_url: str) -> str | None:+ # A body written by the desktop composer is XML-escaped, so ``<`` is a ``<`` in the SQL.+ sql = _unescape_xml(tag.body).strip()+ if not sql:+ return None+ url = _object_url(project_url, _HOGQL_KIND, sql, unfurl=False)+ if tag.attrs.get("display") != "block":+ label = _safe_label(tag.attrs.get("label") or tag.attrs.get("title") or "") or _HOGQL_KIND.label+ return _link(label, url)++ title = _safe_label(tag.attrs.get("title") or "") or _HOGQL_KIND.label+ # No language hint on the fence: Slack shows one as literal text inside the block.+ lines = [f"**{_link(title, url)}**", "```", sql, "```"]+ caption = " ".join((tag.attrs.get("caption") or "").split())+ if caption:+ lines.append(f"_{caption}_")+ return "\n".join(lines)+++def _render_reference(tag: _Tag, kind: _ObjectKind, project_url: str) -> str | None:+ object_id = (tag.attrs.get("id") or "").strip()+ body = tag.body.strip()+ if not object_id and _RE_BARE_ID.match(body):+ # The older ``<insight>abc123</insight>`` form Max's notebook tools still write.+ object_id, body = body, ""+ if not object_id:+ # A tag with a title but no id (a notebook query node) has no page to link; keep the title.+ return _safe_label(tag.attrs.get("title") or "") or None+ is_block = tag.attrs.get("display") == "block"+ label = _safe_label(tag.attrs.get("title") or body) or f"{kind.label} {_safe_label(object_id)}"+ return _link(label, _object_url(project_url, kind, object_id, unfurl=is_block))+++def _render_tag(tag: _Tag, project_url: str) -> str | None:+ kind = _resolve_kind(tag.name)+ if kind is None:+ # An agent sometimes extends the convention to a kind nobody renders (``<inbox id="…">``).+ # The label is still the useful part, so keep it and drop the markup.+ label = _safe_label(tag.body)+ return label if "id" in tag.attrs and label else None+ if kind is _HOGQL_KIND:+ return _render_hogql(tag, project_url)+ return _render_reference(tag, kind, project_url)+++def rewrite_object_tags_for_slack(text: str, *, project_url: str) -> str:+ """Replace agent object tags in ``text`` with markdown Slack can render.++ ``project_url`` is the absolute ``/project/<id>`` base every object link hangs off. Tags inside+ fenced code blocks and inline code spans stay literal, as they do in the desktop renderer.+ """+ if "<" not in text:+ return text+ base = project_url.rstrip("/")+ tags = _scan_tags(text, _code_spans(text))+ if not tags:+ return text+ output = ""+ position = 0+ needs_paragraph_break = False+ for tag in tags:+ rendered = _render_tag(tag, base)+ if rendered is None:+ continue+ before = text[position : tag.start]+ if needs_paragraph_break:+ # The fence must end its line, so anything after it starts a new paragraph.+ before = "\n\n" + before.lstrip("\n")+ needs_paragraph_break = False+ output += before+ if "\n" in rendered:+ # A fenced block only survives markdown conversion as its own paragraph.+ if output.strip() and not output.endswith("\n\n"):+ output = output.rstrip("\n") + "\n\n"+ needs_paragraph_break = True+ output += rendered+ position = tag.end+ rest = text[position:]+ if needs_paragraph_break and rest.strip():+ rest = "\n\n" + rest.lstrip("\n")+ return output + rest+++# A streamed flush that ends inside a tag would post the fragments as raw XML; hold back at most+# this much so a genuinely unterminated tag still flushes eventually.+_MAX_HELD_SUFFIX = 4000+++@frozen+class StreamSplit:+ """A streamed chunk split into the part safe to post now and an incomplete trailing tag."""++ sendable: str+ held: str+++def _unclosed_fence_start(text: str) -> int | None:+ fence_char = ""+ fence_length = 0+ fence_start = 0+ offset = 0+ for line in text.split("\n"):+ fence = _RE_FENCE_LINE.match(line)+ if fence_char:+ if (+ fence is not None+ and fence.group(1)[0] == fence_char+ and len(fence.group(1)) >= fence_length+ and line[fence.end() :].strip() == ""+ ):+ fence_char = ""+ elif fence:+ fence_char = fence.group(1)[0]+ fence_length = len(fence.group(1))+ fence_start = offset+ offset += len(line) + 1+ return fence_start if fence_char else None+++def split_incomplete_tag_suffix(text: str) -> StreamSplit:+ """Split off a trailing object tag, or code fence, that has not finished arriving.++ Used between streaming flushes so a tag split across two chunks is rewritten whole in the+ next one, and a tag inside a still-open fence is not rewritten at all. The whole text can be+ held; the caller then waits for more instead of posting.+ """+ held_from: int | None = _unclosed_fence_start(text)+ last_lt = text.rfind("<")+ if held_from is not None:+ pass+ elif last_lt != -1 and ">" not in text[last_lt:] and re.fullmatch(r"<(?:[a-z][\w-]*(?:\s[^>]*)?)?", text[last_lt:]):+ held_from = last_lt+ else:+ last_open = None+ for match in _RE_OPEN_TAG.finditer(text):+ if match.group(3) == ">" and _resolve_kind(match.group(1)) is not None:+ last_open = match+ if (+ last_open is not None+ and re.search(rf"</{re.escape(last_open.group(1))}\s*>", text[last_open.end() :]) is None+ ):+ held_from = last_open.start()+ if held_from is None or len(text) - held_from > _MAX_HELD_SUFFIX:+ return StreamSplit(sendable=text, held="")+ return StreamSplit(sendable=text[:held_from], held=text[held_from:])diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_object_tags.py b/products/tasks/backend/temporal/slack_relay/tests/test_object_tags.pynew file mode 100644index 000000000000..e4e9e8a83af2--- /dev/null+++ b/products/tasks/backend/temporal/slack_relay/tests/test_object_tags.py@@ -0,0 +1,251 @@+import unittest++from parameterized import parameterized++from products.tasks.backend.temporal.slack_relay.activities import _markdown_to_slack_mrkdwn+from products.tasks.backend.temporal.slack_relay.object_tags import (+ rewrite_object_tags_for_slack,+ split_incomplete_tag_suffix,+)++PROJECT = "https://us.posthog.com/project/2"+UUID = "0190f8a1-7c3e-7b2a-9d4f-2a1b3c4d5e6f"+++def rewrite(text: str) -> str:+ return rewrite_object_tags_for_slack(text, project_url=PROJECT)+++class TestRewriteObjectTagsForSlack(unittest.TestCase):+ @parameterized.expand(+ [+ ("insight", "9pQx3", "/insights/9pQx3"),+ ("dashboard", "123", "/dashboard/123"),+ ("error", UUID, f"/error_tracking/{UUID}"),+ ("replay", "0190f8a1-sess", "/replay/0190f8a1-sess"),+ ("flag", "42", "/feature_flags/42"),+ ("experiment", "7", "/experiments/7"),+ ("survey", UUID, f"/surveys/{UUID}"),+ ("ticket", UUID, f"/support/tickets/{UUID}"),+ ("trace", UUID, f"/ai-observability/traces/{UUID}"),+ ("eval", "5", "/ai-evals/evaluations/5"),+ ("event", UUID, f"/data-management/events/{UUID}"),+ ("cohort", "9", "/cohorts/9"),+ ("action", "11", "/data-management/actions/11"),+ ("person", UUID, f"/persons/{UUID}"),+ ("person", "a b", "/persons/a%20b"),+ ("session-replay", "sess", "/replay/sess"),+ ("session_replay", "sess", "/replay/sess"),+ ("recording", "sess", "/replay/sess"),+ ("feature-flag", "42", "/feature_flags/42"),+ ("feature_flag", "42", "/feature_flags/42"),+ ("sql", "SELECT 1", "/sql?open_query=SELECT%201"),+ ]+ )+ def test_every_kind_and_alias_links_to_its_page(self, tag: str, object_id: str, path: str) -> None:+ if tag == "sql":+ text = f'<sql label="label">{object_id}</sql>'+ else:+ text = f'<{tag} id="{object_id}">label</{tag}>'+ separator = "&" if "?" in path else "?"+ assert rewrite(text) == f"[label]({PROJECT}{path}{separator}unfurl=false)"++ @parameterized.expand(+ [+ ("flag_cited_by_key", '<flag id="new-checkout-flow">new-checkout-flow</flag>', "new-checkout-flow"),+ ("event_cited_by_name", '<event id="$pageview">pageview</event>', "pageview"),+ ("unknown_kind_with_id", '<inbox id="019f">Split generated PRs</inbox>', "Split generated PRs"),+ ]+ )+ def test_reference_without_a_page_keeps_only_its_label(self, _name: str, text: str, expected: str) -> None:+ assert rewrite(f"before {text} after") == f"before {expected} after"++ @parameterized.expand(+ [+ (+ "self_closing_inline_uses_kind_and_id_as_label",+ 'Rolled out <flag id="42"/> yesterday.',+ f"Rolled out [Feature flag 42]({PROJECT}/feature_flags/42?unfurl=false) yesterday.",+ ),+ (+ "block_insight_keeps_unfurl_on",+ '<insight id="THgiHKou" display="block"/>',+ f"[Insight THgiHKou]({PROJECT}/insights/THgiHKou)",+ ),+ (+ "block_replay_links_into_player",+ '<replay id="sess-1" display="block"/>',+ f"[Session replay sess-1]({PROJECT}/replay/sess-1)",+ ),+ (+ "title_attribute_wins_over_body_and_id",+ '<insight id="abc" title="Checkout funnel" display="block"/>',+ f"[Checkout funnel]({PROJECT}/insights/abc)",+ ),+ (+ "escaped_sql_body_is_unescaped_before_linking",+ '<hogql label="small">SELECT value < 3</hogql>',+ f"[small]({PROJECT}/sql?open_query=SELECT%20value%20%3C%203&unfurl=false)",+ ),+ (+ "html_entities_that_are_not_xml_stay_in_the_sql",+ "<hogql label=\"mark\">SELECT '©'</hogql>",+ f"[mark]({PROJECT}/sql?open_query=SELECT%20%27%26copy%3B%27&unfurl=false)",+ ),+ (+ "inline_tag_right_after_a_block_starts_its_own_paragraph",+ '<hogql display="block" title="T">SELECT 1</hogql><insight id="1">x</insight>',+ f"**[T]({PROJECT}/sql?open_query=SELECT%201&unfurl=false)**\n```\nSELECT 1\n```\n\n[x]({PROJECT}/insights/1?unfurl=false)",+ ),+ (+ "backtick_identifiers_in_sql_do_not_hide_the_tag",+ '<hogql display="block" title="Events">SELECT `event` FROM events</hogql>',+ f"**[Events]({PROJECT}/sql?open_query=SELECT%20%60event%60%20FROM%20events&unfurl=false)**\n```\nSELECT `event` FROM events\n```",+ ),+ (+ "legacy_id_in_body_form_links_to_the_insight",+ "See <insight>abc123</insight> for the trend.",+ f"See [Insight abc123]({PROJECT}/insights/abc123?unfurl=false) for the trend.",+ ),+ (+ "title_only_query_tag_keeps_the_title",+ '<insight title="Signups by day" query_kind="TrendsQuery">{"kind":"TrendsQuery"}</insight>',+ "Signups by day",+ ),+ (+ "inline_hogql_links_to_sql_editor",+ 'See <hogql label="signups today">SELECT count() FROM events</hogql>.',+ f"See [signups today]({PROJECT}/sql?open_query=SELECT%20count%28%29%20FROM%20events&unfurl=false).",+ ),+ (+ "label_characters_that_break_slack_links_are_dropped",+ '<insight id="1">a | b [d]</insight>',+ f"[a b d]({PROJECT}/insights/1?unfurl=false)",+ ),+ (+ "comparison_operators_in_labels_become_entities",+ '<insight id="1" title="Error rate > 1%"/> and <insight id="2">users < 30 days</insight>',+ f"[Error rate > 1%]({PROJECT}/insights/1?unfurl=false) and [users < 30 days]({PROJECT}/insights/2?unfurl=false)",+ ),+ (+ "xml_entities_in_attributes_are_unescaped",+ '<hogql label="a & b">SELECT 1</hogql>',+ f"[a & b]({PROJECT}/sql?open_query=SELECT%201&unfurl=false)",+ ),+ ]+ )+ def test_rewrites(self, _name: str, text: str, expected: str) -> None:+ assert rewrite(text) == expected++ @parameterized.expand(+ [+ ("unknown_self_closing_tag", "line one<br/>line two"),+ ("unterminated_tag", 'The <insight id="9pQx3">checkout funnel dropped.'),+ ("tag_missing_id", "<insight>checkout funnel</insight>"),+ ("tag_inside_inline_code", 'Write `<insight id="1">x</insight>` to cite.'),+ ("tag_inside_double_backtick_code", 'Write ``<insight id="1">x</insight>`` to cite.'),+ ("tag_inside_fenced_code", '```xml\n<insight id="1">x</insight>\n```'),+ ("tag_inside_unclosed_fence", 'Example:\n```xml\n<insight id="1">x</insight>'),+ ("tag_inside_tilde_fence", '~~~\n<insight id="1">x</insight>\n~~~'),+ ("text_without_tags", "plain **bold** text"),+ ]+ )+ def test_leaves_text_alone(self, _name: str, text: str) -> None:+ assert rewrite(text) == text++ def test_block_hogql_becomes_titled_fenced_sql_in_its_own_paragraph(self) -> None:+ text = (+ "Here is the split:\n"+ '<hogql display="block" title="Unassigned %" caption="Ready-only strips the mix shift">'+ "SELECT day,\n count() AS n\nFROM reports\nGROUP BY day</hogql>\n"+ "Aug 26 is still partial."+ )+ assert rewrite(text) == (+ "Here is the split:\n\n"+ f"**[Unassigned %]({PROJECT}/sql?open_query=SELECT%20day%2C%0A%20%20%20%20%20%20%20count%28%29%20AS%20n%0AFROM%20reports%0AGROUP%20BY%20day&unfurl=false)**\n"+ "```\n"+ "SELECT day,\n count() AS n\nFROM reports\nGROUP BY day\n"+ "```\n"+ "_Ready-only strips the mix shift_\n\n"+ "Aug 26 is still partial."+ )++ def test_block_hogql_with_oversized_sql_keeps_the_sql_but_drops_the_link(self) -> None:+ sql = "SELECT " + ", ".join(f"col_{i}" for i in range(400))+ rendered = rewrite(f'<hogql display="block" title="Wide">{sql}</hogql>')+ assert rendered == f"**Wide**\n```\n{sql}\n```"++ def test_many_tags_in_one_message_all_rewrite(self) -> None:+ text = " ".join(f'<insight id="i{i}">insight {i}</insight>' for i in range(500))+ rendered = rewrite(text)+ assert "<insight" not in rendered+ assert rendered.count("](") == 500++ def test_code_spans_interleaved_with_tags_only_skip_the_code(self) -> None:+ text = " ".join('`<flag id="1"/>` <flag id="2">live</flag>' for _ in range(200))+ rendered = rewrite(text)+ assert rendered.count('`<flag id="1"/>`') == 200+ assert rendered.count(f"[live]({PROJECT}/feature_flags/2?unfurl=false)") == 200++ def test_long_backtick_runs_do_not_hide_tags_or_stall(self) -> None:+ # Runs of different lengths never pair into a code span, so the tag between them is live.+ text = "x " + "`" * 20000 + ' <flag id="42">beta</flag> ' + "`" * 19999+ assert rewrite(text).count(f"[beta]({PROJECT}/feature_flags/42?unfurl=false)") == 1++ def test_unmatched_openers_do_not_stop_later_tags_rewriting(self) -> None:+ text = ('<insight id="open"> ' * 300) + '<flag id="42">beta</flag>'+ rendered = rewrite(text)+ assert rendered.endswith(f"[beta]({PROJECT}/feature_flags/42?unfurl=false)")+ assert rendered.count('<insight id="open">') == 300++ def test_rewritten_output_survives_mrkdwn_conversion(self) -> None:+ text = (+ 'Two tiles: <insight id="F6tNdPRe">ready-only</insight> and <insight id="jjF0PSO2" display="block"/>\n\n'+ '<hogql display="block" title="DAU">SELECT 1</hogql>'+ )+ converted = _markdown_to_slack_mrkdwn(rewrite(text))+ assert f"<{PROJECT}/insights/F6tNdPRe?unfurl=false|ready-only>" in converted+ assert f"<{PROJECT}/insights/jjF0PSO2|Insight jjF0PSO2>" in converted+ assert f"*<{PROJECT}/sql?open_query=SELECT%201&unfurl=false|DAU>*" in converted+ assert "```\nSELECT 1\n```" in converted+ assert "<hogql" not in converted++ def test_entities_in_labels_survive_mrkdwn_conversion(self) -> None:+ converted = _markdown_to_slack_mrkdwn(rewrite('<insight id="1" title="Error rate > 1%"/>'))+ assert converted == f"<{PROJECT}/insights/1?unfurl=false|Error rate > 1%>"+++class TestSplitIncompleteTagSuffix(unittest.TestCase):+ @parameterized.expand(+ [+ ("opener_cut_mid_attribute", 'The <insight id="9pQ', "The ", '<insight id="9pQ'),+ ("opener_cut_before_name", "The <", "The ", "<"),+ ("body_still_streaming", 'The <insight id="1">check', "The ", '<insight id="1">check'),+ (+ "complete_tag_is_sent",+ 'The <insight id="1">x</insight> dropped',+ 'The <insight id="1">x</insight> dropped',+ "",+ ),+ ("self_closing_tag_is_sent", 'See <flag id="1"/> now', 'See <flag id="1"/> now', ""),+ ("comparison_is_not_a_tag", "a < b and c", "a < b and c", ""),+ ("unknown_tag_is_sent", "x <unknown>y", "x <unknown>y", ""),+ ("whole_text_is_held_when_it_is_all_one_open_tag", '<insight id="1">check', "", '<insight id="1">check'),+ (+ "open_fence_is_held",+ 'Example:\n```xml\n<insight id="1">x</insight>',+ "Example:\n",+ '```xml\n<insight id="1">x</insight>',+ ),+ ("closed_fence_is_sent", "```\nx\n```\ndone", "```\nx\n```\ndone", ""),+ ]+ )+ def test_split(self, _name: str, text: str, sendable: str, held: str) -> None:+ split = split_incomplete_tag_suffix(text)+ assert (split.sendable, split.held) == (sendable, held)++ def test_oversized_suffix_is_sent_rather_than_held(self) -> None:+ text = "intro " + '<insight id="1">' + "x" * 5000+ split = split_incomplete_tag_suffix(text)+ assert split.held == ""+ assert split.sendable == text