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): quality tab fixes from testing round (#72901)

Arno Hillen0ddab2192ab1
diff --git a/frontend/src/lib/lemon-ui/PaginationControl/types.ts b/frontend/src/lib/lemon-ui/PaginationControl/types.ts
index b0feda792621..e4f9db53f79a 100644
--- a/frontend/src/lib/lemon-ui/PaginationControl/types.ts
+++ b/frontend/src/lib/lemon-ui/PaginationControl/types.ts
@@ -21,6 +21,12 @@ export interface PaginationManual extends PaginationBase {
onForward?: () => void
/** Previous page navigation handler. */
onBackward?: () => void
+ /**
+ * Set to false to stop page changes from being pushed to the URL as a `page` search param.
+ * Only for tables whose page state lives entirely in their own logic: handler-less controlled
+ * tables navigate exclusively through that URL param, so they must keep the default.
+ */
+ useUrl?: boolean
}
export type PaginationState<T> = {
diff --git a/frontend/src/lib/lemon-ui/PaginationControl/usePagination.test.ts b/frontend/src/lib/lemon-ui/PaginationControl/usePagination.test.ts
new file mode 100644
index 000000000000..cbe2fb006bba
--- /dev/null
+++ b/frontend/src/lib/lemon-ui/PaginationControl/usePagination.test.ts
@@ -0,0 +1,31 @@
+import { act, renderHook } from '@testing-library/react'
+import { router } from 'kea-router'
+
+import { initKeaTests } from '~/test/init'
+
+import { usePagination } from './usePagination'
+
+const DATA = ['a', 'b', 'c']
+
+describe('usePagination', () => {
+ beforeEach(() => {
+ initKeaTests()
+ router.actions.push('/table')
+ })
+
+ it('setCurrentPage pushes the page into the URL by default', () => {
+ const { result } = renderHook(() =>
+ usePagination(DATA, { controlled: true, pageSize: 1, currentPage: 1, entryCount: 3 })
+ )
+ act(() => result.current.setCurrentPage(2))
+ expect(router.values.searchParams.page).toBe(2)
+ })
+
+ it('setCurrentPage leaves the URL alone when useUrl is false', () => {
+ const { result } = renderHook(() =>
+ usePagination(DATA, { controlled: true, pageSize: 1, currentPage: 1, entryCount: 3, useUrl: false })
+ )
+ act(() => result.current.setCurrentPage(2))
+ expect(router.values.searchParams.page).toBeUndefined()
+ })
+})
diff --git a/frontend/src/lib/lemon-ui/PaginationControl/usePagination.ts b/frontend/src/lib/lemon-ui/PaginationControl/usePagination.ts
index ef020e06ea3a..37f9f4c1fbbe 100644
--- a/frontend/src/lib/lemon-ui/PaginationControl/usePagination.ts
+++ b/frontend/src/lib/lemon-ui/PaginationControl/usePagination.ts
@@ -15,9 +15,14 @@ export function usePagination<T>(
const { location, searchParams, hashParams } = useValues(router)
const { push } = useActions(router)
+ const syncPageToUrl = !(pagination?.controlled && pagination.useUrl === false)
const setCurrentPage = useCallback(
- (newPage: number) => push(location.pathname, { ...searchParams, [currentPageParam]: newPage }, hashParams),
- [location, searchParams, hashParams, push] // oxlint-disable-line react-hooks/exhaustive-deps
+ (newPage: number) => {
+ if (syncPageToUrl) {
+ push(location.pathname, { ...searchParams, [currentPageParam]: newPage }, hashParams)
+ }
+ },
+ [location, searchParams, hashParams, push, syncPageToUrl] // oxlint-disable-line react-hooks/exhaustive-deps
)
const entryCount: number | null = pagination?.controlled ? pagination.entryCount || null : dataSource.length
diff --git a/products/replay_vision/backend/prompt_suggestions.py b/products/replay_vision/backend/prompt_suggestions.py
index e5f69f64489f..6fd4b309df5c 100644
--- a/products/replay_vision/backend/prompt_suggestions.py
+++ b/products/replay_vision/backend/prompt_suggestions.py
@@ -15,6 +15,7 @@ from typing import Any
from django.conf import settings
from django.db import transaction
+from django.db.models import Count, Q
from django.db.models.fields.json import KeyTextTransform
from django.utils import timezone
@@ -227,11 +228,16 @@ def _build_user_content(
def _gemini_client() -> GeminiClient:
# The generate endpoint runs inline in a web worker, so a hung provider call must time out.
- return genai.Client(
- api_key=settings.REPLAY_VISION_GEMINI_API_KEY or settings.GEMINI_API_KEY,
- posthog_client=posthoganalytics.default_client,
- http_options={"timeout": _MODEL_CALL_TIMEOUT_MS},
- )
+ try:
+ return genai.Client(
+ api_key=settings.REPLAY_VISION_GEMINI_API_KEY or settings.GEMINI_API_KEY,
+ posthog_client=posthoganalytics.default_client,
+ http_options={"timeout": _MODEL_CALL_TIMEOUT_MS},
+ )
+ except Exception as e:
+ # A missing or malformed API key raises at construction. Wrap it so the API returns
+ # the friendly 400 instead of a 500.
+ raise PromptSuggestionError("model client unavailable") from e
def _parse_llm_output(text: str) -> dict[str, Any]:
@@ -615,7 +621,16 @@ def generate_prompt_suggestion(
# The change list is the source of truth for "did anything meaningful change": dict equality trips on
# keys a proposer always injects (e.g. a defaulted allow_inconclusive) that the stored config never had.
status = SuggestionStatus.NO_CHANGE if not changes else SuggestionStatus.PENDING
- up = len([o for o in observations if _label(o).is_correct])
+ # Count the full rated set, not the capped briefing slice: the agent can page through every rated
+ # session via its tools, and the UI shows these next to chart totals computed over all ratings.
+ label_counts = ReplayObservation.objects.filter(
+ team_id=scanner.team_id,
+ scanner_id=scanner.id,
+ status=ObservationStatus.SUCCEEDED,
+ label__isnull=False,
+ ).aggregate(up=Count("id", filter=Q(label__is_correct=True)), total=Count("id"))
+ up = label_counts["up"] or 0
+ down = (label_counts["total"] or 0) - up
with transaction.atomic():
# Serialize per scanner: a manual generate racing the sweep refresh must not leave two pending rows.
ReplayScanner.objects.select_for_update().filter(team_id=scanner.team_id, pk=scanner.pk).first()
@@ -634,7 +649,7 @@ def generate_prompt_suggestion(
rationale=str(llm_output.get("rationale", "")).strip(),
status=status,
based_on_up=up,
- based_on_down=len(observations) - up,
+ based_on_down=down,
labels_fingerprint=labels_fingerprint(scanner),
scanner_version=scanner.scanner_version,
created_by=user,
diff --git a/products/replay_vision/backend/proposers/monitor.py b/products/replay_vision/backend/proposers/monitor.py
index f2f4e952db76..2acf95af0d25 100644
--- a/products/replay_vision/backend/proposers/monitor.py
+++ b/products/replay_vision/backend/proposers/monitor.py
@@ -36,7 +36,10 @@ class MonitorProposer:
return _SYSTEM_PROMPT
def grounding(self, scanner: "ReplayScanner") -> str:
- return ""
+ # The schema requires echoing allow_inconclusive, so the briefing must state the current value.
+ # Without it the model guesses and writes rationales claiming flag changes that are no-ops.
+ allow = bool((scanner.scanner_config or {}).get("allow_inconclusive", False))
+ return f"Current allow_inconclusive: {str(allow).lower()}."
def to_config_patch(self, llm_output: dict[str, Any], base_config: dict[str, Any]) -> dict[str, Any]:
config = dict(base_config)
diff --git a/products/replay_vision/backend/proposers/scorer.py b/products/replay_vision/backend/proposers/scorer.py
index d31aac3eea1d..b3e1d964bc01 100644
--- a/products/replay_vision/backend/proposers/scorer.py
+++ b/products/replay_vision/backend/proposers/scorer.py
@@ -45,7 +45,12 @@ class ScorerProposer:
return _SYSTEM_PROMPT
def grounding(self, scanner: "ReplayScanner") -> str:
- return ""
+ # The schema requires echoing the scale, so the briefing must state the current one.
+ scale = (scanner.scanner_config or {}).get("scale") or {}
+ if not scale:
+ return ""
+ label = f" ({scale['label']})" if scale.get("label") else ""
+ return f"Current scale: {scale.get('min')} to {scale.get('max')}{label}."
def to_config_patch(self, llm_output: dict[str, Any], base_config: dict[str, Any]) -> dict[str, Any]:
config = dict(base_config)
diff --git a/products/replay_vision/backend/proposers/summarizer.py b/products/replay_vision/backend/proposers/summarizer.py
index e64d7c72b158..1ec42f9fbc78 100644
--- a/products/replay_vision/backend/proposers/summarizer.py
+++ b/products/replay_vision/backend/proposers/summarizer.py
@@ -38,7 +38,9 @@ class SummarizerProposer:
return _SYSTEM_PROMPT
def grounding(self, scanner: "ReplayScanner") -> str:
- return ""
+ # The schema requires echoing the length, so the briefing must state the current one.
+ length = (scanner.scanner_config or {}).get("length", "medium")
+ return f"Current summary length: {length}."
def to_config_patch(self, llm_output: dict[str, Any], base_config: dict[str, Any]) -> dict[str, Any]:
config = dict(base_config)
diff --git a/products/replay_vision/backend/tag_suggestions.py b/products/replay_vision/backend/tag_suggestions.py
index 551f875556b3..38e173e641a9 100644
--- a/products/replay_vision/backend/tag_suggestions.py
+++ b/products/replay_vision/backend/tag_suggestions.py
@@ -301,11 +301,16 @@ def _generate(*, user_content: str, team_id: int, distinct_id: str) -> _LlmSugge
# Inline the key resolution (rather than importing the temporal helper) to keep this off the temporal import path.
api_key = settings.REPLAY_VISION_GEMINI_API_KEY or settings.GEMINI_API_KEY
# Runs inline on the interactive request path, so a hung provider call must time out.
- client = genai.Client(
- api_key=api_key,
- posthog_client=posthoganalytics.default_client,
- http_options={"timeout": _MODEL_CALL_TIMEOUT_MS},
- )
+ try:
+ client = genai.Client(
+ api_key=api_key,
+ posthog_client=posthoganalytics.default_client,
+ http_options={"timeout": _MODEL_CALL_TIMEOUT_MS},
+ )
+ except Exception as e:
+ # A missing or malformed API key raises at construction. Wrap it so the API returns
+ # the friendly 503 instead of a 500.
+ raise SuggestionError("model client unavailable") from e
config = GenerateContentConfig(
system_instruction=_SYSTEM_PROMPT,
response_mime_type="application/json",
diff --git a/products/replay_vision/backend/tests/test_prompt_suggestions_api.py b/products/replay_vision/backend/tests/test_prompt_suggestions_api.py
index ff344aa0d645..356c30004cfb 100644
--- a/products/replay_vision/backend/tests/test_prompt_suggestions_api.py
+++ b/products/replay_vision/backend/tests/test_prompt_suggestions_api.py
@@ -100,6 +100,40 @@ class TestPromptSuggestions(_VisionAPITestCase):
self.assertEqual(resp.status_code, 400)
self.assertFalse(ReplayScannerPromptSuggestion.objects.exists())
+ def test_based_on_counts_cover_all_ratings_beyond_briefing_cap(self) -> None:
+ # The briefing is capped to the most recent rated sessions, but based_on_* is shown in the UI
+ # next to chart totals over ALL ratings, and the agent can page through the full set via tools.
+ self._create_rated_observation("sess-1", True)
+ self._create_rated_observation("sess-2", True)
+ self._create_rated_observation("sess-3", False, "should be yes")
+
+ with patch("products.replay_vision.backend.prompt_suggestions._MAX_RATED_SESSIONS", 2):
+ resp = self.client.post(self._suggestions_url("generate/"))
+
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.assertEqual(resp.json()["based_on_up"], 2)
+ self.assertEqual(resp.json()["based_on_down"], 1)
+
+ def test_generate_returns_friendly_error_when_model_client_unavailable(self) -> None:
+ # A missing/malformed Gemini key raises at client construction, before any model call.
+ # Run the real generation paths so the failure propagates as it would in production.
+ self._create_rated_observation("sess-1", False, "should be yes")
+ self.agentic_patcher.stop()
+ self.generate_patcher.stop()
+ try:
+ with patch(
+ "products.replay_vision.backend.prompt_suggestions.genai.Client",
+ side_effect=ValueError("Missing key inputs argument!"),
+ ):
+ resp = self.client.post(self._suggestions_url("generate/"))
+ finally:
+ self.mock_agentic = self.agentic_patcher.start()
+ self.mock_generate = self.generate_patcher.start()
+
+ self.assertEqual(resp.status_code, 400)
+ self.assertIn("Couldn't generate a suggestion right now", resp.json()["detail"])
+ self.assertFalse(ReplayScannerPromptSuggestion.objects.exists())
+
def test_quality_flag_off_hides_endpoints(self) -> None:
# `replay-vision-quality` gates the sub-feature even when product-level `replay-vision` is on.
self._create_rated_observation("sess-1", True)
diff --git a/products/replay_vision/backend/tests/test_proposers.py b/products/replay_vision/backend/tests/test_proposers.py
index 133004cde34d..777651cb7382 100644
--- a/products/replay_vision/backend/tests/test_proposers.py
+++ b/products/replay_vision/backend/tests/test_proposers.py
@@ -2,7 +2,7 @@ from typing import Any
import pytest
-from products.replay_vision.backend.models.replay_scanner import ScannerType
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
from products.replay_vision.backend.proposers import get_proposer
from products.replay_vision.backend.proposers.base import ConfigChange
from products.replay_vision.backend.tests.test_api import _VisionAPITestCase
@@ -192,6 +192,26 @@ def test_summarizer_patch_defends_against_missing_or_invalid_length() -> None:
)
+ "scanner_type,config,expected",
+ [
+ ("monitor", {"prompt": "p"}, "allow_inconclusive: false"),
+ ("monitor", {"prompt": "p", "allow_inconclusive": True}, "allow_inconclusive: true"),
+ ("scorer", {"prompt": "p", "scale": {"min": 1, "max": 5, "label": "frustration"}}, "1 to 5 (frustration)"),
+ ("scorer", {"prompt": "p", "scale": {"min": 0, "max": 10}}, "0 to 10."),
+ ("summarizer", {"prompt": "p"}, "length: medium"),
+ ("summarizer", {"prompt": "p", "length": "long"}, "length: long"),
+ ],
+)
+def test_grounding_states_current_type_specific_config(
+ scanner_type: str, config: dict[str, Any], expected: str
+) -> None:
+ # The output schemas force the model to echo these fields, so the briefing must state their
+ # current values. Without them the model guesses and writes rationales claiming no-op changes.
+ scanner = ReplayScanner(scanner_config=config)
+ assert expected in get_proposer(scanner_type).grounding(scanner)
+
+
class TestClassifierGrounding(_VisionAPITestCase):
def test_grounding_reflects_own_config_but_omits_sibling_vocabularies(self) -> None:
# grounding() must reflect the scanner's own config (proving it calls into tag_suggestions rather
diff --git a/products/replay_vision/backend/tests/test_tag_suggestions.py b/products/replay_vision/backend/tests/test_tag_suggestions.py
index 9aa19801e1e9..f0547670a819 100644
--- a/products/replay_vision/backend/tests/test_tag_suggestions.py
+++ b/products/replay_vision/backend/tests/test_tag_suggestions.py
@@ -127,6 +127,17 @@ class TestSuggestTagsEndpoint(_VisionAPITestCase):
# The raw error must not leak to the client.
assert "model down" not in resp.content.decode()
+ @patch(
+ "products.replay_vision.backend.tag_suggestions.genai.Client",
+ side_effect=ValueError("Missing key inputs argument!"),
+ )
+ def test_client_construction_failure_is_a_clean_503(self, _mock):
+ # A missing/malformed Gemini key raises at construction, before any model call.
+ # It must wrap into SuggestionError so the endpoint 503s instead of 500ing.
+ resp = self.client.post(self.suggest_url, data={"prompt": "categorize by intent"}, format="json")
+
+ assert resp.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+
def test_unknown_scanner_id_is_not_found(self):
resp = self.client.post(
self.suggest_url,
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQualityTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQualityTab.tsx
index 1b46be752d07..30aaf72d9cd7 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQualityTab.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQualityTab.tsx
@@ -44,10 +44,11 @@ import { OBSERVATION_CREDITS_BY_MODEL } from '../types'
import { ConfigChangeCards } from './ConfigChangeCards'
import { versionTag } from './ScannerObservationsTable'
-const RATED_FILTER_OPTIONS: { value: RatedFilterValue; label: string }[] = [
- { value: 'unrated', label: 'Unrated' },
- { value: 'rated', label: 'Rated' },
- { value: 'all', label: 'All' },
+// data-attr must live on each option: LemonSegmentedButton renders no element of its own that takes one.
+const RATED_FILTER_OPTIONS: { value: RatedFilterValue; label: string; 'data-attr': string }[] = [
+ { value: 'unrated', label: 'Unrated', 'data-attr': 'vision-quality-rated-filter-unrated' },
+ { value: 'rated', label: 'Rated', 'data-attr': 'vision-quality-rated-filter-rated' },
+ { value: 'all', label: 'All', 'data-attr': 'vision-quality-rated-filter-all' },
]
const SUGGESTION_STATUS_TAGS: Record<string, { type: LemonTagType; label: string; tooltip: string }> = {
@@ -242,7 +243,12 @@ function SuggestionEvaluationPanel({
title: 'Session',
key: 'session',
render: (_, result) => (
- <Link to={urls.replaySingle(result.session_id)} className="font-mono">
+ // New tab like the results table links, so reviewers keep their place.
+ <Link
+ to={urls.replaySingle(result.session_id)}
+ target="_blank"
+ className="font-mono"
+ >
{result.session_id.slice(0, 8)}…
</Link>
),
@@ -575,16 +581,18 @@ function VersionBadgeBridge({
type ChartMode = 'session' | 'rating'
-const CHART_MODE_OPTIONS: { value: ChartMode; label: string; tooltip: string }[] = [
+const CHART_MODE_OPTIONS: { value: ChartMode; label: string; tooltip: string; 'data-attr': string }[] = [
{
value: 'session',
label: 'By session day',
tooltip: 'Ratings placed on the day the session was scanned: how scanner quality trends over time',
+ 'data-attr': 'vision-quality-chart-mode-session',
},
{
value: 'rating',
label: 'By rating day',
tooltip: "Ratings placed on the day they were given or changed: the team's rating activity",
+ 'data-attr': 'vision-quality-chart-mode-rating',
},
]
@@ -644,13 +652,7 @@ function RatingsOverTimePanel({ scannerId }: { scannerId: string }): JSX.Element
: `last ${LABEL_CHART_DAYS} days`}
</span>
<div className="ml-auto">
- <LemonSegmentedButton
- size="xsmall"
- value={mode}
- onChange={setMode}
- options={CHART_MODE_OPTIONS}
- data-attr="vision-quality-chart-mode"
- />
+ <LemonSegmentedButton size="xsmall" value={mode} onChange={setMode} options={CHART_MODE_OPTIONS} />
</div>
</div>
{versionAccuracy.length > 0 && (
@@ -951,7 +953,6 @@ export function ScannerQualityTab({ scannerId }: { scannerId: string }): JSX.Ele
value={ratedFilter}
onChange={setRatedFilter}
options={RATED_FILTER_OPTIONS}
- data-attr="vision-quality-rated-filter"
/>
</div>
</div>
@@ -970,6 +971,9 @@ export function ScannerQualityTab({ scannerId }: { scannerId: string }): JSX.Ele
entryCount: total,
onForward: () => setPage(page + 1),
onBackward: () => setPage(page - 1),
+ // Page state lives in scannerQualityLogic; without this the control also pushes a
+ // `page` URL param that nothing reads and that goes stale on filter or tab changes.
+ useUrl: false,
}}
sorting={sort}
onSort={(next) => setSort(next)}