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.

53.3 KB
Raw Blame
"""
Simple async test for the survey creation MaxTool.
"""

import os

import pytest
from posthog.test.base import BaseTest

from asgiref.sync import sync_to_async
from langchain_core.runnables import RunnableConfig
from parameterized import parameterized

from posthog.models import Organization, Project, Team

from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_analytics.backend.facade.models import Insight
from products.surveys.backend.models import Survey

from .max_tools import CreateSurveyTool, EditSurveyTool, SimpleSurveyQuestion, SurveyAnalysisTool


async def create_test_team(organization: Organization, name: str) -> Team:
    project_id = await sync_to_async(Team.objects.increment_id_sequence)()
    project = await Project.objects.acreate(id=project_id, organization=organization)
    return await Team.objects.acreate(id=project.id, project=project, organization=organization, name=name)


class TestSurveyCreatorTool(BaseTest):
    def setUp(self):
        super().setUp()
        os.environ["OPENAI_API_KEY"] = "test-api-key"
        self._config: RunnableConfig = {
            "configurable": {
                "team": self.team,
                "user": self.user,
            },
        }

    def tearDown(self):
        super().tearDown()
        if "OPENAI_API_KEY" in os.environ:
            del os.environ["OPENAI_API_KEY"]

    def _setup_tool(self):
        return CreateSurveyTool(team=self.team, user=self.user, config=self._config)

    def test_get_team_survey_config(self):
        from products.surveys.backend.max_tools import get_team_survey_config

        config = get_team_survey_config(self.team)

        assert "appearance" in config
        assert "default_settings" in config
        assert config["default_settings"]["type"] == "popover"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_arun_impl_success(self):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl(
            name="Test Survey",
            description="A simple test survey",
            questions=[
                SimpleSurveyQuestion(
                    type="open", question="How do you feel about our product?", description="Please share your thoughts"
                ),
            ],
        )

        assert "Survey" in content
        assert "created" in content
        assert "successfully" in content
        assert "survey_id" in artifact
        assert "survey_name" in artifact

        survey = await sync_to_async(Survey.objects.get)(id=artifact["survey_id"])
        assert survey.name == "Test Survey"
        assert survey.description == "A simple test survey"
        assert survey.type == "popover"
        assert survey.questions is not None
        assert len(survey.questions) == 1
        assert not survey.archived

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_arun_impl_no_questions_validation(self):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl(name="Test Survey", questions=[])

        assert "Survey must have at least one question" in content
        assert artifact["error"] == "validation_failed"
        assert "No questions provided" in artifact["error_message"]

    @parameterized.expand([("single_choice",), ("multiple_choice",)])
    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_arun_impl_choice_question_without_choices_validation(self, question_type):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl(
            name="Test Survey",
            questions=[SimpleSurveyQuestion(type=question_type, question="Pick one")],
        )

        assert "Survey validation failed" in content
        assert artifact["error"] == "validation_failed"
        assert "choices" in artifact["error_message"]

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_arun_impl_with_launch(self):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl(
            name="Launch Survey",
            description="A survey to launch",
            questions=[SimpleSurveyQuestion(type="open", question="Test question?")],
            should_launch=True,
        )

        assert "Survey" in content
        assert "successfully" in content

        survey = await sync_to_async(Survey.objects.get)(id=artifact["survey_id"])
        assert survey.start_date is not None

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_create_survey_with_feature_flag(self):
        tool = self._setup_tool()

        flag = await sync_to_async(FeatureFlag.objects.create)(
            team=self.team,
            key="test-feature",
            name="Test Feature",
            created_by=self.user,
            filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
        )

        content, artifact = await tool._arun_impl(
            name="Feature Flag Survey",
            description="Survey for users with test feature",
            questions=[SimpleSurveyQuestion(type="csat", question="How satisfied are you with the new feature?")],
            linked_flag_id=flag.id,
        )

        assert "Survey" in content
        assert "successfully" in content

        survey = await sync_to_async(Survey.objects.select_related("linked_flag").get)(id=artifact["survey_id"])
        assert survey.name == "Feature Flag Survey"
        assert survey.linked_flag_id == flag.id

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_create_survey_rejects_linked_flag_from_another_organization(self):
        other_organization = await Organization.objects.acreate(name="Other Organization")
        other_team = await create_test_team(other_organization, "Other Team")
        other_flag = await FeatureFlag.objects.acreate(
            team=other_team,
            key="other-organization-feature",
            created_by=self.user,
        )

        result = await self._setup_tool().ainvoke(
            {
                "name": "Cross-organization survey",
                "questions": [{"type": "open", "question": "How is it going?"}],
                "linked_flag_id": other_flag.id,
            }
        )

        assert "Survey validation failed" in result
        assert not await Survey.objects.filter(team=self.team, name="Cross-organization survey").aexists()

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_create_survey_with_feature_flag_variant(self):
        tool = self._setup_tool()

        flag = await sync_to_async(FeatureFlag.objects.create)(
            team=self.team,
            key="ab-test-feature",
            name="A/B Test Feature",
            created_by=self.user,
            filters={
                "groups": [{"properties": [], "rollout_percentage": 100}],
                "multivariate": {
                    "variants": [
                        {"key": "control", "rollout_percentage": 50},
                        {"key": "treatment", "rollout_percentage": 50},
                    ]
                },
            },
        )

        content, artifact = await tool._arun_impl(
            name="A/B Test Control Survey",
            description="Survey for users in control variant",
            questions=[
                SimpleSurveyQuestion(
                    type="single_choice",
                    question="Which version do you prefer?",
                    choices=["Version A", "Version B", "No preference"],
                )
            ],
            linked_flag_id=flag.id,
            linked_flag_variant="control",
        )

        assert "Survey" in content
        assert "successfully" in content

        survey = await sync_to_async(Survey.objects.select_related("linked_flag").get)(id=artifact["survey_id"])
        assert survey.name == "A/B Test Control Survey"
        assert survey.linked_flag_id == flag.id
        assert survey.conditions is not None
        assert survey.conditions["linkedFlagVariant"] == "control"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_create_survey_with_feature_flag_variant_any(self):
        tool = self._setup_tool()

        flag = await sync_to_async(FeatureFlag.objects.create)(
            team=self.team,
            key="multivariate-feature",
            name="Multivariate Feature",
            created_by=self.user,
            filters={
                "groups": [{"properties": [], "rollout_percentage": 100}],
                "multivariate": {
                    "variants": [
                        {"key": "variant-a", "rollout_percentage": 33},
                        {"key": "variant-b", "rollout_percentage": 33},
                        {"key": "variant-c", "rollout_percentage": 34},
                    ]
                },
            },
        )

        content, artifact = await tool._arun_impl(
            name="All Variants Survey",
            description="Survey for all users with the feature enabled",
            questions=[SimpleSurveyQuestion(type="open", question="How is the new feature working for you?")],
            linked_flag_id=flag.id,
            linked_flag_variant="any",
        )

        assert "Survey" in content
        assert "successfully" in content

        survey = await sync_to_async(Survey.objects.select_related("linked_flag").get)(id=artifact["survey_id"])
        assert survey.name == "All Variants Survey"
        assert survey.linked_flag_id == flag.id
        assert survey.conditions is not None
        assert survey.conditions["linkedFlagVariant"] == "any"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_is_dangerous_operation_with_launch(self):
        tool = self._setup_tool()
        is_dangerous = await tool.is_dangerous_operation(should_launch=True)
        assert is_dangerous is True

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_is_dangerous_operation_without_launch(self):
        tool = self._setup_tool()
        is_dangerous = await tool.is_dangerous_operation(should_launch=False)
        assert is_dangerous is False

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_format_dangerous_operation_preview(self):
        tool = self._setup_tool()

        preview = await tool.format_dangerous_operation_preview(
            name="NPS Survey",
            questions=[
                SimpleSurveyQuestion(type="nps", question="How likely are you to recommend us?"),
                SimpleSurveyQuestion(type="open", question="Why?", optional=True),
            ],
            should_launch=True,
        )

        assert "Create and launch" in preview
        assert "NPS Survey" in preview
        assert "2 question(s)" in preview
        assert "start collecting responses" in preview

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_create_survey_with_linked_insight(self):
        insight = await sync_to_async(Insight.objects.create)(
            team=self.team,
            name="Test Funnel",
            created_by=self.user,
        )

        tool = CreateSurveyTool(
            team=self.team,
            user=self.user,
            config={
                **self._config,
                "configurable": {
                    **self._config.get("configurable", {}),
                    "contextual_tools": {"create_survey": {"insight_id": insight.id}},
                },
            },
        )

        content, artifact = await tool._arun_impl(
            name="Funnel Survey",
            description="Survey for funnel conversion",
            questions=[SimpleSurveyQuestion(type="open", question="Why didn't you complete the checkout?")],
        )

        assert "Survey" in content
        assert "successfully" in content

        survey = await sync_to_async(Survey.objects.select_related("linked_insight").get)(id=artifact["survey_id"])
        assert survey.name == "Funnel Survey"
        assert survey.linked_insight_id == insight.id

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_create_nps_survey_builds_correct_question(self):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl(
            name="NPS Survey",
            questions=[
                SimpleSurveyQuestion(
                    type="nps",
                    question="How likely are you to recommend us?",
                    lower_bound_label="Not likely at all",
                    upper_bound_label="Extremely likely",
                )
            ],
        )

        assert "successfully" in content
        survey = await sync_to_async(Survey.objects.get)(id=artifact["survey_id"])
        assert survey.questions is not None
        assert len(survey.questions) > 0

        q = survey.questions[0]
        assert q["type"] == "rating"
        assert q["scale"] == 10
        assert q["display"] == "number"
        assert q["lowerBoundLabel"] == "Not likely at all"
        assert q["upperBoundLabel"] == "Extremely likely"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_create_survey_with_url_targeting(self):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl(
            name="Pricing Feedback",
            questions=[SimpleSurveyQuestion(type="open", question="Is our pricing clear?")],
            target_url="/pricing",
            target_url_match="contains",
        )

        assert "successfully" in content
        survey = await sync_to_async(Survey.objects.get)(id=artifact["survey_id"])

        assert survey.conditions is not None
        assert survey.conditions["url"] == "/pricing"
        assert survey.conditions["urlMatchType"] == "icontains"

    @parameterized.expand(
        [
            ("always_without_conditions", {"schedule": "always"}, "always", None, None, "no display conditions"),
            (
                "always_with_url",
                {"schedule": "always", "target_url": "/pricing"},
                "always",
                None,
                None,
                "every time its display conditions are met",
            ),
            ("recurring_defaults", {"schedule": "recurring"}, "recurring", 2, 90, None),
            (
                "recurring_custom",
                {"schedule": "recurring", "iteration_count": 4, "iteration_frequency_days": 30},
                "recurring",
                4,
                30,
                None,
            ),
            ("unset", {}, "once", None, None, None),
            (
                "iteration_values_without_schedule",
                {"iteration_count": 4, "iteration_frequency_days": 30},
                "recurring",
                4,
                30,
                None,
            ),
            (
                "always_with_wait_period",
                {"schedule": "always", "wait_period_days": 7},
                "always",
                None,
                None,
                "shows again every 7 days",
            ),
        ]
    )
    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_create_survey_schedule(
        self, _name, kwargs, expected_schedule, expected_count, expected_frequency, expected_warning
    ):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl(
            name="Feedback", questions=[SimpleSurveyQuestion(type="open", question="Any feedback?")], **kwargs
        )

        survey = await sync_to_async(Survey.objects.get)(id=artifact["survey_id"])
        assert survey.schedule == expected_schedule
        assert survey.iteration_count == expected_count
        assert survey.iteration_frequency_days == expected_frequency
        if expected_warning:
            assert expected_warning in content
        else:
            assert "display conditions" not in content
        if kwargs.get("wait_period_days"):
            assert "Add a wait period" not in content

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_create_external_survey(self):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl(
            name="Hosted Feedback",
            questions=[SimpleSurveyQuestion(type="open", question="How was your experience?")],
            survey_type="external_survey",
        )

        assert "successfully" in content
        assert "shareable link" in content
        assert artifact["survey_type"] == "external_survey"

        survey = await sync_to_async(Survey.objects.get)(id=artifact["survey_id"])
        assert survey.type == "external_survey"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_create_external_survey_ignores_in_app_targeting(self):
        tool = self._setup_tool()

        # Targeting is invalid for external surveys server-side; the tool must drop it rather than
        # pass it through and trigger a validation error.
        flag = await sync_to_async(FeatureFlag.objects.create)(
            team=self.team,
            key="hosted-flag",
            name="Hosted Flag",
            created_by=self.user,
        )

        content, artifact = await tool._arun_impl(
            name="Hosted Feedback",
            questions=[SimpleSurveyQuestion(type="open", question="How was your experience?")],
            survey_type="external_survey",
            target_url="/pricing",
            target_url_match="contains",
            linked_flag_id=flag.id,
            wait_period_days=7,
        )

        assert "successfully" in content
        survey = await sync_to_async(Survey.objects.get)(id=artifact["survey_id"])
        assert survey.type == "external_survey"
        assert survey.linked_flag_id is None
        assert not survey.conditions

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_create_survey_sanitizes_question_html(self):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl(
            name="Sanitized Survey",
            questions=[
                SimpleSurveyQuestion(
                    type="link",
                    question="<b>Click here</b><script>alert('xss')</script>",
                    description="<i>Learn more</i><script>evil()</script>",
                    button_text="<strong>Open</strong><script>bad()</script>",
                    link="https://example.com",
                )
            ],
        )

        assert "successfully" in content
        survey = await sync_to_async(Survey.objects.get)(id=artifact["survey_id"])
        assert survey.questions is not None

        question = survey.questions[0]
        assert "<b>Click here</b>" in question["question"]
        assert "<script>" not in question["question"]
        assert "<i>Learn more</i>" in question["description"]
        assert "<script>" not in question["description"]
        assert "<strong>Open</strong>" in question["buttonText"]
        assert "<script>" not in question["buttonText"]

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_create_survey_rejects_javascript_link(self):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl(
            name="Unsafe Survey",
            questions=[
                SimpleSurveyQuestion(
                    type="link",
                    question="Open this link",
                    link="javascript:alert('xss')",
                )
            ],
        )

        assert "validation failed" in content.lower()
        assert artifact["error"] == "validation_failed"
        assert "schemes" in artifact["error_message"]
        assert not await sync_to_async(Survey.objects.filter(name="Unsafe Survey").exists)()


class TestSurveyAnalysisTool(BaseTest):
    def setUp(self):
        super().setUp()
        self._config: RunnableConfig = {
            "configurable": {
                "team": self.team,
                "user": self.user,
            },
        }

    def _setup_tool(self):
        return SurveyAnalysisTool(
            team=self.team,
            user=self.user,
            config=self._config,
        )

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_arun_impl_no_survey_id(self):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl()

        assert "no survey id provided" in content.lower()
        assert artifact["error"] == "no_survey_id"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_arun_impl_survey_not_found(self):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl(survey_id="00000000-0000-0000-0000-000000000000")

        assert "not found" in content.lower()
        assert artifact["error"] == "not_found"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_arun_impl_no_responses(self):
        from unittest.mock import patch

        with patch("products.surveys.backend.max_tools.fetch_responses", return_value=[]):
            survey = await sync_to_async(Survey.objects.create)(
                team=self.team,
                name="Test Survey",
                type="popover",
                questions=[{"type": "open", "question": "Test?", "id": "q1"}],
                created_by=self.user,
            )
            tool = self._setup_tool()

            content, artifact = await tool._arun_impl(survey_id=str(survey.id))

            assert "no open-ended responses" in content.lower()
            assert artifact["response_count"] == 0

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_arun_impl_returns_formatted_responses(self):
        from unittest.mock import patch

        mock_responses = [
            "Love the app but need dark mode",
            "Mobile version is slow",
            "Great overall experience",
        ]

        with patch("products.surveys.backend.max_tools.fetch_responses", return_value=mock_responses):
            survey = await sync_to_async(Survey.objects.create)(
                team=self.team,
                name="Product Feedback Survey",
                type="popover",
                questions=[{"type": "open", "question": "How can we improve?", "id": "q1"}],
                created_by=self.user,
            )
            tool = self._setup_tool()

            content, artifact = await tool._arun_impl(survey_id=str(survey.id))

            assert "Product Feedback Survey" in content
            assert "3" in content
            assert "How can we improve?" in content
            assert "Love the app but need dark mode" in content
            assert "Mobile version is slow" in content
            assert "Great overall experience" in content
            assert "themes" in content.lower()
            assert "sentiment" in content.lower()

            assert artifact["survey_id"] == str(survey.id)
            assert artifact["survey_name"] == "Product Feedback Survey"
            assert artifact["response_count"] == 3

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_arun_impl_multiple_questions(self):
        from unittest.mock import patch

        with patch(
            "products.surveys.backend.max_tools.fetch_responses",
            side_effect=[
                ["Great UI", "Fast performance"],
                ["Add dark mode"],
            ],
        ):
            survey = await sync_to_async(Survey.objects.create)(
                team=self.team,
                name="Multi-Question Survey",
                type="popover",
                questions=[
                    {"type": "open", "question": "What do you like?", "id": "q1"},
                    {"type": "open", "question": "What could be better?", "id": "q2"},
                ],
                created_by=self.user,
            )
            tool = self._setup_tool()

            content, artifact = await tool._arun_impl(survey_id=str(survey.id))

            assert "What do you like?" in content
            assert "What could be better?" in content
            assert "Great UI" in content
            assert "Fast performance" in content
            assert "Add dark mode" in content
            assert artifact["response_count"] == 3

    def test_format_responses_for_analysis(self):
        from posthog.schema import SurveyAnalysisQuestionGroup, SurveyAnalysisResponseItem

        tool = self._setup_tool()

        question_groups = [
            SurveyAnalysisQuestionGroup(
                questionName="What do you think?",
                questionId="q1",
                responses=[
                    SurveyAnalysisResponseItem(responseText="Great product", isOpenEnded=True),
                    SurveyAnalysisResponseItem(responseText="Could be better", isOpenEnded=True),
                ],
            ),
        ]

        formatted = tool._format_responses_for_analysis(question_groups)

        assert 'Question: "What do you think?"' in formatted
        assert '- "Great product"' in formatted
        assert '- "Could be better"' in formatted

    def test_format_responses_for_analysis_empty_responses(self):
        from posthog.schema import SurveyAnalysisQuestionGroup

        tool = self._setup_tool()

        question_groups = [
            SurveyAnalysisQuestionGroup(
                questionName="Empty question",
                questionId="q1",
                responses=[],
            ),
        ]

        formatted = tool._format_responses_for_analysis(question_groups)

        assert 'Question: "Empty question"' in formatted
        assert "Responses: (none)" in formatted


class TestEditSurveyTool(BaseTest):
    def setUp(self):
        super().setUp()
        os.environ["OPENAI_API_KEY"] = "test-api-key"
        self._config: RunnableConfig = {
            "configurable": {
                "team": self.team,
                "user": self.user,
            },
        }

    def tearDown(self):
        super().tearDown()
        if "OPENAI_API_KEY" in os.environ:
            del os.environ["OPENAI_API_KEY"]

    def _setup_tool(self):
        return EditSurveyTool(team=self.team, user=self.user, config=self._config)

    async def _create_test_survey(self, **kwargs):
        defaults = {
            "team": self.team,
            "name": "Test Survey",
            "description": "A test survey",
            "type": "popover",
            "questions": [{"type": "open", "question": "Test question?", "id": "q1"}],
            "created_by": self.user,
        }
        defaults.update(kwargs)
        return await sync_to_async(Survey.objects.create)(**defaults)

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_name_description(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        content, artifact = await tool._arun_impl(
            survey_id=str(survey.id), name="Updated Name", description="Updated description"
        )

        assert "Updated Name" in content
        assert "updated_fields" in artifact
        assert "name" in artifact["updated_fields"]
        assert "description" in artifact["updated_fields"]

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.name == "Updated Name"
        assert updated_survey.description == "Updated description"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_questions(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        content, artifact = await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[
                SimpleSurveyQuestion(type="csat", question="New rating question?"),
                SimpleSurveyQuestion(type="open", question="Follow-up?", optional=True),
            ],
        )

        assert "updated successfully" in content
        assert "questions" in artifact["updated_fields"]

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.questions is not None
        assert len(updated_survey.questions) == 2
        assert updated_survey.questions[0]["type"] == "rating"
        assert updated_survey.questions[0]["scale"] == 5

    @parameterized.expand([("single_choice",), ("multiple_choice",)])
    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_choice_question_without_choices_validation(self, question_type):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        content, artifact = await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[SimpleSurveyQuestion(type=question_type, question="Pick one")],
        )

        assert "Survey validation failed" in content
        assert artifact["error"] == "validation_failed"
        assert "choices" in artifact["error_message"]

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_questions_preserves_ids_with_numeric_labels(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey(
            questions=[
                {"type": "open", "question": "First?", "id": "uuid-first"},
                {"type": "open", "question": "Second?", "id": "uuid-second"},
            ]
        )

        _, _ = await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[
                SimpleSurveyQuestion(id="1", type="open", question="First (edited)?"),
                SimpleSurveyQuestion(id="2", type="open", question="Second (edited)?"),
            ],
        )

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.questions is not None
        assert updated_survey.questions[0]["id"] == "uuid-first"
        assert updated_survey.questions[1]["id"] == "uuid-second"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_questions_reorder_preserves_ids(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey(
            questions=[
                {"type": "open", "question": "First?", "id": "uuid-first"},
                {"type": "open", "question": "Second?", "id": "uuid-second"},
            ]
        )

        _, _ = await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[
                SimpleSurveyQuestion(id="2", type="open", question="Second (now first)?"),
                SimpleSurveyQuestion(id="1", type="open", question="First (now second)?"),
            ],
        )

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.questions is not None
        assert updated_survey.questions[0]["id"] == "uuid-second"
        assert updated_survey.questions[1]["id"] == "uuid-first"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_questions_new_question_gets_fresh_id(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey(
            questions=[{"type": "open", "question": "Existing?", "id": "uuid-existing"}]
        )

        _, _ = await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[
                SimpleSurveyQuestion(id="1", type="open", question="Existing (kept)?"),
                SimpleSurveyQuestion(type="open", question="Brand new?"),
            ],
        )

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.questions is not None
        assert updated_survey.questions[0]["id"] == "uuid-existing"
        assert updated_survey.questions[1]["id"] != "uuid-existing"
        assert updated_survey.questions[1]["id"]  # non-empty fresh UUID

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_questions_remove_question_keeps_remaining_ids(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey(
            questions=[
                {"type": "open", "question": "First?", "id": "uuid-first"},
                {"type": "open", "question": "Second?", "id": "uuid-second"},
            ]
        )

        _, _ = await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[
                SimpleSurveyQuestion(id="1", type="open", question="First (kept)?"),
            ],
        )

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.questions is not None
        assert len(updated_survey.questions) == 1
        assert updated_survey.questions[0]["id"] == "uuid-first"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_url_targeting(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        content, artifact = await tool._arun_impl(
            survey_id=str(survey.id), target_url="/dashboard", target_url_match="contains"
        )

        assert "updated successfully" in content
        assert "conditions" in artifact["updated_fields"]

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.conditions is not None
        assert updated_survey.conditions["url"] == "/dashboard"
        assert updated_survey.conditions["urlMatchType"] == "icontains"

    @parameterized.expand(
        [
            (
                "flag_variant_preserves_url",
                False,
                {
                    "url": "app.heygen.com/(home|projects|voices|templates|labs)",
                    "urlMatchType": "regex",
                    "seenSurveyWaitPeriodInDays": 7,
                },
                {"linked_flag_variant": "control"},
                {
                    "url": "app.heygen.com/(home|projects|voices|templates|labs)",
                    "urlMatchType": "regex",
                    "seenSurveyWaitPeriodInDays": 7,
                    "linkedFlagVariant": "control",
                },
            ),
            (
                "url_preserves_flag_variant",
                True,
                {
                    "seenSurveyWaitPeriodInDays": 7,
                    "linkedFlagVariant": "control",
                },
                {
                    "target_url": "app.heygen.com/(home|projects|voices|templates|labs)",
                    "target_url_match": "regex",
                },
                {
                    "url": "app.heygen.com/(home|projects|voices|templates|labs)",
                    "urlMatchType": "regex",
                    "seenSurveyWaitPeriodInDays": 7,
                    "linkedFlagVariant": "control",
                },
            ),
        ]
    )
    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_targeting_updates_preserve_existing_conditions(
        self,
        _case_name,
        initial_linked_flag,
        initial_conditions,
        tool_kwargs,
        expected_conditions,
    ):
        tool = self._setup_tool()
        flag = await sync_to_async(FeatureFlag.objects.create)(
            team=self.team,
            key="survey-targeting-flag",
            created_by=self.user,
            filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
        )
        if "linked_flag_variant" in tool_kwargs:
            tool_kwargs = {**tool_kwargs, "linked_flag_id": flag.id}

        survey = await self._create_test_survey(
            linked_flag=flag if initial_linked_flag else None,
            conditions=initial_conditions,
        )

        content, artifact = await tool._arun_impl(survey_id=str(survey.id), **tool_kwargs)

        assert "updated successfully" in content
        assert "conditions" in artifact["updated_fields"]
        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        if "linked_flag_id" in tool_kwargs or initial_linked_flag:
            assert updated_survey.linked_flag_id == flag.id
        assert updated_survey.conditions == expected_conditions

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_rejects_linked_flag_from_another_organization(self):
        other_organization = await Organization.objects.acreate(name="Other Organization")
        other_team = await create_test_team(other_organization, "Other Team")
        other_flag = await FeatureFlag.objects.acreate(
            team=other_team,
            key="other-organization-feature",
            created_by=self.user,
        )
        survey = await self._create_test_survey()

        result = await self._setup_tool().ainvoke(
            {
                "survey_id": str(survey.id),
                "linked_flag_id": other_flag.id,
            }
        )

        assert "Survey validation failed" in result
        await survey.arefresh_from_db()
        assert survey.linked_flag_id is None

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_can_explicitly_remove_targeting(self):
        tool = self._setup_tool()
        flag = await sync_to_async(FeatureFlag.objects.create)(
            team=self.team,
            key="survey-targeting-flag",
            created_by=self.user,
            filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
        )
        survey = await self._create_test_survey(
            linked_flag=flag,
            conditions={
                "url": "/old-page",
                "urlMatchType": "icontains",
                "seenSurveyWaitPeriodInDays": 7,
                "linkedFlagVariant": "control",
            },
        )

        content, artifact = await tool._arun_impl(
            survey_id=str(survey.id),
            remove_url_targeting=True,
            remove_linked_flag=True,
            remove_wait_period=True,
        )

        assert "updated successfully" in content
        assert "linked_flag_id" in artifact["updated_fields"]
        assert "conditions" in artifact["updated_fields"]
        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.linked_flag_id is None
        assert updated_survey.conditions == {}

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_remove_targeting_is_dangerous(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        is_dangerous = await tool.is_dangerous_operation(survey_id=str(survey.id), remove_url_targeting=True)
        preview = await tool.format_dangerous_operation_preview(
            survey_id=str(survey.id), remove_url_targeting=True, remove_linked_flag=True
        )

        assert is_dangerous is True
        assert "Remove URL targeting" in preview
        assert "Remove linked feature flag targeting" in preview

    @parameterized.expand(
        [
            ("recurring_to_always", {"schedule": "always"}, "always", None, None),
            ("recurring_to_once", {"schedule": "once"}, "once", None, None),
            ("change_count_only", {"iteration_count": 5}, "recurring", 5, 30),
            ("count_below_current_iteration", {"iteration_count": 1}, "recurring", 3, 30),
        ]
    )
    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_schedule(self, _name, kwargs, expected_schedule, expected_count, expected_frequency):
        tool = self._setup_tool()
        survey = await self._create_test_survey(
            schedule="recurring", iteration_count=3, iteration_frequency_days=30, current_iteration=2
        )

        await tool._arun_impl(survey_id=str(survey.id), **kwargs)

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.schedule == expected_schedule
        assert updated_survey.iteration_count == expected_count
        assert updated_survey.iteration_frequency_days == expected_frequency

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_launch(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        content, artifact = await tool._arun_impl(survey_id=str(survey.id), launch=True)

        assert "launched" in content
        assert "start_date" in artifact["updated_fields"]

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.start_date is not None

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_stop(self):
        import django.utils.timezone

        tool = self._setup_tool()
        survey = await self._create_test_survey(start_date=django.utils.timezone.now())

        content, artifact = await tool._arun_impl(survey_id=str(survey.id), stop=True)

        assert "stopped" in content
        assert "end_date" in artifact["updated_fields"]

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.end_date is not None

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_archive(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        content, artifact = await tool._arun_impl(survey_id=str(survey.id), archive=True)

        assert "archived" in content
        assert "archived" in artifact["updated_fields"]

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.archived is True

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_not_found(self):
        tool = self._setup_tool()

        content, artifact = await tool._arun_impl(survey_id="00000000-0000-0000-0000-000000000000", name="New Name")

        assert "not found" in content.lower()
        assert artifact["error"] == "not_found"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_wrong_team(self):
        other_org = await sync_to_async(Organization.objects.create)(name="Other Org")
        other_team = await sync_to_async(Team.objects.create)(organization=other_org, name="Other Team")
        other_survey = await sync_to_async(Survey.objects.create)(
            team=other_team,
            name="Other Survey",
            type="popover",
            questions=[{"type": "open", "question": "Test?"}],
            created_by=self.user,
        )

        tool = self._setup_tool()
        content, artifact = await tool._arun_impl(survey_id=str(other_survey.id), name="Hacked Name")

        assert "not found" in content.lower()
        assert artifact["error"] == "not_found"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_no_updates(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        content, artifact = await tool._arun_impl(survey_id=str(survey.id))

        assert "no updates" in content.lower()
        assert artifact["error"] == "no_updates"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_stop_and_archive(self):
        import django.utils.timezone

        tool = self._setup_tool()
        survey = await self._create_test_survey(start_date=django.utils.timezone.now())

        content, artifact = await tool._arun_impl(survey_id=str(survey.id), stop=True, archive=True)

        assert "stopped" in content
        assert "archived" in content
        assert "end_date" in artifact["updated_fields"]
        assert "archived" in artifact["updated_fields"]

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.end_date is not None
        assert updated_survey.archived is True

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_sanitizes_question_html(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        content, artifact = await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[
                SimpleSurveyQuestion(
                    id="1",
                    type="open",
                    question="<b>Updated question</b><script>alert('xss')</script>",
                    description="<i>Details</i><script>bad()</script>",
                    button_text="<strong>Send</strong><script>evil()</script>",
                )
            ],
        )

        assert "updated successfully" in content
        assert "questions" in artifact["updated_fields"]

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.questions is not None
        question = updated_survey.questions[0]
        assert "<b>Updated question</b>" in question["question"]
        assert "<script>" not in question["question"]
        assert "<i>Details</i>" in question["description"]
        assert "<script>" not in question["description"]
        assert "<strong>Send</strong>" in question["buttonText"]
        assert "<script>" not in question["buttonText"]

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_rejects_javascript_link(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey(
            questions=[{"type": "link", "question": "Safe question?", "link": "https://example.com", "id": "q1"}]
        )

        content, artifact = await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[
                SimpleSurveyQuestion(
                    id="1",
                    type="link",
                    question="Unsafe question?",
                    link="javascript:alert('xss')",
                )
            ],
        )

        assert "validation failed" in content.lower()
        assert artifact["error"] == "validation_failed"
        assert "schemes" in artifact["error_message"]

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.questions is not None
        assert updated_survey.questions[0]["question"] == "Safe question?"
        assert updated_survey.questions[0]["link"] == "https://example.com"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_is_dangerous_operation_launch(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        is_dangerous = await tool.is_dangerous_operation(survey_id=str(survey.id), launch=True)
        assert is_dangerous is True

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_is_dangerous_operation_stop(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        is_dangerous = await tool.is_dangerous_operation(survey_id=str(survey.id), stop=True)
        assert is_dangerous is True

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_is_dangerous_operation_archive(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        is_dangerous = await tool.is_dangerous_operation(survey_id=str(survey.id), archive=True)
        assert is_dangerous is True

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_is_dangerous_operation_regular_update(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey()

        is_dangerous = await tool.is_dangerous_operation(
            survey_id=str(survey.id), name="New Name", description="New description"
        )
        assert is_dangerous is False

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_format_dangerous_operation_preview_launch(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey(name="My NPS Survey")

        preview = await tool.format_dangerous_operation_preview(survey_id=str(survey.id), launch=True)

        assert "Launch" in preview
        assert "My NPS Survey" in preview
        assert "start collecting responses" in preview

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_format_dangerous_operation_preview_multiple_actions(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey(name="Survey to Archive")

        preview = await tool.format_dangerous_operation_preview(survey_id=str(survey.id), stop=True, archive=True)

        assert "Stop" in preview
        assert "Archive" in preview
        assert "Survey to Archive" in preview

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_questions_preserve_ids_with_real_uuids(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey(
            questions=[
                {"type": "open", "question": "First?", "id": "026fdedd-f37c-4bf6-880b-c3aaa76778e8"},
                {"type": "open", "question": "Second?", "id": "84fb53eb-933c-498f-b567-1644fe75e549"},
            ]
        )

        await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[
                SimpleSurveyQuestion(
                    id="026fdedd-f37c-4bf6-880b-c3aaa76778e8", type="open", question="First (edited)?"
                ),
                SimpleSurveyQuestion(
                    id="84fb53eb-933c-498f-b567-1644fe75e549", type="open", question="Second (edited)?"
                ),
            ],
        )

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.questions is not None
        assert [q["id"] for q in updated_survey.questions] == [
            "026fdedd-f37c-4bf6-880b-c3aaa76778e8",
            "84fb53eb-933c-498f-b567-1644fe75e549",
        ]
        assert updated_survey.questions[0]["question"] == "First (edited)?"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_reorder_preserves_rating_scale_and_labels(self):
        # Regression: a reorder or text edit must not rebuild a rating question from the semantic
        # type map and silently flip its 10-point scale to csat's 5 or drop its custom labels.
        tool = self._setup_tool()
        survey = await self._create_test_survey(
            questions=[
                {"type": "open", "question": "What's your role?", "id": "role-uuid"},
                {
                    "type": "rating",
                    "scale": 10,
                    "display": "number",
                    "lowerBoundLabel": "Terrible",
                    "upperBoundLabel": "Great",
                    "question": "How's the experience so far?",
                    "id": "exp-uuid",
                },
            ]
        )

        await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[
                SimpleSurveyQuestion(id="exp-uuid", type="csat", question="How's the experience so far?"),
                SimpleSurveyQuestion(id="role-uuid", type="open", question="What's your role?"),
            ],
        )

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.questions is not None
        exp = next(q for q in updated_survey.questions if q["id"] == "exp-uuid")
        assert exp["type"] == "rating"
        assert exp["scale"] == 10
        assert exp["display"] == "number"
        assert exp["lowerBoundLabel"] == "Terrible"
        assert exp["upperBoundLabel"] == "Great"

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_can_change_rating_scale_explicitly(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey(
            questions=[{"type": "rating", "scale": 5, "display": "number", "question": "Rate it", "id": "r1"}]
        )

        await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[SimpleSurveyQuestion(id="r1", type="csat", question="Rate it", scale=10)],
        )

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.questions is not None
        assert updated_survey.questions[0]["id"] == "r1"
        assert updated_survey.questions[0]["scale"] == 10

    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_type_change_rebuilds_but_keeps_id(self):
        tool = self._setup_tool()
        survey = await self._create_test_survey(
            questions=[
                {"type": "rating", "scale": 10, "lowerBoundLabel": "Bad", "question": "Old rating", "id": "q-keep"}
            ]
        )

        await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[SimpleSurveyQuestion(id="q-keep", type="open", question="Now open text")],
        )

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.questions is not None
        assert updated_survey.questions[0]["id"] == "q-keep"
        assert updated_survey.questions[0]["type"] == "open"
        assert "scale" not in updated_survey.questions[0]
        assert "lowerBoundLabel" not in updated_survey.questions[0]

    @parameterized.expand(
        [
            ("two_positional_labels", "1", "1"),
            ("label_and_real_uuid", "1", "uuid-first"),
        ]
    )
    @pytest.mark.django_db
    @pytest.mark.asyncio
    async def test_edit_survey_questions_keep_ids_unique(self, _name, first_ref, second_ref):
        # Two inputs referencing the same existing question must not both claim its id.
        tool = self._setup_tool()
        survey = await self._create_test_survey(
            questions=[
                {"type": "open", "question": "First?", "id": "uuid-first"},
                {"type": "open", "question": "Second?", "id": "uuid-second"},
            ]
        )

        await tool._arun_impl(
            survey_id=str(survey.id),
            questions=[
                SimpleSurveyQuestion(id=first_ref, type="open", question="Keeps the id?"),
                SimpleSurveyQuestion(id=second_ref, type="open", question="Duplicate reference?"),
            ],
        )

        updated_survey = await sync_to_async(Survey.objects.get)(id=survey.id)
        assert updated_survey.questions is not None
        ids = [q["id"] for q in updated_survey.questions]
        assert ids[0] == "uuid-first"
        assert ids[1] and ids[1] != "uuid-first"
        assert len(set(ids)) == len(ids)