Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(conversations): richer ticket context (#103112)

Alex V703829972fe5
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 8ed215875628..e5b1e9d56cf4 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -808,6 +808,7 @@ export interface ConversationsSettings {
ai_reply_modes?: Record<string, Record<string, 'private_note' | 'bot_reply'>> | null
ai_reply_custom_instructions?: string | null
docs_source?: 'posthog' | null
+ ai_context_account_property_ids?: string[] | null
}
export interface LogsSettings {
diff --git a/posthog/api/project.py b/posthog/api/project.py
index f2dae0d26a83..6972267e039a 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -651,12 +651,16 @@ class ProjectBackwardCompatSerializer(
if "widget_domains" in value and value["widget_domains"] is not None:
value["widget_domains"] = [domain for domain in value["widget_domains"] if domain]
validate_authorized_url_wildcards(value["widget_domains"])
+ from products.conversations.backend.api.ai_context import validate_ai_context_conversations_settings
from products.conversations.backend.api.ai_reply_playbook import validate_playbook_conversations_settings
# conversations_settings lives on the passthrough Team, not on Project, so a partial
# update that omits docs_source still normalizes against the saved source.
existing = self.instance.passthrough_team.conversations_settings if self.instance is not None else None
validate_playbook_conversations_settings(value, existing=existing if isinstance(existing, dict) else None)
+ validate_ai_context_conversations_settings(
+ value, team_id=self.instance.passthrough_team.id if self.instance is not None else None
+ )
return value
class Meta:
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 8e5165ea30d1..f2d71a883b48 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -1885,10 +1885,14 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
value["ai_reply_modes"] = cleaned_modes
else:
raise serializers.ValidationError({"ai_reply_modes": "Must be an object or null."})
+ from products.conversations.backend.api.ai_context import validate_ai_context_conversations_settings
from products.conversations.backend.api.ai_reply_playbook import validate_playbook_conversations_settings
existing = getattr(self.instance, "conversations_settings", None) if self.instance is not None else None
validate_playbook_conversations_settings(value, existing=existing if isinstance(existing, dict) else None)
+ validate_ai_context_conversations_settings(
+ value, team_id=self.instance.id if self.instance is not None else None
+ )
return value
def validate_receive_org_level_activity_logs(self, value: bool | None) -> bool | None:
diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.py
index 45bb96f38d5e..4ad0b4fb4f62 100644
--- a/posthog/api/test/test_project.py
+++ b/posthog/api/test/test_project.py
@@ -236,6 +236,32 @@ class TestProjectAPI(team_api_test_factory()): # type: ignore
]
self.organization.save()
+ def test_project_creation_drops_ai_context_account_property_ids(self):
+ self._set_unlimited_projects()
+ from products.customer_analytics.backend.facade.testing import create_custom_property_definition
+
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan", target_type="account")
+
+ created = self.client.post(
+ "/api/projects/",
+ {
+ "name": "Fresh",
+ "conversations_settings": {"ai_context_account_property_ids": [str(definition.id)]},
+ },
+ format="json",
+ )
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ # The new project's team owns no property definition, so an id borrowed from another
+ # team must not survive creation.
+ assert created.json()["conversations_settings"]["ai_context_account_property_ids"] == []
+
+ malformed = self.client.post(
+ "/api/projects/",
+ {"name": "Malformed", "conversations_settings": {"ai_context_account_property_ids": ["not-a-uuid"]}},
+ format="json",
+ )
+ assert malformed.status_code == status.HTTP_400_BAD_REQUEST
+
def test_project_creation_rejects_paid_logs_retention_without_feature(self):
self._set_unlimited_projects()
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 72f713338ae2..96bfd0b5d77a 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -2016,6 +2016,35 @@ def team_api_test_factory():
)
assert bad.status_code == status.HTTP_400_BAD_REQUEST
+ def test_conversations_ai_context_account_property_ids(self):
+ from products.customer_analytics.backend.facade.testing import create_custom_property_definition
+
+ account_def = create_custom_property_definition(team_id=self.team.id, name="Plan", target_type="account")
+ person_def = create_custom_property_definition(team_id=self.team.id, name="Role", target_type="person")
+ ok = self.client.patch(
+ "/api/environments/@current/",
+ {
+ "conversations_settings": {
+ "ai_context_account_property_ids": [str(account_def.id), str(person_def.id)]
+ }
+ },
+ )
+ assert ok.status_code == status.HTTP_200_OK
+ assert ok.json()["conversations_settings"]["ai_context_account_property_ids"] == [str(account_def.id)]
+
+ empty = self.client.patch(
+ "/api/environments/@current/",
+ {"conversations_settings": {"ai_context_account_property_ids": None}},
+ )
+ assert empty.status_code == status.HTTP_200_OK
+ assert empty.json()["conversations_settings"]["ai_context_account_property_ids"] == []
+
+ bad = self.client.patch(
+ "/api/environments/@current/",
+ {"conversations_settings": {"ai_context_account_property_ids": ["not-a-uuid"]}},
+ )
+ assert bad.status_code == status.HTTP_400_BAD_REQUEST
+
def test_enabling_conversations_auto_generates_token(self):
self.team.conversations_enabled = False
self.team.conversations_settings = None
diff --git a/products/access_control/backend/facade/api.py b/products/access_control/backend/facade/api.py
index d4bade238838..81b713090abe 100644
--- a/products/access_control/backend/facade/api.py
+++ b/products/access_control/backend/facade/api.py
@@ -34,7 +34,16 @@ from ..models.property_access_control import PropertyAccessControl
from ..property_access_control import is_property_access_control_enabled
from . import contracts
from .contracts import PropertyAccessLevel
-from .user_access_control import highest_access_level, minimum_access_level, ordered_access_levels
+from .user_access_control import (
+ RESOURCE_INHERITANCE_MAP,
+ RESOURCES_WITHOUT_RESOURCE_LEVEL_CONTROLS,
+ AccessControlLevel,
+ access_level_satisfied_for_resource,
+ default_access_level,
+ highest_access_level,
+ minimum_access_level,
+ ordered_access_levels,
+)
class InvalidObjectAccessControlError(Exception):
@@ -162,6 +171,96 @@ def user_organizations_use_access_controls(*, user_id: int) -> bool:
return AccessControl.objects.filter(team__organization_id__in=entitled).exists()
+def _level_rank(levels: list[AccessControlLevel], level: str) -> int:
+ """Position of `level` on the ladder, with an unrecognized level ranked below every real one."""
+ return levels.index(cast(AccessControlLevel, level)) if level in levels else -1
+
+
+def _grants_at_least(resource: APIScopeObject, level: str, required_level: AccessControlLevel) -> bool:
+ """Whether `level` satisfies `required_level`, reading an unrecognized level as no grant.
+
+ The access level of a row is an unvalidated string, so a value outside the ladder of the
+ resource is possible. Comparing it would raise, so treat it as restricting instead."""
+ if level not in ordered_access_levels(resource):
+ return False
+ return access_level_satisfied_for_resource(resource, cast(AccessControlLevel, level), required_level)
+
+
+def every_member_has_resource_access(
+ *, team_id: int, resource: APIScopeObject, required_level: AccessControlLevel
+) -> bool:
+ """Whether every member of the team resolves at least `required_level` on `resource`.
+
+ For a caller that builds something without a request user and hands it to many readers at
+ once — an AI-drafted ticket note, a userless precompute. Such a caller cannot honor a
+ restriction on one member, so it asks whether any restriction exists at all and leaves the
+ data out when one does.
+
+ Deliberately conservative, and for that reason the same answer under both resolution orders:
+ one restricting rule makes this False, including where highest-wins resolution would let a
+ permissive default outrank it. Erring toward withholding keeps the answer stable when an
+ organization moves to most-specific resolution.
+ """
+ team = Team.objects.select_related("organization").filter(id=team_id).first()
+ if team is None:
+ return False
+
+ # Resolution reads the rows of the parent of an inheriting resource, never the child's own
+ # resource-scope rows, so the parent is what to inspect.
+ resource = RESOURCE_INHERITANCE_MAP.get(resource, resource)
+
+ # With no rules in effect, every member sits at the built-in default for the resource.
+ if resource in RESOURCES_WITHOUT_RESOURCE_LEVEL_CONTROLS or not team.organization.is_feature_available(
+ AvailableFeature.ACCESS_CONTROL
+ ):
+ return _grants_at_least(resource, default_access_level(resource), required_level)
+
+ rows = list(AccessControl.objects.filter(team_id=team_id, resource=resource, resource_id=None))
+ everyone_rows = [row for row in rows if row.organization_member_id is None and row.role_id is None]
+ subject_rows = [row for row in rows if row.organization_member_id is not None or row.role_id is not None]
+
+ levels = ordered_access_levels(resource)
+ floor = (
+ max((row.access_level for row in everyone_rows), key=lambda level: _level_rank(levels, level))
+ if everyone_rows
+ else default_access_level(resource)
+ )
+ if not _grants_at_least(resource, floor, required_level):
+ return False
+ return all(_grants_at_least(resource, row.access_level, required_level) for row in subject_rows)
+
+
+def object_ids_restricted_from_any_member(
+ *, team_id: int, resource: APIScopeObject, required_level: AccessControlLevel
+) -> set[str]:
+ """Ids of `resource` objects carrying a rule that gives somebody less than `required_level`.
+
+ The object-level counterpart of `every_member_has_resource_access`, for the same kind of
+ caller: one that builds something without a request user and hands it to many readers at
+ once. It cannot tell those readers apart, so it leaves out every object that any rule
+ withholds from any of them.
+
+ Conservative in the same way. One restricting rule on an object is enough to name it, even
+ where resolution would let a permissive rule outrank that one, so the answer does not change
+ when an organization moves to most-specific resolution.
+ """
+ team = Team.objects.select_related("organization").filter(id=team_id).first()
+ if team is None or not team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL):
+ return set()
+
+ # Object rows are written against the resource itself, never its parent, so an inheriting
+ # resource is not mapped here the way a resource-scope lookup maps it.
+ satisfying = [
+ level for level in ordered_access_levels(resource) if _grants_at_least(resource, level, required_level)
+ ]
+ restricted = (
+ AccessControl.objects.filter(team_id=team_id, resource=resource, resource_id__isnull=False)
+ .exclude(access_level__in=satisfying)
+ .values_list("resource_id", flat=True)
+ )
+ return {resource_id for resource_id in restricted if resource_id}
+
+
# --- Write API ---
diff --git a/products/access_control/backend/tests/test_api.py b/products/access_control/backend/tests/test_api.py
index 864e0540e3fc..8703af27f645 100644
--- a/products/access_control/backend/tests/test_api.py
+++ b/products/access_control/backend/tests/test_api.py
@@ -8,7 +8,12 @@ from posthog.models import User
from posthog.models.organization import Organization, OrganizationMembership
from products.access_control.backend.facade import contracts
-from products.access_control.backend.facade.api import InvalidObjectAccessControlError, set_object_access_control
+from products.access_control.backend.facade.api import (
+ InvalidObjectAccessControlError,
+ every_member_has_resource_access,
+ object_ids_restricted_from_any_member,
+ set_object_access_control,
+)
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.access_control.backend.models.access_control import AccessControl
from products.access_control.backend.models.role import Role, RoleMembership
@@ -99,3 +104,125 @@ class TestSetObjectAccessControl(BaseTest):
self._grant("viewer", organization_member_id=None)
with pytest.raises(ValueError):
self._grant("viewer", role_id=role.id)
+
+
+class TestEveryMemberHasResourceAccess(BaseTest):
+ """`account` inherits from `customer_analytics`, so every rule here is written on the parent,
+ which is where resolution reads them from."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ self.agent = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ self.agent_membership = OrganizationMembership.objects.get(user=self.agent, organization=self.organization)
+
+ def _everyone_has_access(self) -> bool:
+ return every_member_has_resource_access(team_id=self.team.id, resource="account", required_level="viewer")
+
+ def _rule(self, access_level: str, subject: str | None) -> None:
+ rule: dict = {
+ "team": self.team,
+ "resource": "customer_analytics",
+ "resource_id": None,
+ "access_level": access_level,
+ }
+ if subject == "member":
+ rule["organization_member"] = self.agent_membership
+ elif subject == "role":
+ rule["role"] = Role.objects.create(organization=self.organization, name="Support")
+ AccessControl.objects.create(**rule)
+
+ @parameterized.expand(
+ [
+ ("no rules", None, None, True),
+ ("everyone denied", "none", None, False),
+ ("one member denied", "none", "member", False),
+ ("one role denied", "none", "role", False),
+ ("everyone granted viewer", "viewer", None, True),
+ ("one member granted editor", "editor", "member", True),
+ ]
+ )
+ def test_one_restricting_rule_is_enough_to_answer_no(
+ self, _name: str, access_level: str | None, subject: str | None, expected: bool
+ ) -> None:
+ if access_level is not None:
+ self._rule(access_level, subject)
+ assert self._everyone_has_access() is expected
+
+ def test_rules_are_inert_without_the_entitlement(self) -> None:
+ # Resolution hands everyone the built-in default when the organization can't use access
+ # control, so a leftover rule must not withhold data from a team that isn't restricted.
+ self._rule("none", None)
+ self.organization.available_product_features = []
+ self.organization.save()
+ assert self._everyone_has_access() is True
+
+
+class TestObjectIdsRestrictedFromAnyMember(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ self.agent = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ self.agent_membership = OrganizationMembership.objects.get(user=self.agent, organization=self.organization)
+ self.dashboard = Dashboard.objects.create(team=self.team, created_by=self.user)
+
+ def _restricted(self) -> set[str]:
+ return object_ids_restricted_from_any_member(
+ team_id=self.team.id, resource="dashboard", required_level="viewer"
+ )
+
+ def _rule(self, access_level: str, subject: str | None) -> None:
+ rule: dict = {
+ "team": self.team,
+ "resource": "dashboard",
+ "resource_id": str(self.dashboard.id),
+ "access_level": access_level,
+ }
+ if subject == "member":
+ rule["organization_member"] = self.agent_membership
+ elif subject == "role":
+ rule["role"] = Role.objects.create(organization=self.organization, name="Support")
+ AccessControl.objects.create(**rule)
+
+ @parameterized.expand(
+ [
+ ("no rules", None, None, False),
+ ("everyone denied", "none", None, True),
+ ("one member denied", "none", "member", True),
+ ("one role denied", "none", "role", True),
+ ("everyone granted viewer", "viewer", None, False),
+ ("one member granted editor", "editor", "member", False),
+ ]
+ )
+ def test_one_restricting_rule_is_enough_to_name_the_object(
+ self, _name: str, access_level: str | None, subject: str | None, expected: bool
+ ) -> None:
+ if access_level is not None:
+ self._rule(access_level, subject)
+ assert (str(self.dashboard.id) in self._restricted()) is expected
+
+ def test_names_only_the_restricted_object(self) -> None:
+ # A rule on one object must not withhold its neighbours.
+ reachable = Dashboard.objects.create(team=self.team, created_by=self.user)
+ self._rule("none", None)
+ assert self._restricted() == {str(self.dashboard.id)}
+ assert str(reachable.id) not in self._restricted()
+
+ def test_resource_scope_rules_are_not_object_rules(self) -> None:
+ # A resource-wide rule has no resource_id, so it names no object here.
+ AccessControl.objects.create(team=self.team, resource="dashboard", resource_id=None, access_level="none")
+ assert self._restricted() == set()
+
+ def test_rules_are_inert_without_the_entitlement(self) -> None:
+ self._rule("none", None)
+ self.organization.available_product_features = []
+ self.organization.save()
+ assert self._restricted() == set()
diff --git a/products/conversations/backend/ai/suggest.py b/products/conversations/backend/ai/suggest.py
index a760fd8d0191..00a2d5ca3b60 100644
--- a/products/conversations/backend/ai/suggest.py
+++ b/products/conversations/backend/ai/suggest.py
@@ -17,6 +17,8 @@ from posthog.models.comment import Comment
from posthog.models.person.util import get_persons_by_distinct_ids
from posthog.personhog_client.caller_tag import personhog_caller_tag
+from products.conversations.backend.ai.ticket_context import extra_ticket_context, format_session_context
+
if TYPE_CHECKING:
from posthog.models.team import Team
@@ -45,17 +47,7 @@ def _get_author_label(message: Comment) -> str:
def format_conversation(ticket: Ticket, messages: Iterable[Comment]) -> str:
- parts: list[str] = []
-
- current_url = None
- if ticket.session_context and isinstance(ticket.session_context, dict):
- current_url = ticket.session_context.get("current_url")
-
- if current_url:
- parts.append(f"The customer was on the page: {current_url}")
- parts.append("")
-
- parts.append("Conversation:")
+ parts: list[str] = ["Conversation:"]
truncated: list[str] = []
total_messages = 0
@@ -282,6 +274,12 @@ def _build_ticket_context(
) -> str:
"""Build the full context string that gets injected into the agent as a ContextMessage."""
conversation_text = format_conversation(ticket, messages)
+ session_text = format_session_context(ticket.session_context)
+ if session_text:
+ conversation_text = f"{session_text}\n\n{conversation_text}"
+ extra = extra_ticket_context(ticket, messages, team)
+ if extra:
+ conversation_text = f"{conversation_text}\n\n{extra}"
events: list[dict] = []
exceptions: list[dict] = []
diff --git a/products/conversations/backend/ai/test_suggest.py b/products/conversations/backend/ai/test_suggest.py
index 4316def3e9cd..8d844e70034a 100644
--- a/products/conversations/backend/ai/test_suggest.py
+++ b/products/conversations/backend/ai/test_suggest.py
@@ -1,10 +1,46 @@
-from unittest.mock import MagicMock
+from datetime import UTC, datetime, timedelta
+from uuid import uuid4
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
from parameterized import parameterized
-from products.conversations.backend.ai.suggest import _format_enhanced_context, format_conversation
+from posthog.constants import AvailableFeature
+from posthog.models.comment import Comment
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.access_control.backend.models.role import Role
+from products.conversations.backend.ai.suggest import (
+ _build_ticket_context,
+ _format_enhanced_context,
+ format_conversation,
+)
+from products.conversations.backend.ai.ticket_context import (
+ MAX_PRIOR_TICKET_REPLY_CHARS,
+ MAX_SESSION_CONTEXT_SECTION_CHARS,
+ PriorTicket,
+ format_account_properties,
+ format_prior_tickets,
+ format_session_context,
+ parse_posthog_entity_refs,
+)
+from products.conversations.backend.models import Ticket
+from products.conversations.backend.models.constants import TicketStatus
+from products.customer_analytics.backend.facade.testing import (
+ create_account,
+ create_custom_property_definition,
+ create_custom_property_value,
+)
+
+# Prior tickets are ordered by created_at, so the tests only need a stable point to count
+# back from. A real clock makes the same assertions flaky when CI runs near midnight UTC.
+_FIXED_NOW = datetime(2026, 1, 1, tzinfo=UTC)
class TestFormatEnhancedContext(SimpleTestCase):
@@ -43,3 +79,473 @@ class TestFormatConversation(SimpleTestCase):
message.item_context = item_context
message.content = "hi"
assert expected in format_conversation(ticket, [message])
+
+
+class TestFormatSessionContext(SimpleTestCase):
+ def test_renders_allowlisted_fields(self) -> None:
+ text = format_session_context(
+ {
+ "current_url": "https://app.example.com/billing",
+ "sdk_version": "1.2.3",
+ "browser": "Chrome",
+ "replay_url": "https://us.posthog.com/replay/abc",
+ "email": "[email protected]",
+ "distinct_id": "pii-distinct",
+ }
+ )
+ assert "Page: https://app.example.com/billing" in text
+ assert "SDK version: 1.2.3" in text
+ assert "Browser: Chrome" in text
+ assert "replay" not in text
+ assert "[email protected]" not in text
+ assert "pii-distinct" not in text
+
+ long_url = "https://app.example.com/" + "x" * 2000
+ capped = format_session_context({"current_url": long_url})
+ assert len(capped) <= MAX_SESSION_CONTEXT_SECTION_CHARS
+ assert "..." in capped
+
+ def test_accepts_posthog_prefixed_keys(self) -> None:
+ text = format_session_context({"$lib_version": "1.0.0", "$browser": "Firefox", "$os": "macOS"})
+ assert "SDK version: 1.0.0" in text
+ assert "Browser: Firefox" in text
+ assert "OS: macOS" in text
+
+ def test_does_not_treat_lib_name_as_sdk_version(self) -> None:
+ text = format_session_context({"$lib": "web", "$lib_version": "1.2.3"})
+ assert "SDK version: 1.2.3" in text
+ assert "web" not in text
+
+ def test_skips_non_dict(self) -> None:
+ assert format_session_context(None) == ""
+ assert format_session_context("nope") == ""
+
+
+class TestParsePosthogEntityRefs(SimpleTestCase):
+ def test_parses_urls_and_uuids(self) -> None:
+ recording = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
+ other = "11111111-2222-3333-4444-555555555555"
+ text = (
+ f"See https://us.posthog.com/project/2/feature_flags/session-replay-enabled "
+ f"and /insights/abc123XY /dashboard/42 /replay/{recording} also {other}"
+ )
+ parsed = parse_posthog_entity_refs(text)
+ assert "Feature flag: session-replay-enabled" in parsed
+ assert "Insight: abc123XY" in parsed
+ assert "Dashboard: 42" in parsed
+ assert f"Recording: {recording}" in parsed
+ assert f"UUID: {other}" in parsed
+ assert parsed.count(recording) == 1
+
+ def test_skips_new_paths_and_bare_words(self) -> None:
+ parsed = parse_posthog_entity_refs("Open /feature_flags/new and mention session-replay-enabled")
+ assert parsed == ""
+
+
+class TestFormatPriorTickets(SimpleTestCase):
+ def test_truncates_reply_and_omits_identity_fields(self) -> None:
+ reply = "x" * (MAX_PRIOR_TICKET_REPLY_CHARS + 50)
+ text = format_prior_tickets([PriorTicket(ticket_number=12, title="#12: Billing", reply=reply)])
+ assert "#12: Billing" in text
+ assert "Final reply:" in text
+ assert len(text) < MAX_PRIOR_TICKET_REPLY_CHARS + 80
+ assert "[email protected]" not in text
+ assert "distinct-secret" not in text
+
+
+class TestFormatAccountProperties(SimpleTestCase):
+ def test_renders_selected_values_and_skips_empty(self) -> None:
+ text = format_account_properties([("Plan", "Enterprise"), ("Seats", 12.0), ("Empty", None), ("Flag", True)])
+ assert "- Plan: Enterprise" in text
+ assert "- Seats: 12" in text
+ assert "- Flag: true" in text
+ assert "Empty" not in text
+
+
+class TestBuildTicketContext(BaseTest):
+ def _create_ticket(self, **kwargs) -> Ticket:
+ defaults = {
+ "team": self.team,
+ "widget_session_id": uuid4().hex,
+ "distinct_id": "person-1",
+ }
+ defaults.update(kwargs)
+ return Ticket.objects.create_with_number(**defaults)
+
+ def _comment(self, ticket: Ticket, *, content: str, author_type: str, is_private: bool = False) -> Comment:
+ return Comment.objects.create(
+ team=self.team,
+ created_by=self.user if author_type == "support" else None,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ content=content,
+ item_context={"author_type": author_type, "is_private": is_private},
+ )
+
+ def _context(self, ticket: Ticket, messages: list[Comment] | None = None, team: Team | None = None) -> str:
+ with patch("products.conversations.backend.ai.suggest._load_person_properties", return_value={}):
+ return _build_ticket_context(ticket, messages or [], team or self.team)
+
+ def test_prior_tickets_are_team_scoped_resolved_and_pii_free(self) -> None:
+ current = self._create_ticket(distinct_id="same-person", organization_id="org-1")
+ prior = self._create_ticket(
+ distinct_id="same-person",
+ organization_id="org-1",
+ status=TicketStatus.RESOLVED,
+ email_subject="Replay is blank",
+ email_from="[email protected]",
+ )
+ prior.created_at = _FIXED_NOW - timedelta(days=1)
+ prior.save(update_fields=["created_at"])
+ self._comment(prior, content="Enable session replay in project settings.", author_type="support")
+ self._comment(prior, content="Private diagnosis", author_type="support", is_private=True)
+ self._comment(prior, content="Customer said thanks", author_type="customer")
+
+ open_ticket = self._create_ticket(distinct_id="same-person", status=TicketStatus.OPEN)
+ self._comment(open_ticket, content="Not resolved yet", author_type="support")
+
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ other_ticket = self._create_ticket(
+ team=other_team,
+ distinct_id="same-person",
+ status=TicketStatus.RESOLVED,
+ )
+ Comment.objects.create(
+ team=other_team,
+ created_by=self.user,
+ scope="conversations_ticket",
+ item_id=str(other_ticket.id),
+ content="Other team answer",
+ item_context={"author_type": "support", "is_private": False},
+ )
+
+ message = self._comment(current, content="Replay is still blank", author_type="customer")
+ context = self._context(current, [message])
+
+ assert "Previous resolved tickets:" in context
+ assert "Replay is blank" in context
+ assert "Enable session replay in project settings." in context
+ assert "Private diagnosis" not in context
+ assert "Customer said thanks" not in context
+ assert "Not resolved yet" not in context
+ assert "Other team answer" not in context
+ assert "[email protected]" not in context
+ assert "same-person" not in context
+
+ def test_prior_tickets_match_organization_when_distinct_id_differs(self) -> None:
+ current = self._create_ticket(distinct_id="person-a", organization_id="acct-99", identity_verified=True)
+ prior = self._create_ticket(
+ distinct_id="person-b",
+ organization_id="acct-99",
+ status=TicketStatus.RESOLVED,
+ email_subject="SSO setup",
+ )
+ prior.created_at = _FIXED_NOW - timedelta(days=2)
+ prior.save(update_fields=["created_at"])
+ self._comment(prior, content="Use Google SSO.", author_type="support")
+ context = self._context(current)
+ assert "SSO setup" in context
+ assert "Use Google SSO." in context
+
+ @parameterized.expand(["everyone", "one member", "one role"])
+ def test_prior_tickets_skip_a_ticket_a_member_may_not_open(self, restricted_for: str) -> None:
+ # A rule on one ticket hides it from some agents, but the note quoting it is read by
+ # everyone who can open the ticket being answered. So a restricted ticket stays out.
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ current = self._create_ticket(distinct_id="same-person")
+ restricted = self._create_ticket(
+ distinct_id="same-person", status=TicketStatus.RESOLVED, email_subject="Escalation"
+ )
+ restricted.created_at = _FIXED_NOW - timedelta(days=1)
+ restricted.save(update_fields=["created_at"])
+ self._comment(restricted, content="Their restricted workaround.", author_type="support")
+ open_to_all = self._create_ticket(
+ distinct_id="same-person", status=TicketStatus.RESOLVED, email_subject="Password reset"
+ )
+ open_to_all.created_at = _FIXED_NOW - timedelta(days=2)
+ open_to_all.save(update_fields=["created_at"])
+ self._comment(open_to_all, content="Use the reset link.", author_type="support")
+
+ # Control: with no rule both prior tickets reach the context.
+ control = self._context(current)
+ assert "Escalation" in control
+ assert "Password reset" in control
+
+ rule: dict = {
+ "team": self.team,
+ "resource": "ticket",
+ "resource_id": str(restricted.id),
+ "access_level": "none",
+ }
+ if restricted_for == "one member":
+ agent = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ rule["organization_member"] = OrganizationMembership.objects.get(user=agent, organization=self.organization)
+ elif restricted_for == "one role":
+ rule["role"] = Role.objects.create(organization=self.organization, name="Support")
+ AccessControl.objects.create(**rule)
+
+ context = self._context(current)
+ assert "Escalation" not in context
+ assert "Their restricted workaround." not in context
+ # The neighbour is untouched, so the rule withheld one ticket rather than the section.
+ assert "Password reset" in context
+ assert "Use the reset link." in context
+
+ def test_keeps_last_three_resolved_tickets(self) -> None:
+ current = self._create_ticket(distinct_id="repeat")
+ for index, subject in enumerate(["Oldest", "Keep 1", "Keep 2", "Keep 3"], start=1):
+ prior = self._create_ticket(
+ distinct_id="repeat",
+ status=TicketStatus.RESOLVED,
+ email_subject=subject,
+ )
+ prior.created_at = _FIXED_NOW - timedelta(days=5 - index)
+ prior.save(update_fields=["created_at"])
+ self._comment(prior, content=f"Reply {subject}", author_type="support")
+ context = self._context(current)
+ assert "Oldest" not in context
+ assert "Keep 1" in context
+ assert "Keep 2" in context
+ assert "Keep 3" in context
+
+ def test_final_reply_ignores_team_and_ai_author_types(self) -> None:
+ current = self._create_ticket(distinct_id="same-person")
+ prior = self._create_ticket(
+ distinct_id="same-person",
+ status=TicketStatus.RESOLVED,
+ email_subject="Billing",
+ )
+ prior.created_at = _FIXED_NOW - timedelta(days=1)
+ prior.save(update_fields=["created_at"])
+ self._comment(prior, content="Team analytics type", author_type="team")
+ self._comment(prior, content="Use the billing page.", author_type="human")
+ self._comment(prior, content="AI draft", author_type="AI")
+ context = self._context(current)
+ assert "Use the billing page." in context
+ assert "Team analytics type" not in context
+ assert "AI draft" not in context
+
+ def test_skips_resolved_tickets_without_a_public_human_reply(self) -> None:
+ current = self._create_ticket(distinct_id="same-person")
+ silent = self._create_ticket(
+ distinct_id="same-person",
+ status=TicketStatus.RESOLVED,
+ email_subject="Silent",
+ )
+ silent.created_at = _FIXED_NOW - timedelta(days=1)
+ silent.save(update_fields=["created_at"])
+ self._comment(silent, content="Private only", author_type="support", is_private=True)
+ answered = self._create_ticket(
+ distinct_id="same-person",
+ status=TicketStatus.RESOLVED,
+ email_subject="Answered",
+ )
+ answered.created_at = _FIXED_NOW - timedelta(days=2)
+ answered.save(update_fields=["created_at"])
+ self._comment(answered, content="Here is the fix.", author_type="support")
+ context = self._context(current)
+ assert "Silent" not in context
+ assert "Answered" in context
+ assert "Here is the fix." in context
+
+ def test_prior_reply_stored_on_parent_team_for_child_environment(self) -> None:
+ child = Team.objects.create(
+ organization=self.organization,
+ project=self.project,
+ parent_team=self.team,
+ name="Child environment",
+ )
+ current = self._create_ticket(team=child, distinct_id="same-person")
+ prior = self._create_ticket(
+ team=child,
+ distinct_id="same-person",
+ status=TicketStatus.RESOLVED,
+ email_subject="SSO setup",
+ )
+ prior.created_at = _FIXED_NOW - timedelta(days=1)
+ prior.save(update_fields=["created_at"])
+ comment = Comment.objects.create(
+ team=child,
+ created_by=self.user,
+ scope="conversations_ticket",
+ item_id=str(prior.id),
+ content="Use Google SSO.",
+ item_context={"author_type": "support", "is_private": False},
+ )
+ context = self._context(current, team=child)
+ assert comment.team_id == self.team.id
+ assert "SSO setup" in context
+ assert "Use Google SSO." in context
+
+ def test_last_message_text_is_not_used_as_prior_title(self) -> None:
+ current = self._create_ticket(distinct_id="same-person")
+ prior = self._create_ticket(
+ distinct_id="same-person",
+ status=TicketStatus.RESOLVED,
+ last_message_text="email me at [email protected]",
+ )
+ prior.created_at = _FIXED_NOW - timedelta(days=1)
+ prior.save(update_fields=["created_at"])
+ self._comment(prior, content="Reset the API key.", author_type="support")
+ prior.last_message_text = "email me at [email protected]"
+ prior.save(update_fields=["last_message_text"])
+ context = self._context(current)
+ assert "[email protected]" not in context
+ assert "Reset the API key." in context
+
+ def test_unattested_organization_never_keys_another_accounts_context(self) -> None:
+ # organization_id resolves from client-supplied person properties, so a widget visitor can
+ # claim any organization group key in the project. Without identity verification or a
+ # team-mapped Slack channel, that claim must not reach another account's content.
+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan", target_type="account")
+ account = create_account(team_id=self.team.id, name="Acme", external_id="acct-1")
+ create_custom_property_value(team_id=self.team.id, account=account, definition=plan, value_str="Enterprise")
+ self.team.conversations_settings = {"ai_context_account_property_ids": [str(plan.id)]}
+ self.team.save(update_fields=["conversations_settings"])
+
+ victim = self._create_ticket(
+ distinct_id="victim",
+ organization_id="acct-1",
+ status=TicketStatus.RESOLVED,
+ email_subject="Their SSO setup",
+ )
+ victim.created_at = _FIXED_NOW - timedelta(days=1)
+ victim.save(update_fields=["created_at"])
+ self._comment(victim, content="Their private workaround.", author_type="support")
+
+ spoofed = self._create_ticket(distinct_id="attacker", organization_id="acct-1")
+ context = self._context(spoofed)
+ assert "Their SSO setup" not in context
+ assert "Their private workaround." not in context
+ assert "Account properties:" not in context
+
+ spoofed.identity_verified = True
+ spoofed.save(update_fields=["identity_verified"])
+ attested = self._context(spoofed)
+ assert "Their SSO setup" in attested
+ assert "- Plan: Enterprise" in attested
+
+ def test_entity_refs_only_in_posthog_docs_mode(self) -> None:
+ ticket = self._create_ticket()
+ message = self._comment(
+ ticket,
+ content="Broken flag https://us.posthog.com/project/2/feature_flags/my-flag",
+ author_type="customer",
+ )
+ generic = self._context(ticket, [message])
+ assert "Referenced PostHog entities:" not in generic
+
+ self.team.conversations_settings = {"docs_source": "posthog"}
+ self.team.save(update_fields=["conversations_settings"])
+ posthog = self._context(ticket, [message])
+ assert "Feature flag: my-flag" in posthog
+
+ def test_session_context_is_rendered(self) -> None:
+ ticket = self._create_ticket(
+ session_context={"current_url": "https://app.example.com/x", "sdk_version": "9.9.9", "browser": "Safari"}
+ )
+ context = self._context(ticket)
+ assert "Page: https://app.example.com/x" in context
+ assert "SDK version: 9.9.9" in context
+ assert "Browser: Safari" in context
+
+ def test_account_properties_only_selected_and_skip_missing(self) -> None:
+ account = create_account(team_id=self.team.id, name="Acme", external_id="acct-1")
+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan", target_type="account")
+ seats = create_custom_property_definition(team_id=self.team.id, name="Seats", target_type="account")
+ deleted = create_custom_property_definition(team_id=self.team.id, name="Deleted", target_type="account")
+ create_custom_property_value(team_id=self.team.id, account=account, definition=plan, value_str="Enterprise")
+ create_custom_property_value(team_id=self.team.id, account=account, definition=seats, value_str="50")
+ deleted.delete()
+
+ self.team.conversations_settings = {
+ "ai_context_account_property_ids": [str(plan.id), str(deleted.id), str(uuid4())]
+ }
+ self.team.save(update_fields=["conversations_settings"])
+ ticket = self._create_ticket(organization_id="acct-1", identity_verified=True)
+ context = self._context(ticket)
+ assert "- Plan: Enterprise" in context
+ assert "Seats" not in context
+ assert "Deleted" not in context
+
+ @parameterized.expand(["everyone", "one member", "one role"])
+ def test_account_properties_need_account_access_for_every_member(self, restricted: str) -> None:
+ # The section goes into a note that every agent with ticket access reads, and the reply run
+ # can't tell them apart. So a member the team kept out of Customer analytics must not be
+ # handed account data here, however the team wrote that restriction.
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ account = create_account(team_id=self.team.id, name="Acme", external_id="acct-1")
+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan", target_type="account")
+ create_custom_property_value(team_id=self.team.id, account=account, definition=plan, value_str="Enterprise")
+ self.team.conversations_settings = {"ai_context_account_property_ids": [str(plan.id)]}
+ self.team.save(update_fields=["conversations_settings"])
+ ticket = self._create_ticket(organization_id="acct-1", identity_verified=True)
+
+ # Control: with no rule the team default gives every member account access.
+ assert "- Plan: Enterprise" in self._context(ticket)
+
+ rule: dict = {
+ "team": self.team,
+ "resource": "customer_analytics",
+ "resource_id": None,
+ "access_level": "none",
+ }
+ if restricted == "one member":
+ agent = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ rule["organization_member"] = OrganizationMembership.objects.get(user=agent, organization=self.organization)
+ elif restricted == "one role":
+ rule["role"] = Role.objects.create(organization=self.organization, name="Support")
+ AccessControl.objects.create(**rule)
+
+ withheld = self._context(ticket)
+ assert "Account properties:" not in withheld
+ assert "Enterprise" not in withheld
+
+ def test_account_properties_skip_an_account_a_member_may_not_open(self) -> None:
+ # A rule on one account is the object-level twin of the resource-level case above: the
+ # team kept this account from someone, so its properties stay out of a note they read.
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ account = create_account(team_id=self.team.id, name="Acme", external_id="acct-1")
+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan", target_type="account")
+ create_custom_property_value(team_id=self.team.id, account=account, definition=plan, value_str="Enterprise")
+ self.team.conversations_settings = {"ai_context_account_property_ids": [str(plan.id)]}
+ self.team.save(update_fields=["conversations_settings"])
+ ticket = self._create_ticket(organization_id="acct-1", identity_verified=True)
+
+ # Control: the resource is open to everyone, so the section renders.
+ assert "- Plan: Enterprise" in self._context(ticket)
+
+ AccessControl.objects.create(
+ team=self.team,
+ resource="account",
+ resource_id=str(account.id),
+ access_level="none",
+ )
+ restricted = self._context(ticket)
+ assert "Account properties:" not in restricted
+ assert "Enterprise" not in restricted
+
+ def test_skips_account_section_when_account_missing_or_ca_errors(self) -> None:
+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan", target_type="account")
+ self.team.conversations_settings = {"ai_context_account_property_ids": [str(plan.id)]}
+ self.team.save(update_fields=["conversations_settings"])
+ ticket = self._create_ticket(organization_id="missing-acct", identity_verified=True)
+ context = self._context(ticket)
+ assert "Account properties:" not in context
+
+ ticket.organization_id = "acct-err"
+ ticket.save(update_fields=["organization_id"])
+ with patch("products.conversations.backend.ai.ticket_context.get_account", side_effect=RuntimeError("down")):
+ failed = self._context(ticket)
+ assert "Account properties:" not in failed
diff --git a/products/conversations/backend/ai/ticket_context.py b/products/conversations/backend/ai/ticket_context.py
new file mode 100644
index 000000000000..940280853951
--- /dev/null
+++ b/products/conversations/backend/ai/ticket_context.py
@@ -0,0 +1,411 @@
+"""Bounded, PII-allowlisted extras for support AI ticket context."""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable
+from datetime import datetime
+from typing import TYPE_CHECKING
+from urllib.parse import unquote
+from uuid import UUID
+
+from django.db.models import CharField, Exists, OuterRef, Q
+from django.db.models.functions import Cast
+
+from posthog.dataclasses import frozen
+from posthog.exceptions_capture import capture_exception
+from posthog.models.comment import Comment
+from posthog.models.organization import OrganizationMembership
+
+from products.access_control.backend.facade.api import (
+ every_member_has_resource_access,
+ object_ids_restricted_from_any_member,
+)
+from products.access_control.backend.facade.subject_access_control import SubjectAccessControl
+from products.conversations.backend.models import Ticket
+from products.conversations.backend.models.constants import OrganizationIdSource, TicketStatus
+from products.conversations.backend.playbook import is_posthog_docs_source
+from products.conversations.backend.services.messages import public_human_ticket_replies
+from products.customer_analytics.backend.facade.api import (
+ get_account,
+ get_custom_property_definition,
+ list_active_custom_property_values,
+)
+
+if TYPE_CHECKING:
+ from posthog.models.team import Team
+
+MAX_PRIOR_TICKETS = 3
+MAX_PRIOR_TICKET_REPLY_CHARS = 600
+MAX_PRIOR_TICKET_TITLE_CHARS = 120
+MAX_PRIOR_TICKETS_SECTION_CHARS = 2400
+MAX_SESSION_CONTEXT_SECTION_CHARS = 800
+MAX_ENTITY_REFS_SECTION_CHARS = 1200
+MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS = 10
+MAX_ACCOUNT_PROPERTY_VALUE_CHARS = 200
+MAX_ACCOUNT_SECTION_CHARS = 1500
+
+ACCOUNT_TARGET_TYPE = "account"
+
+_SESSION_CONTEXT_FIELDS: tuple[tuple[tuple[str, ...], str], ...] = (
+ (("current_url", "url", "$current_url"), "Page"),
+ (("sdk_version", "lib_version", "$lib_version"), "SDK version"),
+ (("browser", "$browser"), "Browser"),
+ (("browser_version", "$browser_version"), "Browser version"),
+ (("os", "$os"), "OS"),
+)
+
+_FEATURE_FLAG_PATH = re.compile(r"/feature_flags/([^/?#\s]+)", re.IGNORECASE)
+_INSIGHT_PATH = re.compile(r"/insights/([^/?#\s]+)", re.IGNORECASE)
+_RECORDING_PATH = re.compile(
+ r"/(?:replay|session-recordings|recordings)/([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})",
+ re.IGNORECASE,
+)
+_DASHBOARD_PATH = re.compile(r"/dashboard(?:s)?/([^/?#\s]+)", re.IGNORECASE)
+_UUID_RE = re.compile(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b")
+_SKIP_PATH_SEGMENTS = frozenset({"new", "edit", "history", "settings"})
+_ENTITY_KIND_LABELS = {
+ "feature_flag": "Feature flag",
+ "insight": "Insight",
+ "recording": "Recording",
+ "dashboard": "Dashboard",
+ "uuid": "UUID",
+}
+
+
+@frozen
+class PriorTicket:
+ ticket_number: int
+ title: str
+ reply: str
+
+
+def _truncate(text: str, max_chars: int) -> str:
+ if len(text) <= max_chars:
+ return text
+ if max_chars <= 3:
+ return text[:max_chars]
+ return text[: max_chars - 3] + "..."
+
+
+def _capped_section(header: str, lines: list[str], max_chars: int) -> str:
+ text = header + "\n" + "\n".join(lines) if lines else header
+ return _truncate(text, max_chars)
+
+
+def _scalar_text(value: object) -> str | None:
+ if isinstance(value, bool):
+ return "true" if value else "false"
+ if isinstance(value, int | float | str):
+ text = str(value).strip()
+ return text or None
+ return None
+
+
+def format_session_context(session_context: object) -> str:
+ if not isinstance(session_context, dict):
+ return ""
+ lines: list[str] = []
+ for keys, label in _SESSION_CONTEXT_FIELDS:
+ rendered: str | None = None
+ for key in keys:
+ rendered = _scalar_text(session_context.get(key))
+ if rendered is not None:
+ break
+ if rendered is None:
+ continue
+ lines.append(f"- {label}: {_truncate(rendered, 500)}")
+ if not lines:
+ return ""
+ return _capped_section("Session:", lines, MAX_SESSION_CONTEXT_SECTION_CHARS)
+
+
+def parse_posthog_entity_refs(text: str) -> str:
+ if not text.strip():
+ return ""
+
+ found: list[tuple[str, str]] = []
+ seen: set[tuple[str, str]] = set()
+ recording_ids: set[str] = set()
+
+ def add(kind: str, raw: str) -> None:
+ value = unquote(raw).strip().rstrip("/")
+ if not value or value.lower() in _SKIP_PATH_SEGMENTS:
+ return
+ key = (kind, value)
+ if key in seen:
+ return
+ seen.add(key)
+ found.append(key)
+
+ for match in _FEATURE_FLAG_PATH.finditer(text):
+ add("feature_flag", match.group(1))
+ for match in _INSIGHT_PATH.finditer(text):
+ add("insight", match.group(1))
+ for match in _RECORDING_PATH.finditer(text):
+ add("recording", match.group(1))
+ recording_ids.add(match.group(1).lower())
+ for match in _DASHBOARD_PATH.finditer(text):
+ add("dashboard", match.group(1))
+ for match in _UUID_RE.finditer(text):
+ value = match.group(0)
+ if value.lower() in recording_ids:
+ continue
+ add("uuid", value)
+
+ if not found:
+ return ""
+ lines = [f"- {_ENTITY_KIND_LABELS[kind]}: {value}" for kind, value in found]
+ return _capped_section("Referenced PostHog entities:", lines, MAX_ENTITY_REFS_SECTION_CHARS)
+
+
+def format_prior_tickets(tickets: Iterable[PriorTicket]) -> str:
+ lines: list[str] = []
+ for ticket in tickets:
+ lines.append(f"- {ticket.title}")
+ if ticket.reply:
+ lines.append(f" Final reply: {_truncate(ticket.reply, MAX_PRIOR_TICKET_REPLY_CHARS)}")
+ if not lines:
+ return ""
+ return _capped_section("Previous resolved tickets:", lines, MAX_PRIOR_TICKETS_SECTION_CHARS)
+
+
+def _prior_ticket_title(ticket: Ticket) -> str:
+ # email_subject is the ticket title. last_message_text is often the customer's
+ # last message and can carry email addresses, so it stays out of this section.
+ subject = (ticket.email_subject or "").strip()
+ if subject:
+ return f"#{ticket.ticket_number}: {_truncate(subject, MAX_PRIOR_TICKET_TITLE_CHARS)}"
+ return f"#{ticket.ticket_number}"
+
+
+def _comment_team_ids(team: Team) -> set[int]:
+ # Comments are RootTeamMixin, so save() stores them on the parent. Tickets stay on the environment.
+ team_ids = {team.id}
+ if team.parent_team_id:
+ team_ids.add(team.parent_team_id)
+ return team_ids
+
+
+def _load_last_public_human_replies(team: Team, ticket_ids: list[str]) -> dict[str, str]:
+ if not ticket_ids:
+ return {}
+ comments = (
+ public_human_ticket_replies(_comment_team_ids(team), ticket_ids)
+ .order_by("item_id", "-created_at", "-id")
+ .distinct("item_id")
+ .only("item_id", "content")
+ )
+ latest: dict[str, str] = {}
+ for comment in comments:
+ content = (comment.content or "").strip()
+ if content and comment.item_id:
+ latest[comment.item_id] = content
+ return latest
+
+
+def org_identity_is_attested(ticket: Ticket) -> bool:
+ """Whether ``organization_id`` may key another account's content into this reply.
+
+ ``organization_id`` is enrichment. It resolves from person properties and event ``$groups``,
+ both client-supplied, so a widget visitor can claim any organization group key that already
+ exists in the project. Naming the wrong account on an event is a mis-attribution; putting that
+ account's prior replies and account properties in front of the reply model is a disclosure. Two
+ sources clear that bar: an account the team itself mapped to a Slack channel, and a requester
+ the host application vouched for through identity verification.
+ """
+ if ticket.organization_id_source == OrganizationIdSource.SLACK_CHANNEL_ACCOUNT:
+ return True
+ return ticket.identity_verified is True
+
+
+def _restricted_prior_ticket_ids(team_id: int) -> list[UUID]:
+ """Tickets that a rule keeps from some member of the team.
+
+ Only object-level rules matter here. A resource-level one holds the reader back from the
+ ticket being answered too, so it already bounds who reads the note; a rule on one ticket
+ does not, and that is the ticket whose title and reply would otherwise leak into a note
+ its reader was not allowed to open.
+ """
+ ids: list[UUID] = []
+ for value in object_ids_restricted_from_any_member(team_id=team_id, resource="ticket", required_level="viewer"):
+ try:
+ ids.append(UUID(value))
+ except ValueError:
+ # resource_id is free-form, and a value that is not a ticket id matches no ticket.
+ continue
+ return ids
+
+
+def load_prior_tickets(ticket: Ticket) -> list[PriorTicket]:
+ identity = Q()
+ if ticket.distinct_id:
+ identity |= Q(distinct_id=ticket.distinct_id)
+ if ticket.organization_id and org_identity_is_attested(ticket):
+ identity |= Q(organization_id=ticket.organization_id)
+ if not identity:
+ return []
+
+ team = ticket.team
+ has_public_human_reply = public_human_ticket_replies(_comment_team_ids(team)).filter(
+ item_id=Cast(OuterRef("id"), output_field=CharField()),
+ )
+ rows = list(
+ Ticket.objects.filter(team_id=ticket.team_id, status=TicketStatus.RESOLVED)
+ .filter(identity)
+ .exclude(pk=ticket.pk)
+ # Before the limit, so a ticket nobody may read does not take one of the few slots.
+ .exclude(pk__in=_restricted_prior_ticket_ids(ticket.team_id))
+ .filter(Exists(has_public_human_reply))
+ .order_by("-created_at")[:MAX_PRIOR_TICKETS]
+ )
+ replies = _load_last_public_human_replies(team, [str(row.id) for row in rows])
+ prior: list[PriorTicket] = []
+ for row in rows:
+ reply = replies.get(str(row.id))
+ if not reply:
+ continue
+ prior.append(
+ PriorTicket(
+ ticket_number=row.ticket_number,
+ title=_prior_ticket_title(row),
+ reply=reply,
+ )
+ )
+ return prior
+
+
+def parse_account_property_ids(raw: object) -> list[str]:
+ """Keep well-formed UUID strings, ordered, unique, capped. Invalid items are skipped."""
+ if not isinstance(raw, list):
+ return []
+ ids: list[str] = []
+ seen: set[str] = set()
+ for item in raw:
+ if not isinstance(item, str):
+ continue
+ try:
+ parsed = str(UUID(item))
+ except ValueError:
+ continue
+ if parsed in seen:
+ continue
+ seen.add(parsed)
+ ids.append(parsed)
+ if len(ids) >= MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS:
+ break
+ return ids
+
+
+def selected_account_property_ids(team: Team) -> list[str]:
+ settings = team.conversations_settings or {}
+ return parse_account_property_ids(settings.get("ai_context_account_property_ids"))
+
+
+def format_account_property_value(value: object) -> str | None:
+ if value is None:
+ return None
+ if isinstance(value, bool):
+ return "true" if value else "false"
+ if isinstance(value, datetime):
+ return value.isoformat()
+ if isinstance(value, float) and value.is_integer():
+ return str(int(value))
+ text = str(value).strip()
+ if not text:
+ return None
+ return _truncate(text, MAX_ACCOUNT_PROPERTY_VALUE_CHARS)
+
+
+def format_account_properties(pairs: Iterable[tuple[str, object]]) -> str:
+ lines: list[str] = []
+ for name, value in pairs:
+ rendered = format_account_property_value(value)
+ if rendered is None:
+ continue
+ lines.append(f"- {name}: {rendered}")
+ if len(lines) >= MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS:
+ break
+ if not lines:
+ return ""
+ return _capped_section("Account properties:", lines, MAX_ACCOUNT_SECTION_CHARS)
+
+
+def _default_subject_access_control(team: Team) -> SubjectAccessControl | None:
+ """The access the team's default rules give every member, with no member or role of their own.
+
+ Reading a definition name needs somebody to read as, and the reply run has no request user.
+ A subject with no member and no role resolves default rules only, and it drops the org-admin
+ bypass, so the answer no longer changes with which membership row the database returns first.
+
+ Definition names still resolve under it, because names are not object-scoped. Only workflow
+ references are, and this path does not read them.
+ """
+ membership = (
+ OrganizationMembership.objects.filter(organization_id=team.organization_id, user__is_active=True)
+ .select_related("user")
+ .first()
+ )
+ if membership is None:
+ return None
+ return SubjectAccessControl(membership.user, team=team, org_membership=membership)
+
+
+def load_account_context(team: Team, organization_id: str | None) -> str:
+ selected = selected_account_property_ids(team)
+ if not selected or not organization_id:
+ return ""
+ try:
+ # The account and value reads below are team-scoped only, and what they render goes into a
+ # note that every agent who can open the ticket reads. There is no one reader to authorize
+ # here, so the section needs the whole team to hold account access. A team that limited
+ # Customer analytics to some of its members keeps that limit instead of losing it here.
+ if not every_member_has_resource_access(team_id=team.id, resource="account", required_level="viewer"):
+ return ""
+ uac = _default_subject_access_control(team)
+ if uac is None:
+ return ""
+ account = get_account(team.id, external_id=organization_id)
+ if account is None:
+ return ""
+ # The same question one object down. The check above asks whether the team withheld
+ # Customer analytics from anybody; this one asks whether it withheld this account.
+ if str(account.id) in object_ids_restricted_from_any_member(
+ team_id=team.id, resource="account", required_level="viewer"
+ ):
+ return ""
+ values = list_active_custom_property_values(team.id, account.id)
+ value_by_definition = {str(row.definition_id): row.value for row in values}
+ pairs: list[tuple[str, object]] = []
+ for definition_id in selected:
+ if definition_id not in value_by_definition:
+ continue
+ view = get_custom_property_definition(team.id, definition_id, user_access_control=uac)
+ if view is None or view.target_type != ACCOUNT_TARGET_TYPE or not view.name:
+ continue
+ pairs.append((view.name, value_by_definition[definition_id]))
+ return format_account_properties(pairs)
+ except Exception:
+ capture_exception()
+ return ""
+
+
+def extra_ticket_context(ticket: Ticket, messages: list[Comment], team: Team) -> str:
+ parts: list[str] = []
+ prior = format_prior_tickets(load_prior_tickets(ticket))
+ if prior:
+ parts.append(prior)
+
+ settings = team.conversations_settings or {}
+ raw_docs = settings.get("docs_source") if isinstance(settings, dict) else None
+ docs_source = raw_docs if isinstance(raw_docs, str) else None
+ if is_posthog_docs_source(docs_source):
+ chunks = [ticket.email_subject or "", *[message.content or "" for message in messages]]
+ entities = parse_posthog_entity_refs("\n".join(chunks))
+ if entities:
+ parts.append(entities)
+
+ account = load_account_context(team, ticket.organization_id if org_identity_is_attested(ticket) else None)
+ if account:
+ parts.append(account)
+ return "\n\n".join(parts)
diff --git a/products/conversations/backend/api/__init__.py b/products/conversations/backend/api/__init__.py
index 68995f14a75c..c807541e625a 100644
--- a/products/conversations/backend/api/__init__.py
+++ b/products/conversations/backend/api/__init__.py
@@ -1,3 +1,4 @@
+from .ai_context import AIContextAccountPropertiesViewSet
from .ai_reply_playbook import AIReplyPlaybookViewSet
from .ticket_views import TicketViewViewSet
from .tickets import TicketViewSet
@@ -5,6 +6,7 @@ from .widget import WidgetMessagesView, WidgetMessageView, WidgetTicketsView
from .zendesk_import import ZendeskImportViewSet
__all__ = [
+ "AIContextAccountPropertiesViewSet",
"AIReplyPlaybookViewSet",
"TicketViewSet",
"TicketViewViewSet",
diff --git a/products/conversations/backend/api/ai_context.py b/products/conversations/backend/api/ai_context.py
new file mode 100644
index 000000000000..df96ff93cc57
--- /dev/null
+++ b/products/conversations/backend/api/ai_context.py
@@ -0,0 +1,115 @@
+from __future__ import annotations
+
+from typing import Any
+from uuid import UUID
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import serializers, viewsets
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.permissions import TeamMemberLightManagementPermission
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin
+from products.conversations.backend.ai.ticket_context import ACCOUNT_TARGET_TYPE, MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS
+from products.customer_analytics.backend.facade.api import (
+ get_custom_property_definition_target_type,
+ list_custom_property_definitions,
+)
+
+# One bounded read, not a paging loop: each facade call repeats the count, the workflow
+# reference scan and the source enrichment, so paging a large team costs several full scans
+# for a picker that only ever shows a short list.
+MAX_ACCOUNT_PROPERTY_OPTIONS = 500
+
+
+class AIContextAccountPropertySerializer(serializers.Serializer):
+ id = serializers.UUIDField(help_text="Customer analytics account property definition id.")
+ name = serializers.CharField(help_text="Display name of the account property.")
+
+
+def list_account_property_options(team_id: int, user_access_control: UserAccessControl) -> list[dict[str, object]]:
+ page, _ = list_custom_property_definitions(
+ team_id,
+ offset=0,
+ limit=MAX_ACCOUNT_PROPERTY_OPTIONS,
+ user_access_control=user_access_control,
+ exclude_group_targets=True,
+ target_type=ACCOUNT_TARGET_TYPE,
+ )
+ return [{"id": item.id, "name": item.name} for item in page if item.id is not None and item.name]
+
+
+class AIContextAccountPropertiesViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.GenericViewSet):
+ # Same authorization as the Customer analytics definition list this reads from: the names
+ # and ids are account data, so project membership alone is not enough.
+ scope_object = "account"
+ permission_classes = [TeamMemberLightManagementPermission]
+ pagination_class = None
+ serializer_class = AIContextAccountPropertySerializer
+
+ @extend_schema(
+ responses=AIContextAccountPropertySerializer(many=True),
+ description=(
+ "Account-target Customer analytics properties that can be included in AI reply context. "
+ f"Capped at the first {MAX_ACCOUNT_PROPERTY_OPTIONS} properties by name."
+ ),
+ )
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ serializer = self.get_serializer(
+ list_account_property_options(self.team.id, self.user_access_control),
+ many=True,
+ )
+ return Response(serializer.data)
+
+
+def validate_ai_context_conversations_settings(value: dict, *, team_id: int | None) -> dict:
+ """Normalize ai_context_account_property_ids. Raises DRF ValidationError.
+
+ ``team_id`` is ``None`` while a team is being created. The shape checks still run, but a team
+ that does not exist yet owns no property definition, so every id is dropped."""
+ if "ai_context_account_property_ids" not in value:
+ return value
+ raw = value.get("ai_context_account_property_ids")
+ if raw is None:
+ value["ai_context_account_property_ids"] = []
+ return value
+ if not isinstance(raw, list):
+ raise serializers.ValidationError({"ai_context_account_property_ids": "Must be a list of property ids."})
+
+ ids: list[str] = []
+ seen: set[str] = set()
+ for item in raw:
+ if not isinstance(item, str):
+ raise serializers.ValidationError(
+ {"ai_context_account_property_ids": "Each property id must be a UUID string."}
+ )
+ try:
+ parsed = str(UUID(item))
+ except ValueError as exc:
+ raise serializers.ValidationError(
+ {"ai_context_account_property_ids": "Each property id must be a UUID string."}
+ ) from exc
+ if parsed in seen:
+ continue
+ seen.add(parsed)
+ ids.append(parsed)
+ if len(ids) >= MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS:
+ break
+
+ if not ids or team_id is None:
+ value["ai_context_account_property_ids"] = []
+ return value
+
+ try:
+ kept = [
+ item for item in ids if get_custom_property_definition_target_type(team_id, item) == ACCOUNT_TARGET_TYPE
+ ]
+ except Exception as exc:
+ raise serializers.ValidationError(
+ {"ai_context_account_property_ids": "Couldn't validate account properties."}
+ ) from exc
+ value["ai_context_account_property_ids"] = kept
+ return value
diff --git a/products/conversations/backend/api/tests/test_ai_context.py b/products/conversations/backend/api/tests/test_ai_context.py
new file mode 100644
index 000000000000..f6bf7042890a
--- /dev/null
+++ b/products/conversations/backend/api/tests/test_ai_context.py
@@ -0,0 +1,90 @@
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from rest_framework import serializers, status
+
+from posthog.models.team.team import Team
+
+from products.conversations.backend.ai.ticket_context import MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS
+from products.conversations.backend.api.ai_context import validate_ai_context_conversations_settings
+from products.customer_analytics.backend.facade.testing import create_custom_property_definition
+
+
+class TestValidateAiContextConversationsSettings(SimpleTestCase):
+ def test_null_becomes_empty_list(self) -> None:
+ value = validate_ai_context_conversations_settings({"ai_context_account_property_ids": None}, team_id=1)
+ assert value["ai_context_account_property_ids"] == []
+
+ def test_rejects_non_list_and_non_uuid(self) -> None:
+ with self.assertRaises(serializers.ValidationError):
+ validate_ai_context_conversations_settings({"ai_context_account_property_ids": "nope"}, team_id=1)
+ with self.assertRaises(serializers.ValidationError):
+ validate_ai_context_conversations_settings({"ai_context_account_property_ids": ["not-a-uuid"]}, team_id=1)
+
+ def test_keeps_account_defs_in_order_and_caps(self) -> None:
+ ids = [uuid4() for _ in range(MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS + 2)]
+ with patch(
+ "products.conversations.backend.api.ai_context.get_custom_property_definition_target_type",
+ return_value="account",
+ ) as mocked:
+ value = validate_ai_context_conversations_settings(
+ {"ai_context_account_property_ids": [str(item) for item in ids]}, team_id=9
+ )
+ assert mocked.call_count == MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS
+ assert [call.args[1] for call in mocked.call_args_list] == [
+ str(item) for item in ids[:MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS]
+ ]
+ assert value["ai_context_account_property_ids"] == [
+ str(item) for item in ids[:MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS]
+ ]
+
+ def test_creation_drops_every_id(self) -> None:
+ # No team exists yet on create, so nothing can own a definition.
+ value = validate_ai_context_conversations_settings(
+ {"ai_context_account_property_ids": [str(uuid4())]}, team_id=None
+ )
+ assert value["ai_context_account_property_ids"] == []
+
+ def test_creation_still_rejects_malformed_ids(self) -> None:
+ # Dropping every id on create must not short-circuit the shape checks.
+ with self.assertRaises(serializers.ValidationError):
+ validate_ai_context_conversations_settings({"ai_context_account_property_ids": ["nope"]}, team_id=None)
+
+ def test_drops_missing_and_non_account_defs(self) -> None:
+ keep = uuid4()
+ skip = uuid4()
+
+ def target_type(_team_id: int, definition_id: str) -> str | None:
+ if definition_id == str(keep):
+ return "account"
+ if definition_id == str(skip):
+ return "person"
+ return None
+
+ with patch(
+ "products.conversations.backend.api.ai_context.get_custom_property_definition_target_type",
+ side_effect=target_type,
+ ):
+ value = validate_ai_context_conversations_settings(
+ {"ai_context_account_property_ids": [str(keep), str(skip)]},
+ team_id=1,
+ )
+ assert value["ai_context_account_property_ids"] == [str(keep)]
+
+
+class TestAIContextAccountPropertiesAPI(APIBaseTest):
+ def test_lists_account_properties_for_this_team_only(self) -> None:
+ mine = create_custom_property_definition(team_id=self.team.id, name="Plan", target_type="account")
+ create_custom_property_definition(team_id=self.team.id, name="Role", target_type="person")
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ create_custom_property_definition(team_id=other_team.id, name="Other plan", target_type="account")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/conversations/ai_context_account_properties/")
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert [row["name"] for row in body] == ["Plan"]
+ assert body[0]["id"] == str(mine.id)
diff --git a/products/conversations/backend/routes.py b/products/conversations/backend/routes.py
index 01c6b7947937..39412c91fb88 100644
--- a/products/conversations/backend/routes.py
+++ b/products/conversations/backend/routes.py
@@ -1,6 +1,7 @@
from posthog.api.routing import RouterRegistry
from products.conversations.backend.api import (
+ AIContextAccountPropertiesViewSet,
AIReplyPlaybookViewSet,
TicketViewSet,
TicketViewViewSet,
@@ -34,3 +35,9 @@ def register_routes(routers: RouterRegistry) -> None:
"project_conversations_ai_reply_playbook",
["team_id"],
)
+ routers.projects.register(
+ r"conversations/ai_context_account_properties",
+ AIContextAccountPropertiesViewSet,
+ "project_conversations_ai_context_account_properties",
+ ["team_id"],
+ )
diff --git a/products/conversations/frontend/components/AIContextAccountPropertiesSection/AIContextAccountPropertiesSection.tsx b/products/conversations/frontend/components/AIContextAccountPropertiesSection/AIContextAccountPropertiesSection.tsx
new file mode 100644
index 000000000000..5bd91708602a
--- /dev/null
+++ b/products/conversations/frontend/components/AIContextAccountPropertiesSection/AIContextAccountPropertiesSection.tsx
@@ -0,0 +1,51 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonCard } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { SceneSection } from '~/layout/scenes/components/SceneSection'
+
+import { MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS, supportSettingsLogic } from '../../scenes/settings/supportSettingsLogic'
+
+export function AIContextAccountPropertiesSection(): JSX.Element | null {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const {
+ accountPropertyOptions,
+ accountPropertyOptionsLoading,
+ aiContextAccountPropertyIds,
+ aiContextAccountPropertiesSaving,
+ } = useValues(supportSettingsLogic)
+ const { setAiContextAccountPropertyIds } = useActions(supportSettingsLogic)
+
+ if (!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS]) {
+ return null
+ }
+
+ return (
+ <SceneSection
+ title="Account properties in AI context"
+ titleSize="sm"
+ className="my-8"
+ description="The AI includes these Customer analytics account properties when it drafts a reply."
+ >
+ <LemonCard hoverEffect={false} className="flex flex-col gap-y-2 max-w-[800px] px-4 py-3">
+ <LemonInputSelect
+ mode="multiple"
+ value={aiContextAccountPropertyIds}
+ onChange={setAiContextAccountPropertyIds}
+ options={accountPropertyOptions.map((option) => ({ key: option.id, label: option.name }))}
+ loading={accountPropertyOptionsLoading}
+ placeholder={`Select up to ${MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS} properties`}
+ limit={MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS}
+ disabledReason={aiContextAccountPropertiesSaving ? 'Saving selected properties' : undefined}
+ emptyStateComponent={<span>No account properties yet. Add them in Customer analytics first.</span>}
+ fullWidth
+ data-attr="ai-context-account-properties"
+ />
+ </LemonCard>
+ </SceneSection>
+ )
+}
diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.ts
index 3d3dcee30ab5..d456111b0530 100644
--- a/products/conversations/frontend/generated/api.schemas.ts
+++ b/products/conversations/frontend/generated/api.schemas.ts
@@ -7,6 +7,13 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+export interface AIContextAccountPropertyApi {
+ /** Customer analytics account property definition id. */
+ id: string
+ /** Display name of the account property. */
+ name: string
+}
+
export interface AIReplyPlaybookApi {
/** Repo default instructions, plus the PostHog overlay when docs_source is posthog. */
readonly inherited_instructions: string
diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.ts
index c007405abb17..a0366fc3f899 100644
--- a/products/conversations/frontend/generated/api.ts
+++ b/products/conversations/frontend/generated/api.ts
@@ -9,6 +9,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ AIContextAccountPropertyApi,
AIReplyPlaybookApi,
AiFeedbackRequestApi,
BulkUpdateStatusRequestApi,
@@ -53,6 +54,23 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getConversationsAiContextAccountPropertiesListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/conversations/ai_context_account_properties/`
+}
+
+/**
+ * Account-target Customer analytics properties that can be included in AI reply context. Capped at the first 500 properties by name.
+ */
+export const conversationsAiContextAccountPropertiesList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<AIContextAccountPropertyApi[]> => {
+ return apiMutator<AIContextAccountPropertyApi[]>(getConversationsAiContextAccountPropertiesListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getConversationsAiReplyPlaybookRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/conversations/ai_reply_playbook/`
}
diff --git a/products/conversations/frontend/scenes/settings/AISection.tsx b/products/conversations/frontend/scenes/settings/AISection.tsx
index 423ba4e5536c..ea1e3e62a775 100644
--- a/products/conversations/frontend/scenes/settings/AISection.tsx
+++ b/products/conversations/frontend/scenes/settings/AISection.tsx
@@ -10,6 +10,7 @@ import { urls } from 'scenes/urls'
import { SceneSection } from '~/layout/scenes/components/SceneSection'
+import { AIContextAccountPropertiesSection } from '../../components/AIContextAccountPropertiesSection/AIContextAccountPropertiesSection'
import { SupportPlaybookSection } from '../../components/SupportPlaybookSection/SupportPlaybookSection'
import { aiTriageTicketTypeLabel, TicketChannel } from '../../types'
import { supportSettingsLogic } from './supportSettingsLogic'
@@ -135,6 +136,7 @@ export function AISection(): JSX.Element {
)}
{aiSuggestionsEnabled && <SupportPlaybookSection />}
+ {aiSuggestionsEnabled && <AIContextAccountPropertiesSection />}
{aiSuggestionsEnabled && (
<SceneSection
diff --git a/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts b/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts
index 92c39172c4ca..ba8434a86c64 100644
--- a/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts
+++ b/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts
@@ -1,3 +1,5 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
import { expectLogic } from 'kea-test-utils'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -573,4 +575,129 @@ describe('supportSettingsLogic', () => {
expect(logic.values.playbookSaving).toBe(false)
})
})
+
+ describe('AI context account properties', () => {
+ it('saves selected ids and ignores a second submit while in flight', async () => {
+ let resolveTeamPatch: () => void = () => {}
+ const releaseTeamPatch = new Promise<void>((resolve) => {
+ resolveTeamPatch = resolve
+ })
+ useMocks({
+ get: {
+ '/api/conversations/v1/email/status': { configs: [] },
+ '/api/projects/:team_id/conversations/ai_reply_playbook/': PLAYBOOK_GET,
+ '/api/projects/:team_id/conversations/ai_context_account_properties/': [
+ { id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', name: 'Plan' },
+ ],
+ },
+ patch: {
+ '/api/environments/:team_id/': async ({ request }) => {
+ const body = await request.json()
+ await releaseTeamPatch
+ return [200, body]
+ },
+ },
+ })
+ initKeaTests(true, {
+ ...MOCK_DEFAULT_TEAM,
+ conversations_settings: { ai_context_account_property_ids: [] },
+ } as unknown as TeamType)
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOMER_ANALYTICS]: true })
+ logic = supportSettingsLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.accountPropertyOptions).toEqual([
+ { id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', name: 'Plan' },
+ ])
+
+ await expectLogic(logic, () => {
+ logic.actions.setAiContextAccountPropertyIds(['aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'])
+ })
+ .toDispatchActions(['setAiContextAccountPropertiesSaving', 'updateCurrentTeam'])
+ .toMatchValues({ aiContextAccountPropertiesSaving: true })
+
+ // The first PATCH is still open, so the second submit must hit the in-flight guard.
+ await expectLogic(logic, () => {
+ logic.actions.setAiContextAccountPropertyIds(['aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'])
+ }).toNotHaveDispatchedActions(['updateCurrentTeam'])
+
+ resolveTeamPatch()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.aiContextAccountPropertiesSaving).toBe(false)
+ })
+
+ it('ignores a late response from the team the user switched away from', async () => {
+ const TEAM_A_OPTIONS = [{ id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', name: 'Team A plan' }]
+ const TEAM_B_OPTIONS = [{ id: 'bbbbbbbb-cccc-dddd-eeee-ffffffffffff', name: 'Team B plan' }]
+ let releaseTeamA: () => void = () => {}
+ const teamAInFlight = new Promise<void>((resolve) => {
+ releaseTeamA = resolve
+ })
+ useMocks({
+ get: {
+ '/api/conversations/v1/email/status': { configs: [] },
+ '/api/projects/:team_id/conversations/ai_reply_playbook/': PLAYBOOK_GET,
+ '/api/projects/:team_id/conversations/ai_context_account_properties/': async ({ params }) => {
+ if (String(params.team_id) === String(MOCK_DEFAULT_TEAM.id)) {
+ await teamAInFlight
+ return [200, TEAM_A_OPTIONS]
+ }
+ return [200, TEAM_B_OPTIONS]
+ },
+ },
+ })
+ initKeaTests(true, {
+ ...MOCK_DEFAULT_TEAM,
+ conversations_settings: { ai_context_account_property_ids: [] },
+ } as unknown as TeamType)
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOMER_ANALYTICS]: true })
+ logic = supportSettingsLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadAccountPropertyOptions'])
+
+ // Team A's request is still open, so switching teams must start a second load.
+ await expectLogic(logic, () => {
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ id: MOCK_DEFAULT_TEAM.id + 1,
+ conversations_settings: { ai_context_account_property_ids: [] },
+ } as unknown as TeamType)
+ }).toDispatchActions([
+ 'resetAccountPropertyOptions',
+ 'loadAccountPropertyOptions',
+ 'loadAccountPropertyOptionsSuccess',
+ ])
+ expect(logic.values.accountPropertyOptions).toEqual(TEAM_B_OPTIONS)
+
+ releaseTeamA()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.accountPropertyOptions).toEqual(TEAM_B_OPTIONS)
+ })
+
+ it('loads the options when Customer analytics resolves after mount', async () => {
+ const OPTIONS = [{ id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', name: 'Plan' }]
+ useMocks({
+ get: {
+ '/api/conversations/v1/email/status': { configs: [] },
+ '/api/projects/:team_id/conversations/ai_reply_playbook/': PLAYBOOK_GET,
+ '/api/projects/:team_id/conversations/ai_context_account_properties/': OPTIONS,
+ },
+ })
+ initKeaTests(true, {
+ ...MOCK_DEFAULT_TEAM,
+ conversations_settings: { ai_context_account_property_ids: [] },
+ } as unknown as TeamType)
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOMER_ANALYTICS]: false })
+ logic = supportSettingsLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners().toNotHaveDispatchedActions(['loadAccountPropertyOptions'])
+ expect(logic.values.accountPropertyOptions).toEqual([])
+
+ // posthog-js can resolve the flag after the scene is already on screen.
+ await expectLogic(logic, () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOMER_ANALYTICS]: true })
+ }).toDispatchActions(['loadAccountPropertyOptions', 'loadAccountPropertyOptionsSuccess'])
+ expect(logic.values.accountPropertyOptions).toEqual(OPTIONS)
+ })
+ })
})
diff --git a/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts b/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
index d2ca45927f72..145ea90e84df 100644
--- a/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
+++ b/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
@@ -1,5 +1,6 @@
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
import api from 'lib/api'
@@ -13,10 +14,12 @@ import { SlackChannelType, UserBasicType } from '~/types'
import type { FeatureFlagsSet } from '../../../../../frontend/src/lib/logic/featureFlagLogic'
import type { TeamPublicType, TeamType } from '../../../../../frontend/src/types'
-import { conversationsAiReplyPlaybookRetrieve } from '../../generated/api'
-import type { AIReplyPlaybookApi } from '../../generated/api.schemas'
+import { conversationsAiContextAccountPropertiesList, conversationsAiReplyPlaybookRetrieve } from '../../generated/api'
+import type { AIContextAccountPropertyApi, AIReplyPlaybookApi } from '../../generated/api.schemas'
import { TicketChannel } from '../../types'
+export const MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS = 10
+
const BASE_AI_CHANNELS: TicketChannel[] = ['widget', 'email', 'slack']
/** Kept in sync with SUPPORT_SLACK_FILE_SCOPES in products/conversations/backend/support_slack.py. */
@@ -64,8 +67,12 @@ export interface supportSettingsLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
currentTeamLoading: boolean // teamLogic
+ accountPropertyOptions: AIContextAccountPropertyApi[]
+ accountPropertyOptionsLoading: boolean
addEmailFormVisible: boolean
aiAllChannels: TicketChannel[]
+ aiContextAccountPropertiesSaving: boolean
+ aiContextAccountPropertyIds: string[]
aiDiagnosticsEnabled: boolean
aiDiagnosticsLoading: boolean
aiEnabledChannels: TicketChannel[]
@@ -243,12 +250,30 @@ export interface supportSettingsLogicActions {
disconnectTeams: () => {
value: true
}
+ ensureAccountPropertyOptions: () => {
+ value: true
+ }
generateNewToken: () => {
value: true
}
installTeamsApp: (teamId: string) => {
teamId: string
}
+ loadAccountPropertyOptions: (_: any) => any
+ loadAccountPropertyOptionsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAccountPropertyOptionsSuccess: (
+ accountPropertyOptions: AIContextAccountPropertyApi[],
+ payload?: any
+ ) => {
+ accountPropertyOptions: AIContextAccountPropertyApi[]
+ payload?: any
+ }
loadEmailConfigs: () => {
value: true
}
@@ -401,6 +426,9 @@ export interface supportSettingsLogicActions {
removeTeamsChannelPair: (channelId: string) => {
channelId: string
}
+ resetAccountPropertyOptions: () => {
+ value: true
+ }
resetPlaybook: () => {
value: true
}
@@ -444,6 +472,12 @@ export interface supportSettingsLogicActions {
setAddEmailFormVisible: (visible: boolean) => {
visible: boolean
}
+ setAiContextAccountPropertiesSaving: (saving: boolean) => {
+ saving: boolean
+ }
+ setAiContextAccountPropertyIds: (ids: string[]) => {
+ ids: string[]
+ }
setAiDiagnosticsEnabled: (enabled: boolean) => {
enabled: boolean
}
@@ -606,6 +640,7 @@ export interface supportSettingsLogicMeta {
githubSelectedRepos: (currentTeam: TeamPublicType | TeamType | null) => string[]
aiSuggestionsEnabled: (currentTeam: TeamPublicType | TeamType | null) => boolean
aiDiagnosticsEnabled: (currentTeam: TeamPublicType | TeamType | null) => boolean
+ aiContextAccountPropertyIds: (currentTeam: TeamPublicType | TeamType | null) => string[]
aiEnabledChannels: (
currentTeam: TeamPublicType | TeamType | null,
emailConfigs: EmailConfigStatus[]
@@ -746,6 +781,10 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
savePlaybookInstructions: (instructions: string | null) => ({ instructions }),
savePlaybook: true,
resetPlaybook: true,
+ setAiContextAccountPropertyIds: (ids: string[]) => ({ ids }),
+ setAiContextAccountPropertiesSaving: (saving: boolean) => ({ saving }),
+ resetAccountPropertyOptions: true,
+ ensureAccountPropertyOptions: true,
}),
reducers({
conversationsEnabledLoading: [
@@ -963,6 +1002,18 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
"Couldn't load the support playbook. Refresh the page, and if it keeps happening contact support.",
},
],
+ aiContextAccountPropertiesSaving: [
+ false,
+ {
+ setAiContextAccountPropertiesSaving: (_, { saving }) => saving,
+ },
+ ],
+ accountPropertyOptions: [
+ [] as AIContextAccountPropertyApi[],
+ {
+ resetAccountPropertyOptions: () => [],
+ },
+ ],
slackTicketEmojiValue: [
null as string | null,
{
@@ -1028,6 +1079,29 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
},
},
],
+ accountPropertyOptions: [
+ [] as AIContextAccountPropertyApi[],
+ {
+ loadAccountPropertyOptions: async (_, breakpoint) => {
+ const teamId = values.currentTeam?.id
+ if (!teamId) {
+ return []
+ }
+ const options = await conversationsAiContextAccountPropertiesList(String(teamId)).catch(() => null)
+ // A team switch clears the list and starts a newer load. Without this, the
+ // previous team's response would repopulate what the switch just cleared.
+ // It sits outside the catch above so the abort isn't swallowed as a failure.
+ breakpoint()
+ if (options === null) {
+ lemonToast.error(
+ "Couldn't load account properties. Refresh the page, and if it keeps happening contact support."
+ )
+ return values.accountPropertyOptions
+ }
+ return options
+ },
+ },
+ ],
slackChannels: [
[] as SlackChannelType[],
{
@@ -1234,6 +1308,18 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
(currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType): boolean =>
!!currentTeam?.conversations_settings?.ai_diagnostics_enabled,
],
+ aiContextAccountPropertyIds: [
+ (s) => [s.currentTeam],
+ (currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType): string[] => {
+ const raw = currentTeam?.conversations_settings?.ai_context_account_property_ids
+ if (!Array.isArray(raw)) {
+ return []
+ }
+ return raw
+ .filter((id): id is string => typeof id === 'string')
+ .slice(0, MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS)
+ },
+ ],
aiEnabledChannels: [
(s) => [s.currentTeam, s.emailConfigs],
(
@@ -1769,6 +1855,27 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
actions.setPlaybookSaving(false)
}
},
+ setAiContextAccountPropertyIds: async ({ ids }) => {
+ if (values.aiContextAccountPropertiesSaving) {
+ return
+ }
+ const next = [...new Set(ids)].slice(0, MAX_AI_CONTEXT_ACCOUNT_PROPERTY_IDS)
+ const current = values.aiContextAccountPropertyIds
+ if (next.length === current.length && next.every((id, index) => id === current[index])) {
+ return
+ }
+ actions.setAiContextAccountPropertiesSaving(true)
+ try {
+ await teamLogic.asyncActions.updateCurrentTeam({
+ conversations_settings: {
+ ...values.currentTeam?.conversations_settings,
+ ai_context_account_property_ids: next,
+ },
+ })
+ } finally {
+ actions.setAiContextAccountPropertiesSaving(false)
+ }
+ },
connectGithub: async ({ integrationId }) => {
try {
// nosemgrep: prefer-codegen-api
@@ -1805,6 +1912,23 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
if (!values.playbook && !values.playbookLoading) {
actions.loadPlaybook()
}
+ actions.ensureAccountPropertyOptions()
+ },
+ ensureAccountPropertyOptions: () => {
+ const teamId = values.currentTeam?.id
+ if (!values.featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS] || !teamId) {
+ return
+ }
+ // Idempotent, because mount, a team change and the feature flag arriving all reach
+ // this and any of them can come first.
+ if (cache.accountPropertyOptionsTeamId === teamId) {
+ return
+ }
+ // The options belong to one team, so drop the previous team's list rather than
+ // offering it until the new request lands.
+ cache.accountPropertyOptionsTeamId = teamId
+ actions.resetAccountPropertyOptions()
+ actions.loadAccountPropertyOptions({})
},
updateCurrentTeamSuccess: ({ payload }) => {
if (payload && payload === cache.playbookPayload) {
@@ -1864,6 +1988,14 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
}
},
})),
+ subscriptions(({ actions }) => ({
+ // posthog-js resolves flags after the scene mounts, so CUSTOMER_ANALYTICS can turn on
+ // once the picker is already on screen. Without this the picker would render the
+ // "no account properties yet" empty state for a team that has them.
+ featureFlags: () => {
+ actions.ensureAccountPropertyOptions()
+ },
+ })),
afterMount(({ values, actions }) => {
if (values.slackConnected) {
actions.loadSlackChannelsWithToken()
@@ -1887,5 +2019,6 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
actions.loadGithubRepos()
}
actions.loadPlaybook()
+ actions.ensureAccountPropertyOptions()
}),
])
diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yaml
index d44f1367cc6b..66c0bbb2f6f6 100644
--- a/products/conversations/mcp/tools.yaml
+++ b/products/conversations/mcp/tools.yaml
@@ -9,6 +9,9 @@ feature: conversations
url_prefix: /support/tickets
ui_apps: {}
tools:
+ conversations-ai-context-account-properties-list:
+ operation: conversations_ai_context_account_properties_list
+ enabled: false
conversations-ai-reply-playbook-retrieve:
operation: conversations_ai_reply_playbook_retrieve
enabled: false
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 087ac4e51492..325c89c629c2 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -1347,15 +1347,19 @@ def list_custom_property_definitions(
*,
user_access_control: "UserAccessControl",
exclude_group_targets: bool = False,
+ target_type: str | None = None,
) -> tuple[list[contracts.CustomPropertyDefinitionView], int]:
"""Custom property definitions for the team, ordered by name. Returns ``(page, total_count)``.
``has_workflow_reference`` is included for every caller. ``references`` carries only workflow
metadata the caller can read. ``exclude_group_targets`` hides group-target definitions from callers
- without ``group`` read authorization."""
+ without ``group`` read authorization. ``target_type`` narrows the scan to one target, so a caller
+ that wants a single target doesn't page over every definition to find it."""
queryset = CustomPropertyDefinition.objects.for_team(team_id).select_related("source").order_by("name")
if exclude_group_targets:
queryset = queryset.exclude(target_type=TargetType.GROUP.value)
+ if target_type is not None:
+ queryset = queryset.filter(target_type=target_type)
total_count = queryset.count()
page = list(queryset[offset : offset + limit])
workflow_references = _custom_property_references_by_definition_id(team_id)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a2829e627a2a..393ee959f6e2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13,6 +13,13 @@ export namespace Schemas {
/**
*
*/
+ export interface AIContextAccountProperty {
+ /** Customer analytics account property definition id. */
+ id: string;
+ /** Display name of the account property. */
+ name: string;
+ }
+
export type AIEventType = typeof AIEventType[keyof typeof AIEventType];