: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): editable invite subject and message (#61263)
Paul D'Ambraa51a437c6e2a
diff --git a/posthog/helpers/email_utils.py b/posthog/helpers/email_utils.pyindex 8d1406451f67..35cb4d8d8d85 100644--- a/posthog/helpers/email_utils.py+++ b/posthog/helpers/email_utils.py@@ -110,6 +110,18 @@ def validate_message_body(value: str | None) -> str | None:return value+def contains_bare_domain(value: str | None) -> bool:+ """+ True if `value` contains a bare domain (e.g. `example.com`) after NFKC+ normalization. The `validate_*` helpers above intentionally *allow* bare+ domains; callers that want to reject domains entirely (e.g. so mail clients+ can't auto-link them in a branded email) layer this check on top.+ """+ if not value:+ return False+ return bool(_BARE_DOMAIN_RE.search(unicodedata.normalize("NFKC", value)))++def _extract_error_code(err: serializers.ValidationError) -> str:"""Pull the first `code` off a DRF ValidationError. `err.detail` is a uniondiff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambrindex 800a3fff4b5e..4d81dc6a2021 100644--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr@@ -1122,7 +1122,7 @@WHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,(SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_idFROM events- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))+ WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), equals(events.mat_pp_email, 'bla'), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')HAVING 1ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESCdiff --git a/posthog/templates/email/interview_invite.html b/posthog/templates/email/interview_invite.htmlindex d106c6a56162..8c058d7b9d47 100644--- a/posthog/templates/email/interview_invite.html+++ b/posthog/templates/email/interview_invite.html@@ -5,6 +5,9 @@{% block section %}<p>Hey {{ user_name }},</p>+{% if invite_message %}+<p>{{ invite_message|linebreaksbr }}</p>+{% else %}<p>We're researching <strong>{{ topic }}</strong> and your perspective would be really valuable. Got 5–10 minutes for a quick voice conversation?</p>@@ -12,6 +15,7 @@<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>+{% endif %}<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;">diff --git a/products/user_interviews/backend/invite_email.py b/products/user_interviews/backend/invite_email.pynew file mode 100644index 000000000000..ffe0da359416--- /dev/null+++ b/products/user_interviews/backend/invite_email.py@@ -0,0 +1,73 @@+from typing import Any++from django.conf import settings++from rest_framework import serializers++from posthog.helpers.email_utils import (+ contains_bare_domain,+ sanitize_display_name,+ sanitize_message_body,+ validate_display_name,+ validate_message_body,+)++from .models import UserInterviewTopic++INVITE_EMAIL_TEMPLATE = "email/interview_invite.html"++# 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+# no legitimate reason to link out from a research invite, and mail clients auto-link bare domains —+# a phishing vector in a PostHog-branded email.+_INVITE_DOMAIN_ERROR = "Links and domain names aren't allowed in interview invite copy."+++def validate_invite_subject(value: str | None) -> str | None:+ validated = validate_display_name(value)+ if contains_bare_domain(validated):+ raise serializers.ValidationError(_INVITE_DOMAIN_ERROR, code="invalid_domain")+ return validated+++def validate_invite_message(value: str | None) -> str | None:+ validated = validate_message_body(value)+ if contains_bare_domain(validated):+ raise serializers.ValidationError(_INVITE_DOMAIN_ERROR, code="invalid_domain")+ return validated+++def build_invite_email_context(+ *,+ topic: UserInterviewTopic,+ user_name: str,+ interview_url: str,+ 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+ or pre-validation value degrades to the default rather than emitting anything unsafe.+ """+ topic_label = topic.topic or "a quick research interview"+ default_subject = f"Got 5 minutes to talk about {topic_label}?"+ log_context = {"feature": "user_interview_invite", "topic_id": str(topic.id)}+ subject = sanitize_display_name(+ subject_override or topic.invite_subject,+ fallback=default_subject,+ context={**log_context, "field": "subject"},+ )+ invite_message = sanitize_message_body(+ topic.invite_message,+ fallback="",+ context={**log_context, "field": "invite_message"},+ )+ return {+ "subject": subject,+ "template_context": {+ "user_name": user_name,+ "topic": topic_label,+ "interview_url": interview_url,+ "invite_message": invite_message,+ "site_url": settings.SITE_URL,+ },+ }diff --git a/products/user_interviews/backend/max_tools.py b/products/user_interviews/backend/max_tools.pyindex 43a0276e9871..a40b0f5ad84b 100644--- a/products/user_interviews/backend/max_tools.py+++ b/products/user_interviews/backend/max_tools.py@@ -6,6 +6,7 @@ from django.core.exceptions import ValidationError as DjangoValidationErrorfrom openai import OpenAIfrom pydantic import BaseModel, ConfigDict, Field+from rest_framework.serializers import ValidationError as DRFValidationErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.rbac.user_access_control import AccessControlLevel@@ -13,6 +14,7 @@ from posthog.scopes import APIScopeObjectfrom ee.hogai.tool import MaxTool+from .invite_email import validate_invite_message, validate_invite_subjectfrom .models import EmailWithDisplayNameValidator, UserInterview, UserInterviewTopic@@ -163,6 +165,22 @@ class CreateUserInterviewTopicArgs(BaseModel):"call on this topic. Leave empty if no extra context is needed."),)+ invite_subject: str = Field(+ default="",+ description=(+ "Optional subject line for the invitation email. Plain text only — must not contain URLs, "+ "angle brackets, or line breaks. The email template handles personalization, so do not add "+ "placeholders. Leave empty to use the default subject."+ ),+ )+ invite_message: str = Field(+ default="",+ description=(+ "Optional intro message shown in the invitation email body, above the interview link. Plain "+ "prose only (line breaks allowed) — must not contain URLs or angle brackets. Leave empty to "+ "use the default copy."+ ),+ )class CreateUserInterviewTopicTool(MaxTool):@@ -186,6 +204,8 @@ class CreateUserInterviewTopicTool(MaxTool):interviewee_distinct_ids: list[str] | None = None,questions: list[str] | None = None,agent_context: str = "",+ invite_subject: str = "",+ invite_message: str = "",) -> tuple[str, dict[str, Any]]:emails = [e.strip() for e in (interviewee_emails or []) if e and e.strip()]distinct_ids = [d.strip() for d in (interviewee_distinct_ids or []) if d and d.strip()]@@ -242,6 +262,21 @@ class CreateUserInterviewTopicTool(MaxTool):},)+ try:+ invite_subject = validate_invite_subject(invite_subject or "") or ""+ invite_message = validate_invite_message(invite_message or "") or ""+ except DRFValidationError as e:+ return (+ "The invite subject or message contains disallowed content.",+ {+ "error": "validation_failed",+ "error_message": (+ "The invite subject or message was rejected (URLs, angle brackets, and control "+ f"characters are not allowed): {e.detail}"+ ),+ },+ )+try:created_topic = await UserInterviewTopic.objects.acreate(team=self._team,@@ -251,6 +286,8 @@ class CreateUserInterviewTopicTool(MaxTool):interviewee_distinct_ids=distinct_ids,questions=questions,agent_context=agent_context or "",+ invite_subject=invite_subject,+ invite_message=invite_message,)except Exception as e:capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})diff --git a/products/user_interviews/backend/migrations/0006_userinterviewtopic_invite_fields.py b/products/user_interviews/backend/migrations/0006_userinterviewtopic_invite_fields.pynew file mode 100644index 000000000000..aeb6a7251764--- /dev/null+++ b/products/user_interviews/backend/migrations/0006_userinterviewtopic_invite_fields.py@@ -0,0 +1,20 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("user_interviews", "0005_remove_userinterviewtopic_interviewee_cohort_state"),+ ]++ operations = [+ migrations.AddField(+ model_name="userinterviewtopic",+ name="invite_subject",+ field=models.CharField(blank=True, db_default="", default="", max_length=255),+ ),+ migrations.AddField(+ model_name="userinterviewtopic",+ name="invite_message",+ field=models.TextField(blank=True, db_default="", default=""),+ ),+ ]diff --git a/products/user_interviews/backend/migrations/max_migration.txt b/products/user_interviews/backend/migrations/max_migration.txtindex 50101431675b..3002631ed091 100644--- a/products/user_interviews/backend/migrations/max_migration.txt+++ b/products/user_interviews/backend/migrations/max_migration.txt@@ -1 +1 @@-0005_remove_userinterviewtopic_interviewee_cohort_state+0006_userinterviewtopic_invite_fieldsdiff --git a/products/user_interviews/backend/models.py b/products/user_interviews/backend/models.pyindex a1db77ca792f..bfa7ace8a861 100644--- a/products/user_interviews/backend/models.py+++ b/products/user_interviews/backend/models.py@@ -61,6 +61,8 @@ class UserInterviewTopic(UUIDTModel, CreatedMetaFields):default=list,blank=True,)+ invite_subject = models.CharField(max_length=255, blank=True, default="", db_default="")+ invite_message = models.TextField(blank=True, default="", db_default="")class Meta:ordering = ["-created_at"]diff --git a/products/user_interviews/backend/presentation/views.py b/products/user_interviews/backend/presentation/views.pyindex b227d238d82b..3a7f2cff88f9 100644--- a/products/user_interviews/backend/presentation/views.py+++ b/products/user_interviews/backend/presentation/views.py@@ -46,6 +46,7 @@ from posthog.utils import absolute_urifrom ..facade.api import parse_interviewee_identifierfrom ..facade.enums import SEARCH_DOCUMENT_TYPES+from ..invite_email import build_invite_email_context, validate_invite_message, validate_invite_subjectfrom ..models import EmailWithDisplayNameValidator, IntervieweeContext, UserInterview, UserInterviewTopiclogger = structlog.get_logger(__name__)@@ -504,6 +505,26 @@ class UserInterviewTopicSerializer(serializers.ModelSerializer):required=False,help_text="Ordered list of questions the voice agent should work through during the interview.",)+ invite_subject = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=255,+ help_text=(+ "Subject line for the invitation email. Plain text only — URLs, angle brackets, and control "+ "characters are rejected. Leave blank to use the default subject. Personalization is handled by "+ "the email template, so do not include placeholders."+ ),+ )+ invite_message = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=1000,+ help_text=(+ "Intro message shown in the invitation email body, above the interview link. Plain prose only — "+ "URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank "+ "to use the default copy."+ ),+ )class Meta:model = UserInterviewTopic@@ -516,9 +537,17 @@ class UserInterviewTopicSerializer(serializers.ModelSerializer):"topic","agent_context","questions",+ "invite_subject",+ "invite_message",)read_only_fields = ("id", "created_by", "created_at")+ def validate_invite_subject(self, value: str | None) -> str | None:+ return validate_invite_subject(value)++ def validate_invite_message(self, value: str | None) -> str | None:+ return validate_invite_message(value)+MISSING_TARGETING_ERROR = "At least one of interviewee_emails or interviewee_distinct_ids must be provided."def validate(self, attrs: dict) -> dict:@@ -791,7 +820,10 @@ 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.",+ help_text=(+ "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."+ ),)reply_to = serializers.EmailField(required=False,@@ -803,6 +835,9 @@ class SendInvitesRequestSerializer(serializers.Serializer):help_text="If true (default), queue delivery via Celery. If false, send synchronously and surface errors immediately.",)+ def validate_subject(self, value: str | None) -> str | None:+ return validate_invite_subject(value)+class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"""Planned user interview topics: who we want to target and what we want to ask about."""@@ -957,8 +992,7 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):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}?"+ subject_override = params.validated_data.get("subject") or ""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@@ -975,18 +1009,19 @@ class UserInterviewTopicViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):results.append({**base, "sent": False, "reason": "not_an_email"})continue+ built = build_invite_email_context(+ topic=topic,+ user_name=link["user_name"],+ interview_url=link["interview_url"],+ subject_override=subject_override,+ )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,- },+ subject=built["subject"],+ template_context=built["template_context"],reply_to=reply_to,)message.add_recipient(email=link["email"], name=link["user_name"])diff --git a/products/user_interviews/backend/test_interview_sharing.py b/products/user_interviews/backend/test_interview_sharing.pyindex abab27c6a3c5..78370451cfa5 100644--- a/products/user_interviews/backend/test_interview_sharing.py+++ b/products/user_interviews/backend/test_interview_sharing.py@@ -11,6 +11,7 @@ from freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.template.loader import get_templatefrom django.test import override_settingsfrom django.utils import timezone@@ -1076,6 +1077,158 @@ class TestSendInterviewInvites(_FeatureFlagEnabledMixin):self.assertFalse(by_id["[email protected]"]["sent"])self.assertTrue(by_id["[email protected]"]["reason"].startswith("error:"))+ def test_send_invites_uses_stored_topic_subject_and_message(self):+ topic = self._create_topic(+ interviewee_emails=["[email protected]"],+ interviewee_distinct_ids=[],+ invite_subject="Quick chat about replay?",+ invite_message="Hey!\nWe'd love your thoughts.",+ )++ with (+ patch("products.user_interviews.backend.presentation.views.EmailMessage") as mock_message_cls,+ patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),+ ):+ self.client.post(self._url(str(topic.id)), data={}, format="json")++ kwargs = mock_message_cls.call_args.kwargs+ assert kwargs["subject"] == "Quick chat about replay?"+ assert kwargs["template_context"]["invite_message"] == "Hey!\nWe'd love your thoughts."++ def test_send_invites_request_subject_overrides_stored(self):+ topic = self._create_topic(+ interviewee_emails=["[email protected]"],+ interviewee_distinct_ids=[],+ invite_subject="Stored subject?",+ )++ with (+ patch("products.user_interviews.backend.presentation.views.EmailMessage") as mock_message_cls,+ patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),+ ):+ self.client.post(self._url(str(topic.id)), data={"subject": "Override subject?"}, format="json")++ assert mock_message_cls.call_args.kwargs["subject"] == "Override subject?"++ def test_send_invites_sanitizes_unsafe_stored_values_at_send_time(self):+ # Defense-in-depth: values written straight to the DB (bypassing serializer validation)+ # must still degrade to safe defaults at send time rather than reaching the email.+ topic = self._create_topic(+ interviewee_emails=["[email protected]"],+ interviewee_distinct_ids=[],+ invite_subject="http://evil.com",+ invite_message="<b>click www.evil.com</b>",+ )++ with (+ patch("products.user_interviews.backend.presentation.views.EmailMessage") as mock_message_cls,+ patch("products.user_interviews.backend.presentation.views.is_email_available", return_value=True),+ ):+ self.client.post(self._url(str(topic.id)), data={}, format="json")++ kwargs = mock_message_cls.call_args.kwargs+ assert kwargs["subject"] == "Got 5 minutes to talk about Session replay adoption?"+ assert "evil.com" not in kwargs["subject"]+ assert kwargs["template_context"]["invite_message"] == ""+++class TestInviteFieldValidation(_FeatureFlagEnabledMixin):+ def _url(self) -> str:+ return f"/api/environments/{self.team.id}/user_interview_topics/"++ UNSAFE_SUBJECTS = [+ ("url_scheme", "Visit http://evil.com"),+ ("www_prefix", "go to www.evil.com now"),+ ("bare_domain", "thoughts on acme.com?"),+ ("angle_brackets", "Hi <b>there</b>"),+ ("newline", "line one\nline two"),+ ("null_byte", "subject\x00"),+ ("zero_width", "subject"),+ ("fullwidth_url", "http://evil.example"),+ ]+ UNSAFE_MESSAGES = [+ ("url_scheme", "click http://evil.com"),+ ("javascript_scheme", "click javascript:alert(1)"),+ ("www_prefix", "see www.evil.com"),+ ("bare_domain", "head to acme.com to learn more"),+ ("angle_brackets", "<script>alert(1)</script>"),+ ("null_byte", "body\x00here"),+ ("bidi_override", "bodyhere"),+ ("fullwidth_url", "http://evil.example"),+ ]++ @parameterized.expand(UNSAFE_SUBJECTS)+ def test_create_rejects_unsafe_subject(self, _name: str, subject: str):+ payload = {"topic": "t", "interviewee_emails": ["[email protected]"], "invite_subject": subject}+ response = self.client.post(self._url(), data=payload, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert response.json()["attr"] == "invite_subject"++ @parameterized.expand(UNSAFE_MESSAGES)+ def test_create_rejects_unsafe_message(self, _name: str, message: str):+ payload = {"topic": "t", "interviewee_emails": ["[email protected]"], "invite_message": message}+ response = self.client.post(self._url(), data=payload, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert response.json()["attr"] == "invite_message"++ @parameterized.expand(+ [+ ("plain_subject_and_message", "Got a sec to chat?", "Hi there,\nThanks for being a user."),+ ("multiline_no_links", "Quick question", "have you seen the new onboarding flow?\nKeen to hear your take."),+ ("blank_values", "", ""),+ ]+ )+ def test_create_accepts_safe_values(self, _name: str, subject: str, message: str):+ payload = {+ "topic": "t",+ "interviewee_emails": ["[email protected]"],+ "invite_subject": subject,+ "invite_message": message,+ }+ response = self.client.post(self._url(), data=payload, format="json")+ assert response.status_code == status.HTTP_201_CREATED, response.content+ topic = UserInterviewTopic.objects.get(id=response.json()["id"], team=self.team)+ assert topic.invite_subject == subject+ assert topic.invite_message == message++ def test_partial_update_rejects_unsafe_subject(self):+ topic = UserInterviewTopic.objects.create(+ team=self.team, created_by=self.user, interviewee_emails=["[email protected]"], topic="t"+ )+ response = self.client.patch(+ f"{self._url()}{topic.id}/", data={"invite_subject": "go to www.evil.com"}, format="json"+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ topic.refresh_from_db()+ assert topic.invite_subject == ""+++class TestInterviewInviteTemplateRendering(unittest.TestCase):+ def _render(self, **context: Any) -> str:+ ctx: dict[str, Any] = {+ "user_name": "Alex",+ "topic": "Session replay",+ "interview_url": "https://app.posthog.com/interview/abc",+ "site_url": "https://app.posthog.com",+ }+ ctx.update(context)+ return get_template("email/interview_invite.html").render(ctx)++ def test_hostile_message_is_escaped_not_live_markup(self):+ html = self._render(invite_message='<script>alert("xss")</script>\nstay safe')+ assert "<script>" in html+ assert "<script>" not in html+ assert "stay safe" in html++ def test_multiline_message_renders_line_breaks(self):+ html = self._render(invite_message="Line one\nLine two")+ assert "Line one<br>" in html+ assert "Line two" in html++ def test_blank_message_falls_back_to_default_copy(self):+ html = self._render(invite_message="")+ assert "AI interviewer" in html+class TestSharingConfigurationCanAccess(APIBaseTest):def test_can_access_interviewee_context(self):diff --git a/products/user_interviews/backend/test_max_tools.py b/products/user_interviews/backend/test_max_tools.pyindex 9c3831ae78bf..13eb8c0a5916 100644--- a/products/user_interviews/backend/test_max_tools.py+++ b/products/user_interviews/backend/test_max_tools.py@@ -131,3 +131,49 @@ class TestCreateUserInterviewTopicTool(BaseTest):assert topic.interviewee_emails == ["[email protected]"]assert topic.interviewee_distinct_ids == ["user_1"]assert topic.questions == ["A real question?"]++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_arun_impl_persists_safe_invite_fields(self):+ tool = self._tool()++ content, artifact = await tool._arun_impl(+ topic="Some topic",+ interviewee_emails=["[email protected]"],+ questions=["A real question?"],+ invite_subject="Got a sec to chat?",+ invite_message="Hi Alex,\nWe'd love your thoughts.",+ )++ assert "Created interview topic" in content+ topic = await sync_to_async(lambda: UserInterviewTopic.objects.get(team=self.team, id=artifact["topic_id"]))()+ assert topic.invite_subject == "Got a sec to chat?"+ assert topic.invite_message == "Hi Alex,\nWe'd love your thoughts."++ @pytest.mark.django_db+ @pytest.mark.asyncio+ @parameterized.expand(+ [+ ("subject_with_url", {"invite_subject": "see http://evil.com"}),+ ("subject_with_brackets", {"invite_subject": "<b>hi</b>"}),+ ("subject_with_newline", {"invite_subject": "line one\nline two"}),+ ("message_with_www", {"invite_message": "go to www.evil.com"}),+ ("message_with_bare_domain", {"invite_message": "head to acme.com to learn more"}),+ ("subject_with_bare_domain", {"invite_subject": "thoughts on acme.com?"}),+ ("message_with_javascript", {"invite_message": "click javascript:alert(1)"}),+ ("message_with_brackets", {"invite_message": "<script>alert(1)</script>"}),+ ]+ )+ async def test_arun_impl_rejects_unsafe_invite_fields(self, _name, invite_kwargs):+ tool = self._tool()++ content, artifact = await tool._arun_impl(+ topic="Some topic",+ interviewee_emails=["[email protected]"],+ questions=["A real question?"],+ **invite_kwargs,+ )++ assert artifact["error"] == "validation_failed"+ assert "invite" in content.lower()+ assert not await sync_to_async(UserInterviewTopic.objects.filter(team=self.team).exists)()diff --git a/products/user_interviews/frontend/generated/api.schemas.ts b/products/user_interviews/frontend/generated/api.schemas.tsindex ee2ee312b6fc..113b705364c9 100644--- a/products/user_interviews/frontend/generated/api.schemas.ts+++ b/products/user_interviews/frontend/generated/api.schemas.ts@@ -76,6 +76,16 @@ export interface UserInterviewTopicApi {agent_context?: string/** Ordered list of questions the voice agent should work through during the interview. */questions?: string[]+ /**+ * Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.+ * @maxLength 255+ */+ invite_subject?: string+ /**+ * Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.+ * @maxLength 1000+ */+ invite_message?: string}export interface PaginatedUserInterviewTopicListApi {@@ -101,6 +111,16 @@ export interface PatchedUserInterviewTopicApi {agent_context?: string/** Ordered list of questions the voice agent should work through during the interview. */questions?: string[]+ /**+ * Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.+ * @maxLength 255+ */+ invite_subject?: string+ /**+ * Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.+ * @maxLength 1000+ */+ invite_message?: string}export interface IntervieweeIdentifierRequestApi {@@ -136,7 +156,7 @@ export interface PaginatedInterviewLinkListApi {export interface SendInvitesRequestApi {/**- * Override the default email subject line. Defaults to a friendly prompt referencing the topic.+ * 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.* @maxLength 200*/subject?: stringdiff --git a/products/user_interviews/frontend/generated/api.zod.ts b/products/user_interviews/frontend/generated/api.zod.tsindex 9892211606b5..faa580ec8edd 100644--- a/products/user_interviews/frontend/generated/api.zod.ts+++ b/products/user_interviews/frontend/generated/api.zod.ts@@ -16,6 +16,10 @@ export const userInterviewTopicsCreateBodyIntervieweeEmailsItemMax = 254export const userInterviewTopicsCreateBodyIntervieweeDistinctIdsItemMax = 400+export const userInterviewTopicsCreateBodyInviteSubjectMax = 255++export const userInterviewTopicsCreateBodyInviteMessageMax = 1000+export const UserInterviewTopicsCreateBody = /* @__PURE__ */ zod.object({interviewee_emails: zod.array(zod.string().max(userInterviewTopicsCreateBodyIntervieweeEmailsItemMax))@@ -34,6 +38,20 @@ export const UserInterviewTopicsCreateBody = /* @__PURE__ */ zod.object({.array(zod.string()).optional().describe('Ordered list of questions the voice agent should work through during the interview.'),+ invite_subject: zod+ .string()+ .max(userInterviewTopicsCreateBodyInviteSubjectMax)+ .optional()+ .describe(+ 'Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.'+ ),+ invite_message: zod+ .string()+ .max(userInterviewTopicsCreateBodyInviteMessageMax)+ .optional()+ .describe(+ 'Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.'+ ),})/**@@ -43,6 +61,10 @@ export const userInterviewTopicsUpdateBodyIntervieweeEmailsItemMax = 254export const userInterviewTopicsUpdateBodyIntervieweeDistinctIdsItemMax = 400+export const userInterviewTopicsUpdateBodyInviteSubjectMax = 255++export const userInterviewTopicsUpdateBodyInviteMessageMax = 1000+export const UserInterviewTopicsUpdateBody = /* @__PURE__ */ zod.object({interviewee_emails: zod.array(zod.string().max(userInterviewTopicsUpdateBodyIntervieweeEmailsItemMax))@@ -61,6 +83,20 @@ export const UserInterviewTopicsUpdateBody = /* @__PURE__ */ zod.object({.array(zod.string()).optional().describe('Ordered list of questions the voice agent should work through during the interview.'),+ invite_subject: zod+ .string()+ .max(userInterviewTopicsUpdateBodyInviteSubjectMax)+ .optional()+ .describe(+ 'Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.'+ ),+ invite_message: zod+ .string()+ .max(userInterviewTopicsUpdateBodyInviteMessageMax)+ .optional()+ .describe(+ 'Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.'+ ),})/**@@ -70,6 +106,10 @@ export const userInterviewTopicsPartialUpdateBodyIntervieweeEmailsItemMax = 254export const userInterviewTopicsPartialUpdateBodyIntervieweeDistinctIdsItemMax = 400+export const userInterviewTopicsPartialUpdateBodyInviteSubjectMax = 255++export const userInterviewTopicsPartialUpdateBodyInviteMessageMax = 1000+export const UserInterviewTopicsPartialUpdateBody = /* @__PURE__ */ zod.object({interviewee_emails: zod.array(zod.string().max(userInterviewTopicsPartialUpdateBodyIntervieweeEmailsItemMax))@@ -88,6 +128,20 @@ export const UserInterviewTopicsPartialUpdateBody = /* @__PURE__ */ zod.object({.array(zod.string()).optional().describe('Ordered list of questions the voice agent should work through during the interview.'),+ invite_subject: zod+ .string()+ .max(userInterviewTopicsPartialUpdateBodyInviteSubjectMax)+ .optional()+ .describe(+ 'Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.'+ ),+ invite_message: zod+ .string()+ .max(userInterviewTopicsPartialUpdateBodyInviteMessageMax)+ .optional()+ .describe(+ 'Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.'+ ),})/**@@ -130,7 +184,9 @@ export const UserInterviewTopicsSendInvitesCreateBody = /* @__PURE__ */ zod.obje.string().max(userInterviewTopicsSendInvitesCreateBodySubjectMax).optional()- .describe('Override the default email subject line. Defaults to a friendly prompt referencing the topic.'),+ .describe(+ "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."+ ),reply_to: zod.email().optional()diff --git a/products/user_interviews/mcp/tools.yaml b/products/user_interviews/mcp/tools.yamlindex cfe40936bfca..172317019b07 100644--- a/products/user_interviews/mcp/tools.yaml+++ b/products/user_interviews/mcp/tools.yaml@@ -52,6 +52,8 @@ tools:- topic- agent_context- questions+ - invite_subject+ - invite_messagefeature_flag: user-interviewsuser-interview-topics-destroy:operation: user_interview_topics_destroy@@ -219,6 +221,8 @@ tools:- questions- interviewee_emails- interviewee_distinct_ids+ - invite_subject+ - invite_messagefeature_flag: user-interviewsuser-interview-topics-remove-interviewee:operation: user_interview_topics_remove_interviewee_creatediff --git a/pyproject.toml b/pyproject.tomlindex c0ca7f8ba4f0..94d80edafe45 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -509,6 +509,7 @@ ignore_imports = ["products.tracing.backend.presentation.views -> products.tracing.backend.sparkline_query_runner","products.tracing.backend.presentation.views -> products.tracing.backend.has_spans_query_runner","products.user_interviews.backend.presentation.views -> products.user_interviews.backend.models",+ "products.user_interviews.backend.presentation.views -> products.user_interviews.backend.invite_email","products.user_interviews.backend.presentation.webhooks -> products.user_interviews.backend.models",]diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a47e8aa139e6..303ef8851f50 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -26260,6 +26260,16 @@ export namespace Schemas {agent_context?: string;/** Ordered list of questions the voice agent should work through during the interview. */questions?: string[];+ /**+ * Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.+ * @maxLength 255+ */+ invite_subject?: string;+ /**+ * Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.+ * @maxLength 1000+ */+ invite_message?: string;}export interface PaginatedUserInterviewTopicList {@@ -32356,6 +32366,16 @@ export namespace Schemas {agent_context?: string;/** Ordered list of questions the voice agent should work through during the interview. */questions?: string[];+ /**+ * Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.+ * @maxLength 255+ */+ invite_subject?: string;+ /**+ * Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.+ * @maxLength 1000+ */+ invite_message?: string;}export interface PatchedUserProductList {@@ -36756,7 +36776,7 @@ export namespace Schemas {export interface SendInvitesRequest {/**- * Override the default email subject line. Defaults to a friendly prompt referencing the topic.+ * 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.* @maxLength 200*/subject?: string;diff --git a/services/mcp/src/generated/user_interviews/api.ts b/services/mcp/src/generated/user_interviews/api.tsindex 0f2589dcc070..d9efae373974 100644--- a/services/mcp/src/generated/user_interviews/api.ts+++ b/services/mcp/src/generated/user_interviews/api.ts@@ -40,6 +40,10 @@ export const userInterviewTopicsCreateBodyIntervieweeEmailsItemMax = 254export const userInterviewTopicsCreateBodyIntervieweeDistinctIdsItemMax = 400+export const userInterviewTopicsCreateBodyInviteSubjectMax = 255++export const userInterviewTopicsCreateBodyInviteMessageMax = 1000+export const UserInterviewTopicsCreateBody = /* @__PURE__ */ zod.object({interviewee_emails: zod.array(zod.string().max(userInterviewTopicsCreateBodyIntervieweeEmailsItemMax))@@ -58,6 +62,20 @@ export const UserInterviewTopicsCreateBody = /* @__PURE__ */ zod.object({.array(zod.string()).optional().describe('Ordered list of questions the voice agent should work through during the interview.'),+ invite_subject: zod+ .string()+ .max(userInterviewTopicsCreateBodyInviteSubjectMax)+ .optional()+ .describe(+ 'Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.'+ ),+ invite_message: zod+ .string()+ .max(userInterviewTopicsCreateBodyInviteMessageMax)+ .optional()+ .describe(+ 'Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.'+ ),})/**@@ -88,6 +106,10 @@ export const userInterviewTopicsPartialUpdateBodyIntervieweeEmailsItemMax = 254export const userInterviewTopicsPartialUpdateBodyIntervieweeDistinctIdsItemMax = 400+export const userInterviewTopicsPartialUpdateBodyInviteSubjectMax = 255++export const userInterviewTopicsPartialUpdateBodyInviteMessageMax = 1000+export const UserInterviewTopicsPartialUpdateBody = /* @__PURE__ */ zod.object({interviewee_emails: zod.array(zod.string().max(userInterviewTopicsPartialUpdateBodyIntervieweeEmailsItemMax))@@ -106,6 +128,20 @@ export const UserInterviewTopicsPartialUpdateBody = /* @__PURE__ */ zod.object({.array(zod.string()).optional().describe('Ordered list of questions the voice agent should work through during the interview.'),+ invite_subject: zod+ .string()+ .max(userInterviewTopicsPartialUpdateBodyInviteSubjectMax)+ .optional()+ .describe(+ 'Subject line for the invitation email. Plain text only — URLs, angle brackets, and control characters are rejected. Leave blank to use the default subject. Personalization is handled by the email template, so do not include placeholders.'+ ),+ invite_message: zod+ .string()+ .max(userInterviewTopicsPartialUpdateBodyInviteMessageMax)+ .optional()+ .describe(+ 'Intro message shown in the invitation email body, above the interview link. Plain prose only — URLs, angle brackets, and control characters are rejected (line breaks are allowed). Leave blank to use the default copy.'+ ),})/**@@ -199,7 +235,9 @@ export const UserInterviewTopicsSendInvitesCreateBody = /* @__PURE__ */ zod.obje.string().max(userInterviewTopicsSendInvitesCreateBodySubjectMax).optional()- .describe('Override the default email subject line. Defaults to a friendly prompt referencing the topic.'),+ .describe(+ "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."+ ),reply_to: zod.email().optional()diff --git a/services/mcp/src/tools/generated/user_interviews.ts b/services/mcp/src/tools/generated/user_interviews.tsindex 46727080ef42..c5b087cd4a62 100644--- a/services/mcp/src/tools/generated/user_interviews.ts+++ b/services/mcp/src/tools/generated/user_interviews.ts@@ -80,6 +80,12 @@ const userInterviewTopicsCreate = (): ToolBase<typeof UserInterviewTopicsCreateSif (params.questions !== undefined) {body['questions'] = params.questions}+ if (params.invite_subject !== undefined) {+ body['invite_subject'] = params.invite_subject+ }+ if (params.invite_message !== undefined) {+ body['invite_message'] = params.invite_message+ }const result = await context.api.request<Schemas.UserInterviewTopic>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/`,@@ -295,6 +301,12 @@ const userInterviewTopicsPartialUpdate = (): ToolBase<if (params.questions !== undefined) {body['questions'] = params.questions}+ if (params.invite_subject !== undefined) {+ body['invite_subject'] = params.invite_subject+ }+ if (params.invite_message !== undefined) {+ body['invite_message'] = params.invite_message+ }const result = await context.api.request<Schemas.UserInterviewTopic>({method: 'PATCH',path: `/api/projects/${encodeURIComponent(String(projectId))}/user_interview_topics/${encodeURIComponent(String(params.id))}/`,