: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(user_interviews): add synthetic test interviewee link (#59504)
Paul D'Ambra5b443e720b5c
diff --git a/products/user_interviews/backend/presentation/views.py b/products/user_interviews/backend/presentation/views.pyindex 426e72813efd..4b3eecf8d917 100644--- a/products/user_interviews/backend/presentation/views.py+++ b/products/user_interviews/backend/presentation/views.py@@ -39,6 +39,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.email import EmailMessage, is_email_availablefrom posthog.models.sharing_configuration import SharingConfiguration+from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.permissions import PostHogFeatureFlagPermissionfrom posthog.tasks.exports.csv_exporter import _sanitize_formula_injection@@ -559,6 +560,33 @@ def _merge_agent_context(topic_context: str, personal_context: str) -> str:return "\n\n".join(parts)+class LatestTestInterviewSerializer(serializers.Serializer):+ completed_at = serializers.DateTimeField(+ help_text="When the test interview was completed.",+ )+ transcript = serializers.CharField(+ allow_blank=True,+ help_text="Full transcript of the test call, if Vapi delivered one. May be empty.",+ )+ summary = serializers.CharField(+ allow_blank=True,+ help_text="AI-generated summary of the test call, if Vapi delivered one. May be empty.",+ )+++class TestInterviewLinkSerializer(serializers.Serializer):+ interview_url = serializers.URLField(+ help_text=(+ "Public, unauthenticated URL the topic author opens to dogfood the voice "+ "interview themselves — does not count against the targeted interviewees."+ ),+ )+ latest_test_interview = LatestTestInterviewSerializer(+ allow_null=True,+ help_text="Most recent test interview completed by the topic author, or null if none yet.",+ )++class InterviewLinkSerializer(serializers.Serializer):interviewee_identifier = serializers.CharField(max_length=400,@@ -575,6 +603,54 @@ class InterviewLinkSerializer(serializers.Serializer):)+def _dogfood_identifier(caller: User) -> str:+ """Identifier for the calling user's personal dogfood interviewee context.++ Prefers the user's email so the existing identifier-parsing surfaces a friendly+ display name in the assistant greeting; falls back to their distinct_id so a+ user without a real email still gets a working test link.+ """+ return caller.email or str(caller.distinct_id)+++def _ensure_dogfood_context(+ *, topic: UserInterviewTopic, team: Team, caller: User+) -> tuple[IntervieweeContext, SharingConfiguration]:+ """Idempotently get-or-create the calling user's `IntervieweeContext` ++ enabled `SharingConfiguration` for a topic. The IC is keyed on the caller's+ own identifier so each team member gets their own dogfood link — we never+ mint a public share token in someone else's name.++ Wrapped in `transaction.atomic` + `select_for_update` on the IC row so two+ concurrent calls don't race into duplicate enabled SharingConfigurations+ for the same (caller, topic).+ """+ identifier = _dogfood_identifier(caller)+ with transaction.atomic():+ ic, _ = IntervieweeContext.objects.select_for_update().get_or_create(+ team=team,+ topic=topic,+ interviewee_identifier=identifier,+ defaults={+ "agent_context": "",+ "created_by": caller,+ },+ )+ sharing_config = (+ SharingConfiguration.objects.filter(team=team, interviewee_context=ic, enabled=True)+ .filter(models.Q(expires_at__isnull=True) | models.Q(expires_at__gt=timezone.now()))+ .order_by("-created_at")+ .first()+ )+ if sharing_config is None:+ sharing_config = SharingConfiguration.objects.create(+ team=team,+ interviewee_context=ic,+ enabled=True,+ )+ return ic, sharing_config++def _materialize_links_for_topic(*, topic: UserInterviewTopic, team: Any, created_by: Any) -> list[dict[str, Any]]:"""Get-or-create an `IntervieweeContext` and enabled `SharingConfiguration` for everytargeted identifier on the topic. Returns one row per identifier with the resolved@@ -740,6 +816,7 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"send_invites","add_interviewee","remove_interviewee",+ "test_link",]queryset = UserInterviewTopic.objects.select_related("created_by").all()serializer_class = UserInterviewTopicSerializer@@ -914,6 +991,52 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return response.Response(InterviewInviteResultSerializer(results, many=True).data)+ @extend_schema(+ request=None,+ responses={200: OpenApiResponse(response=TestInterviewLinkSerializer)},+ description=(+ "Return the calling user's personal dogfood interview link for this topic, "+ "plus the latest test interview they have recorded against it. Lazily "+ "get-or-creates a per-caller IntervieweeContext + enabled SharingConfiguration "+ "the first time it's called, then returns the same stable URL on subsequent "+ "calls. The caller's identifier is intentionally not added to the topic's "+ "targeting arrays — each user dogfoods under their own row, so test calls "+ "never mint a public share token on someone else's behalf."+ ),+ )+ @action(detail=True, methods=["get"], url_path="test_link")+ def test_link(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:+ topic = self.get_object()+ ic, sharing_config = _ensure_dogfood_context(+ topic=topic,+ team=self.team,+ caller=cast(User, request.user),+ )++ latest = (+ UserInterview.objects.filter(+ team_id=self.team_id,+ topic_id=topic.id,+ interviewee_identifier=ic.interviewee_identifier,+ )+ .order_by("-created_at")+ .only("created_at", "transcript", "summary")+ .first()+ )+ latest_payload: dict[str, Any] | None = None+ if latest is not None:+ latest_payload = {+ "completed_at": latest.created_at,+ "transcript": latest.transcript or "",+ "summary": latest.summary or "",+ }++ payload = {+ "interview_url": absolute_uri(f"/interview/{sharing_config.access_token}"),+ "latest_test_interview": latest_payload,+ }+ return response.Response(TestInterviewLinkSerializer(payload).data)+@extend_schema(request=IntervieweeIdentifierRequestSerializer,responses={200: OpenApiResponse(response=UserInterviewTopicSerializer)},diff --git a/products/user_interviews/backend/test_dogfood_interview_link.py b/products/user_interviews/backend/test_dogfood_interview_link.pynew file mode 100644index 000000000000..fdbc3faf254b--- /dev/null+++ b/products/user_interviews/backend/test_dogfood_interview_link.py@@ -0,0 +1,126 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized+from rest_framework import status++from posthog.models.sharing_configuration import SharingConfiguration++from products.user_interviews.backend.models import IntervieweeContext, UserInterview, UserInterviewTopic+++class _FeatureFlagEnabledMixin(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ patcher = patch("posthoganalytics.feature_enabled", return_value=True)+ patcher.start()+ self.addCleanup(patcher.stop)+++class TestDogfoodInterviewLink(_FeatureFlagEnabledMixin):+ def _topics_url(self) -> str:+ return f"/api/environments/{self.team.id}/user_interview_topics/"++ def _test_link_url(self, topic_id: str) -> str:+ return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/test_link/"++ def _create_topic(self) -> UserInterviewTopic:+ response = self.client.post(+ self._topics_url(),+ {+ "topic": "Session replay adoption",+ "interviewee_emails": ["[email protected]"],+ "interviewee_distinct_ids": [],+ "questions": ["What blocks adoption?"],+ },+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.content+ return UserInterviewTopic.objects.get(team=self.team, id=response.json()["id"])++ def test_topic_creation_does_not_eagerly_seed_dogfood_context(self) -> None:+ topic = self._create_topic()+ assert not IntervieweeContext.objects.filter(team=self.team, topic=topic).exists()++ def test_test_link_materializes_caller_context_and_share(self) -> None:+ topic = self._create_topic()++ response = self.client.get(self._test_link_url(str(topic.id)))++ assert response.status_code == status.HTTP_200_OK, response.content+ ic = IntervieweeContext.objects.get(team=self.team, topic=topic, interviewee_identifier=self.user.email)+ assert ic.created_by_id == self.user.id+ assert SharingConfiguration.objects.filter(team=self.team, interviewee_context=ic, enabled=True).exists()++ def test_test_link_is_idempotent(self) -> None:+ topic = self._create_topic()+ first = self.client.get(self._test_link_url(str(topic.id))).json()+ second = self.client.get(self._test_link_url(str(topic.id))).json()+ assert first["interview_url"] == second["interview_url"]+ assert (+ IntervieweeContext.objects.filter(+ team=self.team, topic=topic, interviewee_identifier=self.user.email+ ).count()+ == 1+ )+ assert (+ SharingConfiguration.objects.filter(+ team=self.team,+ interviewee_context__topic=topic,+ interviewee_context__interviewee_identifier=self.user.email,+ ).count()+ == 1+ )++ def test_each_caller_gets_their_own_dogfood_context(self) -> None:+ topic = self._create_topic()+ first_response = self.client.get(self._test_link_url(str(topic.id))).json()++ other_user = self._create_user("[email protected]")+ self.client.force_login(other_user)+ second_response = self.client.get(self._test_link_url(str(topic.id))).json()++ assert first_response["interview_url"] != second_response["interview_url"]+ identifiers = set(+ IntervieweeContext.objects.filter(team=self.team, topic=topic).values_list(+ "interviewee_identifier", flat=True+ )+ )+ assert identifiers == {self.user.email, other_user.email}++ @parameterized.expand(+ [+ ("no_interview", None, None, None),+ ("transcript_only", "hello", "", "hello"),+ ("summary_only", "", "said hello", ""),+ ("both", "hello", "said hello", "hello"),+ ]+ )+ def test_test_link_surfaces_latest_test_interview(+ self,+ _name: str,+ transcript: str | None,+ summary: str | None,+ expected_transcript: str | None,+ ) -> None:+ topic = self._create_topic()+ # First call materializes the dogfood context so we have an identifier to attach an interview to.+ self.client.get(self._test_link_url(str(topic.id)))+ if transcript is not None:+ UserInterview.objects.create(+ team=self.team,+ created_by=self.user,+ topic=topic,+ interviewee_identifier=self.user.email,+ transcript=transcript,+ summary=summary or "",+ )++ latest = self.client.get(self._test_link_url(str(topic.id))).json()["latest_test_interview"]++ if transcript is None:+ assert latest is None+ else:+ assert latest is not None+ assert latest["transcript"] == expected_transcript+ assert latest["summary"] == (summary or "")diff --git a/products/user_interviews/frontend/UserInterview.tsx b/products/user_interviews/frontend/UserInterview.tsxindex 57ead3c6962f..5f743b68d677 100644--- a/products/user_interviews/frontend/UserInterview.tsx+++ b/products/user_interviews/frontend/UserInterview.tsx@@ -1,17 +1,27 @@import { useActions, useValues } from 'kea'-import { IconArrowLeft, IconCheck, IconChevronRight, IconClock, IconDownload } from '@posthog/icons'+import {+ IconArrowLeft,+ IconCheck,+ IconChevronRight,+ IconClock,+ IconCopy,+ IconDownload,+ IconFlask,+} from '@posthog/icons'import { LemonButton, LemonSkeleton, LemonTag, LemonWidget } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'+import { dayjs } from 'lib/dayjs'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { Link } from 'lib/lemon-ui/Link'+import { copyToClipboard } from 'lib/utils/copyToClipboard'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'-import type { UserInterviewTopicApi } from './generated/api.schemas'+import type { TestInterviewLinkApi, UserInterviewTopicApi } from './generated/api.schemas'import { InterviewLinkCopyButton } from './InterviewLinkCopyButton'import { UserInterviewLogicProps, userInterviewLogic } from './userInterviewLogic'@@ -45,8 +55,10 @@ export function UserInterview({ id }: UserInterviewLogicProps): JSX.Element {totalTargeted,responseRate,linksCsvExporting,+ testLink,+ testLinkLoading,} = useValues(userInterviewLogic)- const { exportLinksCsv } = useActions(userInterviewLogic)+ const { exportLinksCsv, loadTestLink } = useActions(userInterviewLogic)if (topicLoading && !topic) {return (@@ -130,6 +142,12 @@ export function UserInterview({ id }: UserInterviewLogicProps): JSX.Element {<StatCard label="Questions" value={questionCount} color="muted" /></div>+ <TestInterviewWidget+ testLink={testLink}+ testLinkLoading={testLinkLoading}+ onRefresh={loadTestLink}+ />+{/* Targeted people list */}<LemonWidget title={`People (${allIdentifiers.length})`}><div className="divide-y">@@ -235,6 +253,106 @@ function DetailRow({ label, value }: { label: string; value: string }): JSX.Elem)}+function TestInterviewWidget({+ testLink,+ testLinkLoading,+ onRefresh,+}: {+ testLink: TestInterviewLinkApi | null+ testLinkLoading: boolean+ onRefresh: () => void+}): JSX.Element {+ const interviewUrl = testLink?.interview_url+ const latest = testLink?.latest_test_interview ?? null++ const handleCopy = (): void => {+ if (interviewUrl) {+ void copyToClipboard(interviewUrl, 'test interview link')+ }+ }++ return (+ <LemonWidget+ title={+ <span className="flex items-center gap-2">+ <IconFlask />+ <span>Test interview</span>+ <LemonTag type="warning">No real user needed</LemonTag>+ </span>+ }+ >+ <div className="p-3 space-y-3">+ <p className="text-muted text-sm mb-0">+ Open this link to try the AI voice interview yourself — your test calls are kept separate from the+ targeted interviewees and the most recent one appears below.+ </p>+ {testLinkLoading && !testLink ? (+ <LemonSkeleton.Text className="h-4 w-[80%]" />+ ) : interviewUrl ? (+ <div className="flex items-center gap-2">+ <Link to={interviewUrl} target="_blank" className="text-sm font-mono break-all">+ {interviewUrl}+ </Link>+ <LemonButton+ type="tertiary"+ size="xsmall"+ icon={<IconCopy />}+ onClick={handleCopy}+ tooltip="Copy test interview link"+ />+ <LemonButton+ type="tertiary"+ size="xsmall"+ onClick={onRefresh}+ loading={testLinkLoading}+ tooltip="Refresh test interview state"+ >+ Refresh+ </LemonButton>+ </div>+ ) : (+ <p className="text-danger text-sm mb-0">Couldn't load the test link. Try refreshing the page.</p>+ )}+ <div>+ <div className="text-xs font-semibold uppercase text-muted tracking-wide mb-1">+ Latest test transcript+ </div>+ {latest ? (+ <div className="text-sm space-y-2">+ <div className="text-muted">+ Recorded {dayjs(latest.completed_at).format('MMM D, YYYY [at] HH:mm')}+ </div>+ {latest.summary ? (+ <div>+ <div className="text-xs font-semibold uppercase text-muted tracking-wide mb-1">+ Summary+ </div>+ <LemonMarkdown>{latest.summary}</LemonMarkdown>+ </div>+ ) : null}+ {latest.transcript ? (+ <details>+ <summary className="cursor-pointer text-xs uppercase text-muted tracking-wide">+ Full transcript+ </summary>+ <pre className="text-xs whitespace-pre-wrap mt-2">{latest.transcript}</pre>+ </details>+ ) : null}+ {!latest.summary && !latest.transcript ? (+ <div className="text-muted">+ The most recent test call completed but no transcript or summary was delivered.+ </div>+ ) : null}+ </div>+ ) : (+ <div className="text-sm text-muted">No test call has completed yet for this topic.</div>+ )}+ </div>+ </div>+ </LemonWidget>+ )+}+function PersonRow({identifier,topicId,diff --git a/products/user_interviews/frontend/generated/api.schemas.ts b/products/user_interviews/frontend/generated/api.schemas.tsindex 17be86e51292..ee2ee312b6fc 100644--- a/products/user_interviews/frontend/generated/api.schemas.ts+++ b/products/user_interviews/frontend/generated/api.schemas.ts@@ -171,6 +171,22 @@ export interface PaginatedInterviewInviteResultListApi {results: InterviewInviteResultApi[]}+export interface LatestTestInterviewApi {+ /** When the test interview was completed. */+ completed_at: string+ /** Full transcript of the test call, if Vapi delivered one. May be empty. */+ transcript: string+ /** AI-generated summary of the test call, if Vapi delivered one. May be empty. */+ summary: string+}++export interface TestInterviewLinkApi {+ /** Public, unauthenticated URL the topic author opens to dogfood the voice interview themselves — does not count against the targeted interviewees. */+ interview_url: string+ /** Most recent test interview completed by the topic author, or null if none yet. */+ latest_test_interview: LatestTestInterviewApi | null+}+export interface IntervieweeContextApi {readonly id: stringreadonly created_by: UserBasicApidiff --git a/products/user_interviews/frontend/generated/api.ts b/products/user_interviews/frontend/generated/api.tsindex 2530e05b9ace..4f3d087d92fb 100644--- a/products/user_interviews/frontend/generated/api.ts+++ b/products/user_interviews/frontend/generated/api.ts@@ -22,6 +22,7 @@ import type {PatchedUserInterviewApi,PatchedUserInterviewTopicApi,SendInvitesRequestApi,+ TestInterviewLinkApi,UserInterviewApi,UserInterviewSearchRequestApi,UserInterviewSearchResultApi,@@ -278,6 +279,24 @@ export const userInterviewTopicsSendInvitesCreate = async ()}+export const getUserInterviewTopicsTestLinkRetrieveUrl = (projectId: string, id: string) => {+ return `/api/environments/${projectId}/user_interview_topics/${id}/test_link/`+}++/**+ * Return the calling user's personal dogfood interview link for this topic, plus the latest test interview they have recorded against it. Lazily get-or-creates a per-caller IntervieweeContext + enabled SharingConfiguration the first time it's called, then returns the same stable URL on subsequent calls. The caller's identifier is intentionally not added to the topic's targeting arrays — each user dogfoods under their own row, so test calls never mint a public share token on someone else's behalf.+ */+export const userInterviewTopicsTestLinkRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<TestInterviewLinkApi> => {+ return apiMutator<TestInterviewLinkApi>(getUserInterviewTopicsTestLinkRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getUserInterviewTopicsIntervieweesListUrl = (projectId: string,topicId: string,diff --git a/products/user_interviews/frontend/userInterviewLogic.ts b/products/user_interviews/frontend/userInterviewLogic.tsindex 6e6de03fe2e0..93f3ebc4ed16 100644--- a/products/user_interviews/frontend/userInterviewLogic.ts+++ b/products/user_interviews/frontend/userInterviewLogic.ts@@ -14,11 +14,13 @@ import {userInterviewTopicsGenerateLinksCreate,userInterviewTopicsIntervieweesList,userInterviewTopicsRetrieve,+ userInterviewTopicsTestLinkRetrieve,userInterviewsList,} from './generated/api'import type {IntervieweeContextApi,InterviewLinkApi,+ TestInterviewLinkApi,UserInterviewApi,UserInterviewTopicApi,} from './generated/api.schemas'@@ -85,6 +87,13 @@ export const userInterviewLogic = kea<userInterviewLogicType>([return unwrapPaginatedOrArray(response)},},+ testLink: {+ __default: null as TestInterviewLinkApi | null,+ loadTestLink: async (): Promise<TestInterviewLinkApi> => {+ const projectId = String(teamLogic.values.currentTeamId)+ return await userInterviewTopicsTestLinkRetrieve(projectId, props.id)+ },+ },})),actions({exportLinksCsv: true,@@ -203,5 +212,6 @@ export const userInterviewLogic = kea<userInterviewLogicType>([actions.loadInterviewees()actions.loadInterviews()actions.loadLinks()+ actions.loadTestLink()}),])diff --git a/products/user_interviews/mcp/tools.yaml b/products/user_interviews/mcp/tools.yamlindex 3c76873b41a9..cfe40936bfca 100644--- a/products/user_interviews/mcp/tools.yaml+++ b/products/user_interviews/mcp/tools.yaml@@ -274,6 +274,9 @@ tools:- reply_to- send_asyncfeature_flag: user-interviews+ user-interview-topics-test-link-retrieve:+ operation: user_interview_topics_test_link_retrieve+ enabled: falseuser-interview-topics-update:operation: user_interview_topics_updateenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4b685eff8e0a..55c214b071d5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -20209,6 +20209,15 @@ export namespace Schemas {Never: 'never',} as const;+ export interface LatestTestInterview {+ /** When the test interview was completed. */+ completed_at: string;+ /** Full transcript of the test call, if Vapi delivered one. May be empty. */+ transcript: string;+ /** AI-generated summary of the test call, if Vapi delivered one. May be empty. */+ summary: string;+ }+export interface LegalDocumentCreator {first_name: string;email: string;@@ -36838,6 +36847,13 @@ export namespace Schemas {message?: string;}+ export interface TestInterviewLink {+ /** Public, unauthenticated URL the topic author opens to dogfood the voice interview themselves — does not count against the targeted interviewees. */+ interview_url: string;+ /** Most recent test interview completed by the topic author, or null if none yet. */+ latest_test_interview: LatestTestInterview | null;+ }+export interface TextReprMetadata {event_type?: string;event_id?: string;