Skip to content

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

feat(user_interviews): add side-effect-free invite preview endpoint (#61283)

Paul D'Ambra01f854981d3e
diff --git a/products/user_interviews/backend/invite_email.py b/products/user_interviews/backend/invite_email.py
index ffe0da359416..87bcf64218c0 100644
--- a/products/user_interviews/backend/invite_email.py
+++ b/products/user_interviews/backend/invite_email.py
@@ -1,9 +1,11 @@
from typing import Any
from django.conf import settings
+from django.template.loader import get_template
from rest_framework import serializers
+from posthog.email import inline_css
from posthog.helpers.email_utils import (
contains_bare_domain,
sanitize_display_name,
@@ -11,10 +13,13 @@ from posthog.helpers.email_utils import (
validate_display_name,
validate_message_body,
)
+from posthog.utils import absolute_uri
+from .logic import parse_interviewee_identifier
from .models import UserInterviewTopic
INVITE_EMAIL_TEMPLATE = "email/interview_invite.html"
+PREVIEW_PLACEHOLDER_PATH = "/interview/preview"
# Interview invite copy is stricter than org-invite copy: we reject bare domains (on top of the
# URL-scheme / bracket / control-char checks the shared validators already enforce) because there's
@@ -45,7 +50,8 @@ def build_invite_email_context(
subject_override: str = "",
) -> dict[str, Any]:
"""Resolve the subject + template context for a topic's invite email, personalized for one
- recipient. Re-sanitizes the stored subject/message at render time (defense-in-depth): a stale
+ recipient. Shared by the send path and the (side-effect-free) preview path so both render
+ identically. Re-sanitizes the stored subject/message at render time (defense-in-depth): a stale
or pre-validation value degrades to the default rather than emitting anything unsafe.
"""
topic_label = topic.topic or "a quick research interview"
@@ -71,3 +77,65 @@ def build_invite_email_context(
"site_url": settings.SITE_URL,
},
}
+
+
+def render_invite_email_html(
+ *,
+ topic: UserInterviewTopic,
+ user_name: str,
+ interview_url: str,
+ subject_override: str = "",
+) -> dict[str, str]:
+ """Render the invite email to CSS-inlined HTML without sending. Renders a fixed template file
+ with autoescaped context — user content never reaches the template engine as a template.
+ """
+ built = build_invite_email_context(
+ topic=topic,
+ user_name=user_name,
+ interview_url=interview_url,
+ subject_override=subject_override,
+ )
+ html = inline_css(get_template(INVITE_EMAIL_TEMPLATE).render(built["template_context"]))
+ return {"subject": built["subject"], "html": html}
+
+
+def _targeted_identifiers(topic: UserInterviewTopic) -> list[str]:
+ return [
+ raw.strip()
+ for raw in [*(topic.interviewee_emails or []), *(topic.interviewee_distinct_ids or [])]
+ if raw and raw.strip()
+ ]
+
+
+def resolve_invite_preview(
+ *,
+ topic: UserInterviewTopic,
+ interviewee_identifier: str = "",
+) -> dict[str, Any] | None:
+ """Render an invite-email preview for one targeted interviewee. Defaults to the first targeted
+ interviewee when none is given. Returns None when the topic targets nobody, or when a specific
+ interviewee_identifier is given that the topic does not target.
+
+ Read-only and never exposes a live interview link: the previewed body always shows an illustrative
+ placeholder URL. The real per-recipient share token is minted only when invites are actually sent,
+ so a read-scoped caller can't harvest working interview links through the preview.
+ """
+ targets = _targeted_identifiers(topic)
+ requested = (interviewee_identifier or "").strip()
+ identifier = requested or (targets[0] if targets else "")
+ if not identifier or (requested and requested not in targets):
+ return None
+
+ identity = parse_interviewee_identifier(identifier)
+ interview_url = absolute_uri(PREVIEW_PLACEHOLDER_PATH)
+ rendered = render_invite_email_html(topic=topic, user_name=identity.display_name, interview_url=interview_url)
+ return {
+ "interviewee_identifier": identifier,
+ "user_name": identity.display_name,
+ "email": identity.email,
+ "subject": rendered["subject"],
+ "html": rendered["html"],
+ "interview_url": interview_url,
+ "emailable": identity.email is not None,
+ "is_preview_link": True,
+ }
diff --git a/products/user_interviews/backend/presentation/views.py b/products/user_interviews/backend/presentation/views.py
index 4b835a04880f..89916ca0d169 100644
--- a/products/user_interviews/backend/presentation/views.py
+++ b/products/user_interviews/backend/presentation/views.py
@@ -48,7 +48,12 @@ from posthog.utils import absolute_uri
from ..facade.api import derive_auto_classifications, parse_interviewee_identifier
from ..facade.enums import SEARCH_DOCUMENT_TYPES
-from ..invite_email import build_invite_email_context, validate_invite_message, validate_invite_subject
+from ..invite_email import (
+ build_invite_email_context,
+ resolve_invite_preview,
+ validate_invite_message,
+ validate_invite_subject,
+)
from ..models import (
EmailWithDisplayNameValidator,
IntervieweeContext,
@@ -903,6 +908,49 @@ class SendInvitesRequestSerializer(serializers.Serializer):
return validate_invite_subject(value)
+class PreviewInviteRequestSerializer(serializers.Serializer):
+ interviewee_identifier = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ max_length=400,
+ help_text=(
+ "Which targeted interviewee to render the preview for (an email or PostHog distinct ID "
+ "already on the topic). Leave blank to preview for the first targeted interviewee."
+ ),
+ )
+
+
+class PreviewInviteResultSerializer(serializers.Serializer):
+ interviewee_identifier = serializers.CharField(
+ help_text="The identifier (email or distinct ID) the preview was rendered for.",
+ )
+ user_name = serializers.CharField(
+ help_text="The display name used in the email greeting, derived from the identifier.",
+ )
+ email = serializers.EmailField(
+ allow_null=True,
+ help_text="The email address the invite would be sent to. Null for distinct-ID-only interviewees.",
+ )
+ subject = serializers.CharField(
+ help_text="The rendered subject line (saved topic subject, sanitized, or the default).",
+ )
+ html = serializers.CharField(
+ help_text="The fully rendered, CSS-inlined HTML body of the invite email. Safe to display in a sandboxed iframe.",
+ )
+ interview_url = serializers.URLField(
+ help_text=(
+ "An illustrative placeholder interview link shown in the previewed email body. The preview "
+ "never exposes a real per-recipient share token — that link is minted only when invites are sent."
+ ),
+ )
+ emailable = serializers.BooleanField(
+ help_text="True if this interviewee has an email address and could actually receive the invite.",
+ )
+ is_preview_link = serializers.BooleanField(
+ help_text="Always true — the previewed interview_url is an illustrative placeholder, never a live link.",
+ )
+
+
class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"""Planned user interview topics: who we want to target and what we want to ask about."""
@@ -924,6 +972,15 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"remove_interviewee",
"test_link",
]
+ # preview_invite is a POST (body carries the identifier, keeping emails out of query-string logs)
+ # but renders read-only with no side effects, so it maps to the read scope. Keep the default read
+ # actions (list/retrieve) — this list REPLACES the default, so omitting them would drop read-scope
+ # access for token-authenticated list/retrieve.
+ scope_object_read_actions = [
+ "list",
+ "retrieve",
+ "preview_invite",
+ ]
queryset = UserInterviewTopic.objects.select_related("created_by").all()
serializer_class = UserInterviewTopicSerializer
filter_backends = [filters.SearchFilter]
@@ -1125,6 +1182,39 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return response.Response(InterviewInviteResultSerializer(results, many=True).data)
+ @extend_schema(
+ request=PreviewInviteRequestSerializer,
+ responses={200: OpenApiResponse(response=PreviewInviteResultSerializer)},
+ description=(
+ "Render the invite email exactly as a specific targeted interviewee would receive it — "
+ "personalized subject and body — without sending anything and without creating or reading "
+ "any share links. Pass `interviewee_identifier` to preview for a particular person, or omit "
+ "it to preview for the first targeted interviewee. The body always shows an illustrative "
+ "placeholder link (`is_preview_link: true`), never a live interview URL."
+ ),
+ )
+ @action(detail=True, methods=["post"], url_path="preview_invite")
+ def preview_invite(self, request: Request, *args: Any, **kwargs: Any) -> response.Response:
+ params = PreviewInviteRequestSerializer(data=request.data)
+ params.is_valid(raise_exception=True)
+
+ topic = self.get_object()
+ payload = resolve_invite_preview(
+ topic=topic,
+ interviewee_identifier=params.validated_data.get("interviewee_identifier") or "",
+ )
+ if payload is None:
+ return response.Response(
+ {
+ "error": (
+ "Topic has no targeted interviewees, or the given interviewee_identifier is not "
+ "one of this topic's interviewee_emails / interviewee_distinct_ids."
+ )
+ },
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ return response.Response(PreviewInviteResultSerializer(payload).data)
+
@extend_schema(
request=None,
responses={200: OpenApiResponse(response=TestInterviewLinkSerializer)},
diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.py
index 150e8ef1921a..adafe20e6948 100644
--- a/products/user_interviews/backend/test_interview_sharing.py
+++ b/products/user_interviews/backend/test_interview_sharing.py
@@ -1278,6 +1278,95 @@ class TestInterviewInviteTemplateRendering(unittest.TestCase):
assert "AI interviewer" in html
+class TestPreviewInterviewInvite(_FeatureFlagEnabledMixin):
+ def _create_topic(self, **overrides) -> UserInterviewTopic:
+ defaults: dict = {
+ "team": self.team,
+ "created_by": self.user,
+ "interviewee_emails": ["Alex <[email protected]>"],
+ "interviewee_distinct_ids": [],
+ "topic": "Session replay adoption",
+ "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}/preview_invite/"
+
+ def test_preview_renders_subject_and_html_for_default_identifier(self):
+ topic = self._create_topic(invite_subject="Quick chat about replay?", invite_message="Hey,\nGot a sec?")
+ response = self.client.post(self._url(str(topic.id)), data={}, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ assert body["interviewee_identifier"] == "Alex <[email protected]>"
+ assert body["user_name"] == "Alex"
+ assert body["email"] == "[email protected]"
+ assert body["subject"] == "Quick chat about replay?"
+ assert body["emailable"] is True
+ assert "Got a sec?" in body["html"]
+
+ @parameterized.expand(
+ [
+ ("blank_message", ""),
+ ("unsafe_stored_brackets", "<script>alert(1)</script>"),
+ ]
+ )
+ def test_preview_falls_back_to_default_copy(self, _name: str, invite_message: str):
+ topic = self._create_topic(invite_message=invite_message)
+ body = self.client.post(self._url(str(topic.id)), data={}, format="json").json()
+ assert "AI interviewer" in body["html"]
+ assert "<script>" not in body["html"]
+ assert body["subject"] == "Got 5 minutes to talk about Session replay adoption?"
+
+ def test_preview_for_distinct_id_only_identifier_is_not_emailable(self):
+ topic = self._create_topic(interviewee_emails=[], interviewee_distinct_ids=["distinct-123"])
+ body = self.client.post(
+ self._url(str(topic.id)), data={"interviewee_identifier": "distinct-123"}, format="json"
+ ).json()
+ assert body["interviewee_identifier"] == "distinct-123"
+ assert body["email"] is None
+ assert body["emailable"] is False
+
+ def test_preview_creates_no_share_rows_and_uses_placeholder_link(self):
+ topic = self._create_topic()
+ before_ic = IntervieweeContext.objects.count()
+ before_sc = SharingConfiguration.objects.count()
+ body = self.client.post(self._url(str(topic.id)), data={}, format="json").json()
+ assert body["is_preview_link"] is True
+ assert "/interview/preview" in body["interview_url"]
+ assert IntervieweeContext.objects.count() == before_ic
+ assert SharingConfiguration.objects.count() == before_sc
+
+ def test_preview_never_exposes_live_share_token(self):
+ # A read-scoped preview must not leak a working interview link even when one exists.
+ topic = self._create_topic()
+ ic = IntervieweeContext.objects.create(
+ team=self.team,
+ topic=topic,
+ interviewee_identifier="Alex <[email protected]>",
+ agent_context="",
+ created_by=self.user,
+ )
+ share = SharingConfiguration.objects.create(team=self.team, interviewee_context=ic, enabled=True)
+ body = self.client.post(self._url(str(topic.id)), data={}, format="json").json()
+ assert share.access_token not in body["interview_url"]
+ assert "/interview/preview" in body["interview_url"]
+ assert body["is_preview_link"] is True
+
+ def test_preview_400_when_topic_has_no_identifiers(self):
+ topic = self._create_topic(interviewee_emails=[], interviewee_distinct_ids=[])
+ response = self.client.post(self._url(str(topic.id)), data={}, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+
+ def test_preview_400_for_non_targeted_identifier(self):
+ topic = self._create_topic(interviewee_emails=["[email protected]"], interviewee_distinct_ids=[])
+ response = self.client.post(
+ self._url(str(topic.id)), data={"interviewee_identifier": "[email protected]"}, format="json"
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+
+
class TestSharingConfigurationCanAccess(APIBaseTest):
def test_can_access_interviewee_context(self):
topic = UserInterviewTopic.objects.create(
diff --git a/products/user_interviews/frontend/generated/api.schemas.ts b/products/user_interviews/frontend/generated/api.schemas.ts
index 4e93586c82c0..5917f5479609 100644
--- a/products/user_interviews/frontend/generated/api.schemas.ts
+++ b/products/user_interviews/frontend/generated/api.schemas.ts
@@ -154,6 +154,36 @@ export interface PaginatedInterviewLinkListApi {
results: InterviewLinkApi[]
}
+export interface PreviewInviteRequestApi {
+ /**
+ * Which targeted interviewee to render the preview for (an email or PostHog distinct ID already on the topic). Leave blank to preview for the first targeted interviewee.
+ * @maxLength 400
+ */
+ interviewee_identifier?: string
+}
+
+export interface PreviewInviteResultApi {
+ /** The identifier (email or distinct ID) the preview was rendered for. */
+ interviewee_identifier: string
+ /** The display name used in the email greeting, derived from the identifier. */
+ user_name: string
+ /**
+ * The email address the invite would be sent to. Null for distinct-ID-only interviewees.
+ * @nullable
+ */
+ email: string | null
+ /** The rendered subject line (saved topic subject, sanitized, or the default). */
+ subject: string
+ /** The fully rendered, CSS-inlined HTML body of the invite email. Safe to display in a sandboxed iframe. */
+ html: string
+ /** An illustrative placeholder interview link shown in the previewed email body. The preview never exposes a real per-recipient share token — that link is minted only when invites are sent. */
+ interview_url: string
+ /** True if this interviewee has an email address and could actually receive the invite. */
+ emailable: boolean
+ /** Always true — the previewed interview_url is an illustrative placeholder, never a live link. */
+ is_preview_link: boolean
+}
+
export interface SendInvitesRequestApi {
/**
* Override the email subject line for this send. Plain text only — URLs, angle brackets, and control characters are rejected. Falls back to the topic's saved subject, then a default.
diff --git a/products/user_interviews/frontend/generated/api.ts b/products/user_interviews/frontend/generated/api.ts
index 70439fa8ac29..854a61294af4 100644
--- a/products/user_interviews/frontend/generated/api.ts
+++ b/products/user_interviews/frontend/generated/api.ts
@@ -21,6 +21,8 @@ import type {
PatchedIntervieweeContextApi,
PatchedUserInterviewApi,
PatchedUserInterviewTopicApi,
+ PreviewInviteRequestApi,
+ PreviewInviteResultApi,
SendInvitesRequestApi,
TestInterviewLinkApi,
UserInterviewApi,
@@ -234,6 +236,27 @@ export const userInterviewTopicsLinksCsvCreate = async (
})
}
+export const getUserInterviewTopicsPreviewInviteCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/user_interview_topics/${id}/preview_invite/`
+}
+
+/**
+ * Render the invite email exactly as a specific targeted interviewee would receive it — personalized subject and body — without sending anything and without creating or reading any share links. Pass `interviewee_identifier` to preview for a particular person, or omit it to preview for the first targeted interviewee. The body always shows an illustrative placeholder link (`is_preview_link: true`), never a live interview URL.
+ */
+export const userInterviewTopicsPreviewInviteCreate = async (
+ projectId: string,
+ id: string,
+ previewInviteRequestApi?: PreviewInviteRequestApi,
+ options?: RequestInit
+): Promise<PreviewInviteResultApi> => {
+ return apiMutator<PreviewInviteResultApi>(getUserInterviewTopicsPreviewInviteCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(previewInviteRequestApi),
+ })
+}
+
export const getUserInterviewTopicsRemoveIntervieweeCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/user_interview_topics/${id}/remove_interviewee/`
}
diff --git a/products/user_interviews/frontend/generated/api.zod.ts b/products/user_interviews/frontend/generated/api.zod.ts
index ab952da421a8..cb821140cdb9 100644
--- a/products/user_interviews/frontend/generated/api.zod.ts
+++ b/products/user_interviews/frontend/generated/api.zod.ts
@@ -158,6 +158,21 @@ export const UserInterviewTopicsAddIntervieweeCreateBody = /* @__PURE__ */ zod.o
),
})
+/**
+ * Render the invite email exactly as a specific targeted interviewee would receive it — personalized subject and body — without sending anything and without creating or reading any share links. Pass `interviewee_identifier` to preview for a particular person, or omit it to preview for the first targeted interviewee. The body always shows an illustrative placeholder link (`is_preview_link: true`), never a live interview URL.
+ */
+export const userInterviewTopicsPreviewInviteCreateBodyIntervieweeIdentifierMax = 400
+
+export const UserInterviewTopicsPreviewInviteCreateBody = /* @__PURE__ */ zod.object({
+ interviewee_identifier: zod
+ .string()
+ .max(userInterviewTopicsPreviewInviteCreateBodyIntervieweeIdentifierMax)
+ .optional()
+ .describe(
+ 'Which targeted interviewee to render the preview for (an email or PostHog distinct ID already on the topic). Leave blank to preview for the first targeted interviewee.'
+ ),
+})
+
/**
* 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/products/user_interviews/mcp/tools.yaml b/products/user_interviews/mcp/tools.yaml
index bc5a5921424a..c44d013ff9c5 100644
--- a/products/user_interviews/mcp/tools.yaml
+++ b/products/user_interviews/mcp/tools.yaml
@@ -224,6 +224,9 @@ tools:
- invite_subject
- invite_message
feature_flag: user-interviews
+ user-interview-topics-preview-invite-create:
+ operation: user_interview_topics_preview_invite_create
+ enabled: false
user-interview-topics-remove-interviewee:
operation: user_interview_topics_remove_interviewee_create
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 231bf22d1171..60c29689fdcb 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -34248,6 +34248,36 @@ export namespace Schemas {
homepage?: PinnedSceneTab | null;
}
+ export interface PreviewInviteRequest {
+ /**
+ * Which targeted interviewee to render the preview for (an email or PostHog distinct ID already on the topic). Leave blank to preview for the first targeted interviewee.
+ * @maxLength 400
+ */
+ interviewee_identifier?: string;
+ }
+
+ export interface PreviewInviteResult {
+ /** The identifier (email or distinct ID) the preview was rendered for. */
+ interviewee_identifier: string;
+ /** The display name used in the email greeting, derived from the identifier. */
+ user_name: string;
+ /**
+ * The email address the invite would be sent to. Null for distinct-ID-only interviewees.
+ * @nullable
+ */
+ email: string | null;
+ /** The rendered subject line (saved topic subject, sanitized, or the default). */
+ subject: string;
+ /** The fully rendered, CSS-inlined HTML body of the invite email. Safe to display in a sandboxed iframe. */
+ html: string;
+ /** An illustrative placeholder interview link shown in the previewed email body. The preview never exposes a real per-recipient share token — that link is minted only when invites are sent. */
+ interview_url: string;
+ /** True if this interviewee has an email address and could actually receive the invite. */
+ emailable: boolean;
+ /** Always true — the previewed interview_url is an illustrative placeholder, never a live link. */
+ is_preview_link: boolean;
+ }
+
/**
* Mapping from event name to the team-configured primary property for that event. Names without a configured primary property are omitted; callers should fall back to the core taxonomy defaults for those.
*/