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(customer-analytics): render links in account conversation messages (#109905)

Arthur Moreira de Deusbed39d610a30
diff --git a/products/conversations/backend/services/email_links.py b/products/conversations/backend/services/email_links.py
index 8fc83aadfca6..11c758409d01 100644
--- a/products/conversations/backend/services/email_links.py
+++ b/products/conversations/backend/services/email_links.py
@@ -23,6 +23,8 @@ import re
import structlog
from bs4 import BeautifulSoup
+from posthog.dataclasses import frozen
+
logger = structlog.get_logger(__name__)
_HTTP_SCHEME_RE = re.compile(r"^https?://", re.IGNORECASE)
@@ -33,6 +35,7 @@ _URL_TRAILING_PUNCTUATION = ".,;:!?"
# Cap the anchors we scan so a large marketing email can't turn one message into
# an expensive parse.
_MAX_ANCHORS = 100
+_MAX_ANGLE_LABEL_LENGTH = 200
# A bare URL, scanned in one linear pass so a hostile body can't force quadratic
# work. The class keeps parentheses so a URL like `.../Markdown_(language)` stays
# whole; any unbalanced trailing parenthesis (from a `(url)` wrapper) is peeled back
@@ -128,28 +131,45 @@ def _recover_from_html(text: str, html: str) -> str:
return text
candidates: list[tuple[str, str]] = []
+ angle_links: list[tuple[str, str]] = []
seen_labels: set[str] = set()
for anchor in soup.find_all("a")[:_MAX_ANCHORS]:
href = (anchor.get("href") or "").strip()
if not href or not _HTTP_SCHEME_RE.match(href):
continue
label = anchor.get_text(separator=" ", strip=True)
- # Skip an unusable label, a URL that already survived into the text, or a
- # label seen already (its first anchor wins).
- if not label or "[" in label or "]" in label or href in text or label in seen_labels:
+ if not label or "[" in label or "]" in label:
+ continue
+ # A URL that survived into the text needs no recovery, but a plain-text
+ # part may still write it as `label <href>` (Gmail does this).
+ if href in text:
+ if label != href and f"<{href}>" in text:
+ angle_links.append((label, href))
+ continue
+ # Skip a label seen already (its first anchor wins).
+ if label in seen_labels:
continue
seen_labels.add(label)
candidates.append((label, href))
- if not candidates:
- return text
+ # Fold confirmed `label <href>` pairs first, then recover missing URLs only
+ # outside them, so a repeated label cannot steal a link that is already present.
+ used: set[str] = set()
+ segments: list[str] = []
+ for segment, is_link in _split_angle_links(text, angle_links):
+ segments.append(segment if is_link else _link_labels(segment, candidates, used))
+ return "".join(segments)
+
- # Rewrite left to right on the not-yet-emitted suffix only, so a later label
- # can never match inside a link or URL we already inserted. Each pass links
- # the earliest remaining label occurrence; earliest position wins on ties.
+def _link_labels(text: str, candidates: list[tuple[str, str]], used: set[str]) -> str:
+ """Rewrite the earliest occurrence of each unused candidate label to `[label](href)`.
+
+ Rewrites go left to right on the not-yet-emitted suffix only, so a later label
+ can never match inside a link or URL we already inserted. Each pass links the
+ earliest remaining label occurrence. The earliest position wins on ties.
+ """
parts: list[str] = []
remaining = text
- used: set[str] = set()
while True:
best: tuple[int, str, str] | None = None
for label, href in candidates:
@@ -166,5 +186,71 @@ def _recover_from_html(text: str, html: str) -> str:
remaining = remaining[index + len(label) :]
used.add(label)
parts.append(remaining)
-
return "".join(parts)
+
+
+@frozen
+class _FoldedAngleLink:
+ start: int
+ end: int
+ markdown: str
+
+
+def _split_angle_links(text: str, links: list[tuple[str, str]]) -> list[tuple[str, bool]]:
+ """Split `text` around plain-text `label <href>` links, rewriting each to `[label](href)`.
+
+ Returns `(segment, is_link)` pairs in order. Each link is folded once, at its
+ first occurrence that does not overlap a link folded already.
+ """
+ folded: list[_FoldedAngleLink] = []
+ for label, href in links:
+ link = _find_angle_link(text, label, href, folded)
+ if link:
+ folded.append(link)
+
+ segments: list[tuple[str, bool]] = []
+ last = 0
+ for link in sorted(folded, key=lambda link: link.start):
+ segments.append((text[last : link.start], False))
+ segments.append((link.markdown, True))
+ last = link.end
+ segments.append((text[last:], False))
+ return segments
+
+
+def _find_angle_link(text: str, label: str, href: str, folded: list[_FoldedAngleLink]) -> _FoldedAngleLink | None:
+ """Find `label <href>` in `text`, allowing any whitespace between label words.
+
+ The search anchors on the literal `<href>` and matches the label backwards from
+ it, so the work stays linear in the text. A hostile email cannot force quadratic
+ regex backtracking with a long repetitive label.
+ """
+ words = label.split()
+ if len(label) > _MAX_ANGLE_LABEL_LENGTH or not words:
+ return None
+ target = f"<{href}>"
+ index = text.find(target)
+ while index != -1:
+ start = _match_label_before(text, words, index)
+ end = index + len(target)
+ if start is not None and not any(start < link.end and link.start < end for link in folded):
+ return _FoldedAngleLink(start=start, end=end, markdown=f"[{label}]({_md_safe_href(href)})")
+ index = text.find(target, index + 1)
+ return None
+
+
+def _match_label_before(text: str, words: list[str], end: int) -> int | None:
+ """Return where `words` start if they end at `end`, separated by whitespace."""
+ position = end
+ while position > 0 and text[position - 1].isspace():
+ position -= 1
+ for word_index, word in enumerate(reversed(words)):
+ if word_index > 0:
+ if position == 0 or not text[position - 1].isspace():
+ return None
+ while position > 0 and text[position - 1].isspace():
+ position -= 1
+ if position < len(word) or not text.startswith(word, position - len(word)):
+ return None
+ position -= len(word)
+ return position
diff --git a/products/conversations/backend/services/gmail_sync.py b/products/conversations/backend/services/gmail_sync.py
index 964b13969edb..c307e29fdc12 100644
--- a/products/conversations/backend/services/gmail_sync.py
+++ b/products/conversations/backend/services/gmail_sync.py
@@ -12,6 +12,7 @@ from django.utils import timezone
from django.utils.html import strip_tags
import requests
+from bs4 import BeautifulSoup, NavigableString, PageElement, Tag
from posthog.dataclasses import frozen
from posthog.egress.google_workspace import google_workspace_request
@@ -35,6 +36,12 @@ GMAIL_PENDING_MESSAGE_IDS_CONFIG_KEY = "gmail_pending_message_ids"
GMAIL_API_BASE_URL = "https://gmail.googleapis.com/gmail/v1/users/me"
INITIAL_IMPORT_QUERY = "{in:inbox in:sent} newer_than:30d"
INITIAL_IMPORT_LIMIT = 100
+_HTML_PARAGRAPH_TAGS = frozenset({"blockquote", "h1", "h2", "h3", "h4", "h5", "h6", "ol", "p", "table", "ul"})
+_HTML_LINE_TAGS = frozenset({"div", "li", "tr"})
+_HTML_SKIPPED_TAGS = frozenset({"head", "script", "style", "title"})
+_HTML_WHITESPACE_RE = re.compile(r"\s+")
+_BLANK_LINES_RE = re.compile(r"\n{3,}")
+_PREFORMATTED_PLACEHOLDER_RE = re.compile(r"\x00(\d+)\x00")
BACKFILL_PAGE_SIZE = 5
HISTORY_PAGE_SIZE = 100
HISTORY_MESSAGE_BATCH_SIZE = 100
@@ -438,7 +445,7 @@ def _parse_gmail_message(
bodies = _message_bodies(message_payload, load_attachment_data=load_attachment_data)
body_plain = bodies.plain
if not body_plain and bodies.html:
- body_plain = unescape(strip_tags(bodies.html))
+ body_plain = _html_to_text(bodies.html)
return ParsedEmail(
message_id=message_id[:998],
@@ -460,6 +467,75 @@ def _parse_gmail_message(
)
+def _html_to_text(html: str) -> str:
+ """Flatten an HTML-only body to plain text, keeping paragraph and line breaks.
+
+ `strip_tags` joins adjacent blocks with no separator, so `<p>a.</p><p>b</p>`
+ becomes `a.b`. Links are folded back in later by `recover_links_from_html`.
+ """
+ preformatted: list[str] = []
+ try:
+ text = _flatten_html(BeautifulSoup(html, "html.parser"), preformatted)
+ except Exception: # noqa: BLE001 — a malformed HTML part must never fail the sync
+ preformatted = []
+ text = unescape(strip_tags(html))
+ lines = (line.strip() for line in text.split("\n"))
+ text = _BLANK_LINES_RE.sub("\n\n", "\n".join(lines)).strip()
+ # Preformatted blocks go back in after the cleanup, so their indentation survives.
+ return _PREFORMATTED_PLACEHOLDER_RE.sub(lambda match: _get_preformatted_block(preformatted, match), text)
+
+
+@frozen
+class _HtmlSeparator:
+ text: str
+
+
+def _flatten_html(soup: BeautifulSoup, preformatted: list[str]) -> str:
+ """Emit the text of `soup` in one pass, replacing each top-level `<pre>` with a placeholder.
+
+ The walk reads the tree without modifying it, because BeautifulSoup locates a
+ node among its siblings with a linear scan on every insert or replace, which
+ makes per-node edits quadratic on an email with many sibling elements.
+ """
+ parts: list[str] = []
+ stack: list[PageElement | _HtmlSeparator] = list(reversed(soup.contents))
+ while stack:
+ node = stack.pop()
+ if isinstance(node, _HtmlSeparator):
+ parts.append(node.text)
+ elif isinstance(node, NavigableString):
+ if type(node) is NavigableString:
+ parts.append(_HTML_WHITESPACE_RE.sub(" ", node).replace("\0", ""))
+ elif isinstance(node, Tag) and node.name not in _HTML_SKIPPED_TAGS:
+ if node.name == "br":
+ parts.append("\n")
+ elif node.name == "pre":
+ preformatted.append(_preformatted_text(node))
+ parts.append(f"\0{len(preformatted) - 1}\0\n\n")
+ else:
+ if node.name in _HTML_PARAGRAPH_TAGS:
+ stack.append(_HtmlSeparator(text="\n\n"))
+ elif node.name in _HTML_LINE_TAGS:
+ stack.append(_HtmlSeparator(text="\n"))
+ stack.extend(reversed(node.contents))
+ return "".join(parts)
+
+
+def _preformatted_text(pre: Tag) -> str:
+ parts: list[str] = []
+ for node in pre.descendants:
+ if type(node) is NavigableString:
+ parts.append(node.replace("\0", ""))
+ elif isinstance(node, Tag) and node.name == "br":
+ parts.append("\n")
+ return "".join(parts).strip("\n")
+
+
+def _get_preformatted_block(preformatted: list[str], match: re.Match[str]) -> str:
+ index = int(match.group(1))
+ return preformatted[index] if index < len(preformatted) else ""
+
+
def _message_headers(raw_headers: list[dict[str, Any]]) -> dict[str, str]:
values: dict[str, list[str]] = {}
for header in raw_headers:
diff --git a/products/conversations/backend/tests/test_email_links.py b/products/conversations/backend/tests/test_email_links.py
index 92b7606c5c93..9ac9b08042d1 100644
--- a/products/conversations/backend/tests/test_email_links.py
+++ b/products/conversations/backend/tests/test_email_links.py
@@ -42,6 +42,32 @@ class TestRecoverLinksFromHtml:
html = '<a href="https://host.example/activate?t=abc">Confirm</a>'
assert recover_links_from_html(text, html) == "Confirm at <https://host.example/activate?t=abc> now"
+ def test_folds_plain_text_angle_link_into_markdown(self) -> None:
+ text = "book a time via our Onboarding\nteam calendar\n<https://cal.example/onboarding>.\nThanks"
+ html = '<p>book a time via our <a href="https://cal.example/onboarding">Onboarding team calendar</a>.</p>'
+ assert (
+ recover_links_from_html(text, html)
+ == "book a time via our [Onboarding team calendar](https://cal.example/onboarding).\nThanks"
+ )
+
+ def test_leaves_angle_link_without_matching_label(self) -> None:
+ text = "Book here: <https://cal.example/onboarding>"
+ html = '<a href="https://cal.example/onboarding">Onboarding team calendar</a>'
+ assert recover_links_from_html(text, html) == text
+
+ def test_angle_link_keeps_its_href_when_label_repeats(self) -> None:
+ text = "Click here <https://example.com/a> then Click here"
+ html = '<a href="https://example.com/a">Click here</a> <a href="https://example.com/b">Click here</a>'
+ assert (
+ recover_links_from_html(text, html)
+ == "[Click here](https://example.com/a) then [Click here](https://example.com/b)"
+ )
+
+ def test_long_repetitive_angle_label_is_not_folded(self) -> None:
+ text = "a " * 24000 + "X <https://example.com/>"
+ html = '<a href="https://example.com/">' + "a " * 12000 + "</a>"
+ assert recover_links_from_html(text, html) == text
+
@parameterized.expand(
[
("trailing_tilde", "https://clicks.example/f/a/token~"),
diff --git a/products/conversations/backend/tests/test_gmail_sync.py b/products/conversations/backend/tests/test_gmail_sync.py
index 76b11f9b48f0..c6371de75a5e 100644
--- a/products/conversations/backend/tests/test_gmail_sync.py
+++ b/products/conversations/backend/tests/test_gmail_sync.py
@@ -132,6 +132,38 @@ class TestGmailSync(BaseTest):
imported = EmailThreadMessage.objects.for_team(self.team.id).select_related("comment").get()
assert imported.comment.content == "Attachment-backed message body"
+ def test_html_only_body_keeps_paragraphs_and_links(self) -> None:
+ message = _gmail_message(label="INBOX", sender="[email protected]", recipient=self.user.email)
+ html = (
+ b"<html><head><style>p { margin: 0 }</style></head><body>"
+ b"<p>Hey team,</p>\n<p>It goes quickly, so start early.</p>"
+ b'<p>See <a href="https://app.example.com/billing">your billing page</a>.<br>Cheers</p>'
+ b"<p>Ref &#0;0&#0;</p>"
+ b"<pre>def run():\n return 1</pre>"
+ b"</body></html>"
+ )
+ message["payload"]["mimeType"] = "text/html"
+ message["payload"]["body"] = {"data": base64.urlsafe_b64encode(html).decode().rstrip("=")}
+
+ with patch.object(
+ gmail_sync,
+ "google_workspace_request",
+ side_effect=[
+ _response({"emailAddress": self.user.email, "historyId": "100"}),
+ _response({"messages": [{"id": "gmail-1"}]}),
+ _response(message),
+ ],
+ ):
+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)
+
+ imported = EmailThreadMessage.objects.for_team(self.team.id).select_related("comment").get()
+ assert imported.comment.content == (
+ "Hey team,\n\nIt goes quickly, so start early.\n\n"
+ "See [your billing page](https://app.example.com/billing).\nCheers\n\n"
+ "Ref 0\n\n"
+ "def run():\n return 1"
+ )
+
def test_message_with_too_many_attachment_backed_bodies_is_skipped(self) -> None:
message = _gmail_message(label="INBOX", sender="[email protected]", recipient=self.user.email)
message["payload"]["mimeType"] = "multipart/alternative"
@@ -399,3 +431,8 @@ class TestGmailSync(BaseTest):
gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)
assert not EmailThread.objects.for_team(self.team.id).exists()
+
+
+class TestHtmlToText:
+ def test_many_sibling_paragraphs_flatten_in_one_pass(self) -> None:
+ assert gmail_sync._html_to_text("<p>x</p>" * 20_000) == "\n\n".join(["x"] * 20_000)
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 087737283e2f..16a4227da8f7 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -238,6 +238,8 @@ Like Opportunities, it loads directly in the logic (no embedded query), so the r
The Email threads tab lists matched customer communication from Conversations. `accountEmailThreadsLogic` fetches paginated summaries that include subject, preview, customer participants, owner, message count, and latest activity. Clicking the subject or a participant toggles the thread; the table does not render a separate expansion control. Expanding one row fetches messages in server-bounded pages and renders them in source-timestamp order. The list endpoint never includes message bodies. Both list and detail endpoints require account viewer access plus ticket viewer access because subjects, previews, addresses, and bodies are customer communication. The logic reports unexpected failures without including any email content in analytics or exception metadata.
+Conversations stores synced email and Support message bodies as Markdown, with recovered links folded in as `[label](url)` or `<url>`. `ConversationMessageContent` renders them with `LemonMarkdown` and passes `disableImages="all"` and `disableMentions`, because external senders write this content. It must not load any image, including PostHog-hosted URLs that could act as tracking pixels, or render member mention chips. Row previews stay plain text: `markdownLinksToText` keeps each link's label and drops its URL.
+
The Meetings tab (flag-gated, `CUSTOMER_ANALYTICS_CSP`) lists the account's synced Google Calendar meetings from the `accounts/:id/meetings` endpoint. The calendar-sync Temporal workflow (`backend/logic/calendar_sync.py`) writes rows from calendars connected in Customer analytics settings and attaches them to an account through known emails, person resolution, and email domains. For each response page, the endpoint checks queryable `calls` tables from synced Gong sources. It joins `calendar_event_id` to the meeting's `ical_uid`, with `_<recurrence_instance_id>` appended for recurring meetings. A matching HTTPS `gong.io` URL appears as an "Open in Gong" button after the meeting name. The optional lookup respects the viewer's warehouse access and does not fail the meetings response when Gong data is unavailable.
`accountMeetingsLogic` owns three states like the Support tickets tab (skeleton on first load / load-failed / "no meetings yet"), plus **server-side pagination and search** (like the Users tab: `page` + `searchTerm` feed the endpoint's `limit`/`offset`/`search` params; search debounces, resets to page 1, and fires `MeetingsSearched`), the **attendee cell** state (first 3 attendees shown, "+N more"/"show less" toggles `expandedAttendeeMeetingIds`; attendees with a resolved `person_id` — populated by the sync via the same HogQL person-email lookup the account matching uses — get a leading `ProfilePicture` (xs, gravatar-by-email) and link to their person page, firing `MeetingAttendeeClicked`; each attendee carries a minimal RSVP glyph after the name — green check accepted, red x declined, muted "?" tentative, nothing for needs_action), and the project-admin-gated **"Edit matching" inline panel**: two `LemonInputSelect` chip inputs editing the account's `email_domains` and `known_emails` properties (normalized, merged into `properties` via `accountsPartialUpdate`, propagated through `accountLinksLogic.loadAccountSuccess`).
The matching editor is deliberately an inline panel above the table, not a dropdown — the `LemonInputSelect` suggestion popover opens below the inputs and would cover Save/Cancel inside a small overlay, so the buttons sit beside the inputs instead.
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx
index 5bdfb777d15c..802a7fdf6781 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx
@@ -247,6 +247,22 @@ function LatestActivity({ conversation }: { conversation: AccountConversation })
)
}
+// Synced emails and support messages are stored as Markdown, with links folded in as `[label](url)` or `<url>`.
+function ConversationMessageContent({ content }: { content: string }): JSX.Element {
+ return (
+ <LemonMarkdown
+ className="break-words text-sm"
+ lowKeyHeadings
+ disableImages="all"
+ disableDocsRedirect
+ disableMentions
+ wrapCode
+ >
+ {content}
+ </LemonMarkdown>
+ )
+}
+
function EmailMessage({ message }: { message: AccountEmailThreadMessageApi }): JSX.Element {
const outgoing = message.direction === 'outbound'
return (
@@ -259,7 +275,7 @@ function EmailMessage({ message }: { message: AccountEmailThreadMessageApi }): J
<Person name={message.sender.name || message.sender.email} email={message.sender.email} />
<ActivityTimestamp time={message.sent_at} />
</div>
- <div className="whitespace-pre-wrap break-words text-sm">{message.content}</div>
+ <ConversationMessageContent content={message.content} />
</LemonCard>
</div>
)
@@ -290,7 +306,7 @@ function SupportMessage({ message }: { message: AccountSupportTicketMessageApi }
</span>
<ActivityTimestamp time={message.created_at} />
</div>
- <div className="whitespace-pre-wrap break-words text-sm">{message.content}</div>
+ <ConversationMessageContent content={message.content} />
</LemonCard>
</div>
)
@@ -434,12 +450,16 @@ function conversationTitle(conversation: AccountConversation): string {
return periodLabel(conversation.summary)
}
+function markdownLinksToText(markdown: string): string {
+ return markdown.replace(/\[([^\]]*)\]\((?:[^()\s]|\([^()\s]*\))*\)/g, '$1').replace(/<(https?:\/\/[^>\s]+)>/g, '$1')
+}
+
function conversationPreview(conversation: AccountConversation): string {
if (conversation.source === 'email') {
- return conversation.email.preview
+ return markdownLinksToText(conversation.email.preview)
}
if (conversation.source === 'support') {
- return conversation.ticket.last_message_text ?? ''
+ return markdownLinksToText(conversation.ticket.last_message_text ?? '')
}
return conversation.summary.content
.replace(/[#*_`>[\]]/g, '')