:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(user-interviews): host AI interview calls via shared links (#58435)
coryslaterc3c458fbf1e0
diff --git a/frontend/package.json b/frontend/package.jsonindex 4bfec0a4ef4b..6c881d6152b6 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -157,6 +157,7 @@"@tiptap/react": "^3.20.1","@tiptap/starter-kit": "^3.20.1","@tiptap/suggestion": "^3.20.1",+ "@vapi-ai/web": "2.5.2","@vitejs/plugin-react": "^4.7.0","@xyflow/react": "^12.6.0","bintrees": "^1.0.2",diff --git a/frontend/src/exporter/Exporter.tsx b/frontend/src/exporter/Exporter.tsxindex 89a737957d45..8244bf7771b4 100644--- a/frontend/src/exporter/Exporter.tsx+++ b/frontend/src/exporter/Exporter.tsx@@ -25,6 +25,7 @@ const LazyHeatmapScene = lazy(() => import('./scenes/ExporterHeatmapScene'))const LazyInsightScene = lazy(() => import('./scenes/ExporterInsightScene'))const LazyNotebookScene = lazy(() => import('./scenes/ExporterNotebookScene'))const LazyRecordingScene = lazy(() => import('./scenes/ExporterRecordingScene'))+const LazyInterviewScene = lazy(() => import('./scenes/ExporterInterviewScene'))function ExportedSceneSkeleton(): JSX.Element {return (@@ -58,6 +59,7 @@ export function Exporter(props: ExportedData): JSX.Element {themes,accessToken,exportToken,+ interview,...exportOptions} = propsconst { whitelabel, showInspector = false } = exportOptions@@ -93,6 +95,14 @@ export function Exporter(props: ExportedData): JSX.Element {return <ExporterLogin whitelabel={whitelabel} />}+ if (type === ExportType.Interview && interview) {+ return (+ <Suspense fallback={<ExportedSceneSkeleton />}>+ <LazyInterviewScene interview={interview} accessToken={accessToken} />+ </Suspense>+ )+ }+return (<BindLogic logic={exporterViewLogic} props={props}><divdiff --git a/frontend/src/exporter/scenes/ExporterInterviewScene.tsx b/frontend/src/exporter/scenes/ExporterInterviewScene.tsxnew file mode 100644index 000000000000..30b861164936--- /dev/null+++ b/frontend/src/exporter/scenes/ExporterInterviewScene.tsx@@ -0,0 +1,157 @@+import { useEffect, useRef, useState } from 'react'++import { LemonButton } from '@posthog/lemon-ui'++import { Logo } from 'lib/brand/Logo'++import { InterviewExportPayload } from '../types'++type CallState = 'idle' | 'loading' | 'connecting' | 'in-call' | 'ended' | 'error'++interface StartCallPayload {+ public_key: string+ assistant_id: string+ assistant_overrides: {+ variableValues?: Record<string, string>+ metadata?: Record<string, string>+ }+}++/**+ * 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.+ */+async function fetchStartCallPayload(accessToken: string): Promise<StartCallPayload> {+ const response = await fetch(`/api/user_interviews/share/${accessToken}/start_call/`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ })+ if (!response.ok) {+ const text = await response.text()+ throw new Error(text || `Server responded ${response.status}`)+ }+ return response.json()+}++export default function ExporterInterviewScene({+ interview,+ accessToken,+}: {+ interview: InterviewExportPayload+ accessToken?: string+}): JSX.Element {+ const [state, setState] = useState<CallState>('idle')+ const [errorMessage, setErrorMessage] = useState<string | null>(null)+ const vapiRef = useRef<{ stop: () => void } | null>(null)++ useEffect(() => {+ document.title = `Interview · ${interview.topic}`+ }, [interview.topic])++ useEffect(() => {+ return () => {+ vapiRef.current?.stop()+ }+ }, [])++ const start = async (): Promise<void> => {+ if (!accessToken) {+ setErrorMessage('Interview link is missing its access token. Open the URL you were emailed.')+ setState('error')+ return+ }+ setState('loading')+ try {+ const [{ default: Vapi }, startPayload] = await Promise.all([+ import(/* webpackChunkName: "vapi-sdk" */ '@vapi-ai/web'),+ fetchStartCallPayload(accessToken),+ ])+ const vapi = new Vapi(startPayload.public_key)+ vapiRef.current = vapi+ vapi.on('call-end', () => setState('ended'))+ vapi.on('error', (e: unknown) => {+ setErrorMessage(e instanceof Error ? e.message : 'Vapi reported an error during the call.')+ setState('error')+ })+ setState('connecting')+ await vapi.start(startPayload.assistant_id, startPayload.assistant_overrides)+ setState('in-call')+ } catch (e) {+ setErrorMessage(e instanceof Error ? e.message : 'Failed to start interview.')+ setState('error')+ }+ }++ const stop = (): void => {+ vapiRef.current?.stop()+ setState('ended')+ }++ return (+ <div className="max-w-2xl mx-auto px-4 py-12">+ <div className="mb-8 flex items-center justify-between">+ <Logo className="text-lg" />+ <span className="text-xs text-muted">Powered by PostHog</span>+ </div>++ <h1 className="text-3xl font-bold mb-4">Hi {interview.user_name}!</h1>++ <p className="text-lg mb-4">+ We're researching <strong>{interview.topic}</strong> and would love to hear your perspective.+ </p>++ <p className="text-muted mb-6">+ This is a 5–10 minute voice conversation with an AI interviewer. Talk like you would to a researcher on+ our team — your feedback helps us build a better product.+ </p>++ <div className="bg-accent-highlight border border-accent p-4 rounded mb-8 text-sm">+ <strong>How it works</strong>+ <ol className="list-decimal pl-5 mt-2 space-y-1">+ <li>+ Click <em>Start interview</em> below.+ </li>+ <li>Allow microphone access when prompted.</li>+ <li>Have a casual conversation — the AI will guide you through a few questions.</li>+ <li>You can end the call any time.</li>+ </ol>+ </div>++ {state === 'idle' && (+ <LemonButton type="primary" size="large" fullWidth onClick={start}>+ Start interview+ </LemonButton>+ )}+ {state === 'loading' && <p>Loading interviewer…</p>}+ {state === 'connecting' && <p>Connecting…</p>}+ {state === 'in-call' && (+ <div>+ <p className="mb-4">You're live with the interviewer.</p>+ <LemonButton type="secondary" onClick={stop}>+ End interview+ </LemonButton>+ </div>+ )}+ {state === 'ended' && (+ <p className="text-success">+ Thanks for taking the time! Your conversation has been recorded — we'll be in touch.+ </p>+ )}+ {state === 'error' && (+ <div className="text-danger">+ <p className="mb-2">{errorMessage ?? 'Something went wrong.'}</p>+ <LemonButton type="secondary" onClick={() => setState('idle')}>+ Try again+ </LemonButton>+ </div>+ )}++ <p className="text-xs text-muted text-center mt-12">+ Your conversation will be transcribed and analyzed to help improve PostHog. We won't share your+ individual responses publicly.+ </p>+ </div>+ )+}diff --git a/frontend/src/exporter/types.ts b/frontend/src/exporter/types.tsindex 6d40502f41c3..ce50a6dbb58c 100644--- a/frontend/src/exporter/types.ts+++ b/frontend/src/exporter/types.ts@@ -17,6 +17,19 @@ export enum ExportType {Scene = 'scene',Unlock = 'unlock',Heatmap = 'heatmap',+ Interview = 'interview',+}++export interface InterviewExportPayload {+ topic_id: string+ interviewee_identifier: string+ user_name: string+ topic: string+ /**+ * 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/`+ * so the personalized agent context never lands in the public HTML.+ */}export interface ExportedData extends SharingConfigurationSettings {@@ -50,4 +63,6 @@ export interface ExportedData extends SharingConfigurationSettings {heatmap_context?: HeatmapExportContext/** Cohort id+name inlined for shared views, which can't reach /api/cohorts. */cohorts?: Pick<CohortType, 'id' | 'name'>[]+ /** AI user interview payload — present only for `type === ExportType.Interview`. */+ interview?: InterviewExportPayload}diff --git a/frontend/src/layout/navigation-3000/navigationLogic.tsx b/frontend/src/layout/navigation-3000/navigationLogic.tsxindex 9789ed362324..defdd38961f5 100644--- a/frontend/src/layout/navigation-3000/navigationLogic.tsx+++ b/frontend/src/layout/navigation-3000/navigationLogic.tsx@@ -597,7 +597,7 @@ export const navigation3000Logic = kea<navigation3000LogicType>([featureFlags[FEATURE_FLAGS.USER_INTERVIEWS]? {identifier: Scene.UserInterviews,- label: 'User interviews',+ label: 'User research',icon: <IconChat />,tag: 'alpha' as const,to: urls.userInterviews(),diff --git a/frontend/src/products.json b/frontend/src/products.jsonindex c485e4500cc8..3189d7f2c556 100644--- a/frontend/src/products.json+++ b/frontend/src/products.json@@ -197,7 +197,7 @@{ "path": "Toolbar", "category": "Tools", "iconType": "toolbar", "type": "toolbar", "intents": ["toolbar"] },{ "path": "Tracing", "category": "Unreleased", "iconType": "tracing", "type": null, "intents": ["tracing"] },{- "path": "User interviews",+ "path": "User research","category": "Unreleased","iconType": "user_interview","type": "user_interview",diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex fbfca9b0590c..0b76fcaae3c3 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -126,6 +126,7 @@ export const productScenes: Record<string, () => Promise<any>> = {Tracing: () => import('../../products/tracing/frontend/TracingScene'),UserInterviews: () => import('../../products/user_interviews/frontend/UserInterviews'),UserInterview: () => import('../../products/user_interviews/frontend/UserInterview'),+ UserInterviewResponse: () => import('../../products/user_interviews/frontend/UserInterviewResponse'),VisualReviewIndex: () => import('../../products/visual_review/frontend/scenes/VisualReviewIndexScene'),VisualReviewRuns: () => import('../../products/visual_review/frontend/scenes/VisualReviewRunsScene'),VisualReviewRun: () => import('../../products/visual_review/frontend/scenes/VisualReviewRunScene'),@@ -234,8 +235,9 @@ export const productRoutes: Record<string, [string, string]> = {'/tasks': ['TaskTracker', 'taskTracker'],'/tasks/:taskId': ['TaskDetail', 'taskDetail'],'/tracing': ['Tracing', 'tracing'],- '/user_interviews': ['UserInterviews', 'userInterviews'],- '/user_interviews/:id': ['UserInterview', 'userInterview'],+ '/user_research': ['UserInterviews', 'userInterviews'],+ '/user_research/:topicId/response/:responseId': ['UserInterviewResponse', 'userInterviewResponse'],+ '/user_research/:id': ['UserInterview', 'userInterview'],'/visual_review': ['VisualReviewIndex', 'visualReviewIndex'],'/visual_review/settings': ['VisualReviewSettings', 'visualReviewSettings'],'/visual_review/runs/:runId': ['VisualReviewRun', 'visualReviewRun'],@@ -300,6 +302,7 @@ export const productRedirects: Record<combineUrl('/logs/drop-rules/new', searchParams, hashParams).url,'/logs/sampling/:id': (params, searchParams, hashParams) =>combineUrl(`/logs/drop-rules/${params.id}`, searchParams, hashParams).url,+ '/user_interviews': '/user_research',}/** This const is auto-generated, as is the whole file */@@ -603,13 +606,14 @@ export const productConfiguration: Record<string, any> = {iconType: 'tracing',},UserInterviews: {- name: 'User interviews',+ name: 'User research',projectBased: true,activityScope: 'UserInterview',- description: 'Record and analyze user interviews with PostHog.',+ description: 'Run AI-powered voice research campaigns to gather user insights at scale.',iconType: 'user_interview',},- UserInterview: { name: 'User interview', projectBased: true, activityScope: 'UserInterview' },+ UserInterview: { name: 'Interview topic', projectBased: true, activityScope: 'UserInterview' },+ UserInterviewResponse: { name: 'Interview response', projectBased: true, activityScope: 'UserInterview' },VisualReviewIndex: { name: 'Visual review', projectBased: true, iconType: 'visual_review' },VisualReviewRuns: { name: 'Runs', projectBased: true, iconType: 'visual_review' },VisualReviewRun: { name: 'Visual review run', projectBased: true, iconType: 'visual_review' },@@ -1000,8 +1004,10 @@ export const productUrls = {taskDetail: (taskId: string | number): string => `/tasks/${taskId}`,toolbarLaunch: (): string => '/toolbar',tracing: (): string => '/tracing',- userInterviews: (): string => '/user_interviews',- userInterview: (id: string): string => `/user_interviews/${id}`,+ userInterviews: (): string => '/user_research',+ userInterview: (id: string): string => `/user_research/${id}`,+ userInterviewResponse: (topicId: string, responseId: string): string =>+ `/user_research/${topicId}/response/${responseId}`,visualReviewRuns: (): string => '/visual_review',visualReviewSettings: (): string => '/visual_review/settings',visualReviewRun: (runId: string): string => `/visual_review/runs/${runId}`,@@ -1153,7 +1159,7 @@ export const fileSystemTypes = {flag: FEATURE_FLAGS.TASKS,},user_interview: {- name: 'User interview',+ name: 'User research',iconType: 'user_interview',href: (ref: string) => urls.userInterview(ref),iconColor: ['var(--color-product-user-interviews-light)'],@@ -1884,7 +1890,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [sceneKeys: ['Tracing'],},{- path: 'User interviews',+ path: 'User research',intents: [ProductKey.USER_INTERVIEWS],category: ProductItemCategory.UNRELEASED,href: urls.userInterviews(),@@ -1894,7 +1900,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [iconType: 'user_interview',iconColor: ['var(--color-product-user-interviews-light)'] as FileSystemIconColor,sceneKey: 'UserInterviews',- sceneKeys: ['UserInterviews', 'UserInterview'],+ sceneKeys: ['UserInterviews', 'UserInterview', 'UserInterviewResponse'],},{path: 'Visual review',diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 173678e3e895..dd10521be87d 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -164,6 +164,7 @@ export enum Scene {Transformations = 'Transformations',Unsubscribe = 'Unsubscribe',UserInterview = 'UserInterview',+ UserInterviewResponse = 'UserInterviewResponse',UserInterviews = 'UserInterviews',VercelConnect = 'VercelConnect',VercelLinkError = 'VercelLinkError',diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 7eeeaa75b1f5..d114e20118aa 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -275,7 +275,7 @@ importers:version: 3.12.1jest:specifier: 'catalog:'- version: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ version: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))oxfmt:specifier: 'catalog:'version: 0.35.0@@ -448,7 +448,7 @@ importers:version: 7.6.4(@babel/[email protected])(@swc/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])'@storybook/test-runner':specifier: ^0.16.0- version: 0.16.0(@types/[email protected])([email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ version: 0.16.0(@types/[email protected])([email protected])'@storybook/theming':specifier: ^7.6.4@@ -859,6 +859,9 @@ importers:'@tiptap/suggestion':specifier: ^3.20.1+ '@vapi-ai/web':+ specifier: 2.5.2+ version: 2.5.2'@vitejs/plugin-react':specifier: ^4.7.0version: 4.7.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -1300,7 +1303,7 @@ importers:version: 29.7.0jest-image-snapshot:specifier: ^6.1.0- version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))+ version: 6.4.0([email protected](@types/[email protected]))kea-typegen:specifier: 3.6.2-leakfix.5version: 3.6.2-leakfix.5([email protected])@@ -1795,7 +1798,7 @@ importers:version: 7.6.24([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@storybook/test-runner':specifier: ^0.16.0- version: 0.16.0(@types/[email protected])([email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ version: 0.16.0(@types/[email protected])([email protected])'@storybook/theming':specifier: ^7.6.20@@ -1816,7 +1819,7 @@ importers:version: 4.7.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))jest-image-snapshot:specifier: ^6.4.0- version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))+ version: 6.4.0([email protected](@types/[email protected]))storybook:specifier: ^7.6.4version: 7.6.4([email protected])@@ -5537,6 +5540,10 @@ packages:resolution: {integrity: sha512-mepCf/e9+SKYy1d02/UkvSy6+6MoyXhVxP8lLDfA7BPE1X1d4dR0sZznmbM8/XVJ1GPM+Svnx7Xj6ZweByWUkw==}engines: {node: '>17.0.0'}+ '@daily-co/[email protected]':+ resolution: {integrity: sha512-lpl111ZWNTUWDnwYcPuNi9PGJPbLCeCw6LzmEY40nG0hv1jg5JLVW8Rq3Cj/+lOCP6W6h4PXm211ss0FFnxITQ==}+ engines: {node: '>=10.0.0'}+'@datadog/[email protected]':resolution: {integrity: sha512-qX32upm9eqObGVGvqHpjQB2bXVPTX0ccXTW3mUqUWXgJrAKyHtTfo9PqfoXhflYs0WD9el9xl9c0bM1RS4vRmQ==}engines: {node: '>=16'}@@ -10205,6 +10212,30 @@ packages:resolution: {integrity: sha512-y2JVHeQsRADEWRLNXV5uf8BAP5PowYU5IBxsSiJY9WCIDS3/RT98g6fFRURefKn+9Dalmp7X7pcHUX5wW2ljYw==}hasBin: true+ '@sentry-internal/[email protected]':+ resolution: {integrity: sha512-GnKod+gL/Y+1FUM/RGV8q6le1CoyiGbT40MitEK7eVwWe+bfTRq1gN7ioupyHFMUg1RlQkDQ4/sENmio/uow5A==}+ engines: {node: '>=14.18'}++ '@sentry-internal/[email protected]':+ resolution: {integrity: sha512-XQy//NWbL0mLLM5w8wNDWMNpXz39VUyW2397dUrH8++kR63WhUVAvTOtL0o0GMVadSAzl1b08oHP9zSUNFQwcg==}+ engines: {node: '>=14.18'}++ '@sentry-internal/[email protected]':+ resolution: {integrity: sha512-P/jGiuR7dRLG9IzD/463fLgiibyYceauav/9prRG0ZxJm1AtuO02OKball2Fs3bbzdzwHCTlcsUuL2ivDF4b5A==}+ engines: {node: '>=14.18'}++ '@sentry-internal/[email protected]':+ resolution: {integrity: sha512-+W43Z697EVe/OgpGW07B773sa8xO1UbpnW0Cr+E+3FMDb6ZbXlaBUoagPTUkkQPdwBe35SDh6r8y2M3EOPGbxg==}+ engines: {node: '>=14.18'}++ '@sentry/[email protected]':+ resolution: {integrity: sha512-xHuPIEKhx9zw5quWvv4YgZprnwoVMCfxIhmOIf6KJ9iizyUHeUDcKpLS59xERroqwX4RpvK+l/27AZu4zfZlzQ==}+ engines: {node: '>=14.18'}++ '@sentry/[email protected]':+ resolution: {integrity: sha512-YlEBwybUcOQ/KjMHDmof1vwweVnBtBxYlQp7DE3fOdtW4pqqdHWTnTntQs4VgYfxzjJYgtkd9LHlGtg8qy+JVQ==}+ engines: {node: '>=14.18'}+'@sgratzl/[email protected]':resolution: {integrity: sha512-XHQTNTk0OtDEZyT7v+BKNKt4OEXYhn4GtfI+iQ1eFiFsx8Aq/csz+mOJYbfpkiP8Popd/8Nky8vLh1zzkYn0gw==}@@ -12648,6 +12679,10 @@ packages:'@upsetjs/[email protected]':resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}+ '@vapi-ai/[email protected]':+ resolution: {integrity: sha512-mT4DjApi0/0+EK77h2xOLq3qVBa7rv3JNQ+gFWuhFE4YdGYxI51+fn8bQI9N535+zU/Z4jFKXotdBHQJ3filHA==}+ engines: {node: '>=18.0.0'}+'@vercel/[email protected]':resolution: {integrity: sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w==}engines: {node: '>= 20'}@@ -28232,6 +28267,14 @@ snapshots:'@dagrejs/[email protected]': {}+ '@daily-co/[email protected]':+ dependencies:+ '@babel/runtime': 7.29.2+ '@sentry/browser': 8.55.2+ bowser: 2.11.0+ dequal: 2.0.3+ events: 3.3.0+'@datadog/[email protected]':dependencies:delay: 5.0.0@@ -29166,41 +29209,6 @@ snapshots:- ts-node- utf-8-validate- '@jest/[email protected]([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':- dependencies:- '@jest/console': 29.7.0- '@jest/reporters': 29.7.0- '@jest/test-result': 29.7.0- '@jest/transform': 29.7.0- '@jest/types': 29.6.3- '@types/node': 22.18.8- ansi-escapes: 4.3.2- chalk: 4.1.2- ci-info: 3.8.0- exit: 0.1.2- graceful-fs: 4.2.11- jest-changed-files: 29.7.0- jest-config: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))- jest-haste-map: 29.7.0- jest-message-util: 29.7.0- jest-regex-util: 29.6.3- jest-resolve: 29.7.0- jest-resolve-dependencies: 29.7.0- jest-runner: 29.7.0- jest-runtime: 29.7.0- jest-snapshot: 29.7.0- jest-util: 29.7.0- jest-validate: 29.7.0- jest-watcher: 29.7.0- micromatch: 4.0.8- pretty-format: 29.7.0- slash: 3.0.0- strip-ansi: 6.0.1- transitivePeerDependencies:- - babel-plugin-macros- - supports-color- - ts-node-'@jest/[email protected]([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':dependencies:'@jest/console': 29.7.0@@ -33179,6 +33187,34 @@ snapshots:'@segment/[email protected]': {}+ '@sentry-internal/[email protected]':+ dependencies:+ '@sentry/core': 8.55.2++ '@sentry-internal/[email protected]':+ dependencies:+ '@sentry/core': 8.55.2++ '@sentry-internal/[email protected]':+ dependencies:+ '@sentry-internal/replay': 8.55.2+ '@sentry/core': 8.55.2++ '@sentry-internal/[email protected]':+ dependencies:+ '@sentry-internal/browser-utils': 8.55.2+ '@sentry/core': 8.55.2++ '@sentry/[email protected]':+ dependencies:+ '@sentry-internal/browser-utils': 8.55.2+ '@sentry-internal/feedback': 8.55.2+ '@sentry-internal/replay': 8.55.2+ '@sentry-internal/replay-canvas': 8.55.2+ '@sentry/core': 8.55.2++ '@sentry/[email protected]': {}+'@sgratzl/[email protected]': {}'@sgratzl/[email protected]([email protected])':@@ -34608,7 +34644,7 @@ snapshots:- encoding- supports-color- '@storybook/[email protected](@types/[email protected])([email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':dependencies:'@babel/core': 7.29.0'@babel/generator': 7.29.1@@ -36589,6 +36625,11 @@ snapshots:d3-selection: 3.0.0d3-transition: 3.0.1([email protected])+ '@vapi-ai/[email protected]':+ dependencies:+ '@daily-co/daily-js': 0.85.0+ events: 3.3.0+'@vercel/[email protected]': {}'@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':@@ -38585,21 +38626,6 @@ snapshots:safe-buffer: 5.2.1sha.js: 2.4.12- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):- dependencies:- '@jest/types': 29.6.3- chalk: 4.1.2- exit: 0.1.2- graceful-fs: 4.2.11- jest-config: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))- jest-util: 29.7.0- prompts: 2.4.2- transitivePeerDependencies:- - '@types/node'- - babel-plugin-macros- - supports-color- - ts-node-[email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@jest/types': 29.6.3@@ -42064,25 +42090,6 @@ snapshots:- ts-node- utf-8-validate- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):- dependencies:- '@jest/core': 29.7.0([email protected](@swc/[email protected])(@types/[email protected])([email protected]))- '@jest/test-result': 29.7.0- '@jest/types': 29.6.3- chalk: 4.1.2- create-jest: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))- exit: 0.1.2- import-local: 3.2.0- jest-config: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))- jest-util: 29.7.0- jest-validate: 29.7.0- yargs: 17.7.2- transitivePeerDependencies:- - '@types/node'- - babel-plugin-macros- - supports-color- - ts-node-[email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@jest/core': 29.7.0([email protected](@swc/[email protected])(@types/[email protected])([email protected]))@@ -42155,37 +42162,6 @@ snapshots:- supports-color- utf-8-validate- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):- dependencies:- '@babel/core': 7.29.0- '@jest/test-sequencer': 29.7.0- '@jest/types': 29.6.3- babel-jest: 29.7.0(@babel/[email protected])- chalk: 4.1.2- ci-info: 3.8.0- deepmerge: 4.3.1- glob: 7.2.3- graceful-fs: 4.2.11- jest-circus: 29.7.0- jest-environment-node: 29.7.0- jest-get-type: 29.6.3- jest-regex-util: 29.6.3- jest-resolve: 29.7.0- jest-runner: 29.7.0- jest-util: 29.7.0- jest-validate: 29.7.0- micromatch: 4.0.8- parse-json: 5.2.0- pretty-format: 29.7.0- slash: 3.0.0- strip-json-comments: 3.1.1- optionalDependencies:- '@types/node': 22.18.8- transitivePeerDependencies:- - babel-plugin-macros- - supports-color-[email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0@@ -42436,7 +42412,7 @@ snapshots:optionalDependencies:fsevents: 2.3.3- [email protected]([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))):dependencies:chalk: 4.1.2get-stdin: 5.0.1@@ -43092,18 +43068,6 @@ snapshots:- ts-node- utf-8-validate- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):- dependencies:- '@jest/core': 29.7.0([email protected](@swc/[email protected])(@types/[email protected])([email protected]))- '@jest/types': 29.6.3- import-local: 3.2.0- jest-cli: 29.7.0(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))- transitivePeerDependencies:- - '@types/node'- - babel-plugin-macros- - supports-color- - ts-node-[email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@jest/core': 29.7.0([email protected](@swc/[email protected])(@types/[email protected])([email protected]))@@ -49450,27 +49414,6 @@ snapshots:tslib: 2.8.1typescript: 5.9.3- dependencies:- '@cspotcode/source-map-support': 0.8.1- '@tsconfig/node10': 1.0.9- '@tsconfig/node12': 1.0.11- '@tsconfig/node14': 1.0.3- '@tsconfig/node16': 1.0.3- '@types/node': 22.18.8- acorn: 8.15.0- acorn-walk: 8.3.2- arg: 4.1.3- create-require: 1.1.1- diff: 4.0.2- make-error: 1.3.6- typescript: 5.9.3- v8-compile-cache-lib: 3.0.1- yn: 3.1.1- optionalDependencies:- '@swc/core': 1.11.4- optional: true-dependencies:'@cspotcode/source-map-support': 0.8.1diff --git a/posthog/api/sharing.py b/posthog/api/sharing.pyindex 214eb14755a8..06af00151e86 100644--- a/posthog/api/sharing.py+++ b/posthog/api/sharing.py@@ -695,7 +695,14 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSeif access_token:try:sharing_configuration = (- SharingConfiguration.objects.select_related("dashboard", "insight", "recording", "notebook")+ SharingConfiguration.objects.select_related(+ "dashboard",+ "insight",+ "recording",+ "notebook",+ "interviewee_context",+ "interviewee_context__topic",+ ).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now())).get(access_token=access_token))@@ -1006,6 +1013,28 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSeexcept Exception:raise NotFound("No heatmap found")+ elif isinstance(resource, SharingConfiguration) and resource.interviewee_context:+ from products.user_interviews.backend.api import _parse_identifier++ ic = resource.interviewee_context+ topic = ic.topic+ asset_title = topic.topic or "User interview"+ asset_description = "PostHog AI user interview"+ user_name, _ = _parse_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.+ exported_data.update(+ {+ "type": "interview",+ "interview": {+ "topic_id": str(topic.id),+ "interviewee_identifier": ic.interviewee_identifier,+ "user_name": user_name,+ "topic": topic.topic,+ },+ }+ )elif isinstance(resource, SharingConfiguration) and resource.recording:asset_title = "Session Recording"recording_data = SessionRecordingSerializer(resource.recording, context=context).datadiff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambrindex e4e6cf0231bb..57ab6f08fa83 100644--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr@@ -1649,6 +1649,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -4577,6 +4578,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -7045,6 +7047,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -8119,6 +8122,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -9316,6 +9320,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -11148,6 +11153,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -11173,6 +11179,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -14759,6 +14766,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -16099,6 +16107,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -16124,6 +16133,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -17154,6 +17164,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -17179,6 +17190,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -18030,6 +18042,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",diff --git a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambrindex a63c718b0913..d6b3d78877d9 100644--- a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr+++ b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr@@ -888,6 +888,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",@@ -906,6 +907,7 @@"posthog_sharingconfiguration"."insight_id","posthog_sharingconfiguration"."recording_id","posthog_sharingconfiguration"."notebook_id",+ "posthog_sharingconfiguration"."interviewee_context_id","posthog_sharingconfiguration"."created_at","posthog_sharingconfiguration"."enabled","posthog_sharingconfiguration"."access_token",diff --git a/posthog/migrations/1155_sharingconfiguration_interviewee_context.py b/posthog/migrations/1155_sharingconfiguration_interviewee_context.pynew file mode 100644index 000000000000..87f534734fc0--- /dev/null+++ b/posthog/migrations/1155_sharingconfiguration_interviewee_context.py@@ -0,0 +1,25 @@+# Generated by Django 5.2.13 on 2026-05-13 20:37++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1154_userpushtoken"),+ ("user_interviews", "0003_intervieweecontext"),+ ]++ operations = [+ migrations.AddField(+ model_name="sharingconfiguration",+ name="interviewee_context",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="sharing_configurations",+ to="user_interviews.intervieweecontext",+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex d1258c0c8d71..38e6b0d3ed4a 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1154_userpushtoken+1155_sharingconfiguration_interviewee_contextdiff --git a/posthog/models/sharing_configuration.py b/posthog/models/sharing_configuration.pyindex c6429889227c..43fb8627c3d8 100644--- a/posthog/models/sharing_configuration.py+++ b/posthog/models/sharing_configuration.py@@ -41,6 +41,13 @@ class SharingConfiguration(models.Model):null=True,blank=True,)+ interviewee_context = models.ForeignKey(+ "user_interviews.IntervieweeContext",+ related_name="sharing_configurations",+ on_delete=models.CASCADE,+ null=True,+ blank=True,+ )created_at = models.DateTimeField(auto_now_add=True, blank=True)@@ -70,6 +77,7 @@ class SharingConfiguration(models.Model):insight=self.insight,recording=self.recording,notebook=self.notebook,+ interviewee_context=self.interviewee_context,enabled=self.enabled,settings=self.settings,password_required=self.password_required,@@ -126,7 +134,7 @@ class SharingConfiguration(models.Model):if obj._meta.object_name == "Insight" and (self.dashboard or self.notebook):return cast(Insight, obj).id in self.get_connected_insight_ids()- for comparison in [self.insight, self.dashboard, self.recording, self.notebook]:+ for comparison in [self.insight, self.dashboard, self.recording, self.notebook, self.interviewee_context]:if comparison and comparison == obj:return Truediff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.pyindex a0e3937fb936..99e556bb9ebe 100644--- a/posthog/settings/__init__.py+++ b/posthog/settings/__init__.py@@ -70,6 +70,11 @@ SITE_URL: str = os.getenv("SITE_URL", "http://localhost:8010").rstrip("/")NGROK_URL: str | None = os.getenv("NGROK_URL", None)INSTANCE_TAG: str = os.getenv("INSTANCE_TAG", "none")+# Vapi voice-AI integration (used by user_interviews to host public interview pages).+VAPI_PUBLIC_KEY: str = os.getenv("VAPI_PUBLIC_KEY", "")+VAPI_ASSISTANT_ID: str = os.getenv("VAPI_ASSISTANT_ID", "")+VAPI_WEBHOOK_SECRET: str = os.getenv("VAPI_WEBHOOK_SECRET", "")+if DEBUG:JS_URL: str = os.getenv("JS_URL", "http://localhost:8234").rstrip("/")else:diff --git a/posthog/templates/email/interview_invite.html b/posthog/templates/email/interview_invite.htmlnew file mode 100644index 000000000000..d106c6a56162--- /dev/null+++ b/posthog/templates/email/interview_invite.html@@ -0,0 +1,30 @@+{% extends "email/base.html" %}++{% block heading %}Got 5 minutes to chat?{% endblock %}++{% block section %}+<p>Hey {{ user_name }},</p>++<p>+ We're researching <strong>{{ topic }}</strong> and your perspective would be really valuable. Got 5–10 minutes for a quick voice conversation?+</p>++<p>+ It's a casual call with an AI interviewer — not a sales call, just research. You can do it whenever's convenient in the next few days.+</p>++<p style="text-align: center; margin: 32px 0;">+ <a href="{{ interview_url }}" target="_blank" style="background: #1d4aff; color: #ffffff; padding: 12px 24px; border-radius: 6px; text-decoration: none; font-weight: 600;">+ Start the interview+ </a>+</p>++<p style="font-size: 12px; color: #888;">+ Or paste this link into your browser: <a href="{{ interview_url }}">{{ interview_url }}</a>+</p>++<p>+ Thanks!<br />+ The PostHog team+</p>+{% endblock %}diff --git a/posthog/urls.py b/posthog/urls.pyindex 48195f1a46f1..6e48ca8d221b 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -57,6 +57,10 @@ from products.signals.backend import views as signals_viewsfrom products.signals.backend.views import SignalUserAutonomyConfigView as signals_user_autonomy_viewfrom products.slack_app.backend.api import posthog_code_event_handler, posthog_code_interactivity_handlerfrom products.surveys.backend.api.survey import public_survey_page+from products.user_interviews.backend.webhooks import (+ start_call as user_interviews_start_call,+ vapi_webhook,+)from .utils import opt_slash_path, render_templatefrom .views import (@@ -252,6 +256,16 @@ urlpatterns = [name="user_signal_autonomy",),path("api/environments/<int:team_id>/messaging/customerio/webhook/", csrf_exempt(CustomerIOWebhookView.as_view())),+ path(+ "api/user_interviews/vapi_webhook/",+ csrf_exempt(vapi_webhook),+ name="user_interviews_vapi_webhook",+ ),+ path(+ "api/user_interviews/share/<str:access_token>/start_call/",+ csrf_exempt(user_interviews_start_call),+ name="user_interviews_start_call",+ ),path("api/sdk_doctor/", sdk_doctor),path("api/conversations/", include("products.conversations.backend.api.urls")),path(@@ -355,6 +369,10 @@ urlpatterns = ["embedded/<str:access_token>",sharing.SharingViewerPageViewSet.as_view({"get": "retrieve"}),),+ path(+ "interview/<str:access_token>",+ sharing.SharingViewerPageViewSet.as_view({"get": "retrieve"}),+ ),path("render_query", render_query, name="render_query"),path("exporter", sharing.SharingViewerPageViewSet.as_view({"get": "retrieve"})),path(diff --git a/products/user_interviews/backend/api.py b/products/user_interviews/backend/api.pyindex 54e795c2f0b4..2cd77335c23b 100644--- a/products/user_interviews/backend/api.py+++ b/products/user_interviews/backend/api.py@@ -6,21 +6,28 @@ from uuid import uuid4from django.conf import settingsfrom django.core.files import File+from django.db import modelsfrom django.db.models import QuerySet+from django.utils import timezoneimport posthoganalyticsimport posthoganalytics.ai.openai-from drf_spectacular.utils import extend_schema+from drf_spectacular.utils import OpenApiResponse, extend_schemafrom elevenlabs import ElevenLabsfrom posthoganalytics.ai.openai import OpenAI-from rest_framework import filters, serializers, viewsets+from rest_framework import filters, response, serializers, status, viewsets+from rest_framework.decorators import actionfrom rest_framework.parsers import JSONParser, MultiPartParser+from rest_framework.request import Requestfrom posthog.schema import ProductKeyfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer+from posthog.email import EmailMessage, is_email_available+from posthog.models.sharing_configuration import SharingConfigurationfrom posthog.permissions import PostHogFeatureFlagPermission+from posthog.utils import absolute_urifrom .models import EmailWithDisplayNameValidator, IntervieweeContext, UserInterview, UserInterviewTopic@@ -38,11 +45,13 @@ class UserInterviewSerializer(serializers.ModelSerializer):"created_by","created_at","interviewee_emails",+ "interviewee_identifier",+ "topic","transcript","summary","audio",)- read_only_fields = ("id", "created_by", "created_at", "transcript")+ read_only_fields = ("id", "created_by", "created_at", "interviewee_identifier", "topic", "transcript")def create(self, validated_data: dict) -> UserInterview:request = self.context["request"]@@ -310,6 +319,140 @@ class UserInterviewTopicSerializer(serializers.ModelSerializer):)+def _parse_identifier(identifier: str) -> tuple[str, str | None]:+ """Split an interviewee identifier into a display name and (optional) email.++ Accepts the same display-name format the topic validator accepts —+ ``"Display Name <email@host>"`` — falling back to a best-effort+ title-cased local-part for raw emails and the identifier as-is for+ distinct IDs.+ """+ display_match = re.match(EmailWithDisplayNameValidator.display_name_regex, identifier)+ if display_match:+ return display_match.group(1).strip(), display_match.group(2).strip()+ if "@" in identifier:+ local_part = identifier.split("@", 1)[0]+ return local_part.replace(".", " ").replace("_", " ").strip().title() or identifier, identifier+ return identifier, None+++def _merge_agent_context(topic_context: str, personal_context: str) -> str:+ parts = [p.strip() for p in (topic_context, personal_context) if p and p.strip()]+ return "\n\n".join(parts)+++class InterviewLinkSerializer(serializers.Serializer):+ interviewee_identifier = serializers.CharField(+ max_length=400,+ help_text="The original identifier (email or distinct ID) from the topic targeting.",+ )+ user_name = serializers.CharField(+ help_text="Best-effort display name derived from the identifier, used to greet the interviewee.",+ )+ interview_url = serializers.URLField(+ help_text="Public, unauthenticated URL the interviewee opens to start the call. Backed by a SharingConfiguration access token.",+ )+ agent_context = serializers.CharField(+ help_text="The merged topic + per-interviewee context the voice agent will see during the call.",+ )+++def _materialize_links_for_topic(*, topic: UserInterviewTopic, team: Any, created_by: Any) -> list[dict[str, Any]]:+ """Get-or-create an `IntervieweeContext` and enabled `SharingConfiguration` for every+ targeted identifier on the topic. Returns one row per identifier with the resolved+ objects attached so callers (link-listing, invite-sending) can fan out without re-querying.++ Race-safe: concurrent calls for the same (topic, identifier) rely on the+ `unique_interviewee_per_topic` constraint (Paul's migration 0003) to coalesce. The+ `SharingConfiguration` lookup is best-effort and may transiently produce two configs+ on a tight race — that's acceptable since both are valid and one wins the next call.+ """+ identifiers: list[str] = []+ seen: set[str] = set()+ for raw in [*(topic.interviewee_emails or []), *(topic.interviewee_distinct_ids or [])]:+ if raw and raw not in seen:+ identifiers.append(raw)+ seen.add(raw)++ if not identifiers:+ return []++ results: list[dict[str, Any]] = []+ for identifier in identifiers:+ ic, _ = IntervieweeContext.objects.get_or_create(+ team=team,+ topic=topic,+ interviewee_identifier=identifier,+ 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,+ )++ user_name, email = _parse_identifier(identifier)+ results.append(+ {+ "identifier": identifier,+ "user_name": user_name,+ "email": email,+ "interview_url": absolute_uri(f"/interview/{sharing_config.access_token}"),+ "agent_context": _merge_agent_context(topic.agent_context or "", ic.agent_context or ""),+ "interviewee_context": ic,+ "sharing_configuration": sharing_config,+ }+ )+ return results+++class InterviewInviteResultSerializer(serializers.Serializer):+ interviewee_identifier = serializers.CharField(+ help_text="The original identifier (email or distinct ID) from the topic targeting.",+ )+ email = serializers.EmailField(+ required=False,+ allow_null=True,+ help_text="Email used for delivery. Null when the identifier was not an email (e.g., a distinct ID).",+ )+ interview_url = serializers.URLField(+ help_text="The personalized public interview URL embedded in the email body.",+ )+ sent = serializers.BooleanField(+ help_text="True if an email was queued for delivery. False when the recipient was skipped — see `reason`.",+ )+ reason = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text="Why the email was skipped (e.g., `not_an_email`, `already_sent`). Empty when sent=true.",+ )+++class SendInvitesRequestSerializer(serializers.Serializer):+ subject = serializers.CharField(+ required=False,+ max_length=200,+ help_text="Override the default email subject line. Defaults to a friendly prompt referencing the topic.",+ )+ reply_to = serializers.EmailField(+ required=False,+ help_text="Email address replies should go to. Defaults to the topic creator's email if blank.",+ )+ send_async = serializers.BooleanField(+ required=False,+ default=True,+ help_text="If true (default), queue delivery via Celery. If false, send synchronously and surface errors immediately.",+ )++@extend_schema(tags=[ProductKey.USER_INTERVIEWS])class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"""Planned user interview topics: who we want to target (cohort) and what we want to ask about."""@@ -322,6 +465,120 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):posthog_feature_flag = "user-interviews"permission_classes = [PostHogFeatureFlagPermission]+ @extend_schema(+ request=None,+ responses={200: OpenApiResponse(response=InterviewLinkSerializer(many=True))},+ description=(+ "Generate one public interview link per targeted interviewee. "+ "Materializes an IntervieweeContext row for every identifier on the topic "+ "(without overwriting existing per-person context), and an enabled "+ "SharingConfiguration with a unique access token. The URL resolves to the "+ "public interview viewer with no PostHog auth required."+ ),+ )+ @action(detail=True, methods=["post"], url_path="generate_links")+ def generate_links(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:+ topic = self.get_object()+ results = _materialize_links_for_topic(topic=topic, team=self.team, created_by=request.user)++ if not results:+ return response.Response(+ {+ "error": (+ "Topic targets a cohort but has no resolved emails or distinct IDs. "+ "Add interviewee_emails or interviewee_distinct_ids before generating links."+ )+ },+ status=status.HTTP_400_BAD_REQUEST,+ )++ payload = [+ {+ "interviewee_identifier": r["identifier"],+ "user_name": r["user_name"],+ "interview_url": r["interview_url"],+ "agent_context": r["agent_context"],+ }+ for r in results+ ]+ return response.Response(InterviewLinkSerializer(payload, many=True).data)++ @extend_schema(+ request=SendInvitesRequestSerializer,+ responses={200: OpenApiResponse(response=InterviewInviteResultSerializer(many=True))},+ description=(+ "Generate (if needed) and email a personalized public interview link to every "+ "targeted interviewee on this topic whose identifier is an email address. "+ "Distinct-ID-only interviewees are skipped and surfaced in the response. "+ "Each invite is keyed on the underlying SharingConfiguration so re-runs after "+ "token rotation produce a fresh send."+ ),+ )+ @action(detail=True, methods=["post"], url_path="send_invites")+ def send_invites(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:+ if not is_email_available():+ return response.Response(+ {"error": "Email is not configured for this PostHog instance."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )++ params = SendInvitesRequestSerializer(data=request.data)+ params.is_valid(raise_exception=True)++ topic = self.get_object()+ links = _materialize_links_for_topic(topic=topic, team=self.team, created_by=request.user)+ if not links:+ return response.Response(+ {+ "error": (+ "Topic targets a cohort but has no resolved emails or distinct IDs. "+ "Add interviewee_emails or interviewee_distinct_ids before sending invites."+ )+ },+ status=status.HTTP_400_BAD_REQUEST,+ )++ topic_label = topic.topic or "a quick research interview"+ subject = params.validated_data.get("subject") or f"Got 5 minutes to talk about {topic_label}?"+ reply_to = params.validated_data.get("reply_to")+ if not reply_to and topic.created_by_id and topic.created_by and topic.created_by.email:+ reply_to = topic.created_by.email+ send_async = params.validated_data["send_async"]++ results: list[dict[str, Any]] = []+ for link in links:+ base = {+ "interviewee_identifier": link["identifier"],+ "email": link["email"],+ "interview_url": link["interview_url"],+ }+ if not link["email"]:+ results.append({**base, "sent": False, "reason": "not_an_email"})+ continue++ campaign_key = f"interview_invite_{link['sharing_configuration'].id}"+ try:+ message = EmailMessage(+ campaign_key=campaign_key,+ template_name="interview_invite",+ subject=subject,+ template_context={+ "user_name": link["user_name"],+ "topic": topic_label,+ "interview_url": link["interview_url"],+ "site_url": settings.SITE_URL,+ },+ reply_to=reply_to,+ )+ message.add_recipient(email=link["email"], name=link["user_name"])+ message.send(send_async=send_async)+ results.append({**base, "sent": True, "reason": ""})+ except Exception as e: # noqa: BLE001 — surface per-recipient failures without aborting the batch+ posthoganalytics.capture_exception(e)+ results.append({**base, "sent": False, "reason": f"error:{type(e).__name__}"})++ return response.Response(InterviewInviteResultSerializer(results, many=True).data)+class IntervieweeContextSerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)@@ -352,11 +609,14 @@ class IntervieweeContextSerializer(serializers.ModelSerializer):if not UserInterviewTopic.objects.filter(id=topic_id, team_id=team.id).exists():raise serializers.ValidationError({"topic": "Topic not found in this project."})- if self.instance is None:- interviewee_identifier = attrs.get("interviewee_identifier")- if IntervieweeContext.objects.filter(+ interviewee_identifier = attrs.get("interviewee_identifier")+ if interviewee_identifier is not None:+ conflicts = IntervieweeContext.objects.filter(topic_id=topic_id, interviewee_identifier=interviewee_identifier- ).exists():+ )+ if self.instance is not None:+ conflicts = conflicts.exclude(pk=self.instance.pk)+ if conflicts.exists():raise serializers.ValidationError({"interviewee_identifier": "A context row for this interviewee already exists on this topic. Update the existing row instead of creating a new one."diff --git a/products/user_interviews/backend/migrations/0004_userinterview_vapi_fields.py b/products/user_interviews/backend/migrations/0004_userinterview_vapi_fields.pynew file mode 100644index 000000000000..c6c2985c17de--- /dev/null+++ b/products/user_interviews/backend/migrations/0004_userinterview_vapi_fields.py@@ -0,0 +1,39 @@+# Generated by Django 5.2.13 on 2026-05-13 20:49++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("user_interviews", "0003_intervieweecontext"),+ ]++ operations = [+ migrations.AddField(+ model_name="userinterview",+ name="call_metadata",+ field=models.JSONField(blank=True, default=dict),+ ),+ migrations.AddField(+ model_name="userinterview",+ name="interviewee_identifier",+ field=models.CharField(blank=True, default="", max_length=400),+ ),+ migrations.AddField(+ model_name="userinterview",+ name="recording_url",+ field=models.URLField(blank=True, default="", max_length=2048),+ ),+ migrations.AddField(+ model_name="userinterview",+ name="topic",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="interviews",+ to="user_interviews.userinterviewtopic",+ ),+ ),+ ]diff --git a/products/user_interviews/backend/migrations/max_migration.txt b/products/user_interviews/backend/migrations/max_migration.txtindex 55f2c4f2ea7a..01b3a6aaefdd 100644--- a/products/user_interviews/backend/migrations/max_migration.txt+++ b/products/user_interviews/backend/migrations/max_migration.txt@@ -1 +1 @@-0003_intervieweecontext+0004_userinterview_vapi_fieldsdiff --git a/products/user_interviews/backend/models.py b/products/user_interviews/backend/models.pyindex 4c5a64a82919..13dcbf344763 100644--- a/products/user_interviews/backend/models.py+++ b/products/user_interviews/backend/models.py@@ -29,6 +29,17 @@ class UserInterview(UUIDTModel, CreatedMetaFields):)transcript = models.TextField(blank=True)summary = models.TextField(blank=True)+ # Optional topic linkage for AI voice interviews triggered via SharingConfiguration links.+ topic = models.ForeignKey(+ "UserInterviewTopic",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ related_name="interviews",+ )+ interviewee_identifier = models.CharField(max_length=400, blank=True, default="")+ recording_url = models.URLField(blank=True, default="", max_length=2048)+ call_metadata = models.JSONField(default=dict, blank=True)class UserInterviewTopic(UUIDTModel, CreatedMetaFields):diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.pynew file mode 100644index 000000000000..51bf83b59f10--- /dev/null+++ b/products/user_interviews/backend/test_interview_sharing.py@@ -0,0 +1,480 @@+import hmac+import json+import hashlib+import datetime+from typing import Any++from freezegun import freeze_time+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import override_settings+from django.utils import timezone++from rest_framework import status++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+++class _FeatureFlagEnabledMixin(APIBaseTest):+ """Auto-mock `posthoganalytics.feature_enabled` so flag-gated viewsets accept calls in tests."""++ def setUp(self) -> None:+ super().setUp()+ patcher = patch("posthoganalytics.feature_enabled", return_value=True)+ patcher.start()+ self.addCleanup(patcher.stop)+++class TestGenerateInterviewLinks(_FeatureFlagEnabledMixin):+ def _create_topic(self, **overrides) -> UserInterviewTopic:+ defaults: dict = {+ "team": self.team,+ "created_by": self.user,+ "interviewee_emails": ["Alex <[email protected]>", "[email protected]"],+ "interviewee_distinct_ids": ["distinct-abc"],+ "topic": "Session replay adoption",+ "agent_context": "Researching adoption of session replay",+ "questions": ["What blocks adoption?"],+ }+ defaults.update(overrides)+ return UserInterviewTopic.objects.create(**defaults)++ def _generate_links_url(self, topic_id: str) -> str:+ return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/generate_links/"++ def test_generate_links_materializes_contexts_and_sharing_configs(self):+ topic = self._create_topic()++ response = self.client.post(self._generate_links_url(str(topic.id)))++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ body = response.json()+ identifiers = sorted(link["interviewee_identifier"] for link in body)+ self.assertEqual(+ identifiers,+ sorted(["Alex <[email protected]>", "[email protected]", "distinct-abc"]),+ )++ for link in body:+ self.assertTrue(link["interview_url"].endswith(link["interview_url"].rsplit("/", 1)[-1]))+ self.assertIn("/interview/", link["interview_url"])++ self.assertEqual(IntervieweeContext.objects.filter(topic=topic).count(), 3)+ self.assertEqual(+ SharingConfiguration.objects.filter(team=self.team, interviewee_context__topic=topic, enabled=True).count(),+ 3,+ )++ def test_generate_links_is_idempotent(self):+ topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])+ first = self.client.post(self._generate_links_url(str(topic.id))).json()+ second = self.client.post(self._generate_links_url(str(topic.id))).json()+ self.assertEqual(first[0]["interview_url"], second[0]["interview_url"])+ self.assertEqual(IntervieweeContext.objects.filter(topic=topic).count(), 1)+ self.assertEqual(SharingConfiguration.objects.filter(interviewee_context__topic=topic).count(), 1)++ def test_generate_links_preserves_existing_personal_context(self):+ topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])+ IntervieweeContext.objects.create(+ team=self.team,+ topic=topic,+ interviewee_identifier="[email protected]",+ agent_context="heavy user, churned last quarter",+ created_by=self.user,+ )+ response = self.client.post(self._generate_links_url(str(topic.id)))+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ link = response.json()[0]+ self.assertIn("heavy user, churned last quarter", link["agent_context"])+ self.assertIn("Researching adoption of session replay", link["agent_context"])++ def test_generate_links_rejects_topic_with_only_cohort(self):+ topic = self._create_topic(+ interviewee_emails=[],+ interviewee_distinct_ids=[],+ interviewee_cohort=123,+ )+ response = self.client.post(self._generate_links_url(str(topic.id)))+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+++class TestInterviewPublicViewer(APIBaseTest):+ def _create_share(self) -> SharingConfiguration:+ topic = UserInterviewTopic.objects.create(+ team=self.team,+ created_by=self.user,+ interviewee_emails=["[email protected]"],+ topic="Session replay adoption",+ agent_context="adoption research",+ questions=["q1"],+ )+ ic = IntervieweeContext.objects.create(+ team=self.team,+ topic=topic,+ interviewee_identifier="[email protected]",+ agent_context="heavy user",+ created_by=self.user,+ )+ return SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)++ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")+ @mock_exporter_template+ def test_public_viewer_renders_interview_payload_without_agent_context(self):+ share = self._create_share()+ self.client.logout()+ response = self.client.get(f"/interview/{share.access_token}")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ body = response.content.decode()+ # The exporter payload is JSON-encoded inside a JSON script tag, so escaped keys appear.+ # We render: type=interview, topic name, access token. We do NOT render the agent+ # context, the questions, or the Vapi credentials — those live behind /start_call/.+ self.assertIn("interview", body)+ self.assertIn(share.access_token, body)+ self.assertIn("Session replay adoption", body)+ self.assertNotIn("heavy user", body)+ self.assertNotIn("adoption research", body)+ self.assertNotIn("pk_test", body)+ self.assertNotIn("asst_test", body)++ def test_public_viewer_rejects_disabled_share(self):+ share = self._create_share()+ share.enabled = False+ share.save()+ self.client.logout()+ response = self.client.get(f"/interview/{share.access_token}")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+++class TestInterviewStartCall(APIBaseTest):+ def _create_share(self) -> SharingConfiguration:+ topic = UserInterviewTopic.objects.create(+ team=self.team,+ created_by=self.user,+ interviewee_emails=["[email protected]"],+ topic="Replay adoption",+ agent_context="adoption research",+ questions=["What blocks you?"],+ )+ ic = IntervieweeContext.objects.create(+ team=self.team,+ topic=topic,+ interviewee_identifier="[email protected]",+ agent_context="heavy user, churned last quarter",+ created_by=self.user,+ )+ return SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)++ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")+ def test_returns_merged_assistant_overrides(self):+ share = self._create_share()+ self.client.logout()+ response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ body = response.json()+ self.assertEqual(body["public_key"], "pk_test")+ self.assertEqual(body["assistant_id"], "asst_test")+ overrides = body["assistant_overrides"]+ # 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"])+ self.assertEqual(overrides["metadata"]["sharing_access_token"], share.access_token)+ self.assertEqual(overrides["metadata"]["interviewee_identifier"], "[email protected]")++ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")+ def test_rejects_disabled_share(self):+ share = self._create_share()+ share.enabled = False+ share.save()+ self.client.logout()+ response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ @override_settings(VAPI_PUBLIC_KEY="", VAPI_ASSISTANT_ID="")+ def test_503_when_vapi_unconfigured(self):+ share = self._create_share()+ self.client.logout()+ response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")+ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)++ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")+ 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"]+ # 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?"])++ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")+ def test_rejects_when_org_disables_public_sharing(self):+ share = self._create_share()+ org = share.team.organization+ # Pretend the org has the enterprise security feature and has disabled public shares.+ org.available_product_features = [{"key": "organization_security_settings", "name": "Org security"}]+ org.allow_publicly_shared_resources = False+ org.save()+ self.client.logout()+ response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ @freeze_time("2026-05-14 12:00:00")+ @override_settings(VAPI_PUBLIC_KEY="pk_test", VAPI_ASSISTANT_ID="asst_test")+ def test_rejects_expired_rotated_token(self):+ # Simulate the post-grace-period state of a rotated SharingConfiguration:+ # `expires_at` in the past, still `enabled=True`. The public viewer 404s on these,+ # and start_call must do the same — otherwise the rotated token is still valid here.+ share = self._create_share()+ share.expires_at = timezone.now() - datetime.timedelta(minutes=1)+ share.save()+ self.client.logout()+ response = self.client.post(f"/api/user_interviews/share/{share.access_token}/start_call/")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+++class TestVapiWebhook(APIBaseTest):+ def _create_share(self) -> SharingConfiguration:+ topic = UserInterviewTopic.objects.create(+ team=self.team,+ created_by=self.user,+ interviewee_emails=["[email protected]"],+ topic="Replay adoption",+ agent_context="ctx",+ questions=[],+ )+ ic = IntervieweeContext.objects.create(+ team=self.team,+ topic=topic,+ interviewee_identifier="[email protected]",+ agent_context="",+ created_by=self.user,+ )+ return SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)++ def _end_of_call_payload(self, access_token: str | None, call_id: str = "call_abc") -> dict:+ return {+ "message": {+ "type": "end-of-call-report",+ "call": {+ "id": call_id,+ "metadata": {"sharing_access_token": access_token},+ "duration": 120,+ },+ "transcript": "Hi! ...",+ "summary": "User talked about replay.",+ "recording": {"url": "https://vapi.example/recording.mp3"},+ }+ }++ 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_webhook_creates_user_interview(self):+ share = self._create_share()+ self.client.logout()+ response = self._signed_post("topsecret", self._end_of_call_payload(share.access_token))+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)+ interview = UserInterview.objects.get(team=self.team)+ assert share.interviewee_context is not None+ self.assertEqual(interview.topic, share.interviewee_context.topic)+ self.assertEqual(interview.interviewee_identifier, "[email protected]")+ self.assertEqual(interview.recording_url, "https://vapi.example/recording.mp3")+ self.assertEqual(interview.transcript, "Hi! ...")++ @override_settings(VAPI_WEBHOOK_SECRET="")+ def test_webhook_fails_closed_when_secret_unset(self):+ share = self._create_share()+ self.client.logout()+ response = self.client.post(+ "/api/user_interviews/vapi_webhook/",+ data=self._end_of_call_payload(share.access_token),+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)+ self.assertEqual(UserInterview.objects.count(), 0)++ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")+ def test_webhook_rejects_unknown_token(self):+ self.client.logout()+ response = self._signed_post("topsecret", self._end_of_call_payload("does-not-exist"))+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")+ def test_webhook_requires_valid_signature(self):+ share = self._create_share()+ self.client.logout()+ response = self.client.post(+ "/api/user_interviews/vapi_webhook/",+ data=self._end_of_call_payload(share.access_token),+ content_type="application/json",+ HTTP_X_VAPI_SIGNATURE="wrong",+ )+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")+ def test_webhook_ignores_non_end_of_call_events(self):+ self.client.logout()+ response = self._signed_post("topsecret", {"message": {"type": "status-update"}})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["status"], "ignored")++ @override_settings(VAPI_WEBHOOK_SECRET="topsecret")+ def test_webhook_is_idempotent_on_call_id(self):+ share = self._create_share()+ self.client.logout()+ payload = self._end_of_call_payload(share.access_token, call_id="call_xyz")+ first = self._signed_post("topsecret", payload)+ self.assertEqual(first.status_code, status.HTTP_201_CREATED)+ second = self._signed_post("topsecret", payload)+ self.assertEqual(second.status_code, status.HTTP_200_OK)+ self.assertEqual(second.json()["status"], "duplicate")+ self.assertEqual(first.json()["interview_id"], second.json()["interview_id"])+ self.assertEqual(UserInterview.objects.filter(team=self.team).count(), 1)+++class TestSendInterviewInvites(_FeatureFlagEnabledMixin):+ def _create_topic(self, **overrides) -> UserInterviewTopic:+ defaults: dict = {+ "team": self.team,+ "created_by": self.user,+ "interviewee_emails": ["Alex <[email protected]>", "[email protected]"],+ "interviewee_distinct_ids": ["distinct-no-email"],+ "topic": "Session replay adoption",+ "agent_context": "ctx",+ "questions": ["q1"],+ }+ defaults.update(overrides)+ return UserInterviewTopic.objects.create(**defaults)++ def _url(self, topic_id: str) -> str:+ return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/send_invites/"++ def test_send_invites_emails_only_email_identifiers(self):+ topic = self._create_topic()++ with (+ patch("products.user_interviews.backend.api.EmailMessage") as mock_message_cls,+ patch("products.user_interviews.backend.api.is_email_available", return_value=True),+ ):+ mock_message = mock_message_cls.return_value+ response = self.client.post(self._url(str(topic.id)), data={"send_async": False}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ results = response.json()+ sent = sorted(r["interviewee_identifier"] for r in results if r["sent"])+ skipped = [r for r in results if not r["sent"]]+ self.assertEqual(sent, sorted(["Alex <[email protected]>", "[email protected]"]))+ self.assertEqual(len(skipped), 1)+ self.assertEqual(skipped[0]["interviewee_identifier"], "distinct-no-email")+ self.assertEqual(skipped[0]["reason"], "not_an_email")++ # Two EmailMessage instances built, each with one recipient, sent synchronously.+ self.assertEqual(mock_message_cls.call_count, 2)+ self.assertEqual(mock_message.add_recipient.call_count, 2)+ mock_message.send.assert_called_with(send_async=False)++ def test_send_invites_defaults_subject_and_reply_to(self):+ topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])++ with (+ patch("products.user_interviews.backend.api.EmailMessage") as mock_message_cls,+ patch("products.user_interviews.backend.api.is_email_available", return_value=True),+ ):+ self.client.post(self._url(str(topic.id)), data={}, format="json")++ kwargs = mock_message_cls.call_args.kwargs+ self.assertIn("Session replay adoption", kwargs["subject"])+ self.assertEqual(kwargs["reply_to"], self.user.email)+ self.assertEqual(kwargs["template_name"], "interview_invite")+ self.assertEqual(kwargs["template_context"]["user_name"], "Alex")+ self.assertIn("/interview/", kwargs["template_context"]["interview_url"])++ def test_send_invites_uses_explicit_subject_and_reply_to(self):+ topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])++ with (+ patch("products.user_interviews.backend.api.EmailMessage") as mock_message_cls,+ patch("products.user_interviews.backend.api.is_email_available", return_value=True),+ ):+ self.client.post(+ self._url(str(topic.id)),+ data={"subject": "Hey, can we chat?", "reply_to": "[email protected]"},+ format="json",+ )++ kwargs = mock_message_cls.call_args.kwargs+ self.assertEqual(kwargs["subject"], "Hey, can we chat?")+ self.assertEqual(kwargs["reply_to"], "[email protected]")++ def test_send_invites_503_when_email_disabled(self):+ topic = self._create_topic()+ with patch("products.user_interviews.backend.api.is_email_available", return_value=False):+ response = self.client.post(self._url(str(topic.id)), data={}, format="json")+ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)++ def test_send_invites_400_when_topic_only_has_cohort(self):+ topic = self._create_topic(interviewee_emails=[], interviewee_distinct_ids=[], interviewee_cohort=123)+ with patch("products.user_interviews.backend.api.is_email_available", return_value=True):+ response = self.client.post(self._url(str(topic.id)), data={}, format="json")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_send_invites_marks_per_recipient_failures(self):+ topic = self._create_topic(+ interviewee_emails=["[email protected]", "[email protected]"], interviewee_distinct_ids=[]+ )++ class FlakyEmail:+ """Stand-in for EmailMessage that raises on send for one specific recipient."""++ def __init__(self, **_kwargs):+ self.recipient_email = None++ def add_recipient(self, email, name=None, distinct_id=None):+ self.recipient_email = email++ def send(self, send_async=True):+ if self.recipient_email == "[email protected]":+ raise RuntimeError("smtp down")++ with (+ patch("products.user_interviews.backend.api.EmailMessage", FlakyEmail),+ patch("products.user_interviews.backend.api.is_email_available", return_value=True),+ ):+ response = self.client.post(self._url(str(topic.id)), data={"send_async": False}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ by_id = {r["interviewee_identifier"]: r for r in response.json()}+ self.assertTrue(by_id["[email protected]"]["sent"])+ self.assertFalse(by_id["[email protected]"]["sent"])+ self.assertTrue(by_id["[email protected]"]["reason"].startswith("error:"))+++class TestSharingConfigurationCanAccess(APIBaseTest):+ def test_can_access_interviewee_context(self):+ topic = UserInterviewTopic.objects.create(+ team=self.team,+ created_by=self.user,+ interviewee_emails=["[email protected]"],+ topic="t",+ )+ ic = IntervieweeContext.objects.create(+ team=self.team,+ topic=topic,+ interviewee_identifier="[email protected]",+ agent_context="",+ created_by=self.user,+ )+ share = SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)+ self.assertTrue(share.can_access_object(ic))diff --git a/products/user_interviews/backend/webhooks.py b/products/user_interviews/backend/webhooks.pynew file mode 100644index 000000000000..1105967ccc3d--- /dev/null+++ b/products/user_interviews/backend/webhooks.py@@ -0,0 +1,223 @@+"""Public, unauthenticated endpoints for the user_interviews product.++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.+* ``vapi_webhook`` — called by Vapi at end-of-call. Persists a UserInterview row+ attributed to the topic creator. Signature-verified; idempotent on ``call.id``.+"""++import hmac+import json+import hashlib+from typing import Any++from django.conf import settings+from django.db import transaction+from django.db.models import Q+from django.utils.timezone import now++import structlog+from rest_framework import status+from rest_framework.decorators import api_view, authentication_classes, permission_classes+from rest_framework.permissions import AllowAny+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.constants import AvailableFeature+from posthog.models.sharing_configuration import SharingConfiguration++from .models import UserInterview++logger = structlog.get_logger(__name__)+++def _verify_signature(secret: str, raw_body: bytes, provided_signature: str | None) -> bool:+ if not secret or not provided_signature:+ return False+ expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()+ return hmac.compare_digest(provided_signature, expected)+++def _resolve_share(access_token: str) -> SharingConfiguration | None:+ """Resolve a share token to its `SharingConfiguration`, mirroring the filters+ used by `SharingViewerPageViewSet.get_object()`:+ * `enabled=True`+ * not expired (`expires_at` null OR in the future) — rotated tokens past their+ 5-minute grace period are excluded so this surface stays consistent with the+ public viewer.+ """+ try:+ return (+ SharingConfiguration.objects.select_related(+ "team",+ "team__organization",+ "interviewee_context",+ "interviewee_context__topic",+ "interviewee_context__topic__created_by",+ )+ .filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now()))+ .get(access_token=access_token, enabled=True)+ )+ except SharingConfiguration.DoesNotExist:+ return None+++def _public_sharing_disabled_for_org(sharing_config: SharingConfiguration) -> bool:+ """Mirror of `SharingViewerPageViewSet.retrieve()`'s org-level kill switch."""+ organization = sharing_config.team.organization+ return (+ organization.is_feature_available(AvailableFeature.ORGANIZATION_SECURITY_SETTINGS)+ and not organization.allow_publicly_shared_resources+ )+++@api_view(["POST"])+@authentication_classes([])+@permission_classes([AllowAny])+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.+ """+ from .api import _merge_agent_context, _parse_identifier++ if not settings.VAPI_PUBLIC_KEY or not settings.VAPI_ASSISTANT_ID:+ return Response(+ {"error": "Vapi is not configured on this PostHog instance."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )++ sharing_config = _resolve_share(access_token)+ if sharing_config is None or sharing_config.interviewee_context is None:+ return Response({"error": "unknown access_token"}, status=status.HTTP_404_NOT_FOUND)+ if _public_sharing_disabled_for_org(sharing_config):+ # Match the public viewer's behavior: return 404 so the kill switch is opaque to+ # link recipients (doesn't reveal whether the token is real, just disabled).+ return Response({"error": "unknown access_token"}, status=status.HTTP_404_NOT_FOUND)++ 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 "")++ return Response(+ {+ "public_key": settings.VAPI_PUBLIC_KEY,+ "assistant_id": settings.VAPI_ASSISTANT_ID,+ "assistant_overrides": {+ "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,+ },+ },+ }+ )+++@api_view(["POST"])+@authentication_classes([])+@permission_classes([AllowAny])+def vapi_webhook(request: Request) -> Response:+ """Receive a Vapi ``end-of-call-report`` and persist it as a UserInterview.++ Fail-closed: if ``VAPI_WEBHOOK_SECRET`` is not configured we refuse to accept any+ request — treating an unconfigured deployment as inert rather than insecure.+ With the secret set, the request body is HMAC-SHA256 verified.++ Idempotent: Vapi retries on 5xx and transient errors, so we de-duplicate by+ ``call.id`` (stored in ``call_metadata.id``). A repeat delivery returns the+ existing interview's id instead of creating a second row.+ """+ if not settings.VAPI_WEBHOOK_SECRET:+ return Response(+ {"error": "Vapi webhook secret is not configured on this PostHog instance."},+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )+ provided = request.headers.get("x-vapi-signature") or request.headers.get("X-Vapi-Signature")+ if not _verify_signature(settings.VAPI_WEBHOOK_SECRET, request.body, provided):+ return Response({"error": "invalid signature"}, status=status.HTTP_401_UNAUTHORIZED)++ payload = request.data if isinstance(request.data, dict) else {}+ message: dict[str, Any] = payload.get("message", {})+ if message.get("type") != "end-of-call-report":+ # Other event types (status updates, transcripts mid-call) are ignored.+ return Response({"status": "ignored"})++ call: dict[str, Any] = message.get("call", {}) or {}+ metadata: dict[str, Any] = call.get("metadata", {}) or {}+ access_token = metadata.get("sharing_access_token") or metadata.get("access_token")+ call_id = call.get("id")++ if not access_token:+ return Response(+ {"error": "missing sharing_access_token in call.metadata"},+ status=status.HTTP_400_BAD_REQUEST,+ )++ sharing_config = _resolve_share(access_token)+ if sharing_config is None:+ return Response({"error": "unknown access_token"}, status=status.HTTP_404_NOT_FOUND)++ interviewee_context = sharing_config.interviewee_context+ if interviewee_context is None:+ return Response(+ {"error": "access_token does not belong to a user interview share"},+ status=status.HTTP_400_BAD_REQUEST,+ )++ if call_id:+ existing = UserInterview.objects.filter(team=sharing_config.team, call_metadata__id=call_id).first()+ if existing is not None:+ logger.info(+ "user_interviews_vapi_webhook_duplicate",+ team_id=sharing_config.team_id,+ interview_id=str(existing.id),+ call_id=call_id,+ )+ 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 ""++ 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 [],+ transcript=message.get("transcript", "") or "",+ summary=message.get("summary", "") or "",+ recording_url=recording_url,+ call_metadata=call,+ created_by=topic.created_by,+ )++ logger.info(+ "user_interviews_vapi_webhook_stored",+ team_id=sharing_config.team_id,+ topic_id=str(topic.id),+ interview_id=str(interview.id),+ interviewee=interviewee_context.interviewee_identifier,+ )+ return Response({"status": "created", "interview_id": str(interview.id)}, status=status.HTTP_201_CREATED)diff --git a/products/user_interviews/frontend/UserInterview.tsx b/products/user_interviews/frontend/UserInterview.tsxindex b21fd763f871..233899c43d6d 100644--- a/products/user_interviews/frontend/UserInterview.tsx+++ b/products/user_interviews/frontend/UserInterview.tsx@@ -1,20 +1,17 @@-import { useAsyncActions, useValues } from 'kea'-import posthog from 'posthog-js'-import { useState } from 'react'+import { useValues } from 'kea'-import { IconCheck, IconPencil, IconX } from '@posthog/icons'-import { LemonButton, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'+import { IconArrowLeft, IconCheck, IconChevronRight, IconClock } from '@posthog/icons'+import { LemonButton, LemonSkeleton, LemonTag, LemonWidget } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'-import { dayjs } from 'lib/dayjs'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'-import { LemonTextAreaMarkdown } from 'lib/lemon-ui/LemonTextArea/LemonTextAreaMarkdown'-import { LemonWidget } from 'lib/lemon-ui/LemonWidget/LemonWidget'-import { PersonDisplay } from 'scenes/persons/PersonDisplay'+import { Link } from 'lib/lemon-ui/Link'import { SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'-import { UserInterviewType } from '~/types'+import { SceneContent } from '~/layout/scenes/components/SceneContent'+import type { UserInterviewTopicApi } from './generated/api.schemas'import { UserInterviewLogicProps, userInterviewLogic } from './userInterviewLogic'export const scene: SceneExport<UserInterviewLogicProps> = {@@ -23,136 +20,240 @@ export const scene: SceneExport<UserInterviewLogicProps> = {paramsToProps: ({ params: { id } }) => ({ id }),}-export function UserInterview(): JSX.Element {- const { userInterview, userInterviewLoading } = useValues(userInterviewLogic)- const { updateUserInterview } = useAsyncActions(userInterviewLogic)+function targetingLabel(topic: UserInterviewTopicApi): string {+ const emailCount = topic.interviewee_emails?.length || 0+ const distinctIdCount = topic.interviewee_distinct_ids?.length || 0+ const hasCohort = topic.interviewee_cohort != null+ const parts: string[] = []+ if (hasCohort) {+ parts.push(`Cohort #${topic.interviewee_cohort}`)+ }+ if (emailCount > 0) {+ parts.push(`${emailCount} email${emailCount !== 1 ? 's' : ''}`)+ }+ if (distinctIdCount > 0) {+ parts.push(`${distinctIdCount} ID${distinctIdCount !== 1 ? 's' : ''}`)+ }+ return parts.length > 0 ? parts.join(' + ') : 'Not set'+}- const [summaryInEditing, setSummaryInEditing] = useState<string | null>(null)+export function UserInterview({ id }: UserInterviewLogicProps): JSX.Element {+ const {+ topic,+ topicLoading,+ interviewees,+ intervieweesLoading,+ respondedIdentifiers,+ respondedCount,+ totalTargeted,+ responseRate,+ } = useValues(userInterviewLogic)- if (userInterviewLoading && !userInterview) {+ if (topicLoading && !topic) {return (- <div className="@container">- <div className="grid grid-cols-1 items-start gap-4 @4xl:grid-cols-3">- <LemonWidget title="Summary" className="col-span-2">- <div className="space-y-1.5 p-3">- <LemonSkeleton.Text className="h-6 w-[20%]" />- <LemonSkeleton.Text className="h-3 w-[60%]" />- <LemonSkeleton.Text className="h-3 w-[70%]" />- <LemonSkeleton.Text className="h-3 w-[80%]" />- <LemonSkeleton.Text className="h-3 w-[40%]" />- <LemonSkeleton.Text className="h-3 w-[55%]" />- <LemonSkeleton.Text className="h-3 w-[65%]" />- </div>- </LemonWidget>- <LemonWidget title="Transcript" className="col-span-1">- <div className="space-y-1.5 p-3">- <LemonSkeleton.Text className="h-3 w-[80%]" />- <LemonSkeleton.Text className="h-3 w-[40%]" />- <LemonSkeleton.Text className="h-3 w-[60%]" />- <LemonSkeleton.Text className="h-3 w-[70%]" />- <LemonSkeleton.Text className="h-3 w-[80%]" />- <LemonSkeleton.Text className="h-3 w-[40%]" />- <LemonSkeleton.Text className="h-3 w-[60%]" />- <LemonSkeleton.Text className="h-3 w-[70%]" />- </div>- </LemonWidget>+ <SceneContent>+ <div className="space-y-4">+ <LemonSkeleton.Text className="h-8 w-[60%]" />+ <LemonSkeleton.Text className="h-4 w-[40%]" />+ <div className="grid grid-cols-2 gap-3 @2xl:grid-cols-4">+ <LemonSkeleton className="h-24" />+ <LemonSkeleton className="h-24" />+ <LemonSkeleton className="h-24" />+ <LemonSkeleton className="h-24" />+ </div></div>- </div>+ </SceneContent>)}- if (!userInterview) {- return <NotFound object="user interview" />+ if (!topic) {+ return <NotFound object="interview topic" />}+ const pendingCount = totalTargeted - respondedCount+ const questionCount = topic.questions?.length || 0+ const allIdentifiers = [...(topic.interviewee_emails || []), ...(topic.interviewee_distinct_ids || [])]+return (- <div className="@container">- <InterviewMetadata interview={userInterview} />- <div className="grid grid-cols-1 items-start gap-4 @4xl:grid-cols-3">- <LemonWidget- title="Summary"- className="col-span-2"- actions={- summaryInEditing !== null ? (- <>- <LemonButton- size="xsmall"- icon={<IconX />}- tooltip="Discard changes"- onClick={() => setSummaryInEditing(null)}- disabledReason={userInterviewLoading ? 'Saving…' : undefined}- />- <LemonButton- size="xsmall"- icon={<IconCheck />}- tooltip="Save"- onClick={() => {- updateUserInterview({ summary: summaryInEditing })- .then(() => {- setSummaryInEditing(null)- })- .catch((e) => posthog.captureException(e))- }}- loading={userInterviewLoading}- />- </>- ) : (- <LemonButton- size="xsmall"- icon={<IconPencil />}- onClick={() => setSummaryInEditing(userInterview.summary || '')}- />- )- }- >- {summaryInEditing !== null ? (- <LemonTextAreaMarkdown- value={summaryInEditing}- onChange={(newValue) => setSummaryInEditing(newValue)}- className="pb-2 px-3"- />- ) : (- <LemonMarkdown className="p-3">- {userInterview.summary || '_No summary available._'}- </LemonMarkdown>- )}- </LemonWidget>- <div className="col-span-1 flex flex-col gap-y-4">- <LemonWidget title="Participants">- <div className="p-3 flex flex-col gap-y-2">- {userInterview.interviewee_emails.map((interviewee_email) => (- <PersonDisplay- key={interviewee_email}- person={{- properties: {- email: interviewee_email,- },- distinct_id: interviewee_email,- }}- withIcon- />- ))}+ <SceneContent>+ {/* Header */}+ <div className="flex items-start justify-between mb-4">+ <div>+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconArrowLeft />}+ to={urls.userInterviews()}+ className="mb-1 -ml-2"+ >+ All topics+ </LemonButton>+ <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>++ <div className="grid grid-cols-1 gap-4 @container @4xl:grid-cols-3">+ {/* Left column */}+ <div className="col-span-2 flex flex-col gap-4">+ {/* Stats cards */}+ <div className="grid grid-cols-2 gap-3 @2xl:grid-cols-4">+ {/* Response rate — hero card */}+ <div className="col-span-2 rounded-lg border-2 border-success bg-success-highlight p-4 flex items-center justify-between">+ <div>+ <div className="text-xs font-semibold uppercase text-success tracking-wide">+ Response rate+ </div>+ <div className="text-3xl font-bold text-success mt-1">{responseRate}%</div>+ <div className="text-sm text-muted mt-0.5">+ {respondedCount} of {totalTargeted} responded+ </div>+ </div>+ <div className="text-5xl font-bold text-success opacity-20">{respondedCount}</div>+ </div>++ <StatCard label="Awaiting response" value={pendingCount} color="warning" />+ <StatCard label="Questions" value={questionCount} color="muted" />+ </div>++ {/* Targeted people list */}+ <LemonWidget title={`People (${allIdentifiers.length})`}>+ <div className="divide-y">+ {intervieweesLoading && interviewees.length === 0 && allIdentifiers.length === 0 ? (+ <div className="p-4 space-y-3">+ <LemonSkeleton.Text className="h-4 w-[60%]" />+ <LemonSkeleton.Text className="h-4 w-[40%]" />+ <LemonSkeleton.Text className="h-4 w-[50%]" />+ </div>+ ) : allIdentifiers.length === 0 ? (+ <div className="p-4 text-muted text-center">+ No people targeted yet. Use PostHog AI to set up targeting and generate interview+ links.+ </div>+ ) : (+ allIdentifiers.map((identifier) => (+ <PersonRow+ key={identifier}+ identifier={identifier}+ topicId={id}+ hasResponded={respondedIdentifiers.has(identifier)}+ />+ ))+ )}</div></LemonWidget>- <LemonWidget title="Transcript">- <LemonMarkdown className="p-3">- {userInterview.transcript || '_No transcript available._'}- </LemonMarkdown>+ </div>++ {/* Right column — topic metadata */}+ <div className="col-span-1 flex flex-col gap-4">+ <LemonWidget title="Details">+ <div className="p-3 space-y-3">+ <DetailRow label="Targeting" value={targetingLabel(topic)} />+ <DetailRow label="Created" value={topic.created_at.split('T')[0]} />+ <DetailRow+ label="Owner"+ value={topic.created_by?.first_name || topic.created_by?.email || '—'}+ />+ </div></LemonWidget>++ {questionCount > 0 && (+ <LemonWidget title="Interview questions">+ <div className="p-3">+ <LemonMarkdown>+ {(topic.questions || []).map((q, i) => `${i + 1}. ${q}`).join('\n')}+ </LemonMarkdown>+ </div>+ </LemonWidget>+ )}++ {topic.agent_context && (+ <LemonWidget title="Agent context">+ <div className="p-3">+ <p className="text-sm mb-0">{topic.agent_context}</p>+ </div>+ </LemonWidget>+ )}</div></div>+ </SceneContent>+ )+}++function StatCard({+ label,+ value,+ color,+}: {+ label: string+ value: number+ color: 'success' | 'warning' | 'primary' | 'muted' | 'danger'+}): JSX.Element {+ const borderColor = {+ success: 'border-success',+ warning: 'border-warning',+ primary: 'border-primary',+ muted: 'border-border',+ danger: 'border-danger',+ }[color]+ const textColor = {+ success: 'text-success',+ warning: 'text-warning',+ primary: 'text-primary',+ muted: 'text-muted',+ danger: 'text-danger',+ }[color]++ return (+ <div className={`rounded-lg border-2 ${borderColor} bg-bg-light p-3`}>+ <div className={`text-2xl font-bold ${textColor}`}>{value}</div>+ <div className="text-xs text-muted font-medium mt-0.5">{label}</div>+ </div>+ )+}++function DetailRow({ label, value }: { label: string; value: string }): JSX.Element {+ return (+ <div className="flex justify-between">+ <span className="text-muted text-sm">{label}</span>+ <span className="text-sm font-medium">{value}</span></div>)}-function InterviewMetadata({ interview }: { interview: UserInterviewType }): JSX.Element {+function PersonRow({+ identifier,+ topicId,+ hasResponded,+}: {+ identifier: string+ topicId: string+ hasResponded: boolean+}): JSX.Element {return (- <header className="flex gap-x-2 gap-y-1 flex-wrap items-center">- {interview.created_at && (- <LemonTag className="bg-bg-light">- Created: {dayjs(interview.created_at).format('YYYY-MM-DD HH:mm')}- </LemonTag>- )}- </header>+ <Link+ to={urls.userInterviewResponse(topicId, encodeURIComponent(identifier))}+ className="block no-underline text-current"+ >+ <div className="p-3 hover:bg-bg-light transition-colors">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <div className="font-medium text-sm">{identifier}</div>+ </div>+ <div className="flex items-center gap-2">+ {hasResponded ? (+ <LemonTag type="success" icon={<IconCheck />}>+ Responded+ </LemonTag>+ ) : (+ <LemonTag type="default" icon={<IconClock />}>+ Awaiting+ </LemonTag>+ )}+ <IconChevronRight className="text-muted" />+ </div>+ </div>+ </div>+ </Link>)}diff --git a/products/user_interviews/frontend/UserInterviewResponse.tsx b/products/user_interviews/frontend/UserInterviewResponse.tsxnew file mode 100644index 000000000000..b27f61c72cb3--- /dev/null+++ b/products/user_interviews/frontend/UserInterviewResponse.tsx@@ -0,0 +1,206 @@+import { useEffect, useState } from 'react'++import { IconArrowLeft, IconCalendar, IconPerson, IconSend } from '@posthog/icons'+import { LemonButton, LemonSkeleton, LemonTag, LemonWidget } from '@posthog/lemon-ui'++import api from 'lib/api'+import { NotFound } from 'lib/components/NotFound'+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'+import { PersonDisplay } from 'scenes/persons/PersonDisplay'+import { SceneExport } from 'scenes/sceneTypes'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { PersonType } from '~/types'++import { userInterviewTopicsRetrieve, userInterviewTopicsIntervieweesList, userInterviewsList } from './generated/api'+import type { UserInterviewTopicApi, IntervieweeContextApi, UserInterviewApi } from './generated/api.schemas'++export interface UserInterviewResponseProps {+ topicId: string+ responseId: string+}++export const scene: SceneExport<UserInterviewResponseProps> = {+ component: UserInterviewResponse,+ paramsToProps: ({ params: { topicId, responseId } }) => ({ topicId, responseId }),+}++export function UserInterviewResponse({ topicId, responseId }: UserInterviewResponseProps): JSX.Element {+ const identifier = decodeURIComponent(responseId)+ const [loading, setLoading] = useState(true)+ const [topic, setTopic] = useState<UserInterviewTopicApi | null>(null)+ const [intervieweeContext, setIntervieweeContext] = useState<IntervieweeContextApi | null>(null)+ const [interview, setInterview] = useState<UserInterviewApi | null>(null)+ const [person, setPerson] = useState<PersonType | null>(null)++ useEffect(() => {+ const projectId = String(teamLogic.values.currentTeamId)++ async function load(): Promise<void> {+ setLoading(true)+ try {+ const [topicData, intervieweesData, interviewsData] = await Promise.all([+ userInterviewTopicsRetrieve(projectId, topicId),+ userInterviewTopicsIntervieweesList(projectId, topicId),+ userInterviewsList(projectId),+ ])+ setTopic(topicData)+ const ctx = intervieweesData.results.find((c) => c.interviewee_identifier === identifier)+ setIntervieweeContext(ctx || null)+ const matchingInterviews = interviewsData.results.filter(+ (i) => i.topic === topicId && i.interviewee_identifier === identifier+ )+ // Prefer the interview that has a transcript+ const matchingInterview = matchingInterviews.find((i) => i.transcript) || matchingInterviews[0] || null+ setInterview(matchingInterview)++ // Look up person by email/distinct_id+ try {+ const personResponse = await api.persons.list({ search: identifier })+ if (personResponse.results.length > 0) {+ setPerson(personResponse.results[0])+ }+ } catch {+ // Person lookup is best-effort+ }+ } catch {+ setTopic(null)+ } finally {+ setLoading(false)+ }+ }++ void load()+ }, [topicId, identifier])++ if (loading) {+ return (+ <SceneContent>+ <div className="space-y-4">+ <LemonSkeleton.Text className="h-8 w-[40%]" />+ <LemonSkeleton.Text className="h-4 w-[30%]" />+ <LemonSkeleton className="h-48" />+ </div>+ </SceneContent>+ )+ }++ if (!topic) {+ return <NotFound object="interview response" />+ }++ const hasResponse = !!(interview?.transcript || interview?.summary)+ const displayName = person?.properties?.name || person?.properties?.email || person?.name || identifier++ return (+ <SceneContent>+ <LemonButton+ type="tertiary"+ size="small"+ icon={<IconArrowLeft />}+ to={urls.userInterview(topicId)}+ className="mb-1 -ml-2"+ >+ All responses+ </LemonButton>+ <SceneTitleSection name={displayName} description={topic.topic} resourceType={{ type: 'user_interview' }} />++ <div className="grid grid-cols-1 gap-4 @container @4xl:grid-cols-3">+ {/* Left column — transcript + summary */}+ <div className="col-span-2 flex flex-col gap-4">+ {interview?.summary && (+ <LemonWidget title="Summary">+ <div className="p-4">+ <LemonMarkdown className="text-sm">{interview.summary}</LemonMarkdown>+ </div>+ </LemonWidget>+ )}++ <LemonWidget title="Transcript">+ {interview?.transcript ? (+ <div className="p-4">+ <LemonMarkdown className="text-sm leading-relaxed">+ {interview.transcript}+ </LemonMarkdown>+ </div>+ ) : (+ <div className="p-4 text-muted text-center">+ No transcript available yet. The interview may not have been completed.+ </div>+ )}+ </LemonWidget>+ </div>++ {/* Right column — metadata */}+ <div className="col-span-1 flex flex-col gap-4">+ {/* Person card */}+ <LemonWidget title="Person">+ <div className="p-4 space-y-3">+ {person ? (+ <>+ <PersonDisplay person={person} withIcon />+ <div className="space-y-2 mt-2">+ {person.properties?.email && (+ <div className="flex items-center gap-2">+ <IconSend className="text-muted shrink-0" />+ <span className="text-sm">{person.properties.email}</span>+ </div>+ )}+ {person.created_at && (+ <div className="flex items-center gap-2">+ <IconCalendar className="text-muted shrink-0" />+ <span className="text-sm">+ First seen {person.created_at.split('T')[0]}+ </span>+ </div>+ )}+ </div>+ </>+ ) : (+ <div className="flex items-center gap-2">+ <IconPerson className="text-muted" />+ <span className="font-medium">{identifier}</span>+ </div>+ )}+ <div>+ <LemonTag type={hasResponse ? 'success' : 'default'}>+ {hasResponse ? 'Responded' : 'Awaiting response'}+ </LemonTag>+ </div>+ </div>+ </LemonWidget>++ {intervieweeContext && (+ <LemonWidget title="Interviewee context">+ <div className="p-4">+ <p className="text-sm mb-0">{intervieweeContext.agent_context}</p>+ </div>+ </LemonWidget>+ )}++ <LemonWidget title="Topic details">+ <div className="p-4 space-y-2">+ <DetailRow label="Topic" value={topic.topic} />+ <DetailRow label="Created" value={topic.created_at.split('T')[0]} />+ {topic.interviewee_cohort != null && (+ <DetailRow label="Cohort" value={`#${topic.interviewee_cohort}`} />+ )}+ </div>+ </LemonWidget>+ </div>+ </div>+ </SceneContent>+ )+}++function DetailRow({ label, value }: { label: string; value: string }): JSX.Element {+ return (+ <div className="flex justify-between gap-2">+ <span className="text-muted text-sm shrink-0">{label}</span>+ <span className="text-sm font-medium text-right">{value}</span>+ </div>+ )+}diff --git a/products/user_interviews/frontend/UserInterviews.tsx b/products/user_interviews/frontend/UserInterviews.tsxindex 7dfc6302b49a..2493b8848b3c 100644--- a/products/user_interviews/frontend/UserInterviews.tsx+++ b/products/user_interviews/frontend/UserInterviews.tsx@@ -1,85 +1,127 @@import { useActions, useValues } from 'kea'-import { IconDownload } from '@posthog/icons'-import { LemonButton, LemonTable, LemonTableColumn } from '@posthog/lemon-ui'+import { IconSparkles } from '@posthog/icons'+import { LemonButton, LemonTable } from '@posthog/lemon-ui'-import { PhonePairHogs } from 'lib/components/hedgehogs'-import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'-import { createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'-import { MaxTool } from 'scenes/max/MaxTool'import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'-import { userLogic } from 'scenes/userLogic'+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { ProductKey } from '~/queries/schema/schema-general'-import { UserInterviewType } from '~/types'+import { SidePanelTab } from '~/types'+import type { UserInterviewTopicApi } from './generated/api.schemas'import { userInterviewsLogic } from './userInterviewsLogic'export const scene: SceneExport = {component: UserInterviews,logic: userInterviewsLogic,- productKey: ProductKey.USER_INTERVIEWS,}+function targetingLabel(topic: UserInterviewTopicApi): string {+ const emailCount = topic.interviewee_emails?.length || 0+ const distinctIdCount = topic.interviewee_distinct_ids?.length || 0+ const hasCohort = topic.interviewee_cohort != null+ const parts: string[] = []+ if (hasCohort) {+ parts.push(`Cohort #${topic.interviewee_cohort}`)+ }+ if (emailCount > 0) {+ parts.push(`${emailCount} email${emailCount !== 1 ? 's' : ''}`)+ }+ if (distinctIdCount > 0) {+ parts.push(`${distinctIdCount} ID${distinctIdCount !== 1 ? 's' : ''}`)+ }+ return parts.length > 0 ? parts.join(' + ') : 'Not set'+}++const NEW_TOPIC_PROMPT = `!I want to set up a new user research topic. Help me through the process:++1. First, let's figure out what I want to learn — what feature, behavior, or question I want to research.+2. Then, help me identify the right users to interview — find or create a cohort, or I can provide emails.+3. Draft interview questions based on the topic.+4. Set up the outreach workflow to email each user with their unique interview link.+5. Once I confirm, trigger the emails — I'll track responses in User research.++Let's start — ask me what I want to learn about.`+export function UserInterviews(): JSX.Element {- const { userInterviews, userInterviewsLoading } = useValues(userInterviewsLogic)+ const { topics, topicsLoading } = useValues(userInterviewsLogic)+ const { openSidePanel } = useActions(sidePanelStateLogic)- const { updateHasSeenProductIntroFor } = useActions(userLogic)return (<SceneContent><SceneTitleSectionname={sceneConfigurations[Scene.UserInterviews].name}- description={sceneConfigurations[Scene.UserInterviews].description}+ description="Run AI-powered voice research campaigns. Target a cohort, set a topic, and let the AI handle the interviews."resourceType={{type: sceneConfigurations[Scene.UserInterviews].iconType || 'default_icon_type',}}- />- <ProductIntroduction- productName="User interviews"- productKey={ProductKey.USER_INTERVIEWS}- thingName="user interview"- description="Make full use of user interviews by recording them with PostHog."- customHog={PhonePairHogs}- isEmpty={!userInterviewsLoading && userInterviews.length === 0}- actionElementOverride={+ actions={<LemonButtontype="primary"- icon={<IconDownload />}- onClick={() => updateHasSeenProductIntroFor(ProductKey.USER_INTERVIEWS)}- to="https://posthog.com/recorder"- data-attr="install-recorder"+ icon={<IconSparkles />}+ data-attr="new-topic"+ onClick={() => openSidePanel(SidePanelTab.Max, NEW_TOPIC_PROMPT)}>- Install PostHog Recorder+ New topic</LemonButton>}- className="my-0"/>- <MaxTool identifier="analyze_user_interviews" context={{}}>- <LemonTable- loading={userInterviewsLoading}- columns={[- {- title: 'Interviewees',- key: 'interviewees',- render: (_, row) => (- <LemonTableLink- title={row.interviewee_emails.join(', ')}- to={urls.userInterview(row.id)}- />- ),+ <LemonTable+ loading={topicsLoading}+ columns={[+ {+ title: 'Topic',+ key: 'topic',+ render: (_, row: UserInterviewTopicApi) => (+ <LemonTableLink title={row.topic} to={urls.userInterview(row.id)} />+ ),+ },+ {+ title: 'Targeting',+ key: 'targeting',+ render: (_, row: UserInterviewTopicApi) => (+ <span className="text-sm">{targetingLabel(row)}</span>+ ),+ },+ {+ title: 'Questions',+ key: 'questions',+ width: 100,+ render: (_, row: UserInterviewTopicApi) => {+ const count = row.questions?.length || 0+ return (+ <span className="text-muted">+ {count} question{count !== 1 ? 's' : ''}+ </span>+ )},- createdAtColumn() as LemonTableColumn<UserInterviewType, keyof UserInterviewType | undefined>,- createdByColumn() as LemonTableColumn<UserInterviewType, keyof UserInterviewType | undefined>,- ]}- dataSource={userInterviews}- loadingSkeletonRows={5}- />- </MaxTool>+ },+ {+ title: 'Created',+ key: 'created_at',+ render: (_, row: UserInterviewTopicApi) => (+ <span className="text-muted whitespace-nowrap">{row.created_at?.split('T')[0]}</span>+ ),+ sorter: (a, b) => (a.created_at || '').localeCompare(b.created_at || ''),+ },+ {+ title: 'Created by',+ key: 'created_by',+ render: (_, row: UserInterviewTopicApi) => (+ <span>{row.created_by?.first_name || row.created_by?.email || '—'}</span>+ ),+ },+ ]}+ dataSource={topics}+ rowKey="id"+ loadingSkeletonRows={5}+ emptyState="No topics yet. Click 'New topic' to get started with PostHog AI."+ /></SceneContent>)}diff --git a/products/user_interviews/frontend/generated/api.schemas.ts b/products/user_interviews/frontend/generated/api.schemas.tsindex baff648ba0fa..1977b48d4cdb 100644--- a/products/user_interviews/frontend/generated/api.schemas.ts+++ b/products/user_interviews/frontend/generated/api.schemas.ts@@ -113,6 +113,66 @@ export interface PatchedUserInterviewTopicApi {questions?: string[]}+export interface InterviewLinkApi {+ /**+ * The original identifier (email or distinct ID) from the topic targeting.+ * @maxLength 400+ */+ interviewee_identifier: string+ /** Best-effort display name derived from the identifier, used to greet the interviewee. */+ user_name: string+ /** Public, unauthenticated URL the interviewee opens to start the call. Backed by a SharingConfiguration access token. */+ interview_url: string+ /** The merged topic + per-interviewee context the voice agent will see during the call. */+ agent_context: string+}++export interface PaginatedInterviewLinkListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: InterviewLinkApi[]+}++export interface SendInvitesRequestApi {+ /**+ * Override the default email subject line. Defaults to a friendly prompt referencing the topic.+ * @maxLength 200+ */+ subject?: string+ /** Email address replies should go to. Defaults to the topic creator's email if blank. */+ reply_to?: string+ /** If true (default), queue delivery via Celery. If false, send synchronously and surface errors immediately. */+ send_async?: boolean+}++export interface InterviewInviteResultApi {+ /** The original identifier (email or distinct ID) from the topic targeting. */+ interviewee_identifier: string+ /**+ * Email used for delivery. Null when the identifier was not an email (e.g., a distinct ID).+ * @nullable+ */+ email?: string | null+ /** The personalized public interview URL embedded in the email body. */+ interview_url: string+ /** True if an email was queued for delivery. False when the recipient was skipped — see `reason`. */+ sent: boolean+ /** Why the email was skipped (e.g., `not_an_email`, `already_sent`). Empty when sent=true. */+ reason?: string+}++export interface PaginatedInterviewInviteResultListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: InterviewInviteResultApi[]+}+export interface IntervieweeContextApi {readonly id: stringreadonly created_by: UserBasicApi@@ -159,6 +219,9 @@ export interface UserInterviewApi {readonly created_by: UserBasicApireadonly created_at: stringinterviewee_emails?: string[]+ readonly interviewee_identifier: string+ /** @nullable */+ readonly topic: string | nullreadonly transcript: stringsummary?: stringaudio: string@@ -178,6 +241,9 @@ export interface PatchedUserInterviewApi {readonly created_by?: UserBasicApireadonly created_at?: stringinterviewee_emails?: string[]+ readonly interviewee_identifier?: string+ /** @nullable */+ readonly topic?: string | nullreadonly transcript?: stringsummary?: stringaudio?: stringdiff --git a/products/user_interviews/frontend/generated/api.ts b/products/user_interviews/frontend/generated/api.tsindex 2ef9064f8268..ecfb3dadd2ea 100644--- a/products/user_interviews/frontend/generated/api.ts+++ b/products/user_interviews/frontend/generated/api.ts@@ -10,12 +10,15 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'*/import type {IntervieweeContextApi,+ PaginatedInterviewInviteResultListApi,+ PaginatedInterviewLinkListApi,PaginatedIntervieweeContextListApi,PaginatedUserInterviewListApi,PaginatedUserInterviewTopicListApi,PatchedIntervieweeContextApi,PatchedUserInterviewApi,PatchedUserInterviewTopicApi,+ SendInvitesRequestApi,UserInterviewApi,UserInterviewTopicApi,UserInterviewTopicsIntervieweesListParams,@@ -168,6 +171,48 @@ export const userInterviewTopicsDestroy = async (})}+export const getUserInterviewTopicsGenerateLinksCreateUrl = (projectId: string, id: string) => {+ return `/api/environments/${projectId}/user_interview_topics/${id}/generate_links/`+}++/**+ * Generate one public interview link per targeted interviewee. Materializes an IntervieweeContext row for every identifier on the topic (without overwriting existing per-person context), and an enabled SharingConfiguration with a unique access token. The URL resolves to the public interview viewer with no PostHog auth required.+ */+export const userInterviewTopicsGenerateLinksCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<PaginatedInterviewLinkListApi> => {+ return apiMutator<PaginatedInterviewLinkListApi>(getUserInterviewTopicsGenerateLinksCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getUserInterviewTopicsSendInvitesCreateUrl = (projectId: string, id: string) => {+ return `/api/environments/${projectId}/user_interview_topics/${id}/send_invites/`+}++/**+ * Generate (if needed) and email a personalized public interview link to every targeted interviewee on this topic whose identifier is an email address. Distinct-ID-only interviewees are skipped and surfaced in the response. Each invite is keyed on the underlying SharingConfiguration so re-runs after token rotation produce a fresh send.+ */+export const userInterviewTopicsSendInvitesCreate = async (+ projectId: string,+ id: string,+ sendInvitesRequestApi?: SendInvitesRequestApi,+ options?: RequestInit+): Promise<PaginatedInterviewInviteResultListApi> => {+ return apiMutator<PaginatedInterviewInviteResultListApi>(+ getUserInterviewTopicsSendInvitesCreateUrl(projectId, id),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(sendInvitesRequestApi),+ }+ )+}+export const getUserInterviewTopicsIntervieweesListUrl = (projectId: string,topicId: string,diff --git a/products/user_interviews/frontend/generated/api.zod.ts b/products/user_interviews/frontend/generated/api.zod.tsindex 9c9a8223db14..db7335b1923d 100644--- a/products/user_interviews/frontend/generated/api.zod.ts+++ b/products/user_interviews/frontend/generated/api.zod.ts@@ -114,6 +114,31 @@ export const UserInterviewTopicsPartialUpdateBody = /* @__PURE__ */ zod.object({.describe('Ordered list of questions the voice agent should work through during the interview.'),})+/**+ * Generate (if needed) and email a personalized public interview link to every targeted interviewee on this topic whose identifier is an email address. Distinct-ID-only interviewees are skipped and surfaced in the response. Each invite is keyed on the underlying SharingConfiguration so re-runs after token rotation produce a fresh send.+ */+export const userInterviewTopicsSendInvitesCreateBodySubjectMax = 200++export const userInterviewTopicsSendInvitesCreateBodySendAsyncDefault = true++export const UserInterviewTopicsSendInvitesCreateBody = /* @__PURE__ */ zod.object({+ subject: zod+ .string()+ .max(userInterviewTopicsSendInvitesCreateBodySubjectMax)+ .optional()+ .describe('Override the default email subject line. Defaults to a friendly prompt referencing the topic.'),+ reply_to: zod+ .email()+ .optional()+ .describe("Email address replies should go to. Defaults to the topic creator's email if blank."),+ send_async: zod+ .boolean()+ .default(userInterviewTopicsSendInvitesCreateBodySendAsyncDefault)+ .describe(+ 'If true (default), queue delivery via Celery. If false, send synchronously and surface errors immediately.'+ ),+})+/*** Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).*/diff --git a/products/user_interviews/frontend/userInterviewLogic.ts b/products/user_interviews/frontend/userInterviewLogic.tsindex 6b1ddbefb42b..05e19ca5a5f6 100644--- a/products/user_interviews/frontend/userInterviewLogic.ts+++ b/products/user_interviews/frontend/userInterviewLogic.ts@@ -1,13 +1,14 @@import { afterMount, kea, key, path, props, selectors } from 'kea'import { loaders } from 'kea-loaders'-import api from 'lib/api'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import { Breadcrumb, UserInterviewType } from '~/types'+import { Breadcrumb } from '~/types'+import { userInterviewTopicsRetrieve, userInterviewTopicsIntervieweesList, userInterviewsList } from './generated/api'+import type { UserInterviewTopicApi, IntervieweeContextApi, UserInterviewApi } from './generated/api.schemas'import type { userInterviewLogicType } from './userInterviewLogicType'-import { userInterviewsLogic } from './userInterviewsLogic'export interface UserInterviewLogicProps {id: string@@ -18,45 +19,99 @@ export const userInterviewLogic = kea<userInterviewLogicType>([props({} as UserInterviewLogicProps),key((props) => props.id),loaders(({ props }) => ({- userInterview: [- userInterviewsLogic.findMounted()?.values.userInterviews.find((interview) => interview.id === props.id) ||- null,- {- loadUserInterview: async (id: string): Promise<UserInterviewType | null> => {- try {- return await api.userInterviews.get(id)- } catch {- return null- }- },- updateUserInterview: async (data: { summary: string }): Promise<UserInterviewType> => {- return await api.userInterviews.update(props.id, data)- },+ topic: {+ __default: null as UserInterviewTopicApi | null,+ loadTopic: async () => {+ const projectId = String(teamLogic.values.currentTeamId)+ try {+ return await userInterviewTopicsRetrieve(projectId, props.id)+ } catch {+ return null+ }},- ],+ },+ interviewees: {+ __default: [] as IntervieweeContextApi[],+ loadInterviewees: async () => {+ const projectId = String(teamLogic.values.currentTeamId)+ try {+ const response = await userInterviewTopicsIntervieweesList(projectId, props.id)+ return response.results+ } catch {+ return []+ }+ },+ },+ interviews: {+ __default: [] as UserInterviewApi[],+ loadInterviews: async () => {+ const projectId = String(teamLogic.values.currentTeamId)+ try {+ const response = await userInterviewsList(projectId)+ return response.results+ } catch {+ return []+ }+ },+ },})),selectors(({ props }) => ({+ topicInterviews: [+ (s) => [s.interviews],+ (interviews): UserInterviewApi[] => interviews.filter((i) => i.topic === props.id),+ ],+ respondedIdentifiers: [+ (s) => [s.topicInterviews],+ (interviews): Set<string> => {+ const responded = new Set<string>()+ for (const interview of interviews) {+ if (interview.transcript || interview.summary) {+ if (interview.interviewee_identifier) {+ responded.add(interview.interviewee_identifier)+ }+ }+ }+ return responded+ },+ ],+ respondedCount: [+ (s) => [s.topic, s.respondedIdentifiers],+ (topic, respondedIdentifiers): number => {+ const allTargeted = [...(topic?.interviewee_emails || []), ...(topic?.interviewee_distinct_ids || [])]+ return allTargeted.filter((id) => respondedIdentifiers.has(id)).length+ },+ ],+ totalTargeted: [+ (s) => [s.topic],+ (topic): number =>+ (topic?.interviewee_emails?.length || 0) + (topic?.interviewee_distinct_ids?.length || 0),+ ],+ responseRate: [+ (s) => [s.respondedCount, s.totalTargeted],+ (respondedCount, totalTargeted): number =>+ totalTargeted > 0 ? Math.round((respondedCount / totalTargeted) * 100) : 0,+ ],breadcrumbs: [- (s) => [s.userInterview],- (userInterview): Breadcrumb[] => [+ (s) => [s.topic],+ (topic): Breadcrumb[] => [{key: 'UserInterviews',- name: 'User interviews',+ name: 'User research',path: urls.userInterviews(),iconType: 'user_interview',},{key: props.id,- name: userInterview?.interviewee_emails?.join(', '),+ name: topic?.topic || props.id,path: urls.userInterview(props.id),iconType: 'user_interview',},],],})),- afterMount(({ actions, props }) => {- if (props.id) {- actions.loadUserInterview(props.id)- }+ afterMount(({ actions }) => {+ actions.loadTopic()+ actions.loadInterviewees()+ actions.loadInterviews()}),])diff --git a/products/user_interviews/frontend/userInterviewsLogic.ts b/products/user_interviews/frontend/userInterviewsLogic.tsindex ff5ee36d9176..f605e90b0959 100644--- a/products/user_interviews/frontend/userInterviewsLogic.ts+++ b/products/user_interviews/frontend/userInterviewsLogic.ts@@ -1,20 +1,23 @@import { afterMount, kea, path, selectors } from 'kea'import { loaders } from 'kea-loaders'-import api from 'lib/api'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'-import { Breadcrumb, UserInterviewType } from '~/types'+import { Breadcrumb } from '~/types'+import { userInterviewTopicsList } from './generated/api'+import type { UserInterviewTopicApi } from './generated/api.schemas'import type { userInterviewsLogicType } from './userInterviewsLogicType'export const userInterviewsLogic = kea<userInterviewsLogicType>([path(['products', 'user_interviews', 'frontend', 'userInterviewsLogic']),loaders({- userInterviews: {- __default: [] as UserInterviewType[],- loadUserInterviews: async () => {- const response = await api.userInterviews.list()+ topics: {+ __default: [] as UserInterviewTopicApi[],+ loadTopics: async () => {+ const projectId = String(teamLogic.values.currentTeamId)+ const response = await userInterviewTopicsList(projectId)return response.results},},@@ -25,7 +28,7 @@ export const userInterviewsLogic = kea<userInterviewsLogicType>([(): Breadcrumb[] => [{key: 'UserInterviews',- name: 'User interviews',+ name: 'User research',path: urls.userInterviews(),iconType: 'user_interview',},@@ -33,6 +36,6 @@ export const userInterviewsLogic = kea<userInterviewsLogicType>([],}),afterMount(({ actions }) => {- actions.loadUserInterviews()+ actions.loadTopics()}),])diff --git a/products/user_interviews/manifest.tsx b/products/user_interviews/manifest.tsxindex 3b70ceef9ec0..d8fe7b24a8f5 100644--- a/products/user_interviews/manifest.tsx+++ b/products/user_interviews/manifest.tsx@@ -6,34 +6,46 @@ import { ProductItemCategory, ProductKey } from '~/queries/schema/schema-generalimport { FileSystemIconColor, ProductManifest } from '../../frontend/src/types'export const manifest: ProductManifest = {- name: 'User interviews',+ name: 'User research',scenes: {UserInterviews: {- name: 'User interviews',+ name: 'User research',import: () => import('./frontend/UserInterviews'),projectBased: true,activityScope: 'UserInterview',- description: 'Record and analyze user interviews with PostHog.',+ description: 'Run AI-powered voice research campaigns to gather user insights at scale.',iconType: 'user_interview',},UserInterview: {- name: 'User interview',+ name: 'Interview topic',import: () => import('./frontend/UserInterview'),projectBased: true,activityScope: 'UserInterview',},+ UserInterviewResponse: {+ name: 'Interview response',+ import: () => import('./frontend/UserInterviewResponse'),+ projectBased: true,+ activityScope: 'UserInterview',+ },},routes: {- '/user_interviews': ['UserInterviews', 'userInterviews'],- '/user_interviews/:id': ['UserInterview', 'userInterview'],+ '/user_research': ['UserInterviews', 'userInterviews'],+ '/user_research/:topicId/response/:responseId': ['UserInterviewResponse', 'userInterviewResponse'],+ '/user_research/:id': ['UserInterview', 'userInterview'],+ },+ redirects: {+ '/user_interviews': '/user_research',},urls: {- userInterviews: (): string => '/user_interviews',- userInterview: (id: string): string => `/user_interviews/${id}`,+ userInterviews: (): string => '/user_research',+ userInterview: (id: string): string => `/user_research/${id}`,+ userInterviewResponse: (topicId: string, responseId: string): string =>+ `/user_research/${topicId}/response/${responseId}`,},fileSystemTypes: {user_interview: {- name: 'User interview',+ name: 'User research',iconType: 'user_interview',href: (ref: string) => urls.userInterview(ref),iconColor: ['var(--color-product-user-interviews-light)'],@@ -43,7 +55,7 @@ export const manifest: ProductManifest = {},treeItemsProducts: [{- path: 'User interviews',+ path: 'User research',intents: [ProductKey.USER_INTERVIEWS],category: ProductItemCategory.UNRELEASED,href: urls.userInterviews(),diff --git a/products/user_interviews/mcp/tools.yaml b/products/user_interviews/mcp/tools.yamlindex a35107ddac90..c3eb0fe092de 100644--- a/products/user_interviews/mcp/tools.yaml+++ b/products/user_interviews/mcp/tools.yaml@@ -37,15 +37,61 @@ tools:user-interview-topics-destroy:operation: user_interview_topics_destroyenabled: false+ user-interview-topics-generate-links:+ operation: user_interview_topics_generate_links_create+ enabled: true+ scopes:+ - user_interview:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Generate public interview links for a topic+ description: >+ Generate one public, unauthenticated interview link per targeted interviewee on a user interview topic. For+ each identifier in the topic's `interviewee_emails` and `interviewee_distinct_ids`, materializes (or reuses)+ an IntervieweeContext row and an enabled SharingConfiguration, and returns the merged voice-agent context+ alongside the URL the interviewee should open. The URL hosts the call publicly — no PostHog login required.+ Calling this multiple times is safe: existing share links are reused.+ feature_flag: user-interviewsuser-interview-topics-interviewees-create:operation: user_interview_topics_interviewees_create- enabled: false+ enabled: true+ scopes:+ - user_interview:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Add per-interviewee context to a topic+ description: >+ Attach extra context for a single interviewee on a user interview topic. Use this to give the voice agent+ background it should know about this specific person — e.g. "uses the replay product but has never used+ summarization". `interviewee_identifier` is the email or PostHog distinct ID matching one of the entries in+ the parent topic's targeting fields. `agent_context` is free text. At most one row per (topic,+ interviewee_identifier) — calling create twice for the same pair will conflict.+ include_params:+ - interviewee_identifier+ - agent_context+ feature_flag: user-interviewsuser-interview-topics-interviewees-destroy:operation: user_interview_topics_interviewees_destroyenabled: falseuser-interview-topics-interviewees-list:operation: user_interview_topics_interviewees_list- enabled: false+ enabled: true+ scopes:+ - user_interview:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List per-interviewee contexts for a topic+ description: >+ List the per-interviewee context rows attached to a single user interview topic. Each row is+ (interviewee_identifier, agent_context). Use this to see who has extra context attached before adding more.+ feature_flag: user-interviewsuser-interview-topics-interviewees-partial-update:operation: user_interview_topics_interviewees_partial_updateenabled: false@@ -78,6 +124,27 @@ tools:user-interview-topics-retrieve:operation: user_interview_topics_retrieveenabled: false+ user-interview-topics-send-invites:+ operation: user_interview_topics_send_invites_create+ enabled: true+ scopes:+ - user_interview:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ title: Email interview invites to every targeted interviewee+ description: >+ Generate (if not yet created) and email a personalized public interview link to every targeted interviewee+ on a user interview topic whose identifier is an email address. The email includes a friendly greeting and a+ button linking to the public voice-interview page. Distinct-ID-only interviewees are skipped and surfaced in+ the response. Use this once a topic is finalized; safe to call repeatedly — invites are deduplicated per+ share via the messaging system's idempotency record, and a token rotation produces a fresh send key.+ include_params:+ - subject+ - reply_to+ - send_async+ feature_flag: user-interviewsuser-interview-topics-update:operation: user_interview_topics_updateenabled: falsediff --git a/products/user_interviews/package.json b/products/user_interviews/package.jsonindex a80868c2033a..3830eb924dc0 100644--- a/products/user_interviews/package.json+++ b/products/user_interviews/package.json@@ -1,7 +1,7 @@{"name": "@posthog/products-user-interviews","scripts": {- "backend:test": "echo 'No backend tests'"+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},"dependencies": {"kea": "catalog:",diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex ad6fa6dbb2ed..7da79cf19693 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4758,6 +4758,54 @@},"feature_flag": "user-interviews"},+ "user-interview-topics-generate-links": {+ "description": "Generate one public, unauthenticated interview link per targeted interviewee on a user interview topic. For each identifier in the topic's `interviewee_emails` and `interviewee_distinct_ids`, materializes (or reuses) an IntervieweeContext row and an enabled SharingConfiguration, and returns the merged voice-agent context alongside the URL the interviewee should open. The URL hosts the call publicly — no PostHog login required. Calling this multiple times is safe: existing share links are reused.",+ "category": "User interview topics",+ "feature": "user_interviews",+ "summary": "Generate public interview links for a topic",+ "title": "Generate public interview links for a topic",+ "required_scopes": ["user_interview:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "user-interviews"+ },+ "user-interview-topics-interviewees-create": {+ "description": "Attach extra context for a single interviewee on a user interview topic. Use this to give the voice agent background it should know about this specific person — e.g. \"uses the replay product but has never used summarization\". `interviewee_identifier` is the email or PostHog distinct ID matching one of the entries in the parent topic's targeting fields. `agent_context` is free text. At most one row per (topic, interviewee_identifier) — calling create twice for the same pair will conflict.",+ "category": "User interview topics",+ "feature": "user_interviews",+ "summary": "Add per-interviewee context to a topic",+ "title": "Add per-interviewee context to a topic",+ "required_scopes": ["user_interview:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "user-interviews"+ },+ "user-interview-topics-interviewees-list": {+ "description": "List the per-interviewee context rows attached to a single user interview topic. Each row is (interviewee_identifier, agent_context). Use this to see who has extra context attached before adding more.",+ "category": "User interview topics",+ "feature": "user_interviews",+ "summary": "List per-interviewee contexts for a topic",+ "title": "List per-interviewee contexts for a topic",+ "required_scopes": ["user_interview:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "user-interviews"+ },"user-interview-topics-list": {"description": "List planned user interview topics in the current project, newest first. Each result includes the topic, targeting (interviewee_cohort, interviewee_emails, interviewee_distinct_ids), and the voice agent setup (agent_context, questions). Supports `search` for substring match against the topic, and `limit`/`offset` for pagination.","category": "User interview topics",@@ -4774,6 +4822,22 @@},"feature_flag": "user-interviews"},+ "user-interview-topics-send-invites": {+ "description": "Generate (if not yet created) and email a personalized public interview link to every targeted interviewee on a user interview topic whose identifier is an email address. The email includes a friendly greeting and a button linking to the public voice-interview page. Distinct-ID-only interviewees are skipped and surfaced in the response. Use this once a topic is finalized; safe to call repeatedly — invites are deduplicated per share via the messaging system's idempotency record, and a token rotation produces a fresh send key.",+ "category": "User interview topics",+ "feature": "user_interviews",+ "summary": "Email interview invites to every targeted interviewee",+ "title": "Email interview invites to every targeted interviewee",+ "required_scopes": ["user_interview:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "user-interviews"+ },"user-settings-update": {"description": "Update the authenticated user's profile and settings using PATCH semantics — only the fields included in the request body are changed. Pass `@me` as the UUID; non-staff callers may only update their own account. Use `user-get` first to inspect current settings. `notification_settings` merges key-by-key; changing `email` triggers a verification flow; changing `password` also requires `current_password`. Always confirm changes with the user before applying.","category": "Core",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 8527fd1a384e..34edc49a5f9d 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5239,6 +5239,54 @@},"feature_flag": "user-interviews"},+ "user-interview-topics-generate-links": {+ "description": "Generate one public, unauthenticated interview link per targeted interviewee on a user interview topic. For each identifier in the topic's `interviewee_emails` and `interviewee_distinct_ids`, materializes (or reuses) an IntervieweeContext row and an enabled SharingConfiguration, and returns the merged voice-agent context alongside the URL the interviewee should open. The URL hosts the call publicly — no PostHog login required. Calling this multiple times is safe: existing share links are reused.",+ "category": "User interview topics",+ "feature": "user_interviews",+ "summary": "Generate public interview links for a topic",+ "title": "Generate public interview links for a topic",+ "required_scopes": ["user_interview:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "user-interviews"+ },+ "user-interview-topics-interviewees-create": {+ "description": "Attach extra context for a single interviewee on a user interview topic. Use this to give the voice agent background it should know about this specific person — e.g. \"uses the replay product but has never used summarization\". `interviewee_identifier` is the email or PostHog distinct ID matching one of the entries in the parent topic's targeting fields. `agent_context` is free text. At most one row per (topic, interviewee_identifier) — calling create twice for the same pair will conflict.",+ "category": "User interview topics",+ "feature": "user_interviews",+ "summary": "Add per-interviewee context to a topic",+ "title": "Add per-interviewee context to a topic",+ "required_scopes": ["user_interview:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "user-interviews"+ },+ "user-interview-topics-interviewees-list": {+ "description": "List the per-interviewee context rows attached to a single user interview topic. Each row is (interviewee_identifier, agent_context). Use this to see who has extra context attached before adding more.",+ "category": "User interview topics",+ "feature": "user_interviews",+ "summary": "List per-interviewee contexts for a topic",+ "title": "List per-interviewee contexts for a topic",+ "required_scopes": ["user_interview:read"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "user-interviews"+ },"user-interview-topics-list": {"description": "List planned user interview topics in the current project, newest first. Each result includes the topic, targeting (interviewee_cohort, interviewee_emails, interviewee_distinct_ids), and the voice agent setup (agent_context, questions). Supports `search` for substring match against the topic, and `limit`/`offset` for pagination.","category": "User interview topics",@@ -5255,6 +5303,22 @@},"feature_flag": "user-interviews"},+ "user-interview-topics-send-invites": {+ "description": "Generate (if not yet created) and email a personalized public interview link to every targeted interviewee on a user interview topic whose identifier is an email address. The email includes a friendly greeting and a button linking to the public voice-interview page. Distinct-ID-only interviewees are skipped and surfaced in the response. Use this once a topic is finalized; safe to call repeatedly — invites are deduplicated per share via the messaging system's idempotency record, and a token rotation produces a fresh send key.",+ "category": "User interview topics",+ "feature": "user_interviews",+ "summary": "Email interview invites to every targeted interviewee",+ "title": "Email interview invites to every targeted interviewee",+ "required_scopes": ["user_interview:write"],+ "new_mcp": true,+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "user-interviews"+ },"user-settings-update": {"description": "Update the authenticated user's profile and settings using PATCH semantics — only the fields included in the request body are changed. Pass `@me` as the UUID; non-staff callers may only update their own account. Use `user-get` first to inspect current settings. `notification_settings` merges key-by-key; changing `email` triggers a verification flow; changing `password` also requires `current_password`. Always confirm changes with the user before applying.","category": "Core",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 64685bfba26a..a3591d202e96 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -19112,6 +19112,36 @@ export namespace Schemas {line_refs: string;}+ export interface InterviewInviteResult {+ /** The original identifier (email or distinct ID) from the topic targeting. */+ interviewee_identifier: string;+ /**+ * Email used for delivery. Null when the identifier was not an email (e.g., a distinct ID).+ * @nullable+ */+ email?: string | null;+ /** The personalized public interview URL embedded in the email body. */+ interview_url: string;+ /** True if an email was queued for delivery. False when the recipient was skipped — see `reason`. */+ sent: boolean;+ /** Why the email was skipped (e.g., `not_an_email`, `already_sent`). Empty when sent=true. */+ reason?: string;+ }++ export interface InterviewLink {+ /**+ * The original identifier (email or distinct ID) from the topic targeting.+ * @maxLength 400+ */+ interviewee_identifier: string;+ /** Best-effort display name derived from the identifier, used to greet the interviewee. */+ user_name: string;+ /** Public, unauthenticated URL the interviewee opens to start the call. Backed by a SharingConfiguration access token. */+ interview_url: string;+ /** The merged topic + per-interviewee context the voice agent will see during the call. */+ agent_context: string;+ }+export interface IntervieweeContext {readonly id: string;readonly created_by: UserBasic;@@ -21994,6 +22024,24 @@ export namespace Schemas {results: IntegrationConfig[];}+ export interface PaginatedInterviewInviteResultList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: InterviewInviteResult[];+ }++ export interface PaginatedInterviewLinkList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: InterviewLink[];+ }+export interface PaginatedIntervieweeContextList {count: number;/** @nullable */@@ -24705,6 +24753,9 @@ export namespace Schemas {readonly created_by: UserBasic;readonly created_at: string;interviewee_emails?: string[];+ readonly interviewee_identifier: string;+ /** @nullable */+ readonly topic: string | null;readonly transcript: string;summary?: string;audio: string;@@ -30475,6 +30526,9 @@ export namespace Schemas {readonly created_by?: UserBasic;readonly created_at?: string;interviewee_emails?: string[];+ readonly interviewee_identifier?: string;+ /** @nullable */+ readonly topic?: string | null;readonly transcript?: string;summary?: string;audio?: string;@@ -33747,6 +33801,18 @@ export namespace Schemas {sdks: SdkAssessment[];}+ export interface SendInvitesRequest {+ /**+ * Override the default email subject line. Defaults to a friendly prompt referencing the topic.+ * @maxLength 200+ */+ subject?: string;+ /** Email address replies should go to. Defaults to the topic creator's email if blank. */+ reply_to?: string;+ /** If true (default), queue delivery via Celery. If false, send synchronously and surface errors immediately. */+ send_async?: boolean;+ }+export type SentimentResultScores = {[key: string]: number};export type SentimentResultMessages = {[key: string]: MessageSentiment};diff --git a/services/mcp/src/generated/user_interviews/api.ts b/services/mcp/src/generated/user_interviews/api.tsindex 7e30526d4897..af831b402109 100644--- a/services/mcp/src/generated/user_interviews/api.ts+++ b/services/mcp/src/generated/user_interviews/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 2 enabled ops+ * PostHog API - MCP 6 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -67,3 +67,97 @@ export const UserInterviewTopicsCreateBody = /* @__PURE__ */ zod.object({.optional().describe('Ordered list of questions the voice agent should work through during the interview.'),})++/**+ * Generate one public interview link per targeted interviewee. Materializes an IntervieweeContext row for every identifier on the topic (without overwriting existing per-person context), and an enabled SharingConfiguration with a unique access token. The URL resolves to the public interview viewer with no PostHog auth required.+ */+export const UserInterviewTopicsGenerateLinksCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this user interview topic.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++/**+ * Generate (if needed) and email a personalized public interview link to every targeted interviewee on this topic whose identifier is an email address. Distinct-ID-only interviewees are skipped and surfaced in the response. Each invite is keyed on the underlying SharingConfiguration so re-runs after token rotation produce a fresh send.+ */+export const UserInterviewTopicsSendInvitesCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this user interview topic.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const userInterviewTopicsSendInvitesCreateBodySubjectMax = 200++export const userInterviewTopicsSendInvitesCreateBodySendAsyncDefault = true++export const UserInterviewTopicsSendInvitesCreateBody = /* @__PURE__ */ zod.object({+ subject: zod+ .string()+ .max(userInterviewTopicsSendInvitesCreateBodySubjectMax)+ .optional()+ .describe('Override the default email subject line. Defaults to a friendly prompt referencing the topic.'),+ reply_to: zod+ .email()+ .optional()+ .describe("Email address replies should go to. Defaults to the topic creator's email if blank."),+ send_async: zod+ .boolean()+ .default(userInterviewTopicsSendInvitesCreateBodySendAsyncDefault)+ .describe(+ 'If true (default), queue delivery via Celery. If false, send synchronously and surface errors immediately.'+ ),+})++/**+ * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).+ */+export const UserInterviewTopicsIntervieweesListParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+ topic_id: zod.string(),+})++export const UserInterviewTopicsIntervieweesListQueryParams = /* @__PURE__ */ zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})++/**+ * Per-interviewee extra context for a user interview topic. At most one row per (topic, interviewee_identifier).+ */+export const UserInterviewTopicsIntervieweesCreateParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+ topic_id: zod.string(),+})++export const userInterviewTopicsIntervieweesCreateBodyIntervieweeIdentifierMax = 400++export const userInterviewTopicsIntervieweesCreateBodyAgentContextMax = 10000++export const UserInterviewTopicsIntervieweesCreateBody = /* @__PURE__ */ zod.object({+ interviewee_identifier: zod+ .string()+ .max(userInterviewTopicsIntervieweesCreateBodyIntervieweeIdentifierMax)+ .describe(+ "Identifier for the interviewee — typically an email address or PostHog distinct ID. Must match a value in the parent topic's interviewee_emails or interviewee_distinct_ids."+ ),+ agent_context: zod+ .string()+ .max(userInterviewTopicsIntervieweesCreateBodyAgentContextMax)+ .describe(+ "Extra context the voice agent should know about this specific interviewee — e.g. 'uses the replay product but has never used summarization'."+ ),+})diff --git a/services/mcp/src/tools/generated/user_interviews.ts b/services/mcp/src/tools/generated/user_interviews.tsindex c606b13238a8..3094b534316a 100644--- a/services/mcp/src/tools/generated/user_interviews.ts+++ b/services/mcp/src/tools/generated/user_interviews.ts@@ -2,7 +2,17 @@import { z } from 'zod'import type { Schemas } from '@/api/generated'-import { UserInterviewTopicsCreateBody, UserInterviewTopicsListQueryParams } from '@/generated/user_interviews/api'+import {+ UserInterviewTopicsCreateBody,+ UserInterviewTopicsGenerateLinksCreateParams,+ UserInterviewTopicsIntervieweesCreateBody,+ UserInterviewTopicsIntervieweesCreateParams,+ UserInterviewTopicsIntervieweesListParams,+ UserInterviewTopicsIntervieweesListQueryParams,+ UserInterviewTopicsListQueryParams,+ UserInterviewTopicsSendInvitesCreateBody,+ UserInterviewTopicsSendInvitesCreateParams,+} from '@/generated/user_interviews/api'import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'@@ -41,6 +51,76 @@ const userInterviewTopicsCreate = (): ToolBase<typeof UserInterviewTopicsCreateS},})+const UserInterviewTopicsGenerateLinksSchema = UserInterviewTopicsGenerateLinksCreateParams.omit({ project_id: true })++const userInterviewTopicsGenerateLinks = (): ToolBase<+ typeof UserInterviewTopicsGenerateLinksSchema,+ Schemas.PaginatedInterviewLinkList+> => ({+ name: 'user-interview-topics-generate-links',+ schema: UserInterviewTopicsGenerateLinksSchema,+ handler: async (context: Context, params: z.infer<typeof UserInterviewTopicsGenerateLinksSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedInterviewLinkList>({+ method: 'POST',+ path: `/api/environments/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.id))}/generate_links/`,+ })+ return result+ },+})++const UserInterviewTopicsIntervieweesCreateSchema = UserInterviewTopicsIntervieweesCreateParams.omit({+ project_id: true,+}).extend(UserInterviewTopicsIntervieweesCreateBody.shape)++const userInterviewTopicsIntervieweesCreate = (): ToolBase<+ typeof UserInterviewTopicsIntervieweesCreateSchema,+ Schemas.IntervieweeContext+> => ({+ name: 'user-interview-topics-interviewees-create',+ schema: UserInterviewTopicsIntervieweesCreateSchema,+ handler: async (context: Context, params: z.infer<typeof UserInterviewTopicsIntervieweesCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.interviewee_identifier !== undefined) {+ body['interviewee_identifier'] = params.interviewee_identifier+ }+ if (params.agent_context !== undefined) {+ body['agent_context'] = params.agent_context+ }+ const result = await context.api.request<Schemas.IntervieweeContext>({+ method: 'POST',+ path: `/api/environments/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.topic_id))}/interviewees/`,+ body,+ })+ return result+ },+})++const UserInterviewTopicsIntervieweesListSchema = UserInterviewTopicsIntervieweesListParams.omit({+ project_id: true,+}).extend(UserInterviewTopicsIntervieweesListQueryParams.shape)++const userInterviewTopicsIntervieweesList = (): ToolBase<+ typeof UserInterviewTopicsIntervieweesListSchema,+ WithPostHogUrl<Schemas.PaginatedIntervieweeContextList>+> => ({+ name: 'user-interview-topics-interviewees-list',+ schema: UserInterviewTopicsIntervieweesListSchema,+ handler: async (context: Context, params: z.infer<typeof UserInterviewTopicsIntervieweesListSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedIntervieweeContextList>({+ method: 'GET',+ path: `/api/environments/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.topic_id))}/interviewees/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ return await withPostHogUrl(context, result, '/user_interviews')+ },+})+const UserInterviewTopicsListSchema = UserInterviewTopicsListQueryParamsconst userInterviewTopicsList = (): ToolBase<@@ -64,7 +144,42 @@ const userInterviewTopicsList = (): ToolBase<},})+const UserInterviewTopicsSendInvitesSchema = UserInterviewTopicsSendInvitesCreateParams.omit({+ project_id: true,+}).extend(UserInterviewTopicsSendInvitesCreateBody.shape)++const userInterviewTopicsSendInvites = (): ToolBase<+ typeof UserInterviewTopicsSendInvitesSchema,+ Schemas.PaginatedInterviewInviteResultList+> => ({+ name: 'user-interview-topics-send-invites',+ schema: UserInterviewTopicsSendInvitesSchema,+ handler: async (context: Context, params: z.infer<typeof UserInterviewTopicsSendInvitesSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.subject !== undefined) {+ body['subject'] = params.subject+ }+ if (params.reply_to !== undefined) {+ body['reply_to'] = params.reply_to+ }+ if (params.send_async !== undefined) {+ body['send_async'] = params.send_async+ }+ const result = await context.api.request<Schemas.PaginatedInterviewInviteResultList>({+ method: 'POST',+ path: `/api/environments/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.id))}/send_invites/`,+ body,+ })+ return result+ },+})+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'user-interview-topics-create': userInterviewTopicsCreate,+ 'user-interview-topics-generate-links': userInterviewTopicsGenerateLinks,+ 'user-interview-topics-interviewees-create': userInterviewTopicsIntervieweesCreate,+ 'user-interview-topics-interviewees-list': userInterviewTopicsIntervieweesList,'user-interview-topics-list': userInterviewTopicsList,+ 'user-interview-topics-send-invites': userInterviewTopicsSendInvites,}