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.

fix(api): preserve managed conversation settings (#108163)

Paul D'Ambra7a5104607b7b
diff --git a/posthog/api/project.py b/posthog/api/project.py
index 6d285deb6cd5..53d28273c50c 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -30,6 +30,7 @@ from posthog.api.tagged_item import TaggedItemSerializerMixin
# project.py must NOT depend on team.py at that point. The parity *logic* (config writes, retention check,
# and the team-config actions) is defined locally below rather than imported, so it survives that removal.
from posthog.api.team import (
+ LOCKED_CONVERSATIONS_COLUMNS,
TEAM_CONFIG_FIELD_ACCESS_CONTROLLED_FIELDS,
TEAM_CONFIG_FIELDS,
TEAM_CONFIG_MEMBER_FIELDS_SET,
@@ -47,14 +48,14 @@ from posthog.api.team import (
TeamWorkflowsConfigSerializer,
_default_data_color_theme_id,
_format_serializer_errors,
- conversations_settings_as_dict,
get_or_mint_live_events_token,
- handle_conversations_token_on_update,
handle_experiments_config,
handle_logs_config,
handle_tracing_config,
heatmaps_screenshot_secret_for_reader,
+ merge_conversations_settings_locked,
report_conversations_settings_changes,
+ strip_managed_conversations_settings,
team_event_ingestion_restrictions_view,
validate_secret_token_generation,
validate_team_attrs,
@@ -663,8 +664,7 @@ class ProjectBackwardCompatSerializer(
def validate_conversations_settings(self, value: dict | None) -> dict | None:
if value is None:
return value
- if not isinstance(value, dict):
- raise serializers.ValidationError("Conversation settings must be an object or null.")
+ strip_managed_conversations_settings(value)
# Filter out None values from widget_domains if present
if "widget_domains" in value and value["widget_domains"] is not None:
value["widget_domains"] = [domain for domain in value["widget_domains"] if domain]
@@ -1219,6 +1219,13 @@ class ProjectBackwardCompatSerializer(
# the passthrough loop below setattr()s everything left in validated_data onto the Project
# or its Team. So tags come out here and are written at the end.
tags = validated_data.pop("tags", None)
+ # The settings patch persisted under lock below must not be written again from the
+ # stale request snapshot; the token handler can add the key later, so capture the
+ # client's intent now.
+ patch_conversations_settings = "conversations_settings" in validated_data
+ # Captured before the locked block pops the keys, so the refresh/re-cache step
+ # below still knows this request touched the team row.
+ conversations_lock_applied = patch_conversations_settings or "conversations_enabled" in validated_data
team = instance.passthrough_team
team_before_update = team.__dict__.copy()
@@ -1307,16 +1314,6 @@ class ProjectBackwardCompatSerializer(
**validated_data["modifiers"],
}
- # Merge conversations_settings with existing values, unless explicitly clearing with null
- if "conversations_settings" in validated_data and validated_data["conversations_settings"] is not None:
- existing_settings = conversations_settings_as_dict(team.conversations_settings)
- new_settings = validated_data["conversations_settings"]
- validated_data["conversations_settings"] = {**existing_settings, **new_settings}
-
- validated_data = handle_conversations_token_on_update(
- validated_data, team.conversations_enabled, team.conversations_settings
- )
-
# Persist only the fields this request changes. A full-row save() writes back every
# column from this request's snapshot of the team, so two concurrent PATCHes clobber
# each other — e.g. an `onboarding_tasks` PATCH racing the onboarding-completion PATCH
@@ -1325,6 +1322,8 @@ class ProjectBackwardCompatSerializer(
updated_team_fields = []
updated_project_fields = []
for attr, value in validated_data.items():
+ if attr in LOCKED_CONVERSATIONS_COLUMNS:
+ continue
if attr not in self.Meta.team_passthrough_fields:
# This attr is a Project field
setattr(instance, attr, value)
@@ -1342,13 +1341,21 @@ class ProjectBackwardCompatSerializer(
if updated_project_fields:
instance.save(update_fields=updated_project_fields)
- if updated_team_fields:
+ # Merge conversations_settings under a lock; a null clear still keeps the managed keys.
+ if conversations_lock_applied:
+ locked_conversations = merge_conversations_settings_locked(
+ team, validated_data, patch_conversations_settings, updated_team_fields
+ )
+ # The locked re-read is newer than the snapshot, so a concurrent write is not logged as this user's.
+ team_before_update["conversations_settings"] = locked_conversations["conversations_settings"]
+ team_before_update["conversations_enabled"] = locked_conversations["conversations_enabled"]
+ elif updated_team_fields:
# auto_now fields only refresh when included in update_fields
team.save(update_fields=[*updated_team_fields, "updated_at"])
# Snapshot before the cache refresh below so the audit diff only reflects this
# request's writes, not fields a concurrent request changed.
team_after_update = team.__dict__.copy()
- if updated_team_fields:
+ if updated_team_fields or conversations_lock_applied:
# The in-memory team may hold stale values for fields a concurrent request
# changed, and the post-save receiver has already cached that snapshot. Reload
# and re-cache so the team cache reflects the merged row.
@@ -1393,6 +1400,7 @@ class ProjectBackwardCompatSerializer(
report_conversations_settings_changes(
cast(User, self.context["request"].user),
team_before_update.get("conversations_settings"),
+ team_after_update.get("conversations_settings"),
team,
)
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 46463ef9d274..c6103f284d3f 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -1923,31 +1923,11 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
def validate_conversations_settings(self, value: dict | None) -> dict | None:
if value is None:
return value
- if not isinstance(value, dict):
- raise serializers.ValidationError("Conversation settings must be an object or null.")
+ strip_managed_conversations_settings(value)
# Filter out None values from widget_domains if present
if "widget_domains" in value and value["widget_domains"] is not None:
value["widget_domains"] = [domain for domain in value["widget_domains"] if domain]
validate_authorized_url_wildcards(value["widget_domains"])
- # Strip widget_public_token from user input - it's auto-generated only
- if "widget_public_token" in value:
- value.pop("widget_public_token")
- # Integration state is managed only by dedicated endpoints, not user input
- for managed_key in (
- "slack_bot_token",
- "slack_team_id",
- "slack_enabled",
- "slack_scopes",
- "email_enabled",
- "teams_enabled",
- "teams_tenant_id",
- "teams_team_id",
- "teams_team_name",
- "teams_channel_id",
- "teams_channel_name",
- "teams_channels",
- ):
- value.pop(managed_key, None)
# Normalize multi-channel list: must be a list of non-empty strings, deduped, capped at 50
if "slack_channel_ids" in value:
raw = value.get("slack_channel_ids")
@@ -2256,6 +2236,13 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
def update(self, instance: Team, validated_data: dict[str, Any]) -> Team:
before_update = instance.__dict__.copy()
+ # The settings patch persisted under lock below must not be written again from the
+ # stale request snapshot; the token handler can add the key later, so capture the
+ # client's intent now.
+ patch_conversations_settings = "conversations_settings" in validated_data
+ # Captured before the locked block pops the keys, so the refresh/re-cache step
+ # below still knows this request touched the team row.
+ conversations_lock_applied = patch_conversations_settings or "conversations_enabled" in validated_data
# Should be validated already, but let's be extra sure
if config_data := validated_data.pop("revenue_analytics_config", None):
@@ -2337,16 +2324,6 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
**validated_data["session_replay_config"],
}
- # Merge conversations_settings with existing values, unless explicitly clearing with null
- if "conversations_settings" in validated_data and validated_data["conversations_settings"] is not None:
- existing_settings = conversations_settings_as_dict(instance.conversations_settings)
- new_settings = validated_data["conversations_settings"]
- validated_data["conversations_settings"] = {**existing_settings, **new_settings}
-
- validated_data = handle_conversations_token_on_update(
- validated_data, instance.conversations_enabled, instance.conversations_settings
- )
-
# Merge modifiers with existing values so that updating one modifier doesn't wipe out others
if "modifiers" in validated_data and validated_data["modifiers"] is not None:
validated_data["modifiers"] = {
@@ -2359,15 +2336,25 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
# each other — e.g. an `onboarding_tasks` PATCH racing the onboarding-completion PATCH
# erased `has_completed_onboarding_for` and reverted `completed_snippet_onboarding`,
# bouncing freshly onboarded users back into onboarding.
- for attr, value in validated_data.items():
- setattr(instance, attr, value)
- if validated_data:
+ other_team_fields = [attr for attr in validated_data if attr not in LOCKED_CONVERSATIONS_COLUMNS]
+ for attr in other_team_fields:
+ setattr(instance, attr, validated_data[attr])
+
+ # Merge conversations_settings under a lock; a null clear still keeps the managed keys.
+ if conversations_lock_applied:
+ locked_conversations = merge_conversations_settings_locked(
+ instance, validated_data, patch_conversations_settings, other_team_fields
+ )
+ # The locked re-read is newer than the snapshot, so a concurrent write is not logged as this user's.
+ before_update["conversations_settings"] = locked_conversations["conversations_settings"]
+ before_update["conversations_enabled"] = locked_conversations["conversations_enabled"]
+ elif other_team_fields:
# auto_now fields only refresh when included in update_fields
- instance.save(update_fields=[*validated_data.keys(), "updated_at"])
+ instance.save(update_fields=[*other_team_fields, "updated_at"])
# Snapshot before the cache refresh below so the audit diff only reflects this
# request's writes, not fields a concurrent request changed.
after_update = instance.__dict__.copy()
- if validated_data:
+ if other_team_fields or conversations_lock_applied:
# The in-memory instance may hold stale values for fields a concurrent request
# changed, and the post-save receiver has already cached that snapshot. Reload
# and re-cache so the team cache reflects the merged row.
@@ -2394,6 +2381,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
report_conversations_settings_changes(
cast(User, self.context["request"].user),
before_update.get("conversations_settings"),
+ after_update.get("conversations_settings"),
updated_team,
)
@@ -3184,13 +3172,17 @@ def conversations_settings_as_dict(value: object) -> dict[str, Any]:
return value if isinstance(value, dict) else {}
-def report_conversations_settings_changes(user: User, before_settings: dict | None, team: Team) -> None:
+def report_conversations_settings_changes(
+ user: User, before_settings: dict | None, after_settings: dict | None, team: Team
+) -> None:
"""Fire one "support setting changed" event per changed conversations_settings key.
Shared by the team and project serializers — both endpoints can PATCH the settings.
+ Pass the settings this request wrote, not the refreshed row: a write that commits
+ after this request's write would otherwise be reported as this user's change.
"""
old_settings = conversations_settings_as_dict(before_settings)
- new_settings = conversations_settings_as_dict(team.conversations_settings)
+ new_settings = conversations_settings_as_dict(after_settings)
changed_keys = sorted(
k for k in old_settings.keys() | new_settings.keys() if old_settings.get(k) != new_settings.get(k)
)
@@ -3204,6 +3196,97 @@ def report_conversations_settings_changes(user: User, before_settings: dict | No
report_user_action(user, "support setting changed", properties, team=team)
+MANAGED_CONVERSATIONS_SETTINGS = (
+ # Strip widget_public_token from user input - it's auto-generated only
+ "widget_public_token",
+ # Integration state is managed only by dedicated endpoints, not user input
+ "slack_bot_token",
+ "slack_team_id",
+ "slack_enabled",
+ "slack_scopes",
+ "email_enabled",
+ "teams_enabled",
+ "teams_tenant_id",
+ "teams_team_id",
+ "teams_team_name",
+ "teams_channel_id",
+ "teams_channel_name",
+ "teams_channels",
+ "github_enabled",
+ "github_integration_id",
+ "github_repos",
+)
+
+LOCKED_CONVERSATIONS_COLUMNS = ("conversations_settings", "conversations_enabled")
+
+
+def merge_conversations_settings_locked(
+ team: Team,
+ validated_data: dict[str, Any],
+ patch_conversations_settings: bool,
+ other_update_fields: list[str],
+) -> dict[str, Any]:
+ """Merge the conversations columns this request writes under one lock on the team row.
+
+ Shared by the team and project serializers — both endpoints can PATCH the settings.
+ The merge reads and the save must share one locked view of the team row: a dedicated
+ integration update (Slack/Teams OAuth, support token rotation) commits whole-blob
+ conversations_settings writes too, and a merge built on the pre-request snapshot would
+ silently restore the state that update had just replaced. Keyed on the columns this
+ request writes, not on which key the client sent: the token handler can inject
+ conversations_settings into a payload that only sent conversations_enabled.
+ The same save writes other_update_fields, which the caller already set on the team, so a
+ PATCH that mixes conversation and other fields saves the row once and commits all or nothing.
+ Returns the locked row's pre-merge conversations_settings and conversations_enabled,
+ so the caller can correct its before-snapshot: that snapshot was taken before this
+ lock re-read the row, and a concurrent integration write in between would otherwise
+ get attributed to this request in the activity log and the settings-changed event.
+ """
+ with transaction.atomic():
+ locked_team = (
+ Team.objects.select_for_update(no_key=True)
+ .only("conversations_settings", "conversations_enabled")
+ .get(pk=team.pk)
+ )
+ if patch_conversations_settings:
+ validated_data["conversations_settings"] = merge_conversations_settings(
+ validated_data["conversations_settings"], locked_team.conversations_settings
+ )
+
+ validated_data = handle_conversations_token_on_update(
+ validated_data, locked_team.conversations_enabled, locked_team.conversations_settings
+ )
+ team.conversations_settings = validated_data.get("conversations_settings", locked_team.conversations_settings)
+ # Sync the flag even when this request does not write it. Otherwise the caller's
+ # after-snapshot keeps a stale value and a concurrent toggle is logged as this user's.
+ team.conversations_enabled = validated_data.get("conversations_enabled", locked_team.conversations_enabled)
+ update_fields = ["conversations_settings", *other_update_fields, "updated_at"]
+ if "conversations_enabled" in validated_data:
+ update_fields.append("conversations_enabled")
+ team.save(update_fields=update_fields)
+ for column in LOCKED_CONVERSATIONS_COLUMNS:
+ validated_data.pop(column, None)
+
+ return {
+ "conversations_settings": locked_team.conversations_settings,
+ "conversations_enabled": locked_team.conversations_enabled,
+ }
+
+
+def strip_managed_conversations_settings(value: dict[str, Any]) -> None:
+ if not isinstance(value, dict):
+ raise serializers.ValidationError("Conversation settings must be an object or null.")
+ for managed_key in MANAGED_CONVERSATIONS_SETTINGS:
+ value.pop(managed_key, None)
+
+
+def merge_conversations_settings(value: dict[str, Any] | None, existing: object) -> dict[str, Any] | None:
+ existing = conversations_settings_as_dict(existing)
+ if value is None:
+ return {key: existing[key] for key in MANAGED_CONVERSATIONS_SETTINGS if key in existing} or None
+ return {**existing, **value}
+
+
def handle_conversations_token_on_update(
validated_data: dict[str, Any],
current_conversations_enabled: bool | None,
@@ -3222,11 +3305,11 @@ def handle_conversations_token_on_update(
# Check if token already exists in current DB state (not user input, which is stripped)
has_token = stored_settings.get("widget_public_token")
if not has_token:
- conv_settings = dict(validated_data.get("conversations_settings") or stored_settings)
+ conv_settings = dict(validated_data.get("conversations_settings", stored_settings) or {})
conv_settings["widget_public_token"] = secrets.token_urlsafe(32)
validated_data["conversations_settings"] = conv_settings
elif is_disabling:
- conv_settings = dict(validated_data.get("conversations_settings") or stored_settings)
+ conv_settings = dict(validated_data.get("conversations_settings", stored_settings) or {})
conv_settings["widget_public_token"] = None
validated_data["conversations_settings"] = conv_settings
diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.py
index 218b37535735..e99884655b48 100644
--- a/posthog/api/test/test_project.py
+++ b/posthog/api/test/test_project.py
@@ -1,17 +1,19 @@
from datetime import timedelta
+from typing import Any
from unittest.mock import MagicMock, patch
from django.core.cache import cache
+from django.db import DatabaseError
from django.utils import timezone
from parameterized import parameterized
from rest_framework import status
from rest_framework.test import APIRequestFactory
-from posthog.api.project import ProjectViewSet
+from posthog.api.project import ProjectBackwardCompatSerializer, ProjectViewSet
from posthog.api.project_tags import MAX_TAGS_PER_FILTER
-from posthog.api.team import TeamCustomerAnalyticsConfigSerializer
+from posthog.api.team import TeamCustomerAnalyticsConfigSerializer, TeamSerializer
from posthog.api.test.test_team import EnvironmentToProjectRewriteClient, team_api_test_factory
from posthog.constants import AvailableFeature
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -22,7 +24,9 @@ from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.project import Project
from posthog.models.tag import Tag
from posthog.models.team.extensions import get_or_create_team_extension
+from posthog.models.team.team import Team
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.test.db_context_capturing import capture_db_queries
from posthog.test.persons import create_person, delete_person
from products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfig
@@ -899,6 +903,193 @@ class TestProjectAPI(team_api_test_factory()): # type: ignore
self.assertIsNotNone(settings.get("widget_public_token"))
self.assertGreater(len(settings["widget_public_token"]), 20)
+ @parameterized.expand(
+ [(False, False, False), (True, False, False), (False, True, False), (True, True, False), (False, True, True)]
+ )
+ def test_conversations_settings_preserve_managed_values(
+ self, include_enabled: bool, clear_settings: bool, use_team_serializer: bool
+ ) -> None:
+ managed = {
+ "widget_public_token": "test-server-generated-token",
+ "slack_bot_token": "test-server-managed-token",
+ "slack_team_id": "test-slack-team",
+ "slack_enabled": False,
+ "slack_scopes": "test-scope",
+ "teams_enabled": False,
+ "teams_tenant_id": None,
+ "teams_team_id": "test-team",
+ "teams_team_name": "Test team",
+ "teams_channel_id": "test-channel",
+ "teams_channel_name": "Test channel",
+ "teams_channels": [],
+ "email_enabled": True,
+ "github_enabled": True,
+ "github_integration_id": 123,
+ "github_repos": ["example-org/example-repo"],
+ }
+ self.team.conversations_enabled = True
+ self.team.conversations_settings = {**managed, "widget_color": "#123456"}
+ self.team.save()
+ payload: dict[str, dict[str, str] | bool | None] = {
+ "conversations_settings": None if clear_settings else dict.fromkeys(managed, "test-client-value")
+ }
+ if include_enabled:
+ payload["conversations_enabled"] = True
+
+ if use_team_serializer:
+ request = APIRequestFactory().patch("/", payload, format="json")
+ request.user = self.user
+ TeamSerializer(context={"request": request}).update(self.team, payload)
+ else:
+ response = self.client.patch(f"/api/projects/{self.project.id}/", payload, format="json")
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+
+ self.team.refresh_from_db()
+ expected = managed if clear_settings else {**managed, "widget_color": "#123456"}
+ self.assertEqual(self.team.conversations_settings, expected)
+
+ @parameterized.expand(
+ [(TeamSerializer, "null"), (ProjectBackwardCompatSerializer, "null"), (TeamSerializer, "enabled")]
+ )
+ def test_conversations_settings_clear_rereads_team_before_merging(self, serializer_class: type, mode: str) -> None:
+ # A conversations PATCH must read the team row it writes from under the lock, not
+ # from the instance the serializer was handed. Otherwise a dedicated integration
+ # update that commits between the request's snapshot and the save gets clobbered
+ # by the whole-blob write, restoring stale state.
+ self.team.conversations_enabled = False
+ self.team.conversations_settings = {"widget_color": "#123456"}
+ self.team.save()
+
+ def simulate_integration_update(*args: Any, **kwargs: Any) -> Any:
+ # Runs when the update path takes its locking re-read: commit the
+ # integration change now, so the merge must see it. The null clear
+ # keeps only managed keys, so the token and the integration state
+ # the integration update just wrote are the ones that must survive.
+ # Another admin enables conversations in the same window.
+ Team.objects.filter(pk=self.team.pk).update(
+ conversations_enabled=True,
+ conversations_settings={
+ "widget_color": "#123456",
+ "widget_public_token": "integration-token",
+ "teams_enabled": True,
+ },
+ )
+ return real_select_for_update(*args, **kwargs)
+
+ def simulate_late_integration_update(team: Team, *args: Any, **kwargs: Any) -> None:
+ # Runs after this request's locked write commits. The late write must not
+ # be reported as this user's setting change.
+ latest = Team.objects.only("conversations_settings").get(pk=team.pk).conversations_settings
+ Team.objects.filter(pk=team.pk).update(conversations_settings={**latest, "late_key": True})
+ real_refresh_from_db(team, *args, **kwargs)
+
+ real_select_for_update = Team.objects.select_for_update
+ real_refresh_from_db = Team.refresh_from_db
+ if mode == "null":
+ payload: dict[str, Any] = {"conversations_settings": None}
+ else:
+ payload = {"conversations_enabled": True}
+
+ with (
+ capture_db_queries() as queries,
+ patch("posthog.api.team.report_user_action") as mock_report,
+ ):
+ with (
+ patch.object(Team.objects, "select_for_update", simulate_integration_update),
+ patch.object(Team, "refresh_from_db", simulate_late_integration_update),
+ ):
+ if serializer_class is TeamSerializer:
+ TeamSerializer(context={"request": MagicMock(user=self.user)}).update(self.team, payload)
+ else:
+ request = APIRequestFactory().patch("/", payload, format="json")
+ request.user = self.user
+ ProjectBackwardCompatSerializer(context={"request": request, "view": None}).update(
+ self.project, payload
+ )
+
+ self.team.refresh_from_db()
+ if mode == "enabled":
+ # The enable path finds the token the integration update just wrote, so it
+ # keeps that whole blob rather than re-minting.
+ expected: dict[str, Any] = {
+ "widget_color": "#123456",
+ "widget_public_token": "integration-token",
+ "teams_enabled": True,
+ }
+ else:
+ expected = {"widget_public_token": "integration-token", "teams_enabled": True}
+ self.assertEqual(self.team.conversations_settings, {**expected, "late_key": True})
+ self.assertTrue(self.team.conversations_enabled)
+
+ # The blob must be written exactly once by this request, inside the lock. The
+ # first captured UPDATE is the simulated integration write; a second one after
+ # the lock is released would clobber an integration writer queued on it.
+ settings_saves = [
+ q
+ for q in queries.captured_queries
+ if q["sql"].startswith('UPDATE "posthog_team"') and "late_key" not in q["sql"]
+ ]
+ self.assertEqual(len(settings_saves), 2, [q["sql"][:120] for q in settings_saves])
+ self.assertIn("integration-token", settings_saves[0]["sql"])
+
+ # Neither concurrent writer's keys may be reported as this user's setting changes.
+ reported = [c.args[2]["setting"] for c in mock_report.call_args_list if c.args[1] == "support setting changed"]
+ self.assertEqual(reported, [] if mode == "enabled" else ["widget_color"])
+
+ # The other admin's toggle must not be logged as this user's change.
+ logged_fields = [
+ change["field"]
+ for log in ActivityLog.objects.filter(team_id=self.team.pk, scope="Team")
+ for change in (log.detail or {}).get("changes") or []
+ ]
+ self.assertNotIn("conversations_enabled", logged_fields)
+
+ @parameterized.expand(
+ [
+ (TeamSerializer, "saved"),
+ (ProjectBackwardCompatSerializer, "saved"),
+ (TeamSerializer, "save_fails"),
+ (ProjectBackwardCompatSerializer, "save_fails"),
+ ]
+ )
+ def test_conversations_patch_with_other_team_fields_saves_the_team_once(
+ self, serializer_class: type, outcome: str
+ ) -> None:
+ self.team.conversations_settings = {"widget_color": "#123456"}
+ self.team.capture_console_log_opt_in = False
+ self.team.save()
+ payload = {"conversations_settings": {"widget_color": "#654321"}, "capture_console_log_opt_in": True}
+ request = APIRequestFactory().patch("/", payload, format="json")
+ request.user = self.user
+ serializer = serializer_class(context={"request": request, "view": None})
+ instance = self.team if serializer_class is TeamSerializer else self.project
+
+ real_save = Team.save
+
+ def save_that_fails_on_other_fields(team: Team, *args: Any, **kwargs: Any) -> None:
+ if "capture_console_log_opt_in" in (kwargs.get("update_fields") or []):
+ raise DatabaseError("simulated failure")
+ real_save(team, *args, **kwargs)
+
+ if outcome == "save_fails":
+ with (
+ patch.object(Team, "save", autospec=True, side_effect=save_that_fails_on_other_fields),
+ self.assertRaises(DatabaseError),
+ ):
+ serializer.update(instance, payload)
+ self.team.refresh_from_db()
+ self.assertEqual(self.team.conversations_settings, {"widget_color": "#123456"})
+ self.assertFalse(self.team.capture_console_log_opt_in)
+ return
+
+ with capture_db_queries() as queries:
+ serializer.update(instance, payload)
+ team_saves = [q["sql"] for q in queries.captured_queries if q["sql"].startswith('UPDATE "posthog_team"')]
+ self.assertEqual(len(team_saves), 1, [sql[:120] for sql in team_saves])
+ self.team.refresh_from_db()
+ self.assertEqual(self.team.conversations_settings, {"widget_color": "#654321"})
+ self.assertTrue(self.team.capture_console_log_opt_in)
+
def test_generate_conversations_public_token(self):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 054c4cb608f3..073256ff4249 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -25,6 +25,8 @@ from posthog.api.team import (
TeamWorkflowsConfigSerializer,
_default_data_color_theme_id,
_reset_default_data_color_theme_id_cache,
+ handle_conversations_token_on_update,
+ merge_conversations_settings,
)
from posthog.constants import AvailableFeature
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -4077,6 +4079,49 @@ _TOO_MANY_WILDCARDS = ["https://*.*.*.*.*.*.example.com"]
class TestTeamSerializerValidationNoDB(SimpleTestCase):
+ @parameterized.expand([(None,), ({},), ({"widget_color": "#123456"},)])
+ def test_conversations_settings_clear_without_managed_values(self, existing: dict[str, str] | None) -> None:
+ self.assertIsNone(merge_conversations_settings(None, existing))
+
+ @parameterized.expand([(enabling, has_token) for enabling in (False, True) for has_token in (False, True)])
+ def test_conversations_clear_retains_integration_state_on_toggle(self, enabling: bool, has_token: bool) -> None:
+ current: dict[str, object] = {
+ "widget_color": "#123456",
+ "slack_enabled": False,
+ "teams_tenant_id": None,
+ }
+ if has_token:
+ current["widget_public_token"] = "test-existing-token"
+ updates = {
+ "conversations_enabled": enabling,
+ "conversations_settings": merge_conversations_settings(None, current),
+ }
+
+ with patch("posthog.api.team.secrets.token_urlsafe", return_value="test-generated-token"):
+ result = handle_conversations_token_on_update(updates, not enabling, current)
+
+ token = ("test-existing-token" if has_token else "test-generated-token") if enabling else None
+ self.assertEqual(
+ result["conversations_settings"],
+ {"slack_enabled": False, "teams_tenant_id": None, "widget_public_token": token},
+ )
+
+ @parameterized.expand(
+ [(enabling, settings_input) for enabling in (False, True) for settings_input in ("omitted", "null", "empty")]
+ )
+ def test_conversations_token_update_respects_cleared_settings(self, enabling: bool, settings_input: str) -> None:
+ current_settings = {"widget_color": "#123456"}
+ updates: dict[str, object] = {"conversations_enabled": enabling}
+ if settings_input != "omitted":
+ updates["conversations_settings"] = None if settings_input == "null" else {}
+
+ with patch("posthog.api.team.secrets.token_urlsafe", return_value="test-generated-token"):
+ result = handle_conversations_token_on_update(updates, not enabling, current_settings)
+
+ expected: dict[str, str | None] = dict(current_settings) if settings_input == "omitted" else {}
+ expected["widget_public_token"] = "test-generated-token" if enabling else None
+ self.assertEqual(result["conversations_settings"], expected)
+
@parameterized.expand(
[
(serializer, value)