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): show scan results in Max and MCP (#82809)

Tue Haulund467bd2cc7049
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 00de38e1d552..a4f51c28fab8 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4566,6 +4566,16 @@ snapshots:
hash: v1.k794b7964.902b5373ca5305edcf1bd3440def4e5e2918ae9ddc32f21c780a3bb4a006b9a7.zBD1FDF7WTERVfwWCIZhb5T9D8FPJNbD3_UFCWB8mhc
mcp-apps-query-results--time-series--light:
hash: v1.k794b7964.bdd2acb8fbfafb10f436d9354bf858c354a6e66a4d1e83728f0504624a4dce1d.ghTEcDWR6YEL_542Xn3EF8OzroIB27eFlxU8o9BBvEo
+ mcp-apps-replay-vision--ineligible-observation--light:
+ hash: v1.k794b7964.97cd87311e3b647f567456c5874b0fd660c9f74143895624a68cb4da6047a6c8.4Tfag7PUinnbUZAc3SYFTn_sB1NNb0XKZXjUyAPaeaI
+ mcp-apps-replay-vision--observation-list--light:
+ hash: v1.k794b7964.d77b67b04cc90f24ee5cad8851a5bcb3b736d087ce2155ac92d221c5e59afdc2.Y5LTeRkQB6y8azdEvTjo09CgLErrb_ONlEnsmOiuVOk
+ mcp-apps-replay-vision--scan-out-of-credits--light:
+ hash: v1.k794b7964.db60de687fb8c2fec37705eb89023c7cc8afa908b1a668bbd06289a240841260.4-CWSMVDR5Bh1hST20uW5dmE3amfHdqPd5Ey15sZMjQ
+ mcp-apps-replay-vision--scan-started--light:
+ hash: v1.k794b7964.59b19eb625c2dd4b62462988dac3644b9973f38983cb7450cef4a7f9c4ca233b.1b7ZsYP3phATd_xHMq7n6JQ4l9JPw_95ZPi9ZC3ikeg
+ mcp-apps-replay-vision--summarized-observation--light:
+ hash: v1.k794b7964.4cab768380511d0083520c47d343fada2a450dd3481e8a6f27c9632119c93ded.Ux_0QD283XWD6HQMyP_BxbJE_LEaVzXx_gvyvML2QD8
mcp-apps-retention-actors--daily--light:
hash: v1.k794b7964.98ed364bc169b666ee69ff6e44c7fa385360df9410875c5ee3cd85ff2e53104f.-p5rL3gbD8LRZ-kriXkNM3NHeYm8nf0v0VfVq5XWZFs
mcp-apps-stickiness--multiple-series--light:
@@ -4758,10 +4768,10 @@ snapshots:
hash: v1.k794b7964.ea754a4783f7653247f127337c407a8cdd4a9c6bc3f1b908d8d00dd1a090b966.KQ3yKnRzi4l3ZeYVThZdmo4L6mAbxtNa2uQh7y-kGWA
products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues--tile-filters-read-only--light:
hash: v1.k794b7964.b2ca2efc52a9ccf56953159c66d3c8766acd1d3a17379d5faec45a4715ae24a9.fK76p7ZVcgvFJNcKJ5Ixy3YnBm_BcBSFnoytLS2jZdU
- products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--before-exception-ingestion--dark:
- hash: v1.k794b7964.ee9bd78f705c05a89b8dffa7ce394b1af07b75a9597fd220c94d177b49def5bd.Ii4is9m845vi1gNJRW-Pdw93hMfdAEL_0UIj6lAOTvw
- products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--before-exception-ingestion--light:
- hash: v1.k794b7964.b71412d69902241f7ec02efa87c138362522d5c7227c36a71e7f0dc0627d2a38.xiUrsbrXCMYmKv85SCzax7k6HNDzZsfKE5ZBhZBFPsI
+ ? products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--before-exception-ingestion--dark
+ : hash: v1.k794b7964.ee9bd78f705c05a89b8dffa7ce394b1af07b75a9597fd220c94d177b49def5bd.Ii4is9m845vi1gNJRW-Pdw93hMfdAEL_0UIj6lAOTvw
+ ? products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--before-exception-ingestion--light
+ : hash: v1.k794b7964.b71412d69902241f7ec02efa87c138362522d5c7227c36a71e7f0dc0627d2a38.xiUrsbrXCMYmKv85SCzax7k6HNDzZsfKE5ZBhZBFPsI
products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--default--dark:
hash: v1.k794b7964.b1e0f5f542426e34dec73826f3135902a392c0c13dade4fec14037c615186b13.kbxxijyDI1SdvgdKwkRnIRLLgmsine5AYvOcD79DYsY
products-dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--default--light:
@@ -6678,6 +6688,18 @@ snapshots:
hash: v1.k794b7964.4d75bf1926fdf1fdebad47ad4fd07f4035634bca040c9aeb0fd58e18adaa4fb4.3sBwvXuvVbhUPQY3T9JG4G3LwQL6Tvv_a22YYhQJifo
scenes-app-marketing-analytics-cell-actions--source-cell-action-unmapped--light:
hash: v1.k794b7964.c15b997111d34fb17ad2dd192b97c01d0a7ab3a320c5edf9a3e20b0b63a4ff9b.UHxcXJdZkFGXRnzIMFWO99QMD_gZm0V47g8f1j4OFS0
+ scenes-app-max-ai-replay-vision-scan-widget--finished--dark:
+ hash: v1.k794b7964.1223f99370d58d32715cc85f7dcee08b5edf77d9b93095b81474c76eb3138f2f.GJOY2COZjRyTv8DY54QNd7uUJ4H7DxTz-8TdiWq3yc8
+ scenes-app-max-ai-replay-vision-scan-widget--finished--light:
+ hash: v1.k794b7964.e6f462d9d5124783d905b2b2b336269f53e92cfc3277085e41b6dd89f4e278a7.TBrWDrr5B6WW5WJWKSO0XjgnZ8Kv8aXbUIjM7xmXNvQ
+ scenes-app-max-ai-replay-vision-scan-widget--running--dark:
+ hash: v1.k794b7964.66c56bdf672494e6874334e58bc8b4e6dfa59dbe5ba0ec11dc9c07ff734c88e0.PbtR0H24ylzUtl0CX33FauDVArJQpIvCyJ6-UZ4DBU0
+ scenes-app-max-ai-replay-vision-scan-widget--running--light:
+ hash: v1.k794b7964.564913d40b34927137b88e0543242300e502660aa4ffcb216f33603745346063.IJpzJ8C5tkuSjzy1X1JwJZt-zmyPCVPcr8jeMiD31cA
+ scenes-app-max-ai-replay-vision-scan-widget--with-skipped--dark:
+ hash: v1.k794b7964.7c7322f707f4ecc916bbc14b0d366b2172b5d4be5ab26b23321683e82b080cca.hetGT6h6m07CvFHpzbMvf2WaU_k-GfRYMcZZJnnbPW8
+ scenes-app-max-ai-replay-vision-scan-widget--with-skipped--light:
+ hash: v1.k794b7964.c543228b0f31abb2aae3b274819abdee4ba6a89fb3324fc6aaa2b18aefee5815.S9etTEY8oT2JhOgLO5hdc6VqvbvYhD-nU4P1WKh24yg
scenes-app-mcp-analytics--activity--dark:
hash: v1.k794b7964.fee5b0d29723a6bd9b57e4156e9e5e6e08eeab2f8fd7f5a9f11e3755417695d5.zLaglPs_UUTHRFCjpGKyFgXfdVSbgqFwJNGxJCD49ao
scenes-app-mcp-analytics--activity--light:
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index 08d3df805f46..bd385493c84b 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -79,6 +79,7 @@ import {
MessageTemplate,
ReasoningAnswer,
RecordingsWidget,
+ ReplayVisionScanWidget,
ResourcesBar,
ThreadView,
} from 'products/posthog_ai/frontend/api/primitives'
@@ -1466,6 +1467,14 @@ function renderToolCallWidget(
onAcceptFilters={onAcceptSessionFilters}
/>
)
+ case 'replay_vision_scan':
+ return (
+ <ReplayVisionScanWidget
+ scanId={widgetDef.args.scanId}
+ sessionIds={widgetDef.args.sessionIds}
+ skipped={widgetDef.args.skipped}
+ />
+ )
default:
return null
}
diff --git a/frontend/src/scenes/max/max-constants.test.ts b/frontend/src/scenes/max/max-constants.test.ts
new file mode 100644
index 000000000000..9b5c4a8c97fb
--- /dev/null
+++ b/frontend/src/scenes/max/max-constants.test.ts
@@ -0,0 +1,54 @@
+import { AgentMode, TaskExecutionStatus } from '~/queries/schema/schema-assistant-messages'
+
+import { EnhancedToolCall, TOOL_DEFINITIONS, getToolsForMode } from './max-constants'
+
+function scanToolCall(results: { session_id: string; scan_outcome: string }[]): EnhancedToolCall {
+ return {
+ id: 'call-1',
+ name: 'scan_replay_vision_sessions',
+ args: {},
+ status: TaskExecutionStatus.Completed,
+ result: {
+ type: 'tool' as any,
+ content: '',
+ tool_call_id: 'call-1',
+ ui_payload: { scan_replay_vision_sessions: { scan_id: 'scanner-1', results } },
+ },
+ } as unknown as EnhancedToolCall
+}
+
+function widgetArgs(results: { session_id: string; scan_outcome: string }[]): any {
+ const formatted = TOOL_DEFINITIONS.scan_replay_vision_sessions.displayFormatter?.(scanToolCall(results), {
+ registeredToolMap: {},
+ })
+ return Array.isArray(formatted) ? formatted[1]?.args : undefined
+}
+
+describe('max-constants', () => {
+ it('waits only on outcomes that produce an observation', () => {
+ const args = widgetArgs([
+ { session_id: 'a', scan_outcome: 'started' },
+ { session_id: 'b', scan_outcome: 'already_scanned' },
+ { session_id: 'c', scan_outcome: 'skipped_quota' },
+ ])
+
+ expect(args.sessionIds).toEqual(['a', 'b'])
+ expect(args.skipped).toEqual([{ sessionId: 'c', reason: 'skipped_quota' }])
+ })
+
+ it('reports an unrecognized outcome instead of waiting on it', () => {
+ // A denylist would treat a new backend outcome as in flight, so the widget would wait on a
+ // recording that never gets a row.
+ const args = widgetArgs([{ session_id: 'a', scan_outcome: 'some_future_outcome' }])
+
+ expect(args.sessionIds).toEqual([])
+ expect(args.skipped).toEqual([{ sessionId: 'a', reason: 'some_future_outcome' }])
+ })
+
+ it('does not offer the retired session summarization tool in any mode', () => {
+ // The tool is gone; the definition only remains so old conversations still render its calls.
+ const offered = Object.values(AgentMode).flatMap((mode) => getToolsForMode(mode).map((tool) => tool.name))
+
+ expect(offered).not.toContain(TOOL_DEFINITIONS.summarize_sessions.name)
+ })
+})
diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsx
index af8ca76d1615..f4faeffbb430 100644
--- a/frontend/src/scenes/max/max-constants.tsx
+++ b/frontend/src/scenes/max/max-constants.tsx
@@ -63,7 +63,7 @@ export interface ToolDefinition<N extends string = string> {
displayFormatter?: (
toolCall: EnhancedToolCall,
{ registeredToolMap }: DisplayFormatterContext
- ) => string | [text: string, widgetDef: RecordingsWidgetDef | null]
+ ) => string | [text: string, widgetDef: RecordingsWidgetDef | ReplayVisionScanWidgetDef | null]
/**
* If only available in a specific product, specify it here.
* We're using Scene instead of ProductKey, because that's more flexible (specifically for SQL editor there
@@ -134,6 +134,11 @@ export interface RecordingsWidgetDef {
args: RecordingUniversalFilters
}
+export interface ReplayVisionScanWidgetDef {
+ widget: 'replay_vision_scan'
+ args: { scanId: string; sessionIds: string[]; skipped: { sessionId: string; reason: string }[] }
+}
+
/** Static mode definition for display purposes. */
export interface ModeDefinition {
name: string
@@ -172,6 +177,39 @@ function skillStatusFormatter(
return `${pendingLabel}${suffix}...`
}
+/** Only these produce a row to wait for. Anything else is reported rather than polled for. */
+const OUTCOMES_THAT_MINT_AN_OBSERVATION = ['started', 'already_running', 'already_scanned']
+
+/**
+ * The scan tool reports what it started, per session, and the results land later on the scanner it
+ * minted. Sessions it skipped never get a row, so they are carried separately rather than left to
+ * look like work still in progress.
+ */
+function replayVisionScanWidgetDef(toolCall: EnhancedToolCall): ReplayVisionScanWidgetDef | null {
+ const payload = toolCall.result?.ui_payload?.scan_replay_vision_sessions
+ const scanId = typeof payload?.scan_id === 'string' ? payload.scan_id : null
+ if (!scanId || !Array.isArray(payload?.results)) {
+ return null
+ }
+ const results = payload.results as { session_id?: unknown; scan_outcome?: unknown }[]
+ const sessionIds: string[] = []
+ const skipped: { sessionId: string; reason: string }[] = []
+ for (const result of results) {
+ if (typeof result?.session_id !== 'string' || typeof result?.scan_outcome !== 'string') {
+ continue
+ }
+ if (OUTCOMES_THAT_MINT_AN_OBSERVATION.includes(result.scan_outcome)) {
+ sessionIds.push(result.session_id)
+ } else {
+ skipped.push({ sessionId: result.session_id, reason: result.scan_outcome })
+ }
+ }
+ if (!sessionIds.length && !skipped.length) {
+ return null
+ }
+ return { widget: 'replay_vision_scan', args: { scanId, sessionIds, skipped } }
+}
+
export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
call_mcp_server: {
name: 'Call an MCP server',
@@ -789,10 +827,10 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
icon: iconForType('session_replay'),
modes: [AgentMode.SessionReplay],
displayFormatter: (toolCall) => {
- if (toolCall.status === 'completed') {
- return 'Started scanning recordings'
+ if (toolCall.status !== 'completed') {
+ return 'Starting scans...'
}
- return 'Starting scans...'
+ return ['Scanned recordings', replayVisionScanWidgetDef(toolCall)]
},
},
retry_replay_vision_observation: {
@@ -1323,11 +1361,11 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
},
},
summarize_sessions: {
- // The tool is retired; the entry stays so tool calls in old conversations still render.
+ // Retired tool. The entry stays so old conversations still render it, but it carries no `modes`:
+ // `getToolsForMode` reads that field, and listing it would offer a tool nobody can call.
name: 'Summarize sessions',
description: 'Summarize sessions analyze real user behavior',
icon: iconForType('session_replay'),
- modes: [AgentMode.SessionReplay],
displayFormatter: (toolCall) =>
toolCall.status === 'completed' ? 'Summarized sessions' : 'Summarizing sessions...',
},
diff --git a/frontend/src/scenes/max/toolCallDisplay.ts b/frontend/src/scenes/max/toolCallDisplay.ts
index 8886b1ebe622..422811009656 100644
--- a/frontend/src/scenes/max/toolCallDisplay.ts
+++ b/frontend/src/scenes/max/toolCallDisplay.ts
@@ -1,8 +1,14 @@
import { TaskExecutionStatus } from '~/queries/schema/schema-assistant-messages'
-import { EnhancedToolCall, RecordingsWidgetDef, ToolRegistration, getToolDefinitionFromToolCall } from './max-constants'
+import {
+ EnhancedToolCall,
+ RecordingsWidgetDef,
+ ReplayVisionScanWidgetDef,
+ ToolRegistration,
+ getToolDefinitionFromToolCall,
+} from './max-constants'
-export type ToolCallWidgetDef = RecordingsWidgetDef
+export type ToolCallWidgetDef = RecordingsWidgetDef | ReplayVisionScanWidgetDef
/**
* Returns the human-readable description of a tool call plus the widget definition (data,
diff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.ts
index 2b1b73bd0edf..f3b8d3d9d418 100644
--- a/products/posthog_ai/frontend/api/primitives.ts
+++ b/products/posthog_ai/frontend/api/primitives.ts
@@ -89,5 +89,6 @@ export type { Option } from '../components/OptionSelector'
export { VisualizationWidget, getArtifactOpenTarget } from '../components/tool/widgets/VisualizationWidget'
export type { VisualizationWidgetProps } from '../components/tool/widgets/VisualizationWidget'
export { RecordingsWidget } from '../components/tool/widgets/RecordingsWidget'
+export { ReplayVisionScanWidget } from '../components/tool/widgets/ReplayVisionScanWidget'
export { ErrorTrackingFiltersWidget } from '../components/tool/widgets/ErrorTrackingFiltersWidget'
export { ErrorTrackingIssueCard } from '../components/tool/widgets/ErrorTrackingIssueCard'
diff --git a/products/posthog_ai/frontend/components/tool/widgets/ReplayVisionScanWidget.stories.tsx b/products/posthog_ai/frontend/components/tool/widgets/ReplayVisionScanWidget.stories.tsx
new file mode 100644
index 000000000000..14e3241127e2
--- /dev/null
+++ b/products/posthog_ai/frontend/components/tool/widgets/ReplayVisionScanWidget.stories.tsx
@@ -0,0 +1,91 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { useStorybookMocks } from '~/mocks/browser'
+
+import { ReplayVisionScanWidget } from './ReplayVisionScanWidget'
+
+const SCAN_ID = '0199c0de-1111-7000-8000-0000000000aa'
+const SESSION_A = '0199c0de-2222-7000-8000-0000000000b1'
+const SESSION_B = '0199c0de-2222-7000-8000-0000000000b2'
+const SESSION_C = '0199c0de-2222-7000-8000-0000000000b3'
+
+const meta: Meta<typeof ReplayVisionScanWidget> = {
+ title: 'Scenes-App/Max AI/Replay Vision scan widget',
+ component: ReplayVisionScanWidget,
+ parameters: {
+ layout: 'padded',
+ testOptions: { waitForLoadersToDisappear: false },
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof ReplayVisionScanWidget>
+
+function observation(sessionId: string, status: string, modelOutput?: Record<string, unknown>): Record<string, any> {
+ return {
+ id: `obs-${sessionId}`,
+ scanner_id: SCAN_ID,
+ session_id: sessionId,
+ status,
+ error_reason: status === 'ineligible' ? 'too_short:the recording is under five seconds long' : '',
+ scanner_result: modelOutput ? { model_output: modelOutput, signals_count: 0 } : null,
+ }
+}
+
+function mockObservations(results: Record<string, any>[]): void {
+ useStorybookMocks({
+ get: {
+ '/api/projects/:team_id/vision/scanners/:scanner_id/observations/': () => [200, { results }],
+ },
+ })
+}
+
+export const Running: Story = {
+ render: () => {
+ mockObservations([
+ observation(SESSION_A, 'succeeded', {
+ title: 'Abandoned checkout at the payment step',
+ summary: 'The user retyped the card number four times, then closed the tab.',
+ }),
+ observation(SESSION_B, 'running'),
+ ])
+ return <ReplayVisionScanWidget scanId={SCAN_ID} sessionIds={[SESSION_A, SESSION_B]} skipped={[]} />
+ },
+ name: 'One finished, one still watching',
+}
+
+export const Finished: Story = {
+ render: () => {
+ mockObservations([
+ observation(SESSION_A, 'succeeded', {
+ title: 'Abandoned checkout at the payment step',
+ summary: 'The user retyped the card number four times, then closed the tab.',
+ }),
+ observation(SESSION_B, 'ineligible'),
+ ])
+ return <ReplayVisionScanWidget scanId={SCAN_ID} sessionIds={[SESSION_A, SESSION_B]} skipped={[]} />
+ },
+ name: 'All recordings settled',
+}
+
+export const WithSkipped: Story = {
+ render: () => {
+ mockObservations([
+ observation(SESSION_A, 'succeeded', {
+ title: 'Completed signup without help',
+ summary: 'The user filled the form once and reached the dashboard.',
+ }),
+ ])
+ return (
+ <ReplayVisionScanWidget
+ scanId={SCAN_ID}
+ sessionIds={[SESSION_A]}
+ skipped={[
+ { sessionId: SESSION_B, reason: 'skipped_quota' },
+ { sessionId: SESSION_C, reason: 'skipped_quota' },
+ ]}
+ />
+ )
+ },
+ name: 'Some recordings skipped',
+}
diff --git a/products/posthog_ai/frontend/components/tool/widgets/ReplayVisionScanWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/ReplayVisionScanWidget.tsx
new file mode 100644
index 000000000000..eaa97fa98d23
--- /dev/null
+++ b/products/posthog_ai/frontend/components/tool/widgets/ReplayVisionScanWidget.tsx
@@ -0,0 +1,114 @@
+import { useValues } from 'kea'
+
+import { LemonBanner, Link, Spinner } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import type { ReplayObservationApi } from 'products/replay_vision/frontend/generated/api.schemas'
+import {
+ readErrorMessage,
+ readReasoning,
+ readSummary,
+ readTitle,
+} from 'products/replay_vision/frontend/utils/observation'
+
+import { replayVisionScanWidgetLogic } from './replayVisionScanWidgetLogic'
+
+export interface ReplayVisionScanWidgetProps {
+ scanId: string
+ sessionIds: string[]
+ /** Sessions the scan did not start, with the reason, so the user is not left waiting on them. */
+ skipped: { sessionId: string; reason: string }[]
+}
+
+const SKIP_MESSAGES: Record<string, string> = {
+ skipped_quota: "this project's monthly Replay Vision credits are used up",
+ skipped_scanner_limit: 'this scanner reached its own credit limit',
+ skipped_limit: 'too many scans were already running',
+ failed: 'the scan could not be started',
+}
+
+export function ReplayVisionScanWidget({ scanId, sessionIds, skipped }: ReplayVisionScanWidgetProps): JSX.Element {
+ const { gaveUp, latestPerSession, pendingCount } = useValues(replayVisionScanWidgetLogic({ scanId, sessionIds }))
+ const skippedByReason = Object.entries(
+ skipped.reduce<Record<string, number>>((counts, entry) => {
+ counts[entry.reason] = (counts[entry.reason] ?? 0) + 1
+ return counts
+ }, {})
+ )
+
+ return (
+ <div className="overflow-hidden rounded border bg-surface-primary">
+ <div className="flex items-center justify-between gap-2 border-b px-3 py-2">
+ <span className="text-sm font-semibold">
+ {pendingCount === 0
+ ? 'Scan complete'
+ : gaveUp
+ ? `${pendingCount} recording${pendingCount === 1 ? '' : 's'} still running`
+ : `Watching ${pendingCount} of ${sessionIds.length} recordings`}
+ </span>
+ {pendingCount > 0 && !gaveUp && <Spinner />}
+ </div>
+
+ {skippedByReason.length > 0 && (
+ <LemonBanner type="warning" className="m-3">
+ {skippedByReason.map(([reason, count]) => (
+ <p key={reason} className="m-0">
+ {count} recording{count === 1 ? ' was' : 's were'} not scanned because{' '}
+ {SKIP_MESSAGES[reason] ?? 'the scan could not be started'}.
+ </p>
+ ))}
+ </LemonBanner>
+ )}
+
+ <div className="divide-y">
+ {latestPerSession.map((observation) => (
+ <ObservationRow key={observation.id} observation={observation} />
+ ))}
+ {pendingCount > 0 && gaveUp && (
+ <p className="m-0 px-3 py-3 text-sm text-secondary">
+ These are taking longer than usual. Their results will appear on the recordings when they
+ finish.
+ </p>
+ )}
+ {latestPerSession.length === 0 && pendingCount > 0 && !gaveUp && (
+ <p className="m-0 px-3 py-3 text-sm text-secondary">Starting the scans...</p>
+ )}
+ </div>
+ </div>
+ )
+}
+
+function ObservationRow({ observation }: { observation: ReplayObservationApi }): JSX.Element {
+ if (observation.status === 'pending' || observation.status === 'running') {
+ return (
+ <div className="flex items-center gap-2 px-3 py-2 text-sm text-secondary">
+ <Spinner />
+ <span>Still watching</span>
+ </div>
+ )
+ }
+
+ if (observation.status !== 'succeeded') {
+ const reason = readErrorMessage(observation)
+ return (
+ <div className="px-3 py-2 text-sm">
+ <p className="m-0 text-secondary">Could not watch this recording{reason ? `: ${reason}` : '.'}</p>
+ </div>
+ )
+ }
+
+ // Summarizers write a title and a body; a monitor scan on the same widget has reasoning instead.
+ const title = readTitle(observation)
+ const body = readSummary(observation) ?? readReasoning(observation)
+
+ return (
+ <div className="px-3 py-2 text-sm">
+ {title && <p className="m-0 font-semibold">{title}</p>}
+ {body && <p className="m-0 mt-0.5 text-secondary">{body}</p>}
+ <Link to={urls.replayVisionObservation(observation.id)} className="text-xs">
+ View details
+ </Link>
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/tool/widgets/replayVisionScanWidgetLogic.test.ts b/products/posthog_ai/frontend/components/tool/widgets/replayVisionScanWidgetLogic.test.ts
new file mode 100644
index 000000000000..43f444b53ff8
--- /dev/null
+++ b/products/posthog_ai/frontend/components/tool/widgets/replayVisionScanWidgetLogic.test.ts
@@ -0,0 +1,141 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import type {
+ ObservationStatusEnumApi,
+ ReplayObservationApi,
+} from 'products/replay_vision/frontend/generated/api.schemas'
+
+import { replayVisionScanWidgetLogic } from './replayVisionScanWidgetLogic'
+
+const SCAN_ID = 'scanner-1'
+
+function observation(sessionId: string, status: ObservationStatusEnumApi): Partial<ReplayObservationApi> {
+ return { id: `obs-${sessionId}`, scanner_id: SCAN_ID, session_id: sessionId, status }
+}
+
+describe('replayVisionScanWidgetLogic', () => {
+ let logic: ReturnType<typeof replayVisionScanWidgetLogic.build>
+ let results: Partial<ReplayObservationApi>[]
+
+ beforeEach(() => {
+ results = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/vision/scanners/:scanner_id/observations/': () => [200, { results }],
+ },
+ })
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it('counts a session with no row yet as still pending', async () => {
+ // The observation row is written moments after the scan starts. Treating an absent row as
+ // finished would stop the poll before any result arrived.
+ results = [observation('a', 'succeeded')]
+ logic = replayVisionScanWidgetLogic({ scanId: SCAN_ID, sessionIds: ['a', 'b'] })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ pendingCount: 1 })
+ })
+
+ it('reports nothing pending once every session has a terminal row', async () => {
+ results = [observation('a', 'succeeded'), observation('b', 'failed')]
+ logic = replayVisionScanWidgetLogic({ scanId: SCAN_ID, sessionIds: ['a', 'b'] })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ pendingCount: 0 })
+ })
+
+ it('keeps polling after a failed read', async () => {
+ // The scanner is shared and the read can blip. Dropping the poll on the first failure leaves a
+ // spinner on screen forever even though the results landed.
+ let calls = 0
+ useMocks({
+ get: {
+ '/api/projects/:team_id/vision/scanners/:scanner_id/observations/': () => {
+ calls += 1
+ return calls === 1 ? [500, {}] : [200, { results: [observation('a', 'succeeded')] }]
+ },
+ },
+ })
+ logic = replayVisionScanWidgetLogic({ scanId: SCAN_ID, sessionIds: ['a'] })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.loadObservations()
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ pendingCount: 0 })
+ })
+
+ it('counts two rows for one session once', async () => {
+ // A retry adds a second row for the same session. Counting rows would call the scan complete
+ // while another session is still running.
+ results = [observation('a', 'succeeded'), observation('a', 'succeeded')]
+ logic = replayVisionScanWidgetLogic({ scanId: SCAN_ID, sessionIds: ['a', 'b'] })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ pendingCount: 1 })
+ })
+
+ it('reads nothing back when the scan started nothing', async () => {
+ // Every session skipped means no session filter, which the API reads as "no filter" and would
+ // answer with the shared scanner's whole history under a "Scan complete" header.
+ let requested = false
+ useMocks({
+ get: {
+ '/api/projects/:team_id/vision/scanners/:scanner_id/observations/': () => {
+ requested = true
+ return [200, { results: [observation('someone-elses-session', 'succeeded')] }]
+ },
+ },
+ })
+ logic = replayVisionScanWidgetLogic({ scanId: SCAN_ID, sessionIds: [] })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ observations: [], pendingCount: 0 })
+
+ expect(requested).toBe(false)
+ })
+
+ it('says so when it stops before every recording settled', async () => {
+ // Polling stops after repeated failures. Without a visible give-up the widget keeps a spinner
+ // on a recording it is no longer waiting for.
+ useMocks({
+ get: {
+ '/api/projects/:team_id/vision/scanners/:scanner_id/observations/': () => [500, {}],
+ },
+ })
+ logic = replayVisionScanWidgetLogic({ scanId: SCAN_ID, sessionIds: ['a'] })
+ logic.mount()
+
+ for (let attempt = 0; attempt < 5; attempt++) {
+ logic.actions.loadObservations()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ await expectLogic(logic).toMatchValues({ gaveUp: true, pendingCount: 1 })
+ })
+
+ it("asks the server for only this scan's sessions", async () => {
+ // The scanner is shared across everyone asking the same question. Filtering client-side after a
+ // page limit can return a page holding none of these sessions, so the filter has to be server-side.
+ let requestedSessionIds: string | null = null
+ useMocks({
+ get: {
+ '/api/projects/:team_id/vision/scanners/:scanner_id/observations/': ({ request }) => {
+ requestedSessionIds = new URL(request.url).searchParams.get('session_id')
+ return [200, { results: [observation('a', 'succeeded')] }]
+ },
+ },
+ })
+ logic = replayVisionScanWidgetLogic({ scanId: SCAN_ID, sessionIds: ['a', 'b'] })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(requestedSessionIds).toBe('a,b')
+ })
+})
diff --git a/products/posthog_ai/frontend/components/tool/widgets/replayVisionScanWidgetLogic.ts b/products/posthog_ai/frontend/components/tool/widgets/replayVisionScanWidgetLogic.ts
new file mode 100644
index 000000000000..f3bf611fd2cb
--- /dev/null
+++ b/products/posthog_ai/frontend/components/tool/widgets/replayVisionScanWidgetLogic.ts
@@ -0,0 +1,173 @@
+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { visionScannersObservationsList } from 'products/replay_vision/frontend/generated/api'
+import type { ReplayObservationApi } from 'products/replay_vision/frontend/generated/api.schemas'
+import {
+ OBSERVE_POLL_GRACE_MS,
+ scheduleObservationPoll,
+ shouldPollObservations,
+} from 'products/replay_vision/frontend/logics/observationPolling'
+
+/**
+ * A scan takes at most MAX_SESSIONS_PER_SCAN (200) recordings and a session can hold more than one row,
+ * so the default page would truncate a large scan and leave sessions looking unfinished forever.
+ */
+const OBSERVATIONS_PAGE_LIMIT = 500
+/** Give up after this long. A recording that has not settled by now needs the scanner page, not a spinner. */
+const POLL_DEADLINE_MS = 10 * 60 * 1000
+/** Consecutive failed reads before the widget stops retrying. */
+const MAX_CONSECUTIVE_FAILURES = 5
+
+export interface ReplayVisionScanWidgetLogicProps {
+ /** The inline scanner the scan minted. Its observations are the scan's results. */
+ scanId: string
+ /** Only these sessions belong to this scan; the scanner is shared and holds older rows too. */
+ sessionIds: string[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface replayVisionScanWidgetLogicValues {
+ gaveUp: boolean
+ latestPerSession: ReplayObservationApi[]
+ observations: ReplayObservationApi[]
+ observationsLoading: boolean
+ pendingCount: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface replayVisionScanWidgetLogicActions {
+ giveUp: () => {
+ value: true
+ }
+ loadObservations: () => any
+ loadObservationsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadObservationsSuccess: (
+ observations: ReplayObservationApi[],
+ payload?: any
+ ) => {
+ observations: ReplayObservationApi[]
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface replayVisionScanWidgetLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ latestPerSession: (observations: ReplayObservationApi[]) => ReplayObservationApi[]
+ pendingCount: (latestPerSession: ReplayObservationApi[], arg: string[]) => number
+ }
+}
+
+export type replayVisionScanWidgetLogicType = MakeLogicType<
+ replayVisionScanWidgetLogicValues,
+ replayVisionScanWidgetLogicActions,
+ ReplayVisionScanWidgetLogicProps,
+ replayVisionScanWidgetLogicMeta
+>
+
+export const replayVisionScanWidgetLogic = kea<replayVisionScanWidgetLogicType>([
+ path(['products', 'posthog_ai', 'frontend', 'components', 'tool', 'widgets', 'replayVisionScanWidgetLogic']),
+ props({} as ReplayVisionScanWidgetLogicProps),
+ key((props: ReplayVisionScanWidgetLogicProps) => `${props.scanId}:${props.sessionIds.join(',')}`),
+
+ actions({ giveUp: true }),
+
+ reducers({
+ gaveUp: [false, { giveUp: () => true }],
+ }),
+
+ loaders(({ props }) => ({
+ observations: [
+ [] as ReplayObservationApi[],
+ {
+ loadObservations: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ // An empty `session_id` reads as "no filter", which would return the shared scanner's
+ // whole history. Nothing started, so there is nothing to read back.
+ if (!teamId || !props.sessionIds.length) {
+ return []
+ }
+ // Filter server-side. The scanner is shared, so asking for the newest N rows can come
+ // back holding only other people's sessions, leaving this scan looking unfinished.
+ const response = await visionScannersObservationsList(String(teamId), props.scanId, {
+ session_id: props.sessionIds.join(','),
+ limit: OBSERVATIONS_PAGE_LIMIT,
+ })
+ return response.results ?? []
+ },
+ },
+ ],
+ })),
+
+ selectors({
+ latestPerSession: [
+ (s) => [s.observations],
+ (observations: ReplayObservationApi[]): ReplayObservationApi[] => {
+ // A session can hold more than one row, an earlier scan plus a retry. Newest wins, so a
+ // stale row is never shown as this scan's finding and never counts a session twice.
+ const newest = new Map<string, ReplayObservationApi>()
+ for (const observation of observations) {
+ if (!newest.has(observation.session_id)) {
+ newest.set(observation.session_id, observation)
+ }
+ }
+ return [...newest.values()]
+ },
+ ],
+ pendingCount: [
+ (s) => [s.latestPerSession, (_, p: ReplayVisionScanWidgetLogicProps) => p.sessionIds],
+ (latestPerSession: ReplayObservationApi[], sessionIds: string[]): number =>
+ Math.max(
+ 0,
+ sessionIds.length -
+ latestPerSession.filter((o) => o.status !== 'pending' && o.status !== 'running').length
+ ),
+ ],
+ }),
+
+ listeners(({ actions, values, cache }) => {
+ // A row appears a moment after its scan starts, so an empty early response means "not yet".
+ // The deadline stops a recording that never settles from polling for the life of the thread.
+ const withinWindow = (): boolean =>
+ shouldPollObservations(values.pendingCount > 0, cache.startedAt + OBSERVE_POLL_GRACE_MS) &&
+ Date.now() < cache.startedAt + POLL_DEADLINE_MS
+ const reschedule = (shouldPoll: boolean): void =>
+ scheduleObservationPoll(cache.disposables, shouldPoll, actions.loadObservations)
+
+ // Stopping while work is outstanding has to be visible, or the spinner sits there for good.
+ const settle = (shouldPoll: boolean): void => {
+ reschedule(shouldPoll)
+ if (!shouldPoll && values.pendingCount > 0) {
+ actions.giveUp()
+ }
+ }
+
+ return {
+ loadObservationsSuccess: () => {
+ cache.failures = 0
+ settle(withinWindow())
+ },
+ loadObservationsFailure: () => {
+ // Without this the poll dies on the first blip and the spinner never resolves.
+ cache.failures = (cache.failures ?? 0) + 1
+ settle(cache.failures < MAX_CONSECUTIVE_FAILURES && withinWindow())
+ },
+ }
+ }),
+
+ afterMount(({ actions, cache }) => {
+ cache.startedAt = Date.now()
+ cache.failures = 0
+ actions.loadObservations()
+ }),
+])
diff --git a/products/replay_vision/frontend/utils/observation.ts b/products/replay_vision/frontend/utils/observation.ts
index ca1d3b8d5e35..7d1dfae43fef 100644
--- a/products/replay_vision/frontend/utils/observation.ts
+++ b/products/replay_vision/frontend/utils/observation.ts
@@ -30,6 +30,27 @@ export function readReasoning(obs: ReplayObservationApi): string | null {
return typeof raw === 'string' && raw ? raw : null
}
+/** Summarizer output: the one-line headline. */
+export function readTitle(obs: ReplayObservationApi): string | null {
+ const raw = readModelOutput(obs)?.title
+ return typeof raw === 'string' && raw ? raw : null
+}
+
+/** Summarizer output: the narrative body. */
+export function readSummary(obs: ReplayObservationApi): string | null {
+ const raw = readModelOutput(obs)?.summary
+ return typeof raw === 'string' && raw ? raw : null
+}
+
+/** `error_reason` is stored as `kind:message`; the message is the half worth showing a person. */
+export function readErrorMessage(obs: ReplayObservationApi): string | null {
+ if (!obs.error_reason) {
+ return null
+ }
+ const separator = obs.error_reason.indexOf(':')
+ return separator === -1 ? obs.error_reason : obs.error_reason.slice(separator + 1)
+}
+
function readStringArray(value: unknown): string[] {
if (!Array.isArray(value)) {
return []
diff --git a/products/replay_vision/mcp/apps/InlineScanView.tsx b/products/replay_vision/mcp/apps/InlineScanView.tsx
new file mode 100644
index 000000000000..29ad3d64edec
--- /dev/null
+++ b/products/replay_vision/mcp/apps/InlineScanView.tsx
@@ -0,0 +1,85 @@
+import type { ReactElement } from 'react'
+
+import { DescriptionList } from '@posthog/mcp-ui'
+import { Badge, Card, CardContent } from '@posthog/quill'
+
+export interface InlineScanResult {
+ session_id: string
+ scan_outcome: string
+}
+
+export interface InlineScanData {
+ started: number
+ results: InlineScanResult[]
+ scan_id?: string | null
+ _posthogUrl?: string
+}
+
+const outcomeLabel: Record<string, string> = {
+ started: 'Scanning',
+ already_running: 'Already scanning',
+ already_scanned: 'Already scanned',
+ skipped_limit: 'Skipped, too many running',
+ skipped_quota: 'Skipped, out of credits',
+ skipped_scanner_limit: 'Skipped, scanner limit',
+ failed: 'Failed to start',
+}
+
+const outcomeVariant: Record<string, 'success' | 'destructive' | 'warning' | 'default'> = {
+ started: 'success',
+ already_running: 'default',
+ already_scanned: 'default',
+ skipped_limit: 'warning',
+ skipped_quota: 'warning',
+ skipped_scanner_limit: 'warning',
+ failed: 'destructive',
+}
+
+export function InlineScanView({ data }: { data: InlineScanData }): ReactElement {
+ const total = data.results.length
+ const readable = data.results.some(
+ (r) =>
+ r.scan_outcome === 'already_scanned' || r.scan_outcome === 'started' || r.scan_outcome === 'already_running'
+ )
+
+ return (
+ <div className="p-4">
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-col gap-1">
+ <span className="text-lg font-semibold">
+ {data.started} of {total} recording{total === 1 ? '' : 's'} scanning
+ </span>
+ <span className="text-sm text-muted-foreground">
+ {/* Results arrive per recording, so the answer is read back rather than returned here. */}
+ {readable
+ ? 'Read the results with vision-observations-list once each recording finishes.'
+ : 'Nothing started, so there is nothing to read back.'}
+ </span>
+ </div>
+
+ {data.scan_id && (
+ <Card>
+ <CardContent>
+ <DescriptionList items={[{ label: 'Scan id', value: data.scan_id }]} />
+ </CardContent>
+ </Card>
+ )}
+
+ <Card>
+ <CardContent>
+ <div className="flex flex-col gap-2">
+ {data.results.map((result) => (
+ <div key={result.session_id} className="flex items-center justify-between gap-2">
+ <span className="text-sm break-all">{result.session_id}</span>
+ <Badge variant={outcomeVariant[result.scan_outcome] ?? 'default'}>
+ {outcomeLabel[result.scan_outcome] ?? result.scan_outcome}
+ </Badge>
+ </div>
+ ))}
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+ )
+}
diff --git a/products/replay_vision/mcp/apps/ReplayVision.stories.tsx b/products/replay_vision/mcp/apps/ReplayVision.stories.tsx
new file mode 100644
index 000000000000..902731a33a8b
--- /dev/null
+++ b/products/replay_vision/mcp/apps/ReplayVision.stories.tsx
@@ -0,0 +1,120 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'
+
+import {
+ InlineScanView,
+ type InlineScanData,
+ VisionObservationListView,
+ type VisionObservationData,
+ type VisionObservationListData,
+ VisionObservationView,
+} from './index'
+
+const meta: Meta = {
+ title: 'MCP Apps/Replay Vision',
+ decorators: [McpThemeDecorator],
+ parameters: {
+ testOptions: {
+ // McpThemeDecorator has no dark mode, so a dark snapshot would just duplicate the light one.
+ skipDarkMode: true,
+ },
+ },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+const scanStarted: InlineScanData = {
+ started: 2,
+ scan_id: '0199c0de-1111-7000-8000-0000000000aa',
+ results: [
+ { session_id: '0199c0de-2222-7000-8000-0000000000b1', scan_outcome: 'started' },
+ { session_id: '0199c0de-2222-7000-8000-0000000000b2', scan_outcome: 'started' },
+ { session_id: '0199c0de-2222-7000-8000-0000000000b3', scan_outcome: 'already_scanned' },
+ ],
+}
+
+const scanOutOfCredits: InlineScanData = {
+ started: 0,
+ scan_id: null,
+ results: [
+ { session_id: '0199c0de-2222-7000-8000-0000000000b1', scan_outcome: 'skipped_quota' },
+ { session_id: '0199c0de-2222-7000-8000-0000000000b2', scan_outcome: 'skipped_scanner_limit' },
+ ],
+}
+
+export const ScanStarted: Story = {
+ render: () => <InlineScanView data={scanStarted} />,
+ name: 'Inline scan started',
+}
+
+export const ScanOutOfCredits: Story = {
+ render: () => <InlineScanView data={scanOutOfCredits} />,
+ name: 'Inline scan with nothing started',
+}
+
+const summarized: VisionObservationData = {
+ id: '0199c0de-3333-7000-8000-0000000000c1',
+ session_id: '0199c0de-2222-7000-8000-0000000000b1',
+ status: 'succeeded',
+ recording_subject_email: '[email protected]',
+ scanner_result: {
+ model_output: {
+ title: 'Abandoned checkout at the payment step',
+ summary:
+ 'The user browsed three product pages, added a jacket to the basket, and opened checkout. ' +
+ 'They filled in the shipping form, then switched to the payment tab and retyped the card ' +
+ 'number four times. Each attempt returned a validation message under the expiry field. ' +
+ 'They closed the tab without completing the order.',
+ },
+ },
+}
+
+const runningObservation: VisionObservationData = {
+ id: '0199c0de-3333-7000-8000-0000000000c2',
+ session_id: '0199c0de-2222-7000-8000-0000000000b2',
+ status: 'running',
+ scanner_result: null,
+}
+
+const ineligibleObservation: VisionObservationData = {
+ id: '0199c0de-3333-7000-8000-0000000000c3',
+ session_id: '0199c0de-2222-7000-8000-0000000000b3',
+ status: 'ineligible',
+ error_reason: 'too_short:the recording is under five seconds long',
+ scanner_result: null,
+}
+
+const monitorObservation: VisionObservationData = {
+ id: '0199c0de-3333-7000-8000-0000000000c4',
+ session_id: '0199c0de-2222-7000-8000-0000000000b4',
+ status: 'succeeded',
+ scanner_result: {
+ model_output: {
+ verdict: 'yes',
+ reasoning: 'The user opened the pricing page twice and never reached the signup form.',
+ },
+ },
+}
+
+export const SummarizedObservation: Story = {
+ render: () => <VisionObservationView data={summarized} />,
+ name: 'Observation with a summary',
+}
+
+export const IneligibleObservation: Story = {
+ render: () => <VisionObservationView data={ineligibleObservation} />,
+ name: 'Observation that could not be watched',
+}
+
+const observationList: VisionObservationListData = {
+ count: 4,
+ results: [summarized, monitorObservation, runningObservation, ineligibleObservation],
+ _posthogUrl: 'https://us.posthog.com/project/1/replay-vision',
+}
+
+export const ObservationList: Story = {
+ render: () => <VisionObservationListView data={observationList} />,
+ name: 'Observation list',
+}
diff --git a/products/replay_vision/mcp/apps/VisionObservationListView.tsx b/products/replay_vision/mcp/apps/VisionObservationListView.tsx
new file mode 100644
index 000000000000..ee87609cc50a
--- /dev/null
+++ b/products/replay_vision/mcp/apps/VisionObservationListView.tsx
@@ -0,0 +1,90 @@
+import { type ReactElement, type ReactNode } from 'react'
+
+import { DataTable, type DataTableColumn, ListDetailView } from '@posthog/mcp-ui'
+import { Badge, Button } from '@posthog/quill'
+
+import {
+ VisionObservationView,
+ type VisionObservationData,
+ observationHeadline,
+ statusVariant,
+} from './VisionObservationView'
+
+export interface VisionObservationListData {
+ count?: number
+ results: VisionObservationData[]
+ _posthogUrl?: string
+}
+
+export interface VisionObservationListViewProps {
+ data: VisionObservationListData
+ onVisionObservationClick?: (observation: VisionObservationData) => Promise<VisionObservationData | null>
+}
+
+export function VisionObservationListView({
+ data,
+ onVisionObservationClick,
+}: VisionObservationListViewProps): ReactElement {
+ const pending = data.results.filter((o) => o.status === 'pending' || o.status === 'running').length
+
+ return (
+ <ListDetailView<VisionObservationData>
+ onItemClick={onVisionObservationClick}
+ backLabel="All observations"
+ getItemName={(observation) => observationHeadline(observation)}
+ renderDetail={(observation) => <VisionObservationView data={observation} />}
+ renderList={(handleClick) => {
+ const columns: DataTableColumn<VisionObservationData>[] = [
+ {
+ key: 'result',
+ header: 'Result',
+ render: (row): ReactNode =>
+ onVisionObservationClick ? (
+ <Button
+ variant="link"
+ size="sm"
+ onClick={() => handleClick(row)}
+ className="h-auto px-0 text-left max-w-md truncate"
+ >
+ {observationHeadline(row)}
+ </Button>
+ ) : (
+ <span className="max-w-md truncate block">{observationHeadline(row)}</span>
+ ),
+ },
+ {
+ key: 'status',
+ header: 'Status',
+ sortable: true,
+ render: (row): ReactNode => (
+ <Badge variant={statusVariant[row.status] ?? 'default'}>{row.status}</Badge>
+ ),
+ },
+ {
+ key: 'session_id',
+ header: 'Session',
+ render: (row): ReactNode => <span className="text-xs break-all">{row.session_id}</span>,
+ },
+ ]
+
+ return (
+ <div className="p-4">
+ <div className="flex flex-col gap-2">
+ <span className="text-sm text-muted-foreground">
+ {data.results.length} observation{data.results.length === 1 ? '' : 's'}
+ {/* Say what is still coming, so a partial list does not read as the final answer. */}
+ {pending > 0 ? `, ${pending} still running` : ''}
+ </span>
+ <DataTable<VisionObservationData>
+ columns={columns}
+ data={data.results}
+ pageSize={10}
+ emptyMessage="No observations yet"
+ />
+ </div>
+ </div>
+ )
+ }}
+ />
+ )
+}
diff --git a/products/replay_vision/mcp/apps/VisionObservationView.test.tsx b/products/replay_vision/mcp/apps/VisionObservationView.test.tsx
new file mode 100644
index 000000000000..2d1de2016188
--- /dev/null
+++ b/products/replay_vision/mcp/apps/VisionObservationView.test.tsx
@@ -0,0 +1,86 @@
+import { cleanup, render, screen } from '@testing-library/react'
+import { type ReactElement } from 'react'
+
+import { VisionObservationView, observationHeadline } from './VisionObservationView'
+
+jest.mock(
+ '@posthog/mcp-ui',
+ () => ({
+ DescriptionList: ({ items }: { items: { label: string; value: string }[] }): ReactElement => (
+ <dl>
+ {items.map((item) => (
+ <div key={item.label}>
+ <dt>{item.label}</dt>
+ <dd>{item.value}</dd>
+ </div>
+ ))}
+ </dl>
+ ),
+ }),
+ { virtual: true }
+)
+
+jest.mock(
+ '@posthog/quill',
+ () => ({
+ Badge: ({ children }: { children: ReactElement }): ReactElement => <span>{children}</span>,
+ Card: ({ children }: { children: ReactElement }): ReactElement => <div>{children}</div>,
+ CardContent: ({ children }: { children: ReactElement }): ReactElement => <div>{children}</div>,
+ }),
+ { virtual: true }
+)
+
+describe('VisionObservationView', () => {
+ afterEach(cleanup)
+
+ // The scanner type decides which output fields exist, and the list shows one line per row. A bare
+ // monitor verdict ("yes") reads as nothing, so reasoning has to win when both are present.
+ it.each([
+ ['summarizer', { title: 'Abandoned checkout', summary: 'They gave up.' }, 'Abandoned checkout'],
+ ['summarizer without a title', { summary: 'They gave up.' }, 'They gave up.'],
+ ['monitor', { verdict: 'yes', reasoning: 'Never reached signup.' }, 'Never reached signup.'],
+ ['monitor without reasoning', { verdict: 'yes' }, 'yes'],
+ ['a finished scan with no output', null, 'No result'],
+ ])('takes the headline from %s output', (_name, modelOutput, expected) => {
+ const headline = observationHeadline({
+ id: 'obs-1',
+ session_id: 'session-1',
+ status: 'succeeded',
+ scanner_result: modelOutput ? { model_output: modelOutput } : null,
+ })
+
+ expect(headline).toBe(expected)
+ })
+
+ it('shows why a recording could not be watched', () => {
+ render(
+ <VisionObservationView
+ data={{
+ id: 'obs-2',
+ session_id: 'session-2',
+ status: 'ineligible',
+ error_reason: 'too_short:the recording is under five seconds long',
+ scanner_result: null,
+ }}
+ />
+ )
+
+ expect(screen.getByText('the recording is under five seconds long')).toBeTruthy()
+ })
+
+ it('renders the summary body for a summarizer result', () => {
+ render(
+ <VisionObservationView
+ data={{
+ id: 'obs-3',
+ session_id: 'session-3',
+ status: 'succeeded',
+ scanner_result: { model_output: { title: 'Abandoned checkout', summary: 'They gave up.' } },
+ }}
+ />
+ )
+
+ expect(screen.getByText('Abandoned checkout')).toBeTruthy()
+ expect(screen.getByText('They gave up.')).toBeTruthy()
+ })
+})
diff --git a/products/replay_vision/mcp/apps/VisionObservationView.tsx b/products/replay_vision/mcp/apps/VisionObservationView.tsx
new file mode 100644
index 000000000000..591371bf98c2
--- /dev/null
+++ b/products/replay_vision/mcp/apps/VisionObservationView.tsx
@@ -0,0 +1,107 @@
+import type { ReactElement } from 'react'
+
+import { DescriptionList } from '@posthog/mcp-ui'
+import { Badge, Card, CardContent } from '@posthog/quill'
+
+export interface VisionObservationData {
+ id: string
+ session_id: string
+ status: string
+ error_reason?: string | null
+ scanner_result?: { model_output?: unknown } | null
+ recording_subject_email?: string | null
+ _posthogUrl?: string
+}
+
+export const statusVariant: Record<string, 'success' | 'destructive' | 'warning' | 'default'> = {
+ succeeded: 'success',
+ failed: 'destructive',
+ ineligible: 'warning',
+ pending: 'default',
+ running: 'default',
+}
+
+/** The scanner type decides the shape, so read the fields that exist rather than assuming one. */
+export function readOutput(observation: VisionObservationData): Record<string, unknown> | null {
+ const output = observation.scanner_result?.model_output
+ return output && typeof output === 'object' ? (output as Record<string, unknown>) : null
+}
+
+function readString(output: Record<string, unknown> | null, key: string): string | null {
+ const value = output?.[key]
+ return typeof value === 'string' && value ? value : null
+}
+
+/**
+ * One line describing what the scanner found. A monitor's bare verdict ("yes") says nothing on its
+ * own, so its reasoning comes first; a row with no result yet says so rather than repeating the
+ * session id already shown in its own column.
+ */
+export function observationHeadline(observation: VisionObservationData): string {
+ const output = readOutput(observation)
+ const found =
+ readString(output, 'title') ??
+ readString(output, 'summary') ??
+ readString(output, 'reasoning') ??
+ readString(output, 'verdict')
+ if (found) {
+ return found
+ }
+ if (observation.status === 'pending' || observation.status === 'running') {
+ return 'Still watching'
+ }
+ return humanReason(observation) ?? 'No result'
+}
+
+/** Error reasons are stored as `kind:message`; the message is the half worth showing. */
+export function humanReason(observation: VisionObservationData): string | null {
+ if (!observation.error_reason) {
+ return null
+ }
+ const separator = observation.error_reason.indexOf(':')
+ return separator === -1 ? observation.error_reason : observation.error_reason.slice(separator + 1)
+}
+
+export function VisionObservationView({ data }: { data: VisionObservationData }): ReactElement {
+ const output = readOutput(data)
+ const summary = readString(output, 'summary')
+ const reasoning = readString(output, 'reasoning')
+ const title = readString(output, 'title')
+
+ const items = [
+ { label: 'Session', value: data.session_id },
+ { label: 'Status', value: data.status },
+ ]
+ if (data.recording_subject_email) {
+ items.push({ label: 'Person', value: data.recording_subject_email })
+ }
+ const reason = humanReason(data)
+ if (reason) {
+ items.push({ label: 'Reason', value: reason })
+ }
+
+ return (
+ <div className="p-4">
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-lg font-semibold break-all">{title ?? data.session_id}</span>
+ <Badge variant={statusVariant[data.status] ?? 'default'}>{data.status}</Badge>
+ </div>
+
+ {(summary || reasoning) && (
+ <Card>
+ <CardContent>
+ <p className="m-0 text-sm whitespace-pre-wrap">{summary ?? reasoning}</p>
+ </CardContent>
+ </Card>
+ )}
+
+ <Card>
+ <CardContent>
+ <DescriptionList items={items} />
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+ )
+}
diff --git a/products/replay_vision/mcp/apps/index.ts b/products/replay_vision/mcp/apps/index.ts
new file mode 100644
index 000000000000..81e111400862
--- /dev/null
+++ b/products/replay_vision/mcp/apps/index.ts
@@ -0,0 +1,7 @@
+export { InlineScanView, type InlineScanData, type InlineScanResult } from './InlineScanView'
+export {
+ VisionObservationListView,
+ type VisionObservationListData,
+ type VisionObservationListViewProps,
+} from './VisionObservationListView'
+export { VisionObservationView, type VisionObservationData } from './VisionObservationView'
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yaml
index 323b4b57b0ac..4bfb1f197318 100644
--- a/products/replay_vision/mcp/tools.yaml
+++ b/products/replay_vision/mcp/tools.yaml
@@ -7,7 +7,15 @@
category: Replay vision
feature: replay_vision
url_prefix: /replay-vision
-ui_apps: {}
+ui_apps:
+ inline-scan:
+ type: detail
+ view_prop: data
+ vision-observation-list:
+ type: list
+ detail_tool: vision-observations-retrieve
+ item_name_field: id
+ entity_label: observation
tools:
vision-actions-create:
operation: vision_actions_create
@@ -217,6 +225,7 @@ tools:
`timestamp_ms` is the recording-relative offset of the moment being cited — append `?t=<seconds>`
(`timestamp_ms` / 1000, rounded down) to that URL to seek straight to it. When you report a finding to
someone, deep-link the one or two moments it turns on rather than only describing them.
+ ui_app: vision-observation-list
url_prefix: /replay
vision-observations-retrieve:
operation: vision_observations_retrieve
@@ -440,6 +449,7 @@ tools:
than being charged twice. Scans cost credits per session at the same rate a scanner does; check
`vision-quota-retrieve` first if the batch is large, since sessions past the monthly limit come back as
`skipped_quota` instead of failing the call.
+ ui_app: inline-scan
requires_ai_consent: true
vision-scanners-list:
operation: vision_scanners_list
@@ -520,6 +530,7 @@ tools:
`timestamp_ms` is the recording-relative offset of the moment being cited — append `?t=<seconds>`
(`timestamp_ms` / 1000, rounded down) to that URL to seek straight to it. When you report a finding to
someone, deep-link the one or two moments it turns on rather than only describing them.
+ ui_app: vision-observation-list
url_prefix: /replay
vision-scanners-observations-retry-create:
operation: vision_scanners_observations_retry_create
diff --git a/services/mcp/src/resources/ui-apps.generated.ts b/services/mcp/src/resources/ui-apps.generated.ts
index 2a6a3fe0d3bc..7ca4e282b40a 100644
--- a/services/mcp/src/resources/ui-apps.generated.ts
+++ b/services/mcp/src/resources/ui-apps.generated.ts
@@ -15,6 +15,7 @@ export const EXPERIMENT_RESULTS_RESOURCE_URI = 'ui://posthog/experiment-results.
export const FEATURE_FLAG_RESOURCE_URI = 'ui://posthog/feature-flag.html'
export const FEATURE_FLAG_LIST_RESOURCE_URI = 'ui://posthog/feature-flag-list.html'
export const FEATURE_FLAG_TESTING_RESOURCE_URI = 'ui://posthog/feature-flag-testing.html'
+export const INLINE_SCAN_RESOURCE_URI = 'ui://posthog/inline-scan.html'
export const INSIGHT_ACTORS_RESOURCE_URI = 'ui://posthog/insight-actors.html'
export const INVITE_EMAIL_PREVIEW_RESOURCE_URI = 'ui://posthog/invite-email-preview.html'
export const LLM_COSTS_RESOURCE_URI = 'ui://posthog/llm-costs.html'
@@ -28,6 +29,7 @@ export const SURVEY_LIST_RESOURCE_URI = 'ui://posthog/survey-list.html'
export const SURVEY_STATS_RESOURCE_URI = 'ui://posthog/survey-stats.html'
export const TRACE_SPAN_RESOURCE_URI = 'ui://posthog/trace-span.html'
export const TRACE_SPAN_LIST_RESOURCE_URI = 'ui://posthog/trace-span-list.html'
+export const VISION_OBSERVATION_LIST_RESOURCE_URI = 'ui://posthog/vision-observation-list.html'
export const VISUAL_REVIEW_SNAPSHOTS_RESOURCE_URI = 'ui://posthog/visual-review-snapshots.html'
export const WORKFLOW_RESOURCE_URI = 'ui://posthog/workflow.html'
export const WORKFLOW_LIST_RESOURCE_URI = 'ui://posthog/workflow-list.html'
@@ -48,6 +50,7 @@ export type UiAppKey =
| 'feature-flag'
| 'feature-flag-list'
| 'feature-flag-testing'
+ | 'inline-scan'
| 'insight-actors'
| 'invite-email-preview'
| 'llm-costs'
@@ -61,6 +64,7 @@ export type UiAppKey =
| 'survey-stats'
| 'trace-span'
| 'trace-span-list'
+ | 'vision-observation-list'
| 'visual-review-snapshots'
| 'workflow'
| 'workflow-list'
@@ -81,6 +85,7 @@ export const URI_MAP: Record<UiAppKey, string> = {
'feature-flag': FEATURE_FLAG_RESOURCE_URI,
'feature-flag-list': FEATURE_FLAG_LIST_RESOURCE_URI,
'feature-flag-testing': FEATURE_FLAG_TESTING_RESOURCE_URI,
+ 'inline-scan': INLINE_SCAN_RESOURCE_URI,
'insight-actors': INSIGHT_ACTORS_RESOURCE_URI,
'invite-email-preview': INVITE_EMAIL_PREVIEW_RESOURCE_URI,
'llm-costs': LLM_COSTS_RESOURCE_URI,
@@ -94,6 +99,7 @@ export const URI_MAP: Record<UiAppKey, string> = {
'survey-stats': SURVEY_STATS_RESOURCE_URI,
'trace-span': TRACE_SPAN_RESOURCE_URI,
'trace-span-list': TRACE_SPAN_LIST_RESOURCE_URI,
+ 'vision-observation-list': VISION_OBSERVATION_LIST_RESOURCE_URI,
'visual-review-snapshots': VISUAL_REVIEW_SNAPSHOTS_RESOURCE_URI,
workflow: WORKFLOW_RESOURCE_URI,
'workflow-list': WORKFLOW_LIST_RESOURCE_URI,
@@ -118,6 +124,7 @@ export const DISPATCHABLE_APP_KEYS: UiAppKey[] = [
'feature-flag',
'feature-flag-list',
'feature-flag-testing',
+ 'inline-scan',
'insight-actors',
'invite-email-preview',
'llm-costs',
@@ -129,6 +136,7 @@ export const DISPATCHABLE_APP_KEYS: UiAppKey[] = [
'survey-stats',
'trace-span',
'trace-span-list',
+ 'vision-observation-list',
'workflow',
'workflow-list',
]
@@ -229,6 +237,12 @@ export const UI_APPS: Array<{
description: 'Feature Flag Testing detail view',
appDir: 'generated/feature-flag-testing',
},
+ {
+ name: 'PostHog Inline Scan',
+ uri: INLINE_SCAN_RESOURCE_URI,
+ description: 'Inline Scan detail view',
+ appDir: 'generated/inline-scan',
+ },
{
name: 'PostHog Insight Actors',
uri: INSIGHT_ACTORS_RESOURCE_URI,
@@ -307,6 +321,12 @@ export const UI_APPS: Array<{
description: 'Trace Span List view',
appDir: 'generated/trace-span-list',
},
+ {
+ name: 'PostHog Vision Observation List',
+ uri: VISION_OBSERVATION_LIST_RESOURCE_URI,
+ description: 'Vision Observation List view',
+ appDir: 'generated/vision-observation-list',
+ },
{
name: 'PostHog Visual Review Snapshots',
uri: VISUAL_REVIEW_SNAPSHOTS_RESOURCE_URI,
diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.ts
index 8073258aaf96..53d98dc84500 100644
--- a/services/mcp/src/tools/generated/replay_vision.ts
+++ b/services/mcp/src/tools/generated/replay_vision.ts
@@ -44,6 +44,7 @@ import {
VisionScannersPromptSuggestionsGenerateCreateParams,
VisionScannersRetrieveParams,
} from '@/generated/replay_vision/api'
+import { withUiApp } from '@/resources/ui-apps'
import { withPostHogUrl, withAgentNote, type WithPostHogUrl, type WithAgentNote } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -289,38 +290,39 @@ const VisionObservationsListSchema = VisionObservationsListQueryParams
const visionObservationsList = (): ToolBase<
typeof VisionObservationsListSchema,
WithAgentNote<WithPostHogUrl<Schemas.PaginatedReplayObservationList>>
-> => ({
- name: 'vision-observations-list',
- schema: VisionObservationsListSchema,
- handler: async (context: Context, params: z.infer<typeof VisionObservationsListSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedReplayObservationList>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/observations/`,
- query: {
- limit: params.limit,
- offset: params.offset,
- order_by: params.order_by,
- session_id: params.session_id,
- },
- })
- return withAgentNote(
- await withPostHogUrl(
- context,
- {
- ...result,
- results: await Promise.all(
- (result.results ?? []).map((item) =>
- withPostHogUrl(context, item, `/replay/${item.session_id}`)
- )
- ),
+> =>
+ withUiApp('vision-observation-list', {
+ name: 'vision-observations-list',
+ schema: VisionObservationsListSchema,
+ handler: async (context: Context, params: z.infer<typeof VisionObservationsListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedReplayObservationList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/observations/`,
+ query: {
+ limit: params.limit,
+ offset: params.offset,
+ order_by: params.order_by,
+ session_id: params.session_id,
},
- '/replay'
- ),
- "Each observation's `_posthogUrl` opens the recording it analysed. `scanner_result.model_output.reasoning_segments` interleaves prose with `chip` segments, and a chip's `timestamp_ms` is the recording-relative offset of the moment being cited — append `?t=<seconds>` (`timestamp_ms` / 1000, rounded down) to that URL to seek straight to it. When you report a finding to someone, deep-link the one or two moments it turns on rather than only describing them.\n"
- )
- },
-})
+ })
+ return withAgentNote(
+ await withPostHogUrl(
+ context,
+ {
+ ...result,
+ results: await Promise.all(
+ (result.results ?? []).map((item) =>
+ withPostHogUrl(context, item, `/replay/${item.session_id}`)
+ )
+ ),
+ },
+ '/replay'
+ ),
+ "Each observation's `_posthogUrl` opens the recording it analysed. `scanner_result.model_output.reasoning_segments` interleaves prose with `chip` segments, and a chip's `timestamp_ms` is the recording-relative offset of the moment being cited — append `?t=<seconds>` (`timestamp_ms` / 1000, rounded down) to that URL to seek straight to it. When you report a finding to someone, deep-link the one or two moments it turns on rather than only describing them.\n"
+ )
+ },
+ })
const VisionObservationsRetrieveSchema = VisionObservationsRetrieveParams.omit({ project_id: true }).extend(
VisionObservationsRetrieveQueryParams.shape
@@ -559,35 +561,36 @@ const visionScannersImpactRetrieve = (): ToolBase<
const VisionScannersInlineScanCreateSchema = VisionScannersInlineScanCreateBody
-const visionScannersInlineScanCreate = (): ToolBase<typeof VisionScannersInlineScanCreateSchema, unknown> => ({
- name: 'vision-scanners-inline-scan-create',
- schema: VisionScannersInlineScanCreateSchema,
- handler: async (context: Context, params: z.infer<typeof VisionScannersInlineScanCreateSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.session_ids !== undefined) {
- body['session_ids'] = params.session_ids
- }
- if (params.prompt !== undefined) {
- body['prompt'] = params.prompt
- }
- if (params.scanner_type !== undefined) {
- body['scanner_type'] = params.scanner_type
- }
- if (params.scanner_config !== undefined) {
- body['scanner_config'] = params.scanner_config
- }
- if (params.model !== undefined) {
- body['model'] = params.model
- }
- const result = await context.api.request<unknown>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/inline_scan/`,
- body,
- })
- return result
- },
-})
+const visionScannersInlineScanCreate = (): ToolBase<typeof VisionScannersInlineScanCreateSchema, unknown> =>
+ withUiApp('inline-scan', {
+ name: 'vision-scanners-inline-scan-create',
+ schema: VisionScannersInlineScanCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof VisionScannersInlineScanCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.session_ids !== undefined) {
+ body['session_ids'] = params.session_ids
+ }
+ if (params.prompt !== undefined) {
+ body['prompt'] = params.prompt
+ }
+ if (params.scanner_type !== undefined) {
+ body['scanner_type'] = params.scanner_type
+ }
+ if (params.scanner_config !== undefined) {
+ body['scanner_config'] = params.scanner_config
+ }
+ if (params.model !== undefined) {
+ body['model'] = params.model
+ }
+ const result = await context.api.request<unknown>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/inline_scan/`,
+ body,
+ })
+ return result
+ },
+ })
const VisionScannersListSchema = VisionScannersListQueryParams
@@ -663,49 +666,50 @@ const VisionScannersObservationsListSchema = VisionScannersObservationsListParam
const visionScannersObservationsList = (): ToolBase<
typeof VisionScannersObservationsListSchema,
WithAgentNote<WithPostHogUrl<Schemas.PaginatedReplayObservationList>>
-> => ({
- name: 'vision-scanners-observations-list',
- schema: VisionScannersObservationsListSchema,
- handler: async (context: Context, params: z.infer<typeof VisionScannersObservationsListSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedReplayObservationList>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/${encodeURIComponent(String(params.scanner_id))}/observations/`,
- query: {
- backfill_id: params.backfill_id,
- date_from: params.date_from,
- date_to: params.date_to,
- labeled: params.labeled,
- limit: params.limit,
- max_score: params.max_score,
- min_score: params.min_score,
- offset: params.offset,
- order_by: params.order_by,
- recording_subject: params.recording_subject,
- session_id: params.session_id,
- status: params.status,
- tags: params.tags,
- triggered_by: params.triggered_by,
- verdict: params.verdict,
- },
- })
- return withAgentNote(
- await withPostHogUrl(
- context,
- {
- ...result,
- results: await Promise.all(
- (result.results ?? []).map((item) =>
- withPostHogUrl(context, item, `/replay/${item.session_id}`)
- )
- ),
+> =>
+ withUiApp('vision-observation-list', {
+ name: 'vision-scanners-observations-list',
+ schema: VisionScannersObservationsListSchema,
+ handler: async (context: Context, params: z.infer<typeof VisionScannersObservationsListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedReplayObservationList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/${encodeURIComponent(String(params.scanner_id))}/observations/`,
+ query: {
+ backfill_id: params.backfill_id,
+ date_from: params.date_from,
+ date_to: params.date_to,
+ labeled: params.labeled,
+ limit: params.limit,
+ max_score: params.max_score,
+ min_score: params.min_score,
+ offset: params.offset,
+ order_by: params.order_by,
+ recording_subject: params.recording_subject,
+ session_id: params.session_id,
+ status: params.status,
+ tags: params.tags,
+ triggered_by: params.triggered_by,
+ verdict: params.verdict,
},
- '/replay'
- ),
- "Each observation's `_posthogUrl` opens the recording it analysed. `scanner_result.model_output.reasoning_segments` interleaves prose with `chip` segments, and a chip's `timestamp_ms` is the recording-relative offset of the moment being cited — append `?t=<seconds>` (`timestamp_ms` / 1000, rounded down) to that URL to seek straight to it. When you report a finding to someone, deep-link the one or two moments it turns on rather than only describing them.\n"
- )
- },
-})
+ })
+ return withAgentNote(
+ await withPostHogUrl(
+ context,
+ {
+ ...result,
+ results: await Promise.all(
+ (result.results ?? []).map((item) =>
+ withPostHogUrl(context, item, `/replay/${item.session_id}`)
+ )
+ ),
+ },
+ '/replay'
+ ),
+ "Each observation's `_posthogUrl` opens the recording it analysed. `scanner_result.model_output.reasoning_segments` interleaves prose with `chip` segments, and a chip's `timestamp_ms` is the recording-relative offset of the moment being cited — append `?t=<seconds>` (`timestamp_ms` / 1000, rounded down) to that URL to seek straight to it. When you report a finding to someone, deep-link the one or two moments it turns on rather than only describing them.\n"
+ )
+ },
+ })
const VisionScannersObservationsStatsSchema = VisionScannersObservationsStatsRetrieveParams.omit({
project_id: true,
diff --git a/services/mcp/src/ui-apps/apps/generated/inline-scan.tsx b/services/mcp/src/ui-apps/apps/generated/inline-scan.tsx
new file mode 100644
index 000000000000..4f47557796a6
--- /dev/null
+++ b/services/mcp/src/ui-apps/apps/generated/inline-scan.tsx
@@ -0,0 +1,21 @@
+// AUTO-GENERATED by generate-ui-apps.ts — do not edit
+import '../../styles/tailwind.css'
+
+import { createRoot } from 'react-dom/client'
+
+import { type InlineScanData, InlineScanView } from 'products/replay_vision/mcp/apps'
+
+import { AppWrapper } from '../../components/AppWrapper'
+
+function InlineScanApp(): JSX.Element {
+ return (
+ <AppWrapper<InlineScanData> appName="PostHog Inline Scan">
+ {({ data }) => <InlineScanView data={data!} />}
+ </AppWrapper>
+ )
+}
+
+const container = document.getElementById('root')
+if (container) {
+ createRoot(container).render(<InlineScanApp />)
+}
diff --git a/services/mcp/src/ui-apps/apps/generated/vision-observation-list.tsx b/services/mcp/src/ui-apps/apps/generated/vision-observation-list.tsx
new file mode 100644
index 000000000000..cdc020ce2fe3
--- /dev/null
+++ b/services/mcp/src/ui-apps/apps/generated/vision-observation-list.tsx
@@ -0,0 +1,71 @@
+// AUTO-GENERATED by generate-ui-apps.ts — do not edit
+import '../../styles/tailwind.css'
+
+import type { App } from '@modelcontextprotocol/ext-apps'
+import { useCallback } from 'react'
+import { createRoot } from 'react-dom/client'
+
+import {
+ type VisionObservationData,
+ type VisionObservationListData,
+ VisionObservationListView,
+} from 'products/replay_vision/mcp/apps'
+
+import { AppWrapper } from '../../components/AppWrapper'
+
+function VisionObservationListApp(): JSX.Element {
+ return (
+ <AppWrapper<VisionObservationListData> appName="PostHog Vision Observation List">
+ {({ data, app }) => <VisionObservationListContent data={data!} app={app} />}
+ </AppWrapper>
+ )
+}
+
+function VisionObservationListContent({
+ data,
+ app,
+}: {
+ data: VisionObservationListData
+ app: App | null
+}): JSX.Element {
+ const fallbackToChat = useCallback(
+ (name: string) => {
+ app?.sendMessage({
+ role: 'user',
+ content: [{ type: 'text', text: `Show me the details for observation "${name}"` }],
+ })
+ },
+ [app]
+ )
+
+ const handleClick = useCallback(
+ async (item: VisionObservationData): Promise<VisionObservationData | null> => {
+ if (!app) {
+ fallbackToChat(item.id)
+ return null
+ }
+ try {
+ const result = await app.callServerTool({
+ name: 'vision-observations-retrieve',
+ arguments: { id: item.id },
+ })
+ if (result.isError || !result.structuredContent) {
+ fallbackToChat(item.id)
+ return null
+ }
+ return result.structuredContent as unknown as VisionObservationData
+ } catch {
+ fallbackToChat(item.id)
+ return null
+ }
+ },
+ [app, fallbackToChat]
+ )
+
+ return <VisionObservationListView data={data} onVisionObservationClick={handleClick} />
+}
+
+const container = document.getElementById('root')
+if (container) {
+ createRoot(container).render(<VisionObservationListApp />)
+}
diff --git a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
index b5e8b870d6a4..feeace1b77c3 100644
--- a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
+++ b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx
@@ -31,6 +31,13 @@ import {
} from 'products/feature_flags/mcp/apps'
import { InsightActorsView, type InsightActorsData } from 'products/product_analytics/mcp/apps'
import { SessionRecordingView, type SessionRecordingData } from 'products/replay/mcp/apps'
+import {
+ InlineScanView,
+ VisionObservationListView,
+ type InlineScanData,
+ type VisionObservationData,
+ type VisionObservationListData,
+} from 'products/replay_vision/mcp/apps'
import {
SurveyListView,
SurveyStatsView,
@@ -325,6 +332,50 @@ function TraceSpanListContent({ data, app }: { data: TraceSpanListData; app: App
return <TraceSpanListView data={data} onSpanClick={handleClick} />
}
+function VisionObservationListContent({
+ data,
+ app,
+}: {
+ data: VisionObservationListData
+ app: App | null
+}): JSX.Element {
+ const fallbackToChat = useCallback(
+ (name: string) => {
+ app?.sendMessage({
+ role: 'user',
+ content: [{ type: 'text', text: `Show me the details for observation "${name}"` }],
+ })
+ },
+ [app]
+ )
+
+ const handleClick = useCallback(
+ async (item: VisionObservationData): Promise<VisionObservationData | null> => {
+ if (!app) {
+ fallbackToChat(item.id)
+ return null
+ }
+ try {
+ const result = await app.callServerTool({
+ name: 'vision-observations-retrieve',
+ arguments: { id: item.id },
+ })
+ if (result.isError || !result.structuredContent) {
+ fallbackToChat(item.id)
+ return null
+ }
+ return result.structuredContent as unknown as VisionObservationData
+ } catch {
+ fallbackToChat(item.id)
+ return null
+ }
+ },
+ [app, fallbackToChat]
+ )
+
+ return <VisionObservationListView data={data} onVisionObservationClick={handleClick} />
+}
+
function WorkflowListContent({ data, app }: { data: WorkflowListData; app: App | null }): JSX.Element {
const fallbackToChat = useCallback(
(name: string) => {
@@ -378,6 +429,7 @@ export const RENDER_DISPATCH: Partial<Record<UiAppKey, (props: RenderDispatchPro
'feature-flag': ({ data }) => <FeatureFlagView flag={data as FeatureFlagData} />,
'feature-flag-list': ({ data, app }) => <FeatureFlagListContent data={data as FeatureFlagListData} app={app} />,
'feature-flag-testing': ({ data }) => <FeatureFlagTestingView flag={data as FeatureFlagTestingData} />,
+ 'inline-scan': ({ data }) => <InlineScanView data={data as InlineScanData} />,
'insight-actors': ({ data, openLink }) => (
<InsightActorsView data={data as InsightActorsData} openLink={openLink} />
),
@@ -391,6 +443,9 @@ export const RENDER_DISPATCH: Partial<Record<UiAppKey, (props: RenderDispatchPro
'survey-stats': ({ data }) => <SurveyStatsView data={data as SurveyStatsData} />,
'trace-span': ({ data }) => <TraceSpanView data={data as TraceSpanData} />,
'trace-span-list': ({ data, app }) => <TraceSpanListContent data={data as TraceSpanListData} app={app} />,
+ 'vision-observation-list': ({ data, app }) => (
+ <VisionObservationListContent data={data as VisionObservationListData} app={app} />
+ ),
workflow: ({ data }) => <WorkflowView workflow={data as WorkflowData} />,
'workflow-list': ({ data, app }) => <WorkflowListContent data={data as WorkflowListData} app={app} />,
}