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.

feat(replay-vision): render the full summary as slack section blocks (#70581)

Kim Svatos Dugan9282e8c966f3
diff --git a/products/replay_vision/backend/api/delivery.py b/products/replay_vision/backend/api/delivery.py
index 1e747faa2320..c06c174b3848 100644
--- a/products/replay_vision/backend/api/delivery.py
+++ b/products/replay_vision/backend/api/delivery.py
@@ -57,7 +57,11 @@ def _slack_destination_payload(action: VisionAction, target: dict[str, Any]) ->
"inputs": {
"slack_workspace": {"value": target["integration_id"]},
"channel": {"value": _channel_id(target["channel"])},
- # Hog-templated pass-through of the pre-formatted Slack text carried on the event.
+ # Pre-split section blocks carried on the event: a whole-string template on a json input
+ # resolves to the raw list, so the full report renders as ONE message (Slack never splits
+ # blocks, while `text` over ~4k gets split at arbitrary positions, cutting links in half).
+ "blocks": {"value": "{event.properties.slack_blocks}"},
+ # Fallback + notification preview when blocks are present or missing (pre-blocks runs).
"text": {"value": "{event.properties.slack_text}"},
},
}
diff --git a/products/replay_vision/backend/temporal/vision_actions/activities.py b/products/replay_vision/backend/temporal/vision_actions/activities.py
index 29b49d9968e4..dec8f39b4951 100644
--- a/products/replay_vision/backend/temporal/vision_actions/activities.py
+++ b/products/replay_vision/backend/temporal/vision_actions/activities.py
@@ -204,6 +204,9 @@ def _emit(inputs: EmitActionReadyInputs) -> None:
"scanner_id": str(action.scanner_id) if action.scanner_id else None,
"vision_action_run_id": str(run.id),
"slack_text": run.output.get("slack", ""),
+ # Pre-split section blocks so the full report renders as ONE Slack message; None (not
+ # []) when absent so Slack falls back to slack_text rather than rejecting empty blocks.
+ "slack_blocks": run.output.get("slack_blocks") or None,
"action_url": action_url,
},
),
diff --git a/products/replay_vision/backend/temporal/vision_actions/synthesis.py b/products/replay_vision/backend/temporal/vision_actions/synthesis.py
index 0d0aa4649b5b..849e62df6cb1 100644
--- a/products/replay_vision/backend/temporal/vision_actions/synthesis.py
+++ b/products/replay_vision/backend/temporal/vision_actions/synthesis.py
@@ -53,11 +53,15 @@ MAX_OBSERVATIONS = 100
# cap guards against) samples across its newest SAMPLE_SCAN_LIMIT observations rather than every row,
# so this activity can't materialize an unbounded id list.
SAMPLE_SCAN_LIMIT = 10_000
-# Keep the whole report inside ONE Slack message. Slack's hard API limit is ~40k characters, but
-# anything over ~4,000 gets auto-split into multiple messages at arbitrary positions — which cuts
-# `<url|[N]>` citation tokens in half and renders both halves as garbage. The full report is always
-# available in-app, so truncate with a pointer instead of risking the split.
-SLACK_TEXT_MAX = 3_900
+# Slack's hard chat.postMessage cap on `text` is ~40k characters; past that the API rejects the
+# call outright, so truncate as a last resort. Display splitting is NOT handled here: text over
+# ~4,000 characters gets auto-split into multiple messages at arbitrary positions (cutting
+# `<url|[N]>` links in half), so delivery renders `slack_blocks` — the same report pre-split at
+# line boundaries into section blocks Slack never splits — and keeps `text` as the fallback.
+SLACK_TEXT_MAX = 38_000
+# Slack caps a section block's text at 3,000 characters and a message at 50 blocks.
+SLACK_BLOCK_TEXT_LIMIT = 3_000
+_SLACK_MAX_BLOCKS = 49
_SYSTEM_PROMPT = (
"You are summarizing automated observations of user session recordings into one concise group summary "
@@ -163,7 +167,7 @@ def _synthesize(inputs: SynthesizeGroupSummaryInputs) -> SynthesizeGroupSummaryR
slack_text = _markdown_to_slack(markdown, team_id=team.id, observation_ids=batch.observation_ids)
run.synthesized_markdown = markdown
- run.output = {"slack": slack_text}
+ run.output = {"slack": slack_text, "slack_blocks": _slack_blocks(slack_text)}
run.observation_count = len(batch.lines)
run.observation_ids = batch.observation_ids
run.save(update_fields=["synthesized_markdown", "output", "observation_count", "observation_ids", "updated_at"])
@@ -459,7 +463,54 @@ def _markdown_to_slack(markdown: str, *, team_id: int, observation_ids: list[str
cut = cut[:newline]
elif cut.rfind("<") > cut.rfind(">"):
cut = cut[: cut.rfind("<")]
- text = cut.rstrip() + "\n\n…_(truncated — see the full group summary in PostHog)_"
+ text = cut.rstrip() + "\n\n…_(truncated)_"
# Re-run link sanitization as a belt-and-braces guard against any re-exposed bare URL.
text = strip_external_links_markdown(text)
return text
+
+
+def _split_long_line(line: str) -> list[str]:
+ """Hard-split a single line that exceeds the block limit, backing up to a space outside any
+ `<url|[N]>` token so a link is never cut. Lines this long are rare (the citation cap keeps
+ citation runs short), but a pathological one must not produce an invalid block."""
+ parts: list[str] = []
+ while len(line) > SLACK_BLOCK_TEXT_LIMIT:
+ cut = line[:SLACK_BLOCK_TEXT_LIMIT]
+ space = cut.rfind(" ")
+ # A space inside a token means an unterminated `<` after it; back up before the token.
+ if cut.rfind("<") > cut.rfind(">"):
+ cut = cut[: cut.rfind("<")]
+ space = len(cut)
+ split_at = space if space > 0 else len(cut)
+ if split_at <= 0:
+ # A leading unterminated `<` token longer than the limit leaves nothing safe to cut
+ # before it; hard-cut mid-token so every iteration consumes input rather than looping.
+ split_at = SLACK_BLOCK_TEXT_LIMIT
+ parts.append(line[:split_at].rstrip())
+ line = line[split_at:].lstrip()
+ if line:
+ parts.append(line)
+ return parts
+
+
+def _slack_blocks(text: str) -> list[dict[str, Any]]:
+ """Pre-split the mrkdwn report into section blocks so the FULL report fits one Slack message.
+
+ Slack auto-splits `text` over ~4,000 characters into multiple messages at arbitrary character
+ positions — cutting `<url|[N]>` links in half — but never splits blocks. Splitting at line
+ boundaries keeps every link intact (links contain no newlines)."""
+ chunks: list[str] = []
+ current: list[str] = []
+ current_len = 0
+ for raw_line in text.split("\n"):
+ for line in _split_long_line(raw_line) or [""]:
+ # +1 for the newline that rejoins the lines within a chunk.
+ if current and current_len + len(line) + 1 > SLACK_BLOCK_TEXT_LIMIT:
+ chunks.append("\n".join(current))
+ current, current_len = [], 0
+ current.append(line)
+ current_len += len(line) + 1
+ if current:
+ chunks.append("\n".join(current))
+ blocks = [{"type": "section", "text": {"type": "mrkdwn", "text": chunk}} for chunk in chunks if chunk.strip()]
+ return blocks[:_SLACK_MAX_BLOCKS]
diff --git a/products/replay_vision/backend/tests/test_vision_action_delivery.py b/products/replay_vision/backend/tests/test_vision_action_delivery.py
index 9be92b90e7fa..c233a87b7339 100644
--- a/products/replay_vision/backend/tests/test_vision_action_delivery.py
+++ b/products/replay_vision/backend/tests/test_vision_action_delivery.py
@@ -122,6 +122,9 @@ class TestVisionActionDelivery(APIBaseTest):
self.assertEqual(self._inputs(fn)["slack_workspace"]["value"], self.integration.id)
self.assertEqual(self._inputs(fn)["channel"]["value"], "#general")
self.assertEqual(self._inputs(fn)["text"]["value"], "{event.properties.slack_text}")
+ # A whole-string template on the json blocks input resolves to the raw list at delivery time,
+ # so the pre-split report renders as one message instead of Slack splitting the text mid-link.
+ self.assertEqual(self._inputs(fn)["blocks"]["value"], "{event.properties.slack_blocks}")
def test_channel_composite_is_stripped_to_bare_id_for_slack(self) -> None:
# The UI stores the `${id}|#${name}` picker composite; the Slack destination must receive the
diff --git a/products/replay_vision/backend/tests/test_vision_action_engine.py b/products/replay_vision/backend/tests/test_vision_action_engine.py
index 30e64ba063d1..cc845d793397 100644
--- a/products/replay_vision/backend/tests/test_vision_action_engine.py
+++ b/products/replay_vision/backend/tests/test_vision_action_engine.py
@@ -255,7 +255,10 @@ class TestEngineActivities(BaseTest):
def test_emit_produces_internal_event(self) -> None:
action = _action(self.team, delivery_config=[{"type": "slack", "integration_id": 1, "channel": "#general"}])
run = VisionActionRun(
- vision_action=action, team=self.team, idempotency_key="k", output={"slack": "hello *world*"}
+ vision_action=action,
+ team=self.team,
+ idempotency_key="k",
+ output={"slack": "hello *world*", "slack_blocks": [{"type": "section"}]},
)
run.save()
@@ -272,6 +275,7 @@ class TestEngineActivities(BaseTest):
self.assertEqual(event.uuid, str(run.id))
self.assertEqual(event.properties["vision_action_id"], str(action.id))
self.assertEqual(event.properties["slack_text"], "hello *world*")
+ self.assertEqual(event.properties["slack_blocks"], [{"type": "section"}])
def test_emit_noops_without_delivery(self) -> None:
# No destinations configured → nothing to emit; the run row itself is the in-app artifact.
diff --git a/products/replay_vision/backend/tests/test_vision_action_synthesis.py b/products/replay_vision/backend/tests/test_vision_action_synthesis.py
index 0bdb35825ca0..c2d2f2c10b32 100644
--- a/products/replay_vision/backend/tests/test_vision_action_synthesis.py
+++ b/products/replay_vision/backend/tests/test_vision_action_synthesis.py
@@ -14,7 +14,13 @@ from products.replay_vision.backend.models import ReplayObservation, ReplayScann
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ObservationTrigger
from products.replay_vision.backend.models.replay_scanner import ScannerModel, ScannerType
from products.replay_vision.backend.models.vision_action import VisionActionRunStatus
-from products.replay_vision.backend.temporal.vision_actions.synthesis import _markdown_to_slack, _synthesize
+from products.replay_vision.backend.temporal.vision_actions.synthesis import (
+ SLACK_BLOCK_TEXT_LIMIT,
+ _markdown_to_slack,
+ _slack_blocks,
+ _split_long_line,
+ _synthesize,
+)
from products.replay_vision.backend.temporal.vision_actions.types import SynthesisStatus, SynthesizeGroupSummaryInputs
from products.replay_vision.backend.tests.helpers import snapshot_for
@@ -115,6 +121,10 @@ class TestVisionActionSynthesis(BaseTest):
# Slack conversion: heading + bold → *...* — stored under output["slack"]
self.assertIn("*Summary*", run.output["slack"])
self.assertIn("*Two*", run.output["slack"])
+ # Delivery renders the pre-split blocks; a short report is one section block of the same text.
+ self.assertEqual(
+ run.output["slack_blocks"], [{"type": "section", "text": {"type": "mrkdwn", "text": run.output["slack"]}}]
+ )
def test_labels_each_observation_line_for_citation(self) -> None:
# Every fed observation line is prefixed with a 1-based `[obs N]` label so the model can cite the
@@ -623,11 +633,14 @@ class TestMarkdownToSlack(BaseTest):
self.assertNotIn("#", out)
self.assertNotIn("**", out)
- def test_truncates_long_text(self) -> None:
- # Slack auto-splits messages over ~4k characters, so the payload must always fit one message.
+ def test_truncates_only_past_the_api_cap(self) -> None:
+ # Truncation is a last resort against Slack's ~40k chat.postMessage rejection; display
+ # splitting is handled by `_slack_blocks`, so ordinary long reports must NOT be cut.
out = _markdown_to_slack("x" * 50_000, team_id=self.team.id, observation_ids=[])
- self.assertLessEqual(len(out), 4_000)
+ self.assertLessEqual(len(out), 39_000)
self.assertIn("truncated", out)
+ untouched = _markdown_to_slack("line\n" * 1_500, team_id=self.team.id, observation_ids=[])
+ self.assertNotIn("truncated", untouched)
def test_truncation_does_not_split_a_citation_link(self) -> None:
# A citation link straddling the cut point must be dropped whole, not cut in half — a dangling
@@ -637,7 +650,7 @@ class TestMarkdownToSlack(BaseTest):
obs_id = str(uuid4())
text = "a" * (SLACK_TEXT_MAX - 50) + "\n" + "More friction at checkout [obs 1] and beyond. " * 5
out = _markdown_to_slack(text, team_id=self.team.id, observation_ids=[obs_id])
- self.assertLessEqual(len(out), 4_000)
+ self.assertLessEqual(len(out), SLACK_TEXT_MAX + 100)
self.assertIn("truncated", out)
self.assertEqual(out.count("<"), out.count(">"))
self.assertNotIn(obs_id[:8], out) # the straddling link is gone entirely, not half-emitted
@@ -653,3 +666,36 @@ class TestMarkdownToSlack(BaseTest):
# The host must not appear as a live (unquoted) URL in the output.
sanitized = out.replace("`https://evil.example.com/exfil`", "")
self.assertNotIn("https://evil.example.com/exfil", sanitized)
+
+ def test_slack_blocks_split_at_line_boundaries_and_keep_links_whole(self) -> None:
+ # Slack auto-splits `text` over ~4k at arbitrary positions, cutting <url|[N]> links in half —
+ # the pre-split blocks are what delivery renders instead, so every block must fit Slack's
+ # 3,000-char section limit, split only at line breaks, and carry the whole report.
+ link = f"<https://us.posthog.com/project/1/replay-vision/observations/{uuid4()}|[1]>"
+ paragraph = f"Users hit friction at checkout and abandoned their carts repeatedly. {link}"
+ text = "\n".join(paragraph for _ in range(80)) # ~11k characters
+
+ blocks = _slack_blocks(text)
+
+ self.assertGreater(len(blocks), 1)
+ for block in blocks:
+ self.assertEqual(block["type"], "section")
+ self.assertLessEqual(len(block["text"]["text"]), SLACK_BLOCK_TEXT_LIMIT)
+ # No half links: every < has its closing > within the same block.
+ self.assertEqual(block["text"]["text"].count("<"), block["text"]["text"].count(">"))
+ # Nothing dropped: rejoining the blocks reproduces the full report.
+ self.assertEqual("\n".join(b["text"]["text"] for b in blocks), text)
+
+ @parameterized.expand(
+ [
+ ("leading_token", "<https://evil.example/" + "a" * (SLACK_BLOCK_TEXT_LIMIT * 2)),
+ ("whitespace_then_token", " <" + "a" * (SLACK_BLOCK_TEXT_LIMIT * 2)),
+ ]
+ )
+ def test_split_long_line_consumes_unterminated_leading_token(self, _label: str, line: str) -> None:
+ # A line opening with an unterminated `<` token longer than the block limit used to make
+ # the back-up-before-the-token cut resolve to position 0 — zero forward progress, spinning
+ # the synthesis activity forever. The hard-cut guard must always consume input.
+ parts = _split_long_line(line)
+ self.assertTrue(all(len(p) <= SLACK_BLOCK_TEXT_LIMIT for p in parts))
+ self.assertEqual("".join(parts).replace(" ", ""), line.replace(" ", ""))