Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(user-interviews): scope Vapi server messages, emit lifecycle events (#58752)

Paul D'Ambra28a9203ace3a
diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.py
index 7a1475c10257..5ee9cc547c37 100644
--- a/products/user_interviews/backend/test_interview_sharing.py
+++ b/products/user_interviews/backend/test_interview_sharing.py
@@ -476,6 +476,17 @@ class TestInterviewStartCall(APIBaseTest):
self.assertEqual(overrides["metadata"]["sharing_access_token"], share.access_token)
self.assertEqual(overrides["metadata"]["interviewee_identifier"], "[email protected]")
+ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
+ def test_returns_scoped_server_messages(self):
+ share = self._create_share()
+ self.client.logout()
+ response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ overrides = response.json()["assistant_overrides"]
+ # Scoped to the two lifecycle events we act on — keeps Vapi from sending
+ # speech-update / conversation-update / etc that we'd just ignore.
+ self.assertEqual(overrides["serverMessages"], ["status-update", "end-of-call-report"])
+
@override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
def test_returns_personalised_first_message(self):
share = self._create_share()
@@ -626,12 +637,96 @@ class TestVapiWebhook(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
@override_settings(VAPI_WEBHOOK_SECRET="topsecret")
- def test_webhook_ignores_non_end_of_call_events(self):
+ def test_webhook_ignores_unknown_message_types(self):
self.client.logout()
- response = self._signed_post("topsecret", {"message": {"type": "status-update"}})
+ response = self._signed_post("topsecret", {"message": {"type": "speech-update"}})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["status"], "ignored")
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ @patch("products.user_interviews.backend.webhooks.posthoganalytics.capture")
+ def test_webhook_status_update_in_progress_captures_started_event(self, mock_capture):
+ share = self._create_share()
+ self.client.logout()
+ response = self._signed_post(
+ "topsecret",
+ {
+ "message": {
+ "type": "status-update",
+ "status": "in-progress",
+ "call": {"id": "call_xyz", "metadata": {"sharing_access_token": share.access_token}},
+ }
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ mock_capture.assert_called_once()
+ kwargs = mock_capture.call_args.kwargs
+ self.assertEqual(kwargs["event"], "user_interview_conversation_started")
+ # distinct_id is intentionally an opaque interviewee_context UUID — not the
+ # email — so these feature-usage events don't create person profiles for the
+ # third-party interviewees.
+ assert share.interviewee_context is not None
+ self.assertEqual(kwargs["distinct_id"], f"user_interview:{share.interviewee_context.id}")
+ self.assertNotIn("[email protected]", kwargs["distinct_id"])
+ self.assertEqual(kwargs["properties"]["call_id"], "call_xyz")
+
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ @patch("products.user_interviews.backend.webhooks.posthoganalytics.capture")
+ def test_webhook_status_update_duplicate_in_progress_emits_same_insert_id(self, mock_capture):
+ # Vapi re-fires `status-update / in-progress` on transient drops + warm-transfer flows.
+ # We tag every started event with `$insert_id` = "user_interview_conversation_started:<call_id>"
+ # so PostHog dedupes the second delivery at ingest. Both captures fire here (we don't
+ # de-dup client-side); the contract is that they share an insert_id.
+ share = self._create_share()
+ self.client.logout()
+ payload = {
+ "message": {
+ "type": "status-update",
+ "status": "in-progress",
+ "call": {"id": "call_xyz", "metadata": {"sharing_access_token": share.access_token}},
+ }
+ }
+ self._signed_post("topsecret", payload)
+ self._signed_post("topsecret", payload)
+ self.assertEqual(mock_capture.call_count, 2)
+ for call in mock_capture.call_args_list:
+ self.assertEqual(call.kwargs["properties"]["$insert_id"], "user_interview_conversation_started:call_xyz")
+
+ @parameterized.expand([("ringing",), ("ended",), ("queued",), ("forwarding",), ("scheduled",)])
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ @patch("products.user_interviews.backend.webhooks.posthoganalytics.capture")
+ def test_webhook_status_update_other_statuses_do_not_capture(self, call_status: str, mock_capture):
+ share = self._create_share()
+ self.client.logout()
+ response = self._signed_post(
+ "topsecret",
+ {
+ "message": {
+ "type": "status-update",
+ "status": call_status,
+ "call": {"id": "call_xyz", "metadata": {"sharing_access_token": share.access_token}},
+ }
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ mock_capture.assert_not_called()
+
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ @patch("products.user_interviews.backend.webhooks.posthoganalytics.capture")
+ def test_webhook_end_of_call_report_captures_ended_event(self, mock_capture):
+ share = self._create_share()
+ self.client.logout()
+ response = self._signed_post("topsecret", self._end_of_call_payload(share.access_token))
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ mock_capture.assert_called_once()
+ kwargs = mock_capture.call_args.kwargs
+ self.assertEqual(kwargs["event"], "user_interview_conversation_ended")
+ assert share.interviewee_context is not None
+ self.assertEqual(kwargs["distinct_id"], f"user_interview:{share.interviewee_context.id}")
+ self.assertNotIn("[email protected]", kwargs["distinct_id"])
+ self.assertTrue(kwargs["properties"]["had_transcript"])
+ self.assertTrue(kwargs["properties"]["had_summary"])
+
@override_settings(VAPI_WEBHOOK_SECRET="topsecret")
def test_webhook_is_idempotent_on_call_id(self):
share = self._create_share()
diff --git a/products/user_interviews/backend/webhooks.py b/products/user_interviews/backend/webhooks.py
index 94f1b23806f2..6a8de04d5a07 100644
--- a/products/user_interviews/backend/webhooks.py
+++ b/products/user_interviews/backend/webhooks.py
@@ -21,6 +21,7 @@ from django.db.models import Q
from django.utils.timezone import now
import structlog
+import posthoganalytics
from rest_framework import status
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import AllowAny
@@ -31,6 +32,7 @@ from posthog.schema import EmbeddingModelName
from posthog.api.embedding_worker import emit_embedding_request
from posthog.constants import AvailableFeature
+from posthog.event_usage import groups
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.team import Team
from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
@@ -253,6 +255,11 @@ def start_call(request: Request, access_token: str) -> Response:
"assistant_id": settings.VAPI_ASSISTANT_ID,
"assistant_overrides": {
"firstMessage": first_message,
+ # Scope server messages to just the lifecycle hooks we act on. Default Vapi
+ # config sends ~10 message types (speech-update, conversation-update, etc.)
+ # which we'd ignore anyway — and every ignored delivery still costs a
+ # webhook round-trip and a signature verification.
+ "serverMessages": ["status-update", "end-of-call-report"],
"variableValues": {
"userName": user_name,
"topic": topic.topic or "",
@@ -321,19 +328,41 @@ def vapi_webhook(request: Request) -> Response:
payload = request.data if isinstance(request.data, dict) else {}
message: dict[str, Any] = payload.get("message", {})
message_type = message.get("type")
+ call: dict[str, Any] = message.get("call", {}) or {}
+ metadata: dict[str, Any] = call.get("metadata", {}) or {}
+ access_token = metadata.get("sharing_access_token") or metadata.get("access_token")
+ call_id = call.get("id")
+
+ if message_type == "status-update":
+ # Lifecycle ping. We only act on `in-progress` (call started) — the `ended` status
+ # is followed by a separate `end-of-call-report` with the full transcript, so we
+ # capture the ended event from that branch where we already have the interview row.
+ call_status = message.get("status")
+ if call_status == "in-progress" and access_token:
+ sharing_config = _resolve_share(access_token)
+ if sharing_config is not None and sharing_config.interviewee_context is not None:
+ _capture_user_interview_event(
+ "user_interview_conversation_started",
+ sharing_config=sharing_config,
+ call_id=call_id,
+ )
+ logger.info(
+ "user_interviews_vapi_webhook_status_update",
+ call_status=call_status,
+ call_id=call_id,
+ )
+ return Response({"status": "ok"})
+
if message_type != "end-of-call-report":
- # Other event types (status updates, transcripts mid-call) are ignored.
+ # Other event types (transcripts mid-call, speech-update, etc.) shouldn't reach us —
+ # start_call's `serverMessages` override scopes Vapi to status-update + end-of-call-report.
+ # Anything else here means the assistant config drifted; log it so we notice.
logger.info(
"user_interviews_vapi_webhook_ignored_message_type",
message_type=message_type,
)
return Response({"status": "ignored"})
- call: dict[str, Any] = message.get("call", {}) or {}
- metadata: dict[str, Any] = call.get("metadata", {}) or {}
- access_token = metadata.get("sharing_access_token") or metadata.get("access_token")
- call_id = call.get("id")
-
if not access_token:
logger.warning(
"user_interviews_vapi_webhook_missing_access_token",
@@ -394,6 +423,17 @@ def vapi_webhook(request: Request) -> Response:
)
transaction.on_commit(lambda: _emit_interview_embeddings(interview, topic))
+ _capture_user_interview_event(
+ "user_interview_conversation_ended",
+ sharing_config=sharing_config,
+ call_id=call_id,
+ extra_properties={
+ "interview_id": str(interview.id),
+ "had_transcript": bool(interview.transcript),
+ "had_summary": bool(interview.summary),
+ },
+ )
+
logger.info(
"user_interviews_vapi_webhook_stored",
team_id=sharing_config.team_id,
@@ -401,3 +441,50 @@ def vapi_webhook(request: Request) -> Response:
interview_id=str(interview.id),
)
return Response({"status": "created", "interview_id": str(interview.id)}, status=status.HTTP_201_CREATED)
+
+
+def _capture_user_interview_event(
+ event: str,
+ *,
+ sharing_config: SharingConfiguration,
+ call_id: str | None,
+ extra_properties: dict[str, Any] | None = None,
+) -> None:
+ """Fire a PostHog event for a user-interview lifecycle moment (conversation started/ended).
+ Failures never propagate — analytics never blocks a webhook delivery.
+
+ Vapi emits `status-update` per state transition and may re-fire `in-progress` after
+ transient drops or warm-transfer flows, and end-of-call-report can be retried by Vapi
+ until we ack. Set `$insert_id` to `<event>:<call_id>` so PostHog dedupes the second
+ delivery at ingest — funnels see one start and one end per call.
+
+ The `distinct_id` is intentionally an opaque per-interviewee-context UUID — *not* the
+ interviewee's email/distinct_id — so these feature-usage events never create person
+ profiles for the third-party interviewees themselves. The events report on the
+ user_interviews feature, not the people being interviewed."""
+ interviewee_context = sharing_config.interviewee_context
+ if interviewee_context is None:
+ return
+ properties: dict[str, Any] = {
+ "topic_id": str(interviewee_context.topic_id),
+ "team_id": sharing_config.team_id,
+ "call_id": call_id,
+ }
+ if call_id:
+ properties["$insert_id"] = f"{event}:{call_id}"
+ if extra_properties:
+ properties.update(extra_properties)
+ try:
+ posthoganalytics.capture(
+ distinct_id=f"user_interview:{interviewee_context.id}",
+ event=event,
+ properties=properties,
+ groups=groups(organization=sharing_config.team.organization, team=sharing_config.team),
+ )
+ except Exception:
+ logger.exception(
+ "user_interviews_event_capture_failed",
+ event=event,
+ team_id=sharing_config.team_id,
+ call_id=call_id,
+ )