: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
fix(user-interviews): own per-call greeting via firstMessage override (#58690)
Paul D'Ambrabd2ab4c964b0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 4f1c4d8b53c5..e0aef4c7b7d8 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1453,21 +1453,21 @@ snapshots:exporter-funnels--funnel-top-to-bottom-insight-no-results--light:hash: v1.k794b7964.9225d8fd25066264d4b17b2f2e1eaf912252f71215ef01f66375d816baa65b5b.rnlYKUzVzsDLlpiLMAhUCDJTh_3kbaraSu98rjmdmEcexporter-interview--default--medium--dark:- hash: v1.k794b7964.7c4eb178ea47aecef441a210979fd749a5393e612c3116c5aea81fcfa5fd01fc.QmSK8ISG9yruiBWiU6f7Ef706DTEvpTqDx8hJWJ53kM+ hash: v1.k794b7964.daab56e95a7e7d2788baffbd282701f3cfb180e07f13d07914266765361920c5.H-ljHuTGZAZX3YLo3Ar1Ukmx3PHbdex9A7560tkLjaQexporter-interview--default--medium--light:- hash: v1.k794b7964.d4ce02ae0b66a073a445985d229f3a24b71c5c8a42f6f39c32d0d6186d0dc568.Kg9QjtCPGiRvNuXeoz6FMKRgD8zs9zu3ldBS7i87T6Y+ hash: v1.k794b7964.569f151ec0831a0e6de7d7efa2949474df821341fa6597d6289e5cc6192dae0c.cCQGiuciC1_aIVrejuIl5cyvEhe4VABO3XiGiG2D5REexporter-interview--default--narrow--dark:- hash: v1.k794b7964.4534dd934dd7b596d5e0f7eae452809f6bab2c212703d5d81fd2265ef0a56201.GD7KsJkH1LDNFyjIkcP8iKkBnJ610NYUk34quRnzHP0+ hash: v1.k794b7964.c5d1437cfd56dabfbd8af5daf3757996aadd87092f584f7280d161909e975f85.ejQNZ9Yl8Z3VufS5ZX-h2oYg-fMA_ppiQ8zhpWnEq4Qexporter-interview--default--narrow--light:- hash: v1.k794b7964.0b5b45f4dded145fc0caee559eae27bc48e351ace5755c66ceb3539a2148b81a.TrV6E4VwY1GTujrD620T6jE5gF2WTqHCDIXi6P4925w+ hash: v1.k794b7964.6ade7fe0413540d73d82239dd45821d638380d0879cf46780edfdbc9c1814539.0_prkMrs4ftyDEWiQ8plqASHQiDYwfFcphr3R2Dv_1Iexporter-interview--default--superwide--dark:- hash: v1.k794b7964.e2b7be92c8dda676881b79c1ebee852fdf0da4ae9308538300626d76aa4808ec.XsZFx-0VpczPh1ok3v9MJ4vMq4NOenahTfn2DmpGaLQ+ hash: v1.k794b7964.41ea5e2e3e174ac809b010fadc246a1315c7263777978677eec724449ef32d81.QNvImPw9RkM-TFB7f-CWXUn3V6yR0DmMeWus0tLYmFkexporter-interview--default--superwide--light:- hash: v1.k794b7964.a3938a530517fe018b35ea523063fea3dfb21eb8751b5c7fe580b98a3f1e45ca.A05A4GLE7zM2g_QYoLZFK3YZJVv9jRkSXosLC8poJfo+ hash: v1.k794b7964.1675bc003e7142c1328279738ec7cd0d45ecf0a52ae9abbbc320ec8db1221da8.liMMBPIDmabE5mfsqp0ka3qB967Qtm-ZvlB6qVBbhHYexporter-interview--default--wide--dark:- hash: v1.k794b7964.7822c8871f1bb27bde31297394f0e8dc9cc6d80066d44d2b9d21f393816becb4.WbD1ja7-iBct5bq_yiSjKd1LVvCuhpDcsKcbK9acD80+ hash: v1.k794b7964.6caf4c0f2e71bac84d0e35553d64e58ee9063906c4e5fa8e1206c1735581b2c6.B7k4mZ7rZwmQ-bshHdOOfcVm-VdWzpmD3TEem_on81Mexporter-interview--default--wide--light:- hash: v1.k794b7964.fe86239bbd8dc4e4556a9c0b7d69f46c5c43b700f0a7476d868fb0a47e61188a.PQPuSD0pjKnAog9H8u-XRvGiao8qVi3fNEIFSAkcr-E+ hash: v1.k794b7964.23706fa0881fe973e4ccaf0e9935adaf51894528225d5a4042d8208302f7013e.tuXs1vpOUQ9Gjs7ZKME-TRHM0PRM5RFTqjRm8DQO0FMexporter-other--event-table-insight--dark:hash: v1.k794b7964.cdefc1d85f5f375fb9b15ecb4b6a371e98175c5ae136d57dd3b6d204096457c2.IRs92pwVTJ7WYExLWPu1he-krTNZ8WtsG9Rwgm6qYrsexporter-other--event-table-insight--light:diff --git a/frontend/src/exporter/scenes/ExporterInterviewScene.tsx b/frontend/src/exporter/scenes/ExporterInterviewScene.tsxindex ef801a4d40fb..ca83268c03dd 100644--- a/frontend/src/exporter/scenes/ExporterInterviewScene.tsx+++ b/frontend/src/exporter/scenes/ExporterInterviewScene.tsx@@ -1,24 +1,205 @@import Vapi from '@vapi-ai/web'-import { useEffect, useRef, useState } from 'react'+import { memo, useCallback, useEffect, useRef, useState } from 'react'import { LemonButton } from '@posthog/lemon-ui'import { Logo } from 'lib/brand/Logo'-import { RobotHog } from 'lib/components/hedgehogs'+import { HeartHog, MicrophoneHog, ProfessorHog, RobotHog } from 'lib/components/hedgehogs'import { InterviewExportPayload } from '../types'type CallState = 'idle' | 'loading' | 'connecting' | 'in-call' | 'ended' | 'error'+type ConversationPhase = 'agent-talking' | 'user-speaking' | 'waiting'++const USER_SPEAKING_VOLUME_ENTER = 0.05+const USER_SPEAKING_VOLUME_LEAVE = 0.03++const PHASE_LABELS: Record<ConversationPhase, string> = {+ 'agent-talking': 'Talking…',+ 'user-speaking': 'Listening…',+ waiting: 'Thinking…',+}+interface StartCallPayload {public_key: stringassistant_id: stringassistant_overrides: {+ firstMessage?: stringvariableValues?: Record<string, string>metadata?: Record<string, string>}}+function pickHog(state: CallState, phase: ConversationPhase): typeof RobotHog {+ if (state === 'in-call') {+ if (phase === 'agent-talking') {+ return RobotHog+ }+ if (phase === 'user-speaking') {+ return MicrophoneHog+ }+ return ProfessorHog+ }+ if (state === 'ended') {+ return HeartHog+ }+ return RobotHog+}++const CallStatusPanel = memo(function CallStatusPanel({+ state,+ phase,+}: {+ state: CallState+ phase: ConversationPhase+}): JSX.Element {+ const Hog = pickHog(state, phase)+ return (+ <div className="flex-shrink-0 mx-auto md:mx-0 md:w-40">+ <div className="w-40 h-40 mx-auto">+ <Hog className="w-full h-full" alt="" />+ </div>+ {state === 'in-call' && <p className="text-sm text-muted text-center mt-2">{PHASE_LABELS[phase]}</p>}+ </div>+ )+})++function PreCallIntro({ interview }: { interview: InterviewExportPayload }): JSX.Element {+ return (+ <>+ <h1 className="text-3xl font-bold mb-4">Hi {interview.user_name}!</h1>+ <p className="text-lg mb-4">+ We're researching <strong>{interview.topic}</strong> and would love to hear your perspective.+ </p>+ <p className="text-muted mb-6">+ This is a 5–10 minute voice conversation with an AI interviewer. Talk like you would to a researcher on+ our team — your feedback helps us build a better product.+ </p>+ <div className="bg-accent-highlight border border-accent p-4 rounded mb-6 text-sm">+ <strong>How it works</strong>+ <ol className="list-decimal pl-5 mt-2 space-y-1">+ <li>+ Click <em>Start interview</em> below.+ </li>+ <li>Allow microphone access when prompted.</li>+ <li>Have a casual conversation — the AI will guide you through a few questions.</li>+ <li>You can end the call any time.</li>+ </ol>+ </div>+ </>+ )+}++function ConnectingPanel(): JSX.Element {+ return (+ <>+ <h2 className="text-2xl font-bold mb-2">Connecting…</h2>+ <p className="text-muted">Hold tight while we connect you to the AI interviewer.</p>+ </>+ )+}++function LivePanel(): JSX.Element {+ return (+ <>+ <h2 className="text-2xl font-bold mb-2">You're live</h2>+ <p className="text-muted mb-2">Talk as you would to a researcher on our team.</p>+ <p className="text-xs text-muted">+ End the call any time using the button below — the recording will still be saved.+ </p>+ </>+ )+}++function EndedPanel(): JSX.Element {+ return (+ <>+ <h2 className="text-2xl font-bold mb-2">Thanks for taking the time!</h2>+ <p className="text-muted">+ Your conversation has been recorded — we'll be in touch if we have follow-up questions.+ </p>+ </>+ )+}++function ErrorPanel({ errorMessage }: { errorMessage: string | null }): JSX.Element {+ return (+ <div className="text-danger">+ <h2 className="text-2xl font-bold mb-2">Something went wrong</h2>+ <p className="mb-2">{errorMessage ?? 'Unknown error.'}</p>+ </div>+ )+}++function CallActionButton({+ state,+ onStart,+ onStop,+ onRetry,+}: {+ state: CallState+ onStart: () => void+ onStop: () => void+ onRetry: () => void+}): JSX.Element | null {+ switch (state) {+ case 'idle':+ return (+ <LemonButton type="primary" size="large" fullWidth onClick={onStart}>+ Start interview+ </LemonButton>+ )+ case 'loading':+ return <p>Loading interviewer…</p>+ case 'in-call':+ return (+ <LemonButton type="secondary" onClick={onStop}>+ End interview+ </LemonButton>+ )+ case 'error':+ return (+ <LemonButton type="secondary" onClick={onRetry}>+ Try again+ </LemonButton>+ )+ case 'connecting':+ case 'ended':+ return null+ }+}++const CallBodyPanel = memo(function CallBodyPanel({+ state,+ interview,+ errorMessage,+ onStart,+ onStop,+ onRetry,+}: {+ state: CallState+ interview: InterviewExportPayload+ errorMessage: string | null+ onStart: () => void+ onStop: () => void+ onRetry: () => void+}): JSX.Element {+ const isPreCall = state === 'idle' || state === 'loading'+ return (+ <div className="flex-1 min-w-0">+ {isPreCall && <PreCallIntro interview={interview} />}+ {state === 'connecting' && <ConnectingPanel />}+ {state === 'in-call' && <LivePanel />}+ {state === 'ended' && <EndedPanel />}+ {state === 'error' && <ErrorPanel errorMessage={errorMessage} />}+ <div className="mt-4">+ <CallActionButton state={state} onStart={onStart} onStop={onStop} onRetry={onRetry} />+ </div>+ </div>+ )+})+/*** Fetch the Vapi public key, assistant id, and *full* assistant overrides (including* `agent_context`) from the server only when the interviewee clicks Start. Keeps the@@ -45,8 +226,12 @@ export default function ExporterInterviewScene({accessToken?: string}): JSX.Element {const [state, setState] = useState<CallState>('idle')+ const [conversationPhase, setConversationPhase] = useState<ConversationPhase>('waiting')const [errorMessage, setErrorMessage] = useState<string | null>(null)const vapiRef = useRef<Vapi | null>(null)+ const agentTalkingRef = useRef<boolean>(false)+ const lastPhaseRef = useRef<ConversationPhase>('waiting')+ const isMountedRef = useRef<boolean>(true)useEffect(() => {document.title = `Interview · ${interview.topic}`@@ -54,39 +239,91 @@ export default function ExporterInterviewScene({useEffect(() => {return () => {+ isMountedRef.current = falsevapiRef.current?.stop()+ vapiRef.current = null}}, [])- const start = async (): Promise<void> => {+ const start = useCallback((): void => {if (!accessToken) {setErrorMessage('Interview link is missing its access token. Open the URL you were emailed.')setState('error')return}+ vapiRef.current?.stop()+ vapiRef.current = null+ agentTalkingRef.current = false+ lastPhaseRef.current = 'waiting'+ setConversationPhase('waiting')setState('loading')- try {- const startPayload = await fetchStartCallPayload(accessToken)- const vapi = new Vapi(startPayload.public_key)- vapiRef.current = vapi- vapi.on('call-end', () => setState('ended'))- vapi.on('error', (e: unknown) => {- setErrorMessage(e instanceof Error ? e.message : 'Vapi reported an error during the call.')+ void (async () => {+ try {+ const startPayload = await fetchStartCallPayload(accessToken)+ if (!isMountedRef.current) {+ return+ }+ const vapi = new Vapi(startPayload.public_key)+ vapiRef.current = vapi+ const setPhase = (next: ConversationPhase): void => {+ if (lastPhaseRef.current === next) {+ return+ }+ lastPhaseRef.current = next+ setConversationPhase(next)+ }+ vapi.on('call-end', () => setState('ended'))+ vapi.on('error', (e: unknown) => {+ vapi.stop()+ setErrorMessage(e instanceof Error ? e.message : 'Vapi reported an error during the call.')+ setState('error')+ })+ vapi.on('speech-start', () => {+ agentTalkingRef.current = true+ setPhase('agent-talking')+ })+ vapi.on('speech-end', () => {+ agentTalkingRef.current = false+ setPhase('waiting')+ })+ vapi.on('volume-level', (volume: number) => {+ if (agentTalkingRef.current) {+ return+ }+ if (lastPhaseRef.current === 'user-speaking') {+ if (volume < USER_SPEAKING_VOLUME_LEAVE) {+ setPhase('waiting')+ }+ } else if (volume > USER_SPEAKING_VOLUME_ENTER) {+ setPhase('user-speaking')+ }+ })+ setState('connecting')+ await vapi.start(startPayload.assistant_id, startPayload.assistant_overrides)+ if (!isMountedRef.current) {+ vapi.stop()+ return+ }+ setState((current) => (current === 'connecting' ? 'in-call' : current))+ } catch (e) {+ if (!isMountedRef.current) {+ return+ }+ setErrorMessage(e instanceof Error ? e.message : 'Failed to start interview.')setState('error')- })- setState('connecting')- await vapi.start(startPayload.assistant_id, startPayload.assistant_overrides)- setState('in-call')- } catch (e) {- setErrorMessage(e instanceof Error ? e.message : 'Failed to start interview.')- setState('error')- }- }+ }+ })()+ }, [accessToken])- const stop = (): void => {+ const stop = useCallback((): void => {vapiRef.current?.stop()setState('ended')- }+ }, [])++ const retry = useCallback((): void => {+ setErrorMessage(null)+ setState('idle')+ }, [])return (<div className="max-w-2xl mx-auto px-4 py-12">@@ -95,62 +332,18 @@ export default function ExporterInterviewScene({<span className="text-xs text-muted">Powered by PostHog</span></div>- <div className="flex justify-center mb-6">- <RobotHog className="w-40 h-40" alt="" />+ <div className="flex flex-col md:flex-row md:items-start gap-6 md:gap-8 mb-8">+ <CallStatusPanel state={state} phase={conversationPhase} />+ <CallBodyPanel+ state={state}+ interview={interview}+ errorMessage={errorMessage}+ onStart={start}+ onStop={stop}+ onRetry={retry}+ /></div>- <h1 className="text-3xl font-bold mb-4">Hi {interview.user_name}!</h1>-- <p className="text-lg mb-4">- We're researching <strong>{interview.topic}</strong> and would love to hear your perspective.- </p>-- <p className="text-muted mb-6">- This is a 5–10 minute voice conversation with an AI interviewer. Talk like you would to a researcher on- our team — your feedback helps us build a better product.- </p>-- <div className="bg-accent-highlight border border-accent p-4 rounded mb-8 text-sm">- <strong>How it works</strong>- <ol className="list-decimal pl-5 mt-2 space-y-1">- <li>- Click <em>Start interview</em> below.- </li>- <li>Allow microphone access when prompted.</li>- <li>Have a casual conversation — the AI will guide you through a few questions.</li>- <li>You can end the call any time.</li>- </ol>- </div>-- {state === 'idle' && (- <LemonButton type="primary" size="large" fullWidth onClick={start}>- Start interview- </LemonButton>- )}- {state === 'loading' && <p>Loading interviewer…</p>}- {state === 'connecting' && <p>Connecting…</p>}- {state === 'in-call' && (- <div>- <p className="mb-4">You're live with the interviewer.</p>- <LemonButton type="secondary" onClick={stop}>- End interview- </LemonButton>- </div>- )}- {state === 'ended' && (- <p className="text-success">- Thanks for taking the time! Your conversation has been recorded — we'll be in touch.- </p>- )}- {state === 'error' && (- <div className="text-danger">- <p className="mb-2">{errorMessage ?? 'Something went wrong.'}</p>- <LemonButton type="secondary" onClick={() => setState('idle')}>- Try again- </LemonButton>- </div>- )}-<p className="text-xs text-muted text-center mt-12">Your conversation will be transcribed and analyzed to help improve PostHog. We won't share yourindividual responses publicly.diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.pyindex 6ac51a1de647..de1019b59a29 100644--- a/products/user_interviews/backend/test_interview_sharing.py+++ b/products/user_interviews/backend/test_interview_sharing.py@@ -4,6 +4,7 @@ import hashlibimport datetimefrom typing import Any+import unittestfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -19,7 +20,7 @@ from posthog.models.sharing_configuration import SharingConfigurationfrom products.user_interviews.backend.api import UserInterviewTopicSerializerfrom products.user_interviews.backend.models import IntervieweeContext, UserInterview, UserInterviewTopic-from products.user_interviews.backend.webhooks import EMBEDDING_CONTENT_MAX_BYTES+from products.user_interviews.backend.webhooks import EMBEDDING_CONTENT_MAX_BYTES, _build_first_messageclass _FeatureFlagEnabledMixin(APIBaseTest):@@ -324,6 +325,48 @@ class TestInterviewPublicViewer(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+class TestBuildFirstMessage(unittest.TestCase):+ @parameterized.expand(+ [+ ("simple_name_and_topic", "Paul", "taxonomic filter search", ["Hi Paul!", "taxonomic filter search"]),+ ("dotted_local_part", "Cory S", "session replay adoption", ["Hi Cory S!", "session replay adoption"]),+ (+ "name_with_trailing_topic_whitespace",+ "Kim",+ " feature flag rollout ",+ ["Hi Kim!", "feature flag rollout"],+ ),+ ]+ )+ def test_includes_name_and_topic(self, _label: str, user_name: str, topic_text: str, expected_fragments: list[str]):+ message = _build_first_message(user_name=user_name, topic_text=topic_text)+ for fragment in expected_fragments:+ assert fragment in message++ @parameterized.expand([("empty", ""), ("whitespace_only", " ")])+ def test_drops_topic_sentence_when_topic_empty(self, _label: str, topic_text: str):+ message = _build_first_message(user_name="Sam", topic_text=topic_text)+ assert "Hi Sam!" in message+ assert "Today we're talking about" not in message++ @parameterized.expand([("empty", ""), ("whitespace_only", " ")])+ def test_falls_back_to_generic_greeting_when_user_name_empty(self, _label: str, user_name: str):+ message = _build_first_message(user_name=user_name, topic_text="checkout funnel")+ assert "Hi there!" in message+ assert "Hi !" not in message++ def test_collapses_internal_whitespace_in_topic(self):+ message = _build_first_message(user_name="Sam", topic_text="multi\nline\n\ttopic")+ assert "multi line topic" in message+ assert "\n" not in message++ def test_truncates_very_long_topic(self):+ long_topic = "x" * 500+ message = _build_first_message(user_name="Sam", topic_text=long_topic)+ assert "x" * 200 in message+ assert "x" * 201 not in message++class TestInterviewStartCall(APIBaseTest):def _create_share(self) -> SharingConfiguration:topic = UserInterviewTopic.objects.create(@@ -359,6 +402,16 @@ 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_personalised_first_message(self):+ share = self._create_share()+ self.client.logout()+ response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")+ assert response.status_code == status.HTTP_200_OK, response.content+ first_message = response.json()["assistant_overrides"]["firstMessage"]+ assert "Hi Alex!" in first_message+ assert "Replay adoption" in first_message+@override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")def test_rejects_disabled_share(self):share = self._create_share()diff --git a/products/user_interviews/backend/webhooks.py b/products/user_interviews/backend/webhooks.pyindex 7c08d696cdd5..ea32179920ce 100644--- a/products/user_interviews/backend/webhooks.py+++ b/products/user_interviews/backend/webhooks.py@@ -129,6 +129,24 @@ def _public_sharing_disabled_for_org(sharing_config: SharingConfiguration) -> bo)+_TOPIC_MAX_CHARS = 200+++def _normalise_topic(topic_text: str) -> str:+ return " ".join(topic_text.split())[:_TOPIC_MAX_CHARS]+++def _build_first_message(*, user_name: str, topic_text: str) -> str:+ name_part = f"Hi {user_name.strip()}!" if user_name.strip() else "Hi there!"+ greeting = f"{name_part} Thanks for joining."+ topic_normalised = _normalise_topic(topic_text)+ if topic_normalised:+ return (+ f"{greeting} Today we're talking about {topic_normalised}. I'd love your perspective. Ready when you are."+ )+ return f"{greeting} I'd love your perspective. Ready when you are."++@api_view(["POST"])@authentication_classes([])@permission_classes([AllowAny])@@ -164,12 +182,14 @@ def start_call(request: Request, access_token: str) -> Response:topic = ic.topicuser_name, _ = _parse_identifier(ic.interviewee_identifier)agent_context = _merge_agent_context(topic.agent_context or "", ic.agent_context or "")+ first_message = _build_first_message(user_name=user_name, topic_text=topic.topic or "")return Response({"public_key": settings.VAPI_PUBLIC_KEY,"assistant_id": settings.VAPI_ASSISTANT_ID,"assistant_overrides": {+ "firstMessage": first_message,"variableValues": {"userName": user_name,"topic": topic.topic or "",