: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
fix(conversations): prevent partial updates for invalid assignees (#89719)
posthog[bot]0b72e8659d41
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1f273edfebd7..d34db2dacdfc 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6733,7 +6733,7 @@ snapshots:scenes-app-hogfunctions-destination--configuration--light:hash: v1.k794b7964.95608b27807bceadfd2068131fd49e4311aee852fcb3906b8fb9f58b435deb14.3WOAev30EoH9_E2wdxwiHPWOTulXq79z67nv2B202pQscenes-app-hogfunctions-destination--configuration-with-templating-warning--dark:- hash: v1.k794b7964.27836a122e278f4f73483ff79900f08f75bcf01a50c56ed4db1630ef262bd563.LVx2x4gshmrHhfz6goJRqcAnJ1xvhCLyYo1AtHnWnvU+ hash: v1.k794b7964.c36181fed9cb3bef026b10d3c8099bbe0a834b51865a03f486deaa4eb857df55.aR5CI-Z04Q3dPHdBUsFpEAvfiF6ukw7ppBDR6Mgm62Escenes-app-hogfunctions-destination--configuration-with-templating-warning--light:hash: v1.k794b7964.819c775988c21f467569bbe3839e91810b737298bfd72f2a67bdff148ccc4a1a.bmqQ8PVCOsdRsnEY-bIyReFJ2bBV5S0X_a_uMirsQUAscenes-app-hogfunctions-destination--runs-empty--dark:diff --git a/products/conversations/backend/api/tests/test_snooze.py b/products/conversations/backend/api/tests/test_snooze.pyindex 79f398fd2ad2..220d443ba3a2 100644--- a/products/conversations/backend/api/tests/test_snooze.py+++ b/products/conversations/backend/api/tests/test_snooze.py@@ -97,6 +97,18 @@ class TestTicketSnoozeAPI(APIBaseTest):self.ticket.refresh_from_db()self.assertEqual(self.ticket.status, Status.RESOLVED)+ def test_resnooze_keeps_status(self, _):+ self.ticket.snoozed_until = timezone.now() + timedelta(hours=2)+ self.ticket.status = Status.PENDING+ self.ticket.save(update_fields=["snoozed_until", "status"])++ new_snooze_time = (timezone.now() + timedelta(hours=5)).isoformat()+ response = self.client.patch(self.url, {"snoozed_until": new_snooze_time})+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ self.ticket.refresh_from_db()+ self.assertEqual(self.ticket.status, Status.PENDING)+def test_snooze_logs_activity(self, _):snooze_time = (timezone.now() + timedelta(hours=2)).isoformat()self.client.patch(self.url, {"snoozed_until": snooze_time})diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex dd04cdf6911b..f9e8ae99cebf 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -229,28 +229,46 @@ class TestTicketAPI(APIBaseTest):self.ticket.refresh_from_db()self.assertIsNotNone(self.ticket.sla_due_at)- def test_update_sla_due_at_logs_activity(self, mock_on_commit):- sla_time = timezone.now() + timedelta(hours=5)+ @parameterized.expand(+ [+ (+ "sla_due_at",+ {"sla_due_at": "2030-01-01T00:00:00+00:00"},+ {"sla_due_at": (None, "2030-01-01T00:00:00+00:00")},+ ),+ (+ "status_and_priority",+ {"status": Status.RESOLVED, "priority": Priority.HIGH},+ {"status": (Status.NEW, Status.RESOLVED), "priority": (None, Priority.HIGH)},+ ),+ ]+ )+ def test_update_logs_every_changed_field_in_one_activity_entry(+ self, mock_on_commit, _name, payload, expected_changes+ ):response = self.client.patch(f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/",- {"sla_due_at": sla_time.isoformat()},+ payload,)self.assertEqual(response.status_code, status.HTTP_200_OK)- activity = ActivityLog.objects.filter(- team_id=self.team.id,- scope="Ticket",- item_id=str(self.ticket.id),- activity="updated",- ).first()+ entries = list(+ ActivityLog.objects.filter(+ team_id=self.team.id,+ scope="Ticket",+ item_id=str(self.ticket.id),+ activity="updated",+ )+ )+ self.assertEqual(len(entries), 1)- assert activity is not None- assert activity.detail is not None- changes = activity.detail.get("changes", [])- sla_change = next((c for c in changes if c["field"] == "sla_due_at"), None)- assert sla_change is not None- self.assertIsNone(sla_change["before"])- self.assertIsNotNone(sla_change["after"])+ detail = entries[0].detail+ assert detail is not None+ changes = detail.get("changes", [])+ self.assertEqual(+ {change["field"]: (change["before"], change["after"]) for change in changes},+ expected_changes,+ )@parameterized.expand([@@ -1248,30 +1266,29 @@ class TestTicketAssignment(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn(expected_error, str(response.json()))- def test_assign_to_user_not_in_organization(self):- other_user = User.objects.create(email="[email protected]")-- response = self.client.patch(- f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/",- {"assignee": {"id": other_user.id, "type": "user"}},- )-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("not a member of this organization", str(response.json()))- self.assertEqual(TicketAssignment.objects.count(), 0)-- def test_assign_to_role_not_in_organization(self):- other_org = Organization.objects.create(name="Other Org")- other_role = Role.objects.create(name="Other Role", organization=other_org)+ @parameterized.expand(+ [+ ("user", "not a member of this organization"),+ ("role", "does not belong to this organization"),+ ]+ )+ def test_invalid_assignee_membership_does_not_update_ticket(self, assignee_type: str, expected_error: str) -> None:+ if assignee_type == "user":+ assignee_id: int | str = User.objects.create(email="[email protected]").id+ else:+ other_org = Organization.objects.create(name="Other Org")+ assignee_id = str(Role.objects.create(name="Other Role", organization=other_org).id)response = self.client.patch(f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/",- {"assignee": {"id": str(other_role.id), "type": "role"}},+ {"assignee": {"id": assignee_id, "type": assignee_type}, "status": Status.PENDING},)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("does not belong to this organization", str(response.json()))+ self.assertIn(expected_error, str(response.json()))self.assertEqual(TicketAssignment.objects.count(), 0)+ self.ticket.refresh_from_db()+ self.assertEqual(self.ticket.status, Status.NEW)@patch.object(transaction, "on_commit", side_effect=immediate_on_commit)diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex d0003d04fcae..46b72b327031 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -4,7 +4,8 @@ import jsonimport timeimport uuidfrom collections.abc import Sequence-from typing import TYPE_CHECKING, Any, cast+from datetime import datetime+from typing import TYPE_CHECKING, Any, Literal, TypedDict, castfrom django.db import transactionfrom django.db.models import Q, QuerySet, Sum@@ -13,7 +14,14 @@ from django.http import Http404import structlogimport posthoganalyticsfrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_view+from drf_spectacular.utils import (+ OpenApiParameter,+ OpenApiResponse,+ PolymorphicProxySerializer,+ extend_schema,+ extend_schema_field,+ extend_schema_view,+)from rest_framework import (pagination,serializers,@@ -28,6 +36,7 @@ from rest_framework.response import Responsefrom posthog.api.person import get_person_namefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin+from posthog.dataclasses import frozenfrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.impersonation import is_impersonated@@ -71,11 +80,24 @@ from products.conversations.backend.person_lookup import _get_persons_by_emailfrom .. import reply_dedupeif TYPE_CHECKING:- from posthog.models import User+ from posthog.models import Organization, Userlogger = structlog.get_logger(__name__)+class UserTicketAssignee(TypedDict):+ id: int+ type: Literal["user"]+++class RoleTicketAssignee(TypedDict):+ id: str+ type: Literal["role"]+++TicketAssignee = UserTicketAssignee | RoleTicketAssignee++class TicketErrorSerializer(serializers.Serializer):detail = serializers.CharField()error_type = serializers.CharField(required=False)@@ -388,6 +410,80 @@ class TicketSerializer(UserAccessControlSerializerMixin, TaggedItemSerializerMixreturn None+class UserTicketAssigneeRequestSerializer(serializers.Serializer):+ type = serializers.CharField(help_text="Assign the ticket to a user.")+ id = serializers.IntegerField(help_text="User ID.")+++class RoleTicketAssigneeRequestSerializer(serializers.Serializer):+ type = serializers.CharField(help_text="Assign the ticket to a role.")+ id = serializers.UUIDField(help_text="Role ID.")+++_TICKET_ASSIGNEE_REQUEST_SCHEMA = PolymorphicProxySerializer(+ component_name="TicketAssigneeRequest",+ serializers={+ "user": UserTicketAssigneeRequestSerializer,+ "role": RoleTicketAssigneeRequestSerializer,+ },+ resource_type_field_name="type",+)+++@extend_schema_field(_TICKET_ASSIGNEE_REQUEST_SCHEMA)+class TicketAssigneeRequestField(serializers.Field):+ def to_internal_value(self, data: object) -> TicketAssignee | None:+ try:+ return validate_assignee(data)+ except serializers.ValidationError as error:+ if isinstance(error.detail, dict) and "assignee" in error.detail:+ raise serializers.ValidationError(error.detail["assignee"]) from error+ raise+++class TicketUpdateRequestSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):+ """Fields accepted when updating a ticket."""++ assignee = TicketAssigneeRequestField(+ required=False,+ allow_null=True,+ write_only=True,+ help_text="User or role to assign. Pass null to remove the current assignee.",+ )+ tags = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Tag names to set on the ticket.",+ )++ class Meta:+ model = Ticket+ fields = [+ "status",+ "priority",+ "assignee",+ "anonymous_traits",+ "ai_resolved",+ "escalation_reason",+ "sla_due_at",+ "snoozed_until",+ "tags",+ ]+ extra_kwargs = {+ "status": {"help_text": "Ticket status: new, open, pending, on_hold, or resolved."},+ "priority": {"help_text": "Ticket priority: low, medium, high, or critical. Pass null to clear it."},+ "anonymous_traits": {"help_text": "Customer details such as name and email."},+ "ai_resolved": {"help_text": "Whether AI resolved the ticket."},+ "escalation_reason": {"help_text": "Reason the ticket was escalated. Pass null to clear it."},+ "sla_due_at": {"help_text": "SLA deadline. Pass null to clear it."},+ "snoozed_until": {"help_text": "Time to reopen the ticket. Pass null to reopen it now."},+ }++ def update(self, instance: Ticket, validated_data: dict[str, Any]) -> Ticket:+ validated_data.pop("assignee", None)+ return super().update(instance, validated_data)++TICKET_ID_PARAM = OpenApiParameter(name="id",type=OpenApiTypes.STR,@@ -403,10 +499,108 @@ NOTE_MESSAGE_ID_PARAM = OpenApiParameter()+def _status_implied_by_snooze(before: datetime | None, after: datetime | None) -> str | None:+ """Return the status a snooze change implies, or None when it implies no status change.++ Snoozing a ticket puts it on hold, and unsnoozing reopens it. Moving a snooze to a+ different time leaves the status alone.+ """+ if before is None and after is not None:+ return Status.ON_HOLD+ if before is not None and after is None:+ return Status.OPEN+ return None+++def _activity_value(value: Any) -> Any:+ """Render a field value for the activity log. Datetimes go in as ISO strings."""+ return value.isoformat() if isinstance(value, datetime) else value+++def _ticket_action_properties(ticket: Ticket) -> dict[str, Any]:+ return {+ "channel_source": ticket.channel_source,+ "ticket_status": ticket.status,+ "is_assigned": getattr(ticket, "assignment", None) is not None,+ }+++@frozen+class _TicketFields:+ """The ticket fields a single-ticket update compares before and after saving."""++ status: str+ priority: str | None+ sla_due_at: datetime | None+ snoozed_until: datetime | None++ @classmethod+ def read_from(cls, ticket: Ticket) -> _TicketFields:+ return cls(+ status=ticket.status,+ priority=ticket.priority,+ sla_due_at=ticket.sla_due_at,+ snoozed_until=ticket.snoozed_until,+ )+++@frozen+class _TicketUpdateDiff:+ """What a single-ticket update changed, and therefore which side effects run."""++ before: _TicketFields+ after: _TicketFields+ # True when the request carried an assignee, which is not the same as the assignment+ # having changed. assign_ticket() decides that, and stays silent when it did not.+ assignee_submitted: bool++ @property+ def status_changed(self) -> bool:+ return self.before.status != self.after.status++ @property+ def priority_changed(self) -> bool:+ return self.before.priority != self.after.priority++ @property+ def crosses_resolved(self) -> bool:+ return self.status_changed and Status.RESOLVED in (self.before.status, self.after.status)++ @property+ def has_changes(self) -> bool:+ return self.assignee_submitted or self.before != self.after++ def activity_changes(self) -> list[Change]:+ """Build the activity-log entries for every field this update touched."""+ fields: list[tuple[str, Any, Any]] = [+ ("status", self.before.status, self.after.status),+ ("priority", self.before.priority, self.after.priority),+ ("sla_due_at", self.before.sla_due_at, self.after.sla_due_at),+ ("snoozed_until", self.before.snoozed_until, self.after.snoozed_until),+ ]+ # Compare the raw values, so two datetimes for the same instant in different+ # timezones do not register as a change, then render for the log.+ return [+ Change(+ type="Ticket",+ field=field,+ before=_activity_value(before),+ after=_activity_value(after),+ action="changed",+ )+ for field, before, after in fields+ if before != after+ ]++@extend_schema_view(retrieve=extend_schema(parameters=[TICKET_ID_PARAM]),- update=extend_schema(parameters=[TICKET_ID_PARAM]),- partial_update=extend_schema(parameters=[TICKET_ID_PARAM]),+ update=extend_schema(+ parameters=[TICKET_ID_PARAM], request=TicketUpdateRequestSerializer, responses=TicketSerializer+ ),+ partial_update=extend_schema(+ parameters=[TICKET_ID_PARAM], request=TicketUpdateRequestSerializer, responses=TicketSerializer+ ),destroy=extend_schema(parameters=[TICKET_ID_PARAM]),)class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):@@ -786,11 +980,7 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControreport_user_action(request.user,"support ticket viewed",- {- "channel_source": instance.channel_source,- "ticket_status": instance.status,- "is_assigned": getattr(instance, "assignment", None) is not None,- },+ _ticket_action_properties(instance),team=self.team,request=request,)@@ -804,158 +994,135 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro"""Handle ticket updates including assignee changes."""partial = kwargs.pop("partial", False)instance = self.get_object()- old_status = instance.status- old_priority = instance.priority- old_sla_due_at = instance.sla_due_at- old_snoozed_until = instance.snoozed_until-- # Extract assignee without mutating request.data- assignee = request.data.get("assignee", ...) if "assignee" in request.data else ...- data = {k: v for k, v in request.data.items() if k != "assignee"}+ before = _TicketFields.read_from(instance)- # Update other fields normally- serializer = self.get_serializer(instance, data=data, partial=partial)+ serializer = TicketUpdateRequestSerializer(+ instance,+ data=request.data,+ partial=partial,+ context=self.get_serializer_context(),+ )serializer.is_valid(raise_exception=True)- explicit_status = "status" in data- with transaction.atomic():- self.perform_update(serializer)+ assignee_submitted = "assignee" in serializer.validated_data+ validated_assignee = serializer.validated_data.get("assignee")+ if assignee_submitted:+ validate_assignee_membership(validated_assignee, self.organization)++ self._save_ticket_fields(+ serializer,+ instance,+ before,+ explicit_status="status" in serializer.validated_data,+ )- # Auto-status on snooze transitions (only when user didn't explicitly set status)- new_snoozed_until = instance.snoozed_until- snooze_changed = old_snoozed_until != new_snoozed_until- if snooze_changed and not explicit_status:- if old_snoozed_until is None and new_snoozed_until is not None:- instance.status = Status.ON_HOLD- instance.save(update_fields=["status"])- elif old_snoozed_until is not None and new_snoozed_until is None:- instance.status = Status.OPEN- instance.save(update_fields=["status"])-- # Handle assignee update if provided (not ... sentinel)- if assignee is not ...:- assign_ticket(+ if assignee_submitted:+ _assign_ticket(instance,- assignee,+ validated_assignee,self.organization,request.user,self.team_id,is_impersonated(request),)- # Refresh instance to get updated assignmentinstance.refresh_from_db()- # Invalidate unread count cache if status changed to/from resolved- new_status = instance.status- if old_status != new_status and (old_status == "resolved" or new_status == "resolved"):+ diff = _TicketUpdateDiff(+ before=before,+ after=_TicketFields.read_from(instance),+ assignee_submitted=assignee_submitted,+ )+ self._emit_update_side_effects(request, instance, diff)++ # Re-serialize to include updated assignee+ response_serializer = self.get_serializer(instance)+ return Response(response_serializer.data)++ def _save_ticket_fields(+ self,+ serializer: serializers.BaseSerializer,+ instance: Ticket,+ before: _TicketFields,+ *,+ explicit_status: bool,+ ) -> None:+ """Persist the submitted fields, then apply the status a snooze change implies.++ A status in the same request wins over the implied one, so a caller can snooze a+ ticket and keep it pending.+ """+ with transaction.atomic():+ self.perform_update(serializer)++ implied_status = _status_implied_by_snooze(before.snoozed_until, instance.snoozed_until)+ if implied_status is not None and not explicit_status:+ instance.status = implied_status+ instance.save(update_fields=["status"])++ def _emit_update_side_effects(self, request, instance: Ticket, diff: _TicketUpdateDiff) -> None:+ if diff.crosses_resolved:invalidate_unread_count_cache(self.team_id)- # Emit analytics events for workflow triggers- new_priority = instance.priority- new_sla_due_at = instance.sla_due_at- status_changed = old_status != new_status- priority_changed = old_priority != new_priority- sla_changed = old_sla_due_at != new_sla_due_at- assignee_changed = assignee is not ...+ self._capture_update_events(request, instance, diff)+ self._log_update_activity(request, instance, diff)++ if diff.has_changes:+ self._report_ticket_updated(request, instance)+ def _capture_update_events(self, request, instance: Ticket, diff: _TicketUpdateDiff) -> None:+ """Emit the analytics events that workflow triggers listen for."""try:- if status_changed:- capture_ticket_status_changed(instance, old_status, new_status, actor=request.user, actor_type="user")+ if diff.status_changed:+ capture_ticket_status_changed(+ instance, diff.before.status, diff.after.status, actor=request.user, actor_type="user"+ )- if priority_changed:+ if diff.priority_changed:capture_ticket_priority_changed(- instance, old_priority, new_priority, actor=request.user, actor_type="user"+ instance, diff.before.priority, diff.after.priority, actor=request.user, actor_type="user")except Exception as e:capture_exception(e, {"ticket_id": str(instance.id)})- # Log all field changes to activity log- changes: list[Change] = []- if status_changed:- changes.append(- Change(- type="Ticket",- field="status",- before=old_status,- after=new_status,- action="changed",- )- )- if priority_changed:- changes.append(- Change(- type="Ticket",- field="priority",- before=old_priority,- after=new_priority,- action="changed",- )- )- if sla_changed:- changes.append(- Change(- type="Ticket",- field="sla_due_at",- before=old_sla_due_at.isoformat() if old_sla_due_at else None,- after=new_sla_due_at.isoformat() if new_sla_due_at else None,- action="changed",- )- )- if snooze_changed:- changes.append(- Change(- type="Ticket",- field="snoozed_until",- before=old_snoozed_until.isoformat() if old_snoozed_until else None,- after=new_snoozed_until.isoformat() if new_snoozed_until else None,- action="changed",- )- )-- if changes:- try:- log_activity(- organization_id=self.organization.id,- team_id=self.team_id,- user=request.user,- was_impersonated=is_impersonated(request),- item_id=str(instance.id),- scope="Ticket",- activity="updated",- detail=Detail(- name=f"Ticket #{instance.ticket_number}",- changes=changes,- ),- )- except Exception as e:- capture_exception(e, {"ticket_id": str(instance.id)})+ def _log_update_activity(self, request, instance: Ticket, diff: _TicketUpdateDiff) -> None:+ changes = diff.activity_changes()+ if not changes:+ return- # Track internal analytics- if status_changed or priority_changed or assignee_changed or sla_changed or snooze_changed:- try:- report_user_action(- request.user,- "support ticket updated",- {- "channel_source": instance.channel_source,- "ticket_status": instance.status,- "is_assigned": getattr(instance, "assignment", None) is not None,- },- team=self.team,- request=request,- )- except Exception as e:- capture_exception(e, {"ticket_id": str(instance.id)})+ try:+ log_activity(+ organization_id=self.organization.id,+ team_id=self.team_id,+ user=request.user,+ was_impersonated=is_impersonated(request),+ item_id=str(instance.id),+ scope="Ticket",+ activity="updated",+ detail=Detail(+ name=f"Ticket #{instance.ticket_number}",+ changes=changes,+ ),+ )+ except Exception as e:+ capture_exception(e, {"ticket_id": str(instance.id)})- # Re-serialize to include updated assignee- serializer = self.get_serializer(instance)- return Response(serializer.data)+ def _report_ticket_updated(self, request, instance: Ticket) -> None:+ try:+ report_user_action(+ request.user,+ "support ticket updated",+ _ticket_action_properties(instance),+ team=self.team,+ request=request,+ )+ except Exception as e:+ capture_exception(e, {"ticket_id": str(instance.id)})def _emit_status_change_side_effects(self, request, ticket: Ticket, old_status: str, new_status: str) -> None:"""Emit analytics + activity log for a single ticket status change.- Called from both ``update()`` and ``bulk_update_status()`` to keep- event-tracking logic in one place.+ Used by ``bulk_update_status()``. Single-ticket updates log every changed+ field in one entry, so they build their own activity log entry instead."""try:capture_ticket_status_changed(ticket, old_status, new_status, actor=request.user, actor_type="user")@@ -1551,10 +1718,10 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro)-def validate_assignee(assignee) -> None:+def validate_assignee(assignee: object) -> TicketAssignee | None:"""Validate assignee payload structure."""if assignee is None:- return+ return Noneif not isinstance(assignee, dict):raise serializers.ValidationError({"assignee": "must be an object"})if "type" not in assignee or "id" not in assignee:@@ -1571,8 +1738,10 @@ def validate_assignee(assignee) -> None:except (ValueError, AttributeError):raise serializers.ValidationError({"assignee": "role id must be a valid UUID"})+ return cast(TicketAssignee, assignee)+-def validate_assignee_membership(assignee, organization) -> None:+def validate_assignee_membership(assignee: TicketAssignee | None, organization: Organization) -> None:"""Validate that the assignee belongs to the organization."""if assignee is None:return@@ -1586,8 +1755,14 @@ def validate_assignee_membership(assignee, organization) -> None:def assign_ticket(- ticket: Ticket, assignee, organization, user, team_id, was_impersonated, trigger: Trigger | None = None-):+ ticket: Ticket,+ assignee: object,+ organization: Organization,+ user: User | None,+ team_id: int,+ was_impersonated: bool,+ trigger: Trigger | None = None,+) -> None:"""Assign a ticket to a user or role.@@ -1600,9 +1775,20 @@ def assign_ticket(was_impersonated: Whether the session is impersonatedtrigger: Optional Trigger identifying an automated source (e.g. a workflow) that made the change"""- validate_assignee(assignee)- validate_assignee_membership(assignee, organization)-+ validated_assignee = validate_assignee(assignee)+ validate_assignee_membership(validated_assignee, organization)+ _assign_ticket(ticket, validated_assignee, organization, user, team_id, was_impersonated, trigger)+++def _assign_ticket(+ ticket: Ticket,+ assignee: TicketAssignee | None,+ organization: Organization,+ user: User | None,+ team_id: int,+ was_impersonated: bool,+ trigger: Trigger | None = None,+) -> None:with transaction.atomic():# Lock the ticket to prevent concurrent modificationsTicket.objects.select_for_update().get(id=ticket.id, team_id=team_id)diff --git a/products/conversations/frontend/components/Assignee/AssigneeDropdown.tsx b/products/conversations/frontend/components/Assignee/AssigneeDropdown.tsxindex 5c8132fdac15..9ee3e77f2a48 100644--- a/products/conversations/frontend/components/Assignee/AssigneeDropdown.tsx+++ b/products/conversations/frontend/components/Assignee/AssigneeDropdown.tsx@@ -7,7 +7,7 @@ import { urls } from 'scenes/urls'import { AssigneeIconDisplay, AssigneeLabelDisplay } from './AssigneeDisplay'import { assigneeSelectLogic } from './assigneeSelectLogic'-import { Assignee, TicketAssignee } from './types'+import { Assignee, TicketAssignee, toTicketAssignee } from './types'export interface AssigneeDropdownProps {assignee: TicketAssignee@@ -45,7 +45,6 @@ export function AssigneeDropdown({ assignee, onChange }: AssigneeDropdownProps):type: 'user',user: currentUserMember.user,}}- type="user"onSelect={onChange}activeId={assignee?.id}labelSuffix={<span className="text-secondary">(you)</span>}@@ -57,7 +56,6 @@ export function AssigneeDropdown({ assignee, onChange }: AssigneeDropdownProps):title="Roles"loading={rolesLoading}search={!!search}- type="role"items={filteredRoles.map((role) => ({id: role.id,type: 'role' as const,@@ -82,7 +80,6 @@ export function AssigneeDropdown({ assignee, onChange }: AssigneeDropdownProps):title="Users"loading={membersLoading}search={!!search}- type="user"items={otherFilteredMembers.map((member) => ({id: member.user.id,type: 'user' as const,@@ -99,13 +96,11 @@ export function AssigneeDropdown({ assignee, onChange }: AssigneeDropdownProps):const AssigneeItem = ({item,- type,onSelect,activeId,labelSuffix,}: {item: Assignee- type: 'user' | 'role'onSelect: (value: TicketAssignee) => voidactiveId?: string | numberlabelSuffix?: JSX.Element@@ -116,7 +111,7 @@ const AssigneeItem = ({role="menuitem"size="small"icon={<AssigneeIconDisplay assignee={item} />}- onClick={() => item?.id && onSelect(String(activeId) === String(item.id) ? null : { type, id: item.id })}+ onClick={() => item?.id && onSelect(String(activeId) === String(item.id) ? null : toTicketAssignee(item))}active={String(activeId) === String(item?.id)}><span className="flex items-center gap-1">@@ -130,7 +125,6 @@ const AssigneeItem = ({const Section = ({loading,search,- type,items,onSelect,activeId,@@ -140,7 +134,6 @@ const Section = ({title: stringloading: booleansearch: boolean- type: 'user' | 'role'items: Assignee[]onSelect: (value: TicketAssignee) => voidactiveId?: string | number@@ -152,7 +145,7 @@ const Section = ({<h5 className="mx-2 my-0.5">{title}</h5>{items.map((item) => (<li key={item?.id || 'unassigned'}>- <AssigneeItem item={item} type={type} onSelect={onSelect} activeId={activeId} />+ <AssigneeItem item={item} onSelect={onSelect} activeId={activeId} /></li>))}diff --git a/products/conversations/frontend/components/Assignee/AssigneeMultiSelect.tsx b/products/conversations/frontend/components/Assignee/AssigneeMultiSelect.tsxindex 208f52a7fd2f..a93adbd58c4f 100644--- a/products/conversations/frontend/components/Assignee/AssigneeMultiSelect.tsx+++ b/products/conversations/frontend/components/Assignee/AssigneeMultiSelect.tsx@@ -9,7 +9,7 @@ import { urls } from 'scenes/urls'import { clearFilterButtonProps } from '../clearFilterButtonProps'import { AssigneeIconDisplay, AssigneeLabelDisplay, AssigneeResolver } from './AssigneeDisplay'import { assigneeSelectLogic } from './assigneeSelectLogic'-import { Assignee, AssigneeFilterEntry, MAX_ASSIGNEE_FILTER_ENTRIES } from './types'+import { Assignee, AssigneeFilterEntry, MAX_ASSIGNEE_FILTER_ENTRIES, toTicketAssignee } from './types'function isSameEntry(a: AssigneeFilterEntry, b: AssigneeFilterEntry): boolean {// String tokens ('unassigned', 'me') only match the identical token.@@ -183,7 +183,7 @@ function TriggerLabel({ value, emptyLabel }: { value: AssigneeFilterEntry[]; emp)}return (- <AssigneeResolver assignee={entry}>+ <AssigneeResolver assignee={toTicketAssignee(entry)}>{({ assignee }) => (<span className="flex items-center gap-1"><AssigneeIconDisplay assignee={assignee} size="small" />@@ -220,7 +220,7 @@ const AssigneeFilterItem = ({size="small"icon={<LemonCheckbox checked={isSelected(item)} className="pointer-events-none" />}disabledReason={isSelected(item) ? undefined : selectionCapReason}- onClick={() => onToggle({ type: item.type, id: item.id })}+ onClick={() => onToggle(toTicketAssignee(item))}><span className="flex items-center gap-1"><AssigneeIconDisplay assignee={item} size="small" />diff --git a/products/conversations/frontend/components/Assignee/types.test.ts b/products/conversations/frontend/components/Assignee/types.test.tsnew file mode 100644index 000000000000..39f7592df4df--- /dev/null+++ b/products/conversations/frontend/components/Assignee/types.test.ts@@ -0,0 +1,10 @@+import { toTicketAssignee } from './types'++describe('toTicketAssignee', () => {+ it.each([+ ['user', { type: 'user' as const, id: 3, user: { email: '[email protected]' } }, { type: 'user', id: 3 }],+ ['role', { type: 'role' as const, id: 'role-1', role: { members: [1, 2] } }, { type: 'role', id: 'role-1' }],+ ])('keeps only the %s identity', (_name, assignee, expected) => {+ expect(toTicketAssignee(assignee)).toEqual(expected)+ })+})diff --git a/products/conversations/frontend/components/Assignee/types.ts b/products/conversations/frontend/components/Assignee/types.tsindex 7ec1dfc6b921..c495561834d6 100644--- a/products/conversations/frontend/components/Assignee/types.ts+++ b/products/conversations/frontend/components/Assignee/types.ts@@ -1,9 +1,8 @@import type { OrganizationMemberType, RoleType } from '~/types'-export type TicketAssignee = {- type: 'user' | 'role'- id: string | number-} | null+import type { TicketAssigneeRequestApi } from '../../generated/api.schemas'++export type TicketAssignee = TicketAssigneeRequestApi | null// `'me'` is a dynamic, per-viewer token: it filters to whoever is currently// signed in, resolved server-side against `request.user`. Unlike a concrete@@ -11,7 +10,11 @@ export type TicketAssignee = {// a "My tickets" view means each teammate's own tickets rather than the// creator's. It's a filter-only concept — a ticket's actual assignee is always// a concrete user/role, never `'me'`.-export type AssigneeFilterEntry = 'unassigned' | 'me' | NonNullable<TicketAssignee>+export type AssigneeFilterEntry = 'unassigned' | 'me' | { type: 'user' | 'role'; id: string | number }++export function toTicketAssignee(entry: Exclude<AssigneeFilterEntry, string>): NonNullable<TicketAssignee> {+ return entry.type === 'user' ? { type: 'user', id: Number(entry.id) } : { type: 'role', id: String(entry.id) }+}/** Mirrors the entry cap the tickets list endpoint applies to the `assignee` param. */export const MAX_ASSIGNEE_FILTER_ENTRIES = 100diff --git a/products/conversations/frontend/components/SavedViews/SavedViewsModal.tsx b/products/conversations/frontend/components/SavedViews/SavedViewsModal.tsxindex b7bbf1be2daa..fb322d20e809 100644--- a/products/conversations/frontend/components/SavedViews/SavedViewsModal.tsx+++ b/products/conversations/frontend/components/SavedViews/SavedViewsModal.tsx@@ -14,6 +14,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'import { type SavedTicketView, type TicketViewFilters, normalizeAssigneeFilter } from '../../types'import { AssigneeLabelDisplay, AssigneeResolver } from '../Assignee'+import { toTicketAssignee } from '../Assignee/types'import { type TicketViewsLogicProps, ticketViewsLogic } from './ticketViewsLogic'function FiltersSummary({ filters }: { filters: TicketViewFilters }): JSX.Element {@@ -52,7 +53,7 @@ function FiltersSummary({ filters }: { filters: TicketViewFilters }): JSX.Elemen) : entry === 'me' ? ('Me (current user)') : (- <AssigneeResolver assignee={entry}>+ <AssigneeResolver assignee={toTicketAssignee(entry)}>{({ assignee }) => (<AssigneeLabelDisplay assignee={assignee} placeholder={`${entry.type}:${entry.id}`} />)}diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 79349969bf09..e1967f2d639a 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -784,15 +784,46 @@ export interface PaginatedTicketListApi {}/**- * Mixin for serializers to add user access control fields+ * Assign the ticket to a user.*/-export interface PatchedTicketApi {- readonly id?: string- readonly ticket_number?: number- readonly channel_source?: ChannelSourceEnumApi- readonly channel_detail?: ChannelDetailEnumApi | null- readonly distinct_id?: string- /** Ticket status: new, open, pending, on_hold, or resolved+export type UserTicketAssigneeRequestApiType =+ (typeof UserTicketAssigneeRequestApiType)[keyof typeof UserTicketAssigneeRequestApiType]++export const UserTicketAssigneeRequestApiType = {+ User: 'user',+} as const++export interface UserTicketAssigneeRequestApi {+ /** Assign the ticket to a user. */+ type: UserTicketAssigneeRequestApiType+ /** User ID. */+ id: number+}++/**+ * Assign the ticket to a role.+ */+export type RoleTicketAssigneeRequestApiType =+ (typeof RoleTicketAssigneeRequestApiType)[keyof typeof RoleTicketAssigneeRequestApiType]++export const RoleTicketAssigneeRequestApiType = {+ Role: 'role',+} as const++export interface RoleTicketAssigneeRequestApi {+ /** Assign the ticket to a role. */+ type: RoleTicketAssigneeRequestApiType+ /** Role ID. */+ id: string+}++export type TicketAssigneeRequestApi = UserTicketAssigneeRequestApi | RoleTicketAssigneeRequestApi++/**+ * Fields accepted when updating a ticket.+ */+export interface TicketUpdateRequestApi {+ /** Ticket status: new, open, pending, on_hold, or resolved.** * `new` - New* * `open` - Open@@ -800,81 +831,80 @@ export interface PatchedTicketApi {* * `on_hold` - On hold* * `resolved` - Resolved */status?: TicketStatusEnumApi- /** Ticket priority: low, medium, high, or critical. Null if unset.+ /** Ticket priority: low, medium, high, or critical. Pass null to clear it.** * `low` - Low* * `medium` - Medium* * `high` - High* * `critical` - Critical */priority?: TicketPriorityEnumApi | BlankEnumApi | null- readonly assignee?: TicketAssignmentApi- /** Customer-provided traits such as name and email */+ /** User or role to assign. Pass null to remove the current assignee. */+ assignee?: TicketAssigneeRequestApi | null+ /** Customer details such as name and email. */anonymous_traits?: unknown+ /** Whether AI resolved the ticket. */+ ai_resolved?: boolean/**- * Trust signal indicating whether the ticket's claimed identity was attested by the server (widget HMAC, SPF-authenticated email, or a signature-validated platform webhook). True when verified, false when assessed but not attested, null when unknown (e.g. created before this signal existed).+ * Reason the ticket was escalated. Pass null to clear it.* @nullable*/- readonly identity_verified?: boolean | null- ai_resolved?: boolean- /** @nullable */escalation_reason?: string | null- /** AI support pipeline triage and outcome (status, result, ticket_type, confidence, attempts, etc.). */- readonly ai_triage?: unknown- readonly created_at?: string- readonly updated_at?: string- readonly message_count?: number- /** @nullable */- readonly last_message_at?: string | null- /** @nullable */- readonly last_message_text?: string | null- readonly unread_team_count?: number- readonly unread_customer_count?: number- /** @nullable */- readonly session_id?: string | null- readonly session_context?: unknown/**- * SLA deadline set via workflows. Null means no SLA.+ * SLA deadline. Pass null to clear it.* @nullable*/sla_due_at?: string | null- /** @nullable */+ /**+ * Time to reopen the ticket. Pass null to reopen it now.+ * @nullable+ */snoozed_until?: string | null- /** @nullable */- readonly slack_channel_id?: string | null- /** @nullable */- readonly slack_thread_ts?: string | null- /** @nullable */- readonly slack_team_id?: string | null- /** @nullable */- readonly email_subject?: string | null- /** @nullable */- readonly email_from?: string | null- /** @nullable */- readonly email_to?: string | null- readonly cc_participants?: unknown- /** @nullable */- readonly github_repo?: string | null- /** @nullable */- readonly github_issue_number?: number | null- /** @nullable */- readonly zendesk_ticket_id?: number | null+ /** Tag names to set on the ticket. */+ tags?: string[]+}++/**+ * Fields accepted when updating a ticket.+ */+export interface PatchedTicketUpdateRequestApi {+ /** Ticket status: new, open, pending, on_hold, or resolved.+ *+ * * `new` - New+ * * `open` - Open+ * * `pending` - Pending+ * * `on_hold` - On hold+ * * `resolved` - Resolved */+ status?: TicketStatusEnumApi+ /** Ticket priority: low, medium, high, or critical. Pass null to clear it.+ *+ * * `low` - Low+ * * `medium` - Medium+ * * `high` - High+ * * `critical` - Critical */+ priority?: TicketPriorityEnumApi | BlankEnumApi | null+ /** User or role to assign. Pass null to remove the current assignee. */+ assignee?: TicketAssigneeRequestApi | null+ /** Customer details such as name and email. */+ anonymous_traits?: unknown+ /** Whether AI resolved the ticket. */+ ai_resolved?: boolean/**- * Customer's PostHog organization group key, resolved at ticket creation. Null when unknown.+ * Reason the ticket was escalated. Pass null to clear it.* @nullable*/- readonly organization_id?: string | null+ escalation_reason?: string | null/**- * How organization_id was resolved: 'person' (from the requester's identity) or 'slack_channel_account' (inferred from the customer analytics account linked to the ticket's Slack channel). Null when organization_id is unset.+ * SLA deadline. Pass null to clear it.* @nullable*/- readonly organization_id_source?: string | null- readonly person?: TicketPersonApi | null- tags?: unknown[]+ sla_due_at?: string | null/**- * The effective access level the user has for this object+ * Time to reopen the ticket. Pass null to reopen it now.* @nullable*/- readonly user_access_level?: string | null+ snoozed_until?: string | null+ /** Tag names to set on the ticket. */+ tags?: string[]}/**diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.tsindex 36d5e27fccd6..faf4ce72018b 100644--- a/products/conversations/frontend/generated/api.ts+++ b/products/conversations/frontend/generated/api.ts@@ -28,14 +28,15 @@ import type {PaginatedTicketMessageListApi,PaginatedTicketViewListApi,PatchedConversationApi,- PatchedTicketApi,PatchedTicketNoteUpdateRequestApi,+ PatchedTicketUpdateRequestApi,PatchedTicketViewApi,SandboxMessageResponseApi,SandboxOpenApi,TicketApi,TicketMessageApi,TicketReplyRequestApi,+ TicketUpdateRequestApi,TicketViewApi,ZendeskImportJobApi,ZendeskImportStartApi,@@ -350,14 +351,14 @@ export const getConversationsTicketsUpdateUrl = (projectId: string, id: string)export const conversationsTicketsUpdate = async (projectId: string,id: string,- ticketApi?: NonReadonly<TicketApi>,+ ticketUpdateRequestApi?: TicketUpdateRequestApi,options?: RequestInit): Promise<TicketApi> => {return apiMutator<TicketApi>(getConversationsTicketsUpdateUrl(projectId, id), {...options,method: 'PUT',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(ticketApi),+ body: JSON.stringify(ticketUpdateRequestApi),})}@@ -368,14 +369,14 @@ export const getConversationsTicketsPartialUpdateUrl = (projectId: string, id: sexport const conversationsTicketsPartialUpdate = async (projectId: string,id: string,- patchedTicketApi?: NonReadonly<PatchedTicketApi>,+ patchedTicketUpdateRequestApi?: PatchedTicketUpdateRequestApi,options?: RequestInit): Promise<TicketApi> => {return apiMutator<TicketApi>(getConversationsTicketsPartialUpdateUrl(projectId, id), {...options,method: 'PATCH',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedTicketApi),+ body: JSON.stringify(patchedTicketUpdateRequestApi),})}diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.tsindex 0d5c3175becf..c5b26327efc1 100644--- a/products/conversations/frontend/generated/api.zod.ts+++ b/products/conversations/frontend/generated/api.zod.ts@@ -166,7 +166,7 @@ export const ConversationsTicketsUpdateBody = /* @__PURE__ */ zod).optional().describe(- 'Ticket status: new, open, pending, on_hold, or resolved\n\n\* `new` - New\n\* `open` - Open\n\* `pending` - Pending\n\* `on_hold` - On hold\n\* `resolved` - Resolved'+ 'Ticket status: new, open, pending, on_hold, or resolved.\n\n\* `new` - New\n\* `open` - Open\n\* `pending` - Pending\n\* `on_hold` - On hold\n\* `resolved` - Resolved'),priority: zod.union([@@ -178,19 +178,35 @@ export const ConversationsTicketsUpdateBody = /* @__PURE__ */ zod]).optional().describe(- 'Ticket priority: low, medium, high, or critical. Null if unset.\n\n\* `low` - Low\n\* `medium` - Medium\n\* `high` - High\n\* `critical` - Critical'+ 'Ticket priority: low, medium, high, or critical. Pass null to clear it.\n\n\* `low` - Low\n\* `medium` - Medium\n\* `high` - High\n\* `critical` - Critical'),- anonymous_traits: zod.unknown().optional().describe('Customer-provided traits such as name and email'),- ai_resolved: zod.boolean().optional(),- escalation_reason: zod.string().nullish(),- sla_due_at: zod.iso+ assignee: zod+ .union([+ zod.union([+ zod.object({+ type: zod.enum(['user']).describe('Assign the ticket to a user.'),+ id: zod.number().describe('User ID.'),+ }),+ zod.object({+ type: zod.enum(['role']).describe('Assign the ticket to a role.'),+ id: zod.uuid().describe('Role ID.'),+ }),+ ]),+ zod.null(),+ ])+ .optional()+ .describe('User or role to assign. Pass null to remove the current assignee.'),+ anonymous_traits: zod.unknown().optional().describe('Customer details such as name and email.'),+ ai_resolved: zod.boolean().optional().describe('Whether AI resolved the ticket.'),+ escalation_reason: zod.string().nullish().describe('Reason the ticket was escalated. Pass null to clear it.'),+ sla_due_at: zod.iso.datetime({ offset: true }).nullish().describe('SLA deadline. Pass null to clear it.'),+ snoozed_until: zod.iso.datetime({ offset: true }).nullish()- .describe('SLA deadline set via workflows. Null means no SLA.'),- snoozed_until: zod.iso.datetime({ offset: true }).nullish(),- tags: zod.array(zod.unknown()).optional(),+ .describe('Time to reopen the ticket. Pass null to reopen it now.'),+ tags: zod.array(zod.string()).optional().describe('Tag names to set on the ticket.'),})- .describe('Mixin for serializers to add user access control fields')+ .describe('Fields accepted when updating a ticket.')export const ConversationsTicketsPartialUpdateBody = /* @__PURE__ */ zod.object({@@ -201,7 +217,7 @@ export const ConversationsTicketsPartialUpdateBody = /* @__PURE__ */ zod).optional().describe(- 'Ticket status: new, open, pending, on_hold, or resolved\n\n\* `new` - New\n\* `open` - Open\n\* `pending` - Pending\n\* `on_hold` - On hold\n\* `resolved` - Resolved'+ 'Ticket status: new, open, pending, on_hold, or resolved.\n\n\* `new` - New\n\* `open` - Open\n\* `pending` - Pending\n\* `on_hold` - On hold\n\* `resolved` - Resolved'),priority: zod.union([@@ -213,19 +229,35 @@ export const ConversationsTicketsPartialUpdateBody = /* @__PURE__ */ zod]).optional().describe(- 'Ticket priority: low, medium, high, or critical. Null if unset.\n\n\* `low` - Low\n\* `medium` - Medium\n\* `high` - High\n\* `critical` - Critical'+ 'Ticket priority: low, medium, high, or critical. Pass null to clear it.\n\n\* `low` - Low\n\* `medium` - Medium\n\* `high` - High\n\* `critical` - Critical'),- anonymous_traits: zod.unknown().optional().describe('Customer-provided traits such as name and email'),- ai_resolved: zod.boolean().optional(),- escalation_reason: zod.string().nullish(),- sla_due_at: zod.iso+ assignee: zod+ .union([+ zod.union([+ zod.object({+ type: zod.enum(['user']).describe('Assign the ticket to a user.'),+ id: zod.number().describe('User ID.'),+ }),+ zod.object({+ type: zod.enum(['role']).describe('Assign the ticket to a role.'),+ id: zod.uuid().describe('Role ID.'),+ }),+ ]),+ zod.null(),+ ])+ .optional()+ .describe('User or role to assign. Pass null to remove the current assignee.'),+ anonymous_traits: zod.unknown().optional().describe('Customer details such as name and email.'),+ ai_resolved: zod.boolean().optional().describe('Whether AI resolved the ticket.'),+ escalation_reason: zod.string().nullish().describe('Reason the ticket was escalated. Pass null to clear it.'),+ sla_due_at: zod.iso.datetime({ offset: true }).nullish().describe('SLA deadline. Pass null to clear it.'),+ snoozed_until: zod.iso.datetime({ offset: true }).nullish()- .describe('SLA deadline set via workflows. Null means no SLA.'),- snoozed_until: zod.iso.datetime({ offset: true }).nullish(),- tags: zod.array(zod.unknown()).optional(),+ .describe('Time to reopen the ticket. Pass null to reopen it now.'),+ tags: zod.array(zod.string()).optional().describe('Tag names to set on the ticket.'),})- .describe('Mixin for serializers to add user access control fields')+ .describe('Fields accepted when updating a ticket.')/*** Record reviewer feedback on an AI reply, captured to the internal analytics project.diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.tsindex 5dda7e6b8c1f..7db577d1ab15 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts@@ -64,11 +64,15 @@ jest.mock('products/business_knowledge/frontend/generated/api', () => ({jest.mock('products/conversations/frontend/generated/api', () => ({conversationsTicketsNotesPartialUpdate: jest.fn().mockResolvedValue(undefined),conversationsTicketsNotesDestroy: jest.fn().mockResolvedValue(undefined),+ conversationsTicketsPartialUpdate: jest.fn(),}))import api from '~/lib/api'-import { conversationsTicketsNotesPartialUpdate } from 'products/conversations/frontend/generated/api'+import {+ conversationsTicketsNotesPartialUpdate,+ conversationsTicketsPartialUpdate,+} from 'products/conversations/frontend/generated/api'const submitAiFeedbackMock = api.conversationsTickets.submitAiFeedback as jest.Mock@@ -343,7 +347,7 @@ describe('supportTicketSceneLogic sendMessage with statusAfterSend', () => {const createResponseMock = api.createResponse as jest.Mockconst ticketGetMock = api.conversationsTickets.get as jest.Mock- const ticketUpdateMock = api.conversationsTickets.update as jest.Mock+ const ticketUpdateMock = conversationsTicketsPartialUpdate as jest.Mock// Unlike makeTicket(), API responses always carry priority/assignee; without them the// hasUnsavedChanges comparison against the seeded local reducers never settles to false.@@ -382,6 +386,7 @@ describe('supportTicketSceneLogic sendMessage with statusAfterSend', () => {}).toDispatchActions(['updateTicket', 'setTicket'])expect(ticketUpdateMock).toHaveBeenCalledWith(+ expect.any(String),'42',expect.objectContaining({ status: statusAfterSend, assignee: presetAssignee }))@@ -423,7 +428,7 @@ describe('supportTicketSceneLogic sendMessage with statusAfterSend', () => {resolveFirst = () => resolve({ ...loadedTicket(), status: 'resolved' })}))- ticketUpdateMock.mockImplementationOnce((_id: string, data: Record<string, unknown>) =>+ ticketUpdateMock.mockImplementationOnce((_projectId: string, _id: string, data: Record<string, unknown>) =>Promise.resolve({ ...loadedTicket(), ...data }))@@ -437,7 +442,11 @@ describe('supportTicketSceneLogic sendMessage with statusAfterSend', () => {await expectLogic(logic).toFinishAllListeners()expect(ticketUpdateMock).toHaveBeenCalledTimes(2)- expect(ticketUpdateMock).toHaveBeenLastCalledWith('42', expect.objectContaining({ status: 'pending' }))+ expect(ticketUpdateMock).toHaveBeenLastCalledWith(+ expect.any(String),+ '42',+ expect.objectContaining({ status: 'pending' })+ )expect(logic.values.status).toBe('pending')expect(logic.values.ticketUpdating).toBe(false)})@@ -616,7 +625,7 @@ describe('supportTicketSceneLogic tag pool refresh', () => {let logic: ReturnType<typeof supportTicketSceneLogic.build>const ticketGetMock = api.conversationsTickets.get as jest.Mock- const ticketUpdateMock = api.conversationsTickets.update as jest.Mock+ const ticketUpdateMock = conversationsTicketsPartialUpdate as jest.Mockconst tagsListMock = api.tags.list as jest.Mockconst loadedTicket = (): Ticket => ({ ...makeTicket(), priority: 'medium', assignee: null }) as Ticketdiff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex 4d2bcb196b5d..cf3a24731b3b 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -51,7 +51,9 @@ import {import {conversationsTicketsNotesDestroy,conversationsTicketsNotesPartialUpdate,+ conversationsTicketsPartialUpdate,} from 'products/conversations/frontend/generated/api'+import type { PatchedTicketUpdateRequestApi } from 'products/conversations/frontend/generated/api.schemas'import { getCommentsCreateUrl } from 'products/platform_features/frontend/generated/api'import { signalsReportsList } from 'products/signals/frontend/generated/api'import type { SignalReportApi } from 'products/signals/frontend/generated/api.schemas'@@ -1213,13 +1215,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([}breakpoint()- const data: Partial<{- status: string- priority: string- assignee: TicketAssignee- tags: string[]- snoozed_until: string | null- }> = {}+ const data: PatchedTicketUpdateRequestApi = {}if (values.status && values.status !== values.ticket?.status) {data.status = values.status@@ -1231,12 +1227,12 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([data.tags = values.tagsdata.snoozed_until = values.snoozedUntil- const request = api.conversationsTickets.update(props.id.toString(), data)+ const request = conversationsTicketsPartialUpdate(String(getCurrentTeamId()), props.id.toString(), data)cache.ticketUpdateRequest = requesttry {const ticket = await requestbreakpoint()- actions.setTicket(ticket)+ actions.setTicket(ticket as Ticket)lemonToast.success('Ticket updated')actions.loadTickets()// tagsModel loads once per session and never refetches, so newly created tags need an explicit reloaddiff --git a/products/dashboards/frontend/widgets/conversations/conversationsWidgetLogic.test.ts b/products/dashboards/frontend/widgets/conversations/conversationsWidgetLogic.test.tsindex 27949d76bba6..4d35465a9ff3 100644--- a/products/dashboards/frontend/widgets/conversations/conversationsWidgetLogic.test.ts+++ b/products/dashboards/frontend/widgets/conversations/conversationsWidgetLogic.test.ts@@ -1,12 +1,17 @@import { expectLogic } from 'kea-test-utils'-import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { initKeaTests } from '~/test/init'+import { conversationsTicketsPartialUpdate } from 'products/conversations/frontend/generated/api'+import { conversationsWidgetLogic } from './conversationsWidgetLogic'+jest.mock('products/conversations/frontend/generated/api', () => ({+ conversationsTicketsPartialUpdate: jest.fn(),+}))+describe('conversationsWidgetLogic', () => {beforeEach(() => {initKeaTests()@@ -14,7 +19,8 @@ describe('conversationsWidgetLogic', () => {it('updates the assignee and refreshes the tile', async () => {const refresh = jest.fn()- const update = jest.spyOn(api.conversationsTickets, 'update').mockResolvedValue({} as never)+ const update = conversationsTicketsPartialUpdate as jest.Mock+ update.mockResolvedValue({})const logic = conversationsWidgetLogic({ tileId: 1, onRefreshData: refresh })logic.mount()@@ -22,14 +28,17 @@ describe('conversationsWidgetLogic', () => {.toFinishAllListeners().toMatchValues({ ticketAssignmentLoadingId: null })- expect(update).toHaveBeenCalledWith('ticket-1', { assignee: { type: 'user', id: 3 } })+ expect(update).toHaveBeenCalledWith(expect.any(String), 'ticket-1', {+ assignee: { type: 'user', id: 3 },+ })expect(refresh).toHaveBeenCalledTimes(1)logic.unmount()})it('shows an error and permits another assignment after a failed request', async () => {const errorToast = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')- jest.spyOn(api.conversationsTickets, 'update').mockRejectedValue(new Error('Network unavailable'))+ const update = conversationsTicketsPartialUpdate as jest.Mock+ update.mockRejectedValue(new Error('Network unavailable'))const logic = conversationsWidgetLogic({ tileId: 1 })logic.mount()diff --git a/products/dashboards/frontend/widgets/conversations/conversationsWidgetLogic.ts b/products/dashboards/frontend/widgets/conversations/conversationsWidgetLogic.tsindex 4eeea4554acf..e3920657a397 100644--- a/products/dashboards/frontend/widgets/conversations/conversationsWidgetLogic.ts+++ b/products/dashboards/frontend/widgets/conversations/conversationsWidgetLogic.ts@@ -1,9 +1,10 @@import { MakeLogicType, actions, kea, key, listeners, path, props, reducers } from 'kea'-import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { getCurrentTeamId } from 'lib/utils/getAppContext'import type { TicketAssignee } from 'products/conversations/frontend/components/Assignee'+import { conversationsTicketsPartialUpdate } from 'products/conversations/frontend/generated/api'export interface ConversationsWidgetLogicProps {tileId: number@@ -54,7 +55,7 @@ export const conversationsWidgetLogic = kea<conversationsWidgetLogicType>([}actions.assignTicketLoading(ticketId)try {- await api.conversationsTickets.update(ticketId, { assignee })+ await conversationsTicketsPartialUpdate(String(getCurrentTeamId()), ticketId, { assignee })actions.assignTicketSuccess(ticketId)props.onRefreshData?.()} catch {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7689d6ca6436..7b0f6bd9d162 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -66185,15 +66185,59 @@ export namespace Schemas {}/**- * Mixin for serializers to add user access control fields+ * Payload for updating a private note on a ticket.*/- export interface PatchedTicket {- readonly id?: string;- readonly ticket_number?: number;- readonly channel_source?: ChannelSourceEnum;- readonly channel_detail?: ChannelDetailEnum | null;- readonly distinct_id?: string;- /** Ticket status: new, open, pending, on_hold, or resolved+ export interface PatchedTicketNoteUpdateRequest {+ /**+ * Updated note content in markdown.+ * @maxLength 5000+ */+ message?: string;+ /** Optional TipTap rich content JSON. Omit or pass null to clear previous rich content so the thread falls back to the markdown message. */+ rich_content?: unknown;+ }++ /**+ * Assign the ticket to a user.+ */+ export type UserTicketAssigneeRequestType = typeof UserTicketAssigneeRequestType[keyof typeof UserTicketAssigneeRequestType];+++ export const UserTicketAssigneeRequestType = {+ User: 'user',+ } as const;++ export interface UserTicketAssigneeRequest {+ /** Assign the ticket to a user. */+ type: UserTicketAssigneeRequestType;+ /** User ID. */+ id: number;+ }++ /**+ * Assign the ticket to a role.+ */+ export type RoleTicketAssigneeRequestType = typeof RoleTicketAssigneeRequestType[keyof typeof RoleTicketAssigneeRequestType];+++ export const RoleTicketAssigneeRequestType = {+ Role: 'role',+ } as const;++ export interface RoleTicketAssigneeRequest {+ /** Assign the ticket to a role. */+ type: RoleTicketAssigneeRequestType;+ /** Role ID. */+ id: string;+ }++ export type TicketAssigneeRequest = UserTicketAssigneeRequest | RoleTicketAssigneeRequest;++ /**+ * Fields accepted when updating a ticket.+ */+ export interface PatchedTicketUpdateRequest {+ /** Ticket status: new, open, pending, on_hold, or resolved.** * `new` - New* * `open` - Open@@ -66201,94 +66245,36 @@ export namespace Schemas {* * `on_hold` - On hold* * `resolved` - Resolved */status?: TicketStatusEnum;- /** Ticket priority: low, medium, high, or critical. Null if unset.+ /** Ticket priority: low, medium, high, or critical. Pass null to clear it.** * `low` - Low* * `medium` - Medium* * `high` - High* * `critical` - Critical */priority?: TicketPriorityEnum | BlankEnum | null;- readonly assignee?: TicketAssignment;- /** Customer-provided traits such as name and email */+ /** User or role to assign. Pass null to remove the current assignee. */+ assignee?: TicketAssigneeRequest | null;+ /** Customer details such as name and email. */anonymous_traits?: unknown;+ /** Whether AI resolved the ticket. */+ ai_resolved?: boolean;/**- * Trust signal indicating whether the ticket's claimed identity was attested by the server (widget HMAC, SPF-authenticated email, or a signature-validated platform webhook). True when verified, false when assessed but not attested, null when unknown (e.g. created before this signal existed).+ * Reason the ticket was escalated. Pass null to clear it.* @nullable*/- readonly identity_verified?: boolean | null;- ai_resolved?: boolean;- /** @nullable */escalation_reason?: string | null;- /** AI support pipeline triage and outcome (status, result, ticket_type, confidence, attempts, etc.). */- readonly ai_triage?: unknown;- readonly created_at?: string;- readonly updated_at?: string;- readonly message_count?: number;- /** @nullable */- readonly last_message_at?: string | null;- /** @nullable */- readonly last_message_text?: string | null;- readonly unread_team_count?: number;- readonly unread_customer_count?: number;- /** @nullable */- readonly session_id?: string | null;- readonly session_context?: unknown;/**- * SLA deadline set via workflows. Null means no SLA.+ * SLA deadline. Pass null to clear it.* @nullable*/sla_due_at?: string | null;- /** @nullable */- snoozed_until?: string | null;- /** @nullable */- readonly slack_channel_id?: string | null;- /** @nullable */- readonly slack_thread_ts?: string | null;- /** @nullable */- readonly slack_team_id?: string | null;- /** @nullable */- readonly email_subject?: string | null;- /** @nullable */- readonly email_from?: string | null;- /** @nullable */- readonly email_to?: string | null;- readonly cc_participants?: unknown;- /** @nullable */- readonly github_repo?: string | null;- /** @nullable */- readonly github_issue_number?: number | null;- /** @nullable */- readonly zendesk_ticket_id?: number | null;- /**- * Customer's PostHog organization group key, resolved at ticket creation. Null when unknown.- * @nullable- */- readonly organization_id?: string | null;/**- * How organization_id was resolved: 'person' (from the requester's identity) or 'slack_channel_account' (inferred from the customer analytics account linked to the ticket's Slack channel). Null when organization_id is unset.+ * Time to reopen the ticket. Pass null to reopen it now.* @nullable*/- readonly organization_id_source?: string | null;- readonly person?: TicketPerson | null;- tags?: unknown[];- /**- * The effective access level the user has for this object- * @nullable- */- readonly user_access_level?: string | null;- }-- /**- * Payload for updating a private note on a ticket.- */- export interface PatchedTicketNoteUpdateRequest {- /**- * Updated note content in markdown.- * @maxLength 5000- */- message?: string;- /** Optional TipTap rich content JSON. Omit or pass null to clear previous rich content so the thread falls back to the markdown message. */- rich_content?: unknown;+ snoozed_until?: string | null;+ /** Tag names to set on the ticket. */+ tags?: string[];}export interface PatchedTicketView {@@ -84272,6 +84258,50 @@ export namespace Schemas {rich_content?: unknown;}+ /**+ * Fields accepted when updating a ticket.+ */+ export interface TicketUpdateRequest {+ /** Ticket status: new, open, pending, on_hold, or resolved.+ *+ * * `new` - New+ * * `open` - Open+ * * `pending` - Pending+ * * `on_hold` - On hold+ * * `resolved` - Resolved */+ status?: TicketStatusEnum;+ /** Ticket priority: low, medium, high, or critical. Pass null to clear it.+ *+ * * `low` - Low+ * * `medium` - Medium+ * * `high` - High+ * * `critical` - Critical */+ priority?: TicketPriorityEnum | BlankEnum | null;+ /** User or role to assign. Pass null to remove the current assignee. */+ assignee?: TicketAssigneeRequest | null;+ /** Customer details such as name and email. */+ anonymous_traits?: unknown;+ /** Whether AI resolved the ticket. */+ ai_resolved?: boolean;+ /**+ * Reason the ticket was escalated. Pass null to clear it.+ * @nullable+ */+ escalation_reason?: string | null;+ /**+ * SLA deadline. Pass null to clear it.+ * @nullable+ */+ sla_due_at?: string | null;+ /**+ * Time to reopen the ticket. Pass null to reopen it now.+ * @nullable+ */+ snoozed_until?: string | null;+ /** Tag names to set on the ticket. */+ tags?: string[];+ }+export interface TopPage {/** Host for the page, if recorded. */host: string;diff --git a/services/mcp/src/generated/conversations/api.ts b/services/mcp/src/generated/conversations/api.tsindex 2fe63471d04c..3c4a72d87a71 100644--- a/services/mcp/src/generated/conversations/api.ts+++ b/services/mcp/src/generated/conversations/api.ts@@ -159,7 +159,7 @@ export const ConversationsTicketsPartialUpdateBody = /* @__PURE__ */ zod).optional().describe(- 'Ticket status: new, open, pending, on_hold, or resolved\n\n\* `new` - New\n\* `open` - Open\n\* `pending` - Pending\n\* `on_hold` - On hold\n\* `resolved` - Resolved'+ 'Ticket status: new, open, pending, on_hold, or resolved.\n\n\* `new` - New\n\* `open` - Open\n\* `pending` - Pending\n\* `on_hold` - On hold\n\* `resolved` - Resolved'),priority: zod.union([@@ -171,16 +171,32 @@ export const ConversationsTicketsPartialUpdateBody = /* @__PURE__ */ zod]).optional().describe(- 'Ticket priority: low, medium, high, or critical. Null if unset.\n\n\* `low` - Low\n\* `medium` - Medium\n\* `high` - High\n\* `critical` - Critical'+ 'Ticket priority: low, medium, high, or critical. Pass null to clear it.\n\n\* `low` - Low\n\* `medium` - Medium\n\* `high` - High\n\* `critical` - Critical'),- sla_due_at: zod.iso+ assignee: zod+ .union([+ zod.union([+ zod.object({+ type: zod.enum(['user']).describe('Assign the ticket to a user.'),+ id: zod.number().describe('User ID.'),+ }),+ zod.object({+ type: zod.enum(['role']).describe('Assign the ticket to a role.'),+ id: zod.string().describe('Role ID.'),+ }),+ ]),+ zod.null(),+ ])+ .optional()+ .describe('User or role to assign. Pass null to remove the current assignee.'),+ sla_due_at: zod.iso.datetime({ offset: true }).nullish().describe('SLA deadline. Pass null to clear it.'),+ snoozed_until: zod.iso.datetime({ offset: true }).nullish()- .describe('SLA deadline set via workflows. Null means no SLA.'),- snoozed_until: zod.iso.datetime({ offset: true }).nullish(),- tags: zod.array(zod.unknown()).optional(),+ .describe('Time to reopen the ticket. Pass null to reopen it now.'),+ tags: zod.array(zod.string()).optional().describe('Tag names to set on the ticket.'),})- .describe('Mixin for serializers to add user access control fields')+ .describe('Fields accepted when updating a ticket.')/*** Return the message thread for a ticket, ordered chronologically (paginated).diff --git a/services/mcp/src/tools/generated/conversations.ts b/services/mcp/src/tools/generated/conversations.tsindex bf9071c9be86..72f9f6bb4ffc 100644--- a/services/mcp/src/tools/generated/conversations.ts+++ b/services/mcp/src/tools/generated/conversations.ts@@ -245,6 +245,9 @@ const conversationsTicketsUpdate = (): ToolBase<if (params.priority !== undefined) {body['priority'] = params.priority}+ if (params.assignee !== undefined) {+ body['assignee'] = params.assignee+ }if (params.sla_due_at !== undefined) {body['sla_due_at'] = params.sla_due_at}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-update.jsonindex 718d529e2e0c..c9af584e28b6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-update.json@@ -1,6 +1,48 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "assignee": {+ "anyOf": [+ {+ "anyOf": [+ {+ "properties": {+ "id": {+ "description": "User ID.",+ "type": "number"+ },+ "type": {+ "description": "Assign the ticket to a user.",+ "enum": ["user"],+ "type": "string"+ }+ },+ "required": ["type", "id"],+ "type": "object"+ },+ {+ "properties": {+ "id": {+ "description": "Role ID.",+ "type": "string"+ },+ "type": {+ "description": "Assign the ticket to a role.",+ "enum": ["role"],+ "type": "string"+ }+ },+ "required": ["type", "id"],+ "type": "object"+ }+ ]+ },+ {+ "type": "null"+ }+ ],+ "description": "User or role to assign. Pass null to remove the current assignee."+ },"id": {"description": "The ticket's UUID or its numeric ticket number.","type": "string"@@ -20,7 +62,7 @@"type": "null"}],- "description": "Ticket priority: low, medium, high, or critical. Null if unset.\n\n* `low` - Low\n* `medium` - Medium\n* `high` - High\n* `critical` - Critical"+ "description": "Ticket priority: low, medium, high, or critical. Pass null to clear it.\n\n* `low` - Low\n* `medium` - Medium\n* `high` - High\n* `critical` - Critical"},"sla_due_at": {"anyOf": [@@ -33,7 +75,7 @@"type": "null"}],- "description": "SLA deadline set via workflows. Null means no SLA."+ "description": "SLA deadline. Pass null to clear it."},"snoozed_until": {"anyOf": [@@ -45,15 +87,19 @@{"type": "null"}- ]+ ],+ "description": "Time to reopen the ticket. Pass null to reopen it now."},"status": {- "description": "Ticket status: new, open, pending, on_hold, or resolved\n\n* `new` - New\n* `open` - Open\n* `pending` - Pending\n* `on_hold` - On hold\n* `resolved` - Resolved",+ "description": "Ticket status: new, open, pending, on_hold, or resolved.\n\n* `new` - New\n* `open` - Open\n* `pending` - Pending\n* `on_hold` - On hold\n* `resolved` - Resolved","enum": ["new", "open", "pending", "on_hold", "resolved"],"type": "string"},"tags": {- "items": {},+ "description": "Tag names to set on the ticket.",+ "items": {+ "type": "string"+ },"type": "array"}},