: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(surveys): accept and sanitize intro screen translations (#116300)
Lucas Fariae39956ed255d
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex 4edde2c7c672..bfa47fa2829e 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -135,9 +135,7 @@ SURVEY_QUESTION_HTML_FIELDS = (SURVEY_TRANSLATION_HTML_FIELDS = ("name","description",- "thankYouMessageHeader",- "thankYouMessageDescription",- "thankYouMessageCloseButtonText",+ *SURVEY_APPEARANCE_HTML_FIELDS,*SURVEY_QUESTION_HTML_FIELDS,)@@ -224,9 +222,7 @@ def sanitize_survey_question(question: dict[str, Any]) -> dict[str, Any]:SURVEY_API_TRANSLATION_FIELDS = frozenset(["name",- "thankYouMessageHeader",- "thankYouMessageDescription",- "thankYouMessageCloseButtonText",+ *SURVEY_APPEARANCE_HTML_FIELDS,])FIELDS_NOT_APPLICABLE_TO_EXTERNAL_SURVEYS = [@@ -234,11 +230,6 @@ FIELDS_NOT_APPLICABLE_TO_EXTERNAL_SURVEYS = ["targeting_flag_filters",]SURVEY_TRANSLATION_DRAFT_FIELDS = ("name", "description", "type", "appearance", "questions", "translations")-SURVEY_TRANSLATION_DRAFT_APPEARANCE_FIELDS = (- "thankYouMessageHeader",- "thankYouMessageDescription",- "thankYouMessageCloseButtonText",-)SURVEY_TRANSLATION_DRAFT_QUESTION_FIELDS = ("id","type",@@ -278,7 +269,7 @@ class GenerateSurveyTranslationsRequestSerializer(serializers.Serializer):appearance = draft.get("appearance")if isinstance(appearance, dict):draft["appearance"] = {- field: appearance[field] for field in SURVEY_TRANSLATION_DRAFT_APPEARANCE_FIELDS if field in appearance+ field: appearance[field] for field in SURVEY_APPEARANCE_HTML_FIELDS if field in appearance}questions = draft.get("questions")@@ -303,6 +294,15 @@ class GeneratedSurveyRootTranslationSerializer(serializers.Serializer):thankYouMessageCloseButtonText = serializers.CharField(required=False, allow_blank=True, help_text="Translated thank-you close button text.")+ introScreenHeader = serializers.CharField(+ required=False, allow_blank=True, help_text="Translated intro screen header."+ )+ introScreenDescription = serializers.CharField(+ required=False, allow_blank=True, help_text="Translated intro screen description."+ )+ introScreenButtonText = serializers.CharField(+ required=False, allow_blank=True, help_text="Translated intro screen button text."+ )class GeneratedSurveyQuestionTranslationSerializer(serializers.Serializer):@@ -1122,6 +1122,10 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):if thank_you_description_content_type and thank_you_description_content_type not in ["text", "html"]:raise serializers.ValidationError("thankYouMessageDescriptionContentType must be one of ['text', 'html']")+ intro_screen_description_content_type = value.get("introScreenDescriptionContentType")+ if intro_screen_description_content_type and intro_screen_description_content_type not in ["text", "html"]:+ raise serializers.ValidationError("introScreenDescriptionContentType must be one of ['text', 'html']")+survey_popup_delay_seconds = value.get("surveyPopupDelaySeconds")if survey_popup_delay_seconds and survey_popup_delay_seconds < 0:raise serializers.ValidationError("Survey popup delay seconds must be a positive integer")@@ -1246,13 +1250,7 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):raise serializers.ValidationError(f"Translation for '{raw_lang_code}' must be an object")cleaned_translation: dict[str, str] = {}- for field in [- "name",- "description",- "thankYouMessageHeader",- "thankYouMessageDescription",- "thankYouMessageCloseButtonText",- ]:+ for field in ["name", "description", *SURVEY_APPEARANCE_HTML_FIELDS]:if field in translation_data:if not isinstance(translation_data[field], str):raise serializers.ValidationError(diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex 9137c124d759..1f54f9044926 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -556,7 +556,10 @@ class TestSurvey(APIBaseTest):],appearance={"introScreenDescription": '<strong>Welcome</strong><img src="invalid" onerror="void 0">'},translations={- "es": {"thankYouMessageDescription": '<strong>Gracias</strong><img src="invalid" onerror="void 0">'}+ "es": {+ "thankYouMessageDescription": '<strong>Gracias</strong><img src="invalid" onerror="void 0">',+ "introScreenDescription": '<strong>Bienvenido</strong><img src="invalid" onerror="void 0">',+ }},)@@ -568,6 +571,7 @@ class TestSurvey(APIBaseTest):assert "link" not in serialized_survey["questions"][0]assert "<strong>Detalles</strong>" in serialized_survey["questions"][0]["translations"]["es"]["description"]assert "<strong>Gracias</strong>" in serialized_survey["translations"]["es"]["thankYouMessageDescription"]+ assert "<strong>Bienvenido</strong>" in serialized_survey["translations"]["es"]["introScreenDescription"]assert "onerror" not in json.dumps(serialized_survey)def test_detail_payload_sanitizes_stored_survey_html(self) -> None:@@ -586,7 +590,10 @@ class TestSurvey(APIBaseTest):],appearance={"introScreenDescription": '<strong>Welcome</strong><img src="invalid" onerror="void 0">'},translations={- "es": {"thankYouMessageDescription": '<strong>Gracias</strong><img src="invalid" onerror="void 0">'}+ "es": {+ "thankYouMessageDescription": '<strong>Gracias</strong><img src="invalid" onerror="void 0">',+ "introScreenDescription": '<strong>Bienvenido</strong><img src="invalid" onerror="void 0">',+ }},)@@ -596,6 +603,7 @@ class TestSurvey(APIBaseTest):assert "<strong>Welcome</strong>" in response.json()["appearance"]["introScreenDescription"]assert "<strong>Details</strong>" in response.json()["questions"][0]["description"]assert "<strong>Gracias</strong>" in response.json()["translations"]["es"]["thankYouMessageDescription"]+ assert "<strong>Bienvenido</strong>" in response.json()["translations"]["es"]["introScreenDescription"]assert "onerror" not in json.dumps(response.json())def test_sdk_payload_strips_non_runtime_question_fields(self) -> None:@@ -661,6 +669,17 @@ class TestSurvey(APIBaseTest):assert "default" not in resultassert "en" not in result+ def test_sdk_payload_keeps_intro_screen_translation_fields(self) -> None:+ intro_fields = {+ "introScreenHeader": "Bienvenido",+ "introScreenDescription": "Dos preguntas rápidas",+ "introScreenButtonText": "Comenzar",+ }++ result = get_survey_api_translations({"es": {**intro_fields, "unknownField": "dropped"}}, base_language="en")++ assert result == {"es": intro_fields}+@override_settings(CLOUD_DEPLOYMENT="US", GEMINI_API_KEY="test-key")@patch("products.surveys.backend.api.survey.generate_survey_translation")def test_generate_translations_returns_draft_patch(self, mock_generate_survey_translation):@@ -911,6 +930,25 @@ class TestSurvey(APIBaseTest):assert "<strong>Cerrar</strong>" in survey.translations["es"]["thankYouMessageCloseButtonText"]assert "<script>" not in survey.translations["es"]["thankYouMessageCloseButtonText"]+ @parameterized.expand([("introScreenHeader",), ("introScreenDescription",), ("introScreenButtonText",)])+ def test_intro_screen_translations_are_persisted_and_sanitized(self, field: str):+ response = self.client.post(+ f"/api/projects/{self.team.id}/surveys/",+ data={+ "name": "Survey",+ "type": "popover",+ "questions": [{"type": "open", "question": "Question?"}],+ "translations": {"es": {field: "<em>Bienvenido</em><script>xss()</script>"}},+ },+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ survey = Survey.objects.get(id=response.json()["id"])+ assert survey.translations is not None+ assert "<em>Bienvenido</em>" in survey.translations["es"][field]+ assert "<script>" not in survey.translations["es"][field]+def test_inline_question_translations_sanitize_all_fields(self):response = self.client.post(f"/api/projects/{self.team.id}/surveys/",@@ -4598,24 +4636,21 @@ class TestSurveyQuestionValidationWithEnterpriseFeatures(APIBaseTest):assert response.status_code == status.HTTP_201_CREATED, response_dataassert response_data["appearance"]["thankYouMessageDescriptionContentType"] == "text"- def test_validate_thank_you_description_content_type(self):+ @parameterized.expand([("thankYouMessageDescriptionContentType",), ("introScreenDescriptionContentType",)])+ def test_validate_description_content_type(self, content_type_field: str):response = self.client.post(f"/api/projects/{self.team.id}/surveys/",data={"name": "Notebooks beta release survey","description": "Get feedback on the new notebooks feature","type": "popover",- "appearance": {- "thankYouMessageHeader": "Thanks for your feedback!",- "thankYouMessageDescription": "This is a thank you message",- "thankYouMessageDescriptionContentType": "text/html",- },+ "appearance": {content_type_field: "text/html"},},format="json",)response_data = response.json()assert response.status_code == status.HTTP_400_BAD_REQUEST, response_data- assert response_data["detail"] == "thankYouMessageDescriptionContentType must be one of ['text', 'html']"+ assert response_data["detail"] == f"{content_type_field} must be one of ['text', 'html']"def test_create_survey_with_survey_popup_delay(self):response = self.client.post(diff --git a/products/surveys/backend/models.py b/products/surveys/backend/models.pyindex 278ad4c28a2f..423ec0777270 100644--- a/products/surveys/backend/models.py+++ b/products/surveys/backend/models.py@@ -287,7 +287,7 @@ class Survey(FileSystemSyncMixin, RootTeamMixin, UUIDTModel):# The SDK does not read this field — base text is always the rendering fallback when no translation matches.base_language = models.CharField(max_length=20, default="en")# Translations for multi-language support- # Format: { [languageCode]: { name: string, description: string, thankYouMessageHeader: string, thankYouMessageDescription: string, thankYouMessageCloseButtonText: string, ... } }+ # Format: { [languageCode]: { name: string, description: string, thankYouMessageHeader: string, thankYouMessageDescription: string, thankYouMessageCloseButtonText: string, introScreenHeader: string, introScreenDescription: string, introScreenButtonText: string, ... } }# Language codes must be canonical BCP-47-ish strings (e.g. "es", "es-MX"). Aliases like "english" or "default" are rejected by the API.translations = models.JSONField(blank=True, null=True)diff --git a/products/surveys/backend/test_translation.py b/products/surveys/backend/test_translation.pyindex 09667f7d7dea..8646735fbbcf 100644--- a/products/surveys/backend/test_translation.py+++ b/products/surveys/backend/test_translation.py@@ -79,7 +79,7 @@ def test_generate_survey_translation_preserves_manual_translations(mock_generate@patch("products.surveys.backend.translation.generate_structured_output")-def test_generate_survey_translation_includes_submit_and_back_button_labels(+def test_generate_survey_translation_includes_button_labels_and_intro_screen(mock_generate_structured_output: Mock,) -> None:mock_generate_structured_output.return_value = (@@ -88,6 +88,9 @@ def test_generate_survey_translation_includes_submit_and_back_button_labels("root": {"submitButtonText": "Enviar","backButtonText": "Atras",+ "introScreenHeader": "Hola",+ "introScreenDescription": "Dos preguntas",+ "introScreenButtonText": "Empezar",},"questions": [],}@@ -97,7 +100,15 @@ def test_generate_survey_translation_includes_submit_and_back_button_labels(survey = {"name": "Customer feedback","type": "popover",- "appearance": {"submitButtonText": "Submit", "allowGoBack": True, "backButtonText": "Back"},+ "appearance": {+ "submitButtonText": "Submit",+ "allowGoBack": True,+ "backButtonText": "Back",+ "displayIntroScreen": True,+ "introScreenHeader": "Intro headline source",+ "introScreenDescription": "Intro description source",+ "introScreenButtonText": "Intro button source",+ },"translations": {},"questions": [],}@@ -109,9 +120,26 @@ def test_generate_survey_translation_includes_submit_and_back_button_labels(team_id=1,)- assert translations == {"es": {"submitButtonText": "Enviar", "backButtonText": "Atras"}}- assert "translations.es.submitButtonText" in generated_paths- assert "translations.es.backButtonText" in generated_paths+ assert translations == {+ "es": {+ "submitButtonText": "Enviar",+ "backButtonText": "Atras",+ "introScreenHeader": "Hola",+ "introScreenDescription": "Dos preguntas",+ "introScreenButtonText": "Empezar",+ }+ }+ assert {+ "translations.es.submitButtonText",+ "translations.es.backButtonText",+ "translations.es.introScreenHeader",+ "translations.es.introScreenDescription",+ "translations.es.introScreenButtonText",+ } <= set(generated_paths)+ llm_input = str(mock_generate_structured_output.call_args)+ assert "Intro headline source" in llm_input+ assert "Intro description source" in llm_input+ assert "Intro button source" in llm_input@patch("products.surveys.backend.translation.generate_structured_output")diff --git a/products/surveys/backend/translation.py b/products/surveys/backend/translation.pyindex 6f9cabafcdac..c68132e012db 100644--- a/products/surveys/backend/translation.py+++ b/products/surveys/backend/translation.py@@ -15,6 +15,9 @@ class SurveyRootTranslation(BaseModel):thankYouMessageHeader: str | None = NonethankYouMessageDescription: str | None = NonethankYouMessageCloseButtonText: str | None = None+ introScreenHeader: str | None = None+ introScreenDescription: str | None = None+ introScreenButtonText: str | None = NonesubmitButtonText: str | None = NonebackButtonText: str | None = None@@ -59,6 +62,9 @@ def _root_source(survey: dict[str, Any]) -> dict[str, Any]:"thankYouMessageHeader": appearance.get("thankYouMessageHeader"),"thankYouMessageDescription": appearance.get("thankYouMessageDescription"),"thankYouMessageCloseButtonText": appearance.get("thankYouMessageCloseButtonText"),+ "introScreenHeader": appearance.get("introScreenHeader"),+ "introScreenDescription": appearance.get("introScreenDescription"),+ "introScreenButtonText": appearance.get("introScreenButtonText"),"submitButtonText": appearance.get("submitButtonText"),"backButtonText": appearance.get("backButtonText"),"translations": survey.get("translations") or {},diff --git a/products/surveys/frontend/generated/api.schemas.ts b/products/surveys/frontend/generated/api.schemas.tsindex 782e2390b5d5..e7b91c4dfa45 100644--- a/products/surveys/frontend/generated/api.schemas.ts+++ b/products/surveys/frontend/generated/api.schemas.ts@@ -2046,6 +2046,12 @@ export interface GeneratedSurveyRootTranslationApi {thankYouMessageDescription?: string/** Translated thank-you close button text. */thankYouMessageCloseButtonText?: string+ /** Translated intro screen header. */+ introScreenHeader?: string+ /** Translated intro screen description. */+ introScreenDescription?: string+ /** Translated intro screen button text. */+ introScreenButtonText?: string}/**diff --git a/products/surveys/mcp/tools.yaml b/products/surveys/mcp/tools.yamlindex e64bd0f19ca0..17ae9323d1d2 100644--- a/products/surveys/mcp/tools.yaml+++ b/products/surveys/mcp/tools.yaml@@ -108,8 +108,8 @@ tools:translations:description: >Optional survey-level translations keyed by language code. Use for translated survey name,- description, and thank-you message fields. Question text translations belong inside each question's- translations object.+ description, thank-you message, and intro screen fields. Question text translations belong inside+ each question's translations object.form_content:description: >Optional hosted-form content configuration for external_survey forms. Only include this when thediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7eca560eb182..083cd092e75d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -53420,6 +53420,12 @@ export namespace Schemas {thankYouMessageDescription?: string;/** Translated thank-you close button text. */thankYouMessageCloseButtonText?: string;+ /** Translated intro screen header. */+ introScreenHeader?: string;+ /** Translated intro screen description. */+ introScreenDescription?: string;+ /** Translated intro screen button text. */+ introScreenButtonText?: string;}/**diff --git a/services/mcp/src/tools/generated/surveys.ts b/services/mcp/src/tools/generated/surveys.tsindex e4e30ea45b54..59ba10e97290 100644--- a/services/mcp/src/tools/generated/surveys.ts+++ b/services/mcp/src/tools/generated/surveys.ts@@ -54,7 +54,7 @@ const SurveyCreateSchema = () => {'Allows an external_survey form to be embedded in an iframe. Use only when the user explicitly asks for iframe embedding.'),translations: SurveysCreateBody.shape['translations'].describe(- "Optional survey-level translations keyed by language code. Use for translated survey name, description, and thank-you message fields. Question text translations belong inside each question's translations object."+ "Optional survey-level translations keyed by language code. Use for translated survey name, description, thank-you message, and intro screen fields. Question text translations belong inside each question's translations object."),form_content: SurveysCreateBody.shape['form_content'].describe('Optional hosted-form content configuration for external_survey forms. Only include this when the user explicitly asks to customize the hosted form content beyond the standard question flow.'diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-create.jsonindex 6f72a5f7f321..d64150883221 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/survey-create.json@@ -1181,7 +1181,7 @@"description": "Target an in-app survey to a subset of users by person, group, or cohort properties. Pass one or more rules in groups[].properties[], each with key, value, operator, and an optional type. Use this instead of conditions for property targeting. Do not use this for external_survey forms. Cohorts with behavioral filters cannot be used directly. Use a supported static cohort snapshot only with user approval; never remove targeting rules to work around validation."},"translations": {- "description": "Optional survey-level translations keyed by language code. Use for translated survey name, description, and thank-you message fields. Question text translations belong inside each question's translations object."+ "description": "Optional survey-level translations keyed by language code. Use for translated survey name, description, thank-you message, and intro screen fields. Question text translations belong inside each question's translations object."},"type": {"description": "Survey type. Use popover for most in-app surveys, widget for always-available feedback entrypoints, external_survey for hosted forms with a shareable public URL, and api only for headless custom implementations.",