: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): agentic prompt improvement with session context (#68285)
Arno Hillenbb56ec98b62c
diff --git a/products/replay_vision/backend/prompt_suggestions.py b/products/replay_vision/backend/prompt_suggestions.pyindex 6dbeaa5809e9..993251df6f30 100644--- a/products/replay_vision/backend/prompt_suggestions.py+++ b/products/replay_vision/backend/prompt_suggestions.py@@ -5,9 +5,12 @@ Mirrors the frontend "Improve scanner prompt" message: the current prompt plus trewrite. Suggestions are persisted so the Quality tab can show the current one and its history."""+import timeimport uuid+import asyncioimport hashlibimport datetime as dt+from typing import Anyfrom django.conf import settingsfrom django.db import transaction@@ -16,11 +19,19 @@ from django.utils import timezoneimport structlogimport posthoganalytics+from asgiref.sync import async_to_sync+from google.genai import typesfrom google.genai.types import GenerateContentConfig-from posthoganalytics.ai.gemini import genai+from posthoganalytics.ai.gemini import (+ Client as GeminiClient,+ genai,+)from pydantic import BaseModel, Field+from posthog.models.team import Teamfrom posthog.models.user import User+from posthog.rbac.user_access_control import UserAccessControl+from posthog.session_recordings.models.session_recording import SessionRecordingfrom products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservationfrom products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabel@@ -34,10 +45,22 @@ logger = structlog.get_logger(__name__)_SUGGESTION_MODEL = "gemini-3.1-flash-lite-preview"_MODEL_CALL_TIMEOUT_MS = 90_000+# The agentic path digs through sessions before rewriting, so give it the stronger model.+_AGENT_MODEL = "gemini-3-flash-preview"_MAX_RATED_SESSIONS = 20_MAX_REASONING_CHARS = 280_MAX_DISMISSED_EXAMPLES = 3_MAX_DISMISSED_PROMPT_CHARS = 600+_MAX_TOOL_ROUNDS = 6+_MAX_SUMMARIES_PER_RUN = 2+_MAX_TOOL_REASONING_CHARS = 4000+# Wall-clock budgets for the agentic loop: once spent, no new tool rounds start (the final structured+# turn still runs). The inline API path stays close to the old single-call bound; the background+# refresh gets room for cold summaries while finishing well inside its Temporal activity timeout.+_AGENT_BUDGET_INLINE_S = 60.0+_AGENT_BUDGET_BACKGROUND_S = 180.0+# Never start a cold summary with less than this much budget left; the wait is bounded by the remainder.+_COLD_SUMMARY_MIN_BUDGET_S = 60.0_SYSTEM_PROMPT = ("You rewrite the instruction prompt of a session-replay scanner so its future results agree with the "@@ -50,6 +73,17 @@ _SYSTEM_PROMPT = ("describing what you changed and why.")+_AGENT_SYSTEM_ADDENDUM = (+ " Before answering you may call tools to gather context: pull a rated session's full output, reasoning "+ "and feedback; list rated sessions beyond the sample; or fetch a session's summary (what actually "+ "happened in the recording). Prioritize investigating thumbs-down sessions and any session where the "+ "feedback and the scanner output seem to disagree — the summary tells you what really happened. "+ "Summaries are expensive: request them only where they change your rewrite. When you have enough "+ "context, answer."+)++_AGENT_SYSTEM_PROMPT = _SYSTEM_PROMPT + _AGENT_SYSTEM_ADDENDUM+class PromptSuggestionError(Exception):pass@@ -200,14 +234,17 @@ def _build_user_content(scanner: ReplayScanner, base_prompt: str, observations:return "\n".join(lines)-def _generate(*, user_content: str, team_id: int, distinct_id: str) -> _LlmPromptSuggestion:- api_key = settings.REPLAY_VISION_GEMINI_API_KEY or settings.GEMINI_API_KEY- # The generate endpoint runs this inline in a web worker, so a hung provider call must time out.- client = genai.Client(- api_key=api_key,+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},)+++def _generate(*, user_content: str, team_id: int, distinct_id: str) -> _LlmPromptSuggestion:+ client = _gemini_client()config = GenerateContentConfig(system_instruction=_SYSTEM_PROMPT,response_mime_type="application/json",@@ -238,21 +275,328 @@ def _generate(*, user_content: str, team_id: int, distinct_id: str) -> _LlmPrompreturn parsed-def generate_prompt_suggestion(scanner: ReplayScanner, user: User | None = None) -> ReplayScannerPromptSuggestion:+def _agent_tools() -> types.Tool:+ """Function declarations the prompt agent may call while deciding on a rewrite."""+ return types.Tool(+ function_declarations=[+ types.FunctionDeclaration(+ name="get_rated_observation",+ description=(+ "Full detail for one rated session: the scanner's output, its complete reasoning, the "+ "team's rating and written feedback, and the prompt version it ran with."+ ),+ parameters=types.Schema(+ type=types.Type.OBJECT,+ properties={+ "session_id": types.Schema(type=types.Type.STRING, description="The session id."),+ },+ required=["session_id"],+ ),+ ),+ types.FunctionDeclaration(+ name="list_rated_sessions",+ description=(+ "Page through all rated sessions beyond the sample in the briefing, newest first. "+ "Returns one line per session: id, output, rating, whether it has feedback."+ ),+ parameters=types.Schema(+ type=types.Type.OBJECT,+ properties={+ "offset": types.Schema(type=types.Type.INTEGER, description="Rows to skip (default 0)."),+ },+ ),+ ),+ types.FunctionDeclaration(+ name="get_session_summary",+ description=(+ "A narrative summary of what actually happened in the session recording — ground truth to "+ "check a rating or feedback against. Expensive; budgeted per run."+ ),+ parameters=types.Schema(+ type=types.Type.OBJECT,+ properties={+ "session_id": types.Schema(type=types.Type.STRING, description="The session id."),+ },+ required=["session_id"],+ ),+ ),+ ]+ )+++class _AgentToolState:+ def __init__(+ self, scanner: ReplayScanner, summary_user: User | None, allow_cold_summaries: bool, deadline: float+ ) -> None:+ self.scanner = scanner+ self.summary_user = summary_user+ self.allow_cold_summaries = allow_cold_summaries+ self.deadline = deadline+ self.cold_summaries_used = 0+ self.summary_cache: dict[str, str] = {}+++def _rated_observation_for_session(state: _AgentToolState, session_id: str) -> ReplayObservation | None:+ return (+ ReplayObservation.objects.filter(+ team_id=state.scanner.team_id,+ scanner_id=state.scanner.id,+ session_id=session_id,+ status=ObservationStatus.SUCCEEDED,+ label__isnull=False,+ )+ .select_related("label")+ .first()+ )+++def _tool_get_rated_observation(state: _AgentToolState, session_id: str) -> dict[str, Any]:+ observation = _rated_observation_for_session(state, session_id)+ if observation is None:+ return {"error": "no rated observation for that session id on this scanner"}+ label = _label(observation)+ output = (observation.scanner_result or {}).get("model_output") or {}+ raw_reasoning = output.get("reasoning")+ reasoning = raw_reasoning if isinstance(raw_reasoning, str) else ""+ snapshot = observation.scanner_snapshot or {}+ return {+ "session_id": session_id,+ "output": _describe_outcome(observation),+ "reasoning": reasoning[:_MAX_TOOL_REASONING_CHARS],+ "rating": "thumbs_up" if label.is_correct else "thumbs_down",+ "feedback": label.feedback,+ "prompt_version": snapshot.get("scanner_version"),+ }+++def _tool_list_rated_sessions(state: _AgentToolState, offset: int) -> dict[str, Any]:+ base = ReplayObservation.objects.filter(+ team_id=state.scanner.team_id,+ scanner_id=state.scanner.id,+ status=ObservationStatus.SUCCEEDED,+ label__isnull=False,+ )+ offset = max(0, offset)+ rows = list(base.select_related("label").order_by("-created_at")[offset : offset + _MAX_RATED_SESSIONS])+ return {+ "total": base.count(),+ "offset": offset,+ "sessions": [+ {+ "session_id": o.session_id,+ "output": _describe_outcome(o),+ "rating": "thumbs_up" if _label(o).is_correct else "thumbs_down",+ "has_feedback": bool(_label(o).feedback),+ }+ for o in rows+ ],+ }+++def _run_cold_summary(state: _AgentToolState, session_id: str, user: User, *, timeout_s: float) -> dict[str, Any]:+ """Run the summarization workflow for an unsummarized session, waiting at most the remaining run budget."""+ from posthog.temporal.session_replay.session_summary.workflow import ( # noqa: PLC0415 (heavy temporal dep, only loaded on the cold path)+ execute_summarize_session,+ )++ # Count before executing so a failing cold run still spends budget.+ state.cold_summaries_used += 1+ team = Team.objects.get(pk=state.scanner.team_id)++ async def _bounded() -> dict[str, Any]:+ return await asyncio.wait_for(+ execute_summarize_session(+ session_id=session_id,+ user=user,+ team=team,+ custom_tags={"ai_product": "replay_vision", "feature": "suggest_scanner_prompt"},+ ),+ timeout=timeout_s,+ )++ return async_to_sync(_bounded)()+++def _summary_access_error(state: _AgentToolState, session_id: str) -> dict[str, Any] | None:+ """Mirror the session-summary API's recording gate: no summaries for deleted recordings, and reads+ require viewer access on the recording as `summary_user` (the requester inline, the scanner's+ creator in the background refresh)."""+ team = Team.objects.get(pk=state.scanner.team_id)+ recording = SessionRecording.get_or_build(session_id=session_id, team=team)+ if recording.deleted:+ return {"error": "the recording for this session was deleted; decide with the context you have"}+ if state.summary_user is None or not UserAccessControl(state.summary_user, team).check_access_level_for_object(+ recording, required_level="viewer"+ ):+ return {"error": "this session's recording is not accessible; decide with the context you have"}+ return None+++def _tool_get_session_summary(state: _AgentToolState, session_id: str) -> dict[str, Any]:+ if session_id in state.summary_cache:+ return {"session_id": session_id, "summary": state.summary_cache[session_id]}+ if _rated_observation_for_session(state, session_id) is None:+ return {"error": "no rated observation for that session id on this scanner"}+ denied = _summary_access_error(state, session_id)+ if denied is not None:+ return denied+ # Deferred: heavy modules stay off the API import path. Summaries go through core helpers,+ # since replay_vision must not import products.replay internals.+ from posthog.temporal.session_replay.session_summary.state import (+ get_ready_summaries_from_db, # noqa: PLC0415 (heavy temporal dep, see above)+ )++ from ee.hogai.session_summaries.session.stringify import (+ SingleSessionSummaryStringifier, # noqa: PLC0415 (heavy ee dep, see above)+ )++ cached = get_ready_summaries_from_db([session_id], team_id=state.scanner.team_id, extra_summary_context=None)+ summary_json = cached[0].summary if cached else None+ if summary_json is None:+ # Only cold generation is budgeted; cached summaries above are cheap reads.+ summary_user = state.summary_user if state.allow_cold_summaries else None+ if summary_user is None:+ return {"error": "no summary exists for this session yet and generating one is unavailable here"}+ if state.cold_summaries_used >= _MAX_SUMMARIES_PER_RUN:+ return {"error": "summary budget for this run is exhausted; decide with the context you have"}+ remaining = state.deadline - time.monotonic()+ if remaining < _COLD_SUMMARY_MIN_BUDGET_S:+ return {"error": "not enough time left in this run to generate a summary; decide with the context you have"}+ summary_json = _run_cold_summary(state, session_id, summary_user, timeout_s=remaining)+ text = SingleSessionSummaryStringifier(summary_json).stringify_session()+ state.summary_cache[session_id] = text+ return {"session_id": session_id, "summary": text}+++def _dispatch_agent_tool(state: _AgentToolState, call: types.FunctionCall) -> dict[str, Any]:+ name = call.name+ args = dict(call.args or {})+ try:+ if name == "get_rated_observation":+ return _tool_get_rated_observation(state, str(args.get("session_id", "")))+ if name == "list_rated_sessions":+ return _tool_list_rated_sessions(state, int(args.get("offset", 0) or 0))+ if name == "get_session_summary":+ return _tool_get_session_summary(state, str(args.get("session_id", "")))+ except Exception:+ logger.exception("replay_vision.prompt_agent.tool_failed", tool=name, scanner_id=str(state.scanner.id))+ return {"error": "tool failed; decide with the context you have"}+ return {"error": f"unknown tool: {name}"}+++def _model_call(+ client: GeminiClient,+ contents: list[types.Content | types.Part],+ config: GenerateContentConfig,+ *,+ team_id: int,+ distinct_id: str,+) -> types.GenerateContentResponse:+ return client.models.generate_content(+ model=_AGENT_MODEL,+ contents=contents,+ config=config,+ posthog_distinct_id=distinct_id,+ posthog_trace_id=str(uuid.uuid4()),+ posthog_properties={"ai_product": "replay_vision", "feature": "suggest_scanner_prompt_agentic"},+ posthog_groups={"project": str(team_id)},+ )+++def _generate_agentic(+ *,+ scanner: ReplayScanner,+ user_content: str,+ user: User | None,+ allow_cold_summaries: bool,+ distinct_id: str,+) -> _LlmPromptSuggestion:+ """Tool-loop generation: the model may inspect rated sessions (and their summaries) before rewriting,+ then a final tool-free turn forces the structured answer, mirroring the scanner's own tool loop."""+ client = _gemini_client()+ budget_s = _AGENT_BUDGET_BACKGROUND_S if allow_cold_summaries else _AGENT_BUDGET_INLINE_S+ deadline = time.monotonic() + budget_s+ # Summary tools act as the requester (the scanner's creator on the automatic path); attribution stays `user`.+ state = _AgentToolState(scanner, user or scanner.created_by, allow_cold_summaries, deadline)+ tool_config = GenerateContentConfig(+ system_instruction=_AGENT_SYSTEM_PROMPT,+ tools=[_agent_tools()],+ temperature=0.3,+ )+ convo: list[types.Content | types.Part] = [types.Content(role="user", parts=[types.Part(text=user_content)])]+ response = _model_call(client, convo, tool_config, team_id=scanner.team_id, distinct_id=distinct_id)+ for _ in range(_MAX_TOOL_ROUNDS):+ content = response.candidates[0].content if response.candidates else None+ if not response.function_calls or content is None or time.monotonic() >= deadline:+ break+ convo.append(content) # carries thought signatures across the round-trip+ for call in response.function_calls:+ convo.append(+ types.Part(+ function_response=types.FunctionResponse(name=call.name, response=_dispatch_agent_tool(state, call))+ )+ )+ response = _model_call(client, convo, tool_config, team_id=scanner.team_id, distinct_id=distinct_id)+ # Final structured turn: tools off, JSON schema on (Gemini disallows combining the two). If the round or+ # time budget ran out with calls still pending, answer them first: Gemini rejects a conversation that+ # leaves a function_call turn without matching function responses.+ final_parts: list[types.Part] = []+ last_content = response.candidates[0].content if response.candidates else None+ if last_content is not None:+ convo.append(last_content)+ final_parts.extend(+ types.Part(+ function_response=types.FunctionResponse(name=call.name, response=_dispatch_agent_tool(state, call))+ )+ for call in response.function_calls or []+ )+ final_parts.append(types.Part(text="Respond now with the JSON answer."))+ convo.append(types.Content(role="user", parts=final_parts))+ final_config = GenerateContentConfig(+ system_instruction=_AGENT_SYSTEM_PROMPT,+ response_mime_type="application/json",+ response_json_schema=_LlmPromptSuggestion.model_json_schema(),+ tool_config=types.ToolConfig(+ function_calling_config=types.FunctionCallingConfig(mode=types.FunctionCallingConfigMode.NONE)+ ),+ temperature=0.3,+ )+ final = _model_call(client, convo, final_config, team_id=scanner.team_id, distinct_id=distinct_id)+ if not final.text:+ raise PromptSuggestionError("empty response")+ parsed = _LlmPromptSuggestion.model_validate_json(final.text)+ if not parsed.suggested_prompt.strip():+ raise PromptSuggestionError("empty suggested prompt")+ return parsed+++def generate_prompt_suggestion(+ scanner: ReplayScanner, user: User | None = None, *, allow_cold_summaries: bool = False+) -> ReplayScannerPromptSuggestion:"""Generate and persist a fresh suggestion; earlier pending ones become history.`user` is set for explicit (re)generate requests and null for the automatic daily refresh.- A suggestion whose prompt matches the current one lands as `no_change`: the scanner looks good.+ The agentic path lets the model inspect rated sessions (and, budget permitting, their summaries)+ before rewriting; on any agent failure we fall back to the single-shot generation so a suggestion+ still lands. A rewrite matching the current prompt lands as `no_change`: the scanner looks good."""observations = _labeled_observations(scanner)if not observations:raise PromptSuggestionError("no rated observations")base_prompt = (scanner.scanner_config or {}).get("prompt") or ""- parsed = _generate(- user_content=_build_user_content(scanner, base_prompt, observations),- team_id=scanner.team_id,- distinct_id=str(user.uuid) if user else f"replay-vision-scanner-{scanner.id}",- )+ user_content = _build_user_content(scanner, base_prompt, observations)+ distinct_id = str(user.uuid) if user else f"replay-vision-scanner-{scanner.id}"+ try:+ parsed = _generate_agentic(+ scanner=scanner,+ user_content=user_content,+ user=user,+ allow_cold_summaries=allow_cold_summaries,+ distinct_id=distinct_id,+ )+ except Exception:+ logger.exception("replay_vision.prompt_agent.failed_falling_back", scanner_id=str(scanner.id))+ parsed = _generate(user_content=user_content, team_id=scanner.team_id, distinct_id=distinct_id)suggested_prompt = parsed.suggested_prompt.strip()status = SuggestionStatus.NO_CHANGE if suggested_prompt == base_prompt.strip() else SuggestionStatus.PENDINGup = len([o for o in observations if _label(o).is_correct])@@ -296,7 +640,8 @@ def refresh_prompt_suggestion_if_stale(scanner: ReplayScanner) -> str:if timezone.now() - latest.created_at < PROMPT_SUGGESTION_MIN_AGE:return "refreshed_recently"try:- generate_prompt_suggestion(scanner)+ # user=None keeps automatic suggestions unattributed; cold summaries run as the scanner's creator.+ generate_prompt_suggestion(scanner, allow_cold_summaries=True)except PromptSuggestionError as e:if str(e) == "no rated observations":return "no_ratings"diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.pyindex d25ee1f9aee1..102238803329 100644--- a/products/replay_vision/backend/temporal/constants.py+++ b/products/replay_vision/backend/temporal/constants.py@@ -26,11 +26,15 @@ def build_process_vision_action_workflow_id(vision_action_id: UUID) -> str:SCANNER_SCHEDULE_INTERVAL = dt.timedelta(minutes=5)-# Children are ABANDONed and don't count against this budget.-SWEEP_WORKFLOW_EXECUTION_TIMEOUT = dt.timedelta(minutes=5)--# One LLM call; generous but bounded so a slow provider can't eat the sweep budget.-REFRESH_PROMPT_SUGGESTION_TIMEOUT = dt.timedelta(seconds=90)+# Children are ABANDONed and don't count against this budget, but activities do: this must cover the+# prompt-suggestion refresh worst case plus the candidate scan, or a slow refresh kills the whole sweep.+# Overlap SKIP means a slow run absorbs later ticks instead of stacking.+SWEEP_WORKFLOW_EXECUTION_TIMEOUT = dt.timedelta(minutes=15)++# The agentic refresh may run several tool rounds and up to two cold summaries. Its in-process budget+# (_AGENT_BUDGET_BACKGROUND_S) keeps typical runs well under this, so the activity finishes cleanly and+# a suggestion lands; this cap is the backstop for a hung provider.+REFRESH_PROMPT_SUGGESTION_TIMEOUT = dt.timedelta(minutes=5)SCANNER_SCHEDULE_ID_PREFIX = "replay-vision-scanner"# Search-attribute value stamped on every per-scanner schedule so the reconciler can list them.diff --git a/products/replay_vision/backend/tests/test_prompt_agent.py b/products/replay_vision/backend/tests/test_prompt_agent.pynew file mode 100644index 000000000000..2a59e796db1b--- /dev/null+++ b/products/replay_vision/backend/tests/test_prompt_agent.py@@ -0,0 +1,198 @@+import json+import time+from typing import Any++from unittest.mock import patch++from django.utils import timezone++from google.genai import types+from parameterized import parameterized++from posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership, User+from posthog.session_recordings.models.session_recording import SessionRecording++from products.replay_vision.backend.models.replay_observation import (+ ObservationStatus,+ ObservationTrigger,+ ReplayObservation,+)+from products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabel+from products.replay_vision.backend.prompt_suggestions import (+ _MAX_SUMMARIES_PER_RUN,+ _MAX_TOOL_ROUNDS,+ _AgentToolState,+ _dispatch_agent_tool,+ _generate_agentic,+)+from products.replay_vision.backend.tests.test_api import _VisionAPITestCase++from ee.models.rbac.access_control import AccessControl+++def _call(name: str, args: dict[str, Any]) -> types.FunctionCall:+ return types.FunctionCall(name=name, args=args)+++class _Candidate:+ def __init__(self) -> None:+ self.content = "model-turn"+++class _Response:+ def __init__(self, *, calls: list[types.FunctionCall] | None = None, text: str = "") -> None:+ self.function_calls = calls or []+ self.candidates = [_Candidate()]+ self.text = text+++class TestPromptAgent(_VisionAPITestCase):+ def setUp(self) -> None:+ super().setUp()+ self.scanner = self._create_scanner()+ self.observation = ReplayObservation.objects.create(+ scanner=self.scanner,+ team=self.team,+ session_id="sess-1",+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ triggered_by=ObservationTrigger.ON_DEMAND,+ scanner_snapshot={"scanner_version": 1},+ scanner_result={+ "model_output": {+ "verdict": "no",+ "confidence": 0.9,+ "scanner_type": "monitor",+ "reasoning": "the user closed the tab at payment",+ },+ "signals_count": 0,+ },+ )+ ReplayObservationLabel.objects.create(observation=self.observation, is_correct=False, feedback="should be yes")++ def _state(self, *, allow_cold_summaries: bool = False, budget_s: float = 60.0) -> _AgentToolState:+ return _AgentToolState(self.scanner, self.user, allow_cold_summaries, time.monotonic() + budget_s)++ def test_tool_rounds_run_then_final_structured_answer_parses(self) -> None:+ answer = json.dumps({"suggested_prompt": "better prompt", "rationale": "grounded in sess-1"})+ responses = iter(+ [+ _Response(calls=[_call("get_rated_observation", {"session_id": "sess-1"})]),+ _Response(), # model is done with tools+ _Response(text=answer), # forced structured turn+ ]+ )+ with (+ patch("products.replay_vision.backend.prompt_suggestions.genai"),+ patch(+ "products.replay_vision.backend.prompt_suggestions._model_call",+ side_effect=lambda *a, **k: next(responses),+ ),+ ):+ parsed = _generate_agentic(+ scanner=self.scanner,+ user_content="briefing",+ user=self.user,+ allow_cold_summaries=False,+ distinct_id="test",+ )+ self.assertEqual(parsed.suggested_prompt, "better prompt")++ @parameterized.expand(+ [+ ("round_budget_exhausted", 60.0, _MAX_TOOL_ROUNDS + 2),+ ("time_budget_exhausted", 0.0, 2),+ ]+ )+ def test_exhausted_budget_answers_pending_tool_calls_before_the_final_turn(+ self, _name: str, budget_s: float, expected_model_calls: int+ ) -> None:+ answer = json.dumps({"suggested_prompt": "better prompt", "rationale": "grounded"})+ seen_contents: list[list[Any]] = []++ def fake_model_call(client: Any, contents: list[Any], config: Any, **kwargs: Any) -> _Response:+ seen_contents.append(list(contents))+ if config.response_json_schema is not None:+ return _Response(text=answer)+ return _Response(calls=[_call("get_rated_observation", {"session_id": "sess-1"})])++ with (+ patch("products.replay_vision.backend.prompt_suggestions._AGENT_BUDGET_INLINE_S", budget_s),+ patch("products.replay_vision.backend.prompt_suggestions.genai"),+ patch("products.replay_vision.backend.prompt_suggestions._model_call", side_effect=fake_model_call),+ ):+ parsed = _generate_agentic(+ scanner=self.scanner,+ user_content="briefing",+ user=self.user,+ allow_cold_summaries=False,+ distinct_id="test",+ )+ self.assertEqual(parsed.suggested_prompt, "better prompt")+ self.assertEqual(len(seen_contents), expected_model_calls)+ # The last user turn must answer the still-pending call, or Gemini rejects the conversation.+ final_turn = seen_contents[-1][-1]+ self.assertEqual(+ [p.function_response.name for p in final_turn.parts if p.function_response is not None],+ ["get_rated_observation"],+ )+ self.assertEqual(final_turn.parts[-1].text, "Respond now with the JSON answer.")++ def test_observation_tool_returns_full_detail_and_summary_tool_budgets_cold_runs(self) -> None:+ state = self._state()++ detail = _dispatch_agent_tool(state, _call("get_rated_observation", {"session_id": "sess-1"}))+ self.assertEqual(detail["rating"], "thumbs_down")+ self.assertEqual(detail["feedback"], "should be yes")+ self.assertEqual(detail["reasoning"], "the user closed the tab at payment")++ listing = _dispatch_agent_tool(state, _call("list_rated_sessions", {}))+ self.assertEqual(listing["total"], 1)+ self.assertEqual(listing["sessions"][0]["session_id"], "sess-1")++ summary = _dispatch_agent_tool(state, _call("get_session_summary", {"session_id": "sess-1"}))+ self.assertIn("error", summary) # no cached summary, cold generation disallowed here++ cold_state = self._state(allow_cold_summaries=True, budget_s=600.0)+ cold_state.cold_summaries_used = _MAX_SUMMARIES_PER_RUN+ capped = _dispatch_agent_tool(cold_state, _call("get_session_summary", {"session_id": "sess-1"}))+ self.assertIn("budget", capped["error"])++ drained = self._state(allow_cold_summaries=True, budget_s=0.0)+ timed_out = _dispatch_agent_tool(drained, _call("get_session_summary", {"session_id": "sess-1"}))+ self.assertIn("time", timed_out["error"])++ def test_summary_tool_refuses_deleted_and_inaccessible_recordings(self) -> None:+ recording = SessionRecording.objects.create(team=self.team, session_id="sess-1", deleted=True)+ deleted = _dispatch_agent_tool(self._state(), _call("get_session_summary", {"session_id": "sess-1"}))+ self.assertIn("deleted", deleted["error"])++ recording.deleted = False+ recording.save()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ denied_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=denied_user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="session_recording",+ resource_id=None,+ access_level="none",+ organization_member=membership,+ )+ denied_state = _AgentToolState(self.scanner, denied_user, False, time.monotonic() + 60.0)+ denied = _dispatch_agent_tool(denied_state, _call("get_session_summary", {"session_id": "sess-1"}))+ self.assertIn("not accessible", denied["error"])++ # Background refresh with no scanner creator: fail closed rather than serve cached summaries.+ userless_state = _AgentToolState(self.scanner, None, True, time.monotonic() + 600.0)+ userless = _dispatch_agent_tool(userless_state, _call("get_session_summary", {"session_id": "sess-1"}))+ self.assertIn("not accessible", userless["error"])++ def test_unknown_session_and_unknown_tool_return_errors(self) -> None:+ state = self._state()+ self.assertIn("error", _dispatch_agent_tool(state, _call("get_rated_observation", {"session_id": "nope"})))+ self.assertIn("error", _dispatch_agent_tool(state, _call("hack_the_planet", {})))diff --git a/products/replay_vision/backend/tests/test_prompt_suggestions_api.py b/products/replay_vision/backend/tests/test_prompt_suggestions_api.pyindex 8e01ab89b025..567823e521cc 100644--- a/products/replay_vision/backend/tests/test_prompt_suggestions_api.py+++ b/products/replay_vision/backend/tests/test_prompt_suggestions_api.py@@ -24,17 +24,29 @@ class TestPromptSuggestions(_VisionAPITestCase):def setUp(self) -> None:super().setUp()self.scanner = self._create_scanner()+ self.canned = _LlmPromptSuggestion(+ suggested_prompt="Did the user place an order? Only answer yes on an order confirmation.",+ rationale="Tightened the yes condition using the rated sessions.",+ )+ # The agentic loop has its own tests. API tests mock it out, along with its single-shot fallback.+ self.agentic_patcher = patch(+ "products.replay_vision.backend.prompt_suggestions._generate_agentic", side_effect=self._agentic+ )+ self.mock_agentic = self.agentic_patcher.start()self.generate_patcher = patch(- "products.replay_vision.backend.prompt_suggestions._generate",- return_value=_LlmPromptSuggestion(- suggested_prompt="Did the user place an order? Only answer yes on an order confirmation.",- rationale="Tightened the yes condition using the rated sessions.",- ),+ "products.replay_vision.backend.prompt_suggestions._generate", side_effect=self._single_shot)self.mock_generate = self.generate_patcher.start()+ def _agentic(self, **_kwargs) -> _LlmPromptSuggestion:+ return self.canned++ def _single_shot(self, **_kwargs) -> _LlmPromptSuggestion:+ return self.canned+def tearDown(self) -> None:self.generate_patcher.stop()+ self.agentic_patcher.stop()super().tearDown()def _suggestions_url(self, suffix: str = "") -> str:@@ -161,7 +173,7 @@ class TestPromptSuggestions(_VisionAPITestCase):def test_apply_rejects_prompt_failing_scanner_config_validation(self) -> None:self._create_rated_observation("sess-1", False, "should be yes")- self.mock_generate.return_value = _LlmPromptSuggestion(suggested_prompt="x" * 20_001, rationale="too long")+ self.canned = _LlmPromptSuggestion(suggested_prompt="x" * 20_001, rationale="too long")suggestion_id = self.client.post(self._suggestions_url("generate/")).json()["id"]prompt_before = ReplayScanner.objects.get(id=self.scanner.id).scanner_config.get("prompt")@@ -183,7 +195,7 @@ class TestPromptSuggestions(_VisionAPITestCase):def test_generate_marks_no_change_when_model_returns_current_prompt(self) -> None:self._create_rated_observation("sess-1", True)- self.mock_generate.return_value = _LlmPromptSuggestion(+ self.canned = _LlmPromptSuggestion(suggested_prompt="did the user check out?",rationale="The prompt already handles the rated sessions well.",)@@ -199,7 +211,7 @@ class TestPromptSuggestions(_VisionAPITestCase):self.client.post(self._suggestions_url("generate/"))- user_content = self.mock_generate.call_args.kwargs["user_content"]+ user_content = self.mock_agentic.call_args.kwargs["user_content"]self.assertIn("Previously rejected rewrites", user_content)self.assertIn("Did the user place an order? Only answer yes on an order confirmation.", user_content)@@ -207,9 +219,10 @@ class TestPromptSuggestions(_VisionAPITestCase):# No ratings at all: nothing to generate from.self.assertEqual(refresh_prompt_suggestion_if_stale(self.scanner), "no_ratings")- # Ratings but no suggestion yet: generate immediately.+ # Ratings but no suggestion yet: generate immediately, unattributed (no requesting user).self._create_rated_observation("sess-1", False, "should be yes")self.assertEqual(refresh_prompt_suggestion_if_stale(self.scanner), "generated")+ self.assertIsNone(ReplayScannerPromptSuggestion.objects.get().created_by)# Same rated set: skip regardless of age.self.assertEqual(refresh_prompt_suggestion_if_stale(self.scanner), "ratings_unchanged")@@ -223,6 +236,16 @@ class TestPromptSuggestions(_VisionAPITestCase):self.assertEqual(refresh_prompt_suggestion_if_stale(self.scanner), "generated")self.assertEqual(ReplayScannerPromptSuggestion.objects.count(), 2)+ def test_falls_back_to_single_shot_when_the_agent_fails(self) -> None:+ self._create_rated_observation("sess-1", False, "should be yes")+ self.mock_agentic.side_effect = RuntimeError("provider hiccup")++ resp = self.client.post(self._suggestions_url("generate/"))++ self.assertEqual(resp.status_code, 200, resp.json())+ self.assertEqual(resp.json()["status"], "pending")+ self.mock_generate.assert_called_once()+def test_mutations_require_editor_access(self) -> None:self._create_rated_observation("sess-1", False, "should be yes")with patch(