: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(conversations): render and serialize standard rich text nodes (#73165)
Christiaan Hendriksen1ac93031b48b
diff --git a/products/conversations/backend/api/tests/test_formatting.py b/products/conversations/backend/api/tests/test_formatting.pyindex 475bf487773c..08a08e5c902b 100644--- a/products/conversations/backend/api/tests/test_formatting.py+++ b/products/conversations/backend/api/tests/test_formatting.py@@ -5,19 +5,31 @@ from parameterized import parameterizedfrom products.conversations.backend.formatting import (_slack_emoji_name_to_char,_slack_unicode_to_char,+ content_to_slack_mrkdwn,extract_images_from_rich_content,extract_slack_user_ids,+ rich_content_to_html,+ rich_content_to_markdown,rich_content_to_slack_payload,slack_to_content_and_rich_content,)+def _paragraph(text: str) -> dict:+ return {"type": "paragraph", "content": [{"type": "text", "text": text}]}+++def _list_item(*content: dict) -> dict:+ return {"type": "listItem", "content": list(content)}++class TestSlackFormatting(SimpleTestCase):@parameterized.expand([("single_newline", "line1\nline2", "line1 \nline2"),("double_newline", "line1\n\nline2", "line1\n\nline2"),("mrkdwn_marks", "*bold*\n_italic_", "**bold** \n*italic*"),+ ("mrkdwn_strike", "~gone~", "~~gone~~"),])def test_text_fallback_normalizes_newlines(self, _name: str, slack_text: str, expected: str) -> None:@@ -287,6 +299,20 @@ class TestSlackFormatting(SimpleTestCase):else:assert el["elements"][0]["text"] == "\n"+ @parameterized.expand(+ [+ ("bold_stays_bold", "**bold**", "*bold*"),+ ("italic", "*italic*", "_italic_"),+ ("bold_italic", "***both***", "*_both_*"),+ ("strike", "~~gone~~", "~gone~"),+ ("escaped_punctuation_unescaped", "e\\.g\\. query\\-time \\(v2\\)", "e.g. query-time (v2)"),+ ("escaped_syntax_not_emphasis", "2 \\* 3 \\* 4", "2 * 3 * 4"),+ ("backslash_outside_escape_set_kept", "path C:\\\\Users", "path C:\\Users"),+ ]+ )+ def test_outbound_mrkdwn_conversion(self, _name: str, markdown: str, expected: str) -> None:+ assert content_to_slack_mrkdwn(markdown) == expected+def test_outbound_excludes_images_from_text_when_requested(self) -> None:rich_content = {"type": "doc",@@ -435,3 +461,284 @@ class TestSlackFormatting(SimpleTestCase):content, rich_content = slack_to_content_and_rich_content("", blocks)assert "<@UXYZ999>" in contentassert rich_content is not None+++class TestRichContentBlockNodes(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "bullet_list",+ {+ "type": "doc",+ "content": [+ {+ "type": "bulletList",+ "content": [_list_item(_paragraph("one")), _list_item(_paragraph("two"))],+ }+ ],+ },+ "- one\n- two",+ ),+ (+ "ordered_list_respects_start",+ {+ "type": "doc",+ "content": [+ {+ "type": "orderedList",+ "attrs": {"start": 3},+ "content": [_list_item(_paragraph("three")), _list_item(_paragraph("four"))],+ }+ ],+ },+ "3. three\n4. four",+ ),+ (+ "nested_list_indented",+ {+ "type": "doc",+ "content": [+ {+ "type": "orderedList",+ "content": [+ _list_item(+ _paragraph("parent"),+ {"type": "bulletList", "content": [_list_item(_paragraph("child"))]},+ )+ ],+ }+ ],+ },+ "1. parent\n - child",+ ),+ (+ "heading_blockquote_and_rule",+ {+ "type": "doc",+ "content": [+ {"type": "heading", "attrs": {"level": 2}, "content": [{"type": "text", "text": "Options"}]},+ {"type": "blockquote", "content": [_paragraph("quoted")]},+ {"type": "horizontalRule"},+ ],+ },+ "## Options\n\n> quoted\n\n---",+ ),+ (+ "strike_mark",+ {+ "type": "doc",+ "content": [+ {+ "type": "paragraph",+ "content": [{"type": "text", "text": "gone", "marks": [{"type": "strike"}]}],+ }+ ],+ },+ "~~gone~~",+ ),+ (+ "blockquote_wrapping_list",+ {+ "type": "doc",+ "content": [+ {+ "type": "blockquote",+ "content": [+ _paragraph("see options:"),+ {+ "type": "bulletList",+ "content": [_list_item(_paragraph("one")), _list_item(_paragraph("two"))],+ },+ ],+ }+ ],+ },+ "> see options:\n> - one\n> - two",+ ),+ (+ "unknown_block_keeps_inline_content",+ {+ "type": "doc",+ "content": [{"type": "callout", "content": [{"type": "text", "text": "do not lose me"}]}],+ },+ "do not lose me",+ ),+ ]+ )+ def test_rich_content_to_markdown_block_nodes(self, _name: str, doc: dict, expected: str) -> None:+ assert rich_content_to_markdown(doc) == expected++ def test_slack_payload_falls_back_to_text_when_blocks_cannot_represent_doc(self) -> None:+ doc = {+ "type": "doc",+ "content": [+ _paragraph("Two options:"),+ {+ "type": "orderedList",+ "content": [_list_item(_paragraph("query time properties")), _list_item(_paragraph("a cohort"))],+ },+ ],+ }+ text, blocks = rich_content_to_slack_payload(doc, "fallback")+ assert blocks is None+ assert "1. query time properties" in text+ assert "2. a cohort" in text++ def test_slack_payload_maps_strike_to_slack_mrkdwn(self) -> None:+ doc = {+ "type": "doc",+ "content": [+ {+ "type": "bulletList",+ "content": [+ _list_item(+ {+ "type": "paragraph",+ "content": [{"type": "text", "text": "gone", "marks": [{"type": "strike"}]}],+ }+ )+ ],+ }+ ],+ }+ text, blocks = rich_content_to_slack_payload(doc, "fallback")+ assert blocks is None+ assert text == "- ~gone~"++ def test_slack_text_fallback_is_not_markdown_escaped(self) -> None:+ doc = {+ "type": "doc",+ "content": [+ _paragraph("Two options (pick one):"),+ {+ "type": "bulletList",+ "content": [_list_item(_paragraph("Use query-time properties, e.g. person.email"))],+ },+ ],+ }+ text, blocks = rich_content_to_slack_payload(doc, "fallback")+ assert blocks is None+ assert text == "Two options (pick one):\n\n- Use query-time properties, e.g. person.email"++ @parameterized.expand(+ [+ ("bullet", "bullet", "bulletList", "- item one"),+ ("ordered", "ordered", "orderedList", "1. item one"),+ ]+ )+ def test_inbound_slack_list_blocks_become_list_nodes(+ self, _name: str, style: str, expected_node_type: str, expected_content_line: str+ ) -> None:+ blocks = [+ {+ "type": "rich_text",+ "elements": [+ {+ "type": "rich_text_list",+ "style": style,+ "elements": [+ {"type": "rich_text_section", "elements": [{"type": "text", "text": "item one"}]},+ {"type": "rich_text_section", "elements": [{"type": "text", "text": "item two"}]},+ ],+ }+ ],+ }+ ]+ content, rich_content = slack_to_content_and_rich_content("", blocks)+ assert rich_content is not None+ list_node = rich_content["content"][0]+ assert list_node["type"] == expected_node_type+ assert [item["type"] for item in list_node["content"]] == ["listItem", "listItem"]+ assert expected_content_line in content++ def test_rich_content_to_html_renders_hogdesk_block_nodes(self) -> None:+ doc = {+ "type": "doc",+ "content": [+ {"type": "heading", "attrs": {"level": 2}, "content": [{"type": "text", "text": "Options"}]},+ {+ "type": "orderedList",+ "attrs": {"start": 2},+ "content": [+ _list_item(+ _paragraph("parent"),+ {"type": "bulletList", "content": [_list_item(_paragraph("child"))]},+ )+ ],+ },+ {"type": "horizontalRule"},+ {+ "type": "paragraph",+ "content": [{"type": "text", "text": "gone", "marks": [{"type": "strike"}]}],+ },+ ],+ }+ html = rich_content_to_html(doc)+ assert "<h2>Options</h2>" in html+ assert '<ol start="2"><li>parent<ul><li>child</li></ul></li></ol>' in html+ assert "<hr>" in html+ assert "<s>gone</s>" in html++ def test_rich_content_to_html_renders_unknown_block_inline_content_as_paragraph(self) -> None:+ doc = {+ "type": "doc",+ "content": [{"type": "callout", "content": [{"type": "text", "text": "do not lose me"}]}],+ }+ html = rich_content_to_html(doc)+ assert "<p>do not lose me</p>" in html++ def test_rich_content_to_markdown_keeps_non_paragraph_blocks_in_list_items(self) -> None:+ doc = {+ "type": "doc",+ "content": [+ {+ "type": "bulletList",+ "content": [+ _list_item(+ _paragraph("intro"),+ {"type": "heading", "attrs": {"level": 3}, "content": [{"type": "text", "text": "Step"}]},+ {+ "type": "codeBlock",+ "attrs": {"language": "python"},+ "content": [{"type": "text", "text": "print(1)"}],+ },+ )+ ],+ }+ ],+ }+ md = rich_content_to_markdown(doc)+ assert "### Step" in md+ assert "```python" in md+ assert "print(1)" in md++ def test_rich_content_to_html_keeps_non_paragraph_blocks_in_list_items(self) -> None:+ doc = {+ "type": "doc",+ "content": [+ {+ "type": "orderedList",+ "content": [+ _list_item(+ _paragraph("intro"),+ {"type": "codeBlock", "content": [{"type": "text", "text": "print(1)"}]},+ )+ ],+ }+ ],+ }+ html = rich_content_to_html(doc)+ assert "<li>intro<pre><code>print(1)</code></pre></li>" in html++ def test_rich_content_to_html_keeps_non_paragraph_blocks_in_blockquote(self) -> None:+ doc = {+ "type": "doc",+ "content": [+ {+ "type": "blockquote",+ "content": [_paragraph("see"), {"type": "bulletList", "content": [_list_item(_paragraph("one"))]}],+ }+ ],+ }+ html = rich_content_to_html(doc)+ assert "<blockquote>see<br><ul><li>one</li></ul></blockquote>" in htmldiff --git a/products/conversations/backend/formatting.py b/products/conversations/backend/formatting.pyindex a7f426e46f4c..69bdd8b4043a 100644--- a/products/conversations/backend/formatting.py+++ b/products/conversations/backend/formatting.py@@ -16,16 +16,19 @@ _RE_SLACK_LINK_BARE = re.compile(r"<([^>]+)>")_RE_SLACK_BOLD_ITALIC = re.compile(r"\*_([^_]+)_\*")_RE_SLACK_BOLD = re.compile(r"(?<!\*)\*([^*\n]+)\*(?!\*)")_RE_SLACK_ITALIC = re.compile(r"(?<!_)_([^_\n]+)_(?!_)")+_RE_SLACK_STRIKE = re.compile(r"(?<!~)~([^~\n]+)~(?!~)")# Markdown patterns_RE_MD_IMAGE = re.compile(r"!\[([^\]]*)\]\(([^)]+)\)")_RE_MD_BOLD_ITALIC = re.compile(r"\*\*\*(.+?)\*\*\*")_RE_MD_BOLD = re.compile(r"\*\*(.+?)\*\*")_RE_MD_ITALIC = re.compile(r"(?<!\*)\*([^*]+?)\*(?!\*)")+_RE_MD_STRIKE = re.compile(r"~~(.+?)~~")_RE_MD_LINK = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")_RE_MD_MENTION = re.compile(r"@member:([a-f0-9-]+)")_RE_SINGLE_NEWLINE = re.compile(r"(?<!\n)\n(?!\n)")_RE_MD_ESCAPE = re.compile(r"([\\`*_{}\[\]()#+\-.!|])")+_RE_MD_ESCAPED_CHAR = re.compile(r"\\([\\`*_{}\[\]()#+\-.!|])")_RE_ALT_ESCAPE = re.compile(r"([\\\]])")_RE_SLACK_EMOJI = re.compile(r":([a-z0-9_+\-]+):")@@ -159,12 +162,26 @@ def strip_slack_user_mentions(text: str) -> str:def content_to_slack_mrkdwn(content: str) -> str:- """Convert markdown comment content to Slack mrkdwn text."""+ """Convert markdown comment content to Slack mrkdwn text.++ Backslash-escaped characters are unescaped: mrkdwn has no escape syntax, so a+ markdown ``\\.`` would otherwise reach Slack as a literal backslash. They are+ masked before the syntax conversions below so an escaped ``*`` is not mistaken+ for emphasis.+ """if not content:return ""text = content+ escaped_chars: list[str] = []++ def capture_escaped_char(match: re.Match) -> str:+ escaped_chars.append(match.group(1))+ return f"\x00ESC{len(escaped_chars) - 1}\x00"++ text = _RE_MD_ESCAPED_CHAR.sub(capture_escaped_char, text)+text = _RE_MD_IMAGE.sub(r"<\2|\1>", text)bold_italic_matches: list[str] = []@@ -174,10 +191,21 @@ def content_to_slack_mrkdwn(content: str) -> str:return f"\x00BI{len(bold_italic_matches) - 1}\x00"text = _RE_MD_BOLD_ITALIC.sub(capture_bold_italic, text)- text = _RE_MD_BOLD.sub(r"*\1*", text)++ bold_matches: list[str] = []++ def capture_bold(match: re.Match) -> str:+ bold_matches.append(match.group(1))+ return f"\x00B{len(bold_matches) - 1}\x00"++ text = _RE_MD_BOLD.sub(capture_bold, text)text = _RE_MD_ITALIC.sub(r"_\1_", text)+ text = _RE_MD_STRIKE.sub(r"~\1~", text)text = _RE_MD_LINK.sub(r"<\2|\1>", text)+ for index, value in enumerate(bold_matches):+ text = text.replace(f"\x00B{index}\x00", f"*{value}*")+for index, value in enumerate(bold_italic_matches):text = text.replace(f"\x00BI{index}\x00", f"*_{value}_*")@@ -194,7 +222,12 @@ def content_to_slack_mrkdwn(content: str) -> str:passreturn "@teammate"- return _RE_MD_MENTION.sub(resolve_mention, text)+ text = _RE_MD_MENTION.sub(resolve_mention, text)++ for index, value in enumerate(escaped_chars):+ text = text.replace(f"\x00ESC{index}\x00", value)++ return textdef slack_mrkdwn_to_content(text: str, user_names: dict[str, str] | None = None) -> str:@@ -219,6 +252,7 @@ def slack_mrkdwn_to_content(text: str, user_names: dict[str, str] | None = None)text = _RE_SLACK_BOLD_ITALIC.sub(r"***\1***", text)text = _RE_SLACK_BOLD.sub(r"**\1**", text)text = _RE_SLACK_ITALIC.sub(r"*\1*", text)+ text = _RE_SLACK_STRIKE.sub(r"~~\1~~", text)return text@@ -248,6 +282,8 @@ def _style_to_marks(style: JSON | None) -> list[JSON]:marks.append({"type": "italic"})if style.get("underline"):marks.append({"type": "underline"})+ if style.get("strike"):+ marks.append({"type": "strike"})if style.get("code"):marks.append({"type": "code"})return marks@@ -263,6 +299,8 @@ def _marks_to_slack_style(marks: Iterable[JSON]) -> JSON:style["italic"] = Trueelif mark_type == "underline":style["underline"] = True+ elif mark_type == "strike":+ style["strike"] = Trueelif mark_type == "code":style["code"] = Truereturn style@@ -380,14 +418,16 @@ def slack_blocks_to_rich_content(blocks: list[JSON] | None, user_names: dict[strcontinueif element_type == "rich_text_list":+ list_type = "orderedList" if element.get("style") == "ordered" else "bulletList"+ items: list[JSON] = []for list_item in element.get("elements", []):if list_item.get("type") != "rich_text_section":continueinline_nodes = _parse_rich_text_inline_elements(list_item.get("elements", []), user_names)if inline_nodes:- prefix = "• "- inline_nodes.insert(0, {"type": "text", "text": prefix})- doc_nodes.append({"type": "paragraph", "content": inline_nodes})+ items.append({"type": "listItem", "content": [{"type": "paragraph", "content": inline_nodes}]})+ if items:+ doc_nodes.append({"type": list_type, "content": items})continueif element_type == "rich_text_preformatted":@@ -429,6 +469,8 @@ def _serialize_text_node_to_markdown(node: JSON) -> str:text = f"**{text}**"elif mark_type == "italic":text = f"*{text}*"+ elif mark_type == "strike":+ text = f"~~{text}~~"elif mark_type == "code":text = f"`{text}`" if "`" not in text else f"`` {text} ``"# Underline has no standard markdown syntax - preserve in rich content only.@@ -455,6 +497,102 @@ def _serialize_inline_nodes_to_markdown(nodes: list[JSON], include_images: boolreturn "".join(chunks)+def _list_start(node: JSON) -> int:+ attrs = node.get("attrs") or {}+ try:+ return max(int(attrs.get("start") or 1), 1)+ except (TypeError, ValueError):+ return 1+++def _serialize_block_node_to_markdown(node: JSON, include_images: bool = True) -> str:+ """Serialize a single non-list block node to markdown. Lists are handled by+ _serialize_list_to_markdown because they carry indentation state."""+ node_type = node.get("type")++ if node_type == "paragraph":+ return _serialize_inline_nodes_to_markdown(node.get("content", []), include_images=include_images)++ if node_type == "blockquote":+ quote_lines: list[str] = []+ for child in node.get("content", []):+ child_type = child.get("type")+ if child_type in ("bulletList", "orderedList"):+ child_md = _serialize_list_to_markdown(child, child_type == "orderedList", "", include_images)+ else:+ child_md = _serialize_block_node_to_markdown(child, include_images=include_images)+ if child_md:+ quote_lines.extend(f"> {line}".rstrip() for line in child_md.split("\n"))+ return "\n".join(quote_lines)++ if node_type == "heading":+ attrs = node.get("attrs") or {}+ try:+ level = min(max(int(attrs.get("level") or 1), 1), 6)+ except (TypeError, ValueError):+ level = 1+ text = _serialize_inline_nodes_to_markdown(node.get("content", []), include_images=include_images)+ return f"{'#' * level} {text}" if text else ""++ if node_type == "horizontalRule":+ return "---"++ if node_type == "codeBlock":+ code_text = "".join(child.get("text", "") for child in node.get("content", []))+ language = node.get("attrs", {}).get("language") or ""+ return f"```{language}\n{code_text}\n```"++ if node_type == "image":+ src = node.get("attrs", {}).get("src")+ if src and include_images:+ alt = _escape_alt_text(node.get("attrs", {}).get("alt", "image"))+ return f""+ return ""++ if node.get("content"):+ return _serialize_inline_nodes_to_markdown(node.get("content", []), include_images=include_images)++ return ""+++def _serialize_list_to_markdown(node: JSON, ordered: bool, indent: str, include_images: bool = True) -> str:+ start = _list_start(node)+ lines: list[str] = []+ position = 0+ for item in node.get("content", []):+ if item.get("type") != "listItem":+ continue+ marker = f"{start + position}. " if ordered else "- "+ position += 1+ child_indent = indent + " " * len(marker)+ blocks: list[tuple[str, bool]] = []+ for child in item.get("content", []):+ child_type = child.get("type")+ if child_type in ("bulletList", "orderedList"):+ nested = _serialize_list_to_markdown(child, child_type == "orderedList", child_indent, include_images)+ if nested:+ blocks.append((nested, True))+ else:+ text = _serialize_block_node_to_markdown(child, include_images=include_images).strip()+ if text:+ blocks.append((text, False))+ if not blocks:+ lines.append((indent + marker).rstrip())+ continue+ (first_text, first_is_list), *rest = blocks+ if first_is_list:+ lines.append((indent + marker).rstrip())+ lines.append(first_text)+ else:+ lines.append(indent + marker + first_text.replace("\n", "\n" + child_indent))+ for text, is_list in rest:+ if is_list:+ lines.append(text)+ else:+ lines.append("\n".join(child_indent + line for line in text.split("\n")))+ return "\n".join(lines)++def rich_content_to_markdown(rich_content: JSON | None, include_images: bool = True) -> str:"""Serialize PostHog rich content JSON to markdown text."""if not rich_content:@@ -468,21 +606,20 @@ def rich_content_to_markdown(rich_content: JSON | None, include_images: bool = Tfor node in rich_content.get("content", []):node_type = node.get("type")- if node_type == "paragraph":- blocks.append(_serialize_inline_nodes_to_markdown(node.get("content", []), include_images=include_images))+ if node_type in ("bulletList", "orderedList"):+ list_md = _serialize_list_to_markdown(node, node_type == "orderedList", "", include_images)+ if list_md:+ blocks.append(list_md)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```")+ # Empty paragraphs are kept so intentional blank lines survive; other empty blocks are skipped.+ if node_type == "paragraph":+ blocks.append(_serialize_block_node_to_markdown(node, include_images=include_images))continue- if node_type == "image" and include_images:- src = node.get("attrs", {}).get("src")- if src:- alt = _escape_alt_text(node.get("attrs", {}).get("alt", "image"))- blocks.append(f"")+ block_md = _serialize_block_node_to_markdown(node, include_images=include_images)+ if block_md:+ blocks.append(block_md)return "\n\n".join(blocks).strip()@@ -527,11 +664,22 @@ def extract_images_from_rich_content(rich_content: JSON | None) -> list[JSON]:return images+_SLACK_BLOCK_NODE_TYPES = {"paragraph", "codeBlock", "image"}++def rich_content_to_slack_blocks(rich_content: JSON | None, include_images: bool = True) -> list[JSON] | None:- """Serialize PostHog rich content JSON into Slack rich_text blocks."""+ """Serialize PostHog rich content JSON into Slack rich_text blocks.++ Returns None when the doc contains block nodes rich_text can't represent (lists,+ headings, blockquotes, ...) so callers fall back to the complete markdown text+ instead of sending blocks with content silently missing.+ """if not rich_content or rich_content.get("type") != "doc":return None+ if any(node.get("type") not in _SLACK_BLOCK_NODE_TYPES for node in rich_content.get("content", [])):+ return None+rich_text_elements: list[JSON] = []for node in rich_content.get("content", []):@@ -623,6 +771,8 @@ def _serialize_text_node_to_html(node: JSON) -> str:escaped = f"<em>{escaped}</em>"elif mark_type == "underline":escaped = f"<u>{escaped}</u>"+ elif mark_type == "strike":+ escaped = f"<s>{escaped}</s>"elif mark_type == "code":escaped = f"<code>{escaped}</code>"elif mark_type == "link":@@ -650,6 +800,77 @@ def _serialize_inline_nodes_to_html(nodes: list[JSON]) -> str:return "".join(chunks)+def _serialize_block_node_to_html(node: JSON) -> str:+ """Serialize a single non-list block node to email-safe HTML. Lists are handled by+ _serialize_list_to_html."""+ node_type = node.get("type")++ if node_type == "paragraph":+ return f"<p>{_serialize_inline_nodes_to_html(node.get('content', []))}</p>"++ if node_type == "blockquote":+ inner_blocks: list[str] = []+ for child in node.get("content", []):+ child_type = child.get("type")+ if child_type in ("bulletList", "orderedList"):+ inner_blocks.append(_serialize_list_to_html(child, child_type == "orderedList"))+ elif child_type == "paragraph":+ inner_blocks.append(_serialize_inline_nodes_to_html(child.get("content", [])))+ else:+ inner_blocks.append(_serialize_block_node_to_html(child))+ return f"<blockquote>{'<br>'.join(inner_blocks)}</blockquote>"++ if node_type == "heading":+ attrs = node.get("attrs") or {}+ try:+ level = min(max(int(attrs.get("level") or 1), 1), 6)+ except (TypeError, ValueError):+ level = 1+ return f"<h{level}>{_serialize_inline_nodes_to_html(node.get('content', []))}</h{level}>"++ if node_type == "horizontalRule":+ return "<hr>"++ if node_type == "codeBlock":+ return f"<pre><code>{_serialize_inline_nodes_to_html(node.get('content', []))}</code></pre>"++ if node_type == "image":+ src = node.get("attrs", {}).get("src", "")+ if src:+ alt = node.get("attrs", {}).get("alt", "")+ return f'<p><img src="{_escape_html(src)}" alt="{_escape_html(alt)}"></p>'+ return ""++ if node.get("content"):+ inner = _serialize_inline_nodes_to_html(node.get("content", []))+ if inner:+ return f"<p>{inner}</p>"++ return ""+++def _serialize_list_to_html(node: JSON, ordered: bool) -> str:+ items: list[str] = []+ for item in node.get("content", []):+ if item.get("type") != "listItem":+ continue+ inner_parts: list[str] = []+ for child in item.get("content", []):+ child_type = child.get("type")+ if child_type == "paragraph":+ inner_parts.append(_serialize_inline_nodes_to_html(child.get("content", [])))+ elif child_type in ("bulletList", "orderedList"):+ inner_parts.append(_serialize_list_to_html(child, child_type == "orderedList"))+ else:+ inner_parts.append(_serialize_block_node_to_html(child))+ items.append(f"<li>{''.join(inner_parts)}</li>")+ if not ordered:+ return f"<ul>{''.join(items)}</ul>"+ start = _list_start(node)+ start_attr = f' start="{start}"' if start > 1 else ""+ return f"<ol{start_attr}>{''.join(items)}</ol>"++def rich_content_to_html(rich_content: JSON | None) -> str:"""Serialize PostHog rich content JSON to email-safe HTML."""if not rich_content or rich_content.get("type") != "doc":@@ -659,39 +880,13 @@ def rich_content_to_html(rich_content: JSON | None) -> str:for node in rich_content.get("content", []):node_type = node.get("type")- if node_type == "paragraph":- inner = _serialize_inline_nodes_to_html(node.get("content", []))- blocks.append(f"<p>{inner}</p>")- elif node_type == "blockquote":- inner_blocks: list[str] = []- for child in node.get("content", []):- if child.get("type") == "paragraph":- inner_blocks.append(_serialize_inline_nodes_to_html(child.get("content", [])))- blocks.append(f"<blockquote>{'<br>'.join(inner_blocks)}</blockquote>")- elif node_type == "bulletList":- items: list[str] = []- for item in node.get("content", []):- if item.get("type") == "listItem":- for p in item.get("content", []):- if p.get("type") == "paragraph":- items.append(f"<li>{_serialize_inline_nodes_to_html(p.get('content', []))}</li>")- blocks.append(f"<ul>{''.join(items)}</ul>")- elif node_type == "orderedList":- items_o: list[str] = []- for item in node.get("content", []):- if item.get("type") == "listItem":- for p in item.get("content", []):- if p.get("type") == "paragraph":- items_o.append(f"<li>{_serialize_inline_nodes_to_html(p.get('content', []))}</li>")- blocks.append(f"<ol>{''.join(items_o)}</ol>")- elif node_type == "codeBlock":- inner = _serialize_inline_nodes_to_html(node.get("content", []))- blocks.append(f"<pre><code>{inner}</code></pre>")- elif node_type == "image":- src = node.get("attrs", {}).get("src", "")- alt = node.get("attrs", {}).get("alt", "")- if src:- blocks.append(f'<p><img src="{_escape_html(src)}" alt="{_escape_html(alt)}"></p>')+ if node_type in ("bulletList", "orderedList"):+ blocks.append(_serialize_list_to_html(node, node_type == "orderedList"))+ continue++ html = _serialize_block_node_to_html(node)+ if html:+ blocks.append(html)body = "\n".join(blocks)return f"""<!DOCTYPE html>@@ -715,9 +910,8 @@ def rich_content_to_slack_payload("""if rich_content:blocks = rich_content_to_slack_blocks(rich_content, include_images=include_images)- if blocks:- markdown_text = rich_content_to_markdown(rich_content, include_images=include_images)- source_content = markdown_text or fallback_content- return content_to_slack_mrkdwn(source_content), blocks+ markdown_text = rich_content_to_markdown(rich_content, include_images=include_images)+ source_content = markdown_text or fallback_content+ return content_to_slack_mrkdwn(source_content), blocksreturn content_to_slack_mrkdwn(fallback_content), Nonediff --git a/products/conversations/frontend/components/Chat/Message.tsx b/products/conversations/frontend/components/Chat/Message.tsxindex 1b0f60e5f561..29c805b8e68d 100644--- a/products/conversations/frontend/components/Chat/Message.tsx+++ b/products/conversations/frontend/components/Chat/Message.tsx@@ -114,6 +114,8 @@ export function Message({<SupportRichContentPreviewcontent={message.richContent as JSONContent}className="text-sm"+ fallbackContent={message.content}+ fallbackDisableImages={message.fromZendesk}/>) : (<SupportMarkdown className="text-sm" disableImages>diff --git a/products/conversations/frontend/components/Editor/SupportEditor.scss b/products/conversations/frontend/components/Editor/SupportEditor.scssindex dd26d4ab6bcc..bafc33abdbfd 100644--- a/products/conversations/frontend/components/Editor/SupportEditor.scss+++ b/products/conversations/frontend/components/Editor/SupportEditor.scss@@ -50,6 +50,84 @@}}+// Block node styling for standard rich text (lists, headings, blockquotes, rules,+// strikethrough). Tailwind's preflight resets list markers and heading sizes, so+// these have to be restored explicitly, matching the LemonMarkdown/RichMarkdownEditor+// pattern used elsewhere.+@mixin rich-text-block-styles {+ ul,+ ol {+ padding-left: 1.5em;++ li {+ display: list-item;++ p {+ margin-bottom: 0;+ }+ }+ }++ ul {+ list-style-type: disc;+ }++ ol {+ list-style-type: decimal;+ }++ h1,+ h2,+ h3,+ h4,+ h5,+ h6 {+ margin: 0.5em 0 0.25em;+ font-weight: 600;+ line-height: 1.2;+ }++ h1 {+ font-size: 1.25em;+ }++ h2 {+ font-size: 1.125em;+ }++ h3 {+ font-size: 1em;+ }++ h4,+ h5,+ h6 {+ font-size: 0.875em;+ }++ blockquote {+ padding: 0.25em 0.75em;+ margin: 0.5em 0;+ color: var(--color-text-secondary);+ border-left: 3px solid var(--border);++ p:last-child {+ margin-bottom: 0;+ }+ }++ hr {+ margin: 1em 0;+ border: none;+ border-top: 1px solid var(--border);+ }++ s,+ del {+ text-decoration: line-through;+ }+}+.SupportEditor {.SupportEditor__content {display: flex;@@ -100,6 +178,7 @@@include inline-code-styles;@include code-block-styles;+ @include rich-text-block-styles;}.SupportRichContentPreview {@@ -136,4 +215,5 @@@include inline-code-styles;@include code-block-styles;+ @include rich-text-block-styles;}diff --git a/products/conversations/frontend/components/Editor/SupportEditor.test.ts b/products/conversations/frontend/components/Editor/SupportEditor.test.tsnew file mode 100644index 000000000000..d693ead3e19d--- /dev/null+++ b/products/conversations/frontend/components/Editor/SupportEditor.test.ts@@ -0,0 +1,106 @@+import { JSONContent, getSchema } from '@tiptap/core'+import { Node as ProseMirrorNode } from '@tiptap/pm/model'++import { SUPPORT_PREVIEW_EXTENSIONS, serializeToMarkdown } from './SupportEditor'++// jest.setup.ts stubs this module out, which would make schema construction meaningless here+jest.unmock('@tiptap/extension-code-block-lowlight')++const paragraph = (text: string): JSONContent => ({ type: 'paragraph', content: [{ type: 'text', text }] })+const listItem = (...content: JSONContent[]): JSONContent => ({ type: 'listItem', content })++describe('SupportEditor serialization and preview schema', () => {+ // The widget renders only the plain-text field, so anything dropped here is+ // invisible to widget-only customers.+ test.each<[string, JSONContent, string]>([+ [+ 'bullet list',+ {+ type: 'doc',+ content: [{ type: 'bulletList', content: [listItem(paragraph('one')), listItem(paragraph('two'))] }],+ },+ '- one\n- two',+ ],+ [+ 'ordered list respecting start',+ {+ type: 'doc',+ content: [+ {+ type: 'orderedList',+ attrs: { start: 3 },+ content: [listItem(paragraph('three')), listItem(paragraph('four'))],+ },+ ],+ },+ '3. three\n4. four',+ ],+ [+ 'nested list indented under its parent item',+ {+ type: 'doc',+ content: [+ {+ type: 'orderedList',+ content: [+ listItem(paragraph('parent'), {+ type: 'bulletList',+ content: [listItem(paragraph('child'))],+ }),+ ],+ },+ ],+ },+ '1. parent\n - child',+ ],+ [+ 'list followed by paragraph and image keeps all blocks',+ {+ type: 'doc',+ content: [+ { type: 'bulletList', content: [listItem(paragraph('item'))] },+ { type: 'image', attrs: { src: 'https://example.com/cat.png', alt: 'cat' } },+ ],+ },+ '- item\n\n',+ ],+ ])('serializeToMarkdown handles %s', (_name, doc, expected) => {+ expect(serializeToMarkdown(doc)).toBe(expected)+ })++ it('preview schema accepts docs authored with the full HogDesk node set', () => {+ const hogdeskDoc: JSONContent = {+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [+ { type: 'text', text: 'Hey,' },+ { type: 'hardBreak' },+ { type: 'text', text: 'crossed out', marks: [{ type: 'strike' }] },+ ],+ },+ { type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'Options' }] },+ {+ type: 'orderedList',+ attrs: { type: null, start: 1 },+ content: [listItem(paragraph('first')), listItem(paragraph('second'))],+ },+ { type: 'blockquote', content: [paragraph('quoted')] },+ { type: 'horizontalRule' },+ {+ type: 'image',+ attrs: { src: 'https://example.com/a.png', alt: null, title: null, width: 100, height: 50 },+ },+ ],+ }+ const schema = getSchema([...SUPPORT_PREVIEW_EXTENSIONS])+ expect(() => ProseMirrorNode.fromJSON(schema, hogdeskDoc).check()).not.toThrow()+ })++ it('preview schema rejects unknown node types so the plain-content fallback kicks in', () => {+ const doc: JSONContent = { type: 'doc', content: [{ type: 'table', content: [] }] }+ const schema = getSchema([...SUPPORT_PREVIEW_EXTENSIONS])+ expect(() => ProseMirrorNode.fromJSON(schema, doc)).toThrow('Unknown node type: table')+ })+})diff --git a/products/conversations/frontend/components/Editor/SupportEditor.tsx b/products/conversations/frontend/components/Editor/SupportEditor.tsxindex e77482e1e628..e2f85bf5c955 100644--- a/products/conversations/frontend/components/Editor/SupportEditor.tsx+++ b/products/conversations/frontend/components/Editor/SupportEditor.tsx@@ -22,7 +22,7 @@ import { common, createLowlight } from 'lowlight'import posthog from 'posthog-js'import { useCallback, useEffect, useRef, useState } from 'react'-import { IconCode, IconCopy, IconImage, IconTerminal } from '@posthog/icons'+import { IconCode, IconCopy, IconImage, IconList, IconTerminal } from '@posthog/icons'import { EmojiPickerPopover } from 'lib/components/EmojiPicker/EmojiPickerPopover'import { useRichContentEditor } from 'lib/components/RichContentEditor'@@ -117,6 +117,21 @@ const LinkShortcutExtension = Extension.create<LinkShortcutExtensionOptions>({},})+// Ordered list icon (not in @posthog/icons)+function IconOrderedList(): JSX.Element {+ return (+ <svg width="1em" height="1em" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path+ d="M10 6h10M10 12h10M10 18h10M4 6h1v4M4 10h2M4 15.5a1.5 1.5 0 1 1 3 0c0 .7-.5 1.2-1 1.7L4 19h3"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ )+}+// Underline icon (not in @posthog/icons)function IconUnderline(): JSX.Element {return (@@ -230,7 +245,7 @@ export const SUPPORT_EXTENSIONS = [heading: false,blockquote: false,// bold: enabled - Cmd+B- bulletList: false,+ // bulletList: enabled - Cmd+Shift+8// code: enabled - inline code (Cmd+E) - just visual styling, not executablecodeBlock: false, // We use our own SupportCodeBlockExtension// hardBreak: enabled - allows Shift+Enter for line breaks within paragraphs@@ -238,10 +253,10 @@ export const SUPPORT_EXTENSIONS = [// gapcursor: enabled - helps position cursor near images/blockshorizontalRule: false,// italic: enabled - Cmd+I- listItem: false,- listKeymap: false,- orderedList: false,+ // listItem/listKeymap: enabled - required by bulletList/orderedList+ // orderedList: enabled - Cmd+Shift+7strike: false,+ underline: false, // Registered explicitly below}),Underline, // Cmd+UImageExtension,@@ -250,6 +265,22 @@ export const SUPPORT_EXTENSIONS = [SupportCodeBlockExtension,]+export const SUPPORT_PREVIEW_EXTENSIONS = [+ MentionsExtension,+ RichContentNodeMention,+ ExtensionDocument,+ StarterKit.configure({+ document: false,+ link: false, // We use our own Link extension+ codeBlock: false, // We use our own SupportCodeBlockExtension+ underline: false, // Registered explicitly below+ }),+ Underline,+ ImageExtension,+ LinkExtension,+ SupportCodeBlockExtension,+]+// Plain text serialization options for generateText() - used by Comment.tsx// Extracts plain text with special handling for mentions and imagesexport const serializationOptions: { textSerializers?: Record<string, TextSerializer> } = {@@ -277,7 +308,7 @@ function escapeAltText(text: string): string {/*** Serialize tiptap JSON to markdown string.- * Handles: bold, italic, code, images, mentions, hard breaks+ * Handles: bold, italic, code, images, mentions, hard breaks, bullet/ordered lists* Note: underline has no standard markdown syntax and is stripped*/export function serializeToMarkdown(content: JSONContent): string {@@ -346,6 +377,12 @@ function serializeNode(node: JSONContent): string {return content + '\n\n'}+ case 'bulletList':+ return serializeListNode(node, false, '') + '\n\n'++ case 'orderedList':+ return serializeListNode(node, true, '') + '\n\n'+case 'hardBreak':// Two spaces + newline is the standard markdown hard breakreturn ' \n'@@ -378,6 +415,58 @@ function serializeNode(node: JSONContent): string {}}+function serializeListNode(node: JSONContent, ordered: boolean, indent: string): string {+ const rawStart = Number(node.attrs?.start ?? 1)+ const start = ordered && Number.isFinite(rawStart) ? Math.max(Math.trunc(rawStart), 1) : 1+ const lines: string[] = []+ let position = 0+ for (const item of node.content || []) {+ if (item.type !== 'listItem') {+ continue+ }+ const marker = ordered ? `${start + position}. ` : '- '+ position += 1+ const childIndent = indent + ' '.repeat(marker.length)+ const blocks: { text: string; isNestedList: boolean }[] = []+ for (const child of item.content || []) {+ if (child.type === 'bulletList' || child.type === 'orderedList') {+ const nested = serializeListNode(child, child.type === 'orderedList', childIndent)+ if (nested) {+ blocks.push({ text: nested, isNestedList: true })+ }+ } else {+ const serialized = serializeNode(child).trim()+ if (serialized) {+ blocks.push({ text: serialized, isNestedList: false })+ }+ }+ }+ if (blocks.length === 0) {+ lines.push((indent + marker).trimEnd())+ continue+ }+ const [first, ...rest] = blocks+ if (first.isNestedList) {+ lines.push((indent + marker).trimEnd(), first.text)+ } else {+ lines.push(indent + marker + first.text.split('\n').join(`\n${childIndent}`))+ }+ for (const block of rest) {+ if (block.isNestedList) {+ lines.push(block.text)+ } else {+ lines.push(+ block.text+ .split('\n')+ .map((line) => childIndent + line)+ .join('\n')+ )+ }+ }+ }+ return lines.join('\n')+}+export function SupportEditor({initialContent,placeholder,@@ -552,6 +641,20 @@ export function SupportEditor({icon={<IconUnderline />}tooltip="Underline (Cmd+U)"/>+ <LemonButton+ size="small"+ active={ttEditor?.isActive('bulletList')}+ onClick={() => ttEditor?.chain().focus().toggleBulletList().run()}+ icon={<IconList />}+ tooltip="Bullet list (Cmd+Shift+8)"+ />+ <LemonButton+ size="small"+ active={ttEditor?.isActive('orderedList')}+ onClick={() => ttEditor?.chain().focus().toggleOrderedList().run()}+ icon={<IconOrderedList />}+ tooltip="Numbered list (Cmd+Shift+7)"+ /><LemonButtonsize="small"active={ttEditor?.isActive('code')}diff --git a/products/conversations/frontend/components/Editor/SupportRichContentPreview.tsx b/products/conversations/frontend/components/Editor/SupportRichContentPreview.tsxindex 28d149be4940..eba9279345ef 100644--- a/products/conversations/frontend/components/Editor/SupportRichContentPreview.tsx+++ b/products/conversations/frontend/components/Editor/SupportRichContentPreview.tsx@@ -1,28 +1,38 @@import './SupportEditor.scss'-import { JSONContent } from '@tiptap/core'+import { JSONContent, getSchema } from '@tiptap/core'+import { Node as ProseMirrorNode } from '@tiptap/pm/model'import { EditorContent } from '@tiptap/react'import { useMemo } from 'react'import { useRichContentEditor } from 'lib/components/RichContentEditor'import { cn } from 'lib/utils/css-classes'-import { SUPPORT_EXTENSIONS } from './SupportEditor'+import { SUPPORT_PREVIEW_EXTENSIONS } from './SupportEditor'+import { SupportMarkdown } from './SupportMarkdown'import { useImageLightbox } from './useImageLightbox'-const DEFAULT_INITIAL_CONTENT: JSONContent = {- type: 'doc',- content: [- {- type: 'paragraph',- content: [],- },- ],+let previewSchema: ReturnType<typeof getSchema> | null = null++function isRenderableRichContent(content: JSONContent | null): content is JSONContent {+ if (!content) {+ return false+ }+ try {+ previewSchema = previewSchema ?? getSchema([...SUPPORT_PREVIEW_EXTENSIONS])+ ProseMirrorNode.fromJSON(previewSchema, content).check()+ return true+ } catch {+ return false+ }}export interface SupportRichContentPreviewProps {content: JSONContent | nullclassName?: string+ /** Plain-text version of the message, rendered as markdown when `content` can't be parsed */+ fallbackContent?: string+ fallbackDisableImages?: boolean}/**@@ -31,14 +41,33 @@ export interface SupportRichContentPreviewProps {*/const editorImageFilter = (el: HTMLImageElement): boolean => el.classList.contains('SupportEditor__image')-export function SupportRichContentPreview({ content, className }: SupportRichContentPreviewProps): JSX.Element {+export function SupportRichContentPreview({+ content,+ className,+ fallbackContent,+ fallbackDisableImages,+}: SupportRichContentPreviewProps): JSX.Element {+ const renderable = useMemo(() => isRenderableRichContent(content), [content])++ if (!renderable || !content) {+ return (+ <SupportMarkdown className={className} disableImages={fallbackDisableImages}>+ {fallbackContent ?? ''}+ </SupportMarkdown>+ )+ }++ return <RichContentPreviewEditor content={content} className={className} />+}++function RichContentPreviewEditor({ content, className }: { content: JSONContent; className?: string }): JSX.Element {const filter = useMemo(() => editorImageFilter, [])const { handleClick, lightbox } = useImageLightbox(filter)const editor = useRichContentEditor({- extensions: [...SUPPORT_EXTENSIONS],+ extensions: [...SUPPORT_PREVIEW_EXTENSIONS],disabled: true,- initialContent: content ?? DEFAULT_INITIAL_CONTENT,+ initialContent: content,})return (diff --git a/products/conversations/frontend/components/Editor/index.ts b/products/conversations/frontend/components/Editor/index.tsindex e3a8a5f85641..5b565f5b3d51 100644--- a/products/conversations/frontend/components/Editor/index.ts+++ b/products/conversations/frontend/components/Editor/index.ts@@ -1,4 +1,10 @@-export { SupportEditor, serializeToMarkdown, SUPPORT_EXTENSIONS, serializationOptions } from './SupportEditor'+export {+ SupportEditor,+ serializeToMarkdown,+ SUPPORT_EXTENSIONS,+ SUPPORT_PREVIEW_EXTENSIONS,+ serializationOptions,+} from './SupportEditor'export type { SupportEditorProps } from './SupportEditor'export { ImageLightbox } from './ImageLightbox'