: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 scanner, observations, and run from alert messages (#71276)
Kim Svatos Dugan52393d335324
diff --git a/products/replay_vision/backend/temporal/vision_actions/alerts.py b/products/replay_vision/backend/temporal/vision_actions/alerts.pyindex 10b10561af49..d83b0045bacc 100644--- a/products/replay_vision/backend/temporal/vision_actions/alerts.py+++ b/products/replay_vision/backend/temporal/vision_actions/alerts.py@@ -11,6 +11,7 @@ import refrom datetime import UTC, datetime, timedeltafrom typing import Any+from django.conf import settingsfrom django.db.models import Avg, FloatFieldfrom django.db.models.fields.json import KeyTextTransformfrom django.db.models.functions import Cast@@ -196,17 +197,25 @@ def _persist_fired(observations_qs: Any,team: Any,) -> EvaluateAlertResult:- markdown = strip_external_links_markdown(- _alert_markdown(action, alert_config, metric_value, matched_count, observations_qs)- )- observation_ids = [- str(observation_id)- for observation_id in observations_qs.order_by("-created_at", "-id").values_list("id", flat=True)[+ # One fetch feeds both the message and the persisted ids, so the `[obs N]` labels in the example+ # lines always agree with `observation_ids` order (which the run serializer numbers `index` by and+ # both the Slack pass and the in-app view resolve into observation links).+ rows = list(+ observations_qs.order_by("-created_at", "-id").values_list("id", "scanner_result", "created_at")[:MAX_OBSERVATIONS]- ]+ )+ observation_ids = [str(observation_id) for observation_id, _, _ in rows]+ markdown = strip_external_links_markdown(_alert_markdown(action, alert_config, metric_value, matched_count, rows))+ # Links are added AFTER the strip pass (like the Slack citation links) so the URLs aren't defanged+ # on instances whose SITE_URL isn't a posthog.com host (self-hosted, dev).+ run_url = _run_url(team.id, str(action.id), str(run.pk))+ markdown = _linkify_header(markdown, action, run_url)+ if matched_count > EXAMPLE_LINES:+ # More matches than the message lists as examples — point at the run page, which shows every+ # match this alert included (capped at MAX_OBSERVATIONS).+ markdown += f"\n\n[See all {matched_count:,} matches]({run_url})"run.synthesized_markdown = markdown- # Alert messages carry no `[obs N]` citations, so the ids only feed the (no-op) citation pass.run.output = {"slack": _markdown_to_slack(markdown, team_id=team.id, observation_ids=observation_ids)}run.observation_count = matched_countrun.observation_ids = observation_ids@@ -219,19 +228,45 @@ def _format_number(value: float) -> str:return str(int(value)) if float(value).is_integer() else f"{value:.2f}"+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 _scanner_display_name(action: Any) -> str:+ # Scanner name is free text; strip markdown/mrkdwn control chars so it can't garble the bold+ # header, plus link syntax chars so it can't break out of the header link's label.+ 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 _linkify_header(markdown: str, action: Any, run_url: str) -> str:+ """Wrap the header's scanner name in a link to this alert's run page — the alert's own message+ plus every matching observation (and breadcrumbs back to the scanner). A name the strip pass+ rewrote (e.g. it contained a bare URL, now a code span) won't match the expected header — leave+ it unlinked rather than guess."""+ if not action.scanner_id:+ return markdown+ name = _scanner_display_name(action)+ prefix = f"**Alert: {name}**"+ if not markdown.startswith(prefix):+ return markdown+ return f"**Alert: [{name}]({run_url})**" + markdown[len(prefix) :]++def _alert_markdown(action: Any,alert_config: dict[str, Any],metric_value: float,matched_count: int,- observations_qs: Any,+ rows: list[tuple[Any, Any, datetime]],) -> str:"""Deterministic alert report: what fired, the measured value vs the threshold, and a few exampleobservation outcomes (verdict/score/tags via `describe_output` — outcomes only, no- recording-derived prose, so nothing here needs an LLM or invites prompt injection)."""- # Scanner name is free text; strip markdown/mrkdwn control chars so it can't garble the bold header.- 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"+ recording-derived prose, so nothing here needs an LLM or invites prompt injection). Example lines+ carry `[obs N]` citation markers — N is the observation's 1-based position in `rows`+ (= `observation_ids` order) — which the Slack pass and the in-app view resolve into links to each+ observation."""+ scanner_name = _scanner_display_name(action)noun = "observation" if matched_count == 1 else "observations"if alert_config.get("frequency", AlertFrequency.ON_BREACH) == AlertFrequency.EVERY_MATCH:@@ -252,15 +287,13 @@ def _alert_markdown(]examples: list[str] = []- for scanner_result, created_at in observations_qs.order_by("-created_at", "-id").values_list(- "scanner_result", "created_at"- )[:EXAMPLE_LINES]:+ for position, (_, scanner_result, created_at) in enumerate(rows[:EXAMPLE_LINES], start=1):output = scanner_result.get("model_output") if isinstance(scanner_result, dict) else Noneif not isinstance(output, dict):continuedescriptor = describe_output(output)if descriptor:- examples.append(f"- ({created_at:%Y-%m-%d}) {descriptor}")+ examples.append(f"- ({created_at:%Y-%m-%d}) {descriptor} [obs {position}]")if examples:lines.extend(["", "Most recent matches:", *examples])diff --git a/products/replay_vision/backend/temporal/vision_actions/synthesis.py b/products/replay_vision/backend/temporal/vision_actions/synthesis.pyindex d87854b5ace3..19c1ce653e50 100644--- a/products/replay_vision/backend/temporal/vision_actions/synthesis.py+++ b/products/replay_vision/backend/temporal/vision_actions/synthesis.py@@ -89,6 +89,10 @@ _SYSTEM_PROMPT = (_MARKDOWN_HEADING_RE = re.compile(r"^#{1,6}\s*(.+?)\s*#*$", re.MULTILINE)_MARKDOWN_BOLD_RE = re.compile(r"\*\*([^*]+)\*\*")+# Markdown links in the report body (e.g. the alert header's scanner link). Only PostHog-hosted links+# survive `strip_external_links_markdown`, so anything this matches is safe to hand Slack as a link;+# left unconverted, Slack would render the raw `[label](url)` syntax as literal text.+_MARKDOWN_LINK_RE = re.compile(r"\[([^\]]+)\]\((https?://[^\s)]+)\)")# `[obs N]` citation markers the model emits (see `_fetch_observations`); the in-app view and the Slack pass# both resolve them to observation links. The captured group is the 1-based observation number._OBS_CITATION_RE = re.compile(r"\[obs (\d+)\]")@@ -450,9 +454,11 @@ def _escape_slack_specials(text: str) -> str:def _markdown_to_slack(markdown: str, *, team_id: int, observation_ids: list[str]) -> str:- """Light Markdown→Slack-mrkdwn pass: headings and **bold** become *bold*, and `[obs N]` citations become- `[N]` links to each observation. Truncates long reports."""+ """Light Markdown→Slack-mrkdwn pass: headings and **bold** become *bold*, `[obs N]` citations become+ `[N]` links to each observation, and (PostHog-only) Markdown links become `<url|label>`. Truncates+ long reports."""text = _citations_to_slack_links(_escape_slack_specials(markdown), team_id, observation_ids)+ text = _MARKDOWN_LINK_RE.sub(lambda m: f"<{m.group(2)}|{m.group(1)}>", text)text = _MARKDOWN_HEADING_RE.sub(lambda m: f"*{m.group(1)}*", text)text = _MARKDOWN_BOLD_RE.sub(lambda m: f"*{m.group(1)}*", text)if len(text) > SLACK_TEXT_MAX:diff --git a/products/replay_vision/backend/tests/test_vision_action_alerts.py b/products/replay_vision/backend/tests/test_vision_action_alerts.pyindex f1f2855bb587..75c1d128e479 100644--- a/products/replay_vision/backend/tests/test_vision_action_alerts.py+++ b/products/replay_vision/backend/tests/test_vision_action_alerts.py@@ -2,6 +2,7 @@ from datetime import timedeltafrom posthog.test.base import BaseTest+from django.conf import settingsfrom django.utils import timezonefrom parameterized import parameterized@@ -78,8 +79,8 @@ class TestVisionActionAlerts(BaseTest):def test_count_alert_fires_and_persists_deterministic_message(self) -> None:scanner = self._scanner()- self._observation(scanner, {"verdict": "yes", "reasoning": "user hit the bug"})- self._observation(scanner, {"verdict": "yes", "reasoning": "again"}, session_id="s2")+ older = self._observation(scanner, {"verdict": "yes", "reasoning": "user hit the bug"}, age_days=0.01)+ newest = self._observation(scanner, {"verdict": "yes", "reasoning": "again"}, session_id="s2")action = self._alert(scanner, {"metric": "count", "threshold": 2})result, run = self._evaluate(action)@@ -88,12 +89,36 @@ class TestVisionActionAlerts(BaseTest):self.assertEqual(result.observation_count, 2)self.assertEqual(result.metric_value, 2.0)run.refresh_from_db()- self.assertIn("Alert: watcher", run.synthesized_markdown)+ run_url = f"{settings.SITE_URL}/project/{self.team.id}/replay-vision/actions/{action.id}/runs/{run.pk}"+ self.assertIn(f"Alert: [watcher]({run_url})", run.synthesized_markdown)self.assertIn("over the last 24 hours", run.synthesized_markdown)self.assertIn("at or above the threshold of 2", run.synthesized_markdown)self.assertIn("2 observations matched", run.synthesized_markdown)- self.assertTrue(run.output["slack"])- self.assertEqual(len(run.observation_ids), 2)+ # Example lines cite observations by their position in observation_ids (newest first), so the+ # in-app view and the Slack pass both resolve each citation to the right observation.+ self.assertEqual(run.observation_ids, [str(newest.id), str(older.id)])+ self.assertIn("[obs 1]", run.synthesized_markdown)+ self.assertIn("[obs 2]", run.synthesized_markdown)+ self.assertIn(f"<{run_url}|watcher>", run.output["slack"])+ self.assertIn(f"/observations/{newest.id}|[1]>", run.output["slack"])+ self.assertIn(f"/observations/{older.id}|[2]>", run.output["slack"])+ # Every match is already listed, so there's no "see all" overflow link to add noise.+ self.assertNotIn("See all", run.synthesized_markdown)++ def test_many_matches_list_only_examples_and_link_to_the_run(self) -> None:+ scanner = self._scanner()+ for i in range(7):+ self._observation(scanner, {"verdict": "yes"}, session_id=f"s{i}")+ action = self._alert(scanner, {"metric": "count", "threshold": 7})++ result, run = self._evaluate(action)++ self.assertEqual(result.status, AlertStatus.FIRED)+ run.refresh_from_db()+ self.assertEqual(run.synthesized_markdown.count("- ("), 5)+ run_url = f"{settings.SITE_URL}/project/{self.team.id}/replay-vision/actions/{action.id}/runs/{run.pk}"+ self.assertIn(f"[See all 7 matches]({run_url})", run.synthesized_markdown)+ self.assertIn(f"<{run_url}|See all 7 matches>", run.output["slack"])@parameterized.expand([diff --git a/products/replay_vision/frontend/replay_scanners/ActionEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ActionEditorScene.tsxindex 2c39083bd732..41cdc799b7fd 100644--- a/products/replay_vision/frontend/replay_scanners/ActionEditorScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ActionEditorScene.tsx@@ -457,7 +457,7 @@ function ConditionSection({ scannerId }: { scannerId: string }): JSX.Element {options={WINDOW_OPTIONS}data-attr="vision-action-alert-window"/>- <span className="text-sm">reaches</span>+ <span className="text-sm">is at least</span><LemonInputtype="number"size="small"diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionActionRuns.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionActionRuns.tsxindex 97fcc775672e..ab23871c80d9 100644--- a/products/replay_vision/frontend/replay_scanners/components/VisionActionRuns.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/VisionActionRuns.tsx@@ -1,6 +1,7 @@import { useValues } from 'kea'+import { router } from 'kea-router'-import { LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'+import { LemonButton, LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'import { SleepingHog } from 'lib/components/hedgehogs'import { TZLabel } from 'lib/components/TZLabel'@@ -122,6 +123,20 @@ export function VisionActionRuns(): JSX.Element {key: 'observations',render: (_, run) => <span className="text-sm">{run.observation_count}</span>,},+ {+ key: 'actions',+ width: 0,+ render: (_, run) => (+ <LemonButton+ size="small"+ type="secondary"+ to={urls.replayVisionActionRun(actionId, run.id)}+ data-attr="vision-action-run-view"+ >+ View+ </LemonButton>+ ),+ },]return (@@ -134,7 +149,16 @@ export function VisionActionRuns(): JSX.Element {) : runs.length === 0 ? (<EmptyRuns />) : (- <LemonTable columns={columns} dataSource={runs} rowKey="id" data-attr="vision-action-runs-table" />+ <LemonTable+ columns={columns}+ dataSource={runs}+ rowKey="id"+ rowClassName="cursor-pointer"+ onRow={(run) => ({+ onClick: () => router.actions.push(urls.replayVisionActionRun(actionId, run.id)),+ })}+ data-attr="vision-action-runs-table"+ />)}</div>)