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): replay vision page and lenses components (#58220)

Hayne Ryu3a14be287e0f
diff --git a/frontend/package.json b/frontend/package.json
index 01e1746487b8..3e55d35cf768 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -101,6 +101,7 @@
"@posthog/products-platform-features": "workspace:*",
"@posthog/products-product-analytics": "workspace:*",
"@posthog/products-replay": "workspace:*",
+ "@posthog/products-replay-vision": "workspace:*",
"@posthog/products-revenue-analytics": "workspace:*",
"@posthog/products-session-summaries": "workspace:*",
"@posthog/products-surveys": "workspace:*",
diff --git a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
index 548e7db96e99..2fb1cdbe12e7 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
@@ -10,6 +10,7 @@ import {
IconCloud,
IconCode,
IconEndpoints,
+ IconEye,
IconDashboard,
IconDatabase,
IconDecisionTree,
@@ -134,6 +135,10 @@ const iconTypes: Record<FileSystemIconType, { icon: JSX.Element; iconColor?: Fil
icon: <IconRewindPlay />,
iconColor: ['var(--color-product-session-replay-light)', 'var(--color-product-session-replay-dark)'],
},
+ replay_vision: {
+ icon: <IconEye />,
+ iconColor: ['var(--color-product-session-replay-light)', 'var(--color-product-session-replay-dark)'],
+ },
survey: {
icon: <IconMessage />,
iconColor: ['var(--color-product-surveys-light)'],
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 1067c5fa2e15..bd2d8620a133 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -444,6 +444,7 @@ export const FEATURE_FLAGS = {
REPLAY_TRIGGERS_V2: 'replay-triggers-v2', // owner: #team-replay
REPLAY_UI_REDESIGN_2026: 'replay-ui-redesign-2026', // owner: #team-replay, New UI layout for replay
REPLAY_VIDEO_BASED_SUMMARIZATION: 'replay-video-based-summarization', // owner: #team-replay
+ REPLAY_VISION: 'replay-vision', // owner: #team-replay
REPLAY_WAIT_FOR_IFRAME_READY: 'replay-wait-for-full-snapshot-playback', // owner: @ksvat #team-replay
REPLAY_X_LLM_ANALYTICS_CONVERSATION_VIEW: 'replay-x-llm-analytics-conversation-view', // owner: @pauldambra #team-replay
REVENUE_ANALYTICS: 'revenue-analytics', // owner: @rafaeelaudibert #team-customer-analytics
diff --git a/frontend/src/products.json b/frontend/src/products.json
index 3189d7f2c556..72f1cdd1cf2b 100644
--- a/frontend/src/products.json
+++ b/frontend/src/products.json
@@ -186,6 +186,13 @@
"intents": ["session_replay", "mobile_replay"]
},
{ "path": "Heatmaps", "category": "Behavior", "iconType": "heatmap", "type": null, "intents": ["heatmaps"] },
+ {
+ "path": "Replay vision",
+ "category": "Behavior",
+ "iconType": null,
+ "type": "replay_vision",
+ "intents": ["replay_vision"]
+ },
{
"path": "Revenue analytics",
"category": "Analytics",
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 295dad25e807..2bdcae132531 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -119,6 +119,8 @@ export const productScenes: Record<string, () => Promise<any>> = {
ManagedMigration: () => import('../../products/managed_migrations/frontend/ManagedMigration'),
ManagedMigrationNew: () => import('../../products/managed_migrations/frontend/ManagedMigration'),
Metrics: () => import('../../products/metrics/frontend/MetricsScene'),
+ ReplayVision: () => import('../../products/replay_vision/frontend/replay_lenses/ReplayLensesScene'),
+ ReplayVisionLens: () => import('../../products/replay_vision/frontend/replay_lenses/ReplayLens'),
RevenueAnalytics: () => import('../../products/revenue_analytics/frontend/RevenueAnalyticsScene'),
SessionGroupSummariesTable: () => import('../../products/session_summaries/frontend/SessionGroupSummariesTable'),
SessionGroupSummary: () => import('../../products/session_summaries/frontend/SessionGroupSummaryScene'),
@@ -231,6 +233,8 @@ export const productRoutes: Record<string, [string, string]> = {
'/managed_migrations': ['ManagedMigration', 'managedMigration'],
'/managed_migrations/new': ['ManagedMigration', 'managedMigration'],
'/metrics': ['Metrics', 'metrics'],
+ '/replay-vision': ['ReplayVision', 'replayVision'],
+ '/replay-vision/:id': ['ReplayVisionLens', 'replayVision'],
'/revenue_analytics': ['RevenueAnalytics', 'revenueAnalytics'],
'/session-summaries': ['SessionGroupSummariesTable', 'sessionGroupSummariesTable'],
'/session-summaries/:sessionGroupId': ['SessionGroupSummary', 'sessionGroupSummary'],
@@ -567,6 +571,20 @@ export const productConfiguration: Record<string, any> = {
description: 'Monitor and analyze application metrics to understand system performance and health.',
iconType: 'metrics',
},
+ ReplayVision: {
+ name: 'Replay vision',
+ projectBased: true,
+ description:
+ 'Configure named lenses that PostHog applies to completed session recordings. Results land as queryable events.',
+ iconType: 'replay_vision',
+ layout: 'app-container',
+ },
+ ReplayVisionLens: {
+ name: 'Replay vision lens',
+ projectBased: true,
+ iconType: 'replay_vision',
+ layout: 'app-container',
+ },
RevenueAnalytics: {
name: 'Revenue Analytics',
projectBased: true,
@@ -996,6 +1014,7 @@ export const productUrls = {
replayFilePlayback: (): string => '/replay/file-playback',
replayKiosk: (): string => '/replay/kiosk',
replaySettings: (sectionId?: string): string => `/replay/settings${sectionId ? `?sectionId=${sectionId}` : ''}`,
+ replayVision: (id?: string): string => (id ? `/replay-vision/${id}` : '/replay-vision'),
revenueAnalytics: (): string => '/revenue_analytics',
sessionSummaries: (): string => '/session-summaries',
sessionSummary: (sessionGroupId: string): string => `/session-summaries/${sessionGroupId}`,
@@ -1751,6 +1770,22 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
'LLMAnalyticsCluster',
],
},
+ {
+ path: 'Replay vision',
+ category: ProductItemCategory.BEHAVIOR,
+ intents: [ProductKey.REPLAY_VISION],
+ type: 'replay_vision',
+ iconType: 'replay_vision' as FileSystemIconType,
+ iconColor: [
+ 'var(--color-product-session-replay-light)',
+ 'var(--color-product-session-replay-dark)',
+ ] as FileSystemIconColor,
+ href: urls.replayVision(),
+ tags: ['beta'],
+ flag: FEATURE_FLAGS.REPLAY_VISION,
+ sceneKey: 'ReplayVision',
+ sceneKeys: ['ReplayVision', 'ReplayVisionLens'],
+ },
{
path: 'Revenue analytics',
intents: [ProductKey.REVENUE_ANALYTICS],
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 863077337741..75e1793beab7 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -18904,6 +18904,7 @@
"error_tracking",
"heatmap",
"session_replay",
+ "replay_vision",
"session_profile",
"survey",
"product_tour",
@@ -27359,6 +27360,7 @@
"product_tours",
"revenue_analytics",
"session_replay",
+ "replay_vision",
"site_apps",
"subscriptions",
"streamlit_apps",
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 9177706dfcf6..493a5ab16576 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3197,6 +3197,7 @@ export type FileSystemIconType =
| 'error_tracking'
| 'heatmap'
| 'session_replay'
+ | 'replay_vision'
| 'session_profile'
| 'survey'
| 'product_tour'
@@ -6389,6 +6390,7 @@ export enum ProductKey {
PRODUCT_TOURS = 'product_tours',
REVENUE_ANALYTICS = 'revenue_analytics',
SESSION_REPLAY = 'session_replay',
+ REPLAY_VISION = 'replay_vision',
SITE_APPS = 'site_apps',
SUBSCRIPTIONS = 'subscriptions',
STREAMLIT_APPS = 'streamlit_apps',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f3eeefefb95e..d2ddf7fcbe1a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -694,6 +694,9 @@ importers:
'@posthog/products-replay':
specifier: workspace:*
version: link:../products/replay
+ '@posthog/products-replay-vision':
+ specifier: workspace:*
+ version: link:../products/replay_vision
'@posthog/products-revenue-analytics':
specifier: workspace:*
version: link:../products/revenue_analytics
@@ -3143,7 +3146,32 @@ importers:
specifier: 18.3.1
version: 18.3.1
- products/replay_vision: {}
+ products/replay_vision:
+ dependencies:
+ '@posthog/icons':
+ specifier: '*'
+ '@posthog/lemon-ui':
+ specifier: '*'
+ '@types/react':
+ specifier: 18.3.27
+ version: 18.3.27
+ kea:
+ specifier: 'catalog:'
+ version: 4.0.0-pre.5([email protected])
+ kea-forms:
+ specifier: 'catalog:'
+ kea-router:
+ specifier: 'catalog:'
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
+ typescript:
+ specifier: 5.9.3
+ version: 5.9.3
products/revenue_analytics:
dependencies:
diff --git a/posthog/schema.py b/posthog/schema.py
index 84404e299eab..613870e56154 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -2228,6 +2228,7 @@ class FileSystemIconType(StrEnum):
ERROR_TRACKING = "error_tracking"
HEATMAP = "heatmap"
SESSION_REPLAY = "session_replay"
+ REPLAY_VISION = "replay_vision"
SESSION_PROFILE = "session_profile"
SURVEY = "survey"
PRODUCT_TOUR = "product_tour"
@@ -3856,6 +3857,7 @@ class ProductKey(StrEnum):
PRODUCT_TOURS = "product_tours"
REVENUE_ANALYTICS = "revenue_analytics"
SESSION_REPLAY = "session_replay"
+ REPLAY_VISION = "replay_vision"
SITE_APPS = "site_apps"
SUBSCRIPTIONS = "subscriptions"
STREAMLIT_APPS = "streamlit_apps"
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.py
index f2c9e64fd2a3..49e63102b908 100644
--- a/posthog/session_recordings/queries/session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py
@@ -32,6 +32,7 @@ from posthog.session_recordings.queries.utils import (
UnexpectedQueryProperties,
_strip_person_and_event_and_cohort_properties,
expand_test_account_filters,
+ is_session_property,
)
from posthog.types import AnyPropertyFilter
@@ -374,6 +375,13 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
)
)
+ # Session-scoped properties (e.g. $entry_utm_source) join to the sessions table
+ # via property_to_expr's "replay" scope. They're stripped from `remaining_properties`
+ # below to avoid the UnexpectedQueryProperties exception, so handle them here.
+ session_properties = [p for p in (self._query.properties or []) if is_session_property(p)]
+ if session_properties:
+ optional_exprs.append(property_to_expr(session_properties, team=self._team, scope="replay"))
+
remaining_properties = _strip_person_and_event_and_cohort_properties(self._query.properties)
if remaining_properties:
capture_exception(UnexpectedQueryProperties(remaining_properties))
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
index b5bd9933b9f6..d9ebc2d9f3f8 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
@@ -4354,6 +4354,29 @@ class TestClickhouseSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseT
def tearDown(self) -> None:
sync_execute(TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL())
+ def test_session_property_filter_is_applied_to_query(self) -> None:
+ # Regression test for the cross-sell flow: web analytics opens session replay
+ # with a session-scoped UTM filter, which previously got stripped from the
+ # recordings query and silently returned all sessions.
+ query = RecordingsQuery.model_validate(
+ {
+ "properties": [
+ {
+ "key": "$entry_utm_source",
+ "value": ["google"],
+ "operator": "exact",
+ "type": "session",
+ }
+ ]
+ },
+ )
+ session_recording_list_instance = SessionRecordingListFromQuery(
+ query=query, team=self.team, hogql_query_modifiers=None
+ )
+ printed_query = self._print_query(session_recording_list_instance.get_query())
+
+ assert "entry_utm_source" in printed_query
+
@property
def base_time(self):
return (now() - relativedelta(hours=1)).replace(microsecond=0, second=0)
diff --git a/products/replay_vision/frontend/replay_lenses/ReplayLens.tsx b/products/replay_vision/frontend/replay_lenses/ReplayLens.tsx
new file mode 100644
index 000000000000..8a540fbd97dc
--- /dev/null
+++ b/products/replay_vision/frontend/replay_lenses/ReplayLens.tsx
@@ -0,0 +1,193 @@
+import { useActions, useValues } from 'kea'
+import { Field, Form } from 'kea-forms'
+
+import {
+ LemonBanner,
+ LemonButton,
+ LemonInput,
+ LemonSelect,
+ LemonSwitch,
+ LemonTab,
+ LemonTabs,
+ LemonTextArea,
+} from '@posthog/lemon-ui'
+
+import { AccessControlAction } from 'lib/components/AccessControlAction'
+import { More } from 'lib/lemon-ui/LemonButton/More'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
+import { SceneExport } from 'scenes/sceneTypes'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { ProductKey } from '~/queries/schema/schema-general'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import { LensObservationsTable } from './components/LensObservationsTable'
+import { LensTriggers } from './components/LensTriggers'
+import { LensTypeConfigEditor } from './components/LensTypeConfigEditor'
+import { replayLensLogic } from './replayLensLogic'
+import { ReplayLensSceneLogicProps, replayLensSceneLogic } from './replayLensSceneLogic'
+import { EditorTab, LENS_TYPE_OPTIONS, MODEL_OPTIONS } from './types'
+
+export const scene: SceneExport<ReplayLensSceneLogicProps> = {
+ component: ReplayLensSceneComponent,
+ logic: replayLensSceneLogic,
+ productKey: ProductKey.REPLAY_VISION,
+}
+
+export function ReplayLensSceneComponent({ tabId }: { tabId: string }): JSX.Element {
+ const { lensId, activeTab } = useValues(replayLensSceneLogic)
+ const { setActiveTab } = useActions(replayLensSceneLogic)
+
+ const lensLogic = replayLensLogic({ id: lensId, tabId })
+ useAttachedLogic(lensLogic, replayLensSceneLogic)
+
+ const { lens, originalLens, lensLoading, isLensSubmitting, hasUnsavedChanges, isNew } = useValues(lensLogic)
+ const { setLensType, submitLens, resetLens, deleteLens } = useActions(lensLogic)
+
+ if (lensLoading || !lens) {
+ return (
+ <SceneContent>
+ <SceneTitleSection name="Loading…" resourceType={{ type: 'replay_vision' }} />
+ </SceneContent>
+ )
+ }
+
+ const tabs: (LemonTab<EditorTab> | false)[] = [
+ {
+ key: 'configuration',
+ label: 'Configuration',
+ content: (
+ <div className="space-y-6 max-w-3xl">
+ <Field name="name" label="Name">
+ <LemonInput placeholder="e.g. Confused checkout flow" />
+ </Field>
+
+ <Field name="description" label="Description (optional)">
+ <LemonTextArea placeholder="What this lens looks for and why." minRows={2} />
+ </Field>
+
+ <Field name="lens_type" label="Lens type">
+ <LemonSelect
+ value={lens.lens_type}
+ onChange={(v) => setLensType(v)}
+ options={LENS_TYPE_OPTIONS.map((opt) => ({
+ value: opt.value,
+ label: opt.label,
+ labelInMenu: (
+ <div className="flex flex-col">
+ <span className="font-medium">{opt.label}</span>
+ <span className="text-xs text-muted">{opt.description}</span>
+ </div>
+ ),
+ }))}
+ />
+ </Field>
+
+ <LensTypeConfigEditor lensId={lensId} tabId={tabId} />
+
+ <Field name="model" label="Model">
+ <LemonSelect value={lens.model} options={MODEL_OPTIONS} />
+ </Field>
+
+ <Field name="emits_signals">
+ {({ value, onChange }) => (
+ <div className="flex items-center gap-3">
+ <LemonSwitch checked={!!value} onChange={onChange} />
+ <div>
+ <div className="text-sm font-medium">Emit PostHog Signals</div>
+ <div className="text-xs text-muted">
+ When on, the model also identifies actionable issues that feed into PostHog
+ Signals.
+ </div>
+ </div>
+ </div>
+ )}
+ </Field>
+ </div>
+ ),
+ },
+ {
+ key: 'triggers',
+ label: 'Triggers',
+ content: <LensTriggers lensId={lensId} tabId={tabId} />,
+ },
+ !isNew && {
+ key: 'observations' as EditorTab,
+ label: 'Observations',
+ content: <LensObservationsTable lensId={lensId} tabId={tabId} />,
+ },
+ ]
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name={lens.name || (isNew ? 'New lens' : 'Lens')}
+ description={lens.description}
+ resourceType={{ type: 'replay_vision' }}
+ actions={
+ <>
+ {!isNew && (
+ <More
+ size="small"
+ overlay={
+ <LemonButton
+ status="danger"
+ fullWidth
+ onClick={() =>
+ LemonDialog.open({
+ title: `Delete "${lens.name || 'Untitled lens'}"?`,
+ description: 'This cannot be undone.',
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => deleteLens(),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+ >
+ Delete
+ </LemonButton>
+ }
+ />
+ )}
+ {hasUnsavedChanges && originalLens && (
+ <LemonButton type="secondary" size="small" onClick={() => resetLens(originalLens)}>
+ Discard changes
+ </LemonButton>
+ )}
+ <AccessControlAction
+ resourceType={AccessControlResourceType.SessionRecording}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton
+ type="primary"
+ size="small"
+ disabledReason={!isNew && !hasUnsavedChanges ? 'No changes to save' : undefined}
+ loading={isLensSubmitting}
+ onClick={() => submitLens()}
+ data-attr="save-replay-lens"
+ >
+ {isNew ? 'Create' : 'Save'}
+ </LemonButton>
+ </AccessControlAction>
+ </>
+ }
+ />
+
+ {hasUnsavedChanges && !isNew && <LemonBanner type="info">You have unsaved changes.</LemonBanner>}
+
+ <Form logic={replayLensLogic} props={{ id: lensId, tabId }} formKey="lens" enableFormOnSubmit>
+ <LemonTabs
+ activeKey={activeTab}
+ onChange={(key) => setActiveTab(key as EditorTab)}
+ tabs={tabs.filter((t): t is LemonTab<EditorTab> => Boolean(t))}
+ />
+ </Form>
+ </SceneContent>
+ )
+}
+
+export default ReplayLensSceneComponent
diff --git a/products/replay_vision/frontend/replay_lenses/ReplayLensesScene.tsx b/products/replay_vision/frontend/replay_lenses/ReplayLensesScene.tsx
new file mode 100644
index 000000000000..00fd905b9b6d
--- /dev/null
+++ b/products/replay_vision/frontend/replay_lenses/ReplayLensesScene.tsx
@@ -0,0 +1,297 @@
+import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
+
+import { IconCopy, IconEye, IconPencil, IconPlus, IconSearch, IconTrash } from '@posthog/icons'
+import {
+ LemonButton,
+ LemonButtonWithDropdown,
+ LemonCheckbox,
+ LemonInput,
+ LemonSwitch,
+ LemonTable,
+ LemonTag,
+ Link,
+} from '@posthog/lemon-ui'
+
+import { AccessControlAction } from 'lib/components/AccessControlAction'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneSection } from '~/layout/scenes/components/SceneSection'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { ProductKey } from '~/queries/schema/schema-general'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import { VisionQuotaMeter } from './components/VisionQuotaMeter'
+import { replayLensesLogic } from './replayLensesLogic'
+import { ENABLED_OPTIONS, EnabledFilter, LENS_TYPE_OPTIONS, LensType, ReplayLens } from './types'
+
+const TYPE_OPTIONS: { value: LensType; label: string }[] = LENS_TYPE_OPTIONS.map(({ value, label }) => ({
+ value,
+ label,
+}))
+
+export const scene: SceneExport = {
+ component: ReplayLensesScene,
+ logic: replayLensesLogic,
+ productKey: ProductKey.REPLAY_VISION,
+}
+
+function FilterPill<T extends string>({
+ label,
+ options,
+ value,
+ onChange,
+}: {
+ label: string
+ options: { value: T; label: string }[]
+ value: T[]
+ onChange: (next: T[]) => void
+}): JSX.Element {
+ const toggle = (v: T): void => {
+ onChange(value.includes(v) ? value.filter((x) => x !== v) : [...value, v])
+ }
+ return (
+ <LemonButtonWithDropdown
+ type="secondary"
+ size="small"
+ dropdown={{
+ closeOnClickInside: false,
+ overlay: options.map((opt) => (
+ <LemonButton key={opt.value} fullWidth onClick={() => toggle(opt.value)}>
+ <LemonCheckbox checked={value.includes(opt.value)} className="pointer-events-none mr-2" />
+ {opt.label}
+ </LemonButton>
+ )),
+ }}
+ >
+ {value.length > 0 ? `${label} (${value.length})` : label}
+ </LemonButtonWithDropdown>
+ )
+}
+
+export function ReplayLensesScene(): JSX.Element {
+ const { filteredLenses, lenses, lensesLoading, search, enabledFilter, lensTypeFilter, hasActiveFilters } =
+ useValues(replayLensesLogic)
+ const {
+ loadLenses,
+ deleteLens,
+ duplicateLens,
+ toggleLensEnabled,
+ setSearch,
+ setEnabledFilter,
+ setLensTypeFilter,
+ clearFilters,
+ } = useActions(replayLensesLogic)
+ const { push } = useActions(router)
+
+ const columns: LemonTableColumns<ReplayLens> = [
+ {
+ title: 'Name',
+ key: 'name',
+ sorter: (a, b) => a.name.localeCompare(b.name),
+ render: (_, lens) => (
+ <div className="flex flex-col">
+ <Link to={urls.replayVision(lens.id)} className="font-semibold text-primary">
+ {lens.name || '(untitled)'}
+ </Link>
+ {lens.description && <div className="text-muted text-sm">{lens.description}</div>}
+ </div>
+ ),
+ },
+ {
+ title: 'Status',
+ key: 'enabled',
+ render: (_, lens) => (
+ <div className="flex items-center gap-2">
+ <AccessControlAction
+ resourceType={AccessControlResourceType.SessionRecording}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonSwitch checked={lens.enabled} onChange={() => toggleLensEnabled(lens.id)} size="small" />
+ </AccessControlAction>
+ <span className={lens.enabled ? 'text-success' : 'text-muted'}>
+ {lens.enabled ? 'Enabled' : 'Disabled'}
+ </span>
+ </div>
+ ),
+ sorter: (a, b) => Number(b.enabled) - Number(a.enabled),
+ },
+ {
+ title: 'Type',
+ key: 'lens_type',
+ render: (_, lens) => <LemonTag type="option">{lens.lens_type}</LemonTag>,
+ sorter: (a, b) => a.lens_type.localeCompare(b.lens_type),
+ },
+ {
+ title: 'Config',
+ key: 'config',
+ render: (_, lens) => (
+ <div className="max-w-md text-sm font-mono bg-bg-light border rounded px-2 py-1 truncate">
+ {lens.lens_config.prompt || '(empty)'}
+ </div>
+ ),
+ },
+ {
+ title: 'Sampling',
+ key: 'sampling',
+ render: (_, lens) => (
+ <span className="text-sm tabular-nums">
+ {(lens.sampling_rate * 100).toFixed(lens.sampling_rate < 0.1 ? 2 : 1)}%
+ </span>
+ ),
+ sorter: (a, b) => a.sampling_rate - b.sampling_rate,
+ },
+ {
+ title: 'Actions',
+ key: 'actions',
+ render: (_, lens) => (
+ <div className="flex gap-1">
+ <AccessControlAction
+ resourceType={AccessControlResourceType.SessionRecording}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconPencil />}
+ onClick={() => push(urls.replayVision(lens.id))}
+ tooltip="Edit"
+ />
+ </AccessControlAction>
+ <AccessControlAction
+ resourceType={AccessControlResourceType.SessionRecording}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconCopy />}
+ onClick={() => duplicateLens(lens.id)}
+ tooltip="Duplicate"
+ />
+ </AccessControlAction>
+ <AccessControlAction
+ resourceType={AccessControlResourceType.SessionRecording}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton
+ size="small"
+ type="secondary"
+ status="danger"
+ icon={<IconTrash />}
+ onClick={() =>
+ LemonDialog.open({
+ title: `Delete "${lens.name || 'Untitled lens'}"?`,
+ description: 'This cannot be undone.',
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => deleteLens(lens.id),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+ tooltip="Delete"
+ />
+ </AccessControlAction>
+ </div>
+ ),
+ },
+ ]
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name="Replay vision"
+ description="Configure named lenses that PostHog applies to completed session recordings. Results land as queryable events."
+ resourceType={{ type: 'replay_vision' }}
+ />
+
+ <VisionQuotaMeter />
+
+ <SceneSection
+ title="Lenses"
+ actions={
+ <AccessControlAction
+ resourceType={AccessControlResourceType.SessionRecording}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton
+ type="primary"
+ icon={<IconPlus />}
+ onClick={() => push(urls.replayVision('new'))}
+ data-attr="create-replay-lens"
+ >
+ New lens
+ </LemonButton>
+ </AccessControlAction>
+ }
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonInput
+ type="search"
+ placeholder="Search lenses..."
+ value={search}
+ onChange={setSearch}
+ prefix={<IconSearch />}
+ className="max-w-sm"
+ />
+ <FilterPill<EnabledFilter>
+ label="Status"
+ options={ENABLED_OPTIONS}
+ value={enabledFilter}
+ onChange={setEnabledFilter}
+ />
+ <FilterPill<LensType>
+ label="Type"
+ options={TYPE_OPTIONS}
+ value={lensTypeFilter}
+ onChange={setLensTypeFilter}
+ />
+ {hasActiveFilters && (
+ <LemonButton type="tertiary" size="small" onClick={() => clearFilters()}>
+ Clear filters
+ </LemonButton>
+ )}
+ <div className="ml-auto">
+ <LemonButton type="secondary" onClick={() => loadLenses()} size="small">
+ Refresh
+ </LemonButton>
+ </div>
+ </div>
+
+ <LemonTable
+ columns={columns}
+ dataSource={filteredLenses}
+ loading={lensesLoading}
+ rowKey="id"
+ pagination={{ pageSize: 50 }}
+ nouns={['lens', 'lenses']}
+ emptyState={
+ lenses.length === 0 ? (
+ <div className="flex flex-col items-center gap-3 p-8 text-center">
+ <IconEye className="text-3xl text-muted" />
+ <div className="text-muted">No lenses yet.</div>
+ <LemonButton
+ type="primary"
+ icon={<IconPlus />}
+ onClick={() => push(urls.replayVision('new'))}
+ >
+ Create your first lens
+ </LemonButton>
+ </div>
+ ) : (
+ <span className="text-muted">No lenses match your filters.</span>
+ )
+ }
+ />
+ </SceneSection>
+ </SceneContent>
+ )
+}
+
+export default ReplayLensesScene
diff --git a/products/replay_vision/frontend/replay_lenses/components/LensObservationsTable.tsx b/products/replay_vision/frontend/replay_lenses/components/LensObservationsTable.tsx
new file mode 100644
index 000000000000..ebd4849ae598
--- /dev/null
+++ b/products/replay_vision/frontend/replay_lenses/components/LensObservationsTable.tsx
@@ -0,0 +1,234 @@
+import { useActions, useValues } from 'kea'
+
+import { IconRefresh, IconWarning } from '@posthog/icons'
+import { LemonButton, LemonTable, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { urls } from 'scenes/urls'
+
+import { replayLensLogic } from '../replayLensLogic'
+import { LensType, ObservationStatus, ReplayObservation } from '../types'
+
+function StatusTag({ status }: { status: ObservationStatus }): JSX.Element {
+ if (status === 'succeeded') {
+ return <LemonTag type="success">Succeeded</LemonTag>
+ }
+ if (status === 'failed') {
+ return <LemonTag type="danger">Failed</LemonTag>
+ }
+ if (status === 'running') {
+ return (
+ <LemonTag type="warning">
+ <Spinner className="mr-1" /> Running
+ </LemonTag>
+ )
+ }
+ return <LemonTag type="default">Pending</LemonTag>
+}
+
+function ResultPreview({ lensType, observation }: { lensType: LensType; observation: ReplayObservation }): JSX.Element {
+ if (observation.status === 'failed') {
+ return (
+ <Tooltip title={observation.error_reason || 'Unknown error'}>
+ <span className="inline-flex items-center gap-1 text-danger text-sm">
+ <IconWarning /> {observation.error_reason || 'Failed'}
+ </span>
+ </Tooltip>
+ )
+ }
+ if (observation.status !== 'succeeded' || !observation.result) {
+ return <span className="text-muted text-sm">—</span>
+ }
+ const r = observation.result
+ if (lensType === 'monitor') {
+ const verdict = Boolean(r.verdict)
+ return (
+ <div className="flex flex-col gap-1 max-w-md">
+ <LemonTag type={verdict ? 'success' : 'default'}>{verdict ? 'Yes' : 'No'}</LemonTag>
+ {typeof r.reasoning === 'string' && <span className="text-muted text-xs truncate">{r.reasoning}</span>}
+ </div>
+ )
+ }
+ if (lensType === 'summarizer') {
+ return (
+ <div className="flex flex-col max-w-md">
+ {typeof r.title === 'string' && <span className="font-semibold text-sm truncate">{r.title}</span>}
+ {typeof r.summary === 'string' && <span className="text-muted text-xs line-clamp-2">{r.summary}</span>}
+ </div>
+ )
+ }
+ if (lensType === 'classifier') {
+ const tags = Array.isArray(r.tags) ? (r.tags as string[]) : []
+ return (
+ <div className="flex flex-wrap gap-1 max-w-md">
+ {tags.length === 0 ? (
+ <span className="text-muted text-sm">No tags</span>
+ ) : (
+ tags.map((t) => (
+ <LemonTag key={t} type="option">
+ {t}
+ </LemonTag>
+ ))
+ )}
+ </div>
+ )
+ }
+ if (lensType === 'scorer') {
+ const score = typeof r.score === 'number' ? r.score : null
+ const label = typeof r.label === 'string' ? r.label : null
+ return (
+ <div className="flex items-baseline gap-2">
+ <span className="font-semibold text-lg tabular-nums">{score ?? '—'}</span>
+ {label && <span className="text-muted text-xs">{label}</span>}
+ </div>
+ )
+ }
+ if (lensType === 'indexer') {
+ const keywords = Array.isArray(r.keywords) ? (r.keywords as string[]) : []
+ return (
+ <div className="flex flex-col max-w-md">
+ {typeof r.summary === 'string' && <span className="text-sm truncate">{r.summary}</span>}
+ {keywords.length > 0 && (
+ <div className="flex flex-wrap gap-1 mt-1">
+ {keywords.slice(0, 5).map((k) => (
+ <LemonTag key={k} type="option" size="small">
+ {k}
+ </LemonTag>
+ ))}
+ {keywords.length > 5 && <span className="text-muted text-xs">+{keywords.length - 5}</span>}
+ </div>
+ )}
+ </div>
+ )
+ }
+ return <span className="text-muted text-sm">—</span>
+}
+
+export function LensObservationsTable({ lensId, tabId }: { lensId: string; tabId: string }): JSX.Element {
+ const logic = replayLensLogic({ id: lensId, tabId })
+ const { lens, observations, observationsLoading } = useValues(logic)
+ const { loadObservations } = useActions(logic)
+
+ if (!lens) {
+ return <div className="text-muted">Loading…</div>
+ }
+
+ const stats = observations.reduce(
+ (acc, o) => {
+ acc.total += 1
+ if (o.status === 'succeeded') {
+ acc.succeeded += 1
+ } else if (o.status === 'failed') {
+ acc.failed += 1
+ } else {
+ acc.running += 1
+ }
+ return acc
+ },
+ { total: 0, succeeded: 0, failed: 0, running: 0 }
+ )
+ const successRate = stats.total > 0 ? Math.round((stats.succeeded / stats.total) * 100) : null
+
+ const columns: LemonTableColumns<ReplayObservation> = [
+ {
+ title: 'Session',
+ key: 'session',
+ render: (_, obs) => (
+ <Link to={urls.replaySingle(obs.session_id)} className="font-mono text-xs text-primary">
+ {obs.session_id.slice(0, 12)}…
+ </Link>
+ ),
+ },
+ {
+ title: 'Status',
+ key: 'status',
+ render: (_, obs) => <StatusTag status={obs.status} />,
+ },
+ {
+ title: 'Result',
+ key: 'result',
+ render: (_, obs) => <ResultPreview lensType={lens.lens_type} observation={obs} />,
+ },
+ {
+ title: 'Triggered by',
+ key: 'triggered_by',
+ render: (_, obs) => (
+ <LemonTag type={obs.triggered_by === 'on_demand' ? 'highlight' : 'default'}>
+ {obs.triggered_by === 'on_demand' ? 'On demand' : 'Schedule'}
+ </LemonTag>
+ ),
+ },
+ {
+ title: 'Model',
+ key: 'model',
+ render: (_, obs) => <span className="font-mono text-xs text-muted">{obs.model_used || '—'}</span>,
+ },
+ {
+ title: 'Created',
+ key: 'created_at',
+ render: (_, obs) => <TZLabel time={obs.created_at} />,
+ sorter: (a, b) => a.created_at.localeCompare(b.created_at),
+ },
+ ]
+
+ return (
+ <div className="space-y-4 max-w-6xl">
+ <div className="flex items-start justify-between gap-4">
+ <p className="text-muted text-sm m-0">
+ Past applications of this lens to session recordings. Each row is one observation.
+ </p>
+ <div className="flex items-center gap-4">
+ {stats.total > 0 && (
+ <div className="flex gap-4 text-sm">
+ <div className="text-center">
+ <div className="font-semibold text-lg">{stats.total}</div>
+ <div className="text-muted">Total</div>
+ </div>
+ {successRate !== null && (
+ <div className="text-center">
+ <div className="font-semibold text-lg text-success">{successRate}%</div>
+ <div className="text-muted">Success rate</div>
+ </div>
+ )}
+ {stats.failed > 0 && (
+ <div className="text-center">
+ <div className="font-semibold text-lg text-danger">{stats.failed}</div>
+ <div className="text-muted">Failed</div>
+ </div>
+ )}
+ {stats.running > 0 && (
+ <div className="text-center">
+ <div className="font-semibold text-lg">{stats.running}</div>
+ <div className="text-muted">In flight</div>
+ </div>
+ )}
+ </div>
+ )}
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconRefresh />}
+ onClick={() => loadObservations()}
+ loading={observationsLoading}
+ >
+ Refresh
+ </LemonButton>
+ </div>
+ </div>
+ <LemonTable
+ columns={columns}
+ dataSource={observations}
+ loading={observationsLoading}
+ rowKey="id"
+ pagination={{ pageSize: 50 }}
+ nouns={['observation', 'observations']}
+ emptyState={
+ <span className="text-muted">
+ No observations yet. Once this lens runs against matching recordings, results will appear here.
+ </span>
+ }
+ />
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_lenses/components/LensQuotaForecast.tsx b/products/replay_vision/frontend/replay_lenses/components/LensQuotaForecast.tsx
new file mode 100644
index 000000000000..5628f265495a
--- /dev/null
+++ b/products/replay_vision/frontend/replay_lenses/components/LensQuotaForecast.tsx
@@ -0,0 +1,47 @@
+import { useValues } from 'kea'
+
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+
+import { replayLensLogic } from '../replayLensLogic'
+
+interface Props {
+ lensId: string
+ tabId: string
+}
+
+export function LensQuotaForecast({ lensId, tabId }: Props): JSX.Element | null {
+ const { lens } = useValues(replayLensLogic({ id: lensId, tabId }))
+
+ if (!lens) {
+ return null
+ }
+
+ const samplingRatio = Math.max(0, Math.min(lens.sampling_rate, 1))
+ const samplingPercent = Math.round(samplingRatio * 1000) / 10
+ const oneInN = samplingRatio > 0 ? Math.max(1, Math.round(1 / samplingRatio)) : null
+
+ return (
+ <div className="border rounded p-3 bg-bg-light space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">Quota impact</span>
+ <span className="text-sm tabular-nums">{samplingPercent.toFixed(samplingPercent < 1 ? 2 : 1)}%</span>
+ </div>
+ <LemonProgress percent={Math.round(samplingRatio * 100)} />
+ <div className="text-xs text-muted">
+ {oneInN === null ? (
+ <span className="text-danger">Sampling is 0%. This lens will not produce any observations.</span>
+ ) : oneInN === 1 ? (
+ <>
+ Every matching recording produces one observation. Each observation counts against your monthly
+ Vision quota.
+ </>
+ ) : (
+ <>
+ About <strong>1 in {oneInN.toLocaleString()}</strong> matching recordings will be observed.
+ Lower this slider to reduce monthly quota consumption; raise it for denser coverage.
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_lenses/components/LensTriggers.tsx b/products/replay_vision/frontend/replay_lenses/components/LensTriggers.tsx
new file mode 100644
index 000000000000..e0984c8233f1
--- /dev/null
+++ b/products/replay_vision/frontend/replay_lenses/components/LensTriggers.tsx
@@ -0,0 +1,109 @@
+import { useValues } from 'kea'
+import { Field } from 'kea-forms'
+
+import { LemonInput } from '@posthog/lemon-ui'
+
+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { LemonSlider } from 'lib/lemon-ui/LemonSlider'
+
+import { NodeKind, RecordingsQuery } from '~/queries/schema/schema-general'
+import { AnyPropertyFilter } from '~/types'
+
+import { replayLensLogic } from '../replayLensLogic'
+import { LensQuotaForecast } from './LensQuotaForecast'
+
+const RECORDING_FILTER_TYPES: TaxonomicFilterGroupType[] = [
+ TaxonomicFilterGroupType.PersonProperties,
+ TaxonomicFilterGroupType.SessionProperties,
+ TaxonomicFilterGroupType.Cohorts,
+ TaxonomicFilterGroupType.Events,
+]
+
+export function LensTriggers({ lensId, tabId }: { lensId: string; tabId: string }): JSX.Element {
+ const { lens } = useValues(replayLensLogic({ id: lensId, tabId }))
+
+ if (!lens) {
+ return <div className="text-muted">Loading…</div>
+ }
+
+ return (
+ <div className="space-y-6 max-w-3xl">
+ <div className="text-sm text-muted">
+ This lens runs against completed session recordings that match the filters below. Sampling controls what
+ fraction of matching sessions are observed.
+ </div>
+
+ <Field name="sampling_rate" label="Sampling">
+ {({ value, onChange }) => {
+ const ratio = typeof value === 'number' ? value : 0
+ const samplingPercent = Math.round(ratio * 1000) / 10
+ return (
+ <div className="space-y-1">
+ <div className="flex items-center gap-4 max-w-md">
+ <div className="flex-1">
+ <LemonSlider
+ value={samplingPercent}
+ onChange={(v) => onChange(v / 100)}
+ min={0.1}
+ max={100}
+ step={0.1}
+ />
+ </div>
+ <div className="w-24">
+ <LemonInput
+ type="number"
+ value={samplingPercent}
+ onChange={(v) => onChange((Number(v) || 0) / 100)}
+ min={0.1}
+ max={100}
+ step={0.1}
+ suffix={<span>%</span>}
+ status={samplingPercent === 0 ? 'danger' : undefined}
+ />
+ </div>
+ </div>
+ <div className="text-xs text-muted">
+ Each observation counts against your monthly Vision quota. A lens that matches 1,000
+ sessions per day at 10% sampling produces ~100 observations per day.
+ </div>
+ </div>
+ )
+ }}
+ </Field>
+
+ <Field name="query" label="Recording filters">
+ {({ value, onChange }) => {
+ const query = value as RecordingsQuery | null
+ const properties = query?.properties ?? []
+ const updateProperties = (next: AnyPropertyFilter[]): void => {
+ onChange({
+ kind: NodeKind.RecordingsQuery,
+ ...query,
+ properties: next,
+ })
+ }
+ return (
+ <div className="space-y-2">
+ <div className="text-sm text-muted">
+ Filter by person, session, cohort, or event properties to target specific recordings.
+ Leave empty to apply this lens to all completed recordings.
+ </div>
+ <PropertyFilters
+ propertyFilters={properties}
+ onChange={updateProperties}
+ pageKey={`replay-lens-${lens.id}-properties`}
+ taxonomicGroupTypes={RECORDING_FILTER_TYPES}
+ addText="Add filter"
+ hasRowOperator={false}
+ sendAllKeyUpdates
+ />
+ </div>
+ )
+ }}
+ </Field>
+
+ <LensQuotaForecast lensId={lensId} tabId={tabId} />
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_lenses/components/LensTypeConfigEditor.tsx b/products/replay_vision/frontend/replay_lenses/components/LensTypeConfigEditor.tsx
new file mode 100644
index 000000000000..b0731e9426e6
--- /dev/null
+++ b/products/replay_vision/frontend/replay_lenses/components/LensTypeConfigEditor.tsx
@@ -0,0 +1,147 @@
+import { useValues } from 'kea'
+import { Field } from 'kea-forms'
+
+import { LemonInput, LemonSegmentedButton, LemonSwitch, LemonTextArea } from '@posthog/lemon-ui'
+
+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
+
+import { replayLensLogic } from '../replayLensLogic'
+import { SummarizerLensConfig } from '../types'
+
+const SUMMARIZER_LENGTH_OPTIONS: { value: SummarizerLensConfig['length']; label: string }[] = [
+ { value: 'short', label: 'Short (1-2 sentences)' },
+ { value: 'medium', label: 'Medium (1 paragraph)' },
+ { value: 'long', label: 'Long (3-5 paragraphs)' },
+]
+
+export function LensTypeConfigEditor({ lensId, tabId }: { lensId: string; tabId: string }): JSX.Element {
+ const { lens } = useValues(replayLensLogic({ id: lensId, tabId }))
+
+ if (!lens) {
+ return <div className="text-muted">Loading…</div>
+ }
+
+ if (lens.lens_type === 'summarizer') {
+ return (
+ <div className="space-y-4">
+ <Field name="lens_config.prompt" label="Prompt">
+ <LemonTextArea
+ placeholder="Summarize what the user did, focusing on their goal and any obstacles they hit."
+ minRows={6}
+ />
+ </Field>
+ <Field name="lens_config.length" label="Summary length">
+ <LemonSegmentedButton options={SUMMARIZER_LENGTH_OPTIONS} />
+ </Field>
+ </div>
+ )
+ }
+
+ if (lens.lens_type === 'monitor') {
+ return (
+ <Field name="lens_config.prompt" label="Prompt">
+ <LemonTextArea
+ placeholder="Did the user encounter a payment failure? Answer yes or no with a one-sentence reason."
+ minRows={6}
+ />
+ </Field>
+ )
+ }
+
+ if (lens.lens_type === 'classifier') {
+ return (
+ <div className="space-y-4">
+ <Field name="lens_config.prompt" label="Prompt">
+ <LemonTextArea placeholder="Categorize this session by its primary user intent." minRows={6} />
+ </Field>
+ <Field name="lens_config.tags" label="Tag vocabulary">
+ {({ value, onChange }) => (
+ <LemonInputSelect
+ mode="multiple"
+ allowCustomValues
+ placeholder="Type a tag and press enter..."
+ value={(value as string[]) ?? []}
+ onChange={onChange}
+ options={((value as string[]) ?? []).map((t) => ({ key: t, label: t }))}
+ />
+ )}
+ </Field>
+ <Field name="lens_config.multi_label">
+ {({ value, onChange }) => (
+ <div className="flex items-center gap-2">
+ <LemonSwitch checked={!!value} onChange={onChange} />
+ <div>
+ <div className="text-sm font-medium">Allow multiple tags per session</div>
+ <div className="text-xs text-muted">
+ When off, the model picks exactly one tag. When on, it can pick zero or more.
+ </div>
+ </div>
+ </div>
+ )}
+ </Field>
+ </div>
+ )
+ }
+
+ if (lens.lens_type === 'scorer') {
+ return (
+ <div className="space-y-4">
+ <Field name="lens_config.prompt" label="Prompt">
+ <LemonTextArea
+ placeholder="Rate how frustrated the user appeared during this session."
+ minRows={6}
+ />
+ </Field>
+ <Field name="lens_config.scale">
+ {({ value, onChange, error }) => {
+ const scale = (value as { min: number; max: number; label?: string }) ?? { min: 0, max: 10 }
+ return (
+ <div className="space-y-3">
+ <div className="space-y-1">
+ <label className="block text-sm font-medium">Scale</label>
+ <div className="flex items-center gap-3 max-w-md">
+ <LemonInput
+ type="number"
+ value={scale.min}
+ onChange={(v) => onChange({ ...scale, min: Number(v) || 0 })}
+ prefix={<span className="text-muted text-xs">min</span>}
+ />
+ <span className="text-muted">to</span>
+ <LemonInput
+ type="number"
+ value={scale.max}
+ onChange={(v) => onChange({ ...scale, max: Number(v) || 0 })}
+ prefix={<span className="text-muted text-xs">max</span>}
+ />
+ </div>
+ {error && <div className="text-xs text-danger">{error}</div>}
+ </div>
+ <div className="space-y-1">
+ <label className="block text-sm font-medium">Score label (optional)</label>
+ <LemonInput
+ value={scale.label ?? ''}
+ onChange={(v) => onChange({ ...scale, label: v || undefined })}
+ placeholder="frustration"
+ />
+ </div>
+ </div>
+ )
+ }}
+ </Field>
+ </div>
+ )
+ }
+
+ if (lens.lens_type === 'indexer') {
+ return (
+ <Field name="lens_config.prompt" label="Prompt">
+ <LemonTextArea
+ placeholder="Focus on the user's actions and goals. Ignore loading screens and animation noise."
+ minRows={6}
+ />
+ </Field>
+ )
+ }
+
+ return <div className="text-muted text-sm">Unsupported lens type.</div>
+}
diff --git a/products/replay_vision/frontend/replay_lenses/components/VisionQuotaMeter.tsx b/products/replay_vision/frontend/replay_lenses/components/VisionQuotaMeter.tsx
new file mode 100644
index 000000000000..cdd7a978e474
--- /dev/null
+++ b/products/replay_vision/frontend/replay_lenses/components/VisionQuotaMeter.tsx
@@ -0,0 +1,82 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonSegmentedButton, Tooltip } from '@posthog/lemon-ui'
+
+import { Sparkline } from 'lib/components/Sparkline'
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+
+import { replayLensesLogic } from '../replayLensesLogic'
+
+const RANGE_OPTIONS: { value: 7 | 30 | 90; label: string }[] = [
+ { value: 7, label: '7 days' },
+ { value: 30, label: '30 days' },
+ { value: 90, label: '90 days' },
+]
+
+export function VisionQuotaMeter(): JSX.Element | null {
+ const { quota, usageRangeDays } = useValues(replayLensesLogic)
+ const { setUsageRangeDays } = useActions(replayLensesLogic)
+
+ if (!quota) {
+ return null
+ }
+
+ const ratio = quota.limit > 0 ? Math.min(quota.used / quota.limit, 1) : 0
+ const percent = Math.round(ratio * 100)
+ const remaining = Math.max(quota.limit - quota.used, 0)
+ const strokeColor = ratio >= 1 ? 'var(--danger)' : ratio >= 0.8 ? 'var(--warning)' : 'var(--success)'
+
+ const policyCopy =
+ quota.policy === 'block'
+ ? 'Schedules pause when this quota is reached.'
+ : 'Observations beyond the quota accrue against your usage-based meter.'
+
+ const history = quota.usage_history ?? []
+ const slice = history.slice(-usageRangeDays)
+ const sparklineData = slice.map((p) => p.count)
+ const sparklineLabels = slice.map((p) => p.date)
+ const rangeTotal = slice.reduce((sum, p) => sum + p.count, 0)
+
+ return (
+ <div className="border rounded p-3 bg-bg-light space-y-3">
+ <div className="space-y-1">
+ <div className="flex items-center justify-between">
+ <Tooltip title={policyCopy}>
+ <span className="text-sm font-medium">Vision observations this month</span>
+ </Tooltip>
+ <span className="text-sm tabular-nums">
+ {quota.used.toLocaleString()} / {quota.limit.toLocaleString()}
+ </span>
+ </div>
+ <LemonProgress percent={percent} strokeColor={strokeColor} />
+ <div className="text-xs text-muted">
+ {ratio >= 1 ? (
+ <span className="text-danger">Quota reached.</span>
+ ) : (
+ <>{remaining.toLocaleString()} remaining</>
+ )}
+ <span className="mx-1">·</span>
+ <span>{quota.policy === 'block' ? 'Block on overage' : 'Usage-based overage'}</span>
+ </div>
+ </div>
+ {sparklineData.length > 0 && (
+ <div>
+ <div className="flex items-center justify-between mb-1">
+ <div className="text-xs text-muted">
+ Observations per day
+ <span className="mx-1">·</span>
+ <span className="tabular-nums">{rangeTotal.toLocaleString()} in range</span>
+ </div>
+ <LemonSegmentedButton
+ size="xsmall"
+ value={usageRangeDays}
+ onChange={(value) => setUsageRangeDays(value)}
+ options={RANGE_OPTIONS}
+ />
+ </div>
+ <Sparkline data={sparklineData} labels={sparklineLabels} type="bar" className="h-12 w-full" />
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_lenses/replayLensLogic.ts b/products/replay_vision/frontend/replay_lenses/replayLensLogic.ts
new file mode 100644
index 000000000000..7102b434bf1c
--- /dev/null
+++ b/products/replay_vision/frontend/replay_lenses/replayLensLogic.ts
@@ -0,0 +1,254 @@
+import { actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { forms } from 'kea-forms'
+import { router } from 'kea-router'
+
+import { dayjs } from 'lib/dayjs'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { objectsEqual } from 'lib/utils'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { NodeKind } from '~/queries/schema/schema-general'
+
+import {
+ visionLensesCreate,
+ visionLensesDestroy,
+ visionLensesObservationsList,
+ visionLensesPartialUpdate,
+ visionLensesRetrieve,
+} from '../generated/api'
+import type { replayLensLogicType } from './replayLensLogicType'
+import {
+ DEFAULT_MODEL,
+ DEFAULT_PROVIDER,
+ LensConfig,
+ LensType,
+ ReplayLens,
+ ReplayObservation,
+ lensFromApi,
+ lensToApiBody,
+ lensToPatchedApiBody,
+ observationsFromApi,
+} from './types'
+
+export interface ReplayLensLogicProps {
+ id: string
+ tabId: string
+}
+
+function defaultConfigForType(lensType: LensType): LensConfig {
+ if (lensType === 'summarizer') {
+ return { prompt: '', length: 'medium' }
+ }
+ if (lensType === 'classifier') {
+ return { prompt: '', tags: [], multi_label: true }
+ }
+ if (lensType === 'scorer') {
+ return { prompt: '', scale: { min: 0, max: 10 } }
+ }
+ return { prompt: '' }
+}
+
+function omitQuery(lens: ReplayLens): Omit<ReplayLens, 'query'> {
+ const { query: _query, ...rest } = lens
+ return rest
+}
+
+function newLens(): ReplayLens {
+ return {
+ id: 'new',
+ name: '',
+ description: '',
+ enabled: true,
+ sampling_rate: 1,
+ query: { kind: NodeKind.RecordingsQuery },
+ provider: DEFAULT_PROVIDER,
+ model: DEFAULT_MODEL,
+ emits_signals: false,
+ lens_version: 1,
+ last_swept_at: dayjs().toISOString(),
+ created_at: dayjs().toISOString(),
+ updated_at: dayjs().toISOString(),
+ created_by: null,
+ lens_type: 'monitor',
+ lens_config: { prompt: '' },
+ }
+}
+
+export const replayLensLogic = kea<replayLensLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'replay_lenses', 'replayLensLogic']),
+ props({} as ReplayLensLogicProps),
+ key((props) => `${props.tabId}:${props.id}`),
+
+ actions({
+ loadLens: true,
+ loadLensSuccess: (lens: ReplayLens) => ({ lens }),
+ loadLensFailure: true,
+ setLensType: (lensType: LensType) => ({ lensType }),
+ loadObservations: true,
+ loadObservationsSuccess: (observations: ReplayObservation[]) => ({ observations }),
+ loadObservationsFailure: true,
+ deleteLens: true,
+ }),
+
+ forms(({ props }) => ({
+ lens: {
+ defaults: newLens(),
+ errors: (lens: ReplayLens) => {
+ const configErrors: Record<string, string | undefined> = {}
+ if (!lens.lens_config?.prompt?.trim()) {
+ configErrors.prompt = 'Prompt is required'
+ }
+ if (lens.lens_type === 'scorer') {
+ const { min, max } = lens.lens_config.scale
+ if (typeof min !== 'number' || typeof max !== 'number' || min >= max) {
+ configErrors.scale = 'Scale max must be greater than min'
+ }
+ }
+ return {
+ name: !lens.name?.trim() ? 'Name is required' : undefined,
+ sampling_rate:
+ lens.sampling_rate > 0 && lens.sampling_rate <= 1
+ ? undefined
+ : 'Sampling rate must be between 0% and 100%',
+ lens_config: Object.keys(configErrors).length > 0 ? configErrors : undefined,
+ }
+ },
+ submit: async (lens: ReplayLens) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ const body = lens.query == null ? omitQuery(lens) : lens
+ try {
+ if (props.id === 'new') {
+ const response = await visionLensesCreate(String(teamId), lensToApiBody(body))
+ router.actions.replace(urls.replayVision(response.id))
+ lemonToast.success('Lens created')
+ } else {
+ await visionLensesPartialUpdate(String(teamId), props.id, lensToPatchedApiBody(body))
+ lemonToast.success('Lens saved')
+ }
+ } catch (error) {
+ lemonToast.error(`Failed to save lens: ${String(error)}`)
+ throw error
+ }
+ },
+ },
+ })),
+
+ reducers({
+ originalLens: [
+ null as ReplayLens | null,
+ {
+ loadLensSuccess: (_, { lens }) => lens,
+ submitLensSuccess: (_, { lens }: { lens: ReplayLens }) => lens,
+ },
+ ],
+ lensLoading: [
+ false,
+ {
+ loadLens: () => true,
+ loadLensSuccess: () => false,
+ loadLensFailure: () => false,
+ },
+ ],
+ observations: [
+ [] as ReplayObservation[],
+ {
+ loadObservationsSuccess: (_, { observations }) => observations,
+ },
+ ],
+ observationsLoading: [
+ false,
+ {
+ loadObservations: () => true,
+ loadObservationsSuccess: () => false,
+ loadObservationsFailure: () => false,
+ },
+ ],
+ }),
+
+ selectors({
+ isNew: [(_, p) => [p.id], (id: string) => id === 'new'],
+ hasUnsavedChanges: [
+ (s) => [s.lens, s.originalLens],
+ (lens: ReplayLens | null, original: ReplayLens | null): boolean => {
+ if (!lens || !original) {
+ return false
+ }
+ return !objectsEqual(lens, original)
+ },
+ ],
+ }),
+
+ listeners(({ actions, props }) => ({
+ loadLens: async () => {
+ if (props.id === 'new') {
+ actions.loadLensSuccess(newLens())
+ return
+ }
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ try {
+ const response = await visionLensesRetrieve(String(teamId), props.id)
+ actions.loadLensSuccess(lensFromApi(response))
+ } catch (error) {
+ lemonToast.error(`Failed to load lens: ${String(error)}`)
+ actions.loadLensFailure()
+ router.actions.replace(urls.replayVision())
+ }
+ },
+
+ loadLensSuccess: ({ lens }) => {
+ actions.setLensValues(lens)
+ },
+
+ setLensType: ({ lensType }) => {
+ actions.setLensValues({ lens_type: lensType, lens_config: defaultConfigForType(lensType) })
+ },
+
+ deleteLens: async () => {
+ if (props.id === 'new') {
+ return
+ }
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ try {
+ await visionLensesDestroy(String(teamId), props.id)
+ lemonToast.success('Lens deleted')
+ router.actions.replace(urls.replayVision())
+ } catch (error) {
+ lemonToast.error(`Failed to delete lens: ${String(error)}`)
+ }
+ },
+
+ loadObservations: async () => {
+ if (props.id === 'new') {
+ actions.loadObservationsSuccess([])
+ return
+ }
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ try {
+ const response = await visionLensesObservationsList(String(teamId), props.id)
+ actions.loadObservationsSuccess(observationsFromApi(response.results ?? []))
+ } catch {
+ actions.loadObservationsFailure()
+ }
+ },
+ })),
+
+ afterMount(({ actions, props }) => {
+ actions.loadLens()
+ if (props.id !== 'new') {
+ actions.loadObservations()
+ }
+ }),
+])
diff --git a/products/replay_vision/frontend/replay_lenses/replayLensSceneLogic.ts b/products/replay_vision/frontend/replay_lenses/replayLensSceneLogic.ts
new file mode 100644
index 000000000000..d468122a5d5f
--- /dev/null
+++ b/products/replay_vision/frontend/replay_lenses/replayLensSceneLogic.ts
@@ -0,0 +1,87 @@
+import { actions, kea, path, props, reducers, selectors } from 'kea'
+import { router } from 'kea-router'
+
+import { tabAwareActionToUrl } from 'lib/logic/scenes/tabAwareActionToUrl'
+import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'
+import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'
+import { urls } from 'scenes/urls'
+
+import { Breadcrumb } from '~/types'
+
+import type { replayLensSceneLogicType } from './replayLensSceneLogicType'
+import { ALL_EDITOR_TABS, EditorTab } from './types'
+
+export interface ReplayLensSceneLogicProps {
+ tabId: string
+}
+
+export const replayLensSceneLogic = kea<replayLensSceneLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'replay_lenses', 'replayLensSceneLogic']),
+ props({} as ReplayLensSceneLogicProps),
+ tabAwareScene(),
+
+ actions({
+ setLensId: (lensId: string) => ({ lensId }),
+ setActiveTab: (tab: EditorTab) => ({ tab }),
+ }),
+
+ reducers({
+ lensId: [
+ 'new' as string,
+ {
+ setLensId: (_, { lensId }) => lensId,
+ },
+ ],
+ activeTab: [
+ 'configuration' as EditorTab,
+ {
+ setActiveTab: (_, { tab }) => tab,
+ },
+ ],
+ }),
+
+ selectors({
+ breadcrumbs: [
+ (s) => [s.lensId],
+ (lensId: string): Breadcrumb[] => [
+ {
+ key: 'replay-vision',
+ name: 'Replay vision',
+ path: urls.replayVision(),
+ iconType: 'replay_vision',
+ },
+ {
+ key: lensId === 'new' ? 'new-lens' : `lens-${lensId}`,
+ name: lensId === 'new' ? 'New lens' : 'Lens',
+ path: urls.replayVision(lensId),
+ },
+ ],
+ ],
+ }),
+
+ tabAwareActionToUrl(({ values }) => ({
+ setActiveTab: () => {
+ const tab = values.activeTab === 'configuration' ? undefined : values.activeTab
+ return [
+ urls.replayVision(values.lensId),
+ { ...router.values.searchParams, tab },
+ undefined,
+ { replace: true },
+ ]
+ },
+ })),
+
+ tabAwareUrlToAction(({ actions, values }) => ({
+ [urls.replayVision(':id')]: ({ id }, searchParams) => {
+ const lensId = id || 'new'
+ if (lensId !== values.lensId) {
+ actions.setLensId(lensId)
+ }
+ const raw = typeof searchParams.tab === 'string' ? searchParams.tab : ''
+ const tab: EditorTab = (ALL_EDITOR_TABS as string[]).includes(raw) ? (raw as EditorTab) : 'configuration'
+ if (tab !== values.activeTab) {
+ actions.setActiveTab(tab)
+ }
+ },
+ })),
+])
diff --git a/products/replay_vision/frontend/replay_lenses/replayLensesLogic.ts b/products/replay_vision/frontend/replay_lenses/replayLensesLogic.ts
new file mode 100644
index 000000000000..df2a7a2080e2
--- /dev/null
+++ b/products/replay_vision/frontend/replay_lenses/replayLensesLogic.ts
@@ -0,0 +1,292 @@
+import { actions, afterMount, kea, listeners, path, props, reducers, selectors } from 'kea'
+import { router } from 'kea-router'
+
+import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { tabAwareActionToUrl } from 'lib/logic/scenes/tabAwareActionToUrl'
+import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'
+import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { visionLensesCreate, visionLensesDestroy, visionLensesList, visionLensesPartialUpdate } from '../generated/api'
+import type { replayLensesLogicType } from './replayLensesLogicType'
+import {
+ ENABLED_OPTIONS,
+ EnabledFilter,
+ LENS_TYPE_OPTIONS,
+ LensType,
+ ReplayLens,
+ VisionQuota,
+ lensFromApi,
+ lensToApiBody,
+ lensesFromApi,
+} from './types'
+
+export interface ReplayLensesLogicProps {
+ tabId: string
+}
+
+const ALL_ENABLED: EnabledFilter[] = ENABLED_OPTIONS.map((o) => o.value)
+const ALL_LENS_TYPES: LensType[] = LENS_TYPE_OPTIONS.map((o) => o.value)
+
+const csv = (values: string[]): string | undefined => (values.length > 0 ? values.join(',') : undefined)
+const fromCsv = <T extends string>(value: unknown, allowed: readonly T[]): T[] => {
+ if (typeof value !== 'string' || value.length === 0) {
+ return []
+ }
+ return value
+ .split(',')
+ .map((v) => v.trim())
+ .filter((v): v is T => (allowed as readonly string[]).includes(v))
+}
+
+export const replayLensesLogic = kea<replayLensesLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'replay_lenses', 'replayLensesLogic']),
+ props({} as ReplayLensesLogicProps),
+ tabAwareScene(),
+
+ actions({
+ loadLenses: true,
+ loadLensesSuccess: (lenses: ReplayLens[]) => ({ lenses }),
+ loadLensesFailure: (error: string) => ({ error }),
+ loadQuota: true,
+ loadQuotaSuccess: (quota: VisionQuota | null) => ({ quota }),
+ deleteLens: (id: string) => ({ id }),
+ deleteLensSuccess: (id: string) => ({ id }),
+ duplicateLens: (id: string) => ({ id }),
+ duplicateLensSuccess: (lens: ReplayLens) => ({ lens }),
+ toggleLensEnabled: (id: string) => ({ id }),
+ toggleLensEnabledSuccess: (id: string) => ({ id }),
+ setSearch: (search: string) => ({ search }),
+ setEnabledFilter: (values: EnabledFilter[]) => ({ values }),
+ setLensTypeFilter: (lensTypes: LensType[]) => ({ lensTypes }),
+ setUsageRangeDays: (days: 7 | 30 | 90) => ({ days }),
+ clearFilters: true,
+ }),
+
+ reducers({
+ lenses: [
+ [] as ReplayLens[],
+ {
+ loadLensesSuccess: (_, { lenses }) => lenses,
+ deleteLensSuccess: (state, { id }) => state.filter((l) => l.id !== id),
+ duplicateLensSuccess: (state, { lens }) => [...state, lens],
+ toggleLensEnabledSuccess: (state, { id }) =>
+ state.map((l) => (l.id === id ? { ...l, enabled: !l.enabled } : l)),
+ },
+ ],
+ lensesLoading: [
+ false,
+ {
+ loadLenses: () => true,
+ loadLensesSuccess: () => false,
+ loadLensesFailure: () => false,
+ },
+ ],
+ quota: [
+ null as VisionQuota | null,
+ {
+ loadQuotaSuccess: (_, { quota }) => quota,
+ },
+ ],
+ search: [
+ '',
+ {
+ setSearch: (_, { search }) => search,
+ clearFilters: () => '',
+ },
+ ],
+ enabledFilter: [
+ [] as EnabledFilter[],
+ {
+ setEnabledFilter: (_, { values }) => values,
+ clearFilters: () => [],
+ },
+ ],
+ lensTypeFilter: [
+ [] as LensType[],
+ {
+ setLensTypeFilter: (_, { lensTypes }) => lensTypes,
+ clearFilters: () => [],
+ },
+ ],
+ usageRangeDays: [
+ 30 as 7 | 30 | 90,
+ {
+ setUsageRangeDays: (_, { days }) => days,
+ },
+ ],
+ }),
+
+ listeners(({ actions, values }) => ({
+ loadLenses: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ try {
+ const response = await visionLensesList(String(teamId))
+ actions.loadLensesSuccess(lensesFromApi(response.results ?? []))
+ } catch (error) {
+ lemonToast.error(`Failed to load lenses: ${String(error)}`)
+ actions.loadLensesFailure(String(error))
+ }
+ },
+
+ loadQuota: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ try {
+ // nosemgrep: prefer-codegen-api
+ const response = await api.get(`/api/environments/${teamId}/vision/quota/`)
+ actions.loadQuotaSuccess(response)
+ } catch {
+ actions.loadQuotaSuccess(null)
+ }
+ },
+
+ deleteLens: async ({ id }) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ try {
+ await visionLensesDestroy(String(teamId), id)
+ actions.deleteLensSuccess(id)
+ lemonToast.success('Lens deleted')
+ } catch (error) {
+ lemonToast.error(`Failed to delete lens: ${String(error)}`)
+ }
+ },
+
+ duplicateLens: async ({ id }) => {
+ const original = values.lenses.find((l) => l.id === id)
+ if (!original) {
+ return
+ }
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ const duplicate: Record<string, unknown> = {
+ name: `${original.name} (Copy)`,
+ description: original.description,
+ enabled: false,
+ lens_type: original.lens_type,
+ lens_config: original.lens_config,
+ sampling_rate: original.sampling_rate,
+ provider: original.provider,
+ model: original.model,
+ emits_signals: original.emits_signals,
+ }
+ if (original.query != null) {
+ duplicate.query = original.query
+ }
+ try {
+ const response = await visionLensesCreate(String(teamId), lensToApiBody(duplicate))
+ actions.duplicateLensSuccess(lensFromApi(response))
+ } catch (error) {
+ lemonToast.error(`Failed to duplicate lens: ${String(error)}`)
+ }
+ },
+
+ toggleLensEnabled: async ({ id }) => {
+ const lens = values.lenses.find((l) => l.id === id)
+ if (!lens) {
+ return
+ }
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ try {
+ await visionLensesPartialUpdate(String(teamId), id, { enabled: !lens.enabled })
+ actions.toggleLensEnabledSuccess(id)
+ } catch (error) {
+ lemonToast.error(`Failed to ${lens.enabled ? 'disable' : 'enable'} lens: ${String(error)}`)
+ }
+ },
+ })),
+
+ selectors({
+ hasActiveFilters: [
+ (s) => [s.search, s.enabledFilter, s.lensTypeFilter],
+ (search: string, enabled: EnabledFilter[], lensTypes: LensType[]) =>
+ search.trim().length > 0 || enabled.length > 0 || lensTypes.length > 0,
+ ],
+ filteredLenses: [
+ (s) => [s.lenses, s.search, s.enabledFilter, s.lensTypeFilter],
+ (
+ lenses: ReplayLens[],
+ search: string,
+ enabledValues: EnabledFilter[],
+ lensTypes: LensType[]
+ ): ReplayLens[] => {
+ const q = search.trim().toLowerCase()
+ return lenses.filter((l) => {
+ if (q) {
+ const haystack = [l.name, l.description ?? '', l.lens_config.prompt].join(' ').toLowerCase()
+ if (!haystack.includes(q)) {
+ return false
+ }
+ }
+ if (enabledValues.length > 0) {
+ const visible: EnabledFilter = l.enabled ? 'enabled' : 'disabled'
+ if (!enabledValues.includes(visible)) {
+ return false
+ }
+ }
+ if (lensTypes.length > 0 && !lensTypes.includes(l.lens_type)) {
+ return false
+ }
+ return true
+ })
+ },
+ ],
+ }),
+
+ tabAwareActionToUrl(({ values }) => {
+ const buildUrl = (): [string, Record<string, string | undefined>, undefined, { replace: true }] => [
+ urls.replayVision(),
+ {
+ ...router.values.searchParams,
+ search: values.search || undefined,
+ enabled: csv(values.enabledFilter),
+ type: csv(values.lensTypeFilter),
+ },
+ undefined,
+ { replace: true },
+ ]
+ return {
+ setSearch: buildUrl,
+ setEnabledFilter: buildUrl,
+ setLensTypeFilter: buildUrl,
+ clearFilters: buildUrl,
+ }
+ }),
+
+ tabAwareUrlToAction(({ actions, values }) => ({
+ [urls.replayVision()]: (_, searchParams) => {
+ const search = typeof searchParams.search === 'string' ? searchParams.search : ''
+ if (search !== values.search) {
+ actions.setSearch(search)
+ }
+ const enabledValues = fromCsv<EnabledFilter>(searchParams.enabled, ALL_ENABLED)
+ if (csv(enabledValues) !== csv(values.enabledFilter)) {
+ actions.setEnabledFilter(enabledValues)
+ }
+ const types = fromCsv<LensType>(searchParams.type, ALL_LENS_TYPES)
+ if (csv(types) !== csv(values.lensTypeFilter)) {
+ actions.setLensTypeFilter(types)
+ }
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadLenses()
+ actions.loadQuota()
+ }),
+])
diff --git a/products/replay_vision/frontend/replay_lenses/types.ts b/products/replay_vision/frontend/replay_lenses/types.ts
new file mode 100644
index 000000000000..9a281a942f60
--- /dev/null
+++ b/products/replay_vision/frontend/replay_lenses/types.ts
@@ -0,0 +1,186 @@
+import { RecordingsQuery } from '~/queries/schema/schema-general'
+
+import type { PatchedReplayLensApi, ReplayLensApi, ReplayObservationApi } from '../generated/api.schemas'
+
+export type LensType = 'monitor' | 'classifier' | 'scorer' | 'summarizer' | 'indexer'
+
+export type EnabledFilter = 'enabled' | 'disabled'
+
+export type ObservationStatus = 'pending' | 'running' | 'succeeded' | 'failed'
+
+export const DEFAULT_PROVIDER = 'google'
+export const DEFAULT_MODEL = 'gemini-3-flash'
+
+export const ENABLED_OPTIONS: { value: EnabledFilter; label: string }[] = [
+ { value: 'enabled', label: 'Enabled' },
+ { value: 'disabled', label: 'Disabled' },
+]
+
+export const MODEL_OPTIONS: { value: string; label: string }[] = [
+ { value: 'gemini-3-flash', label: 'Gemini 3 Flash' },
+ { value: 'gemini-3-flash-lite', label: 'Gemini 3 Flash Lite' },
+]
+
+export const LENS_TYPE_OPTIONS: { value: LensType; label: string; description: string }[] = [
+ {
+ value: 'monitor',
+ label: 'Monitor',
+ description: 'Detects whether a specific condition occurred in the session.',
+ },
+ {
+ value: 'summarizer',
+ label: 'Summarizer',
+ description: 'Produces a title and a text summary of what happened in the session.',
+ },
+ {
+ value: 'classifier',
+ label: 'Classifier',
+ description: 'Tags the session with one or more categories from a fixed vocabulary.',
+ },
+ {
+ value: 'scorer',
+ label: 'Scorer',
+ description: 'Scores the session on a configurable numeric scale.',
+ },
+ {
+ value: 'indexer',
+ label: 'Indexer',
+ description: 'Generates semantic embeddings of the session for free-text search.',
+ },
+]
+
+export type EditorTab = 'configuration' | 'triggers' | 'observations'
+
+export const ALL_EDITOR_TABS: EditorTab[] = ['configuration', 'triggers', 'observations']
+
+export interface MonitorLensConfig {
+ prompt: string
+}
+
+export interface SummarizerLensConfig {
+ prompt: string
+ length: 'short' | 'medium' | 'long'
+}
+
+export interface ClassifierLensConfig {
+ prompt: string
+ tags: string[]
+ multi_label: boolean
+}
+
+export interface ScorerLensConfig {
+ prompt: string
+ scale: { min: number; max: number; label?: string }
+}
+
+export interface IndexerLensConfig {
+ prompt: string
+}
+
+export type LensConfig =
+ | MonitorLensConfig
+ | SummarizerLensConfig
+ | ClassifierLensConfig
+ | ScorerLensConfig
+ | IndexerLensConfig
+
+export interface BaseReplayLens {
+ id: string
+ name: string
+ description?: string
+ enabled: boolean
+ sampling_rate: number
+ query: RecordingsQuery | null
+ provider: string
+ model: string
+ emits_signals: boolean
+ lens_version: number
+ last_swept_at: string
+ created_at: string
+ updated_at: string
+ created_by: { id: number; first_name: string; last_name?: string; email?: string } | null
+ deleted?: boolean
+}
+
+export interface MonitorLens extends BaseReplayLens {
+ lens_type: 'monitor'
+ lens_config: MonitorLensConfig
+}
+
+export interface SummarizerLens extends BaseReplayLens {
+ lens_type: 'summarizer'
+ lens_config: SummarizerLensConfig
+}
+
+export interface ClassifierLens extends BaseReplayLens {
+ lens_type: 'classifier'
+ lens_config: ClassifierLensConfig
+}
+
+export interface ScorerLens extends BaseReplayLens {
+ lens_type: 'scorer'
+ lens_config: ScorerLensConfig
+}
+
+export interface IndexerLens extends BaseReplayLens {
+ lens_type: 'indexer'
+ lens_config: IndexerLensConfig
+}
+
+export type ReplayLens = MonitorLens | SummarizerLens | ClassifierLens | ScorerLens | IndexerLens
+
+export interface VisionUsagePoint {
+ date: string
+ count: number
+}
+
+export interface VisionQuota {
+ used: number
+ limit: number
+ policy: 'block' | 'usage_based'
+ period_start: string
+ period_end: string
+ /** Daily observation counts across the current period. Optional until the backend exposes it. */
+ usage_history?: VisionUsagePoint[]
+}
+
+// The API exposes lens_config and query as `unknown`. The client narrows them via
+// the lens_type discriminator, so conversion is contained to this single boundary.
+export function lensFromApi(api: ReplayLensApi): ReplayLens {
+ return api as unknown as ReplayLens
+}
+
+export function lensesFromApi(apis: readonly ReplayLensApi[]): ReplayLens[] {
+ return apis.map(lensFromApi)
+}
+
+export function lensToApiBody(lens: Partial<ReplayLens> | Record<string, unknown>): ReplayLensApi {
+ return lens as unknown as ReplayLensApi
+}
+
+export function lensToPatchedApiBody(lens: Partial<ReplayLens> | Record<string, unknown>): PatchedReplayLensApi {
+ return lens as unknown as PatchedReplayLensApi
+}
+
+export function observationsFromApi(apis: readonly ReplayObservationApi[]): ReplayObservation[] {
+ return apis.map((api) => api as unknown as ReplayObservation)
+}
+
+export interface ReplayObservation {
+ id: string
+ lens_id: string
+ session_id: string
+ status: ObservationStatus
+ error_reason: string
+ workflow_id: string
+ lens_version: number
+ lens_config_snapshot: Record<string, unknown>
+ model_used: string
+ provider_used: string
+ triggered_by: 'schedule' | 'on_demand'
+ triggered_by_user: { id: number; first_name: string } | null
+ result: Record<string, unknown> | null
+ created_at: string
+ started_at: string | null
+ completed_at: string | null
+}
diff --git a/products/replay_vision/manifest.tsx b/products/replay_vision/manifest.tsx
index fcbc0d08e070..90fdca2196e2 100644
--- a/products/replay_vision/manifest.tsx
+++ b/products/replay_vision/manifest.tsx
@@ -1,23 +1,58 @@
-/**
- * Product manifest for replay_vision.
- *
- * Defines scenes, routes, URLs, and navigation for this product.
- */
-import { ProductManifest } from '../../frontend/src/types'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { urls } from 'scenes/urls'
+
+import { FileSystemIconType, ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'
+
+import { FileSystemIconColor, ProductManifest } from '../../frontend/src/types'
export const manifest: ProductManifest = {
name: 'ReplayVision',
scenes: {
- // Define scenes here
+ ReplayVision: {
+ name: 'Replay vision',
+ import: () => import('./frontend/replay_lenses/ReplayLensesScene'),
+ projectBased: true,
+ description:
+ 'Configure named lenses that PostHog applies to completed session recordings. Results land as queryable events.',
+ iconType: 'replay_vision',
+ layout: 'app-container',
+ },
+ ReplayVisionLens: {
+ name: 'Replay vision lens',
+ import: () => import('./frontend/replay_lenses/ReplayLens'),
+ projectBased: true,
+ iconType: 'replay_vision',
+ layout: 'app-container',
+ },
},
routes: {
- // Define routes here
+ '/replay-vision': ['ReplayVision', 'replayVision'],
+ '/replay-vision/:id': ['ReplayVisionLens', 'replayVision'],
},
redirects: {},
urls: {
- // Define URL helpers here
+ replayVision:
+ /** @param id A UUID or 'new'. Omit for the lens list page. */
+ (id?: string): string => (id ? `/replay-vision/${id}` : '/replay-vision'),
},
fileSystemTypes: {},
treeItemsNew: [],
- treeItemsProducts: [],
+ treeItemsProducts: [
+ {
+ path: 'Replay vision',
+ category: ProductItemCategory.BEHAVIOR,
+ intents: [ProductKey.REPLAY_VISION],
+ type: 'replay_vision',
+ iconType: 'replay_vision' as FileSystemIconType,
+ iconColor: [
+ 'var(--color-product-session-replay-light)',
+ 'var(--color-product-session-replay-dark)',
+ ] as FileSystemIconColor,
+ href: urls.replayVision(),
+ tags: ['beta'],
+ flag: FEATURE_FLAGS.REPLAY_VISION,
+ sceneKey: 'ReplayVision',
+ sceneKeys: ['ReplayVision', 'ReplayVisionLens'],
+ },
+ ],
}
diff --git a/products/replay_vision/package.json b/products/replay_vision/package.json
index 0e3c2da8a876..ab173b2e79ae 100644
--- a/products/replay_vision/package.json
+++ b/products/replay_vision/package.json
@@ -2,5 +2,17 @@
"name": "@posthog/products-replay-vision",
"scripts": {
"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"
+ },
+ "dependencies": {
+ "kea": "catalog:",
+ "kea-forms": "catalog:",
+ "kea-router": "catalog:"
+ },
+ "peerDependencies": {
+ "@posthog/icons": "*",
+ "@posthog/lemon-ui": "*",
+ "@types/react": "*",
+ "react": "*",
+ "typescript": "*"
}
}