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.

fix(slack): render agent object tags as links instead of dropping them (#101485)

Vojta Bartoš6e19aa2e2a11
diff --git a/products/tasks/backend/temporal/slack_relay/object_tags.py b/posthog/object_tags/slack.py
similarity index 74%
rename from products/tasks/backend/temporal/slack_relay/object_tags.py
rename to posthog/object_tags/slack.py
index 0609d21e24c2..0abdb4582562 100644
--- a/products/tasks/backend/temporal/slack_relay/object_tags.py
+++ b/posthog/object_tags/slack.py
@@ -6,14 +6,20 @@ those into chips and chart cards; Slack has no renderer, so a raw tag reaches th
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 comes from ``posthog/object_tags/kinds.py``, the same source of truth the
+The kind registry comes from ``kinds.py`` beside this module, the same source of truth the
desktop and web renderers are generated from.
"""
import re
from posthog.dataclasses import frozen
-from posthog.object_tags.kinds import OBJECT_KINDS, ObjectKindSpec, object_web_path, resolve_object_kind
+from posthog.object_tags.kinds import (
+ OBJECT_KIND_ALIASES,
+ OBJECT_KINDS,
+ ObjectKindSpec,
+ object_web_path,
+ resolve_object_kind,
+)
# 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.
@@ -32,6 +38,9 @@ _RE_BACKTICK_RUN = re.compile(r"`+")
_RE_LABEL_UNSAFE = re.compile(r"[\[\]|]")
_LABEL_ANGLE_ENTITIES = {"<": "&lt;", ">": "&gt;"}
_RE_BARE_ID = re.compile(r"^[\w$.:-]{1,64}$")
+_RE_TRAILING_LIST_MARKER = re.compile(r"(^|\n)[ \t]{0,3}(?:[-*+]|\d{1,9}[.)])[ \t]*$")
+_RE_ID_ATTR = re.compile(r"(?:^|\s)id\s*=")
+_RE_PARTIAL_OPEN_TAG = re.compile(r"<(?:[a-z][\w-]*(?:\s[^>]*)?)?")
_HOGQL_SPEC = OBJECT_KINDS["hogql"]
@@ -64,10 +73,6 @@ class _Tag:
end: int
-def _resolve_kind(name: str) -> ObjectKindSpec | None:
- return resolve_object_kind(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)}
@@ -92,12 +97,13 @@ def _inline_code_spans(line: str, offset: int) -> list[_Span]:
return spans
-def _code_spans(text: str) -> list[_Span]:
- """Fenced blocks and inline code, found in one pass over the lines.
+def _scan_code(text: str) -> tuple[list[_Span], int | None]:
+ """Fenced blocks and inline code in one pass, plus the start of an unclosed fence.
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.
+ unclosed fence runs to the end of the text. The held-suffix logic needs the unclosed fence's
+ start, so the walker returns it rather than a second walker recomputing the fence state.
"""
spans: list[_Span] = []
fence_char = ""
@@ -125,7 +131,8 @@ def _code_spans(text: str) -> list[_Span]:
offset += len(line) + 1
if fence_char:
spans.append(_Span(start=fence_start, end=len(text)))
- return spans
+ return spans, fence_start
+ return spans, None
def _scan_tags(text: str, skip_spans: list[_Span]) -> list[_Tag]:
@@ -170,13 +177,23 @@ def _scan_tags(text: str, skip_spans: list[_Span]) -> list[_Tag]:
return tags
+def _escape_angles(text: str) -> str:
+ """Entity-encode angle brackets so agent-written text cannot post a Slack broadcast.
+
+ Slack reads ``<!channel>`` and ``<!here>`` as live mentions. An agent composes this text,
+ and an agent summarizes data it was asked to analyze, so the brackets never reach Slack
+ as typed.
+ """
+ return "".join(_LABEL_ANGLE_ENTITIES.get(char, char) for char in text)
+
+
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)
+ return _escape_angles(collapsed)
def _link(label: str, url: str | None) -> str:
@@ -207,8 +224,13 @@ def _render_hogql(tag: _Tag, project_url: str) -> str | None:
title = _safe_label(tag.attrs.get("title") or "") or _HOGQL_SPEC.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())
+ # A backtick run in the SQL at least as long as the fence would close it early and
+ # spill the rest — including a live ``<!channel>`` an agent could be induced to
+ # write — outside the code block.
+ longest_run = max((len(run.group(0)) for run in _RE_BACKTICK_RUN.finditer(sql)), default=0)
+ fence = "`" * max(3, longest_run + 1)
+ lines = [f"**{_link(title, url)}**", fence, sql, fence]
+ caption = _escape_angles(" ".join((tag.attrs.get("caption") or "").split()))
if caption:
lines.append(f"_{caption}_")
return "\n".join(lines)
@@ -229,7 +251,7 @@ def _render_reference(tag: _Tag, kind: ObjectKindSpec, project_url: str) -> str
def _render_tag(tag: _Tag, project_url: str) -> str | None:
- kind = _resolve_kind(tag.name)
+ kind = resolve_object_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.
@@ -249,7 +271,8 @@ def rewrite_object_tags_for_slack(text: str, *, project_url: str) -> str:
if "<" not in text:
return text
base = project_url.rstrip("/")
- tags = _scan_tags(text, _code_spans(text))
+ spans, _ = _scan_code(text)
+ tags = _scan_tags(text, spans)
if not tags:
return text
output = ""
@@ -267,6 +290,9 @@ def rewrite_object_tags_for_slack(text: str, *, project_url: str) -> str:
output += before
if "\n" in rendered:
# A fenced block only survives markdown conversion as its own paragraph.
+ # A list marker whose only content is this block would be left as an empty
+ # bullet once the block moves out, so the bare marker goes too.
+ output = _RE_TRAILING_LIST_MARKER.sub(r"\1", output)
if output.strip() and not output.endswith("\n\n"):
output = output.rstrip("\n") + "\n\n"
needs_paragraph_break = True
@@ -291,27 +317,26 @@ class StreamSplit:
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
+_KNOWN_TAG_NAMES = [*OBJECT_KINDS, *OBJECT_KIND_ALIASES]
+
+
+def _in_span(position: int, spans: list[_Span]) -> bool:
+ return any(span.contains(position) for span in spans)
+
+
+def _partial_could_become_tag(fragment: str) -> bool:
+ """Could this partial tag fragment still become a tag the renderer would touch?
+
+ Either the name so far is a prefix of a registered kind, or the fragment already
+ carries an ``id`` attribute (the object-shaped improvisations the renderer keeps
+ the label of). Anything else — ``plain <widget`` — is prose.
+ """
+ match = re.match(r"<([a-z][\w-]*)", fragment)
+ name = match.group(1) if match else ""
+ if re.search(r"\s", fragment):
+ # The name is complete; only the attributes are still streaming.
+ return resolve_object_kind(name) is not None or _RE_ID_ATTR.search(fragment[1 + len(name) :]) is not None
+ return any(known.startswith(name) for known in _KNOWN_TAG_NAMES)
def split_incomplete_tag_suffix(text: str) -> StreamSplit:
@@ -319,18 +344,37 @@ def split_incomplete_tag_suffix(text: str) -> StreamSplit:
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; the caller then waits for more instead of posting. Unlike the web rewriter, an open
+ fence is held: the splitter is stateless across flushes, so the fence's closer has to arrive
+ into the same buffer for the rewrite to see the fence whole.
+
+ Only the region after the last complete tag is considered, so tag-shaped text inside a
+ complete tag's body — SQL quoting ``'<insight id="x">'`` — never splits the text. Openers
+ inside code spans are prose, not streaming tags.
"""
- held_from: int | None = _unclosed_fence_start(text)
+ spans, held_from = _scan_code(text)
+ search_from = 0
+ if held_from is None:
+ tags = _scan_tags(text, spans)
+ if tags:
+ search_from = tags[-1].end
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:]):
+ elif (
+ last_lt >= search_from
+ and not _in_span(last_lt, spans)
+ and ">" not in text[last_lt:]
+ and _RE_PARTIAL_OPEN_TAG.fullmatch(text[last_lt:])
+ and _partial_could_become_tag(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:
+ if match.start() < search_from or match.group(3) != ">" or _in_span(match.start(), spans):
+ continue
+ if resolve_object_kind(match.group(1)) is not None or _RE_ID_ATTR.search(match.group(2)):
last_open = match
if (
last_open is not None
diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_object_tags.py b/posthog/object_tags/test/test_slack.py
similarity index 82%
rename from products/tasks/backend/temporal/slack_relay/tests/test_object_tags.py
rename to posthog/object_tags/test/test_slack.py
index 5595136793c7..34d423fc3cc8 100644
--- a/products/tasks/backend/temporal/slack_relay/tests/test_object_tags.py
+++ b/posthog/object_tags/test/test_slack.py
@@ -2,10 +2,7 @@ import unittest
from parameterized import parameterized
-from products.tasks.backend.temporal.slack_relay.object_tags import (
- rewrite_object_tags_for_slack,
- split_incomplete_tag_suffix,
-)
+from posthog.object_tags.slack import rewrite_object_tags_for_slack, split_incomplete_tag_suffix
PROJECT = "https://us.posthog.com/project/2"
UUID = "0190f8a1-7c3e-7b2a-9d4f-2a1b3c4d5e6f"
@@ -26,6 +23,7 @@ class TestRewriteObjectTagsForSlack(unittest.TestCase):
("experiment", "7", "/experiments/7"),
("survey", UUID, f"/surveys/{UUID}"),
("ticket", UUID, f"/support/tickets/{UUID}"),
+ ("report", "rep-1", "/inbox/rep-1"),
("trace", UUID, f"/ai-observability/traces/{UUID}"),
("eval", "5", "/ai-evals/evaluations/5"),
("event", UUID, f"/data-management/events/{UUID}"),
@@ -131,11 +129,39 @@ class TestRewriteObjectTagsForSlack(unittest.TestCase):
'<hogql label="a &amp; b">SELECT 1</hogql>',
f"[a & b]({PROJECT}/sql?open_query=SELECT%201&unfurl=false)",
),
+ (
+ "a_broadcast_in_a_label_cannot_ping_the_channel",
+ '<insight id="1" title="&lt;!channel&gt;"/>',
+ f"[&lt;!channel&gt;]({PROJECT}/insights/1?unfurl=false)",
+ ),
+ (
+ "a_broadcast_in_a_caption_cannot_ping_the_channel",
+ '<hogql display="block" title="T" caption="&lt;!channel&gt;">SELECT 1</hogql>',
+ f"**[T]({PROJECT}/sql?open_query=SELECT%201&unfurl=false)**\n```\nSELECT 1\n```\n_&lt;!channel&gt;_",
+ ),
+ (
+ "sql_quoting_tag_markup_stays_one_tag",
+ 'See <hogql label="q">SELECT \'<insight id="x">\'</hogql>.',
+ f"See [q]({PROJECT}/sql?open_query=SELECT%20%27%3Cinsight%20id%3D%22x%22%3E%27&unfurl=false).",
+ ),
]
)
def test_rewrites(self, _name: str, text: str, expected: str) -> None:
assert rewrite(text) == expected
+ def test_the_fence_grows_past_any_backtick_run_in_the_sql(self) -> None:
+ # A run at least as long as the fence would close it early and spill the rest of
+ # the SQL — including a live broadcast token — outside the code block.
+ rendered = rewrite('<hogql display="block" title="T">a\n```\n<!channel> b</hogql>')
+ assert rendered == (
+ f"**[T]({PROJECT}/sql?open_query=a%0A%60%60%60%0A%3C%21channel%3E%20b&unfurl=false)**\n"
+ "````\na\n```\n<!channel> b\n````"
+ )
+
+ def test_a_list_marker_whose_only_content_is_a_block_is_dropped(self) -> None:
+ rendered = rewrite('- <hogql display="block" title="T">SELECT 1</hogql>')
+ assert rendered == f"**[T]({PROJECT}/sql?open_query=SELECT%201&unfurl=false)**\n```\nSELECT 1\n```"
+
@parameterized.expand(
[
("unknown_self_closing_tag", "line one<br/>line two"),
@@ -213,6 +239,16 @@ class TestSplitIncompleteTagSuffix(unittest.TestCase):
("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", ""),
+ ("unknown_partial_is_sent", "plain <widget", "plain <widget", ""),
+ ("unregistered_partial_with_id_is_held", 'x <inbox id="r', "x ", '<inbox id="r'),
+ ("unregistered_opener_with_id_is_held", 'x <inbox id="r1">lab', "x ", '<inbox id="r1">lab'),
+ ("opener_inside_inline_code_is_sent", 'Use `<insight id="a">` now', 'Use `<insight id="a">` now', ""),
+ (
+ "quoted_markup_inside_a_complete_tag_is_sent",
+ "<hogql>SELECT '<insight id=\"x\">'</hogql>",
+ "<hogql>SELECT '<insight id=\"x\">'</hogql>",
+ "",
+ ),
("whole_text_is_held_when_it_is_all_one_open_tag", '<insight id="1">check', "", '<insight id="1">check'),
(
"open_fence_is_held",
diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.py
index 67ab9f784a75..9437751f7182 100644
--- a/products/slack_app/backend/services/slack_messages.py
+++ b/products/slack_app/backend/services/slack_messages.py
@@ -196,70 +196,6 @@ def normalize_labeled_mentions_to_bare(text: str) -> str:
return _RE_LABELED_USER_MENTION.sub(r"<@\1>", text)
-# Object tags are the agent's way of citing a PostHog object inline:
-# `<insight id="9pQx3">checkout funnel</insight>`, `<hogql label="signups today">SELECT …</hogql>`,
-# `<replay id="…" display="block"/>`. The desktop app turns them into chips and chart cards.
-# Slack has no renderer for them, so the markup reaches the reader as literal text.
-# Kinds and aliases mirror `OBJECT_KINDS` in
-# products/desktop/packages/ui/src/utils/objectKinds.ts — an unlisted tag name stays literal,
-# the same way the desktop parser leaves it alone.
-_OBJECT_TAG_KINDS = frozenset(
- {
- "insight",
- "hogql",
- "dashboard",
- "error",
- "replay",
- "flag",
- "experiment",
- "survey",
- "ticket",
- "report",
- "trace",
- "eval",
- "event",
- "cohort",
- "action",
- "person",
- "session-replay",
- "recording",
- "feature-flag",
- "feature_flag",
- "sql",
- }
-)
-_RE_OBJECT_TAG = re.compile(r"""<(\/?)([a-z][\w-]*)(?:\s+[a-z][\w-]*\s*=\s*(?:"[^"]*"|'[^']*'))*\s*(\/?)>""")
-
-
-def strip_object_tags(text: str) -> str:
- pieces: list[str] = []
- cursor = 0
- active_kind: str | None = None
- depth = 0
- for tag in _RE_OBJECT_TAG.finditer(text):
- closing, kind, self_closing = tag.groups()
- if kind not in _OBJECT_TAG_KINDS:
- continue
- if active_kind is not None:
- if kind == active_kind:
- if closing:
- depth -= 1
- elif not self_closing:
- depth += 1
- if depth == 0:
- active_kind = None
- cursor = tag.end()
- continue
- pieces.append(text[cursor : tag.start()])
- cursor = tag.end()
- if not closing and not self_closing:
- active_kind = kind
- depth = 1
- if active_kind is None:
- pieces.append(text[cursor:])
- return "".join(pieces)
-
-
def flatten_block_text(node: Any) -> list[str]:
"""Best-effort plain-text extraction from a Slack block-kit subtree.
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index a9e68ef01175..a9b8d7376b03 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -20,9 +20,9 @@ from products.slack_app.backend.services.slack_messages import (
normalize_labeled_mentions_to_bare,
personal_integrations_url,
post_slack_thread_reply,
+ project_web_url,
reply_footer_block,
slack_message_exists,
- strip_object_tags,
turn_feedback_block,
viewer_has_code_access,
)
@@ -76,10 +76,12 @@ def _split_markdown_text(text: str, limit: int = _MARKDOWN_CHUNK_LIMIT) -> list[
def _markdown_text_pieces(text: str) -> list[str]:
"""Prepare agent prose for `markdown_text` stream chunks.
- Object tags go first because Slack renders none of them, then labeled mentions become
- bare ones so an echoed ping notifies, then the result is split to fit a chunk.
+ Object tags are already markdown by the time they reach here, because the activity that
+ owns the text rewrites them into links and only it knows which project the cited objects
+ live in. This is transport, so it takes the prose as given: labeled mentions become bare
+ ones so an echoed ping notifies, then the result is split to fit a chunk.
"""
- text = normalize_labeled_mentions_to_bare(strip_object_tags(text))
+ text = normalize_labeled_mentions_to_bare(text)
return _split_markdown_text(text) if text.strip() else []
@@ -178,6 +180,15 @@ class SlackThreadHandler:
self._integration = Integration.objects.get(id=self.context.integration_id)
return self._integration
+ @property
+ def project_url(self) -> str:
+ """Base for links to the objects this thread's replies cite.
+
+ Reuses the memoized integration, so asking for it costs nothing beyond the lookup
+ posting already does.
+ """
+ return project_web_url(self._get_integration().team_id)
+
def _get_client(self) -> WebClient:
if self._client is None:
integration = self._get_integration()
diff --git a/products/slack_app/backend/tests/services/slack_messages/test_strip_object_tags.py b/products/slack_app/backend/tests/services/slack_messages/test_strip_object_tags.py
deleted file mode 100644
index f6763f164919..000000000000
--- a/products/slack_app/backend/tests/services/slack_messages/test_strip_object_tags.py
+++ /dev/null
@@ -1,32 +0,0 @@
-import unittest
-
-from parameterized import parameterized
-
-from products.slack_app.backend.services.slack_messages import strip_object_tags
-
-
-class TestStripObjectTags(unittest.TestCase):
- @parameterized.expand(
- [
- ("inline_element", 'Before <insight id="1">hidden label</insight> after.', "Before after."),
- ("SQL_payload", '<hogql title="Daily signups" label="Fallback" display="block">SELECT 1</hogql>', ""),
- ("SQL_alias", "<sql>SELECT 1</sql>", ""),
- ("self_closing_block", '<replay id="example" title="Recording" display="block"/>', ""),
- ("single_quoted_attributes", "<insight id='example'>Hidden</insight>", ""),
- ("nested_same_kind", "<insight>outer<insight>inner</insight>tail</insight>Kept", "Kept"),
- ("nested_other_kind", "<insight>outer<report>inner</report>tail</insight>Kept", "Kept"),
- ("consecutive_elements", "<insight>One</insight><hogql>SELECT 1</hogql>Kept", "Kept"),
- ("unfinished_body", 'Before <hogql title="Hidden">SELECT', "Before "),
- ("stray_closing_tag", "Before </insight> after", "Before after"),
- ("inline_code", "Use `<insight>Hidden</insight>`.", "Use ``."),
- ("fenced_code", "```xml\n<insight>Hidden</insight>\n```", "```xml\n\n```"),
- ("mixed_code", "~~~\nKeep this.\n<insight>Hidden</insight>\n~~~", "~~~\nKeep this.\n\n~~~"),
- ("unknown_markup", "<summary>Keep this</summary>", "<summary>Keep this</summary>"),
- ("encoded_mention_in_title", '<insight title="&lt;!channel&gt;">Hidden</insight>', ""),
- ("raw_mention_in_body", "<insight><!here></insight>", ""),
- ("explicit_mention", "<!here>", "<!here>"),
- ("empty_text", "", ""),
- ]
- )
- def test_strip(self, _name: str, text: str, expected: str) -> None:
- assert strip_object_tags(text) == expected
diff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.py
index 606d35afc3f5..f3f583eff407 100644
--- a/products/slack_app/backend/tests/test_slack_thread.py
+++ b/products/slack_app/backend/tests/test_slack_thread.py
@@ -61,35 +61,6 @@ class TestSlackThreadHandler(SimpleTestCase):
assert "<@U094TR1E59V>" in streamed
assert "Radu Raicea" not in streamed
- @parameterized.expand(
- [
- ("surrounding_prose", 'The <insight id="9pQx3">checkout funnel</insight> dropped.', "The dropped."),
- ("only_element", '<hogql title="Hidden">SELECT 1</hogql>', ""),
- ]
- )
- @patch.object(SlackThreadHandler, "_get_client")
- def test_stop_status_stream_strips_object_tags(
- self, _name: str, text: str, expected: str, mock_get_client: MagicMock
- ) -> None:
- client = mock_get_client.return_value
- context = SlackThreadContext(integration_id=1, channel="C001", thread_ts="1234.5678")
- SlackThreadHandler(context).stop_status_stream(ts="1234.9999", final_markdown=text)
- chunks = [chunk for call in client.chat_appendStream.call_args_list for chunk in call.kwargs["chunks"]]
- assert "".join(chunk.get("text", "") for chunk in chunks) == expected
- if not expected:
- client.chat_appendStream.assert_not_called()
- client.chat_stopStream.assert_called_once()
-
- @patch.object(SlackThreadHandler, "_get_client")
- def test_streamed_label_cannot_create_mentions(self, mock_get_client: MagicMock) -> None:
- context = SlackThreadContext(integration_id=1, channel="C001", thread_ts="1234.5678")
- SlackThreadHandler(context).stop_status_stream(
- ts="1234.9999",
- final_markdown='<insight title="&lt;!channel&gt;">Example</insight> and <!here>',
- )
- chunks = mock_get_client.return_value.chat_appendStream.call_args.kwargs["chunks"]
- assert "".join(chunk.get("text", "") for chunk in chunks) == " and <!here>"
-
@patch.object(SlackThreadHandler, "_find_progress_message_ts", return_value=None)
@patch.object(SlackThreadHandler, "_get_client")
def test_progress_message_carries_only_the_logs_button(self, mock_get_client, _mock_find_progress):
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.py
index 6caa1d19dfbc..11f699886813 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
@@ -12,6 +12,7 @@ from typing import Any, Optional
from temporalio import activity
from posthog.dataclasses import frozen
+from posthog.object_tags.slack import rewrite_object_tags_for_slack
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import close_db_connections
@@ -63,10 +64,16 @@ class StopSlackAgentDesignStreamInput:
trace_id: Optional[str] = None
-def _strip_object_tags(text: Optional[str]) -> Optional[str]:
- from products.slack_app.backend.services.slack_messages import strip_object_tags
+def _rewrite_object_tags(text: Optional[str], project_url: str) -> Optional[str]:
+ """Turn the agent's object tags into the markdown links Slack can render.
- return strip_object_tags(text) if text else text
+ Slack renders none of the tags itself, so they have to become markdown before the text is
+ posted. Rewriting rather than dropping them keeps the label the agent wrote, so a bullet
+ whose only content is a citation still carries text.
+ """
+ if not text:
+ return text
+ return rewrite_object_tags_for_slack(text, project_url=project_url)
@activity.defn
@@ -78,11 +85,12 @@ def start_slack_agent_design_stream(input: StartSlackAgentDesignStreamInput) ->
try:
context = SlackThreadContext.from_dict(input.slack_thread_context)
- return SlackThreadHandler(context).start_status_stream(
+ handler = SlackThreadHandler(context)
+ return handler.start_status_stream(
first_task_id=input.first_task_id,
first_task_title=input.first_task_title,
first_task_details=input.first_task_details,
- first_markdown_text=_strip_object_tags(input.first_markdown_text),
+ first_markdown_text=_rewrite_object_tags(input.first_markdown_text, handler.project_url),
)
except Exception as e:
logger.warning("slack_app_start_agent_design_stream_failed", error=str(e))
@@ -97,12 +105,13 @@ def append_slack_agent_design_steps(input: AppendSlackAgentDesignStepsInput) ->
try:
context = SlackThreadContext.from_dict(input.slack_thread_context)
- SlackThreadHandler(context).append_status_chunks(
+ handler = SlackThreadHandler(context)
+ handler.append_status_chunks(
ts=input.ts,
task_updates=[
{"id": t.id, "title": t.title, "status": t.status, "details": t.details} for t in input.task_updates
],
- markdown_text=_strip_object_tags(input.markdown_text),
+ markdown_text=_rewrite_object_tags(input.markdown_text, handler.project_url),
)
except Exception as e:
logger.warning("slack_app_append_agent_design_steps_failed", error=str(e))
@@ -124,7 +133,7 @@ def stop_slack_agent_design_stream(input: StopSlackAgentDesignStreamInput) -> No
complete_task_id=input.complete_task_id,
complete_task_title=input.complete_task_title,
complete_task_details=input.complete_task_details,
- final_markdown=_strip_object_tags(input.final_markdown),
+ final_markdown=_rewrite_object_tags(input.final_markdown, handler.project_url),
)
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.py
index 728e289565fd..4ad9e7910c64 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,7 +25,7 @@ from temporalio.common import RetryPolicy
from posthog.temporal.common.base import PostHogWorkflow
with workflow.unsafe.imports_passed_through():
- from products.tasks.backend.temporal.slack_relay.object_tags import split_incomplete_tag_suffix
+ from posthog.object_tags.slack import split_incomplete_tag_suffix
from .activities.slack_agent_design import (
AppendSlackAgentDesignStepsInput,
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.py
index 7afd71e77ed3..02a93bed57b2 100644
--- 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.py
@@ -1,6 +1,6 @@
from typing import ClassVar
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, PropertyMock, patch
from django.test import SimpleTestCase, TestCase, override_settings
@@ -9,13 +9,17 @@ from parameterized import parameterized
from posthog.models.integration import Integration
from posthog.models.organization import Organization
from posthog.models.team.team import Team
+from posthog.object_tags.slack import split_incomplete_tag_suffix
-from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler
+from products.slack_app.backend.slack_thread import SlackThreadHandler
from products.tasks.backend.temporal.process_task.activities.slack_agent_design import (
+ AppendSlackAgentDesignStepsInput,
StopSlackAgentDesignStreamInput,
+ append_slack_agent_design_steps,
stop_slack_agent_design_stream,
)
-from products.tasks.backend.temporal.slack_relay.object_tags import split_incomplete_tag_suffix
+
+PROJECT_URL = "https://us.posthog.com/project/7"
class TestBufferedSlackAgentDesignStream(SimpleTestCase):
@@ -27,12 +31,16 @@ class TestBufferedSlackAgentDesignStream(SimpleTestCase):
("open_fence", "```", False),
]
)
+ @patch.object(SlackThreadHandler, "project_url", new_callable=PropertyMock, return_value=PROJECT_URL)
@patch.object(SlackThreadHandler, "_get_client")
- def test_strips_buffered_code_elements(
- self, _name: str, fence: str, closed: bool, mock_get_client: MagicMock
+ def test_buffered_code_elements_reach_slack_intact(
+ self, _name: str, fence: str, closed: bool, mock_get_client: MagicMock, _project_url: PropertyMock
) -> None:
+ # Goes through the activities, so the rewriter runs on every flush. A tag cut by a flush
+ # boundary is held back and sent whole in the next one, and a tag inside a fence stays
+ # literal, so the example arrives as the agent typed it.
client = mock_get_client.return_value
- context = SlackThreadContext(integration_id=1, channel="C001", thread_ts="1234.5678")
+ context = {"integration_id": 1, "channel": "C001", "thread_ts": "1234.5678"}
updates = [f"Before\n\n{fence}xml\n", '<insight id="1">', "Example</insight>\n"]
if closed:
updates.append(f"{fence}\n\nAfter\n")
@@ -41,18 +49,24 @@ class TestBufferedSlackAgentDesignStream(SimpleTestCase):
split = split_incomplete_tag_suffix(pending + update)
pending = split.held
if split.sendable:
- SlackThreadHandler(context).append_status_chunks(
- ts="1234.9999",
- markdown_text=split.sendable,
+ append_slack_agent_design_steps(
+ AppendSlackAgentDesignStepsInput(
+ slack_thread_context=context,
+ ts="1234.9999",
+ markdown_text=split.sendable,
+ )
)
- SlackThreadHandler(context).stop_status_stream(
- ts="1234.9999",
- final_markdown=pending,
+ stop_slack_agent_design_stream(
+ StopSlackAgentDesignStreamInput(
+ slack_thread_context=context,
+ ts="1234.9999",
+ final_markdown=pending,
+ )
)
streamed = "".join(
chunk.get("text", "") for call in client.chat_appendStream.call_args_list for chunk in call.kwargs["chunks"]
)
- assert streamed == "".join(updates).replace('<insight id="1">Example</insight>', "")
+ assert streamed == "".join(updates)
@override_settings(SITE_URL="https://us.posthog.com")
@@ -68,7 +82,9 @@ class TestSlackAgentDesignStream(TestCase):
cls.integration = Integration.objects.create(team=cls.team, kind="slack", integration_id="T123", config={})
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.stop_status_stream")
- def test_streamed_final_answer_removes_object_elements(self, mock_stop) -> None:
+ def test_streamed_final_answer_links_object_elements(self, mock_stop) -> None:
+ # Slack renders none of the tags, so dropping one takes the agent's own label with it.
+ # The project comes from the thread's integration, so the link opens where the reader is.
stop_slack_agent_design_stream(
StopSlackAgentDesignStreamInput(
slack_thread_context={"integration_id": self.integration.id, "channel": "C1", "thread_ts": "1.0"},
@@ -79,7 +95,9 @@ class TestSlackAgentDesignStream(TestCase):
mock_stop.assert_called_once()
final_markdown = mock_stop.call_args.kwargs["final_markdown"]
- assert final_markdown == "The dropped."
+ assert final_markdown == (
+ f"The [checkout funnel](https://us.posthog.com/project/{self.team.id}/insights/9pQx3?unfurl=false) dropped."
+ )
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.stop_status_stream", autospec=True)
def test_closing_the_stream_hands_the_reply_the_turns_trace_id(self, mock_stop) -> None:
diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.py
index 1019daca9330..bc58433f9e88 100644
--- a/products/tasks/backend/temporal/slack_relay/activities.py
+++ b/products/tasks/backend/temporal/slack_relay/activities.py
@@ -5,6 +5,7 @@ from temporalio import activity
from posthog.dataclasses import frozen
from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, opens_with_line_anchored_markdown
+from posthog.object_tags.slack import rewrite_object_tags_for_slack
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import close_db_connections
@@ -176,7 +177,7 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
from products.slack_app.backend.services.slack_messages import (
load_run_footer,
normalize_labeled_mentions_to_bare,
- strip_object_tags,
+ project_web_url,
)
from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler
from products.tasks.backend.models import TaskRun
@@ -204,10 +205,13 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
logger.info("slack_relay_empty_text", run_id=input.run_id, relay_id=input.relay_id)
return
- # Rewrite echoed ``<@U…|name>`` tokens to the bare ``<@U…>`` so the mentions the agent
- # composed actually notify their targets. Done before splitting: the bare form is shorter,
- # so it never enlarges a chunk.
- text = normalize_labeled_mentions_to_bare(strip_object_tags(text)).strip()
+ # Object tags become the markdown links Slack can render, and echoed ``<@U…|name>`` tokens
+ # become the bare ``<@U…>`` so the mentions the agent composed actually notify their targets.
+ # Both run before splitting: a rewritten tag carries a URL, so it grows the text it sits in
+ # and the chunk budget has to be measured after it.
+ text = normalize_labeled_mentions_to_bare(
+ rewrite_object_tags_for_slack(text, project_url=project_web_url(task_run.team_id))
+ ).strip()
# Living-artifacts gating lives in the service: has_pending_slack_file_artifacts
# (and deliver_pending_slack_file_artifacts below) return falsy when the
diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
index 9a6762f1a55e..b322c5804835 100644
--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
@@ -81,15 +81,7 @@ class TestRelaySlackMessage(TestCase):
@parameterized.expand(
[
("no_reaction_emoji", "relay-1", "Which license should I use?", None, "Which license should I use?"),
- ("only_objects", "relay-only-objects", '<hogql title="Hidden">SELECT 1</hogql>', None, ""),
("explicit_reaction_emoji", "relay-2", "Could not deliver follow-up", "x", "Could not deliver follow-up"),
- (
- "object_elements",
- "relay-objects",
- 'Before <insight id="1">hidden label</insight><hogql display="block" title="Hidden title">SELECT 123</hogql> after.',
- None,
- "Before after.",
- ),
]
)
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.update_reaction")
@@ -117,14 +109,8 @@ class TestRelaySlackMessage(TestCase):
)
mock_delete_progress.assert_called_once()
- if expected_text:
- mock_post.assert_called_once()
- assert expected_text in mock_post.call_args.args[0]
- assert "hidden label" not in mock_post.call_args.args[0]
- assert "Hidden title" not in mock_post.call_args.args[0]
- assert "SELECT 123" not in mock_post.call_args.args[0]
- else:
- mock_post.assert_not_called()
+ mock_post.assert_called_once()
+ assert expected_text in mock_post.call_args.args[0]
if reaction_emoji is None:
mock_update.assert_not_called()
else:
@@ -163,6 +149,26 @@ class TestRelaySlackMessage(TestCase):
assert mock_post.call_args.args[0].endswith(self._RICH_ANSWER)
+ @override_settings(SITE_URL="https://us.posthog.com")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")
+ def test_object_tags_reach_slack_as_links_into_the_runs_project(self, mock_delete_progress, mock_post):
+ # Slack renders none of the tags, so dropping one takes the agent's own label with it and
+ # a bullet that holds only a citation posts empty. The link also has to carry the run's
+ # project, or it opens somewhere the reader cannot follow.
+ relay_slack_message(
+ RelaySlackMessageInput(
+ run_id=str(self.task_run.id),
+ relay_id="relay-object-tags",
+ text='- <insight id="geFISqzd">Sandbox 2.0</insight>\n- <hogql label="signups">SELECT 1</hogql>',
+ )
+ )
+
+ posted = mock_post.call_args.args[0]
+ base = f"https://us.posthog.com/project/{self.team.id}"
+ assert f"- [Sandbox 2.0]({base}/insights/geFISqzd?unfurl=false)" in posted
+ assert f"- [signups]({base}/sql?open_query=SELECT%201&unfurl=false)" in posted
+
@parameterized.expand(
[
("heading", "## Heading\n\nBody text.", "<@U123>\n\n## Heading"),