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): format ai replies in the support widget (#124757)

Alex V9a52e85023ca
diff --git a/ee/hogai/tools/create_notebook/test_tiptap.py b/ee/hogai/tools/create_notebook/test_tiptap.py
index 22c6c2b9150f..20ba23cd7a89 100644
--- a/ee/hogai/tools/create_notebook/test_tiptap.py
+++ b/ee/hogai/tools/create_notebook/test_tiptap.py
@@ -1,16 +1,15 @@
+import time
+
from django.test import SimpleTestCase
from parameterized import parameterized
from posthog.schema import MarkdownBlock, SessionReplayBlock
+from posthog.comment.tiptap import _parse_inline, markdown_to_tiptap_nodes
+
from ee.hogai.artifacts.types import StoredBlock, VisualizationRefBlock
-from ee.hogai.tools.create_notebook.tiptap import (
- _parse_inline,
- blocks_to_tiptap_doc,
- markdown_to_tiptap_nodes,
- tiptap_doc_to_text,
-)
+from ee.hogai.tools.create_notebook.tiptap import blocks_to_tiptap_doc, tiptap_doc_to_text
class TestParseInline(SimpleTestCase):
@@ -43,6 +42,25 @@ class TestParseInline(SimpleTestCase):
}
],
),
+ (
+ "bold link label",
+ "[**Set up**](https://example.com)",
+ [
+ {
+ "type": "text",
+ "text": "Set up",
+ "marks": [
+ {"type": "bold"},
+ {"type": "link", "attrs": {"href": "https://example.com"}},
+ ],
+ }
+ ],
+ ),
+ (
+ "unsafe link stays text",
+ "[click](javascript:alert(1))",
+ [{"type": "text", "text": "[click](javascript:alert(1))"}],
+ ),
(
"mixed inline",
"hello **bold** and *italic*",
@@ -158,6 +176,100 @@ class TestMarkdownToTiptapNodes(SimpleTestCase):
}
],
),
+ (
+ "ordered list keeps its numbers across a blank line",
+ "1. first\n\n2. second",
+ [
+ {
+ "type": "orderedList",
+ "content": [
+ {
+ "type": "listItem",
+ "content": [
+ {
+ "type": "paragraph",
+ "content": [{"type": "text", "text": "first"}],
+ }
+ ],
+ },
+ {
+ "type": "listItem",
+ "content": [
+ {
+ "type": "paragraph",
+ "content": [{"type": "text", "text": "second"}],
+ }
+ ],
+ },
+ ],
+ }
+ ],
+ ),
+ (
+ "ordered item keeps the next line",
+ "1. first\nSee more",
+ [
+ {
+ "type": "orderedList",
+ "content": [
+ {
+ "type": "listItem",
+ "content": [
+ {
+ "type": "paragraph",
+ "content": [{"type": "text", "text": "first See more"}],
+ }
+ ],
+ }
+ ],
+ }
+ ],
+ ),
+ (
+ "nested bullets stay inside the numbered step",
+ "1. step\n - bullet\n2. next",
+ [
+ {
+ "type": "orderedList",
+ "content": [
+ {
+ "type": "listItem",
+ "content": [
+ {"type": "paragraph", "content": [{"type": "text", "text": "step"}]},
+ {
+ "type": "bulletList",
+ "content": [
+ {
+ "type": "listItem",
+ "content": [
+ {
+ "type": "paragraph",
+ "content": [{"type": "text", "text": "bullet"}],
+ }
+ ],
+ }
+ ],
+ },
+ ],
+ },
+ {
+ "type": "listItem",
+ "content": [
+ {"type": "paragraph", "content": [{"type": "text", "text": "next"}]},
+ ],
+ },
+ ],
+ }
+ ],
+ ),
+ (
+ "empty heading does not stall the next line",
+ "## \nAfter",
+ [
+ {"type": "paragraph", "content": [{"type": "text", "text": "## "}]},
+ {"type": "paragraph", "content": [{"type": "text", "text": "After"}]},
+ ],
+ ),
("empty string", "", []),
("whitespace only", " \n \n ", []),
]
@@ -165,6 +277,25 @@ class TestMarkdownToTiptapNodes(SimpleTestCase):
def test_markdown_to_tiptap_nodes(self, _name, markdown, expected):
assert markdown_to_tiptap_nodes(markdown) == expected
+ def test_unclosed_brackets_stay_text(self):
+ text = "[" * 20000
+ started = time.monotonic()
+ nodes = _parse_inline(text)
+ assert time.monotonic() - started < 1
+ assert nodes == [{"type": "text", "text": text}]
+
+ def test_failed_link_destination_is_not_rescanned(self):
+ text = "[" * 4000 + "](https://" + "a" * 4000
+ started = time.monotonic()
+ nodes = _parse_inline(text)
+ assert time.monotonic() - started < 1
+ assert "".join(node["text"] for node in nodes) == text
+ blocked = "[" * 2000 + "](javascript:" + "a" * 2000 + ")"
+ started = time.monotonic()
+ nodes = _parse_inline(blocked)
+ assert time.monotonic() - started < 1
+ assert "".join(node["text"] for node in nodes) == blocked
+
def test_multi_block_markdown(self):
md = "# Title\n\nSome text.\n\n- a\n- b\n\n```\ncode\n```"
nodes = markdown_to_tiptap_nodes(md)
diff --git a/ee/hogai/tools/create_notebook/tiptap.py b/ee/hogai/tools/create_notebook/tiptap.py
index 27607598262f..f9d02794f743 100644
--- a/ee/hogai/tools/create_notebook/tiptap.py
+++ b/ee/hogai/tools/create_notebook/tiptap.py
@@ -1,4 +1,3 @@
-import re
import json
from collections.abc import Sequence
from typing import Any
@@ -7,6 +6,8 @@ from pydantic import BaseModel
from posthog.schema import MarkdownBlock, SessionReplayBlock
+from posthog.comment.tiptap import markdown_to_tiptap_nodes
+
from ee.hogai.artifacts.types import VisualizationRefBlock
@@ -95,206 +96,12 @@ def _visualization_ref_to_tiptap(
]
-def markdown_to_tiptap_nodes(text: str) -> list[dict]:
- """
- Convert a markdown string to a list of tiptap nodes.
-
- Supports:
- - Headings (# to ######)
- - Paragraphs
- - Bullet lists (- or *)
- - Ordered lists (1.)
- - Code blocks (triple backtick)
- - Inline: **bold**, *italic*, `code`, [text](url)
- """
- if not text or not text.strip():
- return []
-
- lines = text.split("\n")
- nodes: list[dict] = []
- i = 0
-
- while i < len(lines):
- line = lines[i]
-
- # Code block
- if line.strip().startswith("```"):
- code_lines: list[str] = []
- lang = line.strip()[3:].strip() or None
- i += 1
- while i < len(lines) and not lines[i].strip().startswith("```"):
- code_lines.append(lines[i])
- i += 1
- i += 1 # skip closing ```
- attrs = {}
- if lang:
- attrs["language"] = lang
- node: dict = {
- "type": "codeBlock",
- "content": [{"type": "text", "text": "\n".join(code_lines)}],
- }
- if attrs:
- node["attrs"] = attrs
- nodes.append(node)
- continue
-
- # Heading
- heading_match = re.match(r"^(#{1,6})\s+(.+)$", line)
- if heading_match:
- level = len(heading_match.group(1))
- inline = _parse_inline(heading_match.group(2).strip())
- nodes.append(
- {
- "type": "heading",
- "attrs": {"level": level},
- "content": inline,
- }
- )
- i += 1
- continue
-
- # Unordered list
- if re.match(r"^\s*[-*]\s+", line):
- items: list[dict] = []
- while i < len(lines) and re.match(r"^\s*[-*]\s+", lines[i]):
- item_text = re.sub(r"^\s*[-*]\s+", "", lines[i])
- items.append(
- {
- "type": "listItem",
- "content": [_paragraph(_parse_inline(item_text))],
- }
- )
- i += 1
- nodes.append({"type": "bulletList", "content": items})
- continue
-
- # Ordered list
- if re.match(r"^\s*\d+\.\s+", line):
- items = []
- while i < len(lines) and re.match(r"^\s*\d+\.\s+", lines[i]):
- item_text = re.sub(r"^\s*\d+\.\s+", "", lines[i])
- items.append(
- {
- "type": "listItem",
- "content": [_paragraph(_parse_inline(item_text))],
- }
- )
- i += 1
- nodes.append({"type": "orderedList", "content": items})
- continue
-
- # Empty line
- if not line.strip():
- i += 1
- continue
-
- # Paragraph (collect consecutive non-empty, non-special lines)
- para_lines: list[str] = []
- while i < len(lines) and lines[i].strip() and not _is_special_line(lines[i]):
- para_lines.append(lines[i])
- i += 1
- if para_lines:
- inline = _parse_inline(" ".join(para_lines))
- nodes.append(_paragraph(inline))
-
- return nodes
-
-
-def _is_special_line(line: str) -> bool:
- if line.strip().startswith("```"):
- return True
- if re.match(r"^#{1,6}\s+", line):
- return True
- if re.match(r"^\s*[-*]\s+", line):
- return True
- if re.match(r"^\s*\d+\.\s+", line):
- return True
- return False
-
-
def _paragraph(content: list[dict]) -> dict:
if not content:
return {"type": "paragraph"}
return {"type": "paragraph", "content": content}
-def _parse_inline(text: str) -> list[dict]:
- """
- Parse inline markdown into tiptap text nodes with marks.
-
- Handles: **bold**, *italic*, `code`, [text](url)
- """
- if not text:
- return []
-
- nodes: list[dict] = []
- # Pattern matches: **bold**, *italic*, `code`, [text](url), or plain text
- pattern = re.compile(
- r"(\*\*(.+?)\*\*)" # bold
- r"|(\*(.+?)\*)" # italic
- r"|(`(.+?)`)" # inline code
- r"|(\[([^\]]+)\]\(([^)]+)\))" # link
- )
-
- pos = 0
- for match in pattern.finditer(text):
- # Add preceding plain text
- if match.start() > pos:
- plain = text[pos : match.start()]
- if plain:
- nodes.append({"type": "text", "text": plain})
-
- if match.group(2) is not None:
- # Bold
- nodes.append(
- {
- "type": "text",
- "text": match.group(2),
- "marks": [{"type": "bold"}],
- }
- )
- elif match.group(4) is not None:
- # Italic
- nodes.append(
- {
- "type": "text",
- "text": match.group(4),
- "marks": [{"type": "italic"}],
- }
- )
- elif match.group(6) is not None:
- # Inline code
- nodes.append(
- {
- "type": "text",
- "text": match.group(6),
- "marks": [{"type": "code"}],
- }
- )
- elif match.group(8) is not None:
- # Link
- nodes.append(
- {
- "type": "text",
- "text": match.group(8),
- "marks": [{"type": "link", "attrs": {"href": match.group(9)}}],
- }
- )
-
- pos = match.end()
-
- # Add remaining plain text
- if pos < len(text):
- remaining = text[pos:]
- if remaining:
- nodes.append({"type": "text", "text": remaining})
-
- if not nodes and text:
- nodes.append({"type": "text", "text": text})
-
- return nodes
-
-
# ---------------------------------------------------------------------------
# Tiptap → simplified text (for the agent to read notebook content)
# ---------------------------------------------------------------------------
diff --git a/posthog/comment/tiptap.py b/posthog/comment/tiptap.py
new file mode 100644
index 000000000000..88296bac43cf
--- /dev/null
+++ b/posthog/comment/tiptap.py
@@ -0,0 +1,368 @@
+"""Markdown to the TipTap document the support widget renders.
+
+The widget styles ``rich_content`` and prints ``content`` as plain text.
+A markdown reply with no document shows ``**bold**`` and ``[label](url)`` to the customer.
+"""
+
+from __future__ import annotations
+
+import re
+
+_UL_ITEM = re.compile(r"^\s*[-*]\s+")
+_OL_ITEM = re.compile(r"^\s*\d+\.\s+")
+_HEADING_LINE = re.compile(r"^#{1,6}\s+")
+_UNSAFE_URL = re.compile("[\x00-\x1f\x7f\u200b-\u200d\ufeff]")
+# A help-center paste quoted into a reply must not build a node per character
+# while the ticket row is locked.
+_MAX_PARSED_CHARS = 100_000
+
+
+def markdown_to_tiptap_doc(text: str) -> dict[str, object]:
+ # Single newlines are line breaks in a support reply. Joining them with a space
+ # would glue "See [article](url)" onto the step above it.
+ nodes = markdown_to_tiptap_nodes(text, hard_breaks=True)
+ if not nodes:
+ nodes = [{"type": "paragraph"}]
+ return {"type": "doc", "content": nodes}
+
+
+def markdown_to_tiptap_nodes(text: str, *, hard_breaks: bool = False) -> list[dict]:
+ """
+ Convert a markdown string to a list of tiptap nodes.
+
+ Supports:
+ - Headings (# to ######)
+ - Paragraphs
+ - Bullet lists (- or *)
+ - Ordered lists (1.)
+ - Code blocks (triple backtick)
+ - Inline: **bold**, *italic*, `code`, [text](url)
+ """
+ if not text or not text.strip():
+ return []
+ if len(text) > _MAX_PARSED_CHARS:
+ return [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]
+
+ lines = text.split("\n")
+ nodes: list[dict] = []
+ i = 0
+
+ while i < len(lines):
+ start = i
+ line = lines[i]
+
+ if line.strip().startswith("```"):
+ code_lines: list[str] = []
+ lang = line.strip()[3:].strip() or None
+ i += 1
+ while i < len(lines) and not lines[i].strip().startswith("```"):
+ code_lines.append(lines[i])
+ i += 1
+ i += 1 # skip closing ```
+ attrs = {}
+ if lang:
+ attrs["language"] = lang
+ node: dict = {
+ "type": "codeBlock",
+ "content": [{"type": "text", "text": "\n".join(code_lines)}],
+ }
+ if attrs:
+ node["attrs"] = attrs
+ nodes.append(node)
+ continue
+
+ # Heading
+ heading_match = re.match(r"^(#{1,6})\s+(.+)$", line)
+ if heading_match:
+ level = len(heading_match.group(1))
+ inline = _parse_inline(heading_match.group(2).strip())
+ nodes.append(
+ {
+ "type": "heading",
+ "attrs": {"level": level},
+ "content": inline,
+ }
+ )
+ i += 1
+ continue
+
+ kind = _list_kind(line)
+ if kind is not None:
+ list_node, i = _read_list(lines, i, kind[0], kind[1], hard_breaks=hard_breaks)
+ nodes.append(list_node)
+ continue
+
+ if not line.strip():
+ i += 1
+ continue
+
+ para_lines: list[str] = []
+ while i < len(lines) and lines[i].strip() and not _is_special_line(lines[i]):
+ para_lines.append(lines[i])
+ i += 1
+ if para_lines:
+ nodes.append(_paragraph(_join_lines(para_lines, hard_breaks=hard_breaks)))
+ # `## ` matches a heading line but not a heading with text. Leaving i
+ # here spins inside the ticket-row lock.
+ if i == start:
+ nodes.append(_paragraph(_parse_inline(lines[i])))
+ i += 1
+
+ return nodes
+
+
+def _leading_indent(line: str) -> int:
+ width = 0
+ for char in line:
+ if char == " ":
+ width += 1
+ elif char == "\t":
+ width += 4
+ else:
+ break
+ return width
+
+
+def _list_kind(line: str) -> tuple[str, int] | None:
+ if _UL_ITEM.match(line):
+ return "bulletList", _leading_indent(line)
+ if _OL_ITEM.match(line):
+ return "orderedList", _leading_indent(line)
+ return None
+
+
+def _is_special_line(line: str) -> bool:
+ if line.strip().startswith("```"):
+ return True
+ if _HEADING_LINE.match(line):
+ return True
+ return _list_kind(line) is not None
+
+
+def _read_list(
+ lines: list[str],
+ i: int,
+ list_type: str,
+ base_indent: int,
+ *,
+ hard_breaks: bool,
+) -> tuple[dict, int]:
+ """One list, including a blank line between items.
+
+ The widget renders each orderedList from 1 and ignores a start attribute.
+ A blank line between ``1.`` and ``2.`` must not open a second list.
+ A more-indented list stays inside the item above it, or that item ends
+ and the following step also renders as 1.
+ """
+ item_re = _UL_ITEM if list_type == "bulletList" else _OL_ITEM
+ items: list[dict] = []
+ while i < len(lines):
+ if not lines[i].strip():
+ j = i + 1
+ while j < len(lines) and not lines[j].strip():
+ j += 1
+ nxt = _list_kind(lines[j]) if j < len(lines) else None
+ if nxt is not None and nxt[0] == list_type and nxt[1] == base_indent:
+ i = j
+ continue
+ break
+ kind = _list_kind(lines[i])
+ if kind is None or kind[0] != list_type or kind[1] != base_indent:
+ break
+ blocks, i = _read_item_blocks(lines, i, item_re, base_indent, hard_breaks=hard_breaks)
+ items.append({"type": "listItem", "content": blocks})
+ return {"type": list_type, "content": items}, i
+
+
+def _read_item_blocks(
+ lines: list[str],
+ i: int,
+ item_re: re.Pattern[str],
+ base_indent: int,
+ *,
+ hard_breaks: bool,
+) -> tuple[list[dict], int]:
+ parts = [item_re.sub("", lines[i], count=1)]
+ i += 1
+ blocks: list[dict] = []
+
+ def flush_parts() -> None:
+ if parts:
+ blocks.append(_paragraph(_join_lines(parts, hard_breaks=hard_breaks)))
+ parts.clear()
+
+ while i < len(lines):
+ if not lines[i].strip():
+ break
+ kind = _list_kind(lines[i])
+ if kind is not None and kind[1] > base_indent:
+ flush_parts()
+ nested, i = _read_list(lines, i, kind[0], kind[1], hard_breaks=hard_breaks)
+ blocks.append(nested)
+ continue
+ if kind is not None:
+ break
+ if lines[i].strip().startswith("```") or _HEADING_LINE.match(lines[i]):
+ break
+ parts.append(lines[i])
+ i += 1
+ flush_parts()
+ if not blocks:
+ blocks.append({"type": "paragraph"})
+ return blocks, i
+
+
+def _join_lines(lines: list[str], *, hard_breaks: bool) -> list[dict]:
+ if not hard_breaks:
+ return _parse_inline(" ".join(lines))
+ nodes: list[dict] = []
+ for index, line in enumerate(lines):
+ if index:
+ nodes.append({"type": "hardBreak"})
+ nodes.extend(_parse_inline(line))
+ return nodes
+
+
+def _paragraph(content: list[dict]) -> dict:
+ if not content:
+ return {"type": "paragraph"}
+ return {"type": "paragraph", "content": content}
+
+
+def _safe_href(url: str) -> str | None:
+ """http(s), mailto, tel, or a relative path. Anything else stays literal text.
+
+ Email turns a link mark into an href. The widget blocks ``javascript:`` when it
+ renders, but the mail body would not.
+ """
+ cleaned = _UNSAFE_URL.sub("", url).strip()
+ if not cleaned or cleaned.startswith("//"):
+ return None
+ normalized = re.sub(r"\s+", "", cleaned).lower()
+ if normalized.startswith(("javascript:", "vbscript:", "data:", "file:")):
+ return None
+ if cleaned.startswith(("/", "./", "../", "#")):
+ return cleaned
+ lower = cleaned.lower()
+ if lower.startswith(("https://", "http://", "mailto:", "tel:")):
+ return cleaned
+ return None
+
+
+def _parse_inline(text: str) -> list[dict]:
+ """Bold, italic, code, and links. One left-to-right pass, no backtracking.
+
+ A regex label of ``[`` characters retries from every bracket. A help article
+ full of them would hold the reply worker for the whole attempt.
+ """
+ if not text:
+ return []
+
+ nodes: list[dict] = []
+ buf: list[str] = []
+ i = 0
+ n = len(text)
+ # -1 means no closer exists at or after the cached start.
+ bracket_at = -2
+ failed_bracket = -2
+ bold_at = -2
+ code_at = -2
+
+ def flush() -> None:
+ if buf:
+ nodes.append({"type": "text", "text": "".join(buf)})
+ buf.clear()
+
+ while i < n:
+ if text[i] == "[":
+ # A missing ] is final. Searching again from every [ is quadratic.
+ if bracket_at != -1 and bracket_at < i:
+ bracket_at = text.find("]", i + 1)
+ # One failed destination is the same for every [ that ends at that ].
+ # Re-scanning it per bracket is quadratic and holds the ticket row lock.
+ if bracket_at == failed_bracket or bracket_at <= i:
+ buf.append("[")
+ i += 1
+ continue
+ taken = _take_link(text, i, bracket_at)
+ if taken is None:
+ failed_bracket = bracket_at
+ buf.append("[")
+ i += 1
+ continue
+ flush()
+ nodes.extend(taken[0])
+ i = taken[1]
+ continue
+ if text.startswith("**", i):
+ if bold_at != -1 and bold_at < i + 2:
+ bold_at = text.find("**", i + 2)
+ if bold_at > i + 2:
+ flush()
+ nodes.append({"type": "text", "text": text[i + 2 : bold_at], "marks": [{"type": "bold"}]})
+ i = bold_at + 2
+ continue
+ elif text[i] == "*":
+ close = text.find("*", i + 1)
+ if close > i + 1:
+ flush()
+ nodes.append({"type": "text", "text": text[i + 1 : close], "marks": [{"type": "italic"}]})
+ i = close + 1
+ continue
+ if text[i] == "`":
+ if code_at != -1 and code_at < i + 1:
+ code_at = text.find("`", i + 1)
+ if code_at > i + 1:
+ flush()
+ nodes.append({"type": "text", "text": text[i + 1 : code_at], "marks": [{"type": "code"}]})
+ i = code_at + 1
+ continue
+ buf.append(text[i])
+ i += 1
+
+ flush()
+ return nodes
+
+
+def _take_link(text: str, start: int, bracket_at: int) -> tuple[list[dict], int] | None:
+ """A link that begins at ``start``, or None when this ``[`` is not a link."""
+ if bracket_at < start + 2 or bracket_at + 1 >= len(text) or text[bracket_at + 1] != "(":
+ return None
+ url_close = _markdown_link_close(text, bracket_at + 2)
+ if url_close is None:
+ return None
+ href = _safe_href(text[bracket_at + 2 : url_close])
+ if href is None:
+ return None
+ label = text[start + 1 : bracket_at]
+ label_nodes = _parse_inline(label) or [{"type": "text", "text": label}]
+ linked: list[dict] = []
+ for label_node in label_nodes:
+ if label_node.get("type") != "text":
+ linked.append(label_node)
+ continue
+ marks = list(label_node.get("marks") or [])
+ marks.append({"type": "link", "attrs": {"href": href}})
+ linked.append({**label_node, "marks": marks})
+ return linked, url_close + 1
+
+
+def _markdown_link_close(text: str, url_start: int) -> int | None:
+ """Index of the ``)`` that ends the destination, allowing one nested pair."""
+ depth = 0
+ i = url_start
+ n = len(text)
+ while i < n:
+ char = text[i]
+ if char.isspace():
+ return None
+ if char == "(":
+ if depth == 1:
+ return None
+ depth = 1
+ elif char == ")":
+ if depth == 0:
+ return i
+ depth = 0
+ i += 1
+ return None
diff --git a/products/conversations/backend/temporal/ai_reply/activities/clarify.py b/products/conversations/backend/temporal/ai_reply/activities/clarify.py
index 11da06a16f2a..7a4004ce6766 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/clarify.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/clarify.py
@@ -4,6 +4,7 @@ from django.db import transaction
from temporalio import activity
+from posthog.comment.tiptap import markdown_to_tiptap_doc
from posthog.models.comment import Comment
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
@@ -96,6 +97,7 @@ def _clarify_sync(input: ClarifyInput) -> ClarifyOutput:
scope="conversations_ticket",
item_id=str(ticket.id),
content=content,
+ rich_content=markdown_to_tiptap_doc(content),
item_context=item_context,
)
if publish:
diff --git a/products/conversations/backend/temporal/ai_reply/activities/persist_reply.py b/products/conversations/backend/temporal/ai_reply/activities/persist_reply.py
index 9885c85acb67..817498c5e904 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/persist_reply.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/persist_reply.py
@@ -7,6 +7,7 @@ from django.db.models import Q
from temporalio import activity
+from posthog.comment.tiptap import markdown_to_tiptap_doc
from posthog.models.comment import Comment
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
@@ -119,6 +120,7 @@ def _persist_reply_sync(input: PersistReplyInput) -> PersistReplyOutput:
scope="conversations_ticket",
item_id=input.ticket_id,
content=content,
+ rich_content=markdown_to_tiptap_doc(content),
item_context=item_context,
)
if input.require_awaiting_clarification and ticket is not None:
diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.py
index 315818cb83fa..8a82d0d14333 100644
--- a/products/conversations/backend/temporal/tests/test_pipeline.py
+++ b/products/conversations/backend/temporal/tests/test_pipeline.py
@@ -1328,18 +1328,64 @@ class TestPersistReplyActivity:
team=team, channel_source="widget", widget_session_id="session", distinct_id="customer"
)
+ reply = (
+ "1. Create a Rule with **Hashtag or keywords**.\n"
+ "See [Set up a Rule](https://www.mentbot.com/help/set-up-a-rule#add-a-rule)."
+ )
_persist_reply_sync(
PersistReplyInput(
team_id=team.id,
ticket_id=str(ticket.id),
- reply="Here's how to do X.",
+ reply=reply,
citations=["chunk-1", "chunk-2"],
confidence=0.85,
)
)
comment = Comment.objects.get(team_id=team.id, item_id=str(ticket.id))
- assert comment.content == "Here's how to do X."
+ assert comment.content == reply
+ assert comment.rich_content == {
+ "type": "doc",
+ "content": [
+ {
+ "type": "orderedList",
+ "content": [
+ {
+ "type": "listItem",
+ "content": [
+ {
+ "type": "paragraph",
+ "content": [
+ {"type": "text", "text": "Create a Rule with "},
+ {
+ "type": "text",
+ "text": "Hashtag or keywords",
+ "marks": [{"type": "bold"}],
+ },
+ {"type": "text", "text": "."},
+ {"type": "hardBreak"},
+ {"type": "text", "text": "See "},
+ {
+ "type": "text",
+ "text": "Set up a Rule",
+ "marks": [
+ {
+ "type": "link",
+ "attrs": {
+ "href": "https://www.mentbot.com/help/set-up-a-rule#add-a-rule"
+ },
+ }
+ ],
+ },
+ {"type": "text", "text": "."},
+ ],
+ }
+ ],
+ }
+ ],
+ },
+ ],
+ }
assert comment.scope == "conversations_ticket"
assert comment.item_context is not None
assert comment.item_context["author_type"] == "AI"
@@ -1747,6 +1793,10 @@ class TestClarifyActivity:
assert comment.item_context["is_private"] is False
assert comment.item_context["persist_as"] == "clarification"
assert comment.content == "Which SDK are you using?"
+ assert comment.rich_content == {
+ "type": "doc",
+ "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Which SDK are you using?"}]}],
+ }
assert "The ticket never named an SDK." not in (comment.content or "")
assert ticket.status == Status.PENDING
assert ticket.ai_triage["status"] == "awaiting_clarification"