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(conversations): convert code blocks between slack and app (#67066)

Alex V589153f04049
diff --git a/products/conversations/backend/api/tests/test_formatting.py b/products/conversations/backend/api/tests/test_formatting.py
index 77b3f0a4f895..475bf487773c 100644
--- a/products/conversations/backend/api/tests/test_formatting.py
+++ b/products/conversations/backend/api/tests/test_formatting.py
@@ -159,6 +159,108 @@ class TestSlackFormatting(SimpleTestCase):
# 3 paragraphs: original 2 + spacer section between them
assert len(parsed_rich_content["content"]) == 3
+ def test_inbound_preformatted_becomes_code_block(self) -> None:
+ blocks = [
+ {
+ "type": "rich_text",
+ "elements": [
+ {
+ "type": "rich_text_preformatted",
+ "elements": [{"type": "text", "text": "const x = 1\nconsole.log(x)"}],
+ }
+ ],
+ }
+ ]
+
+ content, rich_content = slack_to_content_and_rich_content("", blocks)
+
+ assert rich_content is not None
+ code_node = rich_content["content"][0]
+ assert code_node["type"] == "codeBlock"
+ assert code_node["content"] == [{"type": "text", "text": "const x = 1\nconsole.log(x)"}]
+ assert content == "```\nconst x = 1\nconsole.log(x)\n```"
+
+ def test_inbound_preformatted_preserves_non_text_elements(self) -> None:
+ blocks = [
+ {
+ "type": "rich_text",
+ "elements": [
+ {
+ "type": "rich_text_preformatted",
+ "elements": [
+ {"type": "text", "text": "see "},
+ {"type": "link", "url": "https://posthog.com"},
+ {"type": "text", "text": " or ping "},
+ {"type": "user", "user_id": "U123ABC"},
+ ],
+ }
+ ],
+ }
+ ]
+
+ _, rich_content = slack_to_content_and_rich_content("", blocks, user_names={"U123ABC": "Alice"})
+
+ assert rich_content is not None
+ code_node = rich_content["content"][0]
+ assert code_node["type"] == "codeBlock"
+ assert code_node["content"] == [{"type": "text", "text": "see https://posthog.com or ping @Alice"}]
+
+ def test_outbound_code_block_emits_preformatted_and_nonempty_text(self) -> None:
+ rich_content = {
+ "type": "doc",
+ "content": [
+ {
+ "type": "codeBlock",
+ "attrs": {"language": "python"},
+ "content": [{"type": "text", "text": "print('hi')"}],
+ }
+ ],
+ }
+
+ slack_text, slack_blocks = rich_content_to_slack_payload(rich_content, "")
+
+ assert slack_blocks is not None
+ preformatted = slack_blocks[0]["elements"][0]
+ assert preformatted["type"] == "rich_text_preformatted"
+ assert preformatted["elements"] == [{"type": "text", "text": "print('hi')"}]
+ # Guard in tasks.py only posts when text or blocks are truthy - a code-only
+ # message must produce non-empty fallback text so it isn't silently dropped.
+ assert slack_text.strip() != ""
+
+ def test_outbound_empty_code_block_emits_no_preformatted_element(self) -> None:
+ rich_content = {
+ "type": "doc",
+ "content": [
+ {"type": "codeBlock", "content": []},
+ {"type": "paragraph", "content": [{"type": "text", "text": "after"}]},
+ ],
+ }
+
+ _, slack_blocks = rich_content_to_slack_payload(rich_content, "")
+
+ assert slack_blocks is not None
+ element_types = [el["type"] for el in slack_blocks[0]["elements"]]
+ assert "rich_text_preformatted" not in element_types
+
+ def test_code_block_roundtrip_preserves_content(self) -> None:
+ rich_content = {
+ "type": "doc",
+ "content": [
+ {
+ "type": "codeBlock",
+ "content": [{"type": "text", "text": "a = 1\nb = 2"}],
+ }
+ ],
+ }
+
+ slack_text, slack_blocks = rich_content_to_slack_payload(rich_content, "")
+ _, parsed_rich_content = slack_to_content_and_rich_content(slack_text, slack_blocks)
+
+ assert parsed_rich_content is not None
+ code_node = parsed_rich_content["content"][0]
+ assert code_node["type"] == "codeBlock"
+ assert code_node["content"] == [{"type": "text", "text": "a = 1\nb = 2"}]
+
@parameterized.expand(
[
("single_paragraph", 1, 1),
diff --git a/products/conversations/backend/formatting.py b/products/conversations/backend/formatting.py
index dc7da840b757..47fa80e5b1f7 100644
--- a/products/conversations/backend/formatting.py
+++ b/products/conversations/backend/formatting.py
@@ -326,6 +326,32 @@ def _parse_rich_text_inline_elements(elements: list[JSON], user_names: dict[str,
return nodes
+def _preformatted_elements_to_text(elements: list[JSON], user_names: dict[str, str] | None = None) -> str:
+ """Flatten a Slack preformatted block's inline elements to literal text.
+
+ Code blocks hold plain text (no marks/links), so each element is reduced to its
+ textual value rather than dropped: link -> label or url, emoji -> char or :name:,
+ user -> resolved name or raw mention, channel -> #name.
+ """
+ parts: list[str] = []
+ for el in elements:
+ el_type = el.get("type")
+ if el_type == "link":
+ parts.append(el.get("text") or el.get("url", ""))
+ elif el_type == "emoji":
+ char = _slack_unicode_to_char(el.get("unicode", "")) or _slack_emoji_name_to_char(el.get("name", ""))
+ parts.append(char or f":{el.get('name', '')}:")
+ elif el_type == "user":
+ uid = el.get("user_id", "")
+ name = user_names.get(uid) if user_names else None
+ parts.append(f"@{name}" if name else f"<@{uid}>")
+ elif el_type == "channel":
+ parts.append(f"#{el.get('name') or el.get('channel_id', '')}")
+ else:
+ parts.append(el.get("text", ""))
+ return "".join(parts)
+
+
def slack_blocks_to_rich_content(blocks: list[JSON] | None, user_names: dict[str, str] | None = None) -> JSON | None:
"""Parse Slack rich_text blocks into PostHog SupportEditor-compatible JSON."""
if not blocks:
@@ -360,9 +386,13 @@ def slack_blocks_to_rich_content(blocks: list[JSON] | None, user_names: dict[str
continue
if element_type == "rich_text_preformatted":
- inline_nodes = _parse_rich_text_inline_elements(element.get("elements", []), user_names)
- if inline_nodes:
- doc_nodes.append({"type": "paragraph", "content": inline_nodes})
+ code_text = _preformatted_elements_to_text(element.get("elements", []), user_names)
+ doc_nodes.append(
+ {
+ "type": "codeBlock",
+ "content": [{"type": "text", "text": code_text}] if code_text else [],
+ }
+ )
continue
if element_type == "rich_text_quote":
@@ -437,6 +467,12 @@ def rich_content_to_markdown(rich_content: JSON | None, include_images: bool = T
blocks.append(_serialize_inline_nodes_to_markdown(node.get("content", []), include_images=include_images))
continue
+ if node_type == "codeBlock":
+ code_text = "".join(child.get("text", "") for child in node.get("content", []))
+ language = node.get("attrs", {}).get("language") or ""
+ blocks.append(f"```{language}\n{code_text}\n```")
+ continue
+
if node_type == "image" and include_images:
src = node.get("attrs", {}).get("src")
if src:
@@ -518,6 +554,14 @@ def rich_content_to_slack_blocks(rich_content: JSON | None, include_images: bool
rich_text_elements.append({"type": "rich_text_section", "elements": section_elements})
continue
+ if node_type == "codeBlock":
+ code_text = "".join(child.get("text", "") for child in node.get("content", []))
+ if code_text:
+ rich_text_elements.append(
+ {"type": "rich_text_preformatted", "elements": [{"type": "text", "text": code_text}]}
+ )
+ continue
+
if node_type == "image" and include_images:
src = node.get("attrs", {}).get("src")
if src: