: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): name the signal in the what-to-watch reason (#104118)
Kim Svatos Dugan1618ac394587
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5d377d5b1aa0..ab5fbf88621b 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10332,6 +10332,10 @@ snapshots:hash: v1.k794b7964.c8b63e7c03105a6a22c7dfecc5fa98afb410af14180977eeb9907c2e57f43e29.9d0B-LDyKHrQ75wpveOo913SMTZvi2fe4RTJOrFtDM0scenes-app-replay-vision--home-watch-feed-empty--light:hash: v1.k794b7964.33393d260f0654e59dbc209d6052c2b0730dfc6e8f59925406cd3a9349569980.63xRgoQrVu1PM7n1sBaVx6QV7Otc_rKCusdfHhsGuBU+ scenes-app-replay-vision--home-watch-feed-only-newest--dark:+ hash: v1.k794b7964.c663fda6f931ec3eb45817b2e6c1a5ce64b76a796aa791fa43809fc8bf76a89d.Stuf9VxRo6CSfm7JlG9zyVo-dgYH-MWGbu-hdjIG3E0+ scenes-app-replay-vision--home-watch-feed-only-newest--light:+ hash: v1.k794b7964.2970158f57cd96907771a0fd8e05e250013df87cf25ad8c8c9358ca1c11cac30.TncjzQ2-615RVwvIXyzAEyKjHKY2sDJqUke0ERJpdzsscenes-app-replay-vision--observation-detail--dark:hash: v1.k794b7964.e9fd7c14ee1899c90ba01049012a8d9947f013869b8ec7d767b7db2220d46166.XZIczm04vBGXxRP7z-rzHaqy34GQDRXXfTrEhICqxi0scenes-app-replay-vision--observation-detail--light:diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 5525ccb5da0e..7c50f6179bec 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -1457,7 +1457,11 @@ class WatchFeedQuerySerializer(serializers.Serializer):default=WATCH_FEED_DEFAULT_LIMIT,min_value=1,max_value=WATCH_FEED_MAX_LIMIT,- help_text=f"Feed items to return, at most {WATCH_FEED_MAX_LIMIT}. The feed is bounded, not paginated.",+ help_text=(+ f"Ceiling on feed items to return, at most {WATCH_FEED_MAX_LIMIT}. The feed is bounded, not "+ "paginated, and routinely returns far fewer: a window is not padded to this number with "+ "clips that carry no finding."+ ),)def validate_tags(self, value: str) -> list[str]:@@ -1473,6 +1477,15 @@ class WatchFeedQuerySerializer(serializers.Serializer):raise serializers.ValidationError("Scanner ids must be UUIDs.")+class WatchFeedSignalSerializer(serializers.Serializer):+ """One signal an observation raised, named rather than counted."""++ problem_type = serializers.CharField(help_text="Issue type: `bug`, `crash`, `design_flaw`, or `ux_friction`.")+ headline = serializers.CharField(+ help_text="The finding in a few words, written by the scan. The full description lives on the signal itself."+ )++class WatchFeedReasonSerializer(serializers.Serializer):"""Machine-readable reason an observation made the feed; the frontend renders the copy."""@@ -1500,6 +1513,15 @@ class WatchFeedReasonSerializer(serializers.Serializer):"signal in the order raised, for `signal_emitted`. Absent on signals scanned before this shipped."),)+ signals = WatchFeedSignalSerializer(+ many=True,+ required=False,+ help_text=(+ "Each emitted signal in the order raised, for `signal_emitted`. Carries what the card needs to name "+ "the findings instead of counting them. Absent on sessions scanned before this shipped, which carry "+ "`problem_types` alone."+ ),+ )verdict = serializers.CharField(required=False, allow_null=True, help_text="The monitor's answer, for `unusual_verdict`.")@@ -1551,9 +1573,10 @@ class WatchFeedResponseSerializer(serializers.Serializer):results = WatchFeedItemSerializer(many=True,help_text=(- "Succeeded observations in the window worth watching, most interesting first: signal emitters, "- "then type-specific hits, then unviewed before viewed, then the scan's own notability judgment, "- "then prose that reads as friction, then newest."+ "Succeeded observations in the window worth watching, most interesting first, each carrying the "+ "reason it ranked. Every observation that carries a finding is returned; observations that carry "+ "none (`unviewed_recent`, `recent`) are returned only to pad a near-empty feed to three items, "+ "so a quiet window answers with a handful of rows rather than a full page of newest clips."),)diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.pyindex 017907324f8f..d127a5fece50 100644--- a/products/replay_vision/backend/temporal/__init__.py+++ b/products/replay_vision/backend/temporal/__init__.py@@ -16,6 +16,7 @@ from products.replay_vision.backend.temporal.activities import (emit_classifier_tags_activity,emit_observation_event_activity,emit_observation_signal_activity,+ emit_observation_signal_summaries_activity,emit_observation_signals_activity,ensure_session_asset_activity,fetch_session_events_activity,@@ -107,6 +108,7 @@ ACTIVITIES: list[Callable[..., Any]] = [emit_classifier_tags_activity,emit_observation_event_activity,emit_observation_signal_activity,+ emit_observation_signal_summaries_activity,emit_observation_signals_activity,cleanup_gemini_file_activity,prepare_observation_thumbnail_activity,@@ -168,6 +170,7 @@ __all__ = ["emit_classifier_tags_activity","emit_observation_event_activity","emit_observation_signal_activity",+ "emit_observation_signal_summaries_activity","emit_observation_signals_activity","ensure_session_asset_activity","fetch_session_events_activity",diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.pyindex 86b772945be6..23f266e627d3 100644--- a/products/replay_vision/backend/temporal/activities/__init__.py+++ b/products/replay_vision/backend/temporal/activities/__init__.py@@ -22,6 +22,7 @@ from products.replay_vision.backend.temporal.activities.emit_classifier_tags impfrom products.replay_vision.backend.temporal.activities.emit_observation_event import emit_observation_event_activityfrom products.replay_vision.backend.temporal.activities.emit_observation_signal import (emit_observation_signal_activity,+ emit_observation_signal_summaries_activity,emit_observation_signals_activity,)from products.replay_vision.backend.temporal.activities.ensure_session_asset import ensure_session_asset_activity@@ -82,6 +83,7 @@ __all__ = ["emit_classifier_tags_activity","emit_observation_event_activity","emit_observation_signal_activity",+ "emit_observation_signal_summaries_activity","emit_observation_signals_activity","ensure_session_asset_activity","fetch_session_events_activity",diff --git a/products/replay_vision/backend/temporal/activities/emit_observation_signal.py b/products/replay_vision/backend/temporal/activities/emit_observation_signal.pyindex be87b4335803..1279efbe188f 100644--- a/products/replay_vision/backend/temporal/activities/emit_observation_signal.py+++ b/products/replay_vision/backend/temporal/activities/emit_observation_signal.py@@ -11,7 +11,12 @@ from products.replay_vision.backend.temporal.decorators import track_activityfrom products.replay_vision.backend.temporal.metrics import record_side_effect_failurefrom products.replay_vision.backend.temporal.scanners.base import MIN_SIGNAL_CONFIDENCEfrom products.replay_vision.backend.temporal.state import load_scanner_llm_inputs-from products.replay_vision.backend.temporal.types import EmitObservationSignalInputs, ScannerLlmInputs, ScannerSnapshot+from products.replay_vision.backend.temporal.types import (+ EmitObservationSignalInputs,+ EmittedSignal,+ ScannerLlmInputs,+ ScannerSnapshot,+)from products.signals.backend.facade.api import emit_signallogger = structlog.get_logger(__name__)@@ -25,10 +30,10 @@ def _load_llm_inputs(observation_id: UUID) -> ScannerLlmInputs | None:return async_to_sync(load_scanner_llm_inputs)(str(observation_id))-def _emit_observation_signals(inputs: EmitObservationSignalInputs) -> list[str]:- """Emit the observation's side-mission findings as PostHog Signals; fails soft, returns the problem type- of each signal it actually emitted, in emission order. Findings below the confidence floor and findings- whose emission fails are left out, so the caller's count and types stay in step."""+def _emit_observation_signals(inputs: EmitObservationSignalInputs) -> list[EmittedSignal]:+ """Emit the observation's side-mission findings as PostHog Signals; fails soft, returns each signal it+ actually emitted, in emission order. Findings below the confidence floor and findings whose emission+ fails are left out, so the caller's count and types stay in step."""try:observation = (ReplayObservation.objects.filter(pk=inputs.observation_id, team_id=inputs.team_id)@@ -71,7 +76,7 @@ def _emit_observation_signals(inputs: EmitObservationSignalInputs) -> list[str]:base_extra["recording_duration"] = meta.duration_secondsbase_extra["recording_active_seconds"] = meta.active_seconds- emitted_problem_types: list[str] = []+ emitted: list[EmittedSignal] = []any_failed = Falsefor index, signal in enumerate(inputs.signals):if signal.confidence < MIN_SIGNAL_CONFIDENCE:@@ -96,9 +101,15 @@ def _emit_observation_signals(inputs: EmitObservationSignalInputs) -> list[str]:"url": signal.url,},)- emitted_problem_types.append(signal.problem_type)+ emitted.append(+ EmittedSignal(+ problem_type=signal.problem_type,+ headline=signal.headline,+ confidence=signal.confidence,+ )+ )# Findings go out one network call at a time, so beat between them.- activity.heartbeat({"emitted": len(emitted_problem_types), "index": index})+ activity.heartbeat({"emitted": len(emitted), "index": index})except Exception:# One bad finding never blocks the rest; signals are advisory.any_failed = True@@ -110,7 +121,7 @@ def _emit_observation_signals(inputs: EmitObservationSignalInputs) -> list[str]:if any_failed:# Per activity, not per finding, so the counter is comparable to the other effects.record_side_effect_failure("signal")- return emitted_problem_types+ return emittedexcept Exception:# Never fail the observation over emission. Counted here because the swallow means# track_activity sees a success.@@ -123,13 +134,21 @@ def _emit_observation_signals(inputs: EmitObservationSignalInputs) -> list[str]:@track_activity(side_effect="signal")def emit_observation_signal_activity(inputs: EmitObservationSignalInputs) -> int:"""Legacy count-returning entry point. Kept so in-flight workflow histories that scheduled it before the- problem-types patch still decode an int on replay; new executions use emit_observation_signals_activity."""+ problem-types patch still decode an int on replay; new executions use the summaries activity below."""return len(_emit_observation_signals(inputs))@activity.defn@track_activity(side_effect="signal")def emit_observation_signals_activity(inputs: EmitObservationSignalInputs) -> list[str]:- """Emit the observation's side-mission findings and return each emitted signal's problem type, in emission- order — the watch feed counts them to name the kinds of issue a session raised."""+ """Legacy problem-type-returning entry point. Kept for the same reason as the count-returning one above:+ histories that scheduled it before the summaries patch must still decode a list of strings on replay."""+ return [signal.problem_type for signal in _emit_observation_signals(inputs)]+++@track_activity(side_effect="signal")+def emit_observation_signal_summaries_activity(inputs: EmitObservationSignalInputs) -> list[EmittedSignal]:+ """Emit the observation's side-mission findings and return each emitted signal, in emission order — the+ watch feed names them on the card and weighs them by confidence when it ranks."""return _emit_observation_signals(inputs)diff --git a/products/replay_vision/backend/temporal/scanners/base.py b/products/replay_vision/backend/temporal/scanners/base.pyindex c2f8f9e1a2f1..66737ab8a160 100644--- a/products/replay_vision/backend/temporal/scanners/base.py+++ b/products/replay_vision/backend/temporal/scanners/base.py@@ -37,6 +37,9 @@ Segment = Annotated[TextSegment | ChipSegment, Field(discriminator="kind")]# The side-mission calibration floor: templated into the prompt and enforced at emission.MIN_SIGNAL_CONFIDENCE = 0.4+# The watch feed lists up to three headlines on one line, so an overlong one reflows the whole card.+SIGNAL_HEADLINE_MAX_LENGTH = 80+# Stable step names the producer (`mission_steps`) and consumers (`assemble`) key on.STEP_CORE = "core"STEP_SIGNALS = "signals"@@ -60,6 +63,14 @@ class SignalFinding(BaseModel, frozen=True):problem_type: Literal["bug", "crash", "design_flaw", "ux_friction"] = Field(description="The kind of issue: `bug`, `crash`, `design_flaw`, or `ux_friction`.")+ headline: str = Field(+ description=(+ "The issue in 8 words or fewer, for a feed card that lists several findings side by side. Name the "+ "control, the page, or the product step it happened on, so the line reads on its own without the "+ "`description`. Never copy text the user typed and never name a person — unlike the description, "+ "this line is shown to a whole team out of context. Sentence case, no final period."+ )+ )start_time: int = Field(ge=0,description=(@@ -97,6 +108,14 @@ class SignalFinding(BaseModel, frozen=True):# the removal (or the model) leaves so the prose stays clean.return re.sub(r"\s{2,}", " ", TIMESTAMP_CITATION_RE.sub("", value)).strip()+ @field_validator("headline", mode="after")+ @classmethod+ def _shorten_headline(cls, value: str) -> str:+ # Same timestamp-marker leak as the description, plus a hard length bound — the prompt asks for 8 words+ # and the model sometimes answers with a sentence, which would reflow the card it lands on.+ cleaned = re.sub(r"\s{2,}", " ", TIMESTAMP_CITATION_RE.sub("", value)).strip()+ return cleaned[:SIGNAL_HEADLINE_MAX_LENGTH].rstrip()+class SignalsResponse(BaseModel, frozen=True):"""The signals side-mission turn's structured output — one entry per video-only issue, usually empty."""diff --git a/products/replay_vision/backend/temporal/scanners/prompts/signals_step.jinja b/products/replay_vision/backend/temporal/scanners/prompts/signals_step.jinjaindex 1192c9e8a42a..460e91c997cf 100644--- a/products/replay_vision/backend/temporal/scanners/prompts/signals_step.jinja+++ b/products/replay_vision/backend/temporal/scanners/prompts/signals_step.jinja@@ -7,6 +7,8 @@ The bar is deliberately high. Report a finding only when ALL of these hold:What makes a finding belong here is that you *saw* it: the `description` must lead with the on-screen detail. Corroboration from the event log *raises* your confidence — call `get_events_around` at the finding's video time to confirm an `$exception`, a failed request, or a `$rageclick`/`$dead_click` backs up what you saw — but never report an issue you only know about from the events.+Write the `headline` as the shortest line that names the defect — 8 words or fewer, naming the control, page, or product step. A reader sees it next to two other headlines with no room for context, so "checkout button does nothing" works and "there was a problem" does not. Never copy text the user typed into the product, and never name a person: the headline travels further than the description does.+Write the `description` as plain prose with no timestamp references — no `(t …)` markers, no timestamps, no "at N seconds", no event IDs. The timing belongs in `start_time` and `end_time`, not the text.One recording can surface more than one distinct defect; list each separately. Don't repeat the earlier turns' conclusions. Skip anything below {{ min_signal_confidence }} confidence.diff --git a/products/replay_vision/backend/temporal/types.py b/products/replay_vision/backend/temporal/types.pyindex e8308d58f449..ea1192e28eba 100644--- a/products/replay_vision/backend/temporal/types.py+++ b/products/replay_vision/backend/temporal/types.py@@ -36,6 +36,16 @@ class VerificationRecord(BaseModel, frozen=True):skipped_reason: str | None = None+class EmittedSignal(BaseModel, frozen=True):+ """One side-mission finding that reached the Signals product. Carries what a reader needs to name the+ finding and what the ranking needs to weigh it, and deliberately not the finding's full description: that+ prose quotes on-screen text, which has no place on a feed card seen out of context."""++ problem_type: str+ headline: str+ confidence: float = Field(ge=0, le=1)++class ScannerResult(BaseModel, frozen=True):"""Result data of a completed observation, persisted into `ReplayObservation.scanner_result`."""@@ -44,6 +54,10 @@ class ScannerResult(BaseModel, frozen=True):# The problem type of each signal actually emitted, in emission order and with repeats kept, so the# watch feed can count the kinds of issue a row carries. Empty on non-signal rows and on old rows.signal_problem_types: list[str] = Field(default_factory=list)+ # The same signals with their headline and confidence, so the feed can name them rather than count them+ # and can rank a weak finding below a strong one. Empty on non-signal rows and on rows scanned before+ # this shipped; `signal_problem_types` stays because those older rows carry only it.+ signal_summaries: list[EmittedSignal] = Field(default_factory=list)verification: VerificationRecord | None = Nonediff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.pyindex 7e997a0ef833..9520c2e2748f 100644--- a/products/replay_vision/backend/temporal/workflow.py+++ b/products/replay_vision/backend/temporal/workflow.py@@ -37,6 +37,7 @@ from products.replay_vision.backend.temporal.activities import (emit_classifier_tags_activity,emit_observation_event_activity,emit_observation_signal_activity,+ emit_observation_signal_summaries_activity,emit_observation_signals_activity,ensure_session_asset_activity,fetch_session_events_activity,@@ -75,6 +76,7 @@ from products.replay_vision.backend.temporal.types import (EmitClassifierTagsInputs,EmitObservationEventInputs,EmitObservationSignalInputs,+ EmittedSignal,EnsureSessionAssetInputs,EnsureSessionAssetOutput,FetchSessionEventsInputs,@@ -355,6 +357,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):self._advance_phase("finalizing")signals_count = 0signal_problem_types: list[str] = []+ signal_summaries: list[EmittedSignal] = []if call_output.signals:emit_inputs = EmitObservationSignalInputs(team_id=inputs.team_id,@@ -362,15 +365,26 @@ class ApplyScannerWorkflow(PostHogWorkflow):exported_asset_id=asset_result.asset_id,signals=call_output.signals,)- # The signals-returning activity reports the problem type of each signal it actually emitted,- # so the count derives from that list. A pre-patch history scheduled the count-returning- # activity, so the else branch keeps calling it and in-flight scans replay cleanly. Both fail- # soft (emit nothing extra on error), so there is nothing to retry; the local catch covers- # Temporal-level failures (timeout, worker loss) — emission is advisory and must never demote- # an otherwise-successful observation. 30s once truncated the tail on a slow facade, so give- # it 2 minutes; retries are safe because each finding carries a deterministic idempotency key.+ # The summaries activity reports every signal it actually emitted, so the count and the+ # problem types both derive from that list. The two branches below it schedule the activity+ # an older history recorded — a count, then a list of problem types — so in-flight scans+ # replay cleanly. All three fail soft (emit nothing extra on error), so there is nothing to+ # retry; the local catch covers Temporal-level failures (timeout, worker loss) — emission is+ # advisory and must never demote an otherwise-successful observation. 30s once truncated the+ # tail on a slow facade, so give it 2 minutes; retries are safe because each finding carries+ # a deterministic idempotency key.try:- if wf.patched("replay-vision-emitted-signal-problem-types"):+ if wf.patched("replay-vision-emitted-signal-summaries"):+ signal_summaries = await wf.execute_activity(+ emit_observation_signal_summaries_activity,+ emit_inputs,+ start_to_close_timeout=dt.timedelta(minutes=2),+ heartbeat_timeout=dt.timedelta(seconds=30),+ retry_policy=common.RetryPolicy(maximum_attempts=3),+ )+ signal_problem_types = [signal.problem_type for signal in signal_summaries]+ signals_count = len(signal_summaries)+ elif wf.patched("replay-vision-emitted-signal-problem-types"):signal_problem_types = await wf.execute_activity(emit_observation_signals_activity,emit_inputs,@@ -399,6 +413,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):model_output=call_output.model_output,signals_count=signals_count,signal_problem_types=signal_problem_types,+ signal_summaries=signal_summaries,verification=call_output.verification,),),diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex d9266a99c633..63d5501a676c 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -4277,7 +4277,7 @@ class TestWatchFeedAPI(_VisionAPITestCase):"signals_count": signals,}- def test_ranks_signal_then_hit_then_friction_then_recency_with_reasons(self) -> None:+ def test_ranks_signal_then_hit_then_friction_and_drops_the_rest(self) -> None:scanner = self._create_scanner(name="m")summarizer = self._create_scanner(name="s", scanner_type=ScannerType.SUMMARIZER, scanner_config={"prompt": "p", "length": "short"}@@ -4306,14 +4306,14 @@ class TestWatchFeedAPI(_VisionAPITestCase):resp = self.client.get(self.feed_url)self.assertEqual(resp.status_code, 200, resp.json())items = resp.json()["results"]+ # Three findings reach the floor, so the two rows that carry nothing are left out entirely.self.assertEqual([item["observation"]["session_id"] for item in items],- ["signal", "hit", "friction-sess", "plain-new", "plain-old"],+ ["signal", "hit", "friction-sess"],)self.assertEqual(items[0]["reason"], {"kind": "signal_emitted", "signals_count": 2})self.assertEqual(items[1]["reason"], {"kind": "verdict_yes"})self.assertEqual(items[2]["reason"], {"kind": "friction"})- self.assertEqual(items[3]["reason"], {"kind": "unviewed_recent"})assert plain_new and hit and signal and plain_olddef test_signal_reason_carries_the_persisted_problem_types(self) -> None:@@ -4334,6 +4334,177 @@ class TestWatchFeedAPI(_VisionAPITestCase):self.assertEqual(reason["kind"], "signal_emitted")self.assertEqual(reason["problem_types"], ["bug", "bug", "crash"])+ def test_signal_reason_names_each_signal(self) -> None:+ # A count told a reader nothing, so the row carries the scan's own headline per finding. The+ # confidence rides the row too, but it ranks the row rather than saying anything to a reader.+ scanner = self._create_scanner(name="m")+ self._succeeded_observation(+ scanner,+ "signal",+ 10,+ {+ "model_output": {"scanner_type": "monitor", "verdict": "no", "reasoning": "r", "confidence": 0.9},+ "signals_count": 2,+ "signal_problem_types": ["bug", "ux_friction"],+ "signal_summaries": [+ {"problem_type": "bug", "headline": "Checkout button does nothing", "confidence": 0.9},+ {"problem_type": "ux_friction", "headline": "Search results load twice", "confidence": 0.6},+ ],+ },+ )+ reason = self.client.get(self.feed_url).json()["results"][0]["reason"]+ self.assertEqual(reason["kind"], "signal_emitted")+ self.assertEqual(+ reason["signals"],+ [+ {"problem_type": "bug", "headline": "Checkout button does nothing"},+ {"problem_type": "ux_friction", "headline": "Search results load twice"},+ ],+ )++ def test_signal_reason_omits_the_signals_on_rows_scanned_before_headlines(self) -> None:+ # Those rows carry a count and the types alone, and the card falls back to counting them.+ scanner = self._create_scanner(name="m")+ self._succeeded_observation(scanner, "signal", 10, self._monitor_result("no", signals=2))+ reason = self.client.get(self.feed_url).json()["results"][0]["reason"]+ self.assertEqual(reason["kind"], "signal_emitted")+ self.assertNotIn("signals", reason)++ def _friction_result(self) -> dict[str, Any]:+ return {+ "model_output": {+ "scanner_type": "summarizer",+ "title": "Checkout gone wrong",+ "summary": "The user hit an error at checkout and retried payment twice.",+ "confidence": 0.9,+ },+ "signals_count": 0,+ }++ def test_signal_rows_never_hold_more_than_their_share_of_the_findings(self) -> None:+ # Signals corroborate across sessions, so a scanner raising them on every session used to crowd the+ # other findings out of the feed. They are held against the other findings rather than against+ # padding, because padding no longer survives the trim.+ scanner = self._create_scanner(name="m")+ summarizer = self._create_scanner(+ name="s", scanner_type=ScannerType.SUMMARIZER, scanner_config={"prompt": "p", "length": "short"}+ )+ for i in range(6):+ self._succeeded_observation(scanner, f"signal-{i}", 10 + i, self._monitor_result("no", signals=1))+ self._succeeded_observation(summarizer, f"friction-{i}", 40 + i, self._friction_result())++ items = self.client.get(f"{self.feed_url}?limit=50").json()["results"]+ self.assertEqual(len(items), 12) # every finding is returned; the cap reorders, it never drops+ kinds = [item["reason"]["kind"] for item in items]+ self.assertEqual(kinds[0], "signal_emitted") # the best row leads whatever it is+ # Six signal rows cannot all fit under the share, so the last of them trail the feed. The share+ # governs everything up to there, which is the part a reader with a normal limit ever sees.+ interleaved = len(kinds) - kinds[::-1].index("friction")+ self.assertEqual(set(kinds[interleaved:]), {"signal_emitted"})+ self.assertEqual(kinds[:5].count("signal_emitted"), 2) # the share, exactly, over the first five+ # The lead is exempt, so the bound is the share or one card, whichever is larger.+ for length in range(2, interleaved + 1):+ prefix = kinds[:length]+ allowed = max(1, int(length * 0.4))+ self.assertLessEqual(prefix.count("signal_emitted"), allowed, f"prefix of {length}: {prefix}")++ def test_clips_that_carry_no_finding_are_dropped_once_the_feed_has_three(self) -> None:+ # The feed used to fill `limit` with whatever was newest, so a window with three findings returned+ # those three under seventeen clips that said only "new since you last looked".+ scanner = self._create_scanner(name="m")+ summarizer = self._create_scanner(+ name="s", scanner_type=ScannerType.SUMMARIZER, scanner_config={"prompt": "p", "length": "short"}+ )+ for i in range(3):+ self._succeeded_observation(summarizer, f"friction-{i}", 10 + i, self._friction_result())+ for i in range(9):+ self._succeeded_observation(scanner, f"plain-{i}", 40 + i, self._monitor_result("no"))++ items = self.client.get(f"{self.feed_url}?limit=50").json()["results"]+ self.assertEqual(+ [item["observation"]["session_id"] for item in items], ["friction-0", "friction-1", "friction-2"]+ )++ def test_every_finding_is_returned_however_many_there_are(self) -> None:+ # The floor pads a thin feed; it never caps a rich one.+ summarizer = self._create_scanner(+ name="s", scanner_type=ScannerType.SUMMARIZER, scanner_config={"prompt": "p", "length": "short"}+ )+ for i in range(10):+ self._succeeded_observation(summarizer, f"friction-{i}", 10 + i, self._friction_result())++ items = self.client.get(f"{self.feed_url}?limit=50").json()["results"]+ self.assertEqual(len(items), 10)+ self.assertEqual({item["reason"]["kind"] for item in items}, {"friction"})++ def test_a_thin_feed_is_padded_to_the_floor_rather_than_to_the_limit(self) -> None:+ # One finding alone reads as a broken feed, and twenty reads as noise, so the padding stops at three.+ scanner = self._create_scanner(name="m")+ summarizer = self._create_scanner(+ name="s", scanner_type=ScannerType.SUMMARIZER, scanner_config={"prompt": "p", "length": "short"}+ )+ self._succeeded_observation(summarizer, "friction-0", 5, self._friction_result())+ for i in range(9):+ self._succeeded_observation(scanner, f"plain-{i}", 40 + i, self._monitor_result("no"))++ items = self.client.get(f"{self.feed_url}?limit=50").json()["results"]+ self.assertEqual([item["reason"]["kind"] for item in items], ["friction", "unviewed_recent", "unviewed_recent"])++ def test_a_window_with_no_findings_returns_the_floor_rather_than_nothing(self) -> None:+ # A feed that empties whenever nothing is wrong reads as broken, so the newest clips still answer.+ scanner = self._create_scanner(name="m")+ for i in range(9):+ self._succeeded_observation(scanner, f"plain-{i}", 10 + i, self._monitor_result("no"))++ items = self.client.get(f"{self.feed_url}?limit=50").json()["results"]+ self.assertEqual([item["observation"]["session_id"] for item in items], ["plain-0", "plain-1", "plain-2"])++ def test_a_window_of_only_signals_still_returns_a_full_feed(self) -> None:+ # With nothing to interleave, the held rows fill the tail rather than vanishing from the feed.+ scanner = self._create_scanner(name="m")+ for i in range(5):+ self._succeeded_observation(scanner, f"signal-{i}", 10 + i, self._monitor_result("no", signals=1))++ items = self.client.get(f"{self.feed_url}?limit=50").json()["results"]+ self.assertEqual(+ [item["observation"]["session_id"] for item in items],+ ["signal-0", "signal-1", "signal-2", "signal-3", "signal-4"],+ )++ def test_a_wide_outlier_outranks_and_outlabels_a_weak_signal(self) -> None:+ # The reason names the strongest evidence now. A row used to read `signal_emitted` whenever it+ # carried a signal, even where a far wider outlier was the thing worth watching.+ scorer = self._create_scanner(+ name="sc", scanner_type=ScannerType.SCORER, scanner_config={"prompt": "p", "scale_max": 10}+ )++ def _scored(session_id: str, minutes_ago: int, score: float, summaries: list[dict] | None = None) -> None:+ self._succeeded_observation(+ scorer,+ session_id,+ minutes_ago,+ {+ "model_output": {"scanner_type": "scorer", "score": score, "reasoning": "r", "confidence": 0.9},+ "signals_count": len(summaries or []),+ "signal_problem_types": [entry["problem_type"] for entry in summaries or []],+ "signal_summaries": summaries or [],+ },+ )++ for i in range(6):+ _scored(f"usual-{i}", 30 + i, 5.0 + (i % 2) * 0.1)+ _scored("outlier", 20, 10.0)+ _scored(+ "weak-signal",+ 10,+ 5.0,+ [{"problem_type": "bug", "headline": "Tooltip sits behind the header", "confidence": 0.45}],+ )++ items = self.client.get(f"{self.feed_url}?limit=50").json()["results"]+ self.assertEqual(items[0]["observation"]["session_id"], "outlier")+ self.assertEqual(items[0]["reason"]["kind"], "outlier_score")+def test_minority_verdict_is_the_hit_regardless_of_prompt_polarity(self) -> None:# "Was the experience good?" answers yes almost always, so its rare "no" is the notable# one; a majority "yes" must not rank as a hit just for being yes.@@ -4666,9 +4837,10 @@ class TestWatchFeedAPI(_VisionAPITestCase):self.assertEqual(reasons["tag-rare"]["kind"], "rare_tag")self.assertEqual(reasons["tag-rare"]["tag"], "rare")self.assertEqual(reasons["sum-novel-sess"]["kind"], "novel_summary")- # Near-identical summaries are the baseline, not novel.- self.assertEqual(reasons["sum-0"]["kind"], "unviewed_recent")- self.assertEqual(reasons["score-0"]["kind"], "unviewed_recent")+ # Near-identical summaries are the baseline, not novel, and a row at the scanner's own average is+ # not an outlier. Neither earns a finding, so with three findings already in the feed both are gone.+ self.assertNotIn("sum-0", reasons)+ self.assertNotIn("score-0", reasons)def test_singleton_tag_is_rare_even_in_a_thin_window(self) -> None:# A pure share cutoff makes rarity impossible below 10 rows and then fire on every singletondiff --git a/products/replay_vision/backend/tests/test_call_scanner_provider.py b/products/replay_vision/backend/tests/test_call_scanner_provider.pyindex 541185e80abf..8c6e93ade0c2 100644--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py@@ -401,6 +401,7 @@ async def test_signal_timestamps_use_recording_duration()signal = SignalFinding(problem_type="bug",+ headline="Blank dialog blocks the editor",start_time=0,end_time=0,url="https://example.com/editor",diff --git a/products/replay_vision/backend/tests/test_scanners.py b/products/replay_vision/backend/tests/test_scanners.pyindex 57a3aa161484..32db2e67129b 100644--- a/products/replay_vision/backend/tests/test_scanners.py+++ b/products/replay_vision/backend/tests/test_scanners.py@@ -20,7 +20,12 @@ from products.replay_vision.backend.temporal.scanners import (SummarizerSummaryResponse,scanner_from_db,)-from products.replay_vision.backend.temporal.scanners.base import BaseScanner, SignalFinding, SignalsResponse+from products.replay_vision.backend.temporal.scanners.base import (+ SIGNAL_HEADLINE_MAX_LENGTH,+ BaseScanner,+ SignalFinding,+ SignalsResponse,+)from products.replay_vision.backend.temporal.scanners.summarizer import summary_embedding_textfrom products.replay_vision.backend.temporal.types import EventTable, ScannerCallOutput@@ -840,6 +845,7 @@ class TestSignalSideMission:# A complete, valid `signal` payload for round-trip tests._VALID_SIGNAL = {"problem_type": "bug",+ "headline": "Checkout CTA does nothing","start_time": 72,"end_time": 78,"url": "https://app.example.com/cart",@@ -960,3 +966,13 @@ class TestSignalSideMission:# The description is embedded for free-text search, so leaked `(t …)` markers must never reach it.signal = SignalFinding.model_validate({**self._VALID_SIGNAL, "description": raw})assert signal.description == clean++ def test_signal_headline_strips_markers_and_holds_its_length(self) -> None:+ # The headline shares the description's marker leak, and a watch feed card lists three of them on one+ # line, so a model that answers with a sentence instead of a phrase must not reflow the card.+ marked = SignalFinding.model_validate({**self._VALID_SIGNAL, "headline": "Checkout CTA (t 844) does nothing"})+ assert marked.headline == "Checkout CTA does nothing"++ long = SignalFinding.model_validate({**self._VALID_SIGNAL, "headline": "word " * 40})+ assert len(long.headline) <= SIGNAL_HEADLINE_MAX_LENGTH+ assert not long.headline.endswith(" ")diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex b11e638803fc..e1afa5221f9c 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -79,6 +79,7 @@ from products.replay_vision.backend.temporal.activities.emit_observation_event ifrom products.replay_vision.backend.temporal.activities.emit_observation_signal import (SIGNAL_WEIGHT,emit_observation_signal_activity,+ emit_observation_signal_summaries_activity,emit_observation_signals_activity,)from products.replay_vision.backend.temporal.activities.ensure_session_asset import ensure_session_asset_activity@@ -132,6 +133,7 @@ from products.replay_vision.backend.temporal.types import (EmitClassifierTagsInputs,EmitObservationEventInputs,EmitObservationSignalInputs,+ EmittedSignal,EnsureSessionAssetInputs,EnsureSessionAssetOutput,EventTable,@@ -3758,6 +3760,7 @@ class TestEmitObservationSignalActivity:def _signal(self, confidence: float = 0.8, **overrides) -> SignalFinding:defaults: dict = {"problem_type": "bug",+ "headline": "Checkout CTA does nothing","start_time": 72,"end_time": 78,"url": "https://app.example.com/cart",@@ -3980,6 +3983,7 @@ async def test_apply_scanner_workflow_emits_the_signal_finding() -> None:signals=[SignalFinding(problem_type="bug",+ headline="Checkout CTA does nothing",start_time=30,end_time=35,url="https://app.example.com/cart",@@ -3988,17 +3992,19 @@ async def test_apply_scanner_workflow_emits_the_signal_finding() -> None:)],),- emit_observation_signals_activity: ["bug"],+ emit_observation_signal_summaries_activity: [+ EmittedSignal(problem_type="bug", headline="Checkout CTA does nothing", confidence=0.8)+ ],},)await _run_workflow(_build_inputs(session_id="sess-sig", team_id=99), mocks)order = [fn for fn, _ in mocks.activity_calls]- assert order.index(call_scanner_provider_activity) < order.index(emit_observation_signals_activity)- assert order.index(emit_observation_signals_activity) < order.index(emit_observation_event_activity)+ assert order.index(call_scanner_provider_activity) < order.index(emit_observation_signal_summaries_activity)+ assert order.index(emit_observation_signal_summaries_activity) < order.index(emit_observation_event_activity)- signal_input = next(arg for fn, arg in mocks.activity_calls if fn is emit_observation_signals_activity)+ signal_input = next(arg for fn, arg in mocks.activity_calls if fn is emit_observation_signal_summaries_activity)assert signal_input.observation_id == new_observation_idassert signal_input.exported_asset_id == 42 # threaded from ensure_session_asset_activityassert signal_input.signals[0].description == "Checkout CTA is broken on /cart"@@ -4008,6 +4014,10 @@ async def test_apply_scanner_workflow_emits_the_signal_finding() -> None:assert succeeded.scanner_result.signals_count == 1# The distinct problem types ride the row so the watch feed can name the kind of issue.assert succeeded.scanner_result.signal_problem_types == ["bug"]+ # And the headline rides it too, so the card names the finding rather than counting it.+ assert [(s.problem_type, s.headline) for s in succeeded.scanner_result.signal_summaries] == [+ ("bug", "Checkout CTA does nothing")+ ]@pytest.mark.asyncio@@ -4028,6 +4038,7 @@ async def test_apply_scanner_workflow_succeeds_when_the_signal_activity_fails()signals=[SignalFinding(problem_type="bug",+ headline="Checkout CTA does nothing",start_time=30,end_time=35,url="https://app.example.com/cart",@@ -4037,7 +4048,7 @@ async def test_apply_scanner_workflow_succeeds_when_the_signal_activity_fails()],),},- activity_errors={emit_observation_signals_activity: TimeoutError("start-to-close exceeded")},+ activity_errors={emit_observation_signal_summaries_activity: TimeoutError("start-to-close exceeded")},)await _run_workflow(_build_inputs(session_id="sess-sig-fail", team_id=99), mocks)@@ -4047,6 +4058,7 @@ async def test_apply_scanner_workflow_succeeds_when_the_signal_activity_fails()succeeded = next(arg for fn, arg in mocks.activity_calls if fn is mark_observation_succeeded_activity)assert succeeded.scanner_result.signals_count == 0assert succeeded.scanner_result.signal_problem_types == []+ assert succeeded.scanner_result.signal_summaries == []@pytest.mark.asyncio@@ -4070,6 +4082,7 @@ async def test_apply_scanner_workflow_counts_signals_for_pre_patch_histories() -signals=[SignalFinding(problem_type="bug",+ headline="Checkout CTA does nothing",start_time=30,end_time=35,url="https://app.example.com/cart",@@ -4087,6 +4100,8 @@ async def test_apply_scanner_workflow_counts_signals_for_pre_patch_histories() -called = [fn for fn, _ in mocks.activity_calls]assert emit_observation_signal_activity in calledassert emit_observation_signals_activity not in called+ assert emit_observation_signal_summaries_activity not in calledsucceeded = next(arg for fn, arg in mocks.activity_calls if fn is mark_observation_succeeded_activity)assert succeeded.scanner_result.signals_count == 2assert succeeded.scanner_result.signal_problem_types == []+ assert succeeded.scanner_result.signal_summaries == []diff --git a/products/replay_vision/backend/watch_feed.py b/products/replay_vision/backend/watch_feed.pyindex 2d3caf71e796..ed3015c98baa 100644--- a/products/replay_vision/backend/watch_feed.py+++ b/products/replay_vision/backend/watch_feed.py@@ -5,6 +5,7 @@ own window), so "outlier" and "rare" mean unusual for that scanner lately, not a"""import re+from collections import dequefrom datetime import datetimefrom statistics import fmean, stdevfrom typing import Any@@ -36,10 +37,10 @@ NOVEL_SUMMARY_MIN_TOKENS = 8# viewer could lean on by hammering the broad feed.NOVEL_SUMMARY_MAX_SIBLINGS = 40-# Component weights for the blended watchability score. A lone signal outranks a lone anything-else,-# but a type hit combined with the scan's own notability can outrank a routine signal — the feed is a-# portfolio of the window's most watchable rows, not signals first and everything after. Retune here.-WATCH_WEIGHT_SIGNAL = 1.0+# Component weights for the blended watchability score. The feed is a portfolio of the window's most+# watchable rows, not signals first and everything after, so the signal weight sits below the hit weight: a+# wide outlier or a rare verdict outranks even the most confident lone signal. Retune here.+WATCH_WEIGHT_SIGNAL = 0.8WATCH_WEIGHT_HIT = 0.9WATCH_WEIGHT_NOTABILITY = 0.7WATCH_WEIGHT_FRICTION = 0.3@@ -50,6 +51,20 @@ WATCH_SEEN_PENALTY = 0.5# A no-baseline "yes" verdict is the weak conventional something-happened phrasing, so it enters the# blend below a verdict the scanner's own window shows to be rare.VERDICT_YES_STRENGTH = 0.5+# Signal strength is the row's most confident finding, and emission floors confidence at 0.4, so a live value+# runs 0.4-1.0. A row scanned before summaries shipped carries a count and no confidence, and takes the+# midpoint of that range: it neither outranks the rows around it nor sinks below them.+SIGNAL_LEGACY_STRENGTH = 0.7+# The share of the feed signal rows may hold, above the leading row and while other rows remain to place.+# Signals corroborate across sessions, so a window full of them says the scanner is working, not that a+# reader should watch all of them.+WATCH_FEED_MAX_SIGNAL_SHARE = 0.4+# Reason kinds that say nothing about the session: the fall-through for a row that scored on no source at+# all. They are ordering, not evidence, so the feed carries them only to reach the floor below.+FILLER_REASON_KINDS = frozenset({"unviewed_recent", "recent"})+# How short the feed may get before filler rows pad it. A feed of 3 real findings beats one of 3 findings+# and 17 "new since you last looked", and a feed that empties the moment nothing is wrong reads as broken.+WATCH_FEED_MIN_ITEMS = 3# The score deviation, in stddevs, at which an outlier counts full strength. The hit fires at# OUTLIER_STDDEVS; its strength climbs from there to 1.0 by this many stddevs, so a wider outlier ranks# above a marginal one instead of both reading as the same boolean hit.@@ -83,6 +98,8 @@ class _Candidate:viewed: boolsignals_count: intsignal_problem_types: tuple[str, ...]+ # (problem_type, headline, confidence) per emitted signal. Empty on rows scanned before this shipped.+ signal_summaries: tuple[tuple[str, str, float], ...]scanner_type: str | Noneverdict: str | Nonescore: float | None@@ -105,6 +122,22 @@ def _parse_candidate(row: dict[str, Any]) -> _Candidate:signal_problem_types = (tuple(pt for pt in raw_problem_types if isinstance(pt, str)) if isinstance(raw_problem_types, list) else ())+ raw_summaries = result.get("signal_summaries") if isinstance(result, dict) else None+ signal_summaries = (+ tuple(+ (entry["problem_type"], entry["headline"], float(entry["confidence"]))+ for entry in raw_summaries+ if isinstance(entry, dict)+ and isinstance(entry.get("problem_type"), str)+ # A blank headline would leave the card's sentence trailing off, so the row counts instead.+ and isinstance(entry.get("headline"), str)+ and entry["headline"].strip()+ and isinstance(entry.get("confidence"), int | float)+ and not isinstance(entry.get("confidence"), bool)+ )+ if isinstance(raw_summaries, list)+ else ()+ )score = output.get("score")raw_tags = output.get("tags")raw_freeform = output.get("tags_freeform")@@ -131,6 +164,7 @@ def _parse_candidate(row: dict[str, Any]) -> _Candidate:viewed=bool(row.get("feed_viewed")),signals_count=signals_count if isinstance(signals_count, int) else 0,signal_problem_types=signal_problem_types,+ signal_summaries=signal_summaries,scanner_type=scanner_type,verdict=verdict,score=float(score) if isinstance(score, int | float) else None,@@ -260,24 +294,103 @@ def _type_hit(return None+def _signal_strength(candidate: _Candidate) -> float:+ """How strongly the row's signals argue for watching it: the confidence of its most confident finding.+ A flat 1.0 for any signal made a marginal finding rank level with an unmistakable one."""+ if candidate.signal_summaries:+ return max(confidence for _, _, confidence in candidate.signal_summaries)+ return SIGNAL_LEGACY_STRENGTH if candidate.signals_count > 0 else 0.0+++def _contributions(candidate: _Candidate, hit_strength: float) -> dict[str, float]:+ """The weighted evidence this row carries, one entry per source. `_watchability` sums these and the+ displayed reason names the largest of them, so the order and the copy read the same numbers."""+ return {+ "signal": WATCH_WEIGHT_SIGNAL * _signal_strength(candidate),+ "hit": WATCH_WEIGHT_HIT * hit_strength,+ "notability": WATCH_WEIGHT_NOTABILITY * (candidate.notability if candidate.notability is not None else 0.0),+ "friction": WATCH_WEIGHT_FRICTION * (1.0 if candidate.friction else 0.0),+ }++def _watchability(candidate: _Candidate, hit_strength: float) -> float:"""Blend the row's signal, type hit, notability, and friction into one score, then dock a row thereader already opened. Every source contributes at once, so a row wins on the sum of its evidencerather than on a single dominant flag."""- signal_strength = 1.0 if candidate.signals_count > 0 else 0.0- notability = candidate.notability if candidate.notability is not None else 0.0- friction = 1.0 if candidate.friction else 0.0- score = (- WATCH_WEIGHT_SIGNAL * signal_strength- + WATCH_WEIGHT_HIT * hit_strength- + WATCH_WEIGHT_NOTABILITY * notability- + WATCH_WEIGHT_FRICTION * friction- )+ score = sum(_contributions(candidate, hit_strength).values())if candidate.viewed:score -= WATCH_SEEN_PENALTYreturn score+def _strongest_reason_part(candidate: _Candidate, contributions: dict[str, float]) -> str | None:+ """Which source the card should name, or None when the row carries no evidence at all.++ The largest weighted part wins. Ties break signal, hit, notability, friction — the order the old+ fixed ladder used — so a row with two equal parts reads the way it always did.+ """+ parts = dict(contributions)+ # Notability below the tier threshold still adds to the score, but the card must not say the scan judged+ # the session worth watching when it did not. The old ladder held this rule; the label holds it now.+ if candidate.notability is None or candidate.notability < NOTABLE_MIN_SCORE:+ parts["notability"] = 0.0+ winner = max(("signal", "hit", "notability", "friction"), key=lambda part: parts[part])+ return winner if parts[winner] > 0 else None+++def _cap_signal_share(ranked: list[WatchFeedEntry]) -> list[WatchFeedEntry]:+ """Hold signal cards to WATCH_FEED_MAX_SIGNAL_SHARE of the feed as it is placed.++ The share is checked per place rather than over the whole list, because the view slices the head of this+ list: a feed of 5 obeys the same share as a feed of 50. Two rows are exempt by design. The best row+ always leads, whatever it is. And a window with more signal rows than the share can hold runs out of+ other rows to interleave, so the rest trail the feed rather than disappear from it — reordering the feed+ is the job here, shortening it is not.++ Because `_trim_filler` runs first, the rows a signal is held against are other findings, not padding.+ So a window whose only findings are signals returns a feed of signals: the share keeps signals from+ crowding out an outlier or a rare verdict, and was never meant to dilute them with clips that carry+ nothing.+ """+ placed: list[WatchFeedEntry] = []+ # A deque, because the candidate cap is 1000 and every admitted row pops from the front.+ held: deque[WatchFeedEntry] = deque()+ signals_placed = 0+ for entry in ranked:+ if entry.reason["kind"] == "signal_emitted":+ held.append(entry)+ else:+ placed.append(entry)+ while held and (not placed or (signals_placed + 1) / (len(placed) + 1) <= WATCH_FEED_MAX_SIGNAL_SHARE):+ placed.append(held.popleft())+ signals_placed += 1+ return placed + list(held)+++def _trim_filler(ranked: list[WatchFeedEntry]) -> list[WatchFeedEntry]:+ """Drop the no-evidence rows once WATCH_FEED_MIN_ITEMS real findings are in the feed.++ `limit` is a ceiling the feed had been filling: a quiet window returned 20 cards of which 17 said+ "New since you last looked", which buries the few that meant something. Findings are kept whatever+ their count; filler only makes up the difference to the floor, so a window with nothing to say+ returns 3 newest clips rather than 20 or an empty state.+ """+ findings = [entry for entry in ranked if entry.reason["kind"] not in FILLER_REASON_KINDS]+ if len(findings) >= WATCH_FEED_MIN_ITEMS:+ return findings+ # Walk rather than concatenate, because a row the reader already opened is docked half a point and can+ # sort below an unviewed filler row — findings are not always a prefix of the list.+ budget = WATCH_FEED_MIN_ITEMS - len(findings)+ kept: list[WatchFeedEntry] = []+ for entry in ranked:+ if entry.reason["kind"] not in FILLER_REASON_KINDS:+ kept.append(entry)+ elif budget > 0:+ kept.append(entry)+ budget -= 1+ return kept++def rank_watch_feed_candidates(rows: list[dict[str, Any]]) -> list[WatchFeedEntry]:"""Rank candidate rows (`id`, `scanner_id`, `created_at`, `scanner_result`, `feed_viewed`) mostwatchable first by a blended score, then newest.@@ -289,8 +402,16 @@ def rank_watch_feed_candidates(rows: list[dict[str, Any]]) -> list[WatchFeedEntrso an unviewed peer comes first while a strong seen row still holds its place above routine unseenrows.- The displayed reason still names the single strongest source (signal, then hit, then notability,- then friction, then seen-state), independent of the score that ordered the row.+ The displayed reason names the largest weighted part of that same score, so the card explains the+ position it earned. It used to name a signal whenever the row carried one, which labelled a row as+ `signal_emitted` even when a wide outlier was the stronger evidence and made the feed read as signals+ with a few other things in it.++ Rows that scored on nothing are then trimmed to a floor of WATCH_FEED_MIN_ITEMS, and the signal rows+ that survive are interleaved down to WATCH_FEED_MAX_SIGNAL_SHARE of the result; see `_trim_filler` and+ `_cap_signal_share`. The trim runs first on purpose: trimming afterwards would strip the very rows the+ cap interleaved signals against, so a feed that satisfied the share when built would breach it on the+ way out."""candidates = [_parse_candidate(row) for row in rows]baselines = _baselines(candidates)@@ -302,17 +423,24 @@ def rank_watch_feed_candidates(rows: list[dict[str, Any]]) -> list[WatchFeedEntrhit_result = _type_hit(candidate, baselines[candidate.scanner_id], by_scanner[candidate.scanner_id])hit = hit_result[0] if hit_result is not None else Nonehit_strength = hit_result[1] if hit_result is not None else 0.0- has_signal = candidate.signals_count > 0- notable = candidate.notability is not None and candidate.notability >= NOTABLE_MIN_SCORE- if has_signal:+ contributions = _contributions(candidate, hit_strength)+ strongest = _strongest_reason_part(candidate, contributions)+ if strongest == "signal":reason: dict[str, Any] = {"kind": "signal_emitted", "signals_count": candidate.signals_count}if candidate.signal_problem_types:reason["problem_types"] = list(candidate.signal_problem_types)- elif hit is not None:+ if candidate.signal_summaries:+ # The card names the findings from this; the confidence stays behind, because it ranks the+ # row rather than telling a reader anything they can act on.+ reason["signals"] = [+ {"problem_type": problem_type, "headline": headline}+ for problem_type, headline, _ in candidate.signal_summaries+ ]+ elif strongest == "hit" and hit is not None:reason = hit- elif notable:+ elif strongest == "notability":reason = {"kind": "notable", "notability": candidate.notability}- elif candidate.friction:+ elif strongest == "friction":reason = {"kind": "friction"}elif not candidate.viewed:reason = {"kind": "unviewed_recent"}@@ -326,4 +454,4 @@ def rank_watch_feed_candidates(rows: list[dict[str, Any]]) -> list[WatchFeedEntrsort_key = (_watchability(candidate, hit_strength), candidate.created_at)scored.append((sort_key, WatchFeedEntry(observation_id=candidate.observation_id, reason=reason)))scored.sort(key=lambda item: item[0], reverse=True)- return [entry for _, entry in scored]+ return _cap_signal_share(_trim_filler([entry for _, entry in scored]))diff --git a/products/replay_vision/evals/test/test_eval_scanner_quality.py b/products/replay_vision/evals/test/test_eval_scanner_quality.pyindex a0cfeffa3bf2..c24e75256f20 100644--- a/products/replay_vision/evals/test/test_eval_scanner_quality.py+++ b/products/replay_vision/evals/test/test_eval_scanner_quality.py@@ -190,6 +190,7 @@ def test_scan_completed_fails_on_schema_breakage() -> None:[{"problem_type": "design_flaw",+ "headline": "Navigation panel covers the book list","start_time": 7,"end_time": 11,"url": "https://example.com/library",@@ -198,6 +199,7 @@ def test_scan_completed_fails_on_schema_breakage() -> None:},{"problem_type": "crash",+ "headline": "Reader errors out after a book opens","start_time": 23,"end_time": 29,"url": "https://example.com/reader",diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex c154595bd943..a5d61c423a74 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -2412,6 +2412,16 @@ export const WatchFeedReasonEnumApi = {Recent: 'recent',} as const+/**+ * One signal an observation raised, named rather than counted.+ */+export interface WatchFeedSignalApi {+ /** Issue type: `bug`, `crash`, `design_flaw`, or `ux_friction`. */+ problem_type: string+ /** The finding in a few words, written by the scan. The full description lives on the signal itself. */+ headline: string+}+/*** Machine-readable reason an observation made the feed; the frontend renders the copy.*/@@ -2436,6 +2446,8 @@ export interface WatchFeedReasonApi {signals_count?: number | null/** Issue type of each emitted signal (`bug`, `crash`, `design_flaw`, `ux_friction`), one entry per signal in the order raised, for `signal_emitted`. Absent on signals scanned before this shipped. */problem_types?: string[]+ /** Each emitted signal in the order raised, for `signal_emitted`. Carries what the card needs to name the findings instead of counting them. Absent on sessions scanned before this shipped, which carry `problem_types` alone. */+ signals?: WatchFeedSignalApi[]/*** The monitor's answer, for `unusual_verdict`.* @nullable@@ -2492,7 +2504,7 @@ export interface WatchFeedItemApi {* Response of GET /vision/scanners/watch_feed/.*/export interface WatchFeedResponseApi {- /** Succeeded observations in the window worth watching, most interesting first: signal emitters, then type-specific hits, then unviewed before viewed, then the scan's own notability judgment, then prose that reads as friction, then newest. */+ /** Succeeded observations in the window worth watching, most interesting first, each carrying the reason it ranked. Every observation that carries a finding is returned; observations that carry none (`unviewed_recent`, `recent`) are returned only to pad a near-empty feed to three items, so a quiet window answers with a handful of rows rather than a full page of newest clips. */results: WatchFeedItemApi[]}@@ -2996,7 +3008,7 @@ export type VisionScannersWatchFeedRetrieveParams = {*/date_to?: string/**- * Feed items to return, at most 50. The feed is bounded, not paginated.+ * Ceiling on feed items to return, at most 50. The feed is bounded, not paginated, and routinely returns far fewer: a window is not padded to this number with clips that carry no finding.* @minimum 1* @maximum 50*/diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex c0141ead096e..27c175ad840b 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -693,6 +693,26 @@ export const HomeWatchFeed: StoryObj = {},}+// A quiet window: nothing scored on any source, so the feed pads to three newest clips and says so+// rather than filling the page with them.+export const HomeWatchFeedOnlyNewest: StoryObj = {+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/vision/scanners/watch_feed/': {+ results: [0, 1, 2].map((i) => ({+ observation: observation({ id: `00000000-0000-0000-0000-0000000000f${i}` }),+ reason: { kind: 'unviewed_recent' },+ })),+ },+ },+ }),+ ],+ parameters: {+ featureFlags: { [FEATURE_FLAGS.REPLAY_VISION_HOME_REDESIGN_EXPERIMENT]: 'test' },+ },+}+export const HomeWatchFeedEmpty: StoryObj = {decorators: [mswDecorator({diff --git a/products/replay_vision/frontend/replay_scanners/components/WatchFeedCard.test.ts b/products/replay_vision/frontend/replay_scanners/components/WatchFeedCard.test.tsindex 216027db930c..6b6c0c09e3ca 100644--- a/products/replay_vision/frontend/replay_scanners/components/WatchFeedCard.test.ts+++ b/products/replay_vision/frontend/replay_scanners/components/WatchFeedCard.test.ts@@ -5,7 +5,7 @@ describe('WatchFeedCard helpers', () => {describe('watchReasonCopy', () => {it.each<{ name: string; reason: WatchFeedReasonApi; expected: string }>([{- name: 'pluralizes multiple signals',+ name: 'counts signals on a session scanned before headlines shipped',reason: { kind: 'signal_emitted', signals_count: 3 } as WatchFeedReasonApi,expected: 'The scanner raised 3 signals from this session.',},@@ -41,6 +41,62 @@ describe('WatchFeedCard helpers', () => {} as WatchFeedReasonApi,expected: 'The scanner raised 3 signals from this session: 2 bug signals, 1 UX friction signal.',},+ {+ name: 'names the finding behind a single signal',+ reason: {+ kind: 'signal_emitted',+ signals_count: 1,+ problem_types: ['bug'],+ signals: [{ problem_type: 'bug', headline: 'Checkout button does nothing' }],+ } as WatchFeedReasonApi,+ expected: 'The scanner raised a bug signal from this session: Checkout button does nothing.',+ },+ {+ name: 'lists the findings when one type raised several',+ reason: {+ kind: 'signal_emitted',+ signals_count: 2,+ problem_types: ['bug', 'bug'],+ signals: [+ { problem_type: 'bug', headline: 'Checkout button does nothing' },+ { problem_type: 'bug', headline: 'Card form rejects a valid card' },+ ],+ } as WatchFeedReasonApi,+ expected:+ 'The scanner raised 2 bug signals from this session: Checkout button does nothing, and Card form rejects a valid card.',+ },+ {+ name: 'groups the findings under each type in a mixed breakdown',+ reason: {+ kind: 'signal_emitted',+ signals_count: 3,+ problem_types: ['bug', 'bug', 'ux_friction'],+ signals: [+ { problem_type: 'bug', headline: 'Checkout button does nothing' },+ { problem_type: 'bug', headline: 'Card form rejects a valid card' },+ { problem_type: 'ux_friction', headline: 'Search results load twice' },+ ],+ } as WatchFeedReasonApi,+ expected:+ 'The scanner raised 3 signals from this session: 2 bug (Checkout button does nothing, Card form rejects a valid card), and 1 UX friction (Search results load twice).',+ },+ {+ name: 'counts the findings it has no room to name',+ reason: {+ kind: 'signal_emitted',+ signals_count: 5,+ problem_types: ['bug', 'bug', 'bug', 'bug', 'bug'],+ signals: [+ { problem_type: 'bug', headline: 'Checkout button does nothing' },+ { problem_type: 'bug', headline: 'Card form rejects a valid card' },+ { problem_type: 'bug', headline: 'Order total shows zero' },+ { problem_type: 'bug', headline: 'Address lookup returns nothing' },+ { problem_type: 'bug', headline: 'Receipt page is blank' },+ ],+ } as WatchFeedReasonApi,+ expected:+ 'The scanner raised 5 bug signals from this session: Checkout button does nothing, Card form rejects a valid card, Order total shows zero, and 2 more.',+ },{name: 'rounds the score and window average',reason: { kind: 'outlier_score', score: 9.53846, window_mean: 5.1428 } as WatchFeedReasonApi,diff --git a/products/replay_vision/frontend/replay_scanners/components/WatchFeedCard.tsx b/products/replay_vision/frontend/replay_scanners/components/WatchFeedCard.tsxindex 4d57a67448c2..ca5e6b13aed7 100644--- a/products/replay_vision/frontend/replay_scanners/components/WatchFeedCard.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/WatchFeedCard.tsx@@ -30,6 +30,16 @@ const PROBLEM_TYPE_LABELS: Record<string, string> = {const problemTypeLabel = (problemType: string): string =>PROBLEM_TYPE_LABELS[problemType] ?? problemType.replace(/_/g, ' ')+// A card lists the findings on one line, so it names the first few and counts the rest.+const MAX_SHOWN_HEADLINES = 3++const joinWithAnd = (parts: string[]): string =>+ parts.length > 1 ? `${parts.slice(0, -1).join(', ')}, and ${parts[parts.length - 1]}` : parts[0]++/** Reason kinds that say nothing about the session. The backend returns these only to pad a near-empty+ * feed, so a feed made up entirely of them means the window turned up no findings at all. */+export const FILLER_REASON_KINDS = new Set(['unviewed_recent', 'recent'])+export function watchReasonCopy(reason: WatchFeedReasonApi): string {// The scan wrote this sentence while watching the session, so it beats anything derived from the// reason kind. Absent on observations scanned before notability shipped, which fall through below.@@ -39,7 +49,9 @@ export function watchReasonCopy(reason: WatchFeedReasonApi): string {switch (reason.kind) {case 'signal_emitted': {const total = reason.signals_count ?? 0- const problemTypes = reason.problem_types ?? []+ const signals = reason.signals ?? []+ const problemTypes =+ signals.length > 0 ? signals.map((signal) => signal.problem_type) : (reason.problem_types ?? [])if (problemTypes.length === 0) {return total > 1? `The scanner raised ${total} signals from this session.`@@ -54,19 +66,44 @@ export function watchReasonCopy(reason: WatchFeedReasonApi): string {}countByType.set(problemType, (countByType.get(problemType) ?? 0) + 1)}+ // Sessions scanned before headlines shipped carry the types alone, so those cards still count.+ if (signals.length === 0) {+ if (order.length === 1) {+ const label = problemTypeLabel(order[0])+ return total > 1+ ? `The scanner raised ${total} ${label} signals from this session.`+ : `The scanner raised a ${label} signal from this session.`+ }+ const breakdown = order+ .map((problemType) => {+ const n = countByType.get(problemType) ?? 0+ return `${n} ${problemTypeLabel(problemType)} signal${n === 1 ? '' : 's'}`+ })+ .join(', ')+ return `The scanner raised ${total} signals from this session: ${breakdown}.`+ }+ const shown = signals.slice(0, MAX_SHOWN_HEADLINES)+ // Against the count, not the named list: the backend drops a finding whose headline came back+ // blank, so the card can hold fewer names than the session raised signals.+ const hidden = Math.max(total, signals.length) - shown.lengthif (order.length === 1) {const label = problemTypeLabel(order[0])+ const named = shown.map((signal) => signal.headline)+ const listed = joinWithAnd(hidden > 0 ? [...named, `${hidden} more`] : named)return total > 1- ? `The scanner raised ${total} ${label} signals from this session.`- : `The scanner raised a ${label} signal from this session.`+ ? `The scanner raised ${total} ${label} signals from this session: ${listed}.`+ : `The scanner raised a ${label} signal from this session: ${listed}.`}- const breakdown = order- .map((problemType) => {- const n = countByType.get(problemType) ?? 0- return `${n} ${problemTypeLabel(problemType)} signal${n === 1 ? '' : 's'}`- })- .join(', ')- return `The scanner raised ${total} signals from this session: ${breakdown}.`+ const groups = order.map((problemType) => {+ const n = countByType.get(problemType) ?? 0+ const named = shown+ .filter((signal) => signal.problem_type === problemType)+ .map((signal) => signal.headline)+ const label = `${n} ${problemTypeLabel(problemType)}`+ return named.length > 0 ? `${label} (${named.join(', ')})` : label+ })+ const listed = joinWithAnd(hidden > 0 ? [...groups, `${hidden} more`] : groups)+ return `The scanner raised ${total} signals from this session: ${listed}.`}case 'unusual_verdict':return reason.verdictdiff --git a/products/replay_vision/frontend/replay_scanners/components/WatchFeedTab.tsx b/products/replay_vision/frontend/replay_scanners/components/WatchFeedTab.tsxindex 4b6246b30871..91dc854f1bac 100644--- a/products/replay_vision/frontend/replay_scanners/components/WatchFeedTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/WatchFeedTab.tsx@@ -11,7 +11,7 @@ import { FilterPill } from '../../components/FilterPill'import { visionScannersListLogic } from '../../logics/visionScannersListLogic'import { SCANNER_TYPE_OPTIONS, ScannerType } from '../types'import { watchFeedLogic } from '../watchFeedLogic'-import { WatchFeedCard } from './WatchFeedCard'+import { FILLER_REASON_KINDS, WatchFeedCard } from './WatchFeedCard'const TYPE_OPTIONS: { value: ScannerType; label: string }[] = SCANNER_TYPE_OPTIONS.map(({ value, label }) => ({value,@@ -63,6 +63,9 @@ export function WatchFeedTab(): JSX.Element {// Only the scanner picker narrows *which* scanners are in scope; the others narrow within them.const narrowedToScanners = scannerIdsFilter.lengthconst scannerCount = new Set(items.map((item) => item.observation.scanner_id)).size+ // Every card carrying a no-evidence reason means the window produced no findings. A feed that mixes a+ // finding with padding needs no explaining, so this stays off unless the whole feed is padding.+ const onlyFiller = items.length > 0 && items.every((item) => FILLER_REASON_KINDS.has(item.reason.kind))return (<div className="flex flex-col gap-4">@@ -148,6 +151,14 @@ export function WatchFeedTab(): JSX.Element {</LemonButton></div>)}+ {/* Three newest clips and nothing else is the answer, not a half-loaded feed, so say so+ rather than leaving the reader to infer it from three identical reason lines. */}+ {onlyFiller && (+ <p className="text-sm text-secondary m-0">+ Nothing stood out in this window. These are the newest clips. Try a longer date range to see+ more.+ </p>+ )}{items.length > 0 ? (items.map((item, index) => (<WatchFeedCard key={item.observation.id} item={item} position={index} />diff --git a/products/replay_vision/frontend/replay_scanners/watchFeedLogic.ts b/products/replay_vision/frontend/replay_scanners/watchFeedLogic.tsindex d3663b917736..72a052bd7af2 100644--- a/products/replay_vision/frontend/replay_scanners/watchFeedLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/watchFeedLogic.ts@@ -285,9 +285,18 @@ export const watchFeedLogic = kea<watchFeedLogicType>([actions.loadFeed()},loadFeedSuccess: ({ feedItems }) => {+ const items = feedItems ?? []+ // The click event reports the reason a reader picked; without this one nothing reports the mix+ // they were offered, so a ranking change cannot be read after it ships.+ const countByReasonKind: Record<string, number> = {}+ for (const item of items) {+ countByReasonKind[item.reason.kind] = (countByReasonKind[item.reason.kind] ?? 0) + 1+ }posthog.capture('replay_vision_watch_feed_viewed', {- clip_count: feedItems?.length ?? 0,- scanner_count: new Set((feedItems ?? []).map((item) => item.observation.scanner_id)).size,+ clip_count: items.length,+ scanner_count: new Set(items.map((item) => item.observation.scanner_id)).size,+ reason_kind_counts: countByReasonKind,+ signal_share: items.length > 0 ? (countByReasonKind.signal_emitted ?? 0) / items.length : 0,})},// A card writes `?t=<seconds>` so the player opens at the cited moment; clear it on close so adiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f42ed837ef52..c5b772cd344a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -98149,6 +98149,16 @@ export namespace Schemas {Recent: 'recent',} as const;+ /**+ * One signal an observation raised, named rather than counted.+ */+ export interface WatchFeedSignal {+ /** Issue type: `bug`, `crash`, `design_flaw`, or `ux_friction`. */+ problem_type: string;+ /** The finding in a few words, written by the scan. The full description lives on the signal itself. */+ headline: string;+ }+/*** Machine-readable reason an observation made the feed; the frontend renders the copy.*/@@ -98173,6 +98183,8 @@ export namespace Schemas {signals_count?: number | null;/** Issue type of each emitted signal (`bug`, `crash`, `design_flaw`, `ux_friction`), one entry per signal in the order raised, for `signal_emitted`. Absent on signals scanned before this shipped. */problem_types?: string[];+ /** Each emitted signal in the order raised, for `signal_emitted`. Carries what the card needs to name the findings instead of counting them. Absent on sessions scanned before this shipped, which carry `problem_types` alone. */+ signals?: WatchFeedSignal[];/*** The monitor's answer, for `unusual_verdict`.* @nullable@@ -98229,7 +98241,7 @@ export namespace Schemas {* Response of GET /vision/scanners/watch_feed/.*/export interface WatchFeedResponse {- /** Succeeded observations in the window worth watching, most interesting first: signal emitters, then type-specific hits, then unviewed before viewed, then the scan's own notability judgment, then prose that reads as friction, then newest. */+ /** Succeeded observations in the window worth watching, most interesting first, each carrying the reason it ranked. Every observation that carries a finding is returned; observations that carry none (`unviewed_recent`, `recent`) are returned only to pad a near-empty feed to three items, so a quiet window answers with a handful of rows rather than a full page of newest clips. */results: WatchFeedItem[];}@@ -113635,7 +113647,7 @@ export namespace Schemas {*/date_to?: string;/**- * Feed items to return, at most 50. The feed is bounded, not paginated.+ * Ceiling on feed items to return, at most 50. The feed is bounded, not paginated, and routinely returns far fewer: a window is not padded to this number with clips that carry no finding.* @minimum 1* @maximum 50*/