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): add max ai chat to summarize the summaries (#60455)

Hayne Ryu8186924a0dba
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 184abdc76ad9..fb77011fdbff 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -3957,7 +3957,7 @@ snapshots:
replay-tabs-home-success--second-recording-in-list--dark:
hash: v1.k794b7964.e55e3f17536c13f7561cd6275dc2c63e9950e7f83394de972364ba0b51211c58.S9fUa5v1eSxXT-D7D7lmS3os0kSj8a1gIhb7EPsivNc
replay-tabs-home-success--second-recording-in-list--light:
- hash: v1.k794b7964.36ceb39895861de3d53bf2bb36ab9803c836b8cdef6a7ac4fb1d7dfee1bf3e26.OVDv2SGgEZpivhEYSsajGdVchscMaXMBMLAY-YDW3dw
+ hash: v1.k794b7964.fbde98c938fc6f7b723a039b4f2a4543abfd6e2b550d89bacdbfc63db8bea0db.zju5OmTahN7mHk7YiUhK4HTO3zD0oNhLaCsELsojZ-Y
scenes-app-ai-observability-clustercard--default--dark:
hash: v1.k794b7964.b52003430ca42f6ccab28d62f0fe64ad91f127545e84bd43fb64c1ed4d3e81bc.t3RP33V9PWx79luc4NgTcByuAMALgAuejhiT7VqHTnw
scenes-app-ai-observability-clustercard--default--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index d62be35083ee..8901f8380eda 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -3746,7 +3746,8 @@
"marketing_list_data_sources",
"marketing_audit_utm",
"marketing_suggest_conversion_goals",
- "marketing_suggest_utm_mappings"
+ "marketing_suggest_utm_mappings",
+ "summarize_replay_vision_summaries"
],
"type": "string"
},
diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.ts
index 42bbf474f4b1..f5bd8e4ce9f4 100644
--- a/frontend/src/queries/schema/schema-assistant-messages.ts
+++ b/frontend/src/queries/schema/schema-assistant-messages.ts
@@ -514,6 +514,7 @@ export type AssistantTool =
| 'marketing_audit_utm'
| 'marketing_suggest_conversion_goals'
| 'marketing_suggest_utm_mappings'
+ | 'summarize_replay_vision_summaries'
export enum AgentMode {
ProductAnalytics = 'product_analytics',
diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsx
index 1a50f7b9e70d..3b72a7958ad7 100644
--- a/frontend/src/scenes/max/max-constants.tsx
+++ b/frontend/src/scenes/max/max-constants.tsx
@@ -673,6 +673,18 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
return 'Analyzing session replays...'
},
},
+ summarize_replay_vision_summaries: {
+ name: 'Summarize session summaries',
+ description: 'Summarize session summaries across a Replay Vision summarizer scanner',
+ icon: iconForType('session_replay'),
+ modes: [AgentMode.SessionReplay],
+ displayFormatter: (toolCall) => {
+ if (toolCall.status === 'completed') {
+ return 'Summarized session summaries'
+ }
+ return 'Summarizing session summaries...'
+ },
+ },
create_survey: {
name: 'Create surveys',
description: 'Create surveys in seconds',
diff --git a/posthog/schema.py b/posthog/schema.py
index 99a0a6549c8f..6436f45060a1 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -750,6 +750,7 @@ class AssistantTool(StrEnum):
MARKETING_AUDIT_UTM = "marketing_audit_utm"
MARKETING_SUGGEST_CONVERSION_GOALS = "marketing_suggest_conversion_goals"
MARKETING_SUGGEST_UTM_MAPPINGS = "marketing_suggest_utm_mappings"
+ SUMMARIZE_REPLAY_VISION_SUMMARIES = "summarize_replay_vision_summaries"
class AssistantToolCall(BaseModel):
diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.py
new file mode 100644
index 000000000000..628b62a681b9
--- /dev/null
+++ b/products/replay_vision/backend/max_tools.py
@@ -0,0 +1,122 @@
+import re
+from textwrap import dedent
+from typing import Any
+
+from posthoganalytics import capture_exception
+from pydantic import BaseModel, Field
+
+from posthog.rbac.user_access_control import AccessControlLevel
+from posthog.scopes import APIScopeObject
+from posthog.sync import database_sync_to_async
+
+from products.replay_vision.backend.feature_flag import is_replay_vision_enabled
+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
+
+from ee.hogai.tool import MaxTool
+
+# Most recent summaries to feed Max — caps the context size for scanners with large histories.
+MAX_SUMMARIES = 100
+
+# Inline citation markers the model emits in summary text; stripped before handing to Max as noise.
+_EVENT_ID_CITATION_RE = re.compile(r"\(event_id [0-9a-f]{16}\)", re.IGNORECASE)
+
+SUMMARIZE_SUMMARIES_TOOL_DESCRIPTION = dedent("""
+ Use this tool to reason across the per-session summaries produced by a Replay Vision *summarizer* scanner.
+
+ # When to use
+ - The user asks for common themes, patterns, or a digest across a summarizer scanner's sessions
+ - The user asks what users are doing, where they struggle, or what stands out across the summarized recordings
+ - The user wants a "summary of the summaries"
+
+ # What it returns
+ The scanner's most recent per-session summaries. Synthesize them to answer the user's question —
+ surface recurring themes, notable outliers, and concrete takeaways rather than restating each summary.
+ """).strip()
+
+
+class SummarizeSummariesArgs(BaseModel):
+ scanner_id: str | None = Field(
+ default=None,
+ description="The summarizer scanner to digest. Only required when not already available from context.",
+ )
+
+
+class SummarizeReplayVisionSummariesTool(MaxTool):
+ name: str = "summarize_replay_vision_summaries"
+ description: str = SUMMARIZE_SUMMARIES_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = SummarizeSummariesArgs
+
+ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:
+ # Summaries expose recording content, so reading them requires session_recording access.
+ return [("session_recording", "viewer")]
+
+ async def _arun_impl(self, scanner_id: str | None = None) -> tuple[str, dict[str, Any]]:
+ resolved_id = self.context.get("scanner_id") or scanner_id
+ if not resolved_id:
+ return "No scanner specified. Please provide a scanner_id.", {"error": "invalid_context"}
+
+ try:
+ return await self._fetch_and_format(str(resolved_id))
+ except Exception as e:
+ capture_exception(
+ e,
+ properties={"team_id": self._team.id, "user_id": self._user.id, "scanner_id": str(resolved_id)},
+ )
+ # Generic content — Max may relay it to the user, so don't surface the raw exception.
+ # Raw detail stays in the artifact (not user-visible) for debugging.
+ return "Something went wrong loading the summaries. Please try again.", {
+ "error": "fetch_failed",
+ "details": str(e),
+ }
+
+ @database_sync_to_async
+ def _fetch_and_format(self, scanner_id: str) -> tuple[str, dict[str, Any]]:
+ # Gate on the product flag, matching the Vision API viewsets — the tool must not return
+ # data when Replay Vision is disabled for the org.
+ if not is_replay_vision_enabled(self._user, self._team):
+ return "Replay Vision is not enabled for this project.", {"error": "not_enabled"}
+
+ scanner = ReplayScanner.objects.filter(team_id=self._team.id, id=scanner_id).first()
+ if scanner is None:
+ return f"Scanner {scanner_id} not found.", {"error": "not_found"}
+ # Summaries inherit the scanner's RBAC — a team member without viewer access to this scanner
+ # must not read its recording-derived output. Treat as not-found so we don't leak existence.
+ if not self.user_access_control.check_access_level_for_object(scanner, "viewer"):
+ return f"Scanner {scanner_id} not found.", {"error": "forbidden"}
+ if scanner.scanner_type != ScannerType.SUMMARIZER:
+ return (
+ f'Scanner "{scanner.name}" is a {scanner.scanner_type} scanner, not a summarizer.',
+ {"error": "wrong_scanner_type"},
+ )
+
+ observations = (
+ ReplayObservation.objects.filter(
+ team_id=self._team.id, scanner_id=scanner_id, status=ObservationStatus.SUCCEEDED
+ )
+ .order_by("-created_at")
+ .values_list("scanner_result", "created_at")[:MAX_SUMMARIES]
+ )
+
+ lines: list[str] = []
+ for scanner_result, created_at in observations:
+ output = scanner_result.get("model_output") if isinstance(scanner_result, dict) else None
+ if not isinstance(output, dict):
+ continue
+ summary = output.get("summary")
+ if not isinstance(summary, str) or not summary.strip():
+ continue
+ title = output.get("title") if isinstance(output.get("title"), str) else None
+ clean = _EVENT_ID_CITATION_RE.sub("", summary).strip()
+ prefix = f"{created_at:%Y-%m-%d}"
+ lines.append(f"- ({prefix}) {f'{title}: ' if title else ''}{clean}")
+
+ if not lines:
+ return (
+ f'Scanner "{scanner.name}" has no completed summaries yet.',
+ {"scanner_id": scanner_id, "summary_count": 0},
+ )
+
+ header = f'Recent session summaries from the "{scanner.name}" scanner ({len(lines)} of the latest):'
+ content = header + "\n\n" + "\n".join(lines)
+ return content, {"scanner_id": scanner_id, "summary_count": len(lines)}
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
index a31774f3b578..dbc26ef8091c 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
@@ -28,6 +28,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { ScannerObservationsTable } from './components/ScannerObservationsTable'
import { ScannerTriggers } from './components/ScannerTriggers'
import { ScannerTypeConfigEditor } from './components/ScannerTypeConfigEditor'
+import { SummarizerMaxChat } from './components/SummarizerMaxChat'
import { replayScannerLogic } from './replayScannerLogic'
import { ReplayScannerSceneLogicProps, replayScannerSceneLogic } from './replayScannerSceneLogic'
import { EditorTab, SCANNER_TYPE_OPTIONS, MODEL_OPTIONS } from './types'
@@ -61,7 +62,12 @@ export function ReplayScannerSceneComponent({ tabId }: { tabId: string }): JSX.E
!isNew && {
key: 'observations' as EditorTab,
label: 'Observations',
- content: <ScannerObservationsTable scannerId={scannerId} tabId={tabId} />,
+ content: (
+ <div className="space-y-4">
+ <SummarizerMaxChat scannerId={scannerId} tabId={tabId} />
+ <ScannerObservationsTable scannerId={scannerId} tabId={tabId} />
+ </div>
+ ),
},
{
key: 'configuration',
diff --git a/products/replay_vision/frontend/replay_scanners/components/SummarizerMaxChat.tsx b/products/replay_vision/frontend/replay_scanners/components/SummarizerMaxChat.tsx
new file mode 100644
index 000000000000..10689e973074
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/SummarizerMaxChat.tsx
@@ -0,0 +1,44 @@
+import { useValues } from 'kea'
+
+import { IconAI } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { useMaxTool } from 'scenes/max/useMaxTool'
+
+import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
+
+import { replayScannerLogic } from '../replayScannerLogic'
+
+/** "Ask Max" entry point for summarizer scanners — lets the user chat about / digest the per-session summaries. */
+export function SummarizerMaxChat({ scannerId, tabId }: { scannerId: string; tabId: string }): JSX.Element | null {
+ const { scanner } = useValues(replayScannerLogic({ id: scannerId, tabId }))
+ const isSummarizer = scanner?.scanner_type === 'summarizer'
+
+ const { openMax } = useMaxTool({
+ identifier: 'summarize_replay_vision_summaries',
+ active: isSummarizer && scannerId !== 'new',
+ context: { scanner_id: scannerId },
+ contextDescription: scanner
+ ? { text: scanner.name || 'Summarizer scanner', icon: iconForType('session_replay') }
+ : undefined,
+ initialMaxPrompt: 'Summarize the session summaries from this scanner',
+ })
+
+ if (!openMax) {
+ return null
+ }
+
+ return (
+ <div className="border rounded p-4 bg-surface-primary flex items-center justify-between gap-4">
+ <div>
+ <h3 className="text-base font-semibold mb-1">Chat about these summaries</h3>
+ <p className="text-sm text-muted m-0">
+ Ask Max to find themes and patterns across this scanner's session summaries.
+ </p>
+ </div>
+ <LemonButton type="primary" icon={<IconAI />} onClick={() => openMax()} className="shrink-0">
+ Ask Max
+ </LemonButton>
+ </div>
+ )
+}
diff --git a/tach.toml b/tach.toml
index 02c54f51457d..1a792719a92f 100644
--- a/tach.toml
+++ b/tach.toml
@@ -478,6 +478,7 @@ layer = "modules"
[[modules]]
path = "products.replay_vision"
depends_on = [
+ "ee",
"posthog",
]
layer = "modules"