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.

fix(replay-vision): state what each config version changed (#74057)

Arno Hillene71a3920f29a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ec768b7724d9..46772c24cc20 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7219,17 +7219,17 @@ snapshots:
scenes-app-replay-vision--scanner-calibration--light:
hash: v1.k794b7964.a9c683734afb2c23bed4af6bbb06ff9112a21d24e14c2cd41d7feaf337c1a01a.zoB_kIb2lsCw0fPapFEvjY0_nYuancAA5u7ToyWnlQs
scenes-app-replay-vision--scanner-configuration--dark:
- hash: v1.k794b7964.743d310929077c6f9536dfc962dce2f27df811003c65cc516fd17d8f0b5eeecd.aW0-0vZESyFTHDpkkwh-h9qMuBPV_vSckCJPimIcCw0
+ hash: v1.k794b7964.c77594e83f7c7ef19638baf76277c9f744ef7ee375a9793f8a0373cfa52f1b18.rR2jerhahs-q8Bhq1djYA2ZENUnMiqWbNHtmxZRdaS0
scenes-app-replay-vision--scanner-configuration--light:
- hash: v1.k794b7964.1206162998fff84813f6229193f0b899b1dd6070278daacf44aecc05221a93e7.ojPoX16jVxawSkCy296WSxvBu8RtOPQBH5RcaNX13hw
+ hash: v1.k794b7964.76d581830af6ecf2f4003f3a6182e6dd06fbc9ce50bc5044122ab1c9b4669780._u4rb_FDHVcZVh_c6lORoMDoHa-2WDIk8tunpgJfrEs
scenes-app-replay-vision--scanner-configuration-lite-standard-pro--dark:
- hash: v1.k794b7964.c0a3d4914a3a70419b2d3017c92fd25687719eb9c4053d28943fcb038c2fec26.916jH-LwqzgTY_vnhAfCNmYbOv8PS0Q3RTgXR9SFLXU
+ hash: v1.k794b7964.2a5060c282a0ce36215998686f26a9c80d05f324158bb77c393d7a1ad7ef65c7.79svu7jvDHY7FOQ9_lrYdXg7BsSV-rKG2fTgbLIBqrQ
scenes-app-replay-vision--scanner-configuration-lite-standard-pro--light:
- hash: v1.k794b7964.ae618eb4ae8f691e6ec7d1c0c479c4de7277dfc83d98339f999b1817be2da27e.lqAjIF_c2t5HcvPhVXKxo-81pzVUa48y1rr4qZgvh6E
+ hash: v1.k794b7964.129d9ae29c83fe6c83f4cadd240d7d00678d39772968239768aa256978086b1f.QEJDd_0bqhq2u2aXq9PkS0zdh0A4YeqD2v9nCXQMlWU
scenes-app-replay-vision--scanner-configuration-tier-names--dark:
- hash: v1.k794b7964.b8ac97b2eeb1809548ba38f22f3b9bcf959e05dae7c7b6ab25f0a2a9b8897cbd.zWWTm0YR8k5zyzy1jofPE4GEJrgjqxzirG5jV1PZS1I
+ hash: v1.k794b7964.a25af64ee96340a7626331ef731f91a3236ebe8a546872a7317930547ea83b69.zG_jCMVVgFfPtTq4r5uZlBMc4taGEDGAUe_QBNe6Neo
scenes-app-replay-vision--scanner-configuration-tier-names--light:
- hash: v1.k794b7964.3a61073bc17d4ebaa1699dfa71674909d94af7571d5114bd1056c053e617d4d4.OhgwYxXR--cEguOyHANN5bfVvM1zQWMH3h1ZMNkiJGA
+ hash: v1.k794b7964.991ecbf284af2423ad7f8f83f26053197e0003eefaedadad4869a1bb243d1822.309ACp4CkQCk6_Bq7Qmef93hciFy3lpOcipREBvpvE0
scenes-app-replay-vision--scanner-digests--dark:
hash: v1.k794b7964.cfb6e46fefd93430d17c650dfceeb62bc813855dd034c2a815db8559686dbeab.4iB6ZrgxCuEO7AoLgZCuqcAMX6eqMa42Fn3j6N6n5Xg
scenes-app-replay-vision--scanner-digests--light:
diff --git a/products/replay_vision/backend/api/observation_stats.py b/products/replay_vision/backend/api/observation_stats.py
index 24a17107eab6..d7132761d01a 100644
--- a/products/replay_vision/backend/api/observation_stats.py
+++ b/products/replay_vision/backend/api/observation_stats.py
@@ -10,9 +10,9 @@ from datetime import timedelta
from typing import Any, Literal, get_args
from django.db import connection
-from django.db.models import Count, Max, Min, Q, QuerySet
+from django.db.models import Count, Max, Min, Q, QuerySet, TextField
from django.db.models.fields.json import KeyTextTransform
-from django.db.models.functions import TruncDate
+from django.db.models.functions import Cast, TruncDate
from django.utils import timezone
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
@@ -114,26 +114,37 @@ def _label_day_counts(
return [{"date": row["day"], "up": row["up"], "down": row["down"]} for row in rows]
+def _parse_json_object(raw: str | None) -> dict[str, Any]:
+ """Run snapshots are a JSONB field, so a legacy row can hold anything. Non-objects read as empty
+ rather than failing the whole stats request."""
+ if not raw:
+ return {}
+ try:
+ parsed = json.loads(raw)
+ except ValueError:
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+
+
def _version_markers(queryset: QuerySet[ReplayObservation]) -> list[dict[str, Any]]:
- """Every prompt version that produced observations, with its first day, full config (from the run
- snapshot), and rating counts. All-time: charts window it client-side; the configuration overview
- shows the full history."""
+ """Every scanner version that produced observations, with its first day, the config it ran with, and
+ rating counts. All-time: charts window it client-side. The configuration overview shows the full history.
+ Fields a snapshot doesn't carry come back null, so the history can say "not recorded" instead of
+ implying nothing changed."""
rows = (
queryset.annotate(snapshot_version=KeyTextTransform("scanner_version", "scanner_snapshot"))
.exclude(snapshot_version=None)
.annotate(
day=TruncDate("created_at"),
- snapshot_prompt=KeyTextTransform("prompt", KeyTextTransform("scanner_config", "scanner_snapshot")),
- # Whole config object as JSON text, not just the prompt key, so tags/scale/etc. version too.
- snapshot_config=KeyTextTransform("scanner_config", "scanner_snapshot"),
+ # The whole snapshot, not just scanner_config, so every version-tracked field can be diffed.
+ snapshot_json=Cast("scanner_snapshot", output_field=TextField()),
)
.order_by()
.values("snapshot_version")
.annotate(
first_day=Min("day"),
- prompt=Max("snapshot_prompt"),
- # Every observation of a given version shares the same snapshot config, so Max just picks it out.
- config_json=Max("snapshot_config"),
+ # The name can change without bumping the version, so Max is a deterministic pick.
+ snapshot=Max("snapshot_json"),
up=Count("id", filter=Q(label__is_correct=True)),
down=Count("id", filter=Q(label__is_correct=False)),
# Only succeeded observations can be rated, so they are the ratable "scanned" total.
@@ -146,16 +157,22 @@ def _version_markers(queryset: QuerySet[ReplayObservation]) -> list[dict[str, An
version = int(row["snapshot_version"])
except (TypeError, ValueError):
continue
- try:
- config = json.loads(row["config_json"]) if row["config_json"] else {}
- except ValueError:
- config = {}
+ snapshot = _parse_json_object(row["snapshot"])
+ config = snapshot.get("scanner_config")
+ config = config if isinstance(config, dict) else {}
markers.append(
{
"date": row["first_day"],
"version": version,
- "prompt": row["prompt"] or "",
+ "prompt": config.get("prompt") or "",
"scanner_config": config,
+ "scanner_type": snapshot.get("scanner_type"),
+ "model": snapshot.get("model"),
+ "provider": snapshot.get("provider"),
+ "emits_signals": snapshot.get("emits_signals"),
+ "query": snapshot.get("query"),
+ "sampling_rate": snapshot.get("sampling_rate"),
+ "sampling_mode": snapshot.get("sampling_mode"),
"up": row["up"],
"down": row["down"],
"total": row["total"],
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 0b0ffaf8aabc..a48eb46ffcb7 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -359,6 +359,21 @@ class ObservationVersionMarkerSerializer(serializers.Serializer):
"allow_inconclusive, tags, scale, or length), taken from the observation run snapshots."
),
)
+ # The remaining version-tracked fields, so the history can name which one bumped a version.
+ # Null means this version's run snapshots predate recording that field.
+ scanner_type = serializers.CharField(allow_null=True, help_text="The scanner type this version ran as.")
+ model = serializers.CharField(allow_null=True, help_text="The model this version ran on.")
+ provider = serializers.CharField(allow_null=True, help_text="The provider this version ran on.")
+ emits_signals = serializers.BooleanField(allow_null=True, help_text="Whether this version emitted signals.")
+ query = serializers.JSONField(
+ allow_null=True,
+ help_text="The `RecordingsQuery` recording filters this version ran with.",
+ )
+ sampling_rate = serializers.FloatField(allow_null=True, help_text="The 0..1 downsample this version ran with.")
+ sampling_mode = serializers.CharField(
+ allow_null=True,
+ help_text="The session-coverage pre-filter this version ran with.",
+ )
up = serializers.IntegerField(help_text="Thumbs-up ratings on this version's observations.")
down = serializers.IntegerField(help_text="Thumbs-down ratings on this version's observations.")
total = serializers.IntegerField(help_text="Succeeded (ratable) observations this version produced, rated or not.")
@@ -384,8 +399,8 @@ class ObservationLabelStatsSerializer(serializers.Serializer):
version_markers = ObservationVersionMarkerSerializer(
many=True,
help_text=(
- "Each scanner (prompt) version that produced observations (all-time), with its first day, prompt, "
- "and rating counts, for chart markers and the prompt version history."
+ "Each scanner version that produced observations (all-time), with its first day, the config it ran "
+ "with, and rating counts, for chart markers and the config version history."
),
)
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 8d6907badf85..5b1a6cc5241c 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -1,3 +1,4 @@
+import json
from typing import Any, NoReturn, cast
from django.db import IntegrityError
@@ -95,8 +96,9 @@ from products.replay_vision.backend.tag_suggestions import SuggestionError, sugg
# Date is set by the schedule at trigger time, not by the user — strip on save.
_QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")
-# Size caps enforced at the write boundary; scanner_config is copied into every observation's snapshot.
+# Size caps enforced at the write boundary; scanner_config and query are copied into every observation's snapshot.
_MAX_DESCRIPTION_LENGTH = 1_000
+_MAX_QUERY_BYTES = 50_000
logger = structlog.get_logger(__name__)
@@ -482,6 +484,10 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Mode
raise serializers.ValidationError({"query": "Recording filter is invalid."})
# Persist exactly what the user sent (validated), minus the date keys the schedule controls.
attrs["query"] = {k: v for k, v in attrs["query"].items() if k not in _QUERY_FIELDS_TO_STRIP}
+ if len(json.dumps(attrs["query"], separators=(",", ":")).encode()) > _MAX_QUERY_BYTES:
+ raise serializers.ValidationError(
+ {"query": f"Recording filter is too large. Keep it under {_MAX_QUERY_BYTES // 1000} KB."}
+ )
def to_representation(self, instance: ReplayScanner) -> dict[str, Any]:
data = super().to_representation(instance)
diff --git a/products/replay_vision/backend/temporal/snapshots.py b/products/replay_vision/backend/temporal/snapshots.py
index 7216e0a5f41e..a0d30a17ff61 100644
--- a/products/replay_vision/backend/temporal/snapshots.py
+++ b/products/replay_vision/backend/temporal/snapshots.py
@@ -28,6 +28,12 @@ class ScannerSnapshot(BaseModel, frozen=True):
provider: str
emits_signals: bool
scanner_config: dict[str, Any]
+ # The remaining version-tracked fields. They never reach the LLM, but the config-versions history is
+ # rebuilt from these snapshots, so without them a version bumped by a sampling or filter change reads
+ # as "nothing changed". Optional so older rows decode as not recorded rather than as unchanged.
+ query: dict[str, Any] | None = None
+ sampling_rate: float | None = None
+ sampling_mode: str | None = None
@classmethod
def from_scanner(cls, scanner: "ReplayScanner") -> "ScannerSnapshot":
@@ -40,6 +46,9 @@ class ScannerSnapshot(BaseModel, frozen=True):
provider=scanner.provider,
emits_signals=scanner.emits_signals,
scanner_config=scanner.scanner_config,
+ query=scanner.query,
+ sampling_rate=scanner.sampling_rate,
+ sampling_mode=scanner.sampling_mode,
)
@classmethod
@@ -58,18 +67,14 @@ class BackfillScannerSnapshot(ScannerSnapshot, frozen=True):
snapshot fields plus the query/sampling inputs the candidate walk needs. Freezing both keeps the
creation-time enumeration and its cost ceiling exact for the backfill's whole lifetime."""
+ # Required here (the base records them optionally): the candidate walk cannot run without them.
query: dict[str, Any]
sampling_rate: float = Field(ge=0.0, le=1.0)
sampling_mode: str
@classmethod
def from_scanner(cls, scanner: "ReplayScanner") -> "BackfillScannerSnapshot":
- return cls(
- **ScannerSnapshot.from_scanner(scanner).model_dump(),
- query=scanner.query,
- sampling_rate=scanner.sampling_rate,
- sampling_mode=scanner.sampling_mode,
- )
+ return cls(**ScannerSnapshot.from_scanner(scanner).model_dump())
@classmethod
def load_for_backfill(cls, backfill_id: UUID, raw: dict[str, Any] | None) -> "BackfillScannerSnapshot":
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index abd791116428..ca2c87cfe0e6 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -451,7 +451,14 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
self.assertNotIn("date_to", body_query)
self.assertEqual(body_query["filter_test_accounts"], True)
- def test_create_rejects_invalid_query(self) -> None:
+ @parameterized.expand(
+ [
+ ("unknown_field", {"this_field_does_not_exist": True}),
+ # An oversized query is copied into every observation's snapshot, so it is capped on save.
+ ("oversized", {"distinct_ids": ["x" * 1_000 for _ in range(100)]}),
+ ]
+ )
+ def test_create_rejects_invalid_query(self, _name: str, query: dict) -> None:
resp = self.client.post(
self.scanners_url,
data={
@@ -459,7 +466,7 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
"scanner_type": ScannerType.MONITOR,
"scanner_config": {"prompt": "p"},
"model": ScannerModel.GEMINI_3_6_FLASH,
- "query": {"this_field_does_not_exist": True},
+ "query": query,
},
format="json",
)
diff --git a/products/replay_vision/backend/tests/test_observation_labels_api.py b/products/replay_vision/backend/tests/test_observation_labels_api.py
index c426ceac4375..35b016ba9f97 100644
--- a/products/replay_vision/backend/tests/test_observation_labels_api.py
+++ b/products/replay_vision/backend/tests/test_observation_labels_api.py
@@ -172,6 +172,16 @@ class TestObservationLabels(_VisionAPITestCase):
)
# All six ratings were given today, including those on out-of-window observations.
self.assertEqual(labels["by_rating_day"], [{"date": now.date().isoformat(), "up": 2, "down": 4}])
+ # These snapshots carry only a version and a config, so the wider fields read as not recorded.
+ not_recorded = {
+ "scanner_type": None,
+ "model": None,
+ "provider": None,
+ "emits_signals": None,
+ "query": None,
+ "sampling_rate": None,
+ "sampling_mode": None,
+ }
self.assertEqual(
labels["version_markers"],
[
@@ -180,6 +190,7 @@ class TestObservationLabels(_VisionAPITestCase):
"version": 1,
"prompt": "v1 prompt",
"scanner_config": v1_config,
+ **not_recorded,
"up": 0,
"down": 1,
"total": 1,
@@ -189,6 +200,7 @@ class TestObservationLabels(_VisionAPITestCase):
"version": 2,
"prompt": "v2 prompt",
"scanner_config": v2_config,
+ **not_recorded,
"up": 1,
"down": 1,
"total": 3,
@@ -196,6 +208,48 @@ class TestObservationLabels(_VisionAPITestCase):
],
)
+ def test_version_markers_carry_every_tracked_field(self) -> None:
+ newer = self._create_observation(self.scanner, "sess-newer")
+ query = {"kind": "RecordingsQuery", "events": [{"id": "$pageview"}]}
+ ReplayObservation.objects.filter(id=self.observation.id).update(
+ scanner_snapshot={
+ "scanner_version": 1,
+ "scanner_config": {"prompt": "same prompt"},
+ "scanner_type": "monitor",
+ "model": "gemini-3.5-flash-lite",
+ "provider": "google",
+ "emits_signals": False,
+ "query": query,
+ "sampling_rate": 0.5,
+ "sampling_mode": "focused",
+ }
+ )
+ ReplayObservation.objects.filter(id=newer.id).update(
+ scanner_snapshot={
+ "scanner_version": 2,
+ "scanner_config": {"prompt": "same prompt"},
+ "scanner_type": "monitor",
+ "model": "gemini-3.5-flash-lite",
+ "provider": "google",
+ "emits_signals": False,
+ "query": query,
+ "sampling_rate": 1.0,
+ "sampling_mode": "balanced",
+ }
+ )
+
+ markers = self.client.get(f"{self.observations_url(self.scanner.id)}stats/").json()["labels"]["version_markers"]
+
+ # v1 to v2 changed sampling only, so without these fields the bump looks like nothing changed.
+ self.assertEqual(
+ [(m["version"], m["sampling_rate"], m["sampling_mode"]) for m in markers],
+ [(1, 0.5, "focused"), (2, 1.0, "balanced")],
+ )
+ self.assertEqual(
+ [(m["scanner_type"], m["model"], m["provider"], m["emits_signals"], m["query"]) for m in markers],
+ [("monitor", "gemini-3.5-flash-lite", "google", False, query)] * 2,
+ )
+
def test_order_by_label_groups_labeled_with_unlabeled_last(self) -> None:
correct_obs = self._create_observation(self.scanner, "sess-correct")
self._create_observation(self.scanner, "sess-unlabeled")
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 9fc0dd2f392f..4f9cc2c99a77 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -259,6 +259,10 @@ class TestCreateObservationActivity:
assert observation.scanner_snapshot["provider"] == str(scanner.provider)
assert observation.scanner_snapshot["emits_signals"] == scanner.emits_signals
assert observation.scanner_snapshot["scanner_config"] == scanner.scanner_config
+ # Without these the config-versions history can't explain a sampling- or filter-only bump.
+ assert observation.scanner_snapshot["query"] == scanner.query
+ assert observation.scanner_snapshot["sampling_rate"] == scanner.sampling_rate
+ assert observation.scanner_snapshot["sampling_mode"] == str(scanner.sampling_mode)
assert observation.started_at is None # set when transitioning to running, not here
assert observation.completed_at is None
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 4d2a391da1de..31e945f940e9 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -1256,6 +1256,38 @@ export interface ObservationVersionMarkerApi {
prompt: string
/** The full type-specific config this version ran with (prompt plus, depending on scanner type, allow_inconclusive, tags, scale, or length), taken from the observation run snapshots. */
scanner_config: unknown
+ /**
+ * The scanner type this version ran as.
+ * @nullable
+ */
+ scanner_type: string | null
+ /**
+ * The model this version ran on.
+ * @nullable
+ */
+ model: string | null
+ /**
+ * The provider this version ran on.
+ * @nullable
+ */
+ provider: string | null
+ /**
+ * Whether this version emitted signals.
+ * @nullable
+ */
+ emits_signals: boolean | null
+ /** The `RecordingsQuery` recording filters this version ran with. */
+ query: unknown
+ /**
+ * The 0..1 downsample this version ran with.
+ * @nullable
+ */
+ sampling_rate: number | null
+ /**
+ * The session-coverage pre-filter this version ran with.
+ * @nullable
+ */
+ sampling_mode: string | null
/** Thumbs-up ratings on this version's observations. */
up: number
/** Thumbs-down ratings on this version's observations. */
@@ -1273,7 +1305,7 @@ export interface ObservationLabelStatsApi {
by_day: ObservationLabelDayCountApi[]
/** Daily label counts over the last `recent_days` days, bucketed by the day the rating was last set or changed: the team's rating activity. Days without rating changes are omitted. */
by_rating_day: ObservationLabelDayCountApi[]
- /** Each scanner (prompt) version that produced observations (all-time), with its first day, prompt, and rating counts, for chart markers and the prompt version history. */
+ /** Each scanner version that produced observations (all-time), with its first day, the config it ran with, and rating counts, for chart markers and the config version history. */
version_markers: ObservationVersionMarkerApi[]
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ConfigChangeCards.tsx b/products/replay_vision/frontend/replay_scanners/components/ConfigChangeCards.tsx
index 8f9990ad2707..9c44d519ea39 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ConfigChangeCards.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ConfigChangeCards.tsx
@@ -1,12 +1,10 @@
import { useActions, useValues } from 'kea'
import { useState } from 'react'
-import { IconExpand45, IconPencil, IconRevert } from '@posthog/icons'
+import { IconPencil, IconRevert } from '@posthog/icons'
import {
- LemonButton,
LemonCard,
LemonInput,
- LemonModal,
LemonSegmentedButton,
LemonTag,
LemonTagType,
@@ -14,7 +12,6 @@ import {
Tooltip,
} from '@posthog/lemon-ui'
-import MonacoDiffEditor from 'lib/components/MonacoDiffEditor'
import { objectsEqual } from 'lib/utils/objects'
import { BooleanTag } from '../../components/BooleanTag'
@@ -32,110 +29,9 @@ import {
parseConfigChanges,
ScannerConfigChange,
} from './configChanges'
+import { PromptDiff } from './PromptDiff'
import { SUMMARIZER_LENGTH_OPTIONS } from './ScannerTypeConfigEditor'
-function SuggestionDiffPanes({
- original,
- modified,
- onChange,
- editable,
- isDarkModeOn,
- editorHeight,
- onExpand,
-}: {
- original: string | null
- modified: string | null
- onChange?: (value: string) => void
- editable?: boolean
- isDarkModeOn: boolean
- editorHeight?: string
- onExpand?: () => void
-}): JSX.Element {
- return (
- <div className="@container border rounded overflow-hidden">
- <div className="flex items-center border-b bg-surface-secondary text-xs font-medium">
- {/* Shown exactly when Monaco renders side by side: its inline flip is on editor width (renderSideBySideInlineBreakpoint), not the viewport. */}
- <div className="hidden @[480px]:block flex-1 px-3 py-1.5 border-r">Current prompt</div>
- <div className="flex-1 px-3 py-1.5 flex items-center justify-between">
- <span>{editable ? 'New prompt (edit directly)' : 'New prompt'}</span>
- {onExpand && (
- <LemonButton
- size="xsmall"
- icon={<IconExpand45 />}
- tooltip="Expand diff to full screen"
- onClick={onExpand}
- data-attr="vision-calibration-expand-diff"
- />
- )}
- </div>
- </div>
- <MonacoDiffEditor
- original={original}
- modified={modified}
- onChange={onChange ? (value) => onChange(value) : undefined}
- modifiedEditable={editable}
- language="markdown"
- theme={isDarkModeOn ? 'vs-dark' : 'vs-light'}
- height={editorHeight}
- options={{
- renderSideBySide: true,
- useInlineViewWhenSpaceIsLimited: true,
- renderSideBySideInlineBreakpoint: 480,
- // Keep both panes at exactly half width on resize, in lockstep with the header row.
- enableSplitViewResizing: false,
- splitViewDefaultRatio: 0.5,
- automaticLayout: true,
- wordWrap: 'on',
- lineNumbers: 'off',
- folding: false,
- renderOverviewRuler: false,
- scrollBeyondLastLine: false,
- diffAlgorithm: 'advanced',
- }}
- />
- </div>
- )
-}
-
-/** The prompt diff, expandable to full screen. Both instances share one onChange. */
-function PromptDiff({
- original,
- modified,
- onChange,
- editable,
- isDarkModeOn,
-}: {
- original: string | null
- modified: string | null
- onChange?: (value: string) => void
- editable?: boolean
- isDarkModeOn: boolean
-}): JSX.Element {
- const [isExpanded, setIsExpanded] = useState(false)
- return (
- <>
- <SuggestionDiffPanes
- original={original}
- modified={modified}
- onChange={onChange}
- editable={editable}
- isDarkModeOn={isDarkModeOn}
- onExpand={() => setIsExpanded(true)}
- />
- <LemonModal isOpen={isExpanded} onClose={() => setIsExpanded(false)} title="Recommendation" fullScreen>
- <SuggestionDiffPanes
- original={original}
- modified={modified}
- onChange={onChange}
- editable={editable}
- isDarkModeOn={isDarkModeOn}
- editorHeight="calc(100vh - 16rem)"
- />
- </LemonModal>
- </>
- )
-}
-
const TAG_OP_TAG_TYPE: Record<ScannerConfigChange['op'], LemonTagType> = {
add: 'success',
remove: 'danger',
@@ -282,7 +178,8 @@ function FieldValueEditor({
return <LemonTextArea value={String(value ?? '')} onChange={onChange} minRows={2} />
}
-function FieldCurrentValue({ kind, value }: { kind: FieldEditorKind; value: unknown }): JSX.Element {
+/** A config field's value, read-only. Shared with the config-versions history so both read the same. */
+export function FieldCurrentValue({ kind, value }: { kind: FieldEditorKind; value: unknown }): JSX.Element {
if (kind === 'tags') {
const tags = (value as string[]) ?? []
return tags.length ? (
diff --git a/products/replay_vision/frontend/replay_scanners/components/PromptDiff.tsx b/products/replay_vision/frontend/replay_scanners/components/PromptDiff.tsx
new file mode 100644
index 000000000000..a37a628fb9bf
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/PromptDiff.tsx
@@ -0,0 +1,157 @@
+import { useState } from 'react'
+
+import { IconExpand45 } from '@posthog/icons'
+import { LemonButton, LemonModal } from '@posthog/lemon-ui'
+
+import MonacoDiffEditor from 'lib/components/MonacoDiffEditor'
+
+function DiffPanes({
+ original,
+ modified,
+ onChange,
+ editable,
+ isDarkModeOn,
+ editorHeight,
+ onExpand,
+ originalTitle,
+ modifiedTitle,
+}: {
+ original: string | null
+ modified: string | null
+ onChange?: (value: string) => void
+ editable?: boolean
+ isDarkModeOn: boolean
+ editorHeight?: string
+ onExpand?: () => void
+ originalTitle: string
+ modifiedTitle: string
+}): JSX.Element {
+ return (
+ <div className="@container border rounded overflow-hidden">
+ <div className="flex items-center border-b bg-surface-secondary text-xs font-medium">
+ {/* Shown exactly when Monaco renders side by side: its inline flip is on editor width (renderSideBySideInlineBreakpoint), not the viewport. */}
+ <div className="hidden @[480px]:block flex-1 px-3 py-1.5 border-r">{originalTitle}</div>
+ <div className="flex-1 px-3 py-1.5 flex items-center justify-between">
+ <span>{modifiedTitle}</span>
+ {onExpand && (
+ <LemonButton
+ size="xsmall"
+ icon={<IconExpand45 />}
+ tooltip="Expand diff to full screen"
+ onClick={onExpand}
+ data-attr="vision-calibration-expand-diff"
+ />
+ )}
+ </div>
+ </div>
+ <MonacoDiffEditor
+ original={original}
+ modified={modified}
+ onChange={onChange ? (value) => onChange(value) : undefined}
+ modifiedEditable={editable}
+ language="markdown"
+ theme={isDarkModeOn ? 'vs-dark' : 'vs-light'}
+ height={editorHeight}
+ options={{
+ renderSideBySide: true,
+ useInlineViewWhenSpaceIsLimited: true,
+ renderSideBySideInlineBreakpoint: 480,
+ // Keep both panes at exactly half width on resize, in lockstep with the header row.
+ enableSplitViewResizing: false,
+ splitViewDefaultRatio: 0.5,
+ automaticLayout: true,
+ wordWrap: 'on',
+ lineNumbers: 'off',
+ folding: false,
+ renderOverviewRuler: false,
+ scrollBeyondLastLine: false,
+ diffAlgorithm: 'advanced',
+ }}
+ />
+ </div>
+ )
+}
+
+/** The prompt diff, expandable to full screen. Both instances share one onChange. */
+export function PromptDiff({
+ original,
+ modified,
+ onChange,
+ editable,
+ isDarkModeOn,
+}: {
+ original: string | null
+ modified: string | null
+ onChange?: (value: string) => void
+ editable?: boolean
+ isDarkModeOn: boolean
+}): JSX.Element {
+ const [isExpanded, setIsExpanded] = useState(false)
+ const titles = {
+ originalTitle: 'Current prompt',
+ modifiedTitle: editable ? 'New prompt (edit directly)' : 'New prompt',
+ }
+ return (
+ <>
+ <DiffPanes
+ original={original}
+ modified={modified}
+ onChange={onChange}
+ editable={editable}
+ isDarkModeOn={isDarkModeOn}
+ onExpand={() => setIsExpanded(true)}
+ {...titles}
+ />
+ <LemonModal isOpen={isExpanded} onClose={() => setIsExpanded(false)} title="Recommendation" fullScreen>
+ <DiffPanes
+ original={original}
+ modified={modified}
+ onChange={onChange}
+ editable={editable}
+ isDarkModeOn={isDarkModeOn}
+ editorHeight="calc(100vh - 16rem)"
+ {...titles}
+ />
+ </LemonModal>
+ </>
+ )
+}
+
+/** Opens a read-only prompt diff in a modal, for surfaces too dense to embed an editor per row. */
+export function PromptDiffButton({
+ original,
+ modified,
+ originalTitle,
+ modifiedTitle,
+ isDarkModeOn,
+}: {
+ original: string | null
+ modified: string | null
+ originalTitle: string
+ modifiedTitle: string
+ isDarkModeOn: boolean
+}): JSX.Element {
+ const [isOpen, setIsOpen] = useState(false)
+ return (
+ <>
+ <LemonButton size="xsmall" type="secondary" onClick={() => setIsOpen(true)} data-attr="vision-version-diff">
+ See what changed
+ </LemonButton>
+ <LemonModal
+ isOpen={isOpen}
+ onClose={() => setIsOpen(false)}
+ title={`Prompt: ${originalTitle} to ${modifiedTitle}`}
+ fullScreen
+ >
+ <DiffPanes
+ original={original}
+ modified={modified}
+ isDarkModeOn={isDarkModeOn}
+ editorHeight="calc(100vh - 16rem)"
+ originalTitle={originalTitle}
+ modifiedTitle={modifiedTitle}
+ />
+ </LemonModal>
+ </>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx
index 40f110198c03..923591ff2e06 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { Fragment } from 'react'
import {
IconBolt,
@@ -10,7 +11,7 @@ import {
IconThumbsDownFilled,
IconThumbsUpFilled,
} from '@posthog/icons'
-import { LemonCard, LemonSwitch, LemonTag } from '@posthog/lemon-ui'
+import { LemonCard, LemonCollapse, LemonSwitch, LemonTag } from '@posthog/lemon-ui'
import { PropertyFilterButton } from 'lib/components/PropertyFilters/components/PropertyFilterButton'
import { TZLabel } from 'lib/components/TZLabel'
@@ -20,6 +21,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { themeLogic } from 'lib/logic/themeLogic'
import { humanFriendlyDurationFilter } from 'scenes/session-recordings/filters/DurationFilter'
import {
deriveOperand,
@@ -37,9 +39,26 @@ import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'
import { visionQuotaLogic } from '../../logics/visionQuotaLogic'
import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
import { formatCreditsMaybeUsd } from '../../utils/credits'
-import { promptUnchangedSince } from '../../utils/labelStats'
import { replayScannerLogic } from '../replayScannerLogic'
-import { ReplayScanner, SAMPLING_MODE_OPTIONS, ScannerType, getModelOptions, modelNamingVariant } from '../types'
+import {
+ ReplayScanner,
+ SAMPLING_MODE_OPTIONS,
+ ScannerType,
+ getModelOptions,
+ modelLabel,
+ modelNamingVariant,
+ scannerTypeLabel,
+} from '../types'
+import { FieldCurrentValue } from './ConfigChangeCards'
+import { fieldEditor } from './configChanges'
+import { PromptDiffButton } from './PromptDiff'
+import {
+ VersionChanges,
+ VersionConfig,
+ versionChangesByVersion,
+ versionConfigFromMarker,
+ versionConfigFromScanner,
+} from './versionChanges'
const SUMMARY_LENGTHS = [
{ value: 'short', label: 'Short' },
@@ -49,6 +68,43 @@ const SUMMARY_LENGTHS = [
const SCANNER_TYPES: ScannerType[] = ['monitor', 'classifier', 'scorer', 'summarizer']
+/** The recording filters a query selects on: events, actions, properties, console logs, duration, test accounts. */
+function RecordingFilters({ query }: { query: unknown }): JSX.Element {
+ // Read every filter dimension, not just top-level properties.
+ const universal = recordingsQueryToUniversalFilters((query ?? null) as RecordingsQuery | null)
+ const filters = filtersFromUniversalFilterGroups(universal)
+ if (filters.length === 0 && universal.duration.length === 0 && !universal.filter_test_accounts) {
+ return <span className="text-muted">No filters</span>
+ }
+ const matchWord = deriveOperand(universal.filter_group) === FilterLogicalOperator.Or ? 'any' : 'all'
+ return (
+ <div className="flex flex-col gap-2">
+ {filters.length > 0 && (
+ <div className="flex flex-wrap items-center gap-1.5">
+ {filters.length > 1 && <span className="text-xs">Match {matchWord} of</span>}
+ {filters.map((filter, i) => (
+ <ReadonlyFilter key={i} filter={filter} />
+ ))}
+ </div>
+ )}
+ {(universal.duration.length > 0 || universal.filter_test_accounts) && (
+ <div className="flex flex-wrap items-center gap-1.5">
+ {universal.duration.map((duration, i) => (
+ <LemonTag key={i} type="default" icon={<IconClock />}>
+ {humanFriendlyDurationFilter(duration, duration.key)}
+ </LemonTag>
+ ))}
+ {universal.filter_test_accounts && (
+ <LemonTag type="default" icon={<IconPeople />}>
+ No internal/test users
+ </LemonTag>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
+
function Multiline({ value }: { value: string | null | undefined }): JSX.Element {
return <div className="whitespace-pre-wrap text-sm">{value || <span className="text-muted">—</span>}</div>
}
@@ -157,109 +213,223 @@ function BehaviorCardContent({ scanner }: { scanner: ReplayScanner }): JSX.Eleme
)
}
-/** Reads the type-specific fields off an unknown scanner_config, defensively: it comes from a run
- * snapshot's JSON field, and different versions of the same scanner can carry different scanner types. */
-function VersionConfigDetails({ config }: { config: unknown }): JSX.Element | null {
- if (!config || typeof config !== 'object') {
- return null
- }
- const record = config as Record<string, unknown>
- const tags = Array.isArray(record.tags) ? record.tags.filter((tag): tag is string => typeof tag === 'string') : []
- const scale = record.scale && typeof record.scale === 'object' ? (record.scale as Record<string, unknown>) : null
- const hasScale = typeof scale?.min === 'number' && typeof scale?.max === 'number'
- const length = typeof record.length === 'string' ? record.length : null
- const hasAllowInconclusive = typeof record.allow_inconclusive === 'boolean'
- if (tags.length === 0 && !hasScale && !length && !hasAllowInconclusive) {
- return null
- }
+/** What a version changed, field by field. Versions bump on any tracked change, so without this a bump the
+ * reader can't spot (a flag, the model, sampling) reads as a no-op. */
+function VersionChangeSummary({
+ changes,
+ version,
+ isDarkModeOn,
+}: {
+ changes: VersionChanges
+ version: number
+ isDarkModeOn: boolean
+}): JSX.Element {
+ const comparedWith = changes.previous.version
return (
- <div className="flex flex-wrap items-center gap-2 text-xs text-muted">
- {tags.length > 0 && (
- <div className="flex flex-wrap gap-1">
- {tags.map((tag) => (
- <LemonTag key={tag} size="small" type="option">
- {tag}
- </LemonTag>
- ))}
+ <div className="rounded bg-surface-secondary px-3 py-2 space-y-1">
+ <div className="text-xs font-medium">
+ {changes.changes.length > 0
+ ? `Changed since v${comparedWith}`
+ : `Nothing recorded for v${version} differs from v${comparedWith}`}
+ </div>
+ {changes.changes.map((change) => (
+ <div key={change.field} className="flex flex-wrap items-baseline gap-x-2 text-xs">
+ <span className="text-muted">{change.label}</span>
+ {change.kind === 'value' ? (
+ <span>
+ <span className="text-muted line-through">{change.before}</span>
+ <span className="text-muted mx-1">→</span>
+ {change.after}
+ </span>
+ ) : (
+ <span className="flex items-center gap-2">
+ <span>edited</span>
+ {change.kind === 'prompt' && (
+ <PromptDiffButton
+ original={change.before}
+ modified={change.after}
+ originalTitle={`v${comparedWith}`}
+ modifiedTitle={`v${version}`}
+ isDarkModeOn={isDarkModeOn}
+ />
+ )}
+ </span>
+ )}
+ </div>
+ ))}
+ {changes.notRecorded.length > 0 && (
+ <div className="text-xs text-muted">
+ {changes.notRecorded.join(', ')} weren't recorded for these versions, so a change there isn't shown.
</div>
)}
- {hasScale && scale && (
+ </div>
+ )
+}
+
+/** Every version-tracked field the version ran with, so the reader sees the whole config, not only the diff. */
+function VersionFields({ config, changed }: { config: VersionConfig; changed: Set<string> }): JSX.Element {
+ // A field the run snapshots never carried must say so, not render a default that reads as a real value.
+ const recorded = (value: unknown, render: () => JSX.Element): JSX.Element =>
+ value == null ? <span className="text-muted">Not recorded</span> : render()
+ const rows: { field: string; label: string; value: JSX.Element }[] = [
+ {
+ field: 'prompt',
+ label: 'Prompt',
+ value: (
+ <div className="whitespace-pre-wrap">
+ {String(config.scannerConfig.prompt ?? '') || <span className="text-muted">—</span>}
+ </div>
+ ),
+ },
+ {
+ field: 'scannerType',
+ label: 'Type',
+ value: recorded(config.scannerType, () => (
+ <span>{scannerTypeLabel(config.scannerType as ScannerType)}</span>
+ )),
+ },
+ {
+ field: 'model',
+ label: 'Model',
+ value: recorded(config.model, () => <span>{modelLabel(config.model)}</span>),
+ },
+ {
+ field: 'provider',
+ label: 'Provider',
+ value: recorded(config.provider, () => <span>{config.provider}</span>),
+ },
+ {
+ field: 'emitsSignals',
+ label: 'Emit signals',
+ value: recorded(config.emitsSignals, () => <BooleanTag value={!!config.emitsSignals} />),
+ },
+ {
+ field: 'samplingMode',
+ label: 'Session coverage',
+ value: recorded(config.samplingMode, () => (
<span>
- Scale: {scale.min as number} – {scale.max as number}
- {scale.label ? ` (${String(scale.label)})` : ''}
- </span>
- )}
- {length && <LemonTag size="small">{length}</LemonTag>}
- {hasAllowInconclusive && (
- <span className="flex items-center gap-1">
- Inconclusive verdicts <BooleanTag value={!!record.allow_inconclusive} />
+ {SAMPLING_MODE_OPTIONS.find((option) => option.value === config.samplingMode)?.label ??
+ config.samplingMode}
</span>
- )}
+ )),
+ },
+ {
+ field: 'samplingRate',
+ label: 'Sampling',
+ value: recorded(config.samplingRate, () => (
+ <span>{Math.round((config.samplingRate ?? 0) * 1000) / 10}%</span>
+ )),
+ },
+ ...Object.keys(config.scannerConfig)
+ .filter((key) => key !== 'prompt')
+ .map((key) => {
+ const { kind, label } = fieldEditor(key, config.scannerConfig[key])
+ return { field: key, label, value: <FieldCurrentValue kind={kind} value={config.scannerConfig[key]} /> }
+ }),
+ {
+ field: 'query',
+ label: 'Recording filters',
+ value: recorded(config.query, () => <RecordingFilters query={config.query} />),
+ },
+ ]
+ return (
+ <div className="grid grid-cols-[auto_1fr] items-baseline gap-x-3 gap-y-1.5 text-xs">
+ {rows.map((row) => (
+ <Fragment key={row.field}>
+ <span className="text-muted">{row.label}</span>
+ {/* Emphasis suits a short value, not a whole prompt. The change summary flags that one. */}
+ <span className={changed.has(row.field) && row.field !== 'prompt' ? 'font-medium' : undefined}>
+ {row.value}
+ </span>
+ </Fragment>
+ ))}
</div>
)
}
-function PromptVersionHistory({ scanner }: { scanner: ReplayScanner }): JSX.Element | null {
+function ConfigVersionHistory({ scanner }: { scanner: ReplayScanner }): JSX.Element | null {
const { observationStatsApi } = useValues(replayScannerLogic({ id: scanner.id }))
+ const { isDarkModeOn } = useValues(themeLogic)
const markers = observationStatsApi?.labels.version_markers ?? []
- // A freshly applied prompt has no scans yet and no marker, so show the live config as its own entry.
const currentVersion = scanner.scanner_version
- const currentPrompt = scanner.scanner_config.prompt
- const showCurrentEntry = Boolean(currentPrompt) && !markers.some((marker) => marker.version === currentVersion)
- if (markers.length === 0 && !showCurrentEntry) {
+ const hasCurrentMarker = markers.some((marker) => marker.version === currentVersion)
+ if (markers.length === 0 && !hasCurrentMarker && !scanner.scanner_config.prompt) {
return null
}
- const newestFirst = [...markers].sort((a, b) => b.version - a.version)
- // Versions bump on any config change, so flag same-prompt versions instead of looking like duplicates.
- const unchangedSince = promptUnchangedSince(markers)
- const newestMarker = newestFirst[0]
- const currentUnchangedFrom =
- newestMarker && currentPrompt === newestMarker.prompt
- ? (unchangedSince.get(newestMarker.version) ?? newestMarker.version)
- : null
+ const byVersion = new Map(markers.map((marker) => [marker.version, marker]))
+ // A version saved but not yet scanned has no marker, so the live scanner stands in for it.
+ const configs = markers.map(versionConfigFromMarker)
+ if (!hasCurrentMarker) {
+ configs.push(versionConfigFromScanner(scanner))
+ }
+ const changesByVersion = versionChangesByVersion(configs)
+ const newestFirst = [...configs].sort((a, b) => b.version - a.version)
return (
<LemonCard className="p-4" hoverEffect={false}>
<CardHeader icon={<IconPencil />} title="Config versions" />
<div className="flex flex-col gap-3">
- {showCurrentEntry && (
- <div className="border rounded p-3 space-y-2" id={`prompt-v${currentVersion}`}>
- <div className="flex flex-wrap items-center gap-2 text-xs text-muted">
- <LemonTag type="warning" className="font-mono">
- v{currentVersion}
- </LemonTag>
- <span>current · no scans yet</span>
- {currentUnchangedFrom !== null && (
- <span>· prompt unchanged from v{currentUnchangedFrom}</span>
- )}
- </div>
- <div className="whitespace-pre-wrap font-mono text-xs">{currentPrompt}</div>
- <VersionConfigDetails config={scanner.scanner_config} />
- </div>
- )}
- {newestFirst.map((marker) => (
- <div key={marker.version} className="border rounded p-3 space-y-2" id={`prompt-v${marker.version}`}>
- <div className="flex flex-wrap items-center gap-2 text-xs text-muted">
- <LemonTag
- type={marker.version === currentVersion ? 'warning' : 'muted'}
- className="font-mono"
- >
- v{marker.version}
- </LemonTag>
- <span>from {dayjs(marker.date).format('MMM D, YYYY')}</span>
- <span className="flex items-center gap-1">
- <IconThumbsUpFilled className="text-success" /> {marker.up}
- </span>
- <span className="flex items-center gap-1">
- <IconThumbsDownFilled className="text-danger" /> {marker.down}
- </span>
- {unchangedSince.has(marker.version) && (
- <span>· prompt unchanged from v{unchangedSince.get(marker.version)}</span>
+ {newestFirst.map((config) => {
+ const marker = byVersion.get(config.version)
+ const changes = changesByVersion.get(config.version)
+ return (
+ <div
+ key={config.version}
+ className="border rounded p-3 space-y-2"
+ id={`prompt-v${config.version}`}
+ >
+ <div className="flex flex-wrap items-center gap-2 text-xs text-muted">
+ <LemonTag
+ type={config.version === currentVersion ? 'warning' : 'muted'}
+ className="font-mono"
+ >
+ v{config.version}
+ </LemonTag>
+ {marker ? (
+ <>
+ <span>from {dayjs(marker.date).format('MMM D, YYYY')}</span>
+ <span className="flex items-center gap-1">
+ <IconThumbsUpFilled className="text-success" /> {marker.up}
+ </span>
+ <span className="flex items-center gap-1">
+ <IconThumbsDownFilled className="text-danger" /> {marker.down}
+ </span>
+ </>
+ ) : (
+ <span>current · no scans yet</span>
+ )}
+ </div>
+ {changes ? (
+ <VersionChangeSummary
+ changes={changes}
+ version={config.version}
+ isDarkModeOn={isDarkModeOn}
+ />
+ ) : (
+ <div className="text-xs text-muted">Oldest version with scans.</div>
)}
+ {/* Collapsed by default: the summary above already names what changed, so the
+ full config is only needed when someone wants the rest of it. */}
+ <LemonCollapse
+ embedded
+ size="xsmall"
+ panels={[
+ {
+ key: 'config',
+ header: 'Full config',
+ content: (
+ <VersionFields
+ config={config}
+ changed={
+ new Set((changes?.changes ?? []).map((change) => change.field))
+ }
+ />
+ ),
+ },
+ ]}
+ />
</div>
- <div className="whitespace-pre-wrap font-mono text-xs">{marker.prompt || '—'}</div>
- <VersionConfigDetails config={marker.scanner_config} />
- </div>
- ))}
+ )
+ })}
</div>
</LemonCard>
)
@@ -272,11 +442,6 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):
const { featureFlags } = useValues(featureFlagLogic)
const namingVariant = modelNamingVariant(featureFlags[FEATURE_FLAGS.REPLAY_VISION_MODEL_TIER_NAMING_EXPERIMENT])
const samplingPercent = Math.round((scanner.sampling_rate ?? 0) * 1000) / 10
- // Read every filter dimension (events, actions, properties, console logs, …), not just top-level properties.
- const universal = recordingsQueryToUniversalFilters((scanner.query ?? null) as RecordingsQuery | null)
- const filters = filtersFromUniversalFilterGroups(universal)
- const hasTriggers = filters.length > 0 || universal.duration.length > 0 || universal.filter_test_accounts
- const matchWord = deriveOperand(universal.filter_group) === FilterLogicalOperator.Or ? 'any' : 'all'
return (
<div className="flex flex-col gap-4">
@@ -338,36 +503,7 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):
</LabeledRow>
<LabeledRow label="Sampling">{samplingPercent}%</LabeledRow>
<LabeledRow label="Recording filters">
- {!hasTriggers ? (
- <span className="text-muted">No filters</span>
- ) : (
- <div className="flex flex-col gap-2">
- {filters.length > 0 && (
- <div className="flex flex-wrap items-center gap-1.5">
- {filters.length > 1 && (
- <span className="text-xs">Match {matchWord} of</span>
- )}
- {filters.map((filter, i) => (
- <ReadonlyFilter key={i} filter={filter} />
- ))}
- </div>
- )}
- {(universal.duration.length > 0 || universal.filter_test_accounts) && (
- <div className="flex flex-wrap items-center gap-1.5">
- {universal.duration.map((duration, i) => (
- <LemonTag key={i} type="default" icon={<IconClock />}>
- {humanFriendlyDurationFilter(duration, duration.key)}
- </LemonTag>
- ))}
- {universal.filter_test_accounts && (
- <LemonTag type="default" icon={<IconPeople />}>
- No internal/test users
- </LemonTag>
- )}
- </div>
- )}
- </div>
- )}
+ <RecordingFilters query={scanner.query} />
</LabeledRow>
</div>
</LemonCard>
@@ -434,7 +570,7 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):
</div>
</LemonCard>
</div>
- <PromptVersionHistory scanner={scanner} />
+ <ConfigVersionHistory scanner={scanner} />
</div>
)
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/versionChanges.test.ts b/products/replay_vision/frontend/replay_scanners/components/versionChanges.test.ts
new file mode 100644
index 000000000000..8684146f4bbc
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/versionChanges.test.ts
@@ -0,0 +1,135 @@
+import { SAMPLING_MODE_OPTIONS } from '../types'
+import { diffVersionConfigs, VersionConfig, versionChangesByVersion } from './versionChanges'
+
+describe('versionChanges', () => {
+ const version = (overrides: Partial<VersionConfig> = {}): VersionConfig => ({
+ version: 1,
+ scannerType: 'classifier',
+ model: 'gemini-3.6-flash',
+ provider: 'google',
+ emitsSignals: true,
+ samplingRate: 1,
+ samplingMode: 'balanced',
+ query: { kind: 'RecordingsQuery', events: [] },
+ scannerConfig: { prompt: 'classify this', tags: ['a', 'b'] },
+ ...overrides,
+ })
+
+ describe('diffVersionConfigs', () => {
+ it.each([
+ // The real bug this readout exists for: turning a flag on bumped the version, and the history
+ // showed nothing because the previous config had no such key at all.
+ ['a flag absent before', { prompt: 'p' }, { prompt: 'p', multi_label: true }, 'off', 'on'],
+ ['a flag removed', { prompt: 'p', multi_label: true }, { prompt: 'p' }, 'on', 'off'],
+ ['a flag flipped', { prompt: 'p', multi_label: true }, { prompt: 'p', multi_label: false }, 'on', 'off'],
+ ])('reports %s', (_name, beforeConfig, afterConfig, before, after) => {
+ const { changes } = diffVersionConfigs(
+ version({ scannerConfig: beforeConfig }),
+ version({ version: 2, scannerConfig: afterConfig })
+ )
+ expect(changes).toEqual([
+ { field: 'multi_label', label: 'Multiple tags per session', kind: 'value', before, after },
+ ])
+ })
+
+ it.each([
+ ['model', { model: 'gemini-3.5-flash-lite' }, 'Model'],
+ ['sampling rate', { samplingRate: 0.25 }, 'Sampling'],
+ ['session coverage', { samplingMode: 'focused' }, 'Session coverage'],
+ ['signal emission', { emitsSignals: false }, 'Emit signals'],
+ ['type', { scannerType: 'monitor' }, 'Type'],
+ ])('reports a changed %s', (_name, overrides, label) => {
+ const { changes } = diffVersionConfigs(version(), version({ version: 2, ...overrides }))
+ expect(changes.map((change) => change.label)).toEqual([label])
+ })
+
+ it('formats sampling and coverage with the labels the configuration tab uses', () => {
+ // Read the copy from the option list rather than pinning it, so renaming a mode isn't a test failure.
+ const modeLabel = (value: string): string =>
+ SAMPLING_MODE_OPTIONS.find((option) => option.value === value)?.label ?? value
+ const { changes } = diffVersionConfigs(
+ version(),
+ version({ version: 2, samplingRate: 0.255, samplingMode: 'focused' })
+ )
+ expect(changes).toEqual([
+ {
+ field: 'samplingMode',
+ label: 'Session coverage',
+ kind: 'value',
+ before: modeLabel('balanced'),
+ after: modeLabel('focused'),
+ },
+ { field: 'samplingRate', label: 'Sampling', kind: 'value', before: '100%', after: '25.5%' },
+ ])
+ // The raw enum leaking through instead of the friendly label is the regression this guards.
+ expect(changes[0].after).not.toBe('focused')
+ })
+
+ it('carries the raw prompt text so the change can be diffed, and puts it first', () => {
+ const { changes } = diffVersionConfigs(
+ version({ scannerConfig: { prompt: 'old', multi_label: false } }),
+ version({ version: 2, scannerConfig: { prompt: 'new', multi_label: true } })
+ )
+ expect(changes[0]).toEqual({
+ field: 'prompt',
+ label: 'Prompt',
+ kind: 'prompt',
+ before: 'old',
+ after: 'new',
+ })
+ expect(changes).toHaveLength(2)
+ })
+
+ it('reports a changed query once, without trying to summarize it in a line', () => {
+ const { changes } = diffVersionConfigs(
+ version(),
+ version({ version: 2, query: { kind: 'RecordingsQuery', events: [{ id: '$pageview' }] } })
+ )
+ expect(changes).toEqual([
+ { field: 'query', label: 'Recording filters', kind: 'query', before: '', after: '' },
+ ])
+ })
+
+ it.each([
+ ['the older version', { query: null }, {}],
+ ['the newer version', {}, { query: null }],
+ ])('treats a query missing from %s as not recorded, not as a change', (_name, before, after) => {
+ const result = diffVersionConfigs(version(before), version({ version: 2, ...after }))
+ expect(result.changes).toEqual([])
+ expect(result.notRecorded).toEqual(['Recording filters'])
+ })
+
+ it('lists every unrecorded field for versions scanned before they were snapshotted', () => {
+ const legacy = { model: null, provider: null, query: null, samplingRate: null, samplingMode: null }
+ const result = diffVersionConfigs(version(legacy), version({ version: 2, ...legacy }))
+ expect(result.changes).toEqual([])
+ expect(result.notRecorded).toEqual([
+ 'Model',
+ 'Provider',
+ 'Session coverage',
+ 'Sampling',
+ 'Recording filters',
+ ])
+ })
+
+ it('reports nothing for identical versions', () => {
+ const result = diffVersionConfigs(version(), version({ version: 2 }))
+ expect(result.changes).toEqual([])
+ expect(result.notRecorded).toEqual([])
+ expect(result.previous.version).toBe(1)
+ })
+ })
+
+ describe('versionChangesByVersion', () => {
+ it('compares against the previous version present, not the previous number', () => {
+ // v2 and v3 scanned nothing, so they have no entry to compare against.
+ const result = versionChangesByVersion([
+ version({ version: 4, scannerConfig: { prompt: 'b' } }),
+ version({ version: 1, scannerConfig: { prompt: 'a' } }),
+ ])
+ expect([...result.keys()]).toEqual([4])
+ expect(result.get(4)?.previous.version).toBe(1)
+ expect(result.get(4)?.changes.map((change) => change.label)).toEqual(['Prompt'])
+ })
+ })
+})
diff --git a/products/replay_vision/frontend/replay_scanners/components/versionChanges.ts b/products/replay_vision/frontend/replay_scanners/components/versionChanges.ts
new file mode 100644
index 000000000000..99f8782c96d4
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/versionChanges.ts
@@ -0,0 +1,150 @@
+import { objectsEqual } from 'lib/utils/objects'
+
+import type { ObservationVersionMarkerApi } from '../../generated/api.schemas'
+import { ReplayScanner, SAMPLING_MODE_OPTIONS, ScannerType, modelLabel, scannerTypeLabel } from '../types'
+import { fieldEditor, formatChangeValue } from './configChanges'
+
+/** One version's full version-tracked config, from a run snapshot or from the live scanner.
+ * A null top-level field means the run snapshots didn't record it, which is not the same as unset. */
+export interface VersionConfig {
+ version: number
+ scannerType?: string | null
+ model?: string | null
+ provider?: string | null
+ emitsSignals?: boolean | null
+ samplingRate?: number | null
+ samplingMode?: string | null
+ query?: unknown
+ scannerConfig: Record<string, unknown>
+}
+
+export interface VersionFieldChange {
+ field: string
+ label: string
+ /** `value` reads as "before → after". A prompt or filter change is too big for one line. */
+ kind: 'prompt' | 'query' | 'value'
+ before: string
+ after: string
+}
+
+export interface VersionChanges {
+ /** The version this one is compared against. */
+ previous: VersionConfig
+ changes: VersionFieldChange[]
+ /** Version-tracked fields one of the two versions didn't record, so they couldn't be compared. */
+ notRecorded: string[]
+}
+
+/** Labels match the configuration tab's own, so both surfaces read the same. */
+const SCANNER_FIELDS: { field: keyof VersionConfig; label: string; format: (value: unknown) => string }[] = [
+ { field: 'scannerType', label: 'Type', format: (v) => scannerTypeLabel(v as ScannerType) },
+ { field: 'model', label: 'Model', format: (v) => modelLabel(v as string) },
+ { field: 'provider', label: 'Provider', format: (v) => String(v) },
+ { field: 'emitsSignals', label: 'Emit signals', format: formatChangeValue },
+ { field: 'samplingMode', label: 'Session coverage', format: (v) => optionLabel(SAMPLING_MODE_OPTIONS, v) },
+ { field: 'samplingRate', label: 'Sampling', format: (v) => `${Math.round(Number(v) * 1000) / 10}%` },
+]
+
+function optionLabel(options: readonly { value: string; label: string }[], value: unknown): string {
+ return options.find((option) => option.value === value)?.label ?? String(value)
+}
+
+/** Humanizes one config value for the one-line change readout. */
+export function formatConfigValue(field: string, value: unknown): string {
+ const { kind } = fieldEditor(field, value)
+ if (value === undefined || value === null) {
+ // An absent flag is off, not unknown: scanner_config is always snapshotted whole.
+ return kind === 'flag' ? 'off' : '—'
+ }
+ if (kind === 'tags') {
+ const tags = value as unknown[]
+ return tags.length ? tags.join(', ') : 'none'
+ }
+ return formatChangeValue(value)
+}
+
+/** Every version-tracked field that differs between two versions, for the "what changed" readout.
+ * Top-level fields only compare when both versions recorded them. Config keys always compare, since
+ * scanner_config is snapshotted whole and an absent key means the value is unset. */
+export function diffVersionConfigs(previous: VersionConfig, current: VersionConfig): VersionChanges {
+ const changes: VersionFieldChange[] = []
+ const notRecorded: string[] = []
+
+ for (const { field, label, format } of SCANNER_FIELDS) {
+ const before = previous[field]
+ const after = current[field]
+ if (before == null || after == null) {
+ notRecorded.push(label)
+ } else if (before !== after) {
+ changes.push({ field, label, kind: 'value', before: format(before), after: format(after) })
+ }
+ }
+
+ if (previous.query == null || current.query == null) {
+ notRecorded.push('Recording filters')
+ } else if (!objectsEqual(previous.query, current.query)) {
+ changes.push({ field: 'query', label: 'Recording filters', kind: 'query', before: '', after: '' })
+ }
+
+ for (const key of new Set([...Object.keys(previous.scannerConfig), ...Object.keys(current.scannerConfig)])) {
+ const before = previous.scannerConfig[key]
+ const after = current.scannerConfig[key]
+ if (objectsEqual(before ?? null, after ?? null)) {
+ continue
+ }
+ const { kind, label } = fieldEditor(key, after ?? before)
+ const isPrompt = kind === 'prompt'
+ changes.push({
+ field: key,
+ label,
+ kind: isPrompt ? 'prompt' : 'value',
+ // The prompt carries its raw text, since a diff, not a one-line summary, is what reads clearly.
+ before: isPrompt ? String(before ?? '') : formatConfigValue(key, before),
+ after: isPrompt ? String(after ?? '') : formatConfigValue(key, after),
+ })
+ }
+
+ // Prompt first, since it is the change that matters most.
+ changes.sort((a, b) => Number(b.kind === 'prompt') - Number(a.kind === 'prompt'))
+ return { previous, changes, notRecorded }
+}
+
+/** The live scanner as a version, so a freshly saved version with no scans yet still shows what it changed. */
+export function versionConfigFromScanner(scanner: ReplayScanner): VersionConfig {
+ return {
+ version: scanner.scanner_version,
+ scannerType: scanner.scanner_type,
+ model: scanner.model,
+ provider: scanner.provider,
+ emitsSignals: scanner.emits_signals,
+ samplingRate: scanner.sampling_rate,
+ samplingMode: scanner.sampling_mode,
+ query: scanner.query ?? {},
+ scannerConfig: scanner.scanner_config as unknown as Record<string, unknown>,
+ }
+}
+
+export function versionConfigFromMarker(marker: ObservationVersionMarkerApi): VersionConfig {
+ return {
+ version: marker.version,
+ scannerType: marker.scanner_type,
+ model: marker.model,
+ provider: marker.provider,
+ emitsSignals: marker.emits_signals,
+ samplingRate: marker.sampling_rate,
+ samplingMode: marker.sampling_mode,
+ query: marker.query,
+ scannerConfig: (marker.scanner_config as Record<string, unknown>) ?? {},
+ }
+}
+
+/** Version -> what it changed, against the next-oldest version present. Versions that scanned nothing
+ * leave gaps, so that isn't always version - 1. The oldest gets no entry. */
+export function versionChangesByVersion(versions: VersionConfig[]): Map<number, VersionChanges> {
+ const ascending = [...versions].sort((a, b) => a.version - b.version)
+ const result = new Map<number, VersionChanges>()
+ for (let index = 1; index < ascending.length; index++) {
+ result.set(ascending[index].version, diffVersionConfigs(ascending[index - 1], ascending[index]))
+ }
+ return result
+}
diff --git a/products/replay_vision/frontend/utils/labelStats.test.ts b/products/replay_vision/frontend/utils/labelStats.test.ts
index e948bfab3243..f692c7bf77c4 100644
--- a/products/replay_vision/frontend/utils/labelStats.test.ts
+++ b/products/replay_vision/frontend/utils/labelStats.test.ts
@@ -1,7 +1,7 @@
import { dayjs } from 'lib/dayjs'
import type { ObservationVersionMarkerApi } from '../generated/api.schemas'
-import { buildChartDayFormatter, fillLabelDays, promptUnchangedSince, versionAccuracyStrip } from './labelStats'
+import { buildChartDayFormatter, fillLabelDays, versionAccuracyStrip } from './labelStats'
describe('labelStats', () => {
describe('fillLabelDays', () => {
@@ -49,6 +49,13 @@ describe('labelStats', () => {
version,
prompt: '',
scanner_config: {},
+ scanner_type: 'monitor',
+ model: 'gemini-3.6-flash',
+ provider: 'google',
+ emits_signals: false,
+ query: {},
+ sampling_rate: 1,
+ sampling_mode: 'balanced',
up,
down,
total,
@@ -86,40 +93,4 @@ describe('labelStats', () => {
expect(versionAccuracyStrip(markers, activeVersion)).toEqual([])
})
})
-
- describe('promptUnchangedSince', () => {
- const versionWithPrompt = (version: number, prompt: string): ObservationVersionMarkerApi => ({
- date: '2026-07-01',
- version,
- prompt,
- scanner_config: {},
- up: 0,
- down: 0,
- total: 0,
- })
-
- it('chains identical prompts to the earliest version, across gaps', () => {
- // v3 never scanned (no marker); v1, v2 and v4 ran the same prompt, v5 changed it.
- const result = promptUnchangedSince([
- versionWithPrompt(5, 'new prompt'),
- versionWithPrompt(4, 'same prompt'),
- versionWithPrompt(2, 'same prompt'),
- versionWithPrompt(1, 'same prompt'),
- ])
- expect([...result.entries()]).toEqual([
- [2, 1],
- [4, 1],
- ])
- })
-
- it('tags nothing for distinct or empty prompts', () => {
- const result = promptUnchangedSince([
- versionWithPrompt(1, 'a'),
- versionWithPrompt(2, 'b'),
- versionWithPrompt(3, ''),
- versionWithPrompt(4, ''),
- ])
- expect(result.size).toBe(0)
- })
- })
})
diff --git a/products/replay_vision/frontend/utils/labelStats.ts b/products/replay_vision/frontend/utils/labelStats.ts
index 57aebad54e29..8865ee1ade58 100644
--- a/products/replay_vision/frontend/utils/labelStats.ts
+++ b/products/replay_vision/frontend/utils/labelStats.ts
@@ -99,19 +99,3 @@ export function versionAccuracyStrip(
}
return entries
}
-
-/** Version -> the earliest older version that ran the same prompt. Versions bump on any tracked
- * config change (model, query, sampling, …), so identical prompts across versions are common and
- * the versions panel tags them instead of looking like duplicates. */
-export function promptUnchangedSince(markers: ObservationVersionMarkerApi[]): Map<number, number> {
- const ascending = [...markers].sort((a, b) => a.version - b.version)
- const result = new Map<number, number>()
- for (let i = 1; i < ascending.length; i++) {
- const current = ascending[i]
- const previous = ascending[i - 1]
- if (current.prompt && current.prompt === previous.prompt) {
- result.set(current.version, result.get(previous.version) ?? previous.version)
- }
- }
- return result
-}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9c208a5a6cd4..bb1d673daa67 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -46417,6 +46417,38 @@ export namespace Schemas {
prompt: string;
/** The full type-specific config this version ran with (prompt plus, depending on scanner type, allow_inconclusive, tags, scale, or length), taken from the observation run snapshots. */
scanner_config: unknown;
+ /**
+ * The scanner type this version ran as.
+ * @nullable
+ */
+ scanner_type: string | null;
+ /**
+ * The model this version ran on.
+ * @nullable
+ */
+ model: string | null;
+ /**
+ * The provider this version ran on.
+ * @nullable
+ */
+ provider: string | null;
+ /**
+ * Whether this version emitted signals.
+ * @nullable
+ */
+ emits_signals: boolean | null;
+ /** The `RecordingsQuery` recording filters this version ran with. */
+ query: unknown;
+ /**
+ * The 0..1 downsample this version ran with.
+ * @nullable
+ */
+ sampling_rate: number | null;
+ /**
+ * The session-coverage pre-filter this version ran with.
+ * @nullable
+ */
+ sampling_mode: string | null;
/** Thumbs-up ratings on this version's observations. */
up: number;
/** Thumbs-down ratings on this version's observations. */
@@ -46434,7 +46466,7 @@ export namespace Schemas {
by_day: ObservationLabelDayCount[];
/** Daily label counts over the last `recent_days` days, bucketed by the day the rating was last set or changed: the team's rating activity. Days without rating changes are omitted. */
by_rating_day: ObservationLabelDayCount[];
- /** Each scanner (prompt) version that produced observations (all-time), with its first day, prompt, and rating counts, for chart markers and the prompt version history. */
+ /** Each scanner version that produced observations (all-time), with its first day, the config it ran with, and rating counts, for chart markers and the config version history. */
version_markers: ObservationVersionMarker[];
}