Skip to content

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

feat(user-interviews): export per-interviewee links as CSV (#59635)

Paul D'Ambra6669d13d53ef
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5ef3ad61f4b7..d5c97bccccaf 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4599,7 +4599,7 @@ snapshots:
scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--superwide--light:
hash: v1.k794b7964.26ff36a61a6cfdabfc95e7c45cdcf7d56b98db68e691495b6624afcdf4cd38dd.JlYx2NiLnbrphm6vTNch194or3BgrT-MWgEm8RAjB3o
scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--dark:
- hash: v1.k794b7964.e37d1addf9a1b24963872de93f7ffdd30084f8a3a4c2d8dde83008de73ae7bdd.OfE7OfHSRIRo7NJfsJdlxt9UOoYoB1WHd-JKL97AWNs
+ hash: v1.k794b7964.96dfb8d0732fdfb84d54691e3c857a08e115a28a2e740b63a9b1857f623c0907.nIpZ7yc1ZQ5En6wG3nxXiy8g4K_b7_PVlPg1QTyUQTg
scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--light:
hash: v1.k794b7964.1a564a7e326dd6ce74422aeec8cc336763529a54aac381e2c3039c950f73e0b9.pQOeGG7_eD40sEsh7BApyC7wiUAQx9-TXPHrzC_seWI
scenes-app-insights-funnels--funnel-time-to-convert--dark:
diff --git a/products/user_interviews/backend/presentation/views.py b/products/user_interviews/backend/presentation/views.py
index 27d99a98a6f0..426e72813efd 100644
--- a/products/user_interviews/backend/presentation/views.py
+++ b/products/user_interviews/backend/presentation/views.py
@@ -10,18 +10,22 @@ from django.core.files import File
from django.db import models, transaction
from django.db.models import QuerySet
from django.utils import timezone
+from django.utils.text import slugify
import structlog
import posthoganalytics
import posthoganalytics.ai.openai
from django_filters.rest_framework import DjangoFilterBackend
+from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiResponse, extend_schema
from elevenlabs import ElevenLabs
from posthoganalytics.ai.openai import OpenAI
from rest_framework import filters, response, serializers, status, viewsets
from rest_framework.decorators import action
+from rest_framework.exceptions import ValidationError
from rest_framework.parsers import JSONParser, MultiPartParser
from rest_framework.request import Request
+from rest_framework_csv import renderers as csvrenderers
from posthog.schema import EmbeddingModelName, ProductKey
@@ -37,6 +41,7 @@ from posthog.email import EmailMessage, is_email_available
from posthog.models.sharing_configuration import SharingConfiguration
from posthog.models.user import User
from posthog.permissions import PostHogFeatureFlagPermission
+from posthog.tasks.exports.csv_exporter import _sanitize_formula_injection
from posthog.utils import absolute_uri
from ..facade.api import parse_interviewee_identifier
@@ -48,6 +53,12 @@ logger = structlog.get_logger(__name__)
elevenlabs_client = ElevenLabs()
+class _InterviewLinksCSVRenderer(csvrenderers.CSVRenderer):
+ """Lock the CSV column order for interview-links exports."""
+
+ header = ["interviewee_identifier", "interviewee_email", "user_name", "interview_url"]
+
+
class UserInterviewSerializer(serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
audio = serializers.FileField(write_only=True)
@@ -725,6 +736,7 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"patch",
"destroy",
"generate_links",
+ "links_csv",
"send_invites",
"add_interviewee",
"remove_interviewee",
@@ -774,6 +786,58 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
]
return response.Response(InterviewLinkSerializer(payload, many=True).data)
+ @extend_schema(
+ request=None,
+ responses={
+ (200, "text/csv"): OpenApiResponse(
+ response=OpenApiTypes.BINARY,
+ description=(
+ "CSV with columns: interviewee_identifier, interviewee_email, user_name, interview_url. "
+ "One row per targeted interviewee."
+ ),
+ )
+ },
+ description=(
+ "Same materialization as generate_links, returned as a downloadable CSV. "
+ "Intended for users who want to mail-merge the per-person interview links "
+ "into their own email tooling."
+ ),
+ )
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="links_csv",
+ renderer_classes=[_InterviewLinksCSVRenderer],
+ )
+ def links_csv(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:
+ raise ValidationError(
+ {
+ "error": (
+ "Topic has no interviewee_emails or interviewee_distinct_ids set. "
+ "Add them before generating links."
+ )
+ }
+ )
+
+ rows = [
+ {
+ "interviewee_identifier": _sanitize_formula_injection(r["identifier"]),
+ "interviewee_email": _sanitize_formula_injection(r["email"] or ""),
+ "user_name": _sanitize_formula_injection(r["user_name"]),
+ "interview_url": _sanitize_formula_injection(r["interview_url"]),
+ }
+ for r in results
+ ]
+ filename = f"{slugify(topic.topic or 'user-interview')}-links.csv"
+ return response.Response(
+ rows,
+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},
+ )
+
@extend_schema(
request=SendInvitesRequestSerializer,
responses={200: OpenApiResponse(response=InterviewInviteResultSerializer(many=True))},
diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.py
index 7d791deb5753..fe4ae348c528 100644
--- a/products/user_interviews/backend/test_interview_sharing.py
+++ b/products/user_interviews/backend/test_interview_sharing.py
@@ -1,3 +1,5 @@
+import io
+import csv
import hmac
import json
import hashlib
@@ -107,6 +109,63 @@ class TestGenerateInterviewLinks(_FeatureFlagEnabledMixin):
response = self.client.post(self._generate_links_url(str(topic.id)))
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ def _generate_links_csv_url(self, topic_id: str) -> str:
+ return f"/api/environments/{self.team.id}/user_interview_topics/{topic_id}/links_csv/"
+
+ def test_generate_links_csv_returns_csv_with_expected_columns_and_rows(self):
+ topic = self._create_topic()
+
+ response = self.client.post(self._generate_links_csv_url(str(topic.id)))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertTrue(response["Content-Type"].startswith("text/csv"))
+ self.assertIn("attachment", response["Content-Disposition"])
+ self.assertIn(".csv", response["Content-Disposition"])
+
+ reader = csv.DictReader(io.StringIO(response.content.decode("utf-8")))
+ self.assertEqual(
+ reader.fieldnames,
+ ["interviewee_identifier", "interviewee_email", "user_name", "interview_url"],
+ )
+ rows = list(reader)
+ # One row per targeted interviewee (3 in the default _create_topic).
+ self.assertEqual(len(rows), 3)
+ # Email column is empty for distinct-id-only rows; URL column always populated.
+ for row in rows:
+ self.assertIn("/interview/", row["interview_url"])
+
+ def test_generate_links_csv_rejects_topic_with_no_identifiers(self):
+ topic = self._create_topic(interviewee_emails=[], interviewee_distinct_ids=[])
+ response = self.client.post(self._generate_links_csv_url(str(topic.id)))
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_generate_links_csv_sanitizes_formula_injection_without_breaking_emails(self):
+ topic = self._create_topic(
+ interviewee_emails=["[email protected]"],
+ # Deliberately craft a malicious distinct ID starting with `=` — must be quoted.
+ interviewee_distinct_ids=["=cmd|/c calc!A1"],
+ )
+ response = self.client.post(self._generate_links_csv_url(str(topic.id)))
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+
+ body = response.content.decode("utf-8")
+ # Plain email is untouched (first char is a letter, not a formula trigger).
+ self.assertIn("[email protected]", body)
+ self.assertNotIn("'[email protected]", body)
+ # Formula-injection identifier is prefixed with a single quote.
+ self.assertIn("'=cmd|/c calc!A1", body)
+
+ def test_generate_links_csv_is_idempotent_with_existing_links(self):
+ topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])
+ # Materialize via the JSON endpoint first; the CSV endpoint must return the same access token.
+ json_body = self.client.post(self._generate_links_url(str(topic.id))).json()
+ expected_url = json_body[0]["interview_url"]
+
+ csv_response = self.client.post(self._generate_links_csv_url(str(topic.id)))
+ self.assertEqual(csv_response.status_code, status.HTTP_200_OK)
+ self.assertIn(expected_url, csv_response.content.decode("utf-8"))
+ self.assertEqual(SharingConfiguration.objects.filter(interviewee_context__topic=topic).count(), 1)
+
class TestUserInterviewTopicCreate(_FeatureFlagEnabledMixin):
def _url(self) -> str:
diff --git a/products/user_interviews/frontend/UserInterview.tsx b/products/user_interviews/frontend/UserInterview.tsx
index 0a2b5c8ad699..57ead3c6962f 100644
--- a/products/user_interviews/frontend/UserInterview.tsx
+++ b/products/user_interviews/frontend/UserInterview.tsx
@@ -1,6 +1,6 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
-import { IconArrowLeft, IconCheck, IconChevronRight, IconClock } from '@posthog/icons'
+import { IconArrowLeft, IconCheck, IconChevronRight, IconClock, IconDownload } from '@posthog/icons'
import { LemonButton, LemonSkeleton, LemonTag, LemonWidget } from '@posthog/lemon-ui'
import { NotFound } from 'lib/components/NotFound'
@@ -44,7 +44,9 @@ export function UserInterview({ id }: UserInterviewLogicProps): JSX.Element {
respondedCount,
totalTargeted,
responseRate,
+ linksCsvExporting,
} = useValues(userInterviewLogic)
+ const { exportLinksCsv } = useActions(userInterviewLogic)
if (topicLoading && !topic) {
return (
@@ -74,7 +76,7 @@ export function UserInterview({ id }: UserInterviewLogicProps): JSX.Element {
return (
<SceneContent>
{/* Header */}
- <div className="flex items-start justify-between mb-4">
+ <div className="flex items-start justify-between mb-4 gap-4">
<div>
<LemonButton
type="tertiary"
@@ -88,6 +90,21 @@ export function UserInterview({ id }: UserInterviewLogicProps): JSX.Element {
<h1 className="text-2xl font-bold mb-1">{topic.topic}</h1>
{topic.agent_context && <p className="text-muted mb-0 text-sm">{topic.agent_context}</p>}
</div>
+ <div className="shrink-0">
+ <LemonButton
+ type="secondary"
+ icon={<IconDownload />}
+ onClick={exportLinksCsv}
+ loading={linksCsvExporting}
+ disabledReason={
+ totalTargeted === 0 ? 'Add interviewees to the topic before exporting links' : undefined
+ }
+ data-attr="export-interview-links-csv"
+ tooltip="Download a CSV with each interviewee's personal interview link, for use in your own email tooling"
+ >
+ Export links (CSV)
+ </LemonButton>
+ </div>
</div>
<div className="grid grid-cols-1 gap-4 @container @4xl:grid-cols-3">
diff --git a/products/user_interviews/frontend/generated/api.ts b/products/user_interviews/frontend/generated/api.ts
index a98fa7d54f62..2530e05b9ace 100644
--- a/products/user_interviews/frontend/generated/api.ts
+++ b/products/user_interviews/frontend/generated/api.ts
@@ -215,6 +215,24 @@ export const userInterviewTopicsGenerateLinksCreate = async (
})
}
+export const getUserInterviewTopicsLinksCsvCreateUrl = (projectId: string, id: string) => {
+ return `/api/environments/${projectId}/user_interview_topics/${id}/links_csv/`
+}
+
+/**
+ * Same materialization as generate_links, returned as a downloadable CSV. Intended for users who want to mail-merge the per-person interview links into their own email tooling.
+ */
+export const userInterviewTopicsLinksCsvCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<Blob> => {
+ return apiMutator<Blob>(getUserInterviewTopicsLinksCsvCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getUserInterviewTopicsRemoveIntervieweeCreateUrl = (projectId: string, id: string) => {
return `/api/environments/${projectId}/user_interview_topics/${id}/remove_interviewee/`
}
diff --git a/products/user_interviews/frontend/userInterviewLogic.ts b/products/user_interviews/frontend/userInterviewLogic.ts
index 718d302b8134..6e6de03fe2e0 100644
--- a/products/user_interviews/frontend/userInterviewLogic.ts
+++ b/products/user_interviews/frontend/userInterviewLogic.ts
@@ -1,12 +1,16 @@
-import { afterMount, kea, key, path, props, reducers, selectors } from 'kea'
+import { actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { lemonToast } from '@posthog/lemon-ui'
+
+import api from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { Breadcrumb } from '~/types'
import {
+ getUserInterviewTopicsLinksCsvCreateUrl,
userInterviewTopicsGenerateLinksCreate,
userInterviewTopicsIntervieweesList,
userInterviewTopicsRetrieve,
@@ -82,6 +86,10 @@ export const userInterviewLogic = kea<userInterviewLogicType>([
},
},
})),
+ actions({
+ exportLinksCsv: true,
+ exportLinksCsvDone: true,
+ }),
reducers({
linksLoadFailed: [
false,
@@ -90,7 +98,41 @@ export const userInterviewLogic = kea<userInterviewLogicType>([
loadLinksFailure: () => true,
},
],
+ linksCsvExporting: [
+ false,
+ {
+ exportLinksCsv: () => true,
+ exportLinksCsvDone: () => false,
+ },
+ ],
}),
+ listeners(({ props, values, actions }) => ({
+ exportLinksCsv: async () => {
+ const projectId = String(teamLogic.values.currentTeamId)
+ try {
+ const response = await api.createResponse(getUserInterviewTopicsLinksCsvCreateUrl(projectId, props.id))
+ if (!response.ok) {
+ throw new Error(`Export failed (${response.status})`)
+ }
+ const blob = await response.blob()
+ const filename = `${(values.topic?.topic || 'user-interview')
+ .replace(/[^\w-]+/g, '-')
+ .toLowerCase()}-links.csv`
+ const url = URL.createObjectURL(blob)
+ const anchor = document.createElement('a')
+ anchor.href = url
+ anchor.download = filename
+ document.body.appendChild(anchor)
+ anchor.click()
+ document.body.removeChild(anchor)
+ URL.revokeObjectURL(url)
+ } catch {
+ lemonToast.error('Could not export interview links as CSV')
+ } finally {
+ actions.exportLinksCsvDone()
+ }
+ },
+ })),
selectors(({ props }) => ({
topicInterviews: [
(s) => [s.interviews],
diff --git a/products/user_interviews/mcp/tools.yaml b/products/user_interviews/mcp/tools.yaml
index 1cb57b22206b..3c76873b41a9 100644
--- a/products/user_interviews/mcp/tools.yaml
+++ b/products/user_interviews/mcp/tools.yaml
@@ -167,6 +167,22 @@ tools:
user-interview-topics-interviewees-update:
operation: user_interview_topics_interviewees_update
enabled: false
+ user-interview-topics-links-csv:
+ operation: user_interview_topics_links_csv_create
+ enabled: true
+ scopes:
+ - user_interview:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Export interview links for a topic as CSV
+ description: >
+ Same materialization as `user-interview-topics-generate-links` but returns the per-interviewee links as a
+ downloadable CSV with columns `interviewee_identifier`, `interviewee_email`, `user_name`, `interview_url`.
+ Use this when the human plans to mail-merge the links into their own email tooling rather than letting
+ PostHog send the invites.
+ feature_flag: user-interviews
user-interview-topics-list:
operation: user_interview_topics_list
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 79fe985f9e3e..4e4b125e4b6a 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -5130,6 +5130,22 @@
},
"feature_flag": "user-interviews"
},
+ "user-interview-topics-links-csv": {
+ "description": "Same materialization as `user-interview-topics-generate-links` but returns the per-interviewee links as a downloadable CSV with columns `interviewee_identifier`, `interviewee_email`, `user_name`, `interview_url`. Use this when the human plans to mail-merge the links into their own email tooling rather than letting PostHog send the invites.",
+ "category": "User interview topics",
+ "feature": "user_interviews",
+ "summary": "Export interview links for a topic as CSV",
+ "title": "Export interview links for a topic as CSV",
+ "required_scopes": ["user_interview:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "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_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",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c79cdbc8a4a4..43ab767310e7 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5611,6 +5611,22 @@
},
"feature_flag": "user-interviews"
},
+ "user-interview-topics-links-csv": {
+ "description": "Same materialization as `user-interview-topics-generate-links` but returns the per-interviewee links as a downloadable CSV with columns `interviewee_identifier`, `interviewee_email`, `user_name`, `interview_url`. Use this when the human plans to mail-merge the links into their own email tooling rather than letting PostHog send the invites.",
+ "category": "User interview topics",
+ "feature": "user_interviews",
+ "summary": "Export interview links for a topic as CSV",
+ "title": "Export interview links for a topic as CSV",
+ "required_scopes": ["user_interview:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "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_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",
diff --git a/services/mcp/src/generated/user_interviews/api.ts b/services/mcp/src/generated/user_interviews/api.ts
index fb98fbecd2c6..0f2589dcc070 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 16 enabled ops
+ * PostHog API - MCP 17 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -143,6 +143,18 @@ export const UserInterviewTopicsGenerateLinksCreateParams = /* @__PURE__ */ zod.
),
})
+/**
+ * Same materialization as generate_links, returned as a downloadable CSV. Intended for users who want to mail-merge the per-person interview links into their own email tooling.
+ */
+export const UserInterviewTopicsLinksCsvCreateParams = /* @__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/."
+ ),
+})
+
/**
* Remove an interviewee from this topic. Drops the identifier from both `interviewee_emails` and `interviewee_distinct_ids`, and disables any active SharingConfiguration linked to an IntervieweeContext for that identifier on this topic so the removed person can no longer open their interview link. Idempotent — removing an identifier that isn't present is a no-op. Returns the updated topic.
*/
diff --git a/services/mcp/src/tools/generated/user_interviews.ts b/services/mcp/src/tools/generated/user_interviews.ts
index 46f686776931..a186da4d0797 100644
--- a/services/mcp/src/tools/generated/user_interviews.ts
+++ b/services/mcp/src/tools/generated/user_interviews.ts
@@ -16,6 +16,7 @@ import {
UserInterviewTopicsIntervieweesListQueryParams,
UserInterviewTopicsIntervieweesPartialUpdateBody,
UserInterviewTopicsIntervieweesPartialUpdateParams,
+ UserInterviewTopicsLinksCsvCreateParams,
UserInterviewTopicsListQueryParams,
UserInterviewTopicsPartialUpdateBody,
UserInterviewTopicsPartialUpdateParams,
@@ -228,6 +229,21 @@ const userInterviewTopicsIntervieweesPartialUpdate = (): ToolBase<
},
})
+const UserInterviewTopicsLinksCsvSchema = UserInterviewTopicsLinksCsvCreateParams.omit({ project_id: true })
+
+const userInterviewTopicsLinksCsv = (): ToolBase<typeof UserInterviewTopicsLinksCsvSchema, unknown> => ({
+ name: 'user-interview-topics-links-csv',
+ schema: UserInterviewTopicsLinksCsvSchema,
+ handler: async (context: Context, params: z.infer<typeof UserInterviewTopicsLinksCsvSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'POST',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.id))}/links_csv/`,
+ })
+ return result
+ },
+})
+
const UserInterviewTopicsListSchema = UserInterviewTopicsListQueryParams
const userInterviewTopicsList = (): ToolBase<
@@ -438,6 +454,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'user-interview-topics-interviewees-destroy': userInterviewTopicsIntervieweesDestroy,
'user-interview-topics-interviewees-list': userInterviewTopicsIntervieweesList,
'user-interview-topics-interviewees-partial-update': userInterviewTopicsIntervieweesPartialUpdate,
+ 'user-interview-topics-links-csv': userInterviewTopicsLinksCsv,
'user-interview-topics-list': userInterviewTopicsList,
'user-interview-topics-partial-update': userInterviewTopicsPartialUpdate,
'user-interview-topics-remove-interviewee': userInterviewTopicsRemoveInterviewee,