: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
feat(replay-vision): link slack group-summaries back to their run page (#72071)
Kim Svatos Dugan48d5f7f9169a
diff --git a/products/replay_vision/backend/temporal/vision_actions/activities.py b/products/replay_vision/backend/temporal/vision_actions/activities.pyindex dec8f39b4951..e4f58dd93b93 100644--- a/products/replay_vision/backend/temporal/vision_actions/activities.py+++ b/products/replay_vision/backend/temporal/vision_actions/activities.py@@ -3,7 +3,6 @@from datetime import UTC, datetime, timedeltafrom uuid import UUID-from django.conf import settingsfrom django.db import transactionfrom django.db.models import Q@@ -188,7 +187,6 @@ def _emit(inputs: EmitActionReadyInputs) -> None:# Nothing to deliver to; the run row (synthesized_markdown) is the in-app artifact.return- action_url = f"{settings.SITE_URL}/project/{team.id}/replay/vision-actions/{action.id}"# Private internal event (cdp_internal_events topic), NOT the public capture pipeline — an# internal_destination HogFunction filtered on vision_action_id delivers it. This is non-forgeable# with the public project token, and (unlike capture) it does NOT land in the analytics events@@ -207,7 +205,6 @@ def _emit(inputs: EmitActionReadyInputs) -> None:# 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.pyindex 7d6b19fa4671..7477930e7771 100644--- a/products/replay_vision/backend/temporal/vision_actions/synthesis.py+++ b/products/replay_vision/backend/temporal/vision_actions/synthesis.py@@ -177,6 +177,11 @@ def _synthesize(inputs: SynthesizeGroupSummaryInputs) -> SynthesizeGroupSummaryRmarkdown = strip_external_links_markdown(_summary_header(action, batch.window_start, len(batch.lines), batch.window_total) + markdown)+ # Link the header's scanner name to this run's page. Added after the strip pass (like the citation+ # links) so the PostHog URL survives on non-posthog.com hosts.+ markdown = _linkify_summary_header(+ markdown, _clean_scanner_name(action), _run_url(team.id, str(action.id), str(run.pk))+ )slack_text = _markdown_to_slack(markdown, team_id=team.id, observation_ids=batch.observation_ids)run.synthesized_markdown = markdown@@ -362,15 +367,23 @@ def _fetch_observations(team: Team, action: VisionAction, run: VisionActionRun))+def _clean_scanner_name(action: VisionAction) -> str:+ """Scanner name is free-text; strip markdown/mrkdwn control chars so it can't garble the bold header+ (in-app Markdown or the Slack `**`→`*` pass) and collapse any newlines that would break the line.++ Also strips link/autolink punctuation `[](){}<>`: `_linkify_summary_header` wraps this name in+ `[name](run_url)` after the external-link strip pass, so a name like `x](//evil/)` would otherwise+ break out of that link and plant a trusted-looking header link to an attacker domain."""+ raw_name = action.scanner.name if action.scanner_id else ""+ return re.sub(r"\s+", " ", re.sub(r"[*_`#\[\]()<>{}]", "", raw_name)).strip() or "your scanner"++def _summary_header(action: VisionAction, window_start: datetime | None, count: int, window_total: int = 0) -> str:"""A trusted one-line preface stating which scanner this summary is for, how many recordings itcovers, and the window's start — the "summary for scans since <prev run>" context the reader needs.When the window held more observations than the cap, it says so ("sampled N of M") so the readerknows the report covers only a sample of the period, not every observation."""- # Scanner name is free-text; strip markdown/mrkdwn control chars so it can't garble the bold header- # (in-app Markdown or the Slack `**`→`*` pass) and collapse any newlines that would break the line.- raw_name = action.scanner.name if action.scanner_id else ""- scanner_name = re.sub(r"\s+", " ", re.sub(r"[*_`#]", "", raw_name)).strip() or "your scanner"+ scanner_name = _clean_scanner_name(action)noun = "recording" if count == 1 else "recordings"# When the period held more observations than the cap, only `count` were summarized — say so.coverage = f"sampled {count} of {window_total:,} {noun}" if window_total > count else f"{count} {noun}"@@ -438,6 +451,21 @@ def _observation_url(team_id: int, observation_id: str) -> str:return f"{settings.SITE_URL}/project/{team_id}/replay-vision/observations/{observation_id}"+def _run_url(team_id: int, action_id: str, run_id: str) -> str:+ return f"{settings.SITE_URL}/project/{team_id}/replay-vision/actions/{action_id}/runs/{run_id}"+++def _linkify_summary_header(markdown: str, scanner_name: str, run_url: str) -> str:+ """Wrap the header's scanner name in a link to this summary's run page — the full report plus every+ cited observation. Added AFTER `strip_external_links_markdown` so the PostHog URL isn't defanged on+ instances whose SITE_URL isn't a posthog.com host (self-hosted, dev). If the strip pass rewrote the+ name (e.g. it carried a bare URL, now a code span), the prefix won't match — leave it unlinked."""+ prefix = f"**Summary for {scanner_name}**"+ if not markdown.startswith(prefix):+ return markdown+ return f"**Summary for [{scanner_name}]({run_url})**" + markdown[len(prefix) :]++def _citations_to_slack_links(markdown: str, team_id: int, observation_ids: list[str]) -> str:"""Resolve each `[obs N]` citation into a Slack `<url|[N]>` link to that observation; drop any that don'tresolve (an out-of-range or hallucinated reference) so no bare label lingers. These links are added afterdiff --git a/products/replay_vision/backend/tests/test_vision_action_synthesis.py b/products/replay_vision/backend/tests/test_vision_action_synthesis.pyindex c2d2f2c10b32..086204314005 100644--- a/products/replay_vision/backend/tests/test_vision_action_synthesis.py+++ b/products/replay_vision/backend/tests/test_vision_action_synthesis.py@@ -195,7 +195,8 @@ class TestVisionActionSynthesis(BaseTest):def test_summary_leads_with_scanner_window_and_count_header(self) -> None:# The report must always state which scanner it's for, how many recordings it covers, and the- # window start — prepended in code so it's present regardless of what the LLM returns.+ # window start — prepended in code so it's present regardless of what the LLM returns. The+ # scanner name links to this run's page so both the in-app report and Slack can jump back to it.self._observation("Users churned at checkout", title="Checkout")self._observation("Onboarding looked smooth", title="Onboarding", session_id="s2")action = self._action()@@ -204,12 +205,13 @@ class TestVisionActionSynthesis(BaseTest):self._synthesize(action, run, llm_content="# Summary\nThemes.")run.refresh_from_db()+ run_url = f"{settings.SITE_URL}/project/{self.team.id}/replay-vision/actions/{action.id}/runs/{run.id}"self.assertTrue(- run.synthesized_markdown.startswith("**Summary for summarizer** — 2 recordings since "),+ run.synthesized_markdown.startswith(f"**Summary for [summarizer]({run_url})** — 2 recordings since "),run.synthesized_markdown,)- # The header rides into the Slack payload too (bold header → *bold*).- self.assertIn("*Summary for summarizer*", run.output["slack"])+ # The linked header rides into the Slack payload too (**bold** → *bold*, [name](url) → <url|name>).+ self.assertIn(f"*Summary for <{run_url}|summarizer>*", run.output["slack"])def test_header_flags_sampling_when_window_exceeds_cap(self) -> None:# When the period holds more observations than the cap, the header must say the summary covers@@ -236,7 +238,7 @@ class TestVisionActionSynthesis(BaseTest):self._synthesize(action, run)run.refresh_from_db()- self.assertIn("**Summary for Checkoutflow**", run.synthesized_markdown)+ self.assertIn("**Summary for [Checkoutflow](", run.synthesized_markdown)def test_summary_header_defangs_links_in_scanner_name(self) -> None:# A scanner name is free text and lands in the header; a name with link/image markdown must not@@ -253,6 +255,28 @@ class TestVisionActionSynthesis(BaseTest):self.assertNotIn("](https://evil.example", run.synthesized_markdown)self.assertNotIn("](https://evil.example", run.output["slack"])+ def test_summary_header_name_cannot_break_out_of_the_run_link(self) -> None:+ # _linkify_summary_header wraps the name in [name](run_url) AFTER the external-link strip pass.+ # A name carrying `](url)` would break out of that link and plant a header link to an attacker+ # domain (the "]" arms the injected link once linkify supplies the opening "["). The name's+ # bracket/paren chars must be stripped so the only link the header can point to is the run page.+ self.scanner.name = "Checkout](//attacker.example/)"+ self.scanner.save()+ self._observation("churned")+ action = self._action()+ run = self._run_for(action)++ self._synthesize(action, run)++ run.refresh_from_db()+ run_url = f"{settings.SITE_URL}/project/{self.team.id}/replay-vision/actions/{action.id}/runs/{run.id}"+ # The header still links, but only to the run page — the attacker domain can't be a link+ # target. It may survive as inert label text; what must not exist is a link pointing at it.+ self.assertIn(f"]({run_url})", run.synthesized_markdown)+ self.assertNotIn("](//attacker.example", run.synthesized_markdown)+ self.assertNotIn("attacker.example|", run.output["slack"])+ self.assertNotIn("<//attacker.example", run.output["slack"])+def test_persists_only_included_observation_ids(self) -> None:# observation_ids must track the summaries actually included — a blank-summary observation is# skipped by _fetch_observations, so its id must not land in the persisted list.