:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(conversations): apply saved ticket views server-side via ?view= param (#73893)
Luke Belton1899f945fd46
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex f014425a7a36..1b7562fdf634 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -571,6 +571,12 @@ SPECTACULAR_SETTINGS = {"EvaluationTargetEnum": "products.ai_observability.backend.models.evaluations.EvaluationTarget","IntegrationKindEnum": "posthog.models.integration.Integration.IntegrationKind","TicketStatusEnum": "products.conversations.backend.models.constants.Status",+ # Shared by Ticket.priority and TicketViewFilters.priority (same choice set).+ "TicketPriorityEnum": "products.conversations.backend.models.constants.Priority",+ "TicketChannelFilterEnum": "products.conversations.backend.api.ticket_filters.TICKET_CHANNEL_FILTER_CHOICES",+ "TicketSlaFilterEnum": "products.conversations.backend.api.ticket_filters.TICKET_SLA_FILTER_CHOICES",+ "TicketTagsMatchEnum": "products.conversations.backend.api.ticket_filters.TICKET_TAGS_MATCH_CHOICES",+ "TicketSortOrderEnum": "products.conversations.backend.api.ticket_filters.TICKET_SORT_ORDER_CHOICES","BatchImportStatusEnum": "products.managed_migrations.backend.models.batch_imports.BatchImport.Status",# Shared by ExperimentMetricsRecalculation.status and ActiveRecalculationRun.status (same choice set)."MetricsRecalculationStatusEnum": (diff --git a/products/conversations/backend/api/tests/test_ticket_views.py b/products/conversations/backend/api/tests/test_ticket_views.pyindex 03fb182849c5..f31fe428fd75 100644--- a/products/conversations/backend/api/tests/test_ticket_views.py+++ b/products/conversations/backend/api/tests/test_ticket_views.py@@ -1,12 +1,17 @@from posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.test import SimpleTestCase+from parameterized import parameterizedfrom rest_framework import status+from rest_framework.exceptions import ValidationErrorfrom rest_framework.test import APIClientfrom posthog.models.team.team import Team+from products.conversations.backend.api.ticket_filters import TicketViewFiltersSerializer+from products.conversations.backend.api.ticket_views import TicketViewFiltersFieldfrom products.conversations.backend.models import TicketView, TicketViewFavorite@@ -107,7 +112,10 @@ class TestTicketViewAPI(APIBaseTest):def test_update_filters_keeps_name(self):created = self._create_via_api()- new_filters = {"status": ["resolved"], "assignee": {"type": "role", "id": "abc"}}+ new_filters = {+ "status": ["resolved"],+ "assignee": {"type": "role", "id": "9c9a4c7e-9ab5-4f30-9b74-3d1e9f9d3a01"},+ }response = self.client.patch(f"{self.base_url}{created['short_id']}/",{"filters": new_filters},@@ -134,7 +142,7 @@ class TestTicketViewAPI(APIBaseTest):"priority": ["high", "medium"],"channel": "slack","sla": "breached",- "assignee": "user:1",+ "assignee": [{"type": "user", "id": 1}],"tags": ["bug", "urgent"],"dateFrom": "-7d","dateTo": None,@@ -155,6 +163,30 @@ class TestTicketViewAPI(APIBaseTest):response = self.client.post(self.base_url, payload, format="json")assert response.status_code == status.HTTP_400_BAD_REQUEST+ @parameterized.expand(+ [+ ("bad_status", {"status": ["bogus"]}),+ # Only rejected in strict mode, so this case proves the write path passes strict_writes.+ ("assignee_string_token", {"assignee": ["user:1"]}),+ ]+ )+ def test_create_rejects_invalid_filter_values(self, _label, filters):+ # Wiring guard: the endpoint must run TicketViewFiltersSerializer, so a filter+ # value the canonical shape rejects never reaches the database.+ response = self.client.post(+ self.base_url,+ {"name": "Bad view", "filters": filters},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not TicketView.objects.filter(team=self.team).exists()++ def test_unknown_filter_keys_survive_round_trip(self):+ # Filters are stored raw, so keys a newer frontend adds must not be dropped+ # by an older backend's stricter validation.+ data = self._create_via_api(filters={"status": ["open"], "futureKey": True})+ assert data["filters"] == {"status": ["open"], "futureKey": True}+# --- Read-only fields ---def test_short_id_ignored_on_create(self):@@ -266,3 +298,113 @@ class TestTicketViewAPI(APIBaseTest):client = APIClient()response = client.get(self.base_url)assert response.status_code == status.HTTP_401_UNAUTHORIZED+++class TestTicketViewFiltersValidation(SimpleTestCase):+ # No DB: TicketViewFiltersSerializer validation runs entirely in memory. The wiring+ # guard in TestTicketViewAPI proves the endpoint invokes it.++ @parameterized.expand(+ [+ ("empty", {}),+ (+ "frontend_defaults",+ {+ "status": [],+ "priority": [],+ "channel": "all",+ "sla": "all",+ "aiTriageResult": [],+ "assignee": "all",+ "tags": [],+ "tagsMatch": "any",+ "tagsExclude": [],+ "sorting": {"columnKey": "updated_at", "order": -1},+ "search": "",+ },+ ),+ (+ "fully_populated",+ {+ "status": ["open", "pending"],+ "priority": ["high", "critical"],+ "channel": "email",+ "sla": "at-risk",+ "aiTriageResult": ["escalated_no_reply", "in_progress"],+ "assignee": ["me", "unassigned", {"type": "user", "id": 1}, {"type": "role", "id": "abc"}],+ "tags": ["billing"],+ "tagsMatch": "all",+ "tagsExclude": ["spam"],+ "dateFrom": "-30d",+ "dateTo": None,+ "sorting": {"columnKey": "created_at", "order": 1},+ "search": "refund",+ },+ ),+ ("legacy_single_assignee", {"assignee": {"type": "user", "id": 5}}),+ ("null_sorting", {"sorting": None}),+ ("unknown_keys_ignored", {"futureKey": True}),+ ]+ )+ def test_accepts_saved_view_shapes(self, _label, filters):+ serializer = TicketViewFiltersSerializer(data=filters)+ assert serializer.is_valid(), serializer.errors++ @parameterized.expand(+ [+ ("bad_status", {"status": ["bogus"]}),+ ("bad_channel", {"channel": "phone"}),+ ("bad_sla", {"sla": "late"}),+ ("bad_tags_match", {"tagsMatch": "some"}),+ ("bad_triage_result", {"aiTriageResult": ["nope"]}),+ ("sorting_missing_order", {"sorting": {"columnKey": "updated_at"}}),+ ("search_too_long", {"search": "x" * 201}),+ ]+ )+ def test_rejects_invalid_filter_values(self, _label, filters):+ serializer = TicketViewFiltersSerializer(data=filters)+ assert not serializer.is_valid()++ @parameterized.expand(+ [+ ("string_token", ["user:1"], []),+ ("mixed_entries", ["me", "user:1"], ["me"]),+ ("legacy_all", "all", []),+ ("user_non_numeric_id", [{"type": "user", "id": "abc"}], []),+ ("role_non_uuid_id", [{"type": "role", "id": "not-a-uuid"}], []),+ ]+ )+ def test_lenient_mode_drops_invalid_assignee_entries(self, _label, assignee, expected):+ # The ?view= read path validates stored blobs without strict_writes: a legacy or+ # corrupted assignee entry must not 400 the whole view, just fall away.+ serializer = TicketViewFiltersSerializer(data={"assignee": assignee})+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data["assignee"] == expected++ @parameterized.expand(+ [+ ("string_token", ["user:1"]),+ ("single_bogus_string", "bogus"),+ ("unknown_type", [{"type": "team", "id": 1}]),+ ("missing_id", [{"type": "user"}]),+ # An unresolvable id would save a view that silently matches all assignees.+ ("user_non_numeric_id", [{"type": "user", "id": "abc"}]),+ ("role_non_uuid_id", [{"type": "role", "id": "not-a-uuid"}]),+ ]+ )+ def test_strict_writes_rejects_invalid_assignee_entries(self, _label, assignee):+ serializer = TicketViewFiltersSerializer(data={"assignee": assignee}, context={"strict_writes": True})+ assert not serializer.is_valid()+ assert "assignee" in serializer.errors++ def test_strict_writes_accepts_legacy_all_sentinel(self):+ serializer = TicketViewFiltersSerializer(data={"assignee": "all"}, context={"strict_writes": True})+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data["assignee"] == []++ def test_field_rejects_oversized_payload(self):+ field = TicketViewFiltersField()+ oversized = {"tags": ["x" * 100] * 150}+ with self.assertRaises(ValidationError) as ctx:+ field.run_validation(oversized)+ assert "too large" in str(ctx.exception)diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex aa47b204b432..ebcc055c8b56 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -30,8 +30,9 @@ from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.test.persons import create_person+from products.conversations.backend.api.ticket_filters import query_params_to_view_filtersfrom products.conversations.backend.api.tickets import TicketReplyRequestSerializer-from products.conversations.backend.models import Ticket, TicketAssignment+from products.conversations.backend.models import Ticket, TicketAssignment, TicketViewfrom products.conversations.backend.models.constants import Channel, ChannelDetail, Priority, Statusfrom products.conversations.backend.person_lookup import PERSON_EMAIL_LOOKUP_QUERY, _get_persons_by_email@@ -109,6 +110,8 @@ class TestTicketAPI(APIBaseTest):[("tags_matches_any", {"tags": '["alpha", "beta"]'}, {"alpha_beta", "alpha", "beta_gamma"}),("tags_all_matches_every", {"tags_all": '["alpha", "beta"]'}, {"alpha_beta"}),+ # tags and tags_all must compose (AND), not clobber each other.+ ("tags_composes_with_tags_all", {"tags": '["gamma"]', "tags_all": '["beta"]'}, {"beta_gamma"}),("tags_exclude_drops_tagged", {"tags_exclude": '["gamma"]'}, {"alpha_beta", "alpha"}),("tags_all_composes_with_tags_exclude",@@ -2634,3 +2637,134 @@ class TestTicketAccessControl(APIBaseTest):format="json",)self.assertEqual(response.status_code, expected_status, response.json())+++class TestTicketViewParamFilter(APIBaseTest):+ def _create_ticket(self, **kwargs) -> Ticket:+ defaults = {+ "team": self.team,+ "channel_source": Channel.WIDGET,+ "widget_session_id": f"session-{Ticket.objects.count()}",+ "distinct_id": "user-123",+ "status": Status.NEW,+ }+ defaults.update(kwargs)+ return Ticket.objects.create_with_number(**defaults)++ def _create_view(self, filters: dict) -> TicketView:+ return TicketView.objects.create(team=self.team, name="Saved view", filters=filters, created_by=self.user)++ def _list_ids(self, **params) -> set[str]:+ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/", data=params)+ assert response.status_code == status.HTTP_200_OK, response.json()+ return {r["id"] for r in response.json()["results"]}++ def test_view_param_matches_equivalent_flat_params(self):+ open_high = self._create_ticket(status=Status.OPEN, priority=Priority.HIGH)+ self._create_ticket(status=Status.OPEN, priority=Priority.LOW)+ self._create_ticket(status=Status.RESOLVED, priority=Priority.HIGH)+ view = self._create_view({"status": ["open"], "priority": ["high"]})++ via_view = self._list_ids(view=view.short_id)+ via_params = self._list_ids(status="open", priority="high")+ assert via_view == via_params == {str(open_high.id)}++ def test_explicit_param_overrides_view_filter(self):+ self._create_ticket(status=Status.OPEN)+ resolved = self._create_ticket(status=Status.RESOLVED)+ view = self._create_view({"status": ["open"]})++ assert self._list_ids(view=view.short_id, status="resolved") == {str(resolved.id)}++ def test_unknown_view_short_id_returns_400(self):+ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/", data={"view": "nonexistent"})+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_other_teams_view_returns_400(self):+ other_team = Team.objects.create(organization=self.organization, name="Team 2")+ other_view = TicketView.objects.create(+ team=other_team, name="Other", filters={"status": ["open"]}, created_by=self.user+ )++ response = self.client.get(+ f"/api/projects/{self.team.id}/conversations/tickets/", data={"view": other_view.short_id}+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_view_assignee_me_resolves_to_requesting_user(self):+ mine = self._create_ticket()+ TicketAssignment.objects.create(ticket=mine, user=self.user)+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ theirs = self._create_ticket()+ TicketAssignment.objects.create(ticket=theirs, user=other_user)+ self._create_ticket() # unassigned+ view = self._create_view({"assignee": ["me"]})++ assert self._list_ids(view=view.short_id) == {str(mine.id)}++ def test_invalid_stored_key_dropped_and_rest_of_view_applies(self):+ open_high = self._create_ticket(status=Status.OPEN, priority=Priority.HIGH)+ self._create_ticket(status=Status.OPEN, priority=Priority.LOW)+ view = self._create_view({"status": ["bogus_legacy_status"], "priority": ["high"]})++ assert self._list_ids(view=view.short_id) == {str(open_high.id)}++ def test_invalid_stored_list_entry_keeps_valid_entries(self):+ # One bad legacy entry must narrow to the valid rest, not drop the whole+ # key and widen the view to all statuses.+ open_ticket = self._create_ticket(status=Status.OPEN)+ self._create_ticket(status=Status.RESOLVED)+ view = self._create_view({"status": ["open", "bogus_legacy_status"]})++ assert self._list_ids(view=view.short_id) == {str(open_ticket.id)}++ def test_stored_tags_all_key_is_not_applied(self):+ # tagsAll is a param-only key: the app can't render it, so a stored view+ # carrying one (written via the raw round-trip) must not apply it either.+ tagged = self._create_ticket()+ tag = Tag.objects.create(name="urgent", team_id=self.team.id)+ tagged.tagged_items.create(tag=tag)+ untagged = self._create_ticket()+ view = self._create_view({"tagsAll": ["urgent"]})++ assert self._list_ids(view=view.short_id) == {str(tagged.id), str(untagged.id)}++ def test_invalid_param_value_does_not_clear_view_filter(self):+ open_ticket = self._create_ticket(status=Status.OPEN)+ self._create_ticket(status=Status.RESOLVED)+ view = self._create_view({"status": ["open"]})++ assert self._list_ids(view=view.short_id, status="bogus") == {str(open_ticket.id)}++ @parameterized.expand(+ [+ ("status", "status", "bogus,nonsense", "status"),+ ("priority", "priority", "bogus", "priority"),+ ("assignee_token", "assignee", "bogus", "assignee"),+ ("assignee_bad_user_id", "assignee", "user:abc", "assignee"),+ ("assignee_bad_role_id", "assignee", "role:not-a-uuid", "assignee"),+ ("order_by", "order_by", "bogus", "sorting"),+ ]+ )+ def test_all_invalid_param_values_leave_key_unset(self, _label, param, value, key):+ assert key not in query_params_to_view_filters({param: value})++ def test_legacy_view_filters_blob_applies_without_error(self):+ # Old saved views carry 'all' sentinels, a single-value assignee, and keys the+ # backend never validated. Applying one must filter nothing and respect sorting.+ first = self._create_ticket()+ second = self._create_ticket()+ view = self._create_view(+ {+ "channel": "all",+ "sla": "all",+ "assignee": "all",+ "search": "",+ "futureKey": True,+ "sorting": {"columnKey": "created_at", "order": 1},+ }+ )++ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/", data={"view": view.short_id})+ assert response.status_code == status.HTTP_200_OK+ assert [r["id"] for r in response.json()["results"]] == [str(first.id), str(second.id)]diff --git a/products/conversations/backend/api/ticket_filters.py b/products/conversations/backend/api/ticket_filters.pynew file mode 100644index 000000000000..8ffcb9818672--- /dev/null+++ b/products/conversations/backend/api/ticket_filters.py@@ -0,0 +1,544 @@+"""Canonical ticket filter shape and the single place it becomes ORM predicates.++`TicketViewFiltersSerializer` is the source of truth for the saved-view filter+contract: it validates writes to `TicketView.filters`, is what the `?view=`+param validates stored blobs against, and generates the frontend TypeScript and+MCP schemas via OpenAPI. `apply_ticket_filters` is the only implementation of+filtering, fed by two adapters: validated view filters, and the flat snake_case+query params (`query_params_to_view_filters`).+"""++from __future__ import annotations++import json+import uuid+from collections.abc import Mapping+from datetime import timedelta+from typing import TYPE_CHECKING, Any++from django.db.models import CharField, F, OrderBy, Q, QuerySet+from django.db.models.functions import Cast+from django.utils import timezone++from drf_spectacular.utils import extend_schema_field+from rest_framework import serializers++from posthog.models.comment import Comment+from posthog.utils import relative_date_parse++from products.conversations.backend.models.constants import Channel, Priority, Status++if TYPE_CHECKING:+ from posthog.models import Team, User++MAX_TAG_FILTER_VALUES = 50+# Matches MAX_ASSIGNEE_FILTER_ENTRIES in products/conversations/frontend/components/Assignee.+MAX_ASSIGNEE_FILTER_ENTRIES = 100+MAX_SEARCH_LENGTH = 200++SLA_FILTER_VALUES = ["breached", "at-risk", "on-track"]+AI_TRIAGE_FILTER_VALUES = [+ "persisted",+ "escalated_with_best",+ "escalated_no_reply",+ "skipped_unactionable",+ "blocked_unsafe",+ "blocked_unsafe_reply",+ "in_progress",+]++ALLOWED_ORDER_COLUMNS = ("updated_at", "sla_due_at", "snoozed_until", "created_at", "ticket_number")++VALID_STATUS_VALUES = frozenset(s.value for s in Status)+VALID_PRIORITY_VALUES = frozenset(p.value for p in Priority)+VALID_CHANNEL_VALUES = frozenset(c.value for c in Channel)++# Named choice sets for ChoiceFields below, registered in ENUM_NAME_OVERRIDES+# (posthog/settings/web.py) so drf-spectacular doesn't mint generic globals like+# ChannelEnum/SlaEnum/OrderEnum in the shared OpenAPI namespace.+TICKET_CHANNEL_FILTER_CHOICES = [*(c.value for c in Channel), "all"]+TICKET_SLA_FILTER_CHOICES = [*SLA_FILTER_VALUES, "all"]+TICKET_TAGS_MATCH_CHOICES = ["any", "all"]+# Tuple pairs, not bare ints: drf-spectacular's override loader only accepts strings+# in plain value lists and crashes on anything else.+TICKET_SORT_ORDER_CHOICES = [(1, 1), (-1, -1)]+++def _is_assignee_entry(value: Any) -> bool:+ if value in ("unassigned", "me"):+ return True+ if not isinstance(value, dict):+ return False+ entry_id = value.get("id")+ if not isinstance(entry_id, str | int) or isinstance(entry_id, bool):+ return False+ # The id must resolve to a real user pk / role UUID: an unresolvable entry would+ # silently apply no filter at query time, widening results past what was asked for.+ if value.get("type") == "user":+ try:+ int(entry_id)+ except (TypeError, ValueError):+ return False+ return True+ if value.get("type") == "role":+ try:+ uuid.UUID(str(entry_id))+ except ValueError:+ return False+ return True+ return False+++def normalize_assignee_filter(value: Any) -> list[Any]:+ """Mirrors the frontend's normalizeAssigneeFilter: accepts the current array shape or+ the legacy single-value shape ('all', 'unassigned', or one assignee object) still+ present in old saved views, keeping only valid entries."""+ entries = value if isinstance(value, list) else [value]+ return [entry for entry in entries if _is_assignee_entry(entry)][:MAX_ASSIGNEE_FILTER_ENTRIES]+++@extend_schema_field(+ {+ "type": "array",+ "items": {+ "oneOf": [+ {"type": "string", "enum": ["me", "unassigned"]},+ {+ "type": "object",+ "properties": {+ "type": {"type": "string", "enum": ["user", "role"]},+ "id": {"oneOf": [{"type": "string"}, {"type": "integer"}]},+ },+ "required": ["type", "id"],+ },+ ]+ },+ "description": (+ "Assignees to match (any of): 'unassigned', 'me' (resolved to the requesting user), "+ "or an object with type ('user' or 'role') and id."+ ),+ }+)+class TicketViewAssigneeFilterField(serializers.Field):+ """Lenient by default so legacy stored blobs still apply (an unrecognized entry is+ dropped, and the legacy 'all' sentinel means no filter). Writes pass+ context={"strict_writes": True}: silently dropping a malformed entry there would+ save a view that quietly matches more assignees than the caller asked for."""++ def to_internal_value(self, data: Any) -> list[Any]:+ if self.context.get("strict_writes"):+ entries = data if isinstance(data, list) else [data]+ if any(not _is_assignee_entry(entry) and entry != "all" for entry in entries):+ raise serializers.ValidationError(+ "Each assignee entry must be 'me', 'unassigned', or an object with type ('user' or 'role') and id."+ )+ return normalize_assignee_filter(data)++ def to_representation(self, value: Any) -> Any:+ return value+++class TicketViewSortingSerializer(serializers.Serializer):+ columnKey = serializers.CharField(+ help_text=f"Ticket column to sort by ({', '.join(ALLOWED_ORDER_COLUMNS)}). "+ "Unknown columns fall back to updated_at."+ )+ order = serializers.ChoiceField(choices=TICKET_SORT_ORDER_CHOICES, help_text="1 for ascending, -1 for descending.")+++class TicketViewFiltersSerializer(serializers.Serializer):+ """Canonical shape of a saved ticket view's filters. Every field is optional; an omitted+ field (or an 'all' sentinel) leaves that dimension unfiltered."""++ status = serializers.ListField(+ child=serializers.ChoiceField(choices=Status.choices),+ required=False,+ help_text="Ticket statuses to include. Empty or omitted means all statuses.",+ )+ priority = serializers.ListField(+ child=serializers.ChoiceField(choices=Priority.choices),+ required=False,+ help_text="Ticket priorities to include. Empty or omitted means all priorities.",+ )+ channel = serializers.ChoiceField(+ choices=TICKET_CHANNEL_FILTER_CHOICES,+ required=False,+ help_text="Channel the ticket originated from. 'all' disables the filter.",+ )+ sla = serializers.ChoiceField(+ choices=TICKET_SLA_FILTER_CHOICES,+ required=False,+ help_text="SLA state: 'breached' is past due, 'at-risk' is due within the next hour, "+ "'on-track' has more than an hour remaining. 'all' disables the filter.",+ )+ aiTriageResult = serializers.ListField(+ child=serializers.ChoiceField(choices=AI_TRIAGE_FILTER_VALUES),+ required=False,+ help_text="AI triage outcomes to include. 'in_progress' matches tickets still being triaged.",+ )+ assignee = TicketViewAssigneeFilterField(+ required=False,+ help_text="Assignees to match (any of): 'unassigned', 'me' (resolved to the requesting user), "+ "or an object with type ('user' or 'role') and id. The legacy single-value shape is accepted "+ "and normalized to a list.",+ )+ tags = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Tag names to match, combined according to tagsMatch.",+ )+ tagsMatch = serializers.ChoiceField(+ choices=TICKET_TAGS_MATCH_CHOICES,+ required=False,+ help_text="'any' returns tickets with at least one of tags (OR); 'all' requires every tag (AND).",+ )+ tagsExclude = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Tickets carrying any of these tags are excluded.",+ )+ dateFrom = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Only include tickets updated on or after this date. Accepts absolute dates (2026-01-01) "+ "or relative ones (-7d). 'all' or null disables the bound.",+ )+ dateTo = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Only include tickets updated on or before this date. Same format as dateFrom.",+ )+ sorting = TicketViewSortingSerializer(required=False, allow_null=True, help_text="Sort order for the ticket list.")+ search = serializers.CharField(+ required=False,+ allow_blank=True,+ max_length=MAX_SEARCH_LENGTH,+ help_text="Free-text search. A numeric value matches a ticket number exactly; otherwise matches "+ "the customer's name or email, the email subject, or message content.",+ )+++def _salvage_list_entries(key: str, value: Any) -> list[Any] | None:+ """Keep the individually-valid entries of an errored list value, so one bad legacy+ entry narrows the filter to the valid rest instead of dropping the key (widening)."""+ field = TicketViewFiltersSerializer().fields.get(key)+ if not isinstance(field, serializers.ListField) or not isinstance(value, list):+ return None+ valid_entries = []+ for entry in value:+ try:+ field.child.run_validation(entry)+ except serializers.ValidationError:+ continue+ valid_entries.append(entry)+ return valid_entries or None+++def parse_stored_view_filters(stored: Any) -> dict[str, Any]:+ """Leniently validate a stored TicketView.filters blob into the canonical shape.++ Stored blobs predate write validation, so a legacy value must not make the view+ unusable: invalid list entries and offending keys are dropped and the rest still+ apply."""+ if not isinstance(stored, dict):+ return {}+ serializer = TicketViewFiltersSerializer(data=stored)+ if not serializer.is_valid():+ cleaned: dict[str, Any] = {}+ for key, value in stored.items():+ if key not in serializer.errors:+ cleaned[key] = value+ elif (salvaged := _salvage_list_entries(key, value)) is not None:+ cleaned[key] = salvaged+ serializer = TicketViewFiltersSerializer(data=cleaned)+ serializer.is_valid()+ return dict(serializer.validated_data)+++def _decode_assignee_param(raw: str) -> list[Any]:+ entries: list[Any] = []+ for raw_entry in raw.split(",")[:MAX_ASSIGNEE_FILTER_ENTRIES]:+ entry = raw_entry.strip()+ if entry.lower() in ("unassigned", "me"):+ entries.append(entry.lower())+ elif entry.startswith("user:"):+ entries.append({"type": "user", "id": entry[5:]})+ elif entry.startswith("role:"):+ entries.append({"type": "role", "id": entry[5:]})+ return [entry for entry in entries if _is_assignee_entry(entry)]+++def _decode_json_tag_list(raw: str) -> list[str] | None:+ try:+ value = json.loads(raw)+ except json.JSONDecodeError:+ return None+ if isinstance(value, list) and value:+ return [str(tag) for tag in value]+ return None+++def _order_by_to_sorting(order_by: str) -> dict[str, Any] | None:+ column = order_by.removeprefix("-")+ if column not in ALLOWED_ORDER_COLUMNS:+ return None+ return {"columnKey": column, "order": -1 if order_by.startswith("-") else 1}+++def query_params_to_view_filters(params: Mapping[str, str]) -> dict[str, Any]:+ """Translate the flat snake_case ticket-list query params into the canonical+ TicketViewFilters shape. Only keys whose param is present are set, so values coming+ from a saved view survive unless explicitly overridden. Invalid values are dropped+ rather than rejected, matching the endpoint's long-standing behavior."""+ filters: dict[str, Any] = {}++ # Guard every list on being non-empty: a param whose values all parse away must not+ # set the key, or merging onto a saved view would clear that filter and widen results.+ status_param = params.get("status")+ if status_param:+ statuses = [s.strip() for s in status_param.split(",") if s.strip() in VALID_STATUS_VALUES]+ if statuses:+ filters["status"] = statuses++ priority_param = params.get("priority")+ if priority_param:+ priorities = [p.strip() for p in priority_param.split(",") if p.strip() in VALID_PRIORITY_VALUES]+ if priorities:+ filters["priority"] = priorities++ channel_source = params.get("channel_source")+ if channel_source and channel_source in VALID_CHANNEL_VALUES:+ filters["channel"] = channel_source++ sla_param = params.get("sla")+ if sla_param and sla_param in SLA_FILTER_VALUES:+ filters["sla"] = sla_param++ ai_triage_result_param = params.get("ai_triage_result")+ if ai_triage_result_param:+ results = [r.strip() for r in ai_triage_result_param.split(",") if r.strip() in AI_TRIAGE_FILTER_VALUES]+ if results:+ filters["aiTriageResult"] = results++ assignee_param = params.get("assignee")+ if assignee_param:+ assignees = _decode_assignee_param(assignee_param)+ if assignees:+ filters["assignee"] = assignees++ tags_param = params.get("tags")+ if tags_param:+ tags = _decode_json_tag_list(tags_param)+ if tags:+ filters["tags"] = tags+ filters["tagsMatch"] = "any"++ tags_all_param = params.get("tags_all")+ if tags_all_param:+ tags = _decode_json_tag_list(tags_all_param)+ if tags:+ # Separate key from tags/tagsMatch so tags= and tags_all= compose (AND)+ # instead of the later param clobbering the earlier one. Deliberately NOT+ # part of the saved-view serializer contract: the app can't render a+ # tagsAll filter, so a view holding one would behave differently in the+ # app than via ?view=.+ filters["tagsAll"] = tags++ tags_exclude_param = params.get("tags_exclude")+ if tags_exclude_param:+ tags = _decode_json_tag_list(tags_exclude_param)+ if tags:+ filters["tagsExclude"] = tags++ search = params.get("search")+ if search and len(search) <= MAX_SEARCH_LENGTH:+ filters["search"] = search++ date_from = params.get("date_from")+ if date_from:+ # 'all' passes through so an explicit param can disable a view's saved lower bound.+ filters["dateFrom"] = date_from++ date_to = params.get("date_to")+ if date_to:+ filters["dateTo"] = date_to++ order_by = params.get("order_by")+ if order_by:+ sorting = _order_by_to_sorting(order_by)+ if sorting:+ filters["sorting"] = sorting++ return filters+++def _sorting_to_order_expressions(sorting: Mapping[str, Any] | None) -> tuple[OrderBy | str, str]:+ column, descending = "updated_at", True+ if sorting and sorting.get("columnKey") in ALLOWED_ORDER_COLUMNS:+ column = sorting["columnKey"]+ descending = sorting.get("order") != 1++ primary: OrderBy | str+ if column in ("sla_due_at", "snoozed_until"):+ # A ticket with no SLA (or no snooze) sorts to the bottom either direction — an+ # absent deadline isn't more urgent than a real one, and it keeps the large NULL+ # block off the first pages so the SLA-sorted rows are what the user actually sees.+ primary = F(column).desc(nulls_last=True) if descending else F(column).asc(nulls_last=True)+ else:+ primary = f"-{column}" if descending else column++ # ticket_number is unique per team (the queryset is already team-scoped), so it breaks+ # ties deterministically. Without it, rows equal on the primary key — every no-SLA+ # ticket shares NULL sla_due_at — have no stable order across the separate LIMIT/OFFSET+ # page queries, so pages overlap or drop rows and the sort looks lost past page 1.+ return primary, "-ticket_number"+++def _assignee_filter_q(entries: list[Any], user: User | None) -> Q:+ user_ids: list[int] = []+ role_ids: list[uuid.UUID] = []+ include_unassigned = False+ for entry in entries:+ if entry == "unassigned":+ include_unassigned = True+ elif entry == "me":+ # Dynamic per-viewer token: resolve to the requesting user so a+ # shared saved view scoped to "me" means each viewer's own tickets.+ if user is not None:+ user_ids.append(user.id)+ elif isinstance(entry, dict) and entry.get("type") == "user":+ try:+ user_ids.append(int(entry["id"]))+ except (ValueError, TypeError):+ pass+ elif isinstance(entry, dict) and entry.get("type") == "role":+ try:+ role_ids.append(uuid.UUID(str(entry["id"])))+ except (ValueError, AttributeError):+ pass+ assignee_q = Q()+ if user_ids:+ assignee_q |= Q(assignment__user_id__in=user_ids)+ if role_ids:+ assignee_q |= Q(assignment__role_id__in=role_ids)+ if include_unassigned:+ assignee_q |= Q(assignment__isnull=True)+ return assignee_q+++def is_ticket_number_search(search: str) -> bool:+ # A leading "#" is how ticket numbers are shown in the UI (e.g. "#1234"), so+ # treat "#1234" the same as "1234" and match the ticket number exactly.+ # Restrict to ASCII digits: str.isdigit() also accepts characters like "²"+ # that int() then rejects, which would 500 the request.+ ticket_number_search = search.removeprefix("#")+ return ticket_number_search.isascii() and ticket_number_search.isdigit()+++def _apply_search(queryset: QuerySet, search: str, team: Team) -> QuerySet:+ if is_ticket_number_search(search):+ return queryset.filter(ticket_number=int(search.removeprefix("#")))++ # Comment match as a non-correlated subquery: self-contained, so Postgres hashes+ # it once per query (scanning posthog_comment through its trigram index) instead+ # of probing comments per ticket the way a correlated EXISTS would. The ticket id+ # is cast to text rather than item_id to uuid — the id side is always a valid+ # UUID, while a malformed item_id row would make the whole search error.+ comment_match = Comment.objects.filter(+ team_id=team.id,+ scope="conversations_ticket",+ deleted=False,+ content__icontains=search,+ ).values("item_id")++ return queryset.alias(id_text=Cast("id", output_field=CharField())).filter(+ Q(anonymous_traits__name__icontains=search)+ | Q(anonymous_traits__email__icontains=search)+ | Q(email_subject__icontains=search)+ | Q(id_text__in=comment_match)+ )+++def apply_ticket_filters(queryset: QuerySet, filters: Mapping[str, Any], *, team: Team, user: User | None) -> QuerySet:+ """Apply a canonical TicketViewFilters mapping to a Ticket queryset and order it.++ `filters` must already be validated/normalized, either by TicketViewFiltersSerializer+ (saved-view path) or by query_params_to_view_filters (flat-param path).+ """+ statuses = filters.get("status") or []+ if statuses:+ queryset = queryset.filter(status__in=statuses)++ priorities = filters.get("priority") or []+ if priorities:+ queryset = queryset.filter(priority__in=priorities)++ channel = filters.get("channel")+ if channel and channel != "all":+ queryset = queryset.filter(channel_source=channel)++ sla = filters.get("sla")+ if sla and sla != "all":+ now = timezone.now()+ if sla == "breached":+ queryset = queryset.filter(sla_due_at__lt=now)+ elif sla == "at-risk":+ queryset = queryset.filter(sla_due_at__gte=now, sla_due_at__lte=now + timedelta(hours=1))+ elif sla == "on-track":+ queryset = queryset.filter(sla_due_at__gt=now + timedelta(hours=1))++ triage_results = set(filters.get("aiTriageResult") or [])+ if triage_results:+ triage_q = Q()+ normal_results = triage_results - {"in_progress"}+ if normal_results:+ triage_q |= Q(ai_triage__result__in=normal_results)+ if "in_progress" in triage_results:+ triage_q |= Q(ai_triage__status="in_progress")+ queryset = queryset.filter(triage_q)++ assignee_entries = normalize_assignee_filter(filters.get("assignee"))+ if assignee_entries:+ assignee_q = _assignee_filter_q(assignee_entries, user)+ if assignee_q:+ queryset = queryset.filter(assignee_q)++ tags = [str(tag) for tag in filters.get("tags") or []][:MAX_TAG_FILTER_VALUES]+ if tags:+ if filters.get("tagsMatch") == "all":+ # One filter per tag (not __in) so this is AND: the ticket must carry every tag.+ for tag_name in tags:+ queryset = queryset.filter(tagged_items__tag__name=tag_name)+ queryset = queryset.distinct()+ else:+ queryset = queryset.filter(tagged_items__tag__name__in=tags).distinct()++ tags_all = [str(tag) for tag in filters.get("tagsAll") or []][:MAX_TAG_FILTER_VALUES]+ if tags_all:+ for tag_name in tags_all:+ queryset = queryset.filter(tagged_items__tag__name=tag_name)+ queryset = queryset.distinct()++ tags_exclude = [str(tag) for tag in filters.get("tagsExclude") or []][:MAX_TAG_FILTER_VALUES]+ if tags_exclude:+ queryset = queryset.exclude(tagged_items__tag__name__in=tags_exclude)++ date_from = filters.get("dateFrom")+ if date_from and date_from != "all":+ parsed = relative_date_parse(date_from, team.timezone_info)+ if parsed:+ queryset = queryset.filter(updated_at__gte=parsed)++ date_to = filters.get("dateTo")+ if date_to and date_to != "all":+ parsed = relative_date_parse(date_to, team.timezone_info)+ if parsed:+ queryset = queryset.filter(updated_at__lte=parsed)++ search = filters.get("search")+ if search and len(search) <= MAX_SEARCH_LENGTH:+ queryset = _apply_search(queryset, search, team)++ return queryset.order_by(*_sorting_to_order_expressions(filters.get("sorting")))diff --git a/products/conversations/backend/api/ticket_views.py b/products/conversations/backend/api/ticket_views.pyindex 7ecf8707ad80..9b886143cdbb 100644--- a/products/conversations/backend/api/ticket_views.py+++ b/products/conversations/backend/api/ticket_views.py@@ -3,12 +3,14 @@ from typing import TYPE_CHECKING, Any, castfrom django.db.models import Exists, OuterRef+from drf_spectacular.utils import extend_schema_fieldfrom rest_framework import mixins, serializers, viewsetsfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import report_user_action+from products.conversations.backend.api.ticket_filters import TicketViewFiltersSerializerfrom products.conversations.backend.models import TicketView, TicketViewFavoriteif TYPE_CHECKING:@@ -17,23 +19,35 @@ if TYPE_CHECKING:MAX_FILTERS_SIZE_BYTES = 10_000+@extend_schema_field(TicketViewFiltersSerializer)+class TicketViewFiltersField(serializers.JSONField):+ """Validates writes against the canonical filter shape but stores and returns the raw+ dict, so unknown keys survive round-trips and legacy blobs render unchanged."""++ def to_internal_value(self, data: Any) -> dict:+ value = super().to_internal_value(data)+ if not isinstance(value, dict):+ raise serializers.ValidationError("Expected a JSON object.")+ if len(json.dumps(value)) > MAX_FILTERS_SIZE_BYTES:+ raise serializers.ValidationError("Filters payload is too large.")+ filters_serializer = TicketViewFiltersSerializer(data=value, context={"strict_writes": True})+ filters_serializer.is_valid(raise_exception=True)+ return value++class TicketViewSerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)- filters = serializers.DictField(+ filters = TicketViewFiltersField(required=False,default=dict,- help_text="Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys.",+ help_text="Saved ticket filter criteria: status, priority, channel, sla, aiTriageResult, assignee, "+ "tags, tagsMatch, tagsExclude, dateFrom, dateTo, sorting, and search.",)is_favorited = serializers.BooleanField(required=False,help_text="Whether the current user has favorited this view. Favorited views sort to the top of the list. Favorites are personal to each user.",)- def validate_filters(self, value: dict) -> dict:- if len(json.dumps(value)) > MAX_FILTERS_SIZE_BYTES:- raise serializers.ValidationError("Filters payload is too large.")- return value-class Meta:model = TicketViewfields = [diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex c35bb91a0afa..6ee43fc96a7c 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -4,14 +4,11 @@ import jsonimport timeimport uuidfrom collections.abc import Sequence-from datetime import timedelta-from typing import Any+from typing import TYPE_CHECKING, Any, castfrom django.db import transaction-from django.db.models import CharField, F, OrderBy, Q, QuerySet, Sum-from django.db.models.functions import Cast+from django.db.models import Q, QuerySet, Sumfrom django.http import Http404-from django.utils import timezoneimport structlogimport posthoganalytics@@ -24,7 +21,7 @@ from rest_framework import (viewsets,)from rest_framework.decorators import action-from rest_framework.exceptions import MethodNotAllowed+from rest_framework.exceptions import MethodNotAllowed, ValidationErrorfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.response import Response@@ -44,9 +41,15 @@ from posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.rate_limit import ComposeTicketBurstThrottle, ComposeTicketSustainedThrottlefrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.user_access_control import UserAccessControlSerializerMixin-from posthog.utils import relative_date_parsefrom products.conversations.backend.api.serializers import TicketAssignmentSerializer+from products.conversations.backend.api.ticket_filters import (+ AI_TRIAGE_FILTER_VALUES,+ apply_ticket_filters,+ is_ticket_number_search,+ parse_stored_view_filters,+ query_params_to_view_filters,+)from products.conversations.backend.cache import (get_cached_unread_count,invalidate_unread_count_cache,@@ -58,12 +61,15 @@ from products.conversations.backend.events import (capture_ticket_status_changed,)from products.conversations.backend.metrics import TICKET_SEARCH_DURATION_SECONDS-from products.conversations.backend.models import EmailChannel, Ticket, TicketAssignment-from products.conversations.backend.models.constants import Channel, ChannelDetail, Priority, Status+from products.conversations.backend.models import EmailChannel, Ticket, TicketAssignment, TicketView+from products.conversations.backend.models.constants import Channel, ChannelDetail, Statusfrom products.conversations.backend.person_lookup import _get_persons_by_emailfrom ee.models.rbac.role import Role+if TYPE_CHECKING:+ from posthog.models import User+logger = structlog.get_logger(__name__)@@ -216,9 +222,6 @@ class TicketMessagePagination(pagination.LimitOffsetPagination):max_limit = 200-MAX_TAG_FILTER_VALUES = 50--class TicketPersonSerializer(serializers.Serializer):"""Minimal person serializer for embedding in ticket responses."""@@ -376,103 +379,23 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro# Which search branch safely_get_queryset applied, for the latency histogram._search_path: str | None = None- def _filter_by_text_search(self, queryset: QuerySet, search: str) -> QuerySet:- # Comment match as a non-correlated subquery: self-contained, so Postgres hashes- # it once per query (scanning posthog_comment through its trigram index) instead- # of probing comments per ticket the way a correlated EXISTS would. The ticket id- # is cast to text rather than item_id to uuid — the id side is always a valid- # UUID, while a malformed item_id row would make the whole search error.- comment_match = Comment.objects.filter(- team_id=self.team_id,- scope="conversations_ticket",- deleted=False,- content__icontains=search,- ).values("item_id")-- return queryset.alias(id_text=Cast("id", output_field=CharField())).filter(- Q(anonymous_traits__name__icontains=search)- | Q(anonymous_traits__email__icontains=search)- | Q(email_subject__icontains=search)- | Q(id_text__in=comment_match)- )-def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:"""Filter tickets by team."""queryset = queryset.filter(team_id=self.team_id)queryset = queryset.select_related("assignment", "assignment__user", "assignment__role", "email_config")- status_param = self.request.query_params.get("status")- if status_param:- valid_statuses = [s.value for s in Status]- statuses = [s.strip() for s in status_param.split(",") if s.strip() in valid_statuses]- if len(statuses) == 1:- queryset = queryset.filter(status=statuses[0])- elif len(statuses) > 1:- queryset = queryset.filter(status__in=statuses)-- priority_param = self.request.query_params.get("priority")- if priority_param:- valid_priorities = [p.value for p in Priority]- priorities = [p.strip() for p in priority_param.split(",") if p.strip() in valid_priorities]- if len(priorities) == 1:- queryset = queryset.filter(priority=priorities[0])- elif len(priorities) > 1:- queryset = queryset.filter(priority__in=priorities)-- channel_source = self.request.query_params.get("channel_source")- if channel_source and channel_source in [c.value for c in Channel]:- queryset = queryset.filter(channel_source=channel_source)+ filters: dict[str, Any] = {}+ view_short_id = self.request.query_params.get("view")+ if view_short_id:+ filters = self._get_view_filters(view_short_id)+ # Explicit query params override the saved view's values, so a caller can apply+ # a view and still narrow it further.+ filters.update(query_params_to_view_filters(self.request.query_params))channel_detail = self.request.query_params.get("channel_detail")if channel_detail and channel_detail in [d.value for d in ChannelDetail]:queryset = queryset.filter(channel_detail=channel_detail)- assignee_param = self.request.query_params.get("assignee")- if assignee_param:- user_ids: list[int] = []- role_ids: list[uuid.UUID] = []- include_unassigned = False- for raw_entry in assignee_param.split(",")[:100]:- entry = raw_entry.strip()- if entry.lower() == "unassigned":- include_unassigned = True- elif entry.lower() == "me":- # Dynamic per-viewer token: resolve to the requesting user so a- # shared saved view scoped to "me" means each viewer's own tickets.- if self.request.user and self.request.user.is_authenticated:- user_ids.append(self.request.user.id)- elif entry.startswith("user:"):- try:- user_ids.append(int(entry[5:]))- except ValueError:- pass- elif entry.startswith("role:"):- try:- role_ids.append(uuid.UUID(entry[5:]))- except (ValueError, AttributeError):- pass- assignee_q = Q()- if user_ids:- assignee_q |= Q(assignment__user_id__in=user_ids)- if role_ids:- assignee_q |= Q(assignment__role_id__in=role_ids)- if include_unassigned:- assignee_q |= Q(assignment__isnull=True)- if assignee_q:- queryset = queryset.filter(assignee_q)-- date_from = self.request.query_params.get("date_from")- if date_from and date_from != "all":- parsed = relative_date_parse(date_from, self.team.timezone_info)- if parsed:- queryset = queryset.filter(updated_at__gte=parsed)-- date_to = self.request.query_params.get("date_to")- if date_to:- parsed = relative_date_parse(date_to, self.team.timezone_info)- if parsed:- queryset = queryset.filter(updated_at__lte=parsed)-# Related-ticket matching: a ticket belongs to the same customer if it shares one of the# person's merged distinct_ids OR the same email address. Email widens the match to tickets# whose distinct_id was never merged into the person (a separate anonymous session, or an@@ -497,30 +420,6 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControif match_q:queryset = queryset.filter(match_q)- search = self.request.query_params.get("search")- if search and len(search) <= 200:- # A leading "#" is how ticket numbers are shown in the UI (e.g. "#1234"), so- # treat "#1234" the same as "1234" and match the ticket number exactly.- # Restrict to ASCII digits: str.isdigit() also accepts characters like "²"- # that int() then rejects, which would 500 the request.- ticket_number_search = search[1:] if search.startswith("#") else search- if ticket_number_search.isascii() and ticket_number_search.isdigit():- self._search_path = "ticket_number"- queryset = queryset.filter(ticket_number=int(ticket_number_search))- else:- self._search_path = "text"- queryset = self._filter_by_text_search(queryset, search)-- sla_param = self.request.query_params.get("sla")- if sla_param:- now = timezone.now()- if sla_param == "breached":- queryset = queryset.filter(sla_due_at__lt=now)- elif sla_param == "at-risk":- queryset = queryset.filter(sla_due_at__gte=now, sla_due_at__lte=now + timedelta(hours=1))- elif sla_param == "on-track":- queryset = queryset.filter(sla_due_at__gt=now + timedelta(hours=1))-snoozed_param = self.request.query_params.get("snoozed")if snoozed_param is not None:if snoozed_param.lower() == "true":@@ -528,92 +427,23 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControelif snoozed_param.lower() == "false":queryset = queryset.filter(snoozed_until__isnull=True)- tags_param = self.request.query_params.get("tags")- if tags_param:- try:- tags_list = json.loads(tags_param)- if isinstance(tags_list, list) and tags_list:- queryset = queryset.filter(tagged_items__tag__name__in=tags_list[:MAX_TAG_FILTER_VALUES]).distinct()- except json.JSONDecodeError:- pass-- tags_all_param = self.request.query_params.get("tags_all")- if tags_all_param:- try:- tags_all_list = json.loads(tags_all_param)- if isinstance(tags_all_list, list) and tags_all_list:- # One filter per tag (not __in) so this is AND: the ticket must carry every tag.- for tag_name in tags_all_list[:MAX_TAG_FILTER_VALUES]:- queryset = queryset.filter(tagged_items__tag__name=tag_name)- queryset = queryset.distinct()- except json.JSONDecodeError:- pass-- tags_exclude_param = self.request.query_params.get("tags_exclude")- if tags_exclude_param:- try:- tags_exclude_list = json.loads(tags_exclude_param)- if isinstance(tags_exclude_list, list) and tags_exclude_list:- queryset = queryset.exclude(tagged_items__tag__name__in=tags_exclude_list[:MAX_TAG_FILTER_VALUES])- except json.JSONDecodeError:- pass-- ai_triage_result_param = self.request.query_params.get("ai_triage_result")- if ai_triage_result_param:- valid_results = {- "persisted",- "escalated_with_best",- "escalated_no_reply",- "skipped_unactionable",- "blocked_unsafe",- "blocked_unsafe_reply",- "in_progress",- }- results = {r.strip() for r in ai_triage_result_param.split(",") if r.strip() in valid_results}- if results:- q = Q()- normal_results = results - {"in_progress"}- if normal_results:- q |= Q(ai_triage__result__in=normal_results)- if "in_progress" in results:- q |= Q(ai_triage__status="in_progress")- queryset = queryset.filter(q)-- allowed_orderings = {- "updated_at",- "-updated_at",- "sla_due_at",- "-sla_due_at",- "snoozed_until",- "-snoozed_until",- "created_at",- "-created_at",- "ticket_number",- "-ticket_number",- }- order_by = self.request.query_params.get("order_by", "-updated_at")- if order_by not in allowed_orderings:- order_by = "-updated_at"+ search = filters.get("search")+ if search:+ self._search_path = "ticket_number" if is_ticket_number_search(search) else "text"# Hide tickets the user has been explicitly denied object-level access to (list action only).queryset = self._filter_queryset_by_access_level(queryset)- field_name = order_by.lstrip("-")- primary: OrderBy | str- if field_name in ("sla_due_at", "snoozed_until"):- # A ticket with no SLA (or no snooze) sorts to the bottom either direction — an- # absent deadline isn't more urgent than a real one, and it keeps the large NULL- # block off the first pages so the SLA-sorted rows are what the user actually sees.- descending = order_by.startswith("-")- primary = F(field_name).desc(nulls_last=True) if descending else F(field_name).asc(nulls_last=True)- else:- primary = order_by+ user = cast("User", self.request.user) if self.request.user and self.request.user.is_authenticated else None+ return apply_ticket_filters(queryset, filters, team=self.team, user=user)- # ticket_number is unique per team (the queryset is already team-scoped), so it breaks- # ties deterministically. Without it, rows equal on the primary key — every no-SLA- # ticket shares NULL sla_due_at — have no stable order across the separate LIMIT/OFFSET- # page queries, so pages overlap or drop rows and the sort looks lost past page 1.- return queryset.order_by(primary, "-ticket_number")+ def _get_view_filters(self, short_id: str) -> dict[str, Any]:+ """Resolve a saved ticket view into the canonical filter shape for apply_ticket_filters."""+ try:+ view = TicketView.objects.get(team_id=self.team_id, short_id=short_id)+ except TicketView.DoesNotExist:+ raise ValidationError({"view": "No saved ticket view matches this short_id."})+ return parse_stored_view_filters(view.filters)def safely_get_object(self, queryset):"""@@ -703,6 +533,16 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro@extend_schema(parameters=[+ OpenApiParameter(+ "view",+ OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ description=(+ "Apply a saved ticket view's filters by its `short_id` (list views via the "+ "`conversations/views` endpoint). Any filter param passed explicitly overrides "+ "the view's saved value for that dimension. Returns 400 if no view matches."+ ),+ ),OpenApiParameter("status",OpenApiTypes.STR,@@ -815,6 +655,21 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControlocation=OpenApiParameter.QUERY,description='JSON-encoded array of tag names; returns tickets that have NONE of them (NOT), e.g. `["escalated"]`.',),+ OpenApiParameter(+ "ai_triage_result",+ OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ description=(+ "Filter by AI triage outcome. Accepts a single value or a comma-separated list. "+ f"Valid values: {', '.join(f'`{v}`' for v in AI_TRIAGE_FILTER_VALUES)}."+ ),+ ),+ OpenApiParameter(+ "snoozed",+ OpenApiTypes.BOOL,+ location=OpenApiParameter.QUERY,+ description="Filter by snooze state: `true` returns only snoozed tickets, `false` only non-snoozed.",+ ),OpenApiParameter("order_by",OpenApiTypes.STR,diff --git a/products/conversations/frontend/components/SavedViews/ticketViewsLogic.ts b/products/conversations/frontend/components/SavedViews/ticketViewsLogic.tsindex acce4c8916d3..3dc923163f45 100644--- a/products/conversations/frontend/components/SavedViews/ticketViewsLogic.ts+++ b/products/conversations/frontend/components/SavedViews/ticketViewsLogic.ts@@ -12,7 +12,7 @@ import {conversationsViewsList,conversationsViewsPartialUpdate,} from '../../generated/api'-import type { PatchedTicketViewApi, TicketViewApiFilters } from '../../generated/api.schemas'+import type { PatchedTicketViewApi, TicketViewFiltersApi } from '../../generated/api.schemas'import { supportTicketsSceneLogic } from '../../scenes/tickets/supportTicketsSceneLogic'import type { SavedTicketView, TicketViewFilters } from '../../types'@@ -187,7 +187,7 @@ export const ticketViewsLogic = kea<ticketViewsLogicType>([createView: async ({ name, filters }: { name: string; filters: TicketViewFilters }) => {const created = (await conversationsViewsCreate(String(values.currentTeamId), {name,- filters: filters as TicketViewApiFilters,+ filters: filters as TicketViewFiltersApi,})) as unknown as SavedTicketViewlemonToast.success('View saved')return [created, ...values.views]diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 0243938fd674..564a7d91d86b 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -1057,17 +1057,164 @@ export interface TicketErrorApi {}/**- * Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys.+ * * `widget` - widget+ * * `email` - email+ * * `slack` - slack+ * * `teams` - teams+ * * `github` - github+ * * `all` - all*/-export type TicketViewApiFilters = { [key: string]: unknown }+export type TicketChannelFilterEnumApi = (typeof TicketChannelFilterEnumApi)[keyof typeof TicketChannelFilterEnumApi]++export const TicketChannelFilterEnumApi = {+ Widget: 'widget',+ Email: 'email',+ Slack: 'slack',+ Teams: 'teams',+ Github: 'github',+ All: 'all',+} as const++/**+ * * `breached` - breached+ * * `at-risk` - at-risk+ * * `on-track` - on-track+ * * `all` - all+ */+export type TicketSlaFilterEnumApi = (typeof TicketSlaFilterEnumApi)[keyof typeof TicketSlaFilterEnumApi]++export const TicketSlaFilterEnumApi = {+ Breached: 'breached',+ AtRisk: 'at-risk',+ OnTrack: 'on-track',+ All: 'all',+} as const++/**+ * * `persisted` - persisted+ * * `escalated_with_best` - escalated_with_best+ * * `escalated_no_reply` - escalated_no_reply+ * * `skipped_unactionable` - skipped_unactionable+ * * `blocked_unsafe` - blocked_unsafe+ * * `blocked_unsafe_reply` - blocked_unsafe_reply+ * * `in_progress` - in_progress+ */+export type AiTriageResultEnumApi = (typeof AiTriageResultEnumApi)[keyof typeof AiTriageResultEnumApi]++export const AiTriageResultEnumApi = {+ Persisted: 'persisted',+ EscalatedWithBest: 'escalated_with_best',+ EscalatedNoReply: 'escalated_no_reply',+ SkippedUnactionable: 'skipped_unactionable',+ BlockedUnsafe: 'blocked_unsafe',+ BlockedUnsafeReply: 'blocked_unsafe_reply',+ InProgress: 'in_progress',+} as const++/**+ * * `any` - any+ * * `all` - all+ */+export type TicketTagsMatchEnumApi = (typeof TicketTagsMatchEnumApi)[keyof typeof TicketTagsMatchEnumApi]++export const TicketTagsMatchEnumApi = {+ Any: 'any',+ All: 'all',+} as const++/**+ * * `1` - 1+ * * `-1` - -1+ */+export type TicketSortOrderEnumApi = (typeof TicketSortOrderEnumApi)[keyof typeof TicketSortOrderEnumApi]++export const TicketSortOrderEnumApi = {+ Number1: 1,+ NumberMinus1: -1,+} as const++export interface TicketViewSortingApi {+ /** Ticket column to sort by (updated_at, sla_due_at, snoozed_until, created_at, ticket_number). Unknown columns fall back to updated_at. */+ columnKey: string+ /** 1 for ascending, -1 for descending.+ *+ * * `1` - 1+ * * `-1` - -1 */+ order: TicketSortOrderEnumApi+}++export type TicketViewFiltersApiAssigneeItem =+ | 'me'+ | 'unassigned'+ | {+ type: 'user' | 'role'+ id: string | number+ }++/**+ * Canonical shape of a saved ticket view's filters. Every field is optional; an omitted+ * field (or an 'all' sentinel) leaves that dimension unfiltered.+ */+export interface TicketViewFiltersApi {+ /** Ticket statuses to include. Empty or omitted means all statuses. */+ status?: TicketStatusEnumApi[]+ /** Ticket priorities to include. Empty or omitted means all priorities. */+ priority?: TicketPriorityEnumApi[]+ /** Channel the ticket originated from. 'all' disables the filter.+ *+ * * `widget` - widget+ * * `email` - email+ * * `slack` - slack+ * * `teams` - teams+ * * `github` - github+ * * `all` - all */+ channel?: TicketChannelFilterEnumApi+ /** SLA state: 'breached' is past due, 'at-risk' is due within the next hour, 'on-track' has more than an hour remaining. 'all' disables the filter.+ *+ * * `breached` - breached+ * * `at-risk` - at-risk+ * * `on-track` - on-track+ * * `all` - all */+ sla?: TicketSlaFilterEnumApi+ /** AI triage outcomes to include. 'in_progress' matches tickets still being triaged. */+ aiTriageResult?: AiTriageResultEnumApi[]+ /** Assignees to match (any of): 'unassigned', 'me' (resolved to the requesting user), or an object with type ('user' or 'role') and id. The legacy single-value shape is accepted and normalized to a list. */+ assignee?: TicketViewFiltersApiAssigneeItem[]+ /** Tag names to match, combined according to tagsMatch. */+ tags?: string[]+ /** 'any' returns tickets with at least one of tags (OR); 'all' requires every tag (AND).+ *+ * * `any` - any+ * * `all` - all */+ tagsMatch?: TicketTagsMatchEnumApi+ /** Tickets carrying any of these tags are excluded. */+ tagsExclude?: string[]+ /**+ * Only include tickets updated on or after this date. Accepts absolute dates (2026-01-01) or relative ones (-7d). 'all' or null disables the bound.+ * @nullable+ */+ dateFrom?: string | null+ /**+ * Only include tickets updated on or before this date. Same format as dateFrom.+ * @nullable+ */+ dateTo?: string | null+ /** Sort order for the ticket list. */+ sorting?: TicketViewSortingApi | null+ /**+ * Free-text search. A numeric value matches a ticket number exactly; otherwise matches the customer's name or email, the email subject, or message content.+ * @maxLength 200+ */+ search?: string+}export interface TicketViewApi {readonly id: stringreadonly short_id: string/** @maxLength 400 */name: string- /** Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys. */- filters?: TicketViewApiFilters+ /** Saved ticket filter criteria: status, priority, channel, sla, aiTriageResult, assignee, tags, tagsMatch, tagsExclude, dateFrom, dateTo, sorting, and search. */+ filters?: TicketViewFiltersApireadonly created_at: stringreadonly created_by: UserBasicApi/** Whether the current user has favorited this view. Favorited views sort to the top of the list. Favorites are personal to each user. */@@ -1083,18 +1230,13 @@ export interface PaginatedTicketViewListApi {results: TicketViewApi[]}-/**- * Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys.- */-export type PatchedTicketViewApiFilters = { [key: string]: unknown }-export interface PatchedTicketViewApi {readonly id?: stringreadonly short_id?: string/** @maxLength 400 */name?: string- /** Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys. */- filters?: PatchedTicketViewApiFilters+ /** Saved ticket filter criteria: status, priority, channel, sla, aiTriageResult, assignee, tags, tagsMatch, tagsExclude, dateFrom, dateTo, sorting, and search. */+ filters?: TicketViewFiltersApireadonly created_at?: stringreadonly created_by?: UserBasicApi/** Whether the current user has favorited this view. Favorited views sort to the top of the list. Favorites are personal to each user. */@@ -1202,6 +1344,10 @@ export type ConversationsListParams = {}export type ConversationsTicketsListParams = {+ /**+ * Filter by AI triage outcome. Accepts a single value or a comma-separated list. Valid values: `persisted`, `escalated_with_best`, `escalated_no_reply`, `skipped_unactionable`, `blocked_unsafe`, `blocked_unsafe_reply`, `in_progress`.+ */+ ai_triage_result?: string/*** Filter by assignee. Accepts a single value or a comma-separated list (matches any, max 100 entries). Each entry is `unassigned` (no assignee), `me` (the requesting user), `user:<user_id>`, or `role:<role_uuid>`, e.g. `assignee=unassigned,user:123`.*/@@ -1254,6 +1400,10 @@ export type ConversationsTicketsListParams = {* Filter by SLA state. `breached` = past `sla_due_at`, `at-risk` = due within the next hour, `on-track` = more than an hour remaining.*/sla?: ConversationsTicketsListSla+ /**+ * Filter by snooze state: `true` returns only snoozed tickets, `false` only non-snoozed.+ */+ snoozed?: boolean/*** Filter by status. Accepts a single value or a comma-separated list (e.g. `new,open,pending`). Valid values: `new`, `open`, `pending`, `on_hold`, `resolved`.*/@@ -1270,6 +1420,10 @@ export type ConversationsTicketsListParams = {* JSON-encoded array of tag names; returns tickets that have NONE of them (NOT), e.g. `["escalated"]`.*/tags_exclude?: string+ /**+ * Apply a saved ticket view's filters by its `short_id` (list views via the `conversations/views` endpoint). Any filter param passed explicitly overrides the view's saved value for that dimension. Returns 400 if no view matches.+ */+ view?: string}export type ConversationsTicketsListChannelDetail =diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.tsindex 9d4f40b0a7e3..6b030120b63a 100644--- a/products/conversations/frontend/generated/api.zod.ts+++ b/products/conversations/frontend/generated/api.zod.ts@@ -365,13 +365,131 @@ export const ConversationsTicketsComposeCreateBody = /* @__PURE__ */ zod.object(export const conversationsViewsCreateBodyNameMax = 400+export const conversationsViewsCreateBodyFiltersOneSearchMax = 200+export const ConversationsViewsCreateBody = /* @__PURE__ */ zod.object({name: zod.string().max(conversationsViewsCreateBodyNameMax),filters: zod- .record(zod.string(), zod.unknown())+ .object({+ status: zod+ .array(+ zod+ .enum(['new', 'open', 'pending', 'on_hold', 'resolved'])+ .describe(+ '\* `new` - New\n\* `open` - Open\n\* `pending` - Pending\n\* `on_hold` - On hold\n\* `resolved` - Resolved'+ )+ )+ .optional()+ .describe('Ticket statuses to include. Empty or omitted means all statuses.'),+ priority: zod+ .array(+ zod+ .enum(['low', 'medium', 'high', 'critical'])+ .describe('\* `low` - Low\n\* `medium` - Medium\n\* `high` - High\n\* `critical` - Critical')+ )+ .optional()+ .describe('Ticket priorities to include. Empty or omitted means all priorities.'),+ channel: zod+ .enum(['widget', 'email', 'slack', 'teams', 'github', 'all'])+ .describe(+ '\* `widget` - widget\n\* `email` - email\n\* `slack` - slack\n\* `teams` - teams\n\* `github` - github\n\* `all` - all'+ )+ .optional()+ .describe(+ "Channel the ticket originated from. 'all' disables the filter.\n\n\* `widget` - widget\n\* `email` - email\n\* `slack` - slack\n\* `teams` - teams\n\* `github` - github\n\* `all` - all"+ ),+ sla: zod+ .enum(['breached', 'at-risk', 'on-track', 'all'])+ .describe('\* `breached` - breached\n\* `at-risk` - at-risk\n\* `on-track` - on-track\n\* `all` - all')+ .optional()+ .describe(+ "SLA state: 'breached' is past due, 'at-risk' is due within the next hour, 'on-track' has more than an hour remaining. 'all' disables the filter.\n\n\* `breached` - breached\n\* `at-risk` - at-risk\n\* `on-track` - on-track\n\* `all` - all"+ ),+ aiTriageResult: zod+ .array(+ zod+ .enum([+ 'persisted',+ 'escalated_with_best',+ 'escalated_no_reply',+ 'skipped_unactionable',+ 'blocked_unsafe',+ 'blocked_unsafe_reply',+ 'in_progress',+ ])+ .describe(+ '\* `persisted` - persisted\n\* `escalated_with_best` - escalated_with_best\n\* `escalated_no_reply` - escalated_no_reply\n\* `skipped_unactionable` - skipped_unactionable\n\* `blocked_unsafe` - blocked_unsafe\n\* `blocked_unsafe_reply` - blocked_unsafe_reply\n\* `in_progress` - in_progress'+ )+ )+ .optional()+ .describe("AI triage outcomes to include. 'in_progress' matches tickets still being triaged."),+ assignee: zod+ .array(+ zod.union([+ zod.enum(['me', 'unassigned']),+ zod.object({+ type: zod.enum(['user', 'role']),+ id: zod.union([zod.string(), zod.number()]),+ }),+ ])+ )+ .optional()+ .describe(+ "Assignees to match (any of): 'unassigned', 'me' (resolved to the requesting user), or an object with type ('user' or 'role') and id. The legacy single-value shape is accepted and normalized to a list."+ ),+ tags: zod.array(zod.string()).optional().describe('Tag names to match, combined according to tagsMatch.'),+ tagsMatch: zod+ .enum(['any', 'all'])+ .describe('\* `any` - any\n\* `all` - all')+ .optional()+ .describe(+ "'any' returns tickets with at least one of tags (OR); 'all' requires every tag (AND).\n\n\* `any` - any\n\* `all` - all"+ ),+ tagsExclude: zod+ .array(zod.string())+ .optional()+ .describe('Tickets carrying any of these tags are excluded.'),+ dateFrom: zod+ .string()+ .nullish()+ .describe(+ "Only include tickets updated on or after this date. Accepts absolute dates (2026-01-01) or relative ones (-7d). 'all' or null disables the bound."+ ),+ dateTo: zod+ .string()+ .nullish()+ .describe('Only include tickets updated on or before this date. Same format as dateFrom.'),+ sorting: zod+ .union([+ zod.object({+ columnKey: zod+ .string()+ .describe(+ 'Ticket column to sort by (updated_at, sla_due_at, snoozed_until, created_at, ticket_number). Unknown columns fall back to updated_at.'+ ),+ order: zod+ .union([zod.literal(1), zod.literal(-1)])+ .describe('\* `1` - 1\n\* `-1` - -1')+ .describe('1 for ascending, -1 for descending.\n\n\* `1` - 1\n\* `-1` - -1'),+ }),+ zod.null(),+ ])+ .optional()+ .describe('Sort order for the ticket list.'),+ search: zod+ .string()+ .max(conversationsViewsCreateBodyFiltersOneSearchMax)+ .optional()+ .describe(+ "Free-text search. A numeric value matches a ticket number exactly; otherwise matches the customer's name or email, the email subject, or message content."+ ),+ })+ .describe(+ "Canonical shape of a saved ticket view's filters. Every field is optional; an omitted\nfield (or an 'all' sentinel) leaves that dimension unfiltered."+ ).optional().describe(- 'Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys.'+ 'Saved ticket filter criteria: status, priority, channel, sla, aiTriageResult, assignee, tags, tagsMatch, tagsExclude, dateFrom, dateTo, sorting, and search.'),is_favorited: zod.boolean()@@ -383,13 +501,131 @@ export const ConversationsViewsCreateBody = /* @__PURE__ */ zod.object({export const conversationsViewsPartialUpdateBodyNameMax = 400+export const conversationsViewsPartialUpdateBodyFiltersOneSearchMax = 200+export const ConversationsViewsPartialUpdateBody = /* @__PURE__ */ zod.object({name: zod.string().max(conversationsViewsPartialUpdateBodyNameMax).optional(),filters: zod- .record(zod.string(), zod.unknown())+ .object({+ status: zod+ .array(+ zod+ .enum(['new', 'open', 'pending', 'on_hold', 'resolved'])+ .describe(+ '\* `new` - New\n\* `open` - Open\n\* `pending` - Pending\n\* `on_hold` - On hold\n\* `resolved` - Resolved'+ )+ )+ .optional()+ .describe('Ticket statuses to include. Empty or omitted means all statuses.'),+ priority: zod+ .array(+ zod+ .enum(['low', 'medium', 'high', 'critical'])+ .describe('\* `low` - Low\n\* `medium` - Medium\n\* `high` - High\n\* `critical` - Critical')+ )+ .optional()+ .describe('Ticket priorities to include. Empty or omitted means all priorities.'),+ channel: zod+ .enum(['widget', 'email', 'slack', 'teams', 'github', 'all'])+ .describe(+ '\* `widget` - widget\n\* `email` - email\n\* `slack` - slack\n\* `teams` - teams\n\* `github` - github\n\* `all` - all'+ )+ .optional()+ .describe(+ "Channel the ticket originated from. 'all' disables the filter.\n\n\* `widget` - widget\n\* `email` - email\n\* `slack` - slack\n\* `teams` - teams\n\* `github` - github\n\* `all` - all"+ ),+ sla: zod+ .enum(['breached', 'at-risk', 'on-track', 'all'])+ .describe('\* `breached` - breached\n\* `at-risk` - at-risk\n\* `on-track` - on-track\n\* `all` - all')+ .optional()+ .describe(+ "SLA state: 'breached' is past due, 'at-risk' is due within the next hour, 'on-track' has more than an hour remaining. 'all' disables the filter.\n\n\* `breached` - breached\n\* `at-risk` - at-risk\n\* `on-track` - on-track\n\* `all` - all"+ ),+ aiTriageResult: zod+ .array(+ zod+ .enum([+ 'persisted',+ 'escalated_with_best',+ 'escalated_no_reply',+ 'skipped_unactionable',+ 'blocked_unsafe',+ 'blocked_unsafe_reply',+ 'in_progress',+ ])+ .describe(+ '\* `persisted` - persisted\n\* `escalated_with_best` - escalated_with_best\n\* `escalated_no_reply` - escalated_no_reply\n\* `skipped_unactionable` - skipped_unactionable\n\* `blocked_unsafe` - blocked_unsafe\n\* `blocked_unsafe_reply` - blocked_unsafe_reply\n\* `in_progress` - in_progress'+ )+ )+ .optional()+ .describe("AI triage outcomes to include. 'in_progress' matches tickets still being triaged."),+ assignee: zod+ .array(+ zod.union([+ zod.enum(['me', 'unassigned']),+ zod.object({+ type: zod.enum(['user', 'role']),+ id: zod.union([zod.string(), zod.number()]),+ }),+ ])+ )+ .optional()+ .describe(+ "Assignees to match (any of): 'unassigned', 'me' (resolved to the requesting user), or an object with type ('user' or 'role') and id. The legacy single-value shape is accepted and normalized to a list."+ ),+ tags: zod.array(zod.string()).optional().describe('Tag names to match, combined according to tagsMatch.'),+ tagsMatch: zod+ .enum(['any', 'all'])+ .describe('\* `any` - any\n\* `all` - all')+ .optional()+ .describe(+ "'any' returns tickets with at least one of tags (OR); 'all' requires every tag (AND).\n\n\* `any` - any\n\* `all` - all"+ ),+ tagsExclude: zod+ .array(zod.string())+ .optional()+ .describe('Tickets carrying any of these tags are excluded.'),+ dateFrom: zod+ .string()+ .nullish()+ .describe(+ "Only include tickets updated on or after this date. Accepts absolute dates (2026-01-01) or relative ones (-7d). 'all' or null disables the bound."+ ),+ dateTo: zod+ .string()+ .nullish()+ .describe('Only include tickets updated on or before this date. Same format as dateFrom.'),+ sorting: zod+ .union([+ zod.object({+ columnKey: zod+ .string()+ .describe(+ 'Ticket column to sort by (updated_at, sla_due_at, snoozed_until, created_at, ticket_number). Unknown columns fall back to updated_at.'+ ),+ order: zod+ .union([zod.literal(1), zod.literal(-1)])+ .describe('\* `1` - 1\n\* `-1` - -1')+ .describe('1 for ascending, -1 for descending.\n\n\* `1` - 1\n\* `-1` - -1'),+ }),+ zod.null(),+ ])+ .optional()+ .describe('Sort order for the ticket list.'),+ search: zod+ .string()+ .max(conversationsViewsPartialUpdateBodyFiltersOneSearchMax)+ .optional()+ .describe(+ "Free-text search. A numeric value matches a ticket number exactly; otherwise matches the customer's name or email, the email subject, or message content."+ ),+ })+ .describe(+ "Canonical shape of a saved ticket view's filters. Every field is optional; an omitted\nfield (or an 'all' sentinel) leaves that dimension unfiltered."+ ).optional().describe(- 'Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys.'+ 'Saved ticket filter criteria: status, priority, channel, sla, aiTriageResult, assignee, tags, tagsMatch, tagsExclude, dateFrom, dateTo, sorting, and search.'),is_favorited: zod.boolean()diff --git a/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx b/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsxindex 77981afea0fb..4731d262989e 100644--- a/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx+++ b/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx@@ -317,6 +317,9 @@ export function SupportTicketsTableFilters({ embedded = false }: SupportTicketsTonChange={setSearchQuery}size="small"className="min-w-64"+ // Matches MAX_SEARCH_LENGTH in ticket_filters.py — the backend ignores+ // longer searches and rejects saving them in a view.+ maxLength={200}/><Tooltiptitle={diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex bf2c575e25e7..8ebdfe5a3990 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -1,9 +1,8 @@-import type { Sorting } from 'lib/lemon-ui/LemonTable/sorting'-import type { AccessControlLevel } from '~/types'import { MAX_ASSIGNEE_FILTER_ENTRIES } from './components/Assignee'import type { AssigneeFilterEntry, TicketAssignee } from './components/Assignee'+import type { TicketViewFiltersApi } from './generated/api.schemas'export type { AssigneeFilterEntry }@@ -94,20 +93,13 @@ export interface KnowledgeGapSuggestion {created_at: string}-export interface TicketViewFilters {- status?: TicketStatus[]- priority?: TicketPriority[]- channel?: TicketChannel | 'all'- sla?: TicketSlaState | 'all'- aiTriageResult?: AITriageFilterValue[]+/**+ * Canonical saved-view filter shape, generated from the backend's TicketViewFiltersSerializer.+ * `assignee` is widened locally: the API stores filters raw, so old saved views can still+ * return the legacy single-value shape — always read it through normalizeAssigneeFilter.+ */+export type TicketViewFilters = Omit<TicketViewFiltersApi, 'assignee'> & {assignee?: AssigneeFilterEntry[] | AssigneeFilterValue- tags?: string[]- tagsMatch?: TicketTagsMatch- tagsExclude?: string[]- dateFrom?: string | null- dateTo?: string | null- sorting?: Sorting | null- search?: string}export interface SavedTicketView {diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yamlindex f95b5868e9a9..8c6fad4d09b2 100644--- a/products/conversations/mcp/tools.yaml+++ b/products/conversations/mcp/tools.yaml@@ -40,9 +40,12 @@ tools:title: List support ticketsdescription: >List support tickets in the project. Supports filtering by status (new, open, pending, on_hold, resolved),- priority (low, medium, high, critical), channel_source (widget, email, slack), assignee, date range, and- search. Results are paginated and ordered by updated_at descending by default. Returns ticket metadata- including status, priority, message counts, and timestamps.+ priority (low, medium, high, critical), channel_source (widget, email, slack), assignee, tags, SLA state, AI+ triage result, date range, and search. To work with a saved ticket view, pass its short_id as the `view`+ parameter (find it via the list-saved-ticket-views tool); the view's saved filters are applied server-side,+ and any filter parameter passed explicitly overrides the view's value for that dimension. Results are+ paginated and ordered by updated_at descending by default. Returns ticket metadata including status,+ priority, message counts, and timestamps.response:include:- id@@ -171,7 +174,8 @@ tools:description: >List the saved ticket views in the project. Each view is a named, saved set of ticket filters — for examplethe per-team views named "Team <name>". Returns each view's short_id and name; a view opens in the app at- /support/tickets?view=<short_id>.+ /support/tickets?view=<short_id>. To get the tickets a view contains, pass its short_id as the `view`+ parameter of the list-support-tickets tool.response:include:- short_iddiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex ffb9df41ddb5..0306c16fcdee 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -1397,7 +1397,7 @@}},"conversations-tickets-list": {- "description": "List support tickets in the project. Supports filtering by status (new, open, pending, on_hold, resolved), priority (low, medium, high, critical), channel_source (widget, email, slack), assignee, date range, and search. Results are paginated and ordered by updated_at descending by default. Returns ticket metadata including status, priority, message counts, and timestamps.",+ "description": "List support tickets in the project. Supports filtering by status (new, open, pending, on_hold, resolved), priority (low, medium, high, critical), channel_source (widget, email, slack), assignee, tags, SLA state, AI triage result, date range, and search. To work with a saved ticket view, pass its short_id as the `view` parameter (find it via the list-saved-ticket-views tool); the view's saved filters are applied server-side, and any filter parameter passed explicitly overrides the view's value for that dimension. Results are paginated and ordered by updated_at descending by default. Returns ticket metadata including status, priority, message counts, and timestamps.","category": "Conversations","feature": "conversations","summary": "List support tickets",@@ -1467,7 +1467,7 @@}},"conversations-views-list": {- "description": "List the saved ticket views in the project. Each view is a named, saved set of ticket filters — for example the per-team views named \"Team <name>\". Returns each view's short_id and name; a view opens in the app at /support/tickets?view=<short_id>.",+ "description": "List the saved ticket views in the project. Each view is a named, saved set of ticket filters — for example the per-team views named \"Team <name>\". Returns each view's short_id and name; a view opens in the app at /support/tickets?view=<short_id>. To get the tickets a view contains, pass its short_id as the `view` parameter of the list-support-tickets tool.","category": "Conversations","feature": "conversations","summary": "List saved ticket views",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex b05b23d38f78..8a2b9d0e1de4 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -1412,7 +1412,7 @@}},"conversations-tickets-list": {- "description": "List support tickets in the project. Supports filtering by status (new, open, pending, on_hold, resolved), priority (low, medium, high, critical), channel_source (widget, email, slack), assignee, date range, and search. Results are paginated and ordered by updated_at descending by default. Returns ticket metadata including status, priority, message counts, and timestamps.",+ "description": "List support tickets in the project. Supports filtering by status (new, open, pending, on_hold, resolved), priority (low, medium, high, critical), channel_source (widget, email, slack), assignee, tags, SLA state, AI triage result, date range, and search. To work with a saved ticket view, pass its short_id as the `view` parameter (find it via the list-saved-ticket-views tool); the view's saved filters are applied server-side, and any filter parameter passed explicitly overrides the view's value for that dimension. Results are paginated and ordered by updated_at descending by default. Returns ticket metadata including status, priority, message counts, and timestamps.","category": "Conversations","feature": "conversations","summary": "List support tickets",@@ -1482,7 +1482,7 @@}},"conversations-views-list": {- "description": "List the saved ticket views in the project. Each view is a named, saved set of ticket filters — for example the per-team views named \"Team <name>\". Returns each view's short_id and name; a view opens in the app at /support/tickets?view=<short_id>.",+ "description": "List the saved ticket views in the project. Each view is a named, saved set of ticket filters — for example the per-team views named \"Team <name>\". Returns each view's short_id and name; a view opens in the app at /support/tickets?view=<short_id>. To get the tickets a view contains, pass its short_id as the `view` parameter of the list-support-tickets tool.","category": "Conversations","feature": "conversations","summary": "List saved ticket views",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e6508651dec5..90643162e971 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -8190,6 +8190,28 @@ export namespace Schemas {feedback_text?: string;}+ /**+ * * `persisted` - persisted+ * * `escalated_with_best` - escalated_with_best+ * * `escalated_no_reply` - escalated_no_reply+ * * `skipped_unactionable` - skipped_unactionable+ * * `blocked_unsafe` - blocked_unsafe+ * * `blocked_unsafe_reply` - blocked_unsafe_reply+ * * `in_progress` - in_progress+ */+ export type AiTriageResultEnum = typeof AiTriageResultEnum[keyof typeof AiTriageResultEnum];+++ export const AiTriageResultEnum = {+ Persisted: 'persisted',+ EscalatedWithBest: 'escalated_with_best',+ EscalatedNoReply: 'escalated_no_reply',+ SkippedUnactionable: 'skipped_unactionable',+ BlockedUnsafe: 'blocked_unsafe',+ BlockedUnsafeReply: 'blocked_unsafe_reply',+ InProgress: 'in_progress',+ } as const;+export interface InsightsThresholdBounds {/** Alert fires when the value drops below this number. */lower?: number | null;@@ -47927,16 +47949,143 @@ export namespace Schemas {}/**- * Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys.+ * * `widget` - widget+ * * `email` - email+ * * `slack` - slack+ * * `teams` - teams+ * * `github` - github+ * * `all` - all+ */+ export type TicketChannelFilterEnum = typeof TicketChannelFilterEnum[keyof typeof TicketChannelFilterEnum];+++ export const TicketChannelFilterEnum = {+ Widget: 'widget',+ Email: 'email',+ Slack: 'slack',+ Teams: 'teams',+ Github: 'github',+ All: 'all',+ } as const;++ /**+ * * `breached` - breached+ * * `at-risk` - at-risk+ * * `on-track` - on-track+ * * `all` - all+ */+ export type TicketSlaFilterEnum = typeof TicketSlaFilterEnum[keyof typeof TicketSlaFilterEnum];+++ export const TicketSlaFilterEnum = {+ Breached: 'breached',+ AtRisk: 'at-risk',+ OnTrack: 'on-track',+ All: 'all',+ } as const;++ /**+ * * `any` - any+ * * `all` - all*/- export type TicketViewFilters = { [key: string]: unknown };+ export type TicketTagsMatchEnum = typeof TicketTagsMatchEnum[keyof typeof TicketTagsMatchEnum];+++ export const TicketTagsMatchEnum = {+ Any: 'any',+ All: 'all',+ } as const;++ /**+ * * `1` - 1+ * * `-1` - -1+ */+ export type TicketSortOrderEnum = typeof TicketSortOrderEnum[keyof typeof TicketSortOrderEnum];+++ export const TicketSortOrderEnum = {+ Number1: 1,+ NumberMinus1: -1,+ } as const;++ export interface TicketViewSorting {+ /** Ticket column to sort by (updated_at, sla_due_at, snoozed_until, created_at, ticket_number). Unknown columns fall back to updated_at. */+ columnKey: string;+ /** 1 for ascending, -1 for descending.+ *+ * * `1` - 1+ * * `-1` - -1 */+ order: TicketSortOrderEnum;+ }++ export type TicketViewFiltersAssigneeItem = 'me' | 'unassigned' | {+ type: 'user' | 'role';+ id: string | number;+ };++ /**+ * Canonical shape of a saved ticket view's filters. Every field is optional; an omitted+ * field (or an 'all' sentinel) leaves that dimension unfiltered.+ */+ export interface TicketViewFilters {+ /** Ticket statuses to include. Empty or omitted means all statuses. */+ status?: TicketStatusEnum[];+ /** Ticket priorities to include. Empty or omitted means all priorities. */+ priority?: TicketPriorityEnum[];+ /** Channel the ticket originated from. 'all' disables the filter.+ *+ * * `widget` - widget+ * * `email` - email+ * * `slack` - slack+ * * `teams` - teams+ * * `github` - github+ * * `all` - all */+ channel?: TicketChannelFilterEnum;+ /** SLA state: 'breached' is past due, 'at-risk' is due within the next hour, 'on-track' has more than an hour remaining. 'all' disables the filter.+ *+ * * `breached` - breached+ * * `at-risk` - at-risk+ * * `on-track` - on-track+ * * `all` - all */+ sla?: TicketSlaFilterEnum;+ /** AI triage outcomes to include. 'in_progress' matches tickets still being triaged. */+ aiTriageResult?: AiTriageResultEnum[];+ /** Assignees to match (any of): 'unassigned', 'me' (resolved to the requesting user), or an object with type ('user' or 'role') and id. The legacy single-value shape is accepted and normalized to a list. */+ assignee?: TicketViewFiltersAssigneeItem[];+ /** Tag names to match, combined according to tagsMatch. */+ tags?: string[];+ /** 'any' returns tickets with at least one of tags (OR); 'all' requires every tag (AND).+ *+ * * `any` - any+ * * `all` - all */+ tagsMatch?: TicketTagsMatchEnum;+ /** Tickets carrying any of these tags are excluded. */+ tagsExclude?: string[];+ /**+ * Only include tickets updated on or after this date. Accepts absolute dates (2026-01-01) or relative ones (-7d). 'all' or null disables the bound.+ * @nullable+ */+ dateFrom?: string | null;+ /**+ * Only include tickets updated on or before this date. Same format as dateFrom.+ * @nullable+ */+ dateTo?: string | null;+ /** Sort order for the ticket list. */+ sorting?: TicketViewSorting | null;+ /**+ * Free-text search. A numeric value matches a ticket number exactly; otherwise matches the customer's name or email, the email subject, or message content.+ * @maxLength 200+ */+ search?: string;+ }export interface TicketView {readonly id: string;readonly short_id: string;/** @maxLength 400 */name: string;- /** Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys. */+ /** Saved ticket filter criteria: status, priority, channel, sla, aiTriageResult, assignee, tags, tagsMatch, tagsExclude, dateFrom, dateTo, sorting, and search. */filters?: TicketViewFilters;readonly created_at: string;readonly created_by: UserBasic;@@ -56076,18 +56225,13 @@ export namespace Schemas {readonly user_access_level?: string | null;}- /**- * Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys.- */- export type PatchedTicketViewFilters = { [key: string]: unknown };-export interface PatchedTicketView {readonly id?: string;readonly short_id?: string;/** @maxLength 400 */name?: string;- /** Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys. */- filters?: PatchedTicketViewFilters;+ /** Saved ticket filter criteria: status, priority, channel, sla, aiTriageResult, assignee, tags, tagsMatch, tagsExclude, dateFrom, dateTo, sorting, and search. */+ filters?: TicketViewFilters;readonly created_at?: string;readonly created_by?: UserBasic;/** Whether the current user has favorited this view. Favorited views sort to the top of the list. Favorites are personal to each user. */@@ -76655,6 +76799,10 @@ export namespace Schemas {};export type ConversationsTicketsListParams = {+ /**+ * Filter by AI triage outcome. Accepts a single value or a comma-separated list. Valid values: `persisted`, `escalated_with_best`, `escalated_no_reply`, `skipped_unactionable`, `blocked_unsafe`, `blocked_unsafe_reply`, `in_progress`.+ */+ ai_triage_result?: string;/*** Filter by assignee. Accepts a single value or a comma-separated list (matches any, max 100 entries). Each entry is `unassigned` (no assignee), `me` (the requesting user), `user:<user_id>`, or `role:<role_uuid>`, e.g. `assignee=unassigned,user:123`.*/@@ -76707,6 +76855,10 @@ export namespace Schemas {* Filter by SLA state. `breached` = past `sla_due_at`, `at-risk` = due within the next hour, `on-track` = more than an hour remaining.*/sla?: ConversationsTicketsListSla;+ /**+ * Filter by snooze state: `true` returns only snoozed tickets, `false` only non-snoozed.+ */+ snoozed?: boolean;/*** Filter by status. Accepts a single value or a comma-separated list (e.g. `new,open,pending`). Valid values: `new`, `open`, `pending`, `on_hold`, `resolved`.*/@@ -76723,6 +76875,10 @@ export namespace Schemas {* JSON-encoded array of tag names; returns tickets that have NONE of them (NOT), e.g. `["escalated"]`.*/tags_exclude?: string;+ /**+ * Apply a saved ticket view's filters by its `short_id` (list views via the `conversations/views` endpoint). Any filter param passed explicitly overrides the view's saved value for that dimension. Returns 400 if no view matches.+ */+ view?: string;};export type ConversationsTicketsListChannelDetail = typeof ConversationsTicketsListChannelDetail[keyof typeof ConversationsTicketsListChannelDetail];diff --git a/services/mcp/src/generated/conversations/api.ts b/services/mcp/src/generated/conversations/api.tsindex d125829c82ba..7e74c5a6f02a 100644--- a/services/mcp/src/generated/conversations/api.ts+++ b/services/mcp/src/generated/conversations/api.ts@@ -20,6 +20,12 @@ export const ConversationsTicketsListParams = /* @__PURE__ */ zod.object({})export const ConversationsTicketsListQueryParams = /* @__PURE__ */ zod.object({+ ai_triage_result: zod+ .string()+ .optional()+ .describe(+ 'Filter by AI triage outcome. Accepts a single value or a comma-separated list. Valid values: `persisted`, `escalated_with_best`, `escalated_no_reply`, `skipped_unactionable`, `blocked_unsafe`, `blocked_unsafe_reply`, `in_progress`.'+ ),assignee: zod.string().optional()@@ -87,6 +93,10 @@ export const ConversationsTicketsListQueryParams = /* @__PURE__ */ zod.object({.describe('Filter by SLA state. `breached` = past `sla_due_at`, `at-risk` = due within the next hour, `on-track` = more than an hour remaining.'),+ snoozed: zod+ .boolean()+ .optional()+ .describe('Filter by snooze state: `true` returns only snoozed tickets, `false` only non-snoozed.'),status: zod.string().optional()@@ -111,6 +121,12 @@ export const ConversationsTicketsListQueryParams = /* @__PURE__ */ zod.object({.describe('JSON-encoded array of tag names; returns tickets that have NONE of them (NOT), e.g. `[\"escalated\"]`.'),+ view: zod+ .string()+ .optional()+ .describe(+ "Apply a saved ticket view's filters by its `short_id` (list views via the `conversations\/views` endpoint). Any filter param passed explicitly overrides the view's saved value for that dimension. Returns 400 if no view matches."+ ),})/**diff --git a/services/mcp/src/tools/generated/conversations.ts b/services/mcp/src/tools/generated/conversations.tsindex d85e9c2fe7ca..405761e703bb 100644--- a/services/mcp/src/tools/generated/conversations.ts+++ b/services/mcp/src/tools/generated/conversations.ts@@ -36,6 +36,7 @@ const conversationsTicketsList = (): ToolBase<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/conversations/tickets/`,query: {+ ai_triage_result: params.ai_triage_result,assignee: params.assignee,channel_detail: params.channel_detail,channel_source: params.channel_source,@@ -49,10 +50,12 @@ const conversationsTicketsList = (): ToolBase<priority: params.priority,search: params.search,sla: params.sla,+ snoozed: params.snoozed,status: params.status,tags: params.tags,tags_all: params.tags_all,tags_exclude: params.tags_exclude,+ view: params.view,},})const filtered = {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.jsonindex bd47dee3bbc6..844136d81148 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.json@@ -1,6 +1,10 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "ai_triage_result": {+ "description": "Filter by AI triage outcome. Accepts a single value or a comma-separated list. Valid values: `persisted`, `escalated_with_best`, `escalated_no_reply`, `skipped_unactionable`, `blocked_unsafe`, `blocked_unsafe_reply`, `in_progress`.",+ "type": "string"+ },"assignee": {"description": "Filter by assignee. Accepts a single value or a comma-separated list (matches any, max 100 entries). Each entry is `unassigned` (no assignee), `me` (the requesting user), `user:<user_id>`, or `role:<role_uuid>`, e.g. `assignee=unassigned,user:123`.","type": "string"@@ -65,6 +69,10 @@"enum": ["at-risk", "breached", "on-track"],"type": "string"},+ "snoozed": {+ "description": "Filter by snooze state: `true` returns only snoozed tickets, `false` only non-snoozed.",+ "type": "boolean"+ },"status": {"description": "Filter by status. Accepts a single value or a comma-separated list (e.g. `new,open,pending`). Valid values: `new`, `open`, `pending`, `on_hold`, `resolved`.","type": "string"@@ -80,6 +88,10 @@"tags_exclude": {"description": "JSON-encoded array of tag names; returns tickets that have NONE of them (NOT), e.g. `[\"escalated\"]`.","type": "string"+ },+ "view": {+ "description": "Apply a saved ticket view's filters by its `short_id` (list views via the `conversations/views` endpoint). Any filter param passed explicitly overrides the view's saved value for that dimension. Returns 400 if no view matches.",+ "type": "string"}},"type": "object"