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): add non-personalised (shared) interview link (#72079)

Paul D'Ambra4346df55000f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index df5f873ada00..20e08f609b86 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2252,6 +2252,22 @@ snapshots:
hash: v1.k794b7964.cdded54a95432b459e3b56e14aef0cf30a8ebae6d3807a970e44753baf7d769f.LPIS0ZqXkHsdnpwTmLbmoCwIeJ3dpPBiO2LlcqaRVQs
exporter-interview--default--wide--light:
hash: v1.k794b7964.0014e85423a79e2e299bf376a734885ad7fab79e8e593b063520a93851da643d.vCAGA3wXiQhCp-7Q3TIDa1IesJiFEexU4AhoUUrH0tw
+ exporter-interview--shared-link--medium--dark:
+ hash: v1.k794b7964.85280b249f9f0656bb67a3d932ff0226aa289aa644004e4aab0cb4e9f37baa2f.oKGgQcmhdXNqFrOvwI4WF4VE6W-i7Fm1SqAPujLd7G4
+ exporter-interview--shared-link--medium--light:
+ hash: v1.k794b7964.ce8d76f42582858810387596274beb927004e96793b28c1e9db266aaea0b3be5.mBDLtqhyofz_JCBzV9zWSh1Sgo3KxENghTEBT21pCWU
+ exporter-interview--shared-link--narrow--dark:
+ hash: v1.k794b7964.eea37ea4e57ab4fe7862dd65823af6d078ce7574896872d968bc44b0675e2d7f.dicxBVQHHt8g1VQN2hi2j_jJ-1RxL9mL9XtzGV9HJ0U
+ exporter-interview--shared-link--narrow--light:
+ hash: v1.k794b7964.ddf8b0cbe69729133ef9e7f10be53219d52811837e47a2dfe486b72b4692717c.O3XJ7lf8RdDrvi7xK8wmWTF73ecAEB6rA9GH0fnJA5Y
+ exporter-interview--shared-link--superwide--dark:
+ hash: v1.k794b7964.66562d7eb7b2e2db226539a65fc7b24b4264de11c1d5d9bece7fcaa44dc255d8.z8BlaOQo9VAvQbbf7FN5A0LQxwruXMUNwXjo-dp38TE
+ exporter-interview--shared-link--superwide--light:
+ hash: v1.k794b7964.10323a11a1cbad29422007f3be064272de304119f3d287e91872b4ae38b6db5c.-4mP5CkXozGxsFrodhMVfyle7XsOwVIkvOMi9URL1Zk
+ exporter-interview--shared-link--wide--dark:
+ hash: v1.k794b7964.c47193f52f4bee5394b5366fe7f77e3ce8686c4d54691538f8b977a9137cc916.2DnCcDgPakh32tzyI1rUrw1HuPsVdemKnwQbCtr71Vs
+ exporter-interview--shared-link--wide--light:
+ hash: v1.k794b7964.939486068c7a4e78a11e5935353c3ec3053409ffd0748a8791ca53b09354e9b1.n75MvjKUHChadX4HGhCUI67Z20X8Luv8IwFAez8je9U
exporter-other--event-table-insight--dark:
hash: v1.k794b7964.b49f709fd4150d9aa62e5e72280c1a01d36b8ce9a73151d49cdc903394406476.HroHAic6d-U6xImox3yNijT04GTbLpTRTwvaxN46Frg
exporter-other--event-table-insight--light:
diff --git a/frontend/src/exporter/scenes/ExporterInterviewScene.tsx b/frontend/src/exporter/scenes/ExporterInterviewScene.tsx
index 9a6e74fcbe29..91f429c74164 100644
--- a/frontend/src/exporter/scenes/ExporterInterviewScene.tsx
+++ b/frontend/src/exporter/scenes/ExporterInterviewScene.tsx
@@ -1,17 +1,58 @@
import Vapi from '@vapi-ai/web'
-import { memo, useCallback, useEffect, useRef, useState } from 'react'
+import { memo, type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import * as roboHogPng from '@posthog/brand/hoggies/png/robo-hog'
-import { LemonButton } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput } from '@posthog/lemon-ui'
import { Logo } from 'lib/brand'
import { pngHoggie } from 'lib/brand/hoggies'
import { useHogfetti } from 'lib/components/Hogfetti/Hogfetti'
+import { uuid } from 'lib/utils/dom'
+import { fromParams } from 'lib/utils/url'
import { InterviewExportPayload } from '../types'
const HedgehogRoboHog = pngHoggie(roboHogPng)
+// Fields a shared-link respondent sends to /start_call/. Empty {} for personalised links.
+interface StartCallBody {
+ name?: string
+ respondent_key?: string
+ distinct_id?: string
+ session_id?: string
+ _hp?: string
+}
+
+// Stable per-browser id for a shared-link respondent, scoped per share token so two topics in the
+// same browser stay distinct. Persisting it means a refresh mid-call re-attaches to the same
+// respondent instead of creating a duplicate. Best-effort: falls back to an in-memory id if
+// localStorage is unavailable (private mode, blocked storage).
+function getOrCreateRespondentKey(accessToken: string): string {
+ const storageKey = `ph-interview-respondent:${accessToken}`
+ try {
+ const existing = window.localStorage.getItem(storageKey)
+ if (existing) {
+ return existing
+ }
+ const created = uuid()
+ window.localStorage.setItem(storageKey, created)
+ return created
+ } catch {
+ return uuid()
+ }
+}
+
+// Best-effort person/session linkage: whoever built the shared link can append ?distinct_id=…&session_id=…
+// so responses can be tied back to the person/session that triggered the interview. Untrusted.
+function readLinkageFromUrl(): { distinct_id: string; session_id: string } {
+ try {
+ const params = fromParams()
+ return { distinct_id: params.distinct_id ?? '', session_id: params.session_id ?? '' }
+ } catch {
+ return { distinct_id: '', session_id: '' }
+ }
+}
+
// Vapi surfaces several normal-completion signals through its `error` channel because
// the underlying Daily.co transport reports the local participant being evicted as
// an error. Treat these as expected end-of-call events rather than failures.
@@ -43,12 +84,10 @@ interface VapiTranscriptMessage {
}
interface StartCallPayload {
- public_key: string
- assistant_id: string
- assistant_overrides: {
- firstMessage?: string
- variableValues?: Record<string, string>
- metadata?: Record<string, string>
+ web_call: {
+ webCallUrl: string
+ id?: string
+ artifactPlan?: { videoRecordingEnabled?: boolean }
}
}
@@ -69,10 +108,20 @@ const CallStatusPanel = memo(function CallStatusPanel({
)
})
-function PreCallIntro({ interview }: { interview: InterviewExportPayload }): JSX.Element {
+function PreCallIntro({
+ interview,
+ name,
+ onNameChange,
+ honeypotRef,
+}: {
+ interview: InterviewExportPayload
+ name: string
+ onNameChange: (value: string) => void
+ honeypotRef: RefObject<HTMLInputElement>
+}): JSX.Element {
return (
<>
- <h1 className="text-3xl font-bold mb-4">Hi {interview.user_name}!</h1>
+ <h1 className="text-3xl font-bold mb-4">{interview.shared ? 'Hi there!' : `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>
@@ -80,6 +129,32 @@ function PreCallIntro({ interview }: { interview: InterviewExportPayload }): JSX
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>
+ {interview.shared && (
+ <div className="mb-6">
+ <label htmlFor="interview-respondent-name" className="block font-semibold mb-1">
+ What's your name?
+ </label>
+ <LemonInput
+ id="interview-respondent-name"
+ value={name}
+ onChange={onNameChange}
+ placeholder="Your name"
+ maxLength={200}
+ autoFocus
+ />
+ {/* Honeypot: hidden from real users, tempting to naive bots. Sent as `_hp`; a
+ filled value gets the request rejected server-side. */}
+ <input
+ ref={honeypotRef}
+ type="text"
+ name="company_website"
+ tabIndex={-1}
+ autoComplete="off"
+ aria-hidden="true"
+ className="hidden"
+ />
+ </div>
+ )}
<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">
@@ -150,11 +225,13 @@ function ErrorPanel({ errorMessage }: { errorMessage: string | null }): JSX.Elem
function CallActionButton({
state,
+ canStart,
onStart,
onStop,
onRetry,
}: {
state: CallState
+ canStart: boolean
onStart: () => void
onStop: () => void
onRetry: () => void
@@ -162,7 +239,13 @@ function CallActionButton({
switch (state) {
case 'idle':
return (
- <LemonButton type="primary" size="large" fullWidth onClick={onStart}>
+ <LemonButton
+ type="primary"
+ size="large"
+ fullWidth
+ onClick={onStart}
+ disabledReason={canStart ? undefined : 'Enter your name to start'}
+ >
Start interview
</LemonButton>
)
@@ -191,6 +274,10 @@ const CallBodyPanel = memo(function CallBodyPanel({
state,
interview,
errorMessage,
+ name,
+ onNameChange,
+ honeypotRef,
+ canStart,
onStart,
onStop,
onRetry,
@@ -198,6 +285,10 @@ const CallBodyPanel = memo(function CallBodyPanel({
state: CallState
interview: InterviewExportPayload
errorMessage: string | null
+ name: string
+ onNameChange: (value: string) => void
+ honeypotRef: RefObject<HTMLInputElement>
+ canStart: boolean
onStart: () => void
onStop: () => void
onRetry: () => void
@@ -206,30 +297,43 @@ const CallBodyPanel = memo(function CallBodyPanel({
return (
<div className="flex-1 min-w-0">
{state === 'already-replied' && <AlreadyRepliedPanel interview={interview} />}
- {isPreCall && <PreCallIntro interview={interview} />}
+ {isPreCall && (
+ <PreCallIntro interview={interview} name={name} onNameChange={onNameChange} honeypotRef={honeypotRef} />
+ )}
{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} />
+ <CallActionButton
+ state={state}
+ canStart={canStart}
+ 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
- * personalized agent context out of the initial HTML payload, so a recipient can't
- * see "this person is a heavy user, be empathetic" just by viewing source.
+ * Ask the server to create one Vapi web call when the interviewee clicks Start. The
+ * response contains only that call's join payload, never reusable Vapi credentials.
*/
-async function fetchStartCallPayload(accessToken: string): Promise<StartCallPayload> {
+async function fetchStartCallPayload(accessToken: string, body: StartCallBody): Promise<StartCallPayload> {
const response = await fetch(`/api/user_interviews/share/${accessToken}/start_call/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
})
if (!response.ok) {
+ // A shared link is opened by many people at once (e.g. posted in a company Slack), so
+ // concurrent respondents can trip the rate limit. Surface a retry-friendly message rather
+ // than a raw error — the error panel already offers a "Try again" button.
+ if (response.status === 429) {
+ throw new Error('A lot of people are starting interviews right now. Please wait a moment and try again.')
+ }
const text = await response.text()
throw new Error(text || `Server responded ${response.status}`)
}
@@ -250,6 +354,11 @@ export default function ExporterInterviewScene({
// read as listening (mic is open), and only the post-user-final gap re-enters thinking.
const [conversationPhase, setConversationPhase] = useState<ConversationPhase>('thinking')
const [errorMessage, setErrorMessage] = useState<string | null>(null)
+ // Shared links ask each respondent for their name before starting; personalised links already
+ // know it. `canStart` gates the button so shared respondents can't start nameless.
+ const [respondentName, setRespondentName] = useState<string>('')
+ const honeypotRef = useRef<HTMLInputElement>(null)
+ const canStart = !interview.shared || respondentName.trim().length > 0
const vapiRef = useRef<Vapi | null>(null)
const agentTalkingRef = useRef<boolean>(false)
const lastPhaseRef = useRef<ConversationPhase>('thinking')
@@ -258,10 +367,31 @@ export default function ExporterInterviewScene({
const hogfettiFiredRef = useRef<boolean>(false)
const { trigger: triggerHogfetti, HogfettiComponent } = useHogfetti({ count: 75, duration: 3000 })
+ // Reused across a refresh so an interrupted call re-attaches to the same respondent instead of
+ // spawning a duplicate. Only meaningful for shared links.
+ const respondentKey = useMemo(
+ () => (interview.shared && accessToken ? getOrCreateRespondentKey(accessToken) : ''),
+ [interview.shared, accessToken]
+ )
+
useEffect(() => {
document.title = `Interview · ${interview.topic}`
}, [interview.topic])
+ // Warn before an accidental refresh/close ends a live call — Vapi's browser call can't be
+ // resumed across a page load, so a lost call means starting over.
+ useEffect(() => {
+ if (state !== 'in-call') {
+ return
+ }
+ const onBeforeUnload = (event: BeforeUnloadEvent): void => {
+ event.preventDefault()
+ event.returnValue = ''
+ }
+ window.addEventListener('beforeunload', onBeforeUnload)
+ return () => window.removeEventListener('beforeunload', onBeforeUnload)
+ }, [state])
+
useEffect(() => {
if (state !== 'ended' || hogfettiFiredRef.current) {
return
@@ -306,13 +436,22 @@ export default function ExporterInterviewScene({
hogfettiFiredRef.current = false
setConversationPhase('thinking')
setState('loading')
+ const body: StartCallBody = {}
+ if (interview.shared) {
+ const { distinct_id, session_id } = readLinkageFromUrl()
+ body.name = respondentName.trim()
+ body.respondent_key = respondentKey
+ body.distinct_id = distinct_id
+ body.session_id = session_id
+ body._hp = honeypotRef.current?.value ?? ''
+ }
void (async () => {
try {
- const startPayload = await fetchStartCallPayload(accessToken)
+ const startPayload = await fetchStartCallPayload(accessToken, body)
if (!isMountedRef.current) {
return
}
- const vapi = new Vapi(startPayload.public_key)
+ const vapi = new Vapi('')
vapiRef.current = vapi
const setPhase = (next: ConversationPhase): void => {
if (lastPhaseRef.current === next) {
@@ -376,7 +515,7 @@ export default function ExporterInterviewScene({
}
})
setState('connecting')
- await vapi.start(startPayload.assistant_id, startPayload.assistant_overrides)
+ await vapi.reconnect(startPayload.web_call)
if (!isMountedRef.current) {
vapi.stop()
return
@@ -394,7 +533,7 @@ export default function ExporterInterviewScene({
setState('error')
}
})()
- }, [accessToken])
+ }, [accessToken, interview.shared, respondentName, respondentKey])
const stop = useCallback((): void => {
vapiRef.current?.stop()
@@ -419,6 +558,10 @@ export default function ExporterInterviewScene({
state={state}
interview={interview}
errorMessage={errorMessage}
+ name={respondentName}
+ onNameChange={setRespondentName}
+ honeypotRef={honeypotRef}
+ canStart={canStart}
onStart={start}
onStop={stop}
onRetry={retry}
diff --git a/frontend/src/exporter/stories/ExporterInterview.stories.tsx b/frontend/src/exporter/stories/ExporterInterview.stories.tsx
index e39ef2bcf3fc..c6696f768e81 100644
--- a/frontend/src/exporter/stories/ExporterInterview.stories.tsx
+++ b/frontend/src/exporter/stories/ExporterInterview.stories.tsx
@@ -11,6 +11,15 @@ const interview: InterviewExportPayload = {
user_name: 'Sam',
topic: 'how you use dashboards',
already_replied: false,
+ shared: false,
+}
+
+// Non-personalised (shared) link: no known interviewee, so the viewer asks for a name first.
+const sharedInterview: InterviewExportPayload = {
+ ...interview,
+ interviewee_identifier: '',
+ user_name: '',
+ shared: true,
}
type Story = StoryObj<ExportedData>
@@ -52,3 +61,9 @@ const meta: Meta<ExportedData> = {
export default meta
export const Default: Story = {}
+
+export const SharedLink: Story = {
+ args: {
+ interview: sharedInterview,
+ },
+}
diff --git a/frontend/src/exporter/types.ts b/frontend/src/exporter/types.ts
index 688090153f92..13f071a46c4c 100644
--- a/frontend/src/exporter/types.ts
+++ b/frontend/src/exporter/types.ts
@@ -26,6 +26,12 @@ export interface InterviewExportPayload {
user_name: string
topic: string
already_replied: boolean
+ /**
+ * True for a non-personalised (shared) topic link, where every visitor is a new anonymous
+ * respondent who self-identifies with a name before starting. False for a personalised
+ * per-invitee link (which greets a known `user_name`).
+ */
+ shared: boolean
/**
* NOTE: `agent_context`, `questions`, and the Vapi credentials are intentionally NOT in
* this payload. They live behind `POST /api/user_interviews/share/<token>/start_call/`
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index 21a16479b25f..367684deb59d 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -1191,18 +1191,30 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
except Exception:
raise NotFound("No heatmap found")
elif isinstance(resource, SharingConfiguration) and resource.interviewee_context:
- from products.user_interviews.backend.facade.api import has_replied, parse_interviewee_identifier
+ from products.user_interviews.backend.facade.api import (
+ has_replied,
+ is_shared_interviewee_context,
+ parse_interviewee_identifier,
+ )
ic = resource.interviewee_context
topic = ic.topic
asset_title = topic.topic or "User interview"
asset_description = "PostHog AI user interview"
- user_name = parse_interviewee_identifier(ic.interviewee_identifier).display_name
- already_replied = has_replied(
- team_id=topic.team_id,
- topic_id=topic.id,
- interviewee_identifier=ic.interviewee_identifier,
- )
+ # A shared link's IntervieweeContext carries a sentinel identifier: every visitor is a new
+ # anonymous respondent, so there's no fixed name and no "already replied" gate — the
+ # viewer prompts for a name before starting.
+ shared = is_shared_interviewee_context(ic.interviewee_identifier)
+ if shared:
+ user_name = ""
+ already_replied = False
+ else:
+ user_name = parse_interviewee_identifier(ic.interviewee_identifier).display_name
+ already_replied = has_replied(
+ team_id=topic.team_id,
+ topic_id=topic.id,
+ interviewee_identifier=ic.interviewee_identifier,
+ )
# Keep agent_context, questions, and Vapi credentials OUT of the public HTML —
# the recipient would otherwise see their own internal-notes context in view-source.
# The exporter scene fetches those server-side via /start_call/ when the user clicks Start.
@@ -1211,10 +1223,11 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
"type": "interview",
"interview": {
"topic_id": str(topic.id),
- "interviewee_identifier": ic.interviewee_identifier,
+ "interviewee_identifier": "" if shared else ic.interviewee_identifier,
"user_name": user_name,
"topic": topic.topic,
"already_replied": already_replied,
+ "shared": shared,
},
}
)
diff --git a/posthog/egress/test/test_vapi_transport.py b/posthog/egress/test/test_vapi_transport.py
new file mode 100644
index 000000000000..5c867a53fad2
--- /dev/null
+++ b/posthog/egress/test/test_vapi_transport.py
@@ -0,0 +1,32 @@
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+import requests
+
+from posthog.egress.vapi.transport import vapi_request
+
+
+class TestVapiTransport(SimpleTestCase):
+ def test_request_keeps_token_in_authorization_header_and_uses_fingerprint_scope(self) -> None:
+ response = requests.Response()
+ response.status_code = 201
+
+ with (
+ patch("posthog.egress.vapi.transport.consume_vapi_api_sync", return_value=True) as consume,
+ patch("requests.request", return_value=response) as request,
+ patch("posthog.egress.vapi.transport.record_vapi_api_response"),
+ ):
+ vapi_request(
+ "POST",
+ "https://api.vapi.ai/call/web",
+ api_token="pk_test",
+ source="user_interviews",
+ endpoint="/call/web",
+ json={"assistantId": "assistant"},
+ )
+
+ assert request.call_args.kwargs["headers"]["Authorization"] == "Bearer pk_test"
+ scope = consume.call_args.args[0]
+ assert scope != "pk_test"
+ assert len(scope) == 16
diff --git a/posthog/egress/vapi/__init__.py b/posthog/egress/vapi/__init__.py
new file mode 100644
index 000000000000..fdc32504893c
--- /dev/null
+++ b/posthog/egress/vapi/__init__.py
@@ -0,0 +1,3 @@
+from posthog.egress.vapi.transport import vapi_request
+
+__all__ = ["vapi_request"]
diff --git a/posthog/egress/vapi/limiter.py b/posthog/egress/vapi/limiter.py
new file mode 100644
index 000000000000..6a5191c41712
--- /dev/null
+++ b/posthog/egress/vapi/limiter.py
@@ -0,0 +1,29 @@
+"""Outbound Vapi API budget keyed by the configured API token fingerprint."""
+
+from django.conf import settings
+
+from posthog.egress.limiter.outbound import get_outbound_rate_limiter
+from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy
+
+VAPI_DOMAIN = "vapi"
+
+
+def _vapi_policy(_key: str) -> RatePolicy:
+ return RatePolicy(
+ limits=(
+ (int(getattr(settings, "VAPI_EGRESS_PER_MINUTE_BUDGET", 10_000)), 60.0),
+ (int(getattr(settings, "VAPI_EGRESS_HOURLY_BUDGET", 100_000)), 3600.0),
+ ),
+ in_memory_divider=4,
+ )
+
+
+register_policy(VAPI_DOMAIN, _vapi_policy)
+
+
+def consume_vapi_api_sync(scope: str, *, priority: Priority, source: str) -> bool:
+ return get_outbound_rate_limiter().consume_sync(
+ f"{VAPI_DOMAIN}:api_key:{scope}",
+ priority=priority,
+ source=source,
+ )
diff --git a/posthog/egress/vapi/observability.py b/posthog/egress/vapi/observability.py
new file mode 100644
index 000000000000..9a5d89924ebf
--- /dev/null
+++ b/posthog/egress/vapi/observability.py
@@ -0,0 +1,58 @@
+"""Vapi outbound API request telemetry."""
+
+import requests
+from prometheus_client import Counter, Gauge
+
+from posthog.egress.observability.observability import (
+ EgressMetrics,
+ EgressObservability,
+ RateLimitSnapshot,
+ register_egress_observability,
+)
+from posthog.egress.vapi.limiter import VAPI_DOMAIN
+
+_metrics = EgressMetrics(
+ request_counter=Counter(
+ "vapi_api_requests",
+ "Outbound Vapi API requests.",
+ labelnames=["scope", "method", "endpoint", "status_code", "source"],
+ ),
+ remaining_gauge=Gauge(
+ "vapi_api_rate_limit_remaining",
+ "Last observed Vapi API rate-limit remaining value.",
+ labelnames=["scope", "resource"],
+ ),
+ limit_gauge=Gauge(
+ "vapi_api_rate_limit_limit",
+ "Last observed Vapi API rate-limit ceiling.",
+ labelnames=["scope", "resource"],
+ ),
+ reset_gauge=Gauge(
+ "vapi_api_rate_limit_reset_at",
+ "Last observed Vapi API rate-limit reset timestamp.",
+ labelnames=["scope", "resource"],
+ ),
+)
+
+
+def _parse_vapi_rate_limit(_response: requests.Response) -> RateLimitSnapshot:
+ return RateLimitSnapshot(resource="api")
+
+
+vapi_egress = EgressObservability(VAPI_DOMAIN, _metrics, _parse_vapi_rate_limit)
+register_egress_observability(vapi_egress)
+
+
+def record_vapi_api_response(
+ response: requests.Response,
+ *,
+ source: str,
+ scope: str,
+ method: str,
+ endpoint: str,
+) -> None:
+ vapi_egress.record_response(response, source=source, scope=scope, method=method, endpoint=endpoint)
+
+
+def record_vapi_api_exception(*, source: str, scope: str, method: str, endpoint: str, url: str) -> None:
+ vapi_egress.record_exception(source=source, scope=scope, method=method, endpoint=endpoint, url=url)
diff --git a/posthog/egress/vapi/transport.py b/posthog/egress/vapi/transport.py
new file mode 100644
index 000000000000..ae11a75ab23f
--- /dev/null
+++ b/posthog/egress/vapi/transport.py
@@ -0,0 +1,75 @@
+"""Gated, recorded transport for calls to the Vapi API."""
+
+import hashlib
+from typing import Any
+
+import requests
+
+from posthog.egress.limiter.policies import Priority
+from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient
+from posthog.egress.vapi.limiter import consume_vapi_api_sync
+from posthog.egress.vapi.observability import record_vapi_api_exception, record_vapi_api_response
+
+
+class VapiEgressBudgetExhausted(EgressBudgetExhausted):
+ pass
+
+
+class VapiClient(EgressClient):
+ def _standard_headers(self) -> dict[str, str]:
+ return {"Accept": "application/json", "Content-Type": "application/json"}
+
+ def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
+ return consume_vapi_api_sync(scope, priority=priority, source=source)
+
+ def _record_response(
+ self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None
+ ) -> None:
+ record_vapi_api_response(
+ response,
+ source=source,
+ scope=scope or "",
+ method=method,
+ endpoint=endpoint or "unknown",
+ )
+
+ def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:
+ record_vapi_api_exception(
+ source=source,
+ scope=scope or "",
+ method=method,
+ endpoint=endpoint or "unknown",
+ url=url,
+ )
+
+ def _budget_exhausted_error(self, scope: str) -> VapiEgressBudgetExhausted:
+ return VapiEgressBudgetExhausted("Vapi egress budget exhausted")
+
+
+_vapi_client = VapiClient()
+
+
+def vapi_request(
+ method: str,
+ url: str,
+ *,
+ api_token: str,
+ source: str,
+ endpoint: str,
+ timeout: float | tuple[float, float] | None = None,
+ session: requests.Session | None = None,
+ **kwargs: Any,
+) -> requests.Response:
+ scope = hashlib.sha256(api_token.encode()).hexdigest()[:16]
+ return _vapi_client.request(
+ method,
+ url,
+ source=source,
+ headers={"Authorization": f"Bearer {api_token}"},
+ scope=scope,
+ priority=Priority.CRITICAL,
+ endpoint=endpoint,
+ timeout=timeout,
+ session=session,
+ **kwargs,
+ )
diff --git a/products/user_interviews/backend/facade/api.py b/products/user_interviews/backend/facade/api.py
index b366c20f39df..fb2835623035 100644
--- a/products/user_interviews/backend/facade/api.py
+++ b/products/user_interviews/backend/facade/api.py
@@ -22,12 +22,30 @@ from products.user_interviews.backend.classification import derive_auto_classifi
from products.user_interviews.backend.facade.contracts import IntervieweeIdentity
__all__ = [
+ "SHARED_INTERVIEWEE_IDENTIFIER",
"IntervieweeIdentity",
"derive_auto_classifications",
"has_replied",
+ "is_shared_interviewee_context",
"parse_interviewee_identifier",
+ "valid_distinct_id",
+ "valid_session_id",
]
+SHARED_INTERVIEWEE_IDENTIFIER = logic.SHARED_INTERVIEWEE_IDENTIFIER
+
+
+def is_shared_interviewee_context(interviewee_identifier: str) -> bool:
+ return logic.is_shared_interviewee_context(interviewee_identifier)
+
+
+def valid_distinct_id(value: object) -> str:
+ return logic.valid_distinct_id(value)
+
+
+def valid_session_id(value: object) -> str:
+ return logic.valid_session_id(value)
+
def parse_interviewee_identifier(identifier: str) -> IntervieweeIdentity:
return logic.parse_interviewee_identifier(identifier)
diff --git a/products/user_interviews/backend/logic.py b/products/user_interviews/backend/logic.py
index 440dacd5ea18..6d9f3134224e 100644
--- a/products/user_interviews/backend/logic.py
+++ b/products/user_interviews/backend/logic.py
@@ -7,10 +7,83 @@ products must keep going through the facade.
"""
import re
+import uuid
from uuid import UUID
from products.user_interviews.backend.facade.contracts import IntervieweeIdentity
-from products.user_interviews.backend.models import EmailWithDisplayNameValidator, UserInterview
+from products.user_interviews.backend.models import (
+ EmailWithDisplayNameValidator,
+ UserInterview,
+ UserInterviewClassification,
+)
+
+# distinct_id rules ported from rust/capture (`CAPTURE_V1_DISTINCT_ID_MAX_SIZE` and
+# `ILLEGAL_DISTINCT_IDS` in v1/analytics/constants.rs). On the shared interview link these are
+# best-effort person/session linkage hints from an untrusted public page, so an invalid value is
+# dropped (ignored), never a reason to reject the interview.
+DISTINCT_ID_MAX_CHARS = 200
+ILLEGAL_DISTINCT_IDS = frozenset(
+ {
+ "0",
+ "00000000-0000-0000-0000-000000000000",
+ "[object object]",
+ "anonymous",
+ "anonymous-user",
+ "backend",
+ "distinct_id",
+ "distinctid",
+ "email",
+ "false",
+ "guest",
+ "id",
+ "nan",
+ "none",
+ "not_authenticated",
+ "null",
+ "system",
+ "true",
+ "undefined",
+ "user",
+ }
+)
+
+
+def valid_distinct_id(value: object) -> str:
+ """Return a usable distinct_id, or "" if it fails the canonical capture rules (empty, longer
+ than the 200-char limit, or a known-bad sentinel). Dropped, not rejected — it's a linkage hint.
+ A too-long id is dropped rather than truncated: a truncated distinct_id would never match a real
+ person, so keeping it would be misleading."""
+ if not value:
+ return ""
+ candidate = str(value).strip()
+ if not candidate or len(candidate) > DISTINCT_ID_MAX_CHARS or candidate.lower() in ILLEGAL_DISTINCT_IDS:
+ return ""
+ return candidate
+
+
+def valid_session_id(value: object) -> str:
+ """Return the session_id only if it's a valid UUIDv7 (PostHog session IDs are UUIDv7), else "".
+ Dropped, not rejected — it's a best-effort linkage hint."""
+ if not value:
+ return ""
+ candidate = str(value).strip()
+ try:
+ return candidate if uuid.UUID(candidate).version == 7 else ""
+ except ValueError:
+ return ""
+
+
+# A shared (non-personalised) interview link is modelled as an IntervieweeContext carrying this
+# reserved identifier — the same machinery as a per-invitee link (and the test/dogfood link), but
+# the token belongs to the whole topic and every visitor is a new anonymous respondent. Using a
+# sentinel row (rather than a new field, or a new FK on the main-app SharingConfiguration) keeps this
+# experiment's blast radius entirely inside the user_interviews product.
+SHARED_INTERVIEWEE_IDENTIFIER = "__posthog_shared_link__"
+
+
+def is_shared_interviewee_context(interviewee_identifier: str) -> bool:
+ """Whether an IntervieweeContext identifier marks the topic's shared (anonymous) link."""
+ return interviewee_identifier == SHARED_INTERVIEWEE_IDENTIFIER
def parse_interviewee_identifier(identifier: str) -> IntervieweeIdentity:
@@ -38,9 +111,23 @@ def parse_interviewee_identifier(identifier: str) -> IntervieweeIdentity:
def has_replied(*, team_id: int, topic_id: UUID, interviewee_identifier: str) -> bool:
- """Whether an interviewee has already completed an interview for this topic."""
- return UserInterview.objects.filter(
- team_id=team_id,
- topic_id=topic_id,
- interviewee_identifier=interviewee_identifier,
- ).exists()
+ """Whether a personalised (invited) interviewee has already completed an interview for this topic.
+
+ Abandoned interviews don't count: an accidental refresh mid-call leaves an abandoned
+ partial behind, and treating that as "replied" would lock the interviewee out of ever
+ finishing. Only a non-abandoned response gates the personalised link.
+
+ Shared-link responses never count: they carry a `respondent_key` and a namespaced
+ `interviewee_identifier`, so this filter is defense-in-depth against a shared respondent
+ (whose distinct_id is untrusted) ever being able to mark a targeted invitee as replied.
+ """
+ return (
+ UserInterview.objects.filter(
+ team_id=team_id,
+ topic_id=topic_id,
+ interviewee_identifier=interviewee_identifier,
+ respondent_key="",
+ )
+ .exclude(classifications__contains=[UserInterviewClassification.ABANDONED])
+ .exists()
+ )
diff --git a/products/user_interviews/backend/migrations/0009_userinterview_shared_respondent_fields.py b/products/user_interviews/backend/migrations/0009_userinterview_shared_respondent_fields.py
new file mode 100644
index 000000000000..d30bf75159a6
--- /dev/null
+++ b/products/user_interviews/backend/migrations/0009_userinterview_shared_respondent_fields.py
@@ -0,0 +1,25 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("user_interviews", "0008_userinterview_user_interview_classif_gin"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="userinterview",
+ name="respondent_name",
+ field=models.CharField(blank=True, db_default="", default="", max_length=400),
+ ),
+ migrations.AddField(
+ model_name="userinterview",
+ name="respondent_key",
+ field=models.CharField(blank=True, db_default="", default="", max_length=64),
+ ),
+ migrations.AddField(
+ model_name="userinterview",
+ name="distinct_id",
+ field=models.CharField(blank=True, db_default="", default="", max_length=200),
+ ),
+ ]
diff --git a/products/user_interviews/backend/migrations/max_migration.txt b/products/user_interviews/backend/migrations/max_migration.txt
index c7efa0be5ae4..470197bc8934 100644
--- a/products/user_interviews/backend/migrations/max_migration.txt
+++ b/products/user_interviews/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0008_userinterview_user_interview_classif_gin
+0009_userinterview_shared_respondent_fields
diff --git a/products/user_interviews/backend/models.py b/products/user_interviews/backend/models.py
index c7dfacaca4d2..c161d2e203c7 100644
--- a/products/user_interviews/backend/models.py
+++ b/products/user_interviews/backend/models.py
@@ -48,7 +48,23 @@ class UserInterview(UUIDTModel, CreatedMetaFields):
blank=True,
related_name="interviews",
)
+ # Email or distinct_id identifying a personalised (invited) interviewee. For shared-link
+ # respondents this is a namespaced, non-authoritative "shared:<key>" marker that can never equal
+ # a targeted invitee's identifier — so an anonymous respondent can neither be attributed to nor
+ # lock out a targeted person. Best-effort person linkage from a shared respondent lives in
+ # `distinct_id`, never here.
interviewee_identifier = models.CharField(max_length=400, blank=True, default="")
+ # Set for responses collected via a non-personalised (shared) topic link, where every
+ # visit is a new self-identifying respondent. Empty for invited (personalised) interviews.
+ respondent_name = models.CharField(max_length=400, blank=True, default="", db_default="")
+ # Stable per-browser key (localStorage) for a shared-link respondent. Used to collapse the
+ # abandoned partial a refresh leaves behind into the respondent's eventual real response.
+ respondent_key = models.CharField(max_length=64, blank=True, default="", db_default="")
+ # Best-effort, UNTRUSTED person linkage for a shared-link respondent: the distinct_id read from
+ # the public interview URL's query string. Never authoritative — never used for access control
+ # and never folded into interviewee_identifier — so a respondent can't claim (or suppress) a
+ # targeted invitee. Empty for personalised interviews.
+ distinct_id = models.CharField(max_length=200, blank=True, default="", db_default="")
recording_url = models.URLField(blank=True, default="", max_length=2048)
call_metadata = models.JSONField(default=dict, blank=True)
diff --git a/products/user_interviews/backend/presentation/views.py b/products/user_interviews/backend/presentation/views.py
index 89916ca0d169..a049434594f4 100644
--- a/products/user_interviews/backend/presentation/views.py
+++ b/products/user_interviews/backend/presentation/views.py
@@ -46,7 +46,7 @@ from posthog.rate_limit import UserInterviewInviteThrottle
from posthog.security.spreadsheet_safety import sanitize_formula_injection
from posthog.utils import absolute_uri
-from ..facade.api import derive_auto_classifications, parse_interviewee_identifier
+from ..facade.api import SHARED_INTERVIEWEE_IDENTIFIER, derive_auto_classifications, parse_interviewee_identifier
from ..facade.enums import SEARCH_DOCUMENT_TYPES
from ..invite_email import (
build_invite_email_context,
@@ -543,6 +543,21 @@ class UserInterviewViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return response.Response(UserInterviewSearchResultSerializer(results, many=True).data)
+# The shared-link sentinel and the `shared:` respondent namespace are internal markers that back a
+# topic's non-personalised link. A user-supplied interviewee identifier equal to one — or in the
+# `shared:` namespace — would collide on the unique (topic, interviewee_identifier) constraint and
+# silently merge with, or revoke, the topic's shared link. Reject them at every input boundary;
+# internal creation of the sentinel goes through the ORM directly, bypassing these serializers.
+_RESERVED_SHARED_IDENTIFIER_PREFIX = "shared:"
+
+
+def _reject_reserved_identifier(value: str) -> None:
+ if value == SHARED_INTERVIEWEE_IDENTIFIER or value.startswith(_RESERVED_SHARED_IDENTIFIER_PREFIX):
+ raise serializers.ValidationError(
+ "This identifier is reserved for shared interview links and can't be assigned to an interviewee."
+ )
+
+
class UserInterviewTopicSerializer(serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
interviewee_emails = serializers.ListField(
@@ -611,19 +626,15 @@ class UserInterviewTopicSerializer(serializers.ModelSerializer):
def validate_invite_message(self, value: str | None) -> str | None:
return validate_invite_message(value)
- MISSING_TARGETING_ERROR = "At least one of interviewee_emails or interviewee_distinct_ids must be provided."
-
- def validate(self, attrs: dict) -> dict:
- if not self._current(attrs, "interviewee_emails", []) and not self._current(
- attrs, "interviewee_distinct_ids", []
- ):
- raise serializers.ValidationError(self.MISSING_TARGETING_ERROR)
- return attrs
+ def validate_interviewee_distinct_ids(self, value: list[str]) -> list[str]:
+ for identifier in value:
+ _reject_reserved_identifier(identifier)
+ return value
- def _current(self, attrs: dict, field: str, default: Any) -> Any:
- if field in attrs:
- return attrs[field]
- return getattr(self.instance, field, default)
+ # A topic needs no targeted interviewees to be valid: a non-personalised (shared) link is created
+ # for a zero-target topic — the whole point for reaching anonymous visitors we have no contact
+ # details for. The personalised flows (generate_links / send_invites) still guard the empty case
+ # with their own errors where they actually need targets.
def create(self, validated_data: dict) -> UserInterviewTopic:
request = self.context["request"]
@@ -703,6 +714,66 @@ class InterviewLinkSerializer(serializers.Serializer):
)
+class SharedInterviewLinkSerializer(serializers.Serializer):
+ interview_url = serializers.URLField(
+ help_text=(
+ "Public, unauthenticated URL any respondent can open to start a new interview for this "
+ "topic. Backed by a topic-level SharingConfiguration access token — not tied to any "
+ "specific interviewee. Each visit is a new anonymous respondent who self-identifies with "
+ "a name; `distinct_id` and `session_id` query params on the URL are captured as "
+ "best-effort person/session linkage."
+ ),
+ )
+
+
+def _get_or_create_active_share(*, team: Team, **resource: Any) -> SharingConfiguration:
+ """Get the active (enabled, unexpired) SharingConfiguration for a user-interviews resource,
+ creating one if none exists. `resource` is the single FK kwarg identifying what's shared —
+ always `interviewee_context=` today (a real invitee, the caller's test link, or the topic's
+ shared-link sentinel). Callers own the surrounding transaction/locking."""
+ sharing_config = (
+ SharingConfiguration.objects.filter(team=team, enabled=True, **resource)
+ .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, enabled=True, **resource)
+ return sharing_config
+
+
+def _ensure_shared_link_for_topic(*, topic: UserInterviewTopic, team: Team, created_by: User) -> SharingConfiguration:
+ """Get-or-create the topic's single shared (non-personalised) interview link.
+
+ Modelled exactly like the per-caller test link — an IntervieweeContext plus an enabled
+ SharingConfiguration — but keyed on a reserved sentinel identifier so the token belongs to the
+ whole topic: every visitor is a new anonymous respondent. No new model and no main-app schema
+ change; the unique (topic, interviewee_identifier) constraint guarantees one shared link per
+ topic and coalesces concurrent creates.
+ """
+ with transaction.atomic():
+ ic, _ = IntervieweeContext.objects.select_for_update().get_or_create(
+ team=team,
+ topic=topic,
+ interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER,
+ defaults={"agent_context": "", "created_by": created_by},
+ )
+ return _get_or_create_active_share(team=team, interviewee_context=ic)
+
+
+def _disable_shared_link_for_topic(*, topic: UserInterviewTopic, team: Team) -> None:
+ """Revoke the topic's shared (non-personalised) interview link so an already-distributed URL stops
+ working. Disables every enabled SharingConfiguration on the topic's shared-link sentinel context —
+ mirrors `_disable_shares_for_identifiers` for the personalised links. A later `shared_link` POST
+ mints a fresh token (rotation)."""
+ SharingConfiguration.objects.filter(
+ team=team,
+ interviewee_context__topic=topic,
+ interviewee_context__interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER,
+ enabled=True,
+ ).update(enabled=False)
+
+
def _dogfood_identifier(caller: User) -> str:
"""Identifier for the calling user's personal dogfood interviewee context.
@@ -736,18 +807,7 @@ def _ensure_dogfood_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,
- )
+ sharing_config = _get_or_create_active_share(team=team, interviewee_context=ic)
return ic, sharing_config
@@ -780,18 +840,7 @@ def _materialize_links_for_topic(*, topic: UserInterviewTopic, team: Any, create
defaults={"agent_context": "", "created_by": created_by},
)
- 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,
- )
+ sharing_config = _get_or_create_active_share(team=team, interviewee_context=ic)
user_name, email = _parse_identifier(identifier)
results.append(
@@ -858,6 +907,7 @@ class IntervieweeIdentifierRequestSerializer(serializers.Serializer):
)
def validate_identifier(self, value: str) -> str:
+ _reject_reserved_identifier(value)
if _identifier_is_email(value) and len(value) > EMAIL_IDENTIFIER_MAX_LENGTH:
raise serializers.ValidationError(
f"Email identifiers must be {EMAIL_IDENTIFIER_MAX_LENGTH} characters or fewer."
@@ -966,6 +1016,7 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"patch",
"destroy",
"generate_links",
+ "shared_link",
"links_csv",
"send_invites",
"add_interviewee",
@@ -1026,6 +1077,38 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
]
return response.Response(InterviewLinkSerializer(payload, many=True).data)
+ @extend_schema(
+ methods=["POST"],
+ request=None,
+ responses={200: OpenApiResponse(response=SharedInterviewLinkSerializer)},
+ description=(
+ "Get-or-create a single non-personalised (shared) interview link for this topic. Unlike "
+ "generate_links, the returned URL is not tied to a specific interviewee — every visitor "
+ "becomes a new anonymous respondent who self-identifies with a name. Idempotent: repeated "
+ "calls return the same active link. `distinct_id` and `session_id` query params appended "
+ "to the URL are captured as best-effort person/session linkage."
+ ),
+ )
+ @extend_schema(
+ methods=["DELETE"],
+ request=None,
+ responses={204: OpenApiResponse(description="Shared link revoked; the already-distributed URL stops working.")},
+ description=(
+ "Revoke this topic's shared (non-personalised) interview link so an already-distributed URL "
+ "can no longer start interviews. Idempotent — a no-op when no active shared link exists. A "
+ "subsequent shared_link POST mints a fresh link (rotation)."
+ ),
+ )
+ @action(detail=True, methods=["post", "delete"], url_path="shared_link")
+ def shared_link(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:
+ topic = self.get_object()
+ if request.method == "DELETE":
+ _disable_shared_link_for_topic(topic=topic, team=self.team)
+ return response.Response(status=status.HTTP_204_NO_CONTENT)
+ sharing_config = _ensure_shared_link_for_topic(topic=topic, team=self.team, created_by=cast(User, request.user))
+ payload = {"interview_url": absolute_uri(f"/interview/{sharing_config.access_token}")}
+ return response.Response(SharedInterviewLinkSerializer(payload).data)
+
@extend_schema(
request=None,
responses={
@@ -1357,6 +1440,10 @@ class IntervieweeContextSerializer(serializers.ModelSerializer):
)
read_only_fields = ("id", "created_by", "created_at")
+ def validate_interviewee_identifier(self, value: str) -> str:
+ _reject_reserved_identifier(value)
+ return value
+
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
topic_id = self.context["topic_id"]
team = self.context["get_team"]()
@@ -1404,6 +1491,10 @@ class BulkIntervieweeContextItemSerializer(serializers.Serializer):
help_text="Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'.",
)
+ def validate_interviewee_identifier(self, value: str) -> str:
+ _reject_reserved_identifier(value)
+ return value
+
class BulkIntervieweeContextRequestSerializer(serializers.Serializer):
items = BulkIntervieweeContextItemSerializer(
@@ -1458,10 +1549,11 @@ class IntervieweeContextViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
permission_classes = [PostHogFeatureFlagPermission]
def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ # Hide the shared-link sentinel row — it's an internal marker, not a real interviewee.
return queryset.filter(
topic_id=self.parents_query_dict["topic_id"],
team_id=self.parents_query_dict["team_id"],
- )
+ ).exclude(interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER)
def get_serializer_context(self) -> dict[str, Any]:
return {**super().get_serializer_context(), "topic_id": self.parents_query_dict["topic_id"]}
diff --git a/products/user_interviews/backend/presentation/webhooks.py b/products/user_interviews/backend/presentation/webhooks.py
index 696bf38420b1..be68142de703 100644
--- a/products/user_interviews/backend/presentation/webhooks.py
+++ b/products/user_interviews/backend/presentation/webhooks.py
@@ -3,8 +3,7 @@
Two surfaces live here, both keyed on a SharingConfiguration access token:
* ``start_call`` — called by the public interview page when the recipient clicks
- Start. Returns the Vapi credentials and the personalized assistant overrides
- (including merged ``agent_context``). Keeps that context off the initial HTML.
+ Start. Creates one Vapi web call server-side and returns only its join payload.
* ``vapi_webhook`` — called by Vapi at end-of-call. Persists a UserInterview row
attributed to the topic creator. Signature-verified; idempotent on ``call.id``.
"""
@@ -15,12 +14,14 @@ import json
import string
import hashlib
from typing import Any
+from uuid import uuid4
from django.conf import settings
from django.db import transaction
from django.db.models import Q
from django.utils.timezone import now
+import requests
import structlog
import posthoganalytics
from rest_framework import status
@@ -34,25 +35,28 @@ from posthog.schema import EmbeddingModelName
from posthog.api.embedding_worker import emit_embedding_request
from posthog.constants import AvailableFeature
+from posthog.egress.vapi import vapi_request
from posthog.event_usage import groups
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.team import Team
from posthog.rate_limit import IPThrottle
from posthog.storage.llm_prompt_cache import get_prompt_by_name_from_cache
-from ..facade.api import derive_auto_classifications
-from ..models import UserInterview, UserInterviewTopic
+from ..facade.api import derive_auto_classifications, is_shared_interviewee_context, valid_distinct_id, valid_session_id
+from ..models import UserInterview, UserInterviewClassification, UserInterviewTopic
logger = structlog.get_logger(__name__)
-class _MetricsEmittingIPThrottle(IPThrottle):
- """`IPThrottle` subclass that emits `rate_limit_exceeded_total` on rejection.
+class _RateLimitMetricsMixin(SimpleRateThrottle):
+ """Mixin that emits `rate_limit_exceeded_total` whenever the throttle it's mixed into rejects
+ a request. Mixed *ahead* of the concrete throttle base (`IPThrottle` or `SimpleRateThrottle`)
+ so `super().allow_request()` runs the real throttle logic, then this records the rejection.
- Kept here (not on the base `IPThrottle`) on purpose: tweaking the base would tighten
- the signature of `allow_request` and cascade into unrelated products that subclass
- `IPThrottle`. Keeping the metric emission product-local means user_interviews owns
- its own alerting surface without touching other products' code.
+ Kept product-local (not folded into the base `IPThrottle`) on purpose: tweaking the base would
+ cascade into unrelated products that subclass it. One mixin serves both the IP-keyed and the
+ token/respondent-keyed throttles here — `IPThrottle` is itself a `SimpleRateThrottle`, so the MRO
+ resolves `super()` to whichever concrete base each throttle names.
"""
def allow_request(self, request: Request, view: Any) -> bool:
@@ -65,17 +69,21 @@ class _MetricsEmittingIPThrottle(IPThrottle):
return bool(allowed)
-class InterviewStartCallIPThrottle(_MetricsEmittingIPThrottle):
- """Per-IP cap on `start_call`. The endpoint is `AllowAny`, so without this any caller
- can spin DB queries on share-token lookups indefinitely. 60/min comfortably handles
- legitimate interviewees clicking Start (one share token can't dial multiple times in
- the same minute), and any single IP burst above that is almost certainly probing."""
+class InterviewStartCallIPThrottle(_RateLimitMetricsMixin, IPThrottle):
+ """Per-IP cap on `start_call`. The endpoint is `AllowAny`, so without this any caller can spin DB
+ queries on share-token lookups indefinitely. This cap's real job is bounding cross-token probing
+ from one IP — per-token abuse is bounded by the token burst (120/min) + sustained (600/hour)
+ buckets. It sits above the token burst on purpose: a shared link's headline use case is many
+ people behind one corporate NAT / mobile CGNAT egress IP opening the same link, so a tight per-IP
+ cap would 429 legitimate concurrent respondents who share an egress. 200/min clears the token
+ burst (so the token bucket, not the IP, governs a single link's concurrency) while still stopping
+ a single IP from probing many tokens."""
scope = "user_interviews_start_call_ip"
- rate = "60/minute"
+ rate = "200/minute"
-class VapiWebhookIPThrottle(_MetricsEmittingIPThrottle):
+class VapiWebhookIPThrottle(_RateLimitMetricsMixin, IPThrottle):
"""Per-IP cap on `vapi_webhook`. Vapi calls us a small handful of times per interview
(status-update + end-of-call-report), but its egress is shared across all of our tenants,
so the bucket has to be generous enough that a noisy concurrent interview hour doesn't
@@ -88,14 +96,17 @@ class VapiWebhookIPThrottle(_MetricsEmittingIPThrottle):
rate = "1200/minute"
-class InterviewStartCallTokenThrottle(SimpleRateThrottle):
- """Per-share-token cap on `start_call`. The access_token uniquely identifies one
- interviewee invitation; a legitimate user clicks Start once. Anything above 10/min on
- the same token is automation. Keying on the token (not IP) means an attacker rotating
- IPs can't drive unbounded share-resolve DB lookups for a single guessed token."""
+class InterviewStartCallTokenThrottle(_RateLimitMetricsMixin):
+ """Sustained per-share-token ceiling on `start_call`. One token maps to either a single invited
+ person (personalised link) or many self-serve respondents (a shared topic link), so this is a
+ generous *sustained* bucket. On its own it would still let the whole hour's budget be spent in a
+ burst — the per-IP cap doesn't bind a caller spread across many IPs, and the respondent throttle
+ keys on a client-supplied respondent_key an attacker can rotate — so the companion
+ `InterviewStartCallTokenBurstThrottle` adds a short-window per-token cap. Keying on the token (not
+ IP) means an attacker rotating IPs still can't drain a guessed token faster than these two allow."""
scope = "user_interviews_start_call_token"
- rate = "10/minute"
+ rate = "600/hour"
def get_cache_key(self, request: Request, view: Any) -> str | None:
resolver_match = getattr(request, "resolver_match", None)
@@ -104,14 +115,36 @@ class InterviewStartCallTokenThrottle(SimpleRateThrottle):
return None
return self.cache_format % {"scope": self.scope, "ident": token}
- def allow_request(self, request: Request, view: Any) -> bool:
- from posthog.rate_limit import RATE_LIMIT_EXCEEDED_COUNTER, get_route_from_path
- allowed = super().allow_request(request, view)
- if not allowed:
- route = get_route_from_path(getattr(request, "path", None))
- RATE_LIMIT_EXCEEDED_COUNTER.labels(team_id="", scope=self.scope, path=route, route=route).inc()
- return bool(allowed)
+class InterviewStartCallTokenBurstThrottle(InterviewStartCallTokenThrottle):
+ """Short-window per-share-token burst cap. Bounds the *instantaneous* rate a single token can be
+ driven at — regardless of how many IPs or rotated respondent_keys a caller uses — so the sustained
+ hourly budget can't be dumped in seconds. Recovers within the minute, and 120/min sits well above
+ the realistic concurrent-Start volume for a shared link at this stage, so legitimate respondents
+ aren't throttled. Reuses the parent's token-keyed cache key under its own scope."""
+
+ scope = "user_interviews_start_call_token_burst"
+ rate = "120/minute"
+
+
+class InterviewStartCallRespondentThrottle(_RateLimitMetricsMixin):
+ """Per-respondent burst on `start_call`, mirroring the support widget's `WidgetUserBurstThrottle`.
+ Keys on the client-generated `respondent_key` (a random per-browser id a shared-link visitor
+ sends) so one respondent hammering Start is bounded without penalising the next visitor sharing
+ the same token. Falls back to IP when no key is present (personalised links, which don't send one)
+ — so a personalised interviewee's effective per-IP ceiling is this 30/min (the lower of this and
+ the 200/min IP throttle), which is still far above one person clicking Start."""
+
+ scope = "user_interviews_start_call_respondent"
+ rate = "30/minute"
+
+ def get_cache_key(self, request: Request, view: Any) -> str | None:
+ respondent_key = request.data.get("respondent_key") if isinstance(request.data, dict) else None
+ if respondent_key:
+ ident = hashlib.sha256(str(respondent_key).encode()).hexdigest()
+ else:
+ ident = self.get_ident(request)
+ return self.cache_format % {"scope": self.scope, "ident": ident}
# Vapi's HMAC-SHA256 hex digest is exactly 64 lowercase hex chars; reject other shapes
@@ -271,21 +304,150 @@ def _build_first_message(
return rendered[:_FIRST_MESSAGE_MAX_CHARS]
+# Max lengths for the self-reported fields a shared-link respondent sends to start_call. These
+# are echoed into Vapi metadata and persisted on the UserInterview, so cap them defensively.
+_RESPONDENT_NAME_MAX_CHARS = 200
+_RESPONDENT_KEY_MAX_CHARS = 64
+
+# Every shared-link response is stored under an identifier carrying this prefix. It can NEVER equal a
+# personalised interviewee's identifier (an email or distinct_id), so an anonymous respondent can
+# neither be attributed to nor lock out a targeted invitee.
+SHARED_RESPONDENT_IDENTIFIER_PREFIX = "shared:"
+
+
+def _clean_field(value: Any, max_chars: int) -> str:
+ return str(value).strip()[:max_chars] if value else ""
+
+
+def _shared_interviewee_identifier(respondent_key: str) -> str:
+ """Namespaced, non-authoritative identity for a shared-link respondent.
+
+ Keyed on the stable per-browser ``respondent_key`` so a refreshed respondent keeps one identity;
+ falls back to a random id when no key was supplied so rows stay distinct. Deliberately independent
+ of any self-reported name or untrusted ``distinct_id`` — those never determine attribution."""
+ return f"{SHARED_RESPONDENT_IDENTIFIER_PREFIX}{respondent_key or uuid4().hex}"
+
+
+VAPI_WEB_CALL_URL = "https://api.vapi.ai/call/web"
+
+
+class VapiWebCallError(Exception):
+ def __init__(self, message: str, status_code: int = status.HTTP_502_BAD_GATEWAY) -> None:
+ super().__init__(message)
+ self.status_code = status_code
+
+
+def _create_vapi_web_call(assistant_overrides: dict[str, Any]) -> dict[str, Any]:
+ try:
+ response = vapi_request(
+ "POST",
+ VAPI_WEB_CALL_URL,
+ api_token=settings.VAPI_PUBLIC_KEY,
+ source="user_interviews",
+ endpoint="/call/web",
+ timeout=(3.05, 15),
+ json={
+ "assistantId": settings.VAPI_ASSISTANT_ID,
+ "assistantOverrides": assistant_overrides,
+ "roomDeleteOnUserLeaveEnabled": True,
+ },
+ )
+ except requests.RequestException as error:
+ raise VapiWebCallError("Could not connect to Vapi.") from error
+
+ if response.status_code == status.HTTP_429_TOO_MANY_REQUESTS:
+ raise VapiWebCallError("Vapi is temporarily rate limited.", status.HTTP_429_TOO_MANY_REQUESTS)
+ if not 200 <= response.status_code < 300:
+ raise VapiWebCallError(f"Vapi rejected web call creation with status {response.status_code}.")
+
+ try:
+ payload = response.json()
+ except ValueError as error:
+ raise VapiWebCallError("Vapi returned an invalid web call response.") from error
+ if not isinstance(payload, dict):
+ raise VapiWebCallError("Vapi returned an invalid web call response.")
+
+ transport = payload.get("transport")
+ transport_url = transport.get("callUrl") if isinstance(transport, dict) else None
+ web_call_url = payload.get("webCallUrl") or transport_url
+ if not isinstance(web_call_url, str) or not web_call_url:
+ raise VapiWebCallError("Vapi returned a web call without a join URL.")
+
+ web_call: dict[str, Any] = {"webCallUrl": web_call_url}
+ call_id = payload.get("id")
+ if isinstance(call_id, str):
+ web_call["id"] = call_id
+ artifact_plan = payload.get("artifactPlan")
+ if isinstance(artifact_plan, dict):
+ web_call["artifactPlan"] = {"videoRecordingEnabled": bool(artifact_plan.get("videoRecordingEnabled", False))}
+ return web_call
+
+
+def _collapse_abandoned_partials(*, team: Team, topic: UserInterviewTopic, respondent_key: str, keep_pk: Any) -> None:
+ """Delete the abandoned partial an accidental mid-call refresh leaves behind, when the same
+ respondent (same ``respondent_key``) comes back and finishes — so the topic shows one response
+ per respondent instead of a junk trail.
+
+ Deletes only rows that STILL auto-derive as ``abandoned`` from their own transcript, rather than
+ trusting the stored label. ``abandoned`` is user-mutable (writable via the update API and the MCP
+ tool), so a real response a curator manually re-tagged ``abandoned`` would otherwise be
+ permanently, unrecoverably deleted here. Re-deriving keeps this a cleanup of genuine AI-only
+ partials and never touches a row that contains real interviewee content.
+ """
+ candidates = (
+ UserInterview.objects.filter(
+ team=team,
+ topic=topic,
+ respondent_key=respondent_key,
+ classifications__contains=[UserInterviewClassification.ABANDONED],
+ )
+ .exclude(pk=keep_pk)
+ .only("id", "transcript")
+ )
+ stale_pks = [
+ c.pk for c in candidates if UserInterviewClassification.ABANDONED in derive_auto_classifications(c.transcript)
+ ]
+ if not stale_pks:
+ return
+ deleted_count, _ = UserInterview.objects.filter(
+ team=team,
+ topic=topic,
+ respondent_key=respondent_key,
+ pk__in=stale_pks,
+ ).delete()
+ logger.info(
+ "user_interviews_collapsed_abandoned_partials",
+ team_id=team.id,
+ topic_id=str(topic.id),
+ deleted_count=deleted_count,
+ )
+
+
@api_view(["POST"])
@authentication_classes([])
@permission_classes([AllowAny])
-@throttle_classes([InterviewStartCallIPThrottle, InterviewStartCallTokenThrottle])
+@throttle_classes(
+ [
+ InterviewStartCallIPThrottle,
+ InterviewStartCallRespondentThrottle,
+ InterviewStartCallTokenBurstThrottle,
+ InterviewStartCallTokenThrottle,
+ ]
+)
def start_call(request: Request, access_token: str) -> Response:
- """Return the Vapi credentials + assistant overrides for a public interview share.
-
- The personalized ``agent_context`` (which may include internal CRM notes about the
- interviewee) is intentionally NOT embedded in the public interview page's HTML — it
- is fetched from here only when the recipient clicks Start. This keeps casual
- view-source / window.POSTHOG_EXPORTED_DATA inspection from leaking the agent prompt.
-
- Note: anyone with the share token can still get this payload — by design, since
- they also use it to actually start the call. The win is removing the leak from the
- initial HTML and giving us a single, auditable, rate-limitable surface.
+ """Create a Vapi web call and return its join payload for a public interview share.
+
+ Handles both share types the token can resolve to:
+ * a personalised (per-invitee) share — greets the named invitee, merges their per-person
+ ``agent_context``;
+ * a non-personalised (shared) topic share — every visitor is a new anonymous respondent who
+ self-identifies with a name; ``distinct_id``/``session_id`` query params are carried through
+ as best-effort person/session linkage, and a client ``respondent_key`` lets a refreshed call
+ re-attach to the same respondent.
+
+ The ``agent_context`` (which may include internal CRM notes about a personalised invitee) and
+ reusable Vapi credentials stay server-side. The browser receives only a single call's join
+ payload after the existing start-call throttles have accepted the request.
"""
from .views import _merge_agent_context, _parse_identifier
@@ -296,6 +458,17 @@ def start_call(request: Request, access_token: str) -> Response:
status=status.HTTP_503_SERVICE_UNAVAILABLE,
)
+ body = request.data if isinstance(request.data, dict) else {}
+ # Honeypot: a hidden field real users never fill, but naive bots do. Present on the shared-link
+ # name form; reject silently-ish with a 400 so a bot can't spin up calls. Log it so a bot wave —
+ # or a false positive dropping a real respondent — is visible rather than a silent black hole.
+ if body.get("_hp"):
+ logger.warning(
+ "user_interviews_start_call_honeypot_tripped",
+ access_token_suffix=access_token[-6:] if access_token else None,
+ )
+ return Response({"error": "invalid request"}, status=status.HTTP_400_BAD_REQUEST)
+
sharing_config = _resolve_share(access_token)
if sharing_config is None or sharing_config.interviewee_context is None:
logger.warning("user_interviews_start_call_unknown_access_token")
@@ -311,8 +484,39 @@ def start_call(request: Request, access_token: str) -> Response:
ic = sharing_config.interviewee_context
topic = ic.topic
- user_name, _ = _parse_identifier(ic.interviewee_identifier)
- agent_context = _merge_agent_context(topic.agent_context or "", ic.agent_context or "")
+ if is_shared_interviewee_context(ic.interviewee_identifier):
+ respondent_name = _clean_field(body.get("name"), _RESPONDENT_NAME_MAX_CHARS)
+ if not respondent_name:
+ return Response({"error": "name is required"}, status=status.HTTP_400_BAD_REQUEST)
+ respondent_key = _clean_field(body.get("respondent_key"), _RESPONDENT_KEY_MAX_CHARS)
+ user_name = respondent_name or "there"
+ agent_context = topic.agent_context or ""
+ # The response is stored under a namespaced identifier that can never collide with a targeted
+ # invitee's. The distinct_id from the URL is best-effort, UNTRUSTED linkage carried in its own
+ # metadata field — never folded into the identifier, so it can't forge attribution or lock a
+ # targeted person out.
+ metadata: dict[str, str] = {
+ "topic_id": str(topic.id),
+ "interviewee_identifier": _shared_interviewee_identifier(respondent_key),
+ "sharing_access_token": access_token,
+ "shared": "true",
+ "respondent_name": respondent_name,
+ "respondent_key": respondent_key,
+ "distinct_id": valid_distinct_id(body.get("distinct_id")),
+ # session_id isn't persisted in the DB — it rides on the lifecycle PostHog event (as
+ # $session_id, which associates the interview with the session recording). Validated
+ # here at the trust boundary; invalid values are dropped, not rejected.
+ "session_id": valid_session_id(body.get("session_id")),
+ }
+ else:
+ user_name, _ = _parse_identifier(ic.interviewee_identifier)
+ agent_context = _merge_agent_context(topic.agent_context or "", ic.agent_context or "")
+ metadata = {
+ "topic_id": str(topic.id),
+ "interviewee_identifier": ic.interviewee_identifier,
+ "sharing_access_token": access_token,
+ }
+
first_message_template = _resolve_first_message_template(sharing_config.team)
first_message = _build_first_message(
first_message_template,
@@ -321,39 +525,38 @@ def start_call(request: Request, access_token: str) -> Response:
team_id=sharing_config.team_id,
)
+ assistant_overrides: dict[str, Any] = {
+ "firstMessage": first_message,
+ # Scope server messages to just the lifecycle hooks we act on. Default Vapi
+ # config sends ~10 message types that we'd otherwise ignore.
+ "serverMessages": ["status-update", "end-of-call-report"],
+ "variableValues": {
+ "userName": user_name,
+ "topic": topic.topic or "",
+ "agent_context": agent_context,
+ "questions": json.dumps(topic.questions or []),
+ },
+ "metadata": metadata,
+ }
+ try:
+ web_call = _create_vapi_web_call(assistant_overrides)
+ except VapiWebCallError as error:
+ logger.exception(
+ "user_interviews_vapi_web_call_creation_failed",
+ team_id=sharing_config.team_id,
+ topic_id=str(topic.id),
+ status_code=error.status_code,
+ )
+ return Response({"error": str(error)}, status=error.status_code)
+
logger.info(
"user_interviews_start_call_issued",
team_id=sharing_config.team_id,
topic_id=str(topic.id),
+ shared=is_shared_interviewee_context(ic.interviewee_identifier),
+ call_id=web_call.get("id"),
)
-
- return Response(
- {
- "public_key": settings.VAPI_PUBLIC_KEY,
- "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 "",
- "agent_context": agent_context,
- # `json.dumps` so the Vapi assistant prompt receives standard JSON
- # (`["q1", "q2"]`) rather than Python's repr (`['q1', 'q2']`).
- "questions": json.dumps(topic.questions or []),
- },
- "metadata": {
- "topic_id": str(topic.id),
- "interviewee_identifier": ic.interviewee_identifier,
- "sharing_access_token": access_token,
- },
- },
- }
- )
+ return Response({"web_call": web_call})
@api_view(["POST"])
@@ -423,6 +626,9 @@ def vapi_webhook(request: Request) -> Response:
or overrides_metadata.get("sharing_access_token")
or overrides_metadata.get("access_token")
)
+ # Shared-link respondent fields (set in start_call's metadata, echoed back by Vapi). Merge with
+ # top-level precedence, mirroring the access_token resolution above.
+ merged_metadata: dict[str, Any] = {**overrides_metadata, **top_metadata}
call_id = call.get("id")
if message_type == "status-update":
@@ -437,6 +643,7 @@ def vapi_webhook(request: Request) -> Response:
"user_interview_conversation_started",
sharing_config=sharing_config,
call_id=call_id,
+ session_id=valid_session_id(merged_metadata.get("session_id")),
)
logger.info(
"user_interviews_vapi_webhook_status_update",
@@ -496,31 +703,64 @@ def vapi_webhook(request: Request) -> Response:
)
return Response({"status": "duplicate", "interview_id": str(existing.id)}, status=status.HTTP_200_OK)
- topic = interviewee_context.topic
recording_url = (message.get("recording") or {}).get("url", "") or message.get("recordingUrl", "") or ""
transcript = message.get("transcript", "") or ""
+ classifications = derive_auto_classifications(transcript)
+ topic = interviewee_context.topic
+
+ if is_shared_interviewee_context(interviewee_context.interviewee_identifier):
+ respondent_name = _clean_field(merged_metadata.get("respondent_name"), _RESPONDENT_NAME_MAX_CHARS)
+ respondent_key = _clean_field(merged_metadata.get("respondent_key"), _RESPONDENT_KEY_MAX_CHARS)
+ # Recompute the identifier from respondent_key rather than trusting the echoed metadata, so it
+ # is always a namespaced shared marker and can never be steered onto a targeted invitee.
+ interviewee_identifier = _shared_interviewee_identifier(respondent_key)
+ interviewee_emails = []
+ # Best-effort, untrusted person linkage. Re-validated here (defense in depth) and stored in its
+ # own column — never as the interviewee_identifier, so it can't forge attribution.
+ distinct_id = valid_distinct_id(merged_metadata.get("distinct_id"))
+ # session_id isn't persisted — it rides on the lifecycle event below. Re-validated here
+ # (defense in depth) so only a well-formed UUIDv7 reaches the event.
+ session_id = valid_session_id(merged_metadata.get("session_id"))
+ else:
+ interviewee_identifier = interviewee_context.interviewee_identifier
+ interviewee_emails = [interviewee_identifier] if "@" in interviewee_identifier else []
+ respondent_name = respondent_key = ""
+ distinct_id = ""
+ session_id = ""
with transaction.atomic():
interview = UserInterview.objects.create(
team=sharing_config.team,
topic=topic,
- interviewee_identifier=interviewee_context.interviewee_identifier,
- interviewee_emails=[interviewee_context.interviewee_identifier]
- if "@" in interviewee_context.interviewee_identifier
- else [],
+ interviewee_identifier=interviewee_identifier,
+ interviewee_emails=interviewee_emails,
+ respondent_name=respondent_name,
+ respondent_key=respondent_key,
+ distinct_id=distinct_id,
transcript=transcript,
summary=message.get("summary", "") or "",
recording_url=recording_url,
call_metadata=call,
created_by=topic.created_by,
- classifications=derive_auto_classifications(transcript),
+ classifications=classifications,
)
+ # Collapse the abandoned partial an accidental refresh leaves behind: when a shared-link
+ # respondent comes back (same respondent_key) and finishes, drop their earlier abandoned
+ # rows so the topic shows one response per respondent instead of a junk trail.
+ if respondent_key and UserInterviewClassification.ABANDONED not in classifications:
+ _collapse_abandoned_partials(
+ team=sharing_config.team,
+ topic=topic,
+ respondent_key=respondent_key,
+ keep_pk=interview.pk,
+ )
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,
+ session_id=session_id,
extra_properties={
"interview_id": str(interview.id),
"had_transcript": bool(interview.transcript),
@@ -542,6 +782,7 @@ def _capture_user_interview_event(
*,
sharing_config: SharingConfiguration,
call_id: str | None,
+ session_id: str = "",
extra_properties: dict[str, Any] | None = None,
) -> None:
"""Fire a PostHog event for a user-interview lifecycle moment (conversation started/ended).
@@ -552,10 +793,14 @@ def _capture_user_interview_event(
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."""
+ When a shared-link respondent supplied a valid session_id, it's attached as `$session_id` so
+ the event (and thus the interview) associates with that session recording — this is how the
+ session is linked without a dedicated DB column.
+
+ The `distinct_id` is intentionally an opaque per-share 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
@@ -564,6 +809,8 @@ def _capture_user_interview_event(
"team_id": sharing_config.team_id,
"call_id": call_id,
}
+ if session_id:
+ properties["$session_id"] = session_id
if call_id:
properties["$insert_id"] = f"{event}:{call_id}"
if extra_properties:
diff --git a/products/user_interviews/backend/test_facade.py b/products/user_interviews/backend/test_facade.py
index ec5128f7c3f3..6b72b9adf8e8 100644
--- a/products/user_interviews/backend/test_facade.py
+++ b/products/user_interviews/backend/test_facade.py
@@ -1,10 +1,13 @@
from posthog.test.base import APIBaseTest
+from django.test import SimpleTestCase
+
from parameterized import parameterized
from products.user_interviews.backend.facade.api import has_replied, parse_interviewee_identifier
from products.user_interviews.backend.facade.contracts import IntervieweeIdentity
-from products.user_interviews.backend.models import UserInterview, UserInterviewTopic
+from products.user_interviews.backend.logic import valid_distinct_id, valid_session_id
+from products.user_interviews.backend.models import UserInterview, UserInterviewClassification, UserInterviewTopic
class TestParseIntervieweeIdentifier(APIBaseTest):
@@ -23,6 +26,42 @@ class TestParseIntervieweeIdentifier(APIBaseTest):
)
+class TestLinkageValidation(SimpleTestCase):
+ # A UUIDv7 (version nibble 7); a UUIDv4 for the wrong-version case.
+ _V7 = "018f0b7a-0000-7000-8000-000000000000"
+ _V4 = "018f0b7a-0000-4000-8000-000000000000"
+
+ @parameterized.expand(
+ [
+ ("uuid_v7", _V7, _V7),
+ ("uuid_v7_trimmed", f" {_V7} ", _V7),
+ ("uuid_v4_wrong_version", _V4, ""),
+ ("not_a_uuid", "session-123", ""),
+ ("empty", "", ""),
+ ("none", None, ""),
+ ]
+ )
+ def test_valid_session_id(self, _name: str, value: object, expected: str) -> None:
+ assert valid_session_id(value) == expected
+
+ @parameterized.expand(
+ [
+ ("normal", "user_42", "user_42"),
+ ("trimmed", " user_42 ", "user_42"),
+ ("illegal_sentinel", "anonymous", ""),
+ ("illegal_case_insensitive", "ANONYMOUS", ""),
+ ("illegal_after_trim", " guest ", ""),
+ ("all_zero_uuid", "00000000-0000-0000-0000-000000000000", ""),
+ ("empty", "", ""),
+ ("none", None, ""),
+ ("too_long", "x" * 201, ""),
+ ("max_length_ok", "x" * 200, "x" * 200),
+ ]
+ )
+ def test_valid_distinct_id(self, _name: str, value: object, expected: str) -> None:
+ assert valid_distinct_id(value) == expected
+
+
class TestHasReplied(APIBaseTest):
def _create_topic(self) -> UserInterviewTopic:
return UserInterviewTopic.objects.create(
@@ -49,6 +88,21 @@ class TestHasReplied(APIBaseTest):
)
assert has_replied(team_id=self.team.id, topic_id=topic.id, interviewee_identifier="[email protected]")
+ def test_abandoned_reply_does_not_count(self) -> None:
+ # An accidental refresh mid-call leaves an abandoned partial behind. Treating that as
+ # "replied" would lock the interviewee out of ever finishing — so it must not count.
+ topic = self._create_topic()
+ UserInterview.objects.create(
+ team=self.team,
+ created_by=self.user,
+ interviewee_emails=["[email protected]"],
+ interviewee_identifier="[email protected]",
+ transcript="",
+ topic=topic,
+ classifications=[UserInterviewClassification.ABANDONED],
+ )
+ assert not has_replied(team_id=self.team.id, topic_id=topic.id, interviewee_identifier="[email protected]")
+
def test_scoped_by_team(self) -> None:
topic = self._create_topic()
other_team = self.organization.teams.create(name="other team")
diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.py
index ca3151e3be0a..d813a8360321 100644
--- a/products/user_interviews/backend/test_interview_sharing.py
+++ b/products/user_interviews/backend/test_interview_sharing.py
@@ -12,7 +12,7 @@ from posthog.test.base import APIBaseTest
from unittest.mock import Mock, patch
from django.template.loader import get_template
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
from django.utils import timezone
from parameterized import parameterized
@@ -24,16 +24,49 @@ from posthog.api.test.test_sharing import mock_exporter_template
from posthog.models.sharing_configuration import SharingConfiguration
from products.user_interviews.backend.models import IntervieweeContext, UserInterview, UserInterviewTopic
-from products.user_interviews.backend.presentation.views import UserInterviewTopicSerializer
from products.user_interviews.backend.presentation.webhooks import (
DEFAULT_FIRST_MESSAGE_TEMPLATE,
EMBEDDING_CONTENT_MAX_BYTES,
FIRST_MESSAGE_PROMPT_NAME,
_build_first_message,
+ _create_vapi_web_call,
_resolve_first_message_template,
)
+def _mock_web_call(assistant_overrides: dict[str, Any]) -> dict[str, Any]:
+ return {"webCallUrl": "https://daily.example/call", "id": "call_test"}
+
+
+class TestCreateVapiWebCall(SimpleTestCase):
+ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
+ @patch("products.user_interviews.backend.presentation.webhooks.vapi_request")
+ def test_creates_call_server_side_and_returns_only_join_fields(self, mock_request: Mock) -> None:
+ response = Mock(status_code=201)
+ response.json.return_value = {
+ "id": "call_123",
+ "webCallUrl": "https://daily.example/call",
+ "assistant": {"id": "asst_test", "secret": "not-for-browser"},
+ "artifactPlan": {"videoRecordingEnabled": False},
+ }
+ mock_request.return_value = response
+ overrides = {"metadata": {"sharing_access_token": "share-token"}}
+
+ web_call = _create_vapi_web_call(overrides)
+
+ assert web_call == {
+ "id": "call_123",
+ "webCallUrl": "https://daily.example/call",
+ "artifactPlan": {"videoRecordingEnabled": False},
+ }
+ assert mock_request.call_args.kwargs["api_token"] == "pk_test"
+ assert mock_request.call_args.kwargs["json"] == {
+ "assistantId": "asst_test",
+ "assistantOverrides": overrides,
+ "roomDeleteOnUserLeaveEnabled": True,
+ }
+
+
class _FeatureFlagEnabledMixin(APIBaseTest):
"""Auto-mock `posthoganalytics.feature_enabled` so flag-gated viewsets accept calls in tests."""
@@ -180,13 +213,12 @@ class TestUserInterviewTopicCreate(_FeatureFlagEnabledMixin):
("empty_lists", {"interviewee_emails": [], "interviewee_distinct_ids": []}),
]
)
- def test_rejects_topic_without_identifiers(self, _name: str, targeting: dict[str, Any]):
+ def test_accepts_topic_without_identifiers(self, _name: str, targeting: dict[str, Any]):
+ # A zero-target topic is valid — it backs a non-personalised (shared) link for anonymous
+ # visitors we have no contact details for. Targets can be added later for personalised links.
payload = {"topic": "Why people churn", **targeting}
response = self.client.post(self._url(), data=payload, format="json")
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
- body = response.json()
- candidates = body.get("non_field_errors") or [body.get("detail", "")]
- assert UserInterviewTopicSerializer.MISSING_TARGETING_ERROR in candidates, body
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
@parameterized.expand(
[
@@ -293,14 +325,19 @@ class TestUserInterviewTopicEdit(_FeatureFlagEnabledMixin):
topic.refresh_from_db()
assert topic.topic == "New angle"
- def test_partial_update_rejects_clearing_all_targeting(self):
+ def test_partial_update_can_clear_all_targeting_for_shared_only_topic(self):
+ # Zero-target topics are valid — a shared (non-personalised) link needs no pre-seeded
+ # interviewees — so clearing all targeting must be allowed, not rejected.
topic = self._topic()
response = self.client.patch(
self._detail_url(str(topic.id)),
data={"interviewee_emails": [], "interviewee_distinct_ids": []},
format="json",
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ topic.refresh_from_db()
+ assert topic.interviewee_emails == []
+ assert topic.interviewee_distinct_ids == []
def test_partial_update_revokes_shares_for_removed_identifiers(self):
topic = self._topic(interviewee_emails=["[email protected]", "[email protected]"])
@@ -504,6 +541,15 @@ class TestResolveFirstMessageTemplate(APIBaseTest):
class TestInterviewStartCall(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ patcher = patch(
+ "products.user_interviews.backend.presentation.webhooks._create_vapi_web_call",
+ side_effect=_mock_web_call,
+ )
+ self.create_vapi_web_call = patcher.start()
+ self.addCleanup(patcher.stop)
+
def _create_share(self) -> SharingConfiguration:
topic = UserInterviewTopic.objects.create(
team=self.team,
@@ -529,9 +575,8 @@ class TestInterviewStartCall(APIBaseTest):
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)
body = response.json()
- self.assertEqual(body["public_key"], "pk_test")
- self.assertEqual(body["assistant_id"], "asst_test")
- overrides = body["assistant_overrides"]
+ self.assertEqual(body, {"web_call": {"webCallUrl": "https://daily.example/call", "id": "call_test"}})
+ overrides = self.create_vapi_web_call.call_args.args[0]
# Merged agent_context combines topic-level and per-person notes.
self.assertIn("adoption research", overrides["variableValues"]["agent_context"])
self.assertIn("heavy user, churned last quarter", overrides["variableValues"]["agent_context"])
@@ -544,7 +589,7 @@ class TestInterviewStartCall(APIBaseTest):
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"]
+ overrides = self.create_vapi_web_call.call_args.args[0]
# 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"])
@@ -555,7 +600,7 @@ class TestInterviewStartCall(APIBaseTest):
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"]
+ first_message = self.create_vapi_web_call.call_args.args[0]["firstMessage"]
assert "Hey Alex!" in first_message
assert "Replay adoption" in first_message
@@ -579,8 +624,8 @@ class TestInterviewStartCall(APIBaseTest):
def test_returns_questions_as_json_not_python_repr(self):
share = self._create_share()
self.client.logout()
- response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
- questions_raw = response.json()["assistant_overrides"]["variableValues"]["questions"]
+ self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")
+ questions_raw = self.create_vapi_web_call.call_args.args[0]["variableValues"]["questions"]
# The Vapi assistant prompt receives this string verbatim; it must parse as JSON,
# not Python repr (which would be `['What blocks you?']` with single quotes).
self.assertEqual(json.loads(questions_raw), ["What blocks you?"])
diff --git a/products/user_interviews/backend/test_shared_interview_link.py b/products/user_interviews/backend/test_shared_interview_link.py
new file mode 100644
index 000000000000..2f33ced98ce0
--- /dev/null
+++ b/products/user_interviews/backend/test_shared_interview_link.py
@@ -0,0 +1,470 @@
+import hmac
+import json
+import hashlib
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.test import override_settings
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.api.test.test_sharing import mock_exporter_template
+from posthog.models.sharing_configuration import SharingConfiguration
+from posthog.models.user import User
+
+from products.user_interviews.backend.facade.api import SHARED_INTERVIEWEE_IDENTIFIER, has_replied
+from products.user_interviews.backend.models import (
+ IntervieweeContext,
+ UserInterview,
+ UserInterviewClassification,
+ UserInterviewTopic,
+)
+
+
+def _mock_web_call(assistant_overrides: dict[str, Any]) -> dict[str, Any]:
+ return {"webCallUrl": "https://daily.example/call", "id": "call_test"}
+
+
+def _make_shared_config(*, team: Any, topic: UserInterviewTopic, created_by: User) -> SharingConfiguration:
+ """Build a shared link the way the product does — a sentinel IntervieweeContext plus a
+ SharingConfiguration on it (no new model / no main-app FK)."""
+ ic = IntervieweeContext.objects.create(
+ team=team,
+ topic=topic,
+ interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER,
+ agent_context="",
+ created_by=created_by,
+ )
+ return SharingConfiguration.objects.create(team=team, interviewee_context=ic, enabled=True)
+
+
+class _FeatureFlagEnabledMixin(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ patcher = patch("posthoganalytics.feature_enabled", return_value=True)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+
+class TestGenerateSharedLink(_FeatureFlagEnabledMixin):
+ def _topic(self) -> UserInterviewTopic:
+ return UserInterviewTopic.objects.create(
+ team=self.team,
+ created_by=self.user,
+ interviewee_emails=[],
+ interviewee_distinct_ids=[],
+ topic="Alternatives and comparisons",
+ questions=["What were you comparing us against?"],
+ )
+
+ def _url(self, topic_id: str) -> str:
+ return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/shared_link/"
+
+ def test_creates_shared_link_via_sentinel_context(self) -> None:
+ topic = self._topic()
+ response = self.client.post(self._url(str(topic.id)))
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+
+ # Modelled as a sentinel IntervieweeContext (no new model / no main-app FK).
+ ic = IntervieweeContext.objects.get(
+ team=self.team, topic=topic, interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER
+ )
+ config = SharingConfiguration.objects.get(team=self.team, interviewee_context=ic, enabled=True)
+ assert config.access_token is not None
+ assert config.access_token in response.json()["interview_url"]
+
+ def test_is_idempotent(self) -> None:
+ topic = self._topic()
+ first = self.client.post(self._url(str(topic.id))).json()
+ second = self.client.post(self._url(str(topic.id))).json()
+ assert first["interview_url"] == second["interview_url"]
+ assert (
+ IntervieweeContext.objects.filter(topic=topic, interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER).count()
+ == 1
+ )
+ assert (
+ SharingConfiguration.objects.filter(
+ interviewee_context__topic=topic,
+ interviewee_context__interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER,
+ enabled=True,
+ ).count()
+ == 1
+ )
+
+ def test_shared_link_works_without_any_targeted_interviewees(self) -> None:
+ # Unlike generate_links (which needs emails/distinct_ids), a shared link is for a topic with
+ # no pre-seeded targets — this is the whole point for anonymous blog visitors.
+ topic = self._topic()
+ assert not topic.interviewee_emails and not topic.interviewee_distinct_ids
+ response = self.client.post(self._url(str(topic.id)))
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+
+
+class TestReservedIdentifierRejected(_FeatureFlagEnabledMixin):
+ # A user-supplied identifier equal to the shared-link sentinel (or in the `shared:` namespace)
+ # would collide on the unique (topic, interviewee_identifier) constraint and silently merge with
+ # or revoke the topic's shared link, so it's rejected at every input boundary.
+ def _topics_url(self) -> str:
+ return f"/api/environments/{self.team.id}/user_interview_topics/"
+
+ @parameterized.expand([("sentinel", SHARED_INTERVIEWEE_IDENTIFIER), ("shared_namespace", "shared:abc123")])
+ def test_topic_create_rejects_reserved_distinct_id(self, _name: str, identifier: str) -> None:
+ response = self.client.post(
+ self._topics_url(),
+ data={"topic": "Why people churn", "interviewee_distinct_ids": [identifier]},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
+
+ @parameterized.expand([("sentinel", SHARED_INTERVIEWEE_IDENTIFIER), ("shared_namespace", "shared:abc123")])
+ def test_add_interviewee_rejects_reserved_identifier(self, _name: str, identifier: str) -> None:
+ topic = UserInterviewTopic.objects.create(team=self.team, created_by=self.user, topic="Why people churn")
+ response = self.client.post(
+ f"{self._topics_url()}{topic.id}/add_interviewee/",
+ data={"identifier": identifier},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
+
+
+class TestRevokeSharedLink(_FeatureFlagEnabledMixin):
+ def _topic(self) -> UserInterviewTopic:
+ return UserInterviewTopic.objects.create(
+ team=self.team,
+ created_by=self.user,
+ topic="Alternatives and comparisons",
+ questions=[],
+ )
+
+ def _url(self, topic_id: str) -> str:
+ return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/shared_link/"
+
+ def _start_call_url(self, token: str) -> str:
+ return f"/api/user_interviews/share/{token}/start_call/"
+
+ def _token(self, body: dict) -> str:
+ return body["interview_url"].rstrip("/").rsplit("/", 1)[-1]
+
+ def _enabled_shared_count(self, topic: UserInterviewTopic) -> int:
+ return SharingConfiguration.objects.filter(
+ interviewee_context__topic=topic,
+ interviewee_context__interviewee_identifier=SHARED_INTERVIEWEE_IDENTIFIER,
+ enabled=True,
+ ).count()
+
+ @patch(
+ "products.user_interviews.backend.presentation.webhooks._create_vapi_web_call",
+ side_effect=_mock_web_call,
+ )
+ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
+ def test_delete_revokes_link_and_post_mints_a_fresh_one(self, _create_vapi_web_call) -> None:
+ topic = self._topic()
+ token1 = self._token(self.client.post(self._url(str(topic.id))).json())
+ assert self._enabled_shared_count(topic) == 1
+
+ assert self.client.delete(self._url(str(topic.id))).status_code == status.HTTP_204_NO_CONTENT
+ assert self._enabled_shared_count(topic) == 0
+
+ token2 = self._token(self.client.post(self._url(str(topic.id))).json())
+ assert token2 != token1
+ assert self._enabled_shared_count(topic) == 1
+
+ # The revoked URL can no longer start a call; the freshly minted one can.
+ self.client.logout()
+ revoked = self.client.post(self._start_call_url(token1), data={"name": "Robin"}, format="json")
+ assert revoked.status_code == status.HTTP_404_NOT_FOUND
+ fresh = self.client.post(self._start_call_url(token2), data={"name": "Robin"}, format="json")
+ assert fresh.status_code == status.HTTP_200_OK
+
+
+class TestSharedInterviewPublicViewer(APIBaseTest):
+ def _shared_config(self) -> SharingConfiguration:
+ topic = UserInterviewTopic.objects.create(
+ team=self.team,
+ created_by=self.user,
+ topic="Alternatives and comparisons",
+ agent_context="internal only",
+ questions=["q1"],
+ )
+ return _make_shared_config(team=self.team, topic=topic, created_by=self.user)
+
+ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
+ @mock_exporter_template
+ def test_public_viewer_marks_payload_shared_and_not_already_replied(self) -> None:
+ config = self._shared_config()
+ self.client.logout()
+ response = self.client.get(f"/interview/{config.access_token}")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ body = response.content.decode()
+ self.assertIn("interview", body)
+ self.assertIn(config.access_token, body)
+ self.assertIn("Alternatives and comparisons", body)
+ # agent_context and Vapi creds stay off the HTML, same as the personalised viewer.
+ self.assertNotIn("internal only", body)
+ self.assertNotIn("pk_test", body)
+
+
+class TestSharedStartCall(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ patcher = patch(
+ "products.user_interviews.backend.presentation.webhooks._create_vapi_web_call",
+ side_effect=_mock_web_call,
+ )
+ self.create_vapi_web_call = patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def _shared_config(self) -> SharingConfiguration:
+ topic = UserInterviewTopic.objects.create(
+ team=self.team,
+ created_by=self.user,
+ topic="Alternatives and comparisons",
+ agent_context="topic ctx",
+ questions=["What were you comparing?"],
+ )
+ return _make_shared_config(team=self.team, topic=topic, created_by=self.user)
+
+ def _url(self, token: str | None) -> str:
+ return f"/api/user_interviews/share/{token}/start_call/"
+
+ _SESSION_ID_V7 = "018f0b7a-0000-7000-8000-000000000000"
+
+ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
+ def test_carries_respondent_name_and_valid_linkage_into_metadata(self) -> None:
+ config = self._shared_config()
+ self.client.logout()
+ response = self.client.post(
+ self._url(config.access_token),
+ data={
+ "name": "Robin",
+ "respondent_key": "resp-123",
+ "distinct_id": "person-abc",
+ "session_id": self._SESSION_ID_V7,
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ metadata = self.create_vapi_web_call.call_args.args[0]["metadata"]
+ assert metadata["shared"] == "true"
+ assert metadata["respondent_name"] == "Robin"
+ # The identifier is namespaced on the respondent_key, never the provided distinct_id — so a
+ # respondent can't attribute themselves to a targeted invitee. The distinct_id rides in its
+ # own field as best-effort, untrusted linkage.
+ assert metadata["interviewee_identifier"] == "shared:resp-123"
+ assert metadata["distinct_id"] == "person-abc"
+ assert metadata["session_id"] == self._SESSION_ID_V7
+ assert metadata["sharing_access_token"] == config.access_token
+ # The self-reported name greets the respondent.
+ assert "Robin" in self.create_vapi_web_call.call_args.args[0]["firstMessage"]
+
+ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
+ def test_drops_invalid_linkage_but_still_starts(self) -> None:
+ # Invalid linkage is a reason to ignore the hint, not to reject the interview: a non-UUIDv7
+ # session_id and an illegal distinct_id ("anonymous") are dropped, and the call still starts.
+ config = self._shared_config()
+ self.client.logout()
+ response = self.client.post(
+ self._url(config.access_token),
+ data={"name": "Robin", "distinct_id": "anonymous", "session_id": "not-a-uuid"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ metadata = self.create_vapi_web_call.call_args.args[0]["metadata"]
+ assert metadata["session_id"] == ""
+ # Illegal distinct_id is dropped from the linkage field; the identifier is still a namespaced
+ # shared marker (never the self-reported name), so same-named respondents can't collide.
+ assert metadata["distinct_id"] == ""
+ assert metadata["interviewee_identifier"].startswith("shared:")
+
+ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
+ def test_missing_name_is_rejected(self) -> None:
+ config = self._shared_config()
+ self.client.logout()
+ response = self.client.post(
+ self._url(config.access_token),
+ data={"respondent_key": "resp-123"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ assert response.json() == {"error": "name is required"}
+
+ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")
+ def test_honeypot_filled_is_rejected(self) -> None:
+ config = self._shared_config()
+ self.client.logout()
+ response = self.client.post(
+ self._url(config.access_token),
+ data={"name": "Robin", "_hp": "http://spam.example"},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+
+class TestSharedVapiWebhook(APIBaseTest):
+ def _shared_config(self) -> SharingConfiguration:
+ topic = UserInterviewTopic.objects.create(
+ team=self.team,
+ created_by=self.user,
+ topic="Alternatives and comparisons",
+ questions=[],
+ )
+ return _make_shared_config(team=self.team, topic=topic, created_by=self.user)
+
+ def _payload(
+ self, token: str | None, *, call_id: str, respondent_key: str, transcript: str, name: str = "Robin"
+ ) -> dict:
+ return {
+ "message": {
+ "type": "end-of-call-report",
+ "call": {
+ "id": call_id,
+ "metadata": {
+ "sharing_access_token": token,
+ "shared": "true",
+ "respondent_name": name,
+ "respondent_key": respondent_key,
+ # start_call namespaces the identifier on respondent_key and keeps the untrusted
+ # distinct_id in its own field.
+ "interviewee_identifier": f"shared:{respondent_key}",
+ "distinct_id": "person-abc",
+ "session_id": "018f0b7a-0000-7000-8000-000000000000",
+ },
+ },
+ "transcript": transcript,
+ "summary": "",
+ }
+ }
+
+ def _signed_post(self, secret: str, payload: dict) -> Any:
+ body = json.dumps(payload)
+ signature = hmac.new(secret.encode(), body.encode(), hashlib.sha256).hexdigest()
+ return self.client.post(
+ "/api/user_interviews/vapi_webhook/",
+ data=body,
+ content_type="application/json",
+ HTTP_X_VAPI_SIGNATURE=signature,
+ )
+
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ def test_persists_respondent_and_linkage_for_topic_share(self) -> None:
+ config = self._shared_config()
+ self.client.logout()
+ response = self._signed_post(
+ "topsecret",
+ self._payload(config.access_token, call_id="call_1", respondent_key="resp-1", transcript="a real answer"),
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ interview = UserInterview.objects.get(team=self.team)
+ assert config.interviewee_context is not None
+ assert interview.topic_id == config.interviewee_context.topic_id
+ assert interview.respondent_name == "Robin"
+ # The identifier is namespaced on respondent_key; the untrusted distinct_id is stored in its
+ # own column, never as the identifier.
+ assert interview.interviewee_identifier == "shared:resp-1"
+ assert interview.distinct_id == "person-abc"
+ assert interview.interviewee_emails == []
+
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ @patch("products.user_interviews.backend.presentation.webhooks.posthoganalytics.capture")
+ def test_session_id_rides_on_the_lifecycle_event(self, mock_capture) -> None:
+ # session_id isn't persisted on the model — it's attached to the conversation event as
+ # $session_id so the interview associates with the session recording.
+ config = self._shared_config()
+ self.client.logout()
+ response = self._signed_post(
+ "topsecret",
+ self._payload(config.access_token, call_id="call_s", respondent_key="resp-s", transcript="hi"),
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ ended = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "user_interview_conversation_ended"]
+ assert ended, "expected a conversation_ended event"
+ assert ended[0].kwargs["properties"]["$session_id"] == "018f0b7a-0000-7000-8000-000000000000"
+
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ def test_shared_response_cannot_impersonate_or_lock_out_a_targeted_invitee(self) -> None:
+ # A shared respondent forges a targeted invitee's identifier as their linkage. It must not
+ # become the stored identifier (no forged attribution) and must not gate the invitee's
+ # personalised link (no lockout) — the core IDOR the namespaced identity prevents.
+ topic = UserInterviewTopic.objects.create(
+ team=self.team,
+ created_by=self.user,
+ interviewee_emails=["[email protected]"],
+ topic="Alternatives and comparisons",
+ questions=[],
+ )
+ config = _make_shared_config(team=self.team, topic=topic, created_by=self.user)
+ payload = self._payload(
+ config.access_token, call_id="call_x", respondent_key="attacker", transcript="a full answer"
+ )
+ # Forge the target's identifier in both the echoed identifier and the linkage field.
+ payload["message"]["call"]["metadata"]["interviewee_identifier"] = "[email protected]"
+ payload["message"]["call"]["metadata"]["distinct_id"] = "[email protected]"
+ self.client.logout()
+ response = self._signed_post("topsecret", payload)
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+
+ interview = UserInterview.objects.get(team=self.team)
+ # Stored under a namespaced shared identity, never the targeted invitee's; the forged linkage
+ # is kept only in the untrusted distinct_id field.
+ assert interview.interviewee_identifier == "shared:attacker"
+ assert interview.distinct_id == "[email protected]"
+ # The targeted invitee's personalised link is NOT marked replied.
+ assert not has_replied(team_id=self.team.id, topic_id=topic.id, interviewee_identifier="[email protected]")
+
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ def test_completed_response_supersedes_abandoned_partial_from_a_refresh(self) -> None:
+ config = self._shared_config()
+ assert config.interviewee_context is not None
+ topic = config.interviewee_context.topic
+ # Simulate the abandoned partial an accidental refresh leaves behind: an AI-only transcript
+ # (the respondent never spoke), which is what auto-derives as abandoned and is safe to collapse.
+ abandoned = UserInterview.objects.create(
+ team=self.team,
+ created_by=self.user,
+ topic=topic,
+ interviewee_identifier="shared:resp-1",
+ respondent_key="resp-1",
+ transcript="AI: Hey! Thanks for making time. Ready to start?",
+ classifications=[UserInterviewClassification.ABANDONED],
+ )
+ self.client.logout()
+ response = self._signed_post(
+ "topsecret",
+ self._payload(config.access_token, call_id="call_2", respondent_key="resp-1", transcript="a full answer"),
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ # The abandoned partial is gone; only the completed response remains for this respondent.
+ assert not UserInterview.objects.filter(pk=abandoned.pk).exists()
+ remaining = UserInterview.objects.filter(team=self.team, respondent_key="resp-1")
+ assert remaining.count() == 1
+ assert remaining.first().transcript == "a full answer" # type: ignore[union-attr]
+
+ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")
+ def test_manually_tagged_real_response_is_not_collapsed(self) -> None:
+ # A real response a curator re-tagged `abandoned` (it contains interviewee turns) must survive
+ # the collapse — the delete re-derives from the transcript, so only genuine AI-only partials go.
+ # `abandoned` is user-mutable, so trusting the stored label would permanently delete real data.
+ config = self._shared_config()
+ assert config.interviewee_context is not None
+ topic = config.interviewee_context.topic
+ real = UserInterview.objects.create(
+ team=self.team,
+ created_by=self.user,
+ topic=topic,
+ interviewee_identifier="shared:resp-9",
+ respondent_key="resp-9",
+ transcript="AI: How do you use this?\nUser: Every day — it's core to my workflow.",
+ classifications=[UserInterviewClassification.ABANDONED],
+ )
+ self.client.logout()
+ response = self._signed_post(
+ "topsecret",
+ self._payload(config.access_token, call_id="call_9", respondent_key="resp-9", transcript="a full answer"),
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ # The mislabeled real response is preserved (it has interviewee turns, so it doesn't re-derive
+ # as abandoned); only genuine AI-only partials are collapsed.
+ assert UserInterview.objects.filter(pk=real.pk).exists()
diff --git a/products/user_interviews/frontend/UserInterview.tsx b/products/user_interviews/frontend/UserInterview.tsx
index 1257ccf77f63..a02081686fe8 100644
--- a/products/user_interviews/frontend/UserInterview.tsx
+++ b/products/user_interviews/frontend/UserInterview.tsx
@@ -56,13 +56,15 @@ export function UserInterview({ id }: UserInterviewLogicProps): JSX.Element {
totalTargeted,
responseRate,
linksCsvExporting,
+ sharedLinkLoading,
testLink,
testLinkLoading,
previewInviteIdentifier,
invitePreview,
invitePreviewLoading,
} = useValues(userInterviewLogic)
- const { exportLinksCsv, loadTestLink, openInvitePreview, closeInvitePreview } = useActions(userInterviewLogic)
+ const { exportLinksCsv, copySharedLink, loadTestLink, openInvitePreview, closeInvitePreview } =
+ useActions(userInterviewLogic)
if (topicLoading && !topic) {
return (
@@ -110,7 +112,17 @@ export function UserInterview({ id }: UserInterviewLogicProps): JSX.Element {
<h1 className="text-2xl font-bold mb-1">{topic.topic}</h1>
{topic.agent_context && <p className="text-muted mb-0 text-sm">{topic.agent_context}</p>}
</div>
- <div className="shrink-0">
+ <div className="shrink-0 flex items-center gap-2">
+ <LemonButton
+ type="secondary"
+ icon={<IconCopy />}
+ onClick={copySharedLink}
+ loading={sharedLinkLoading}
+ data-attr="copy-shared-interview-link"
+ tooltip="Copy one shared link anyone can open — each visitor becomes a new anonymous respondent. No interviewee targeting needed."
+ >
+ Copy shared link
+ </LemonButton>
<LemonButton
type="secondary"
icon={<IconDownload />}
diff --git a/products/user_interviews/frontend/generated/api.schemas.ts b/products/user_interviews/frontend/generated/api.schemas.ts
index 07b46e7972a6..351b8d46696c 100644
--- a/products/user_interviews/frontend/generated/api.schemas.ts
+++ b/products/user_interviews/frontend/generated/api.schemas.ts
@@ -233,6 +233,11 @@ export interface PaginatedInterviewInviteResultListApi {
results: InterviewInviteResultApi[]
}
+export interface SharedInterviewLinkApi {
+ /** Public, unauthenticated URL any respondent can open to start a new interview for this topic. Backed by a topic-level SharingConfiguration access token — not tied to any specific interviewee. Each visit is a new anonymous respondent who self-identifies with a name; `distinct_id` and `session_id` query params on the URL are captured as best-effort person/session linkage. */
+ interview_url: string
+}
+
export interface LatestTestInterviewApi {
/** When the test interview was completed. */
completed_at: string
diff --git a/products/user_interviews/frontend/generated/api.ts b/products/user_interviews/frontend/generated/api.ts
index f01908675a40..adc39cbfdf2a 100644
--- a/products/user_interviews/frontend/generated/api.ts
+++ b/products/user_interviews/frontend/generated/api.ts
@@ -24,6 +24,7 @@ import type {
PreviewInviteRequestApi,
PreviewInviteResultApi,
SendInvitesRequestApi,
+ SharedInterviewLinkApi,
TestInterviewLinkApi,
UserInterviewApi,
UserInterviewSearchRequestApi,
@@ -302,6 +303,42 @@ export const userInterviewTopicsSendInvitesCreate = async (
)
}
+export const getUserInterviewTopicsSharedLinkCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/user_interview_topics/${id}/shared_link/`
+}
+
+/**
+ * Get-or-create a single non-personalised (shared) interview link for this topic. Unlike generate_links, the returned URL is not tied to a specific interviewee — every visitor becomes a new anonymous respondent who self-identifies with a name. Idempotent: repeated calls return the same active link. `distinct_id` and `session_id` query params appended to the URL are captured as best-effort person/session linkage.
+ */
+export const userInterviewTopicsSharedLinkCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<SharedInterviewLinkApi> => {
+ return apiMutator<SharedInterviewLinkApi>(getUserInterviewTopicsSharedLinkCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getUserInterviewTopicsSharedLinkDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/user_interview_topics/${id}/shared_link/`
+}
+
+/**
+ * Revoke this topic's shared (non-personalised) interview link so an already-distributed URL can no longer start interviews. Idempotent — a no-op when no active shared link exists. A subsequent shared_link POST mints a fresh link (rotation).
+ */
+export const userInterviewTopicsSharedLinkDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getUserInterviewTopicsSharedLinkDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
export const getUserInterviewTopicsTestLinkRetrieveUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/user_interview_topics/${id}/test_link/`
}
diff --git a/products/user_interviews/frontend/userInterviewLogic.ts b/products/user_interviews/frontend/userInterviewLogic.ts
index 01b44376ae9d..950021ce1303 100644
--- a/products/user_interviews/frontend/userInterviewLogic.ts
+++ b/products/user_interviews/frontend/userInterviewLogic.ts
@@ -4,6 +4,7 @@ import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -15,9 +16,11 @@ import {
userInterviewTopicsIntervieweesList,
userInterviewTopicsPreviewInviteCreate,
userInterviewTopicsRetrieve,
+ userInterviewTopicsSharedLinkCreate,
userInterviewTopicsTestLinkRetrieve,
userInterviewsList,
} from './generated/api'
+import { ClassificationsEnumApi } from './generated/api.schemas'
import type {
IntervieweeContextApi,
InterviewLinkApi,
@@ -57,6 +60,7 @@ export interface userInterviewLogicValues {
respondedCount: number
respondedIdentifiers: Set<string>
responseRate: number
+ sharedLinkLoading: boolean
testLink: TestInterviewLinkApi | null
testLinkLoading: boolean
topic: UserInterviewTopicApi | null
@@ -70,6 +74,12 @@ export interface userInterviewLogicActions {
closeInvitePreview: () => {
value: true
}
+ copySharedLink: () => {
+ value: true
+ }
+ copySharedLinkDone: () => {
+ value: true
+ }
exportLinksCsv: () => {
value: true
}
@@ -263,10 +273,19 @@ export const userInterviewLogic = kea<userInterviewLogicType>([
actions({
exportLinksCsv: true,
exportLinksCsvDone: true,
+ copySharedLink: true,
+ copySharedLinkDone: true,
openInvitePreview: (identifier: string) => ({ identifier }),
closeInvitePreview: true,
}),
reducers({
+ sharedLinkLoading: [
+ false,
+ {
+ copySharedLink: () => true,
+ copySharedLinkDone: () => false,
+ },
+ ],
linksLoadFailed: [
false,
{
@@ -293,6 +312,29 @@ export const userInterviewLogic = kea<userInterviewLogicType>([
openInvitePreview: ({ identifier }) => {
actions.loadInvitePreview(identifier)
},
+ loadTopicSuccess: ({ topic }) => {
+ // generate_links 400s for a zero-target topic (now valid — a shared-only link needs no
+ // targeted interviewees), so only materialise personalised links once we know the topic
+ // has some. Avoids a guaranteed-failing POST and a misleading "couldn't generate link"
+ // state on the shared-only flow.
+ const hasTargets =
+ (topic?.interviewee_emails?.length || 0) + (topic?.interviewee_distinct_ids?.length || 0) > 0
+ if (hasTargets) {
+ actions.loadLinks()
+ }
+ },
+ copySharedLink: async () => {
+ const projectId = String(teamLogic.values.currentTeamId)
+ try {
+ // Idempotent get-or-create — returns the topic's single shared link.
+ const { interview_url } = await userInterviewTopicsSharedLinkCreate(projectId, props.id)
+ await copyToClipboard(interview_url, 'shared interview link')
+ } catch {
+ lemonToast.error('Could not generate the shared interview link')
+ } finally {
+ actions.copySharedLinkDone()
+ }
+ },
exportLinksCsv: async () => {
const projectId = String(teamLogic.values.currentTeamId)
try {
@@ -340,6 +382,12 @@ export const userInterviewLogic = kea<userInterviewLogicType>([
(interviews: UserInterviewApi[]): Set<string> => {
const responded = new Set<string>()
for (const interview of interviews) {
+ // Mirror the backend `has_replied` rule: an abandoned partial (e.g. a mid-call
+ // refresh) is not a reply, so it must not mark the invitee responded — otherwise
+ // the topic page and the public link disagree on who still needs chasing.
+ if (interview.classifications?.includes(ClassificationsEnumApi.Abandoned)) {
+ continue
+ }
if (interview.transcript || interview.summary) {
if (interview.interviewee_identifier) {
responded.add(interview.interviewee_identifier)
@@ -388,7 +436,8 @@ export const userInterviewLogic = kea<userInterviewLogicType>([
actions.loadTopic()
actions.loadInterviewees()
actions.loadInterviews()
- actions.loadLinks()
+ // loadLinks is fired from loadTopicSuccess only when the topic has targeted interviewees —
+ // generate_links 400s for the zero-target (shared-only) topics this now supports.
actions.loadTestLink()
}),
])
diff --git a/products/user_interviews/mcp/tools.yaml b/products/user_interviews/mcp/tools.yaml
index aa8f35b07d19..fc1429be8eac 100644
--- a/products/user_interviews/mcp/tools.yaml
+++ b/products/user_interviews/mcp/tools.yaml
@@ -307,6 +307,12 @@ tools:
- reply_to
- send_async
feature_flag: user-interviews
+ user-interview-topics-shared-link-create:
+ operation: user_interview_topics_shared_link_create
+ enabled: false
+ user-interview-topics-shared-link-destroy:
+ operation: user_interview_topics_shared_link_destroy
+ enabled: false
user-interview-topics-test-link-retrieve:
operation: user_interview_topics_test_link_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0338462a3d5f..3c8959ca04ef 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -56709,6 +56709,11 @@ export namespace Schemas {
readonly is_active: boolean;
}
+ export interface SharedInterviewLink {
+ /** Public, unauthenticated URL any respondent can open to start a new interview for this topic. Backed by a topic-level SharingConfiguration access token — not tied to any specific interviewee. Each visit is a new anonymous respondent who self-identifies with a name; `distinct_id` and `session_id` query params on the URL are captured as best-effort person/session linkage. */
+ interview_url: string;
+ }
+
export interface SharingConfiguration {
readonly created_at: string;
enabled?: boolean;