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): add per-channel AI gating and bot reply settings (#65821)

Alex V3d84db5a89b0
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index e2a1b02a4cad..4e4973d7c6c3 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -753,6 +753,8 @@ export interface ConversationsSettings {
github_repos?: string[] | null
ai_suggestions_enabled?: boolean
ai_diagnostics_enabled?: boolean
+ ai_resolution_channels?: string[] | null
+ ai_reply_modes?: Record<string, Record<string, 'private_note' | 'bot_reply'>> | null
}
export interface LogsSettings {
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 24ec2c912ab1..90b2ac33779d 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -1286,6 +1286,57 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
value["slack_alert_channel_id"] = alert_channel.strip() or None
else:
raise serializers.ValidationError({"slack_alert_channel_id": "Must be a string."})
+ # AI resolution channels: list of valid channel strings or null
+ VALID_CHANNELS = {"widget", "email", "slack", "teams", "github"}
+ if "ai_resolution_channels" in value:
+ channels = value.get("ai_resolution_channels")
+ if channels is None:
+ pass
+ elif isinstance(channels, list):
+ invalid = [c for c in channels if not isinstance(c, str) or c not in VALID_CHANNELS]
+ if invalid:
+ raise serializers.ValidationError(
+ {
+ "ai_resolution_channels": f"Invalid channel(s): {', '.join(str(c) for c in invalid)}. "
+ f"Valid options: {', '.join(sorted(VALID_CHANNELS))}."
+ }
+ )
+ value["ai_resolution_channels"] = channels
+ else:
+ raise serializers.ValidationError(
+ {"ai_resolution_channels": "Must be a list of channel names or null."}
+ )
+ # AI reply modes: { channel: { ticket_type: mode } } or null
+ VALID_REPLY_MODES = {"private_note", "bot_reply"}
+ VALID_TICKET_TYPES = {"how_to", "diagnostic", "account_billing"}
+ # Only how_to replies may be published to the ticket author. diagnostic/account_billing
+ # draw on project data (events, persons, recordings, logs) and must stay private notes —
+ # there's no per-author authorization that the customer is entitled to that data.
+ BOT_REPLY_TICKET_TYPES = {"how_to"}
+ if "ai_reply_modes" in value:
+ modes = value.get("ai_reply_modes")
+ if modes is None:
+ pass
+ elif isinstance(modes, dict):
+ cleaned_modes: dict[str, dict[str, str]] = {}
+ for ch, type_map in modes.items():
+ if ch not in VALID_CHANNELS or not isinstance(type_map, dict):
+ continue
+ cleaned_map: dict[str, str] = {}
+ for tt, mode in type_map.items():
+ if tt not in VALID_TICKET_TYPES or mode not in VALID_REPLY_MODES:
+ continue
+ # Demote bot_reply to private_note for ticket types that may never be
+ # published (diagnostic/account_billing). Coerce rather than reject so a
+ # stale value doesn't block unrelated settings saves.
+ if mode == "bot_reply" and tt not in BOT_REPLY_TICKET_TYPES:
+ mode = "private_note"
+ cleaned_map[tt] = mode
+ if cleaned_map:
+ cleaned_modes[ch] = cleaned_map
+ value["ai_reply_modes"] = cleaned_modes
+ else:
+ raise serializers.ValidationError({"ai_reply_modes": "Must be an object or null."})
return value
def validate_receive_org_level_activity_logs(self, value: bool | None) -> bool | None:
diff --git a/products/conversations/backend/api/tests/test_signals.py b/products/conversations/backend/api/tests/test_signals.py
index 7e817b0479af..e0aabe7cb814 100644
--- a/products/conversations/backend/api/tests/test_signals.py
+++ b/products/conversations/backend/api/tests/test_signals.py
@@ -465,3 +465,22 @@ class TestEmailReplySignalGuard(BaseTest):
)
assert EmailOutboxMessage.objects.filter(ticket=self.email_ticket).count() == expected_count
+
+
+class TestIsOutboundReply:
+ @parameterized.expand(
+ [
+ ("private_ai_note", {"author_type": "AI", "is_private": True}, None, False),
+ ("public_ai_reply", {"author_type": "AI", "is_private": False}, None, True),
+ ("human_team_reply", {"author_type": "support", "is_private": False}, 42, True),
+ ("private_human_note", {"author_type": "support", "is_private": True}, 42, False),
+ ("customer_message", {"author_type": "customer", "is_private": False}, None, False),
+ ("customer_with_created_by", {"author_type": "customer", "is_private": False}, 1, False),
+ ("none_context", None, 42, False),
+ ("non_dict_context", "garbage", None, False),
+ ]
+ )
+ def test_outbound_reply_gating(self, _name, item_context, created_by_id, expected):
+ from products.conversations.backend.signals import _is_outbound_reply
+
+ assert _is_outbound_reply(item_context, created_by_id) is expected
diff --git a/products/conversations/backend/signals.py b/products/conversations/backend/signals.py
index 0c664ad97c4f..f6ee4237a16b 100644
--- a/products/conversations/backend/signals.py
+++ b/products/conversations/backend/signals.py
@@ -43,6 +43,27 @@ def _get_comment_created_by_id(comment: Comment) -> int | None:
return created_by_id if isinstance(created_by_id, int) else None
+def _is_outbound_reply(item_context: dict | None, created_by_id: int | None) -> bool:
+ """True for messages that should be delivered to the customer's channel.
+
+ This includes human team replies (has created_by, non-customer, non-private) and
+ public AI replies (author_type == "AI" with is_private == False).
+ """
+ if not isinstance(item_context, dict):
+ return False
+ if _is_private_message(item_context):
+ return False
+ author_type = item_context.get("author_type")
+ if created_by_id and author_type != "customer":
+ return True
+ if author_type == "AI":
+ return True
+ return False
+
+
+AI_BOT_DISPLAY_NAME = "AI assistant"
+
+
@receiver(post_save, sender=Ticket)
def emit_ticket_created_event(sender, instance: Ticket, created: bool, **kwargs):
"""
@@ -109,7 +130,9 @@ def update_ticket_on_message(sender, instance: Comment, created: bool, **kwargs)
# New message: update denormalized stats
author_type = item_context.get("author_type") if isinstance(item_context, dict) else None
- is_team_message = created_by_id and author_type != "customer"
+ is_team_message = (created_by_id and author_type != "customer") or (
+ author_type == "AI" and not _is_private_message(item_context)
+ )
update_fields = {
"message_count": F("message_count") + 1,
@@ -258,13 +281,12 @@ def handle_comment_soft_delete(sender, instance: Comment, **kwargs):
@receiver(post_save, sender=Comment)
def post_slack_reply_on_team_message(sender, instance: Comment, created: bool, **kwargs):
"""
- When a team member replies to a Slack-sourced ticket, post the reply
+ When a team member or AI bot replies to a Slack-sourced ticket, post the reply
back to the Slack thread via a Celery task.
Only triggers for:
- Newly created comments (not edits)
- - Non-private messages
- - Messages with a created_by (team member, not customer)
+ - Outbound replies (human team or public AI)
- Tickets with channel_source="slack" and valid slack thread info
"""
if instance.scope != "conversations_ticket":
@@ -274,16 +296,9 @@ def post_slack_reply_on_team_message(sender, instance: Comment, created: bool, *
return
item_context = instance.item_context
- if _is_private_message(item_context):
- return
-
- # Only team messages (has created_by, not customer-authored)
created_by_id = _get_comment_created_by_id(instance)
- if not created_by_id:
- return
- author_type = item_context.get("author_type") if isinstance(item_context, dict) else None
- if author_type == "customer":
+ if not _is_outbound_reply(item_context, created_by_id):
return
# Don't echo messages that originated from Slack back to Slack
@@ -318,6 +333,8 @@ def post_slack_reply_on_team_message(sender, instance: Comment, created: bool, *
if created_by:
author_name = f"{created_by.first_name} {created_by.last_name}".strip() or created_by.email
author_email = created_by.email
+ else:
+ author_name = settings_dict.get("slack_bot_display_name") or AI_BOT_DISPLAY_NAME
cast(Any, post_reply_to_slack).delay(
ticket_id=str(ticket.id),
@@ -338,13 +355,12 @@ def post_slack_reply_on_team_message(sender, instance: Comment, created: bool, *
@receiver(post_save, sender=Comment)
def send_email_reply_on_team_message(sender, instance: Comment, created: bool, **kwargs):
"""
- When a team member replies to an email-sourced ticket, send the reply
+ When a team member or AI bot replies to an email-sourced ticket, send the reply
back to the customer via email through a Celery task.
Only triggers for:
- Newly created comments (not edits)
- - Non-private messages
- - Messages with a created_by (team member, not customer)
+ - Outbound replies (human team or public AI)
- Tickets with channel_source="email"
"""
if instance.scope != "conversations_ticket":
@@ -354,15 +370,9 @@ def send_email_reply_on_team_message(sender, instance: Comment, created: bool, *
return
item_context = instance.item_context
- if _is_private_message(item_context):
- return
-
created_by_id = _get_comment_created_by_id(instance)
- if not created_by_id:
- return
- author_type = item_context.get("author_type") if isinstance(item_context, dict) else None
- if author_type == "customer":
+ if not _is_outbound_reply(item_context, created_by_id):
return
# Don't echo messages that originated from email back via email
@@ -417,13 +427,12 @@ def send_email_reply_on_team_message(sender, instance: Comment, created: bool, *
@receiver(post_save, sender=Comment)
def post_teams_reply_on_team_message(sender, instance: Comment, created: bool, **kwargs):
"""
- When a team member replies to a Teams-sourced ticket, post the reply
+ When a team member or AI bot replies to a Teams-sourced ticket, post the reply
back to the Teams conversation via a Celery task.
Only triggers for:
- Newly created comments (not edits)
- - Non-private messages
- - Messages with a created_by (team member, not customer)
+ - Outbound replies (human team or public AI)
- Tickets with channel_source="teams" and valid teams thread info
- Messages not originating from Teams (to avoid echo)
"""
@@ -434,15 +443,9 @@ def post_teams_reply_on_team_message(sender, instance: Comment, created: bool, *
return
item_context = instance.item_context
- if _is_private_message(item_context):
- return
-
created_by_id = _get_comment_created_by_id(instance)
- if not created_by_id:
- return
- author_type = item_context.get("author_type") if isinstance(item_context, dict) else None
- if author_type == "customer":
+ if not _is_outbound_reply(item_context, created_by_id):
return
# Don't echo messages that originated from Teams back to Teams
@@ -474,6 +477,8 @@ def post_teams_reply_on_team_message(sender, instance: Comment, created: bool, *
author_name = ""
if created_by:
author_name = f"{created_by.first_name} {created_by.last_name}".strip() or created_by.email
+ else:
+ author_name = AI_BOT_DISPLAY_NAME
# Shared channels are written to via Graph (the bot connector can't post
# there); standard channels keep using the bot connector reply path.
@@ -511,13 +516,12 @@ def post_teams_reply_on_team_message(sender, instance: Comment, created: bool, *
@receiver(post_save, sender=Comment)
def post_github_reply_on_team_message(sender, instance: Comment, created: bool, **kwargs):
"""
- When a team member replies to a GitHub-sourced ticket, post the reply
+ When a team member or AI bot replies to a GitHub-sourced ticket, post the reply
back to the GitHub issue via a Celery task.
Only triggers for:
- Newly created comments (not edits)
- - Non-private messages
- - Messages with a created_by (team member, not customer)
+ - Outbound replies (human team or public AI)
- Tickets with channel_source="github" and valid github issue info
- Messages not originating from GitHub (to avoid echo)
"""
@@ -528,15 +532,9 @@ def post_github_reply_on_team_message(sender, instance: Comment, created: bool,
return
item_context = instance.item_context
- if _is_private_message(item_context):
- return
-
created_by_id = _get_comment_created_by_id(instance)
- if not created_by_id:
- return
- author_type = item_context.get("author_type") if isinstance(item_context, dict) else None
- if author_type == "customer":
+ if not _is_outbound_reply(item_context, created_by_id):
return
if isinstance(item_context, dict) and item_context.get("from_github"):
@@ -567,6 +565,8 @@ def post_github_reply_on_team_message(sender, instance: Comment, created: bool,
author_name = ""
if created_by:
author_name = f"{created_by.first_name} {created_by.last_name}".strip() or created_by.email
+ else:
+ author_name = AI_BOT_DISPLAY_NAME
cast(Any, post_reply_to_github).delay(
ticket_id=str(ticket.id),
diff --git a/products/conversations/backend/temporal/coordinator.py b/products/conversations/backend/temporal/coordinator.py
index 845dcc33bcfa..642476413b1d 100644
--- a/products/conversations/backend/temporal/coordinator.py
+++ b/products/conversations/backend/temporal/coordinator.py
@@ -100,6 +100,10 @@ def _collect_eligible(lookback_minutes: int = TICKET_LOOKBACK_MINUTES) -> list[E
if not settings_dict.get("ai_suggestions_enabled", False):
continue
+ allowed_channels = settings_dict.get("ai_resolution_channels")
+ if allowed_channels is not None and ticket.channel_source not in allowed_channels:
+ continue
+
if not team.organization.is_ai_data_processing_approved:
continue
diff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.py
index b81ff8b67edd..ca5b3409ce0a 100644
--- a/products/conversations/backend/temporal/pipeline.py
+++ b/products/conversations/backend/temporal/pipeline.py
@@ -51,6 +51,9 @@ logger = structlog.get_logger(__name__)
MAX_ATTEMPTS = 5
SCORE_THRESHOLD = 0.5
RERANK_TOP_K = 5
+# Ticket types whose replies may ever be published to the (untrusted) ticket author.
+# diagnostic/account_billing draw on project data and must stay private regardless of settings.
+PUBLISHABLE_TICKET_TYPES = {"how_to"}
RETRIEVE_LIMIT = 15
DRAFT_POLL_SECONDS = 600
WIDEN_RADIUS = 3
@@ -425,6 +428,8 @@ class PersistReplyInput:
reply: str
citations: list[str]
confidence: float
+ ticket_type: str = "how_to"
+ allow_bot_reply: bool = False
@dataclass
@@ -1040,14 +1045,42 @@ CITED CHUNKS:
@activity.defn
@close_db_connections
async def support_persist_reply_activity(input: PersistReplyInput) -> None:
- """Persist the validated reply as a private AI comment on the ticket."""
+ """Persist the validated reply as an AI comment on the ticket (private note or bot reply per settings)."""
async with Heartbeater():
await database_sync_to_async(_persist_reply_sync, thread_sensitive=False)(
- input.team_id, input.ticket_id, input.reply, input.citations, input.confidence
+ input.team_id,
+ input.ticket_id,
+ input.reply,
+ input.citations,
+ input.confidence,
+ input.ticket_type,
+ input.allow_bot_reply,
)
-def _persist_reply_sync(team_id: int, ticket_id: str, reply: str, citations: list[str], confidence: float) -> None:
+def _persist_reply_sync(
+ team_id: int,
+ ticket_id: str,
+ reply: str,
+ citations: list[str],
+ confidence: float,
+ ticket_type: str = "how_to",
+ allow_bot_reply: bool = False,
+) -> None:
+ is_private = True
+ # Only how_to replies may be published. diagnostic/account_billing draw on project data and
+ # must stay private regardless of the team's ai_reply_modes — guards against stale settings
+ # since validation now rejects bot_reply for those types. Controlled by team-level opt-in.
+ if allow_bot_reply and ticket_type in PUBLISHABLE_TICKET_TYPES:
+ ticket = Ticket.objects.select_related("team").filter(team_id=team_id, id=ticket_id).first()
+ if ticket:
+ settings_dict = ticket.team.conversations_settings or {}
+ modes = settings_dict.get("ai_reply_modes") or {}
+ channel_modes = modes.get(ticket.channel_source) or {}
+ mode = channel_modes.get(ticket_type, "private_note")
+ if mode == "bot_reply":
+ is_private = False
+
Comment.objects.create(
team_id=team_id,
scope="conversations_ticket",
@@ -1055,7 +1088,7 @@ def _persist_reply_sync(team_id: int, ticket_id: str, reply: str, citations: lis
content=reply,
item_context={
"author_type": "AI",
- "is_private": True,
+ "is_private": is_private,
"citations": citations,
"confidence": confidence,
},
@@ -1304,6 +1337,8 @@ class SupportReplyWorkflow:
reply=draft_output.reply,
citations=draft_output.citations,
confidence=validate_output.confidence,
+ ticket_type=ticket_type,
+ allow_bot_reply=True,
),
start_to_close_timeout=timedelta(minutes=1),
retry_policy=RetryPolicy(maximum_attempts=3),
@@ -1361,6 +1396,8 @@ class SupportReplyWorkflow:
reply=best_reply,
citations=best_citations,
confidence=best_confidence,
+ ticket_type=ticket_type,
+ allow_bot_reply=False,
),
start_to_close_timeout=timedelta(minutes=1),
retry_policy=RetryPolicy(maximum_attempts=3),
diff --git a/products/conversations/backend/temporal/tests/test_coordinator.py b/products/conversations/backend/temporal/tests/test_coordinator.py
index 686de169ede1..f5025d937c9b 100644
--- a/products/conversations/backend/temporal/tests/test_coordinator.py
+++ b/products/conversations/backend/temporal/tests/test_coordinator.py
@@ -38,6 +38,8 @@ def _make_ticket(
has_ready_sources: bool = True,
has_ai_note: bool = False,
has_team_reply: bool = False,
+ channel_source: str = "widget",
+ ai_resolution_channels: list[str] | None = None,
):
ticket_id = ticket_id or str(uuid.uuid4())
org = MagicMock()
@@ -45,10 +47,14 @@ def _make_ticket(
team = MagicMock()
team.id = team_id
team.organization = org
- team.conversations_settings = {"ai_suggestions_enabled": ai_suggestions_enabled}
+ settings: dict = {"ai_suggestions_enabled": ai_suggestions_enabled}
+ if ai_resolution_channels is not None:
+ settings["ai_resolution_channels"] = ai_resolution_channels
+ team.conversations_settings = settings
ticket = MagicMock()
ticket.id = uuid.UUID(ticket_id)
ticket.team = team
+ ticket.channel_source = channel_source
return ticket, ticket_id, team
@@ -62,6 +68,7 @@ class TestCollectEligible:
("has_ai_note", {"has_ai_note": True}),
("has_team_reply", {"has_team_reply": True}),
("rollout_off", {"rollout": False}),
+ ("channel_not_allowed", {"ai_resolution_channels": ["email"], "channel_source": "widget"}),
]
)
# Force the BK-readiness gate on (production default MIN_READY_BK_SOURCES=0 skips it) so the
@@ -94,6 +101,8 @@ class TestCollectEligible:
ai_suggestions_enabled=ai_suggestions_enabled,
ai_data_processing_approved=ai_data_processing_approved,
has_ready_sources=has_ready,
+ channel_source=overrides.get("channel_source", "widget"),
+ ai_resolution_channels=overrides.get("ai_resolution_channels"),
)
mock_master_flag.return_value = master_flag
@@ -137,6 +146,38 @@ class TestCollectEligible:
assert result[0].team_id == team.id
assert result[0].ticket_id == ticket_id
+ @parameterized.expand(
+ [
+ ("channel_in_allowed_list", ["widget"], "widget"),
+ ("null_allows_all", None, "slack"),
+ ]
+ )
+ @patch(f"{COORD_MODULE}._is_rollout_enabled", return_value=True)
+ @patch(f"{COORD_MODULE}.has_ready_sources", return_value=True)
+ @patch(f"{COORD_MODULE}.Comment")
+ @patch(f"{COORD_MODULE}.Ticket")
+ @patch(f"{COORD_MODULE}._is_master_flag_enabled", return_value=True)
+ def test_channel_gate_passes(
+ self,
+ _name,
+ ai_resolution_channels,
+ channel_source,
+ mock_master_flag,
+ mock_ticket_model,
+ mock_comment_model,
+ mock_has_ready,
+ mock_rollout,
+ ):
+ ticket, ticket_id, team = _make_ticket(
+ channel_source=channel_source,
+ ai_resolution_channels=ai_resolution_channels,
+ )
+ mock_ticket_model.objects.filter.return_value.select_related.return_value = [ticket]
+ mock_comment_model.objects.filter.return_value.values_list.return_value = []
+
+ result = _collect_eligible()
+ assert len(result) == 1
+
@patch(f"{COORD_MODULE}._is_rollout_enabled", return_value=True)
@patch(f"{COORD_MODULE}.has_ready_sources", return_value=True)
@patch(f"{COORD_MODULE}.Comment")
diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.py
index a53ba1e34af8..9f3cf5b707c0 100644
--- a/products/conversations/backend/temporal/tests/test_pipeline.py
+++ b/products/conversations/backend/temporal/tests/test_pipeline.py
@@ -374,6 +374,92 @@ class TestPersistReplyActivity:
assert comment.item_context["citations"] == ["chunk-1", "chunk-2"]
assert comment.item_context["confidence"] == 0.85
+ @parameterized.expand(
+ [
+ (
+ "allow_false_ignores_bot_reply_setting",
+ {"allow_bot_reply": False, "channel_source": "widget", "ticket_type": "how_to"},
+ {"widget": {"how_to": "bot_reply"}},
+ True,
+ ),
+ (
+ "allow_true_bot_reply_mode",
+ {"allow_bot_reply": True, "channel_source": "widget", "ticket_type": "how_to"},
+ {"widget": {"how_to": "bot_reply"}},
+ False,
+ ),
+ (
+ "allow_true_private_note_mode",
+ {"allow_bot_reply": True, "channel_source": "widget", "ticket_type": "how_to"},
+ {"widget": {"how_to": "private_note"}},
+ True,
+ ),
+ (
+ "allow_true_no_reply_modes_setting",
+ {"allow_bot_reply": True, "channel_source": "widget", "ticket_type": "how_to"},
+ None,
+ True,
+ ),
+ (
+ "allow_true_missing_channel_in_modes",
+ {"allow_bot_reply": True, "channel_source": "slack", "ticket_type": "how_to"},
+ {"widget": {"how_to": "bot_reply"}},
+ True,
+ ),
+ (
+ "allow_true_missing_ticket_type_in_modes",
+ {"allow_bot_reply": True, "channel_source": "widget", "ticket_type": "account_billing"},
+ {"widget": {"how_to": "bot_reply"}},
+ True,
+ ),
+ (
+ "diagnostic_stays_private_even_if_set_to_bot_reply",
+ {"allow_bot_reply": True, "channel_source": "widget", "ticket_type": "diagnostic"},
+ {"widget": {"diagnostic": "bot_reply"}},
+ True,
+ ),
+ (
+ "account_billing_stays_private_even_if_set_to_bot_reply",
+ {"allow_bot_reply": True, "channel_source": "widget", "ticket_type": "account_billing"},
+ {"widget": {"account_billing": "bot_reply"}},
+ True,
+ ),
+ ]
+ )
+ @pytest.mark.django_db
+ def test_reply_mode_matrix(self, _name, call_kwargs, ai_reply_modes, expected_private):
+ from posthog.models.comment import Comment
+
+ from products.conversations.backend.temporal.pipeline import _persist_reply_sync
+
+ org = Organization.objects.create(name="Test Org")
+ settings: dict[str, Any] = {"ai_suggestions_enabled": True}
+ if ai_reply_modes is not None:
+ settings["ai_reply_modes"] = ai_reply_modes
+ team = Team.objects.create(organization=org, name="Test Team", conversations_settings=settings)
+
+ ticket = Ticket.objects.create_with_number(
+ team=team,
+ widget_session_id="aabbccdd-0000-0000-0000-000000000001",
+ distinct_id="test-user",
+ channel_source=call_kwargs["channel_source"],
+ )
+
+ _persist_reply_sync(
+ team_id=team.id,
+ ticket_id=str(ticket.id),
+ reply="Test reply.",
+ citations=["c1"],
+ confidence=0.9,
+ ticket_type=call_kwargs["ticket_type"],
+ allow_bot_reply=call_kwargs["allow_bot_reply"],
+ )
+
+ comment = Comment.objects.get(team_id=team.id, item_id=str(ticket.id))
+ assert comment.item_context is not None
+ assert comment.item_context["author_type"] == "AI"
+ assert comment.item_context["is_private"] is expected_private
+
class TestStripJsonFence:
@parameterized.expand(
diff --git a/products/conversations/frontend/scenes/settings/AISection.tsx b/products/conversations/frontend/scenes/settings/AISection.tsx
index 2e28059b7737..879c0e95843d 100644
--- a/products/conversations/frontend/scenes/settings/AISection.tsx
+++ b/products/conversations/frontend/scenes/settings/AISection.tsx
@@ -1,15 +1,43 @@
import { useActions, useValues } from 'kea'
-import { LemonCard, LemonSwitch } from '@posthog/lemon-ui'
+import { LemonCard, LemonCheckbox, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
import { SceneSection } from '~/layout/scenes/components/SceneSection'
+import { aiTriageTicketTypeLabel } from '../../types'
import { supportSettingsLogic } from './supportSettingsLogic'
+const CHANNEL_LABELS: Record<string, string> = {
+ widget: 'API / Widget',
+ slack: 'Slack',
+ email: 'Email',
+ teams: 'Microsoft Teams',
+ github: 'GitHub',
+}
+
+const TICKET_TYPES = ['how_to', 'diagnostic', 'account_billing'] as const
+
+// Only how_to replies may be sent to the customer. diagnostic/account_billing draw on project
+// data, so they're locked to private notes (enforced by the backend too).
+const PUBLISHABLE_TICKET_TYPES = new Set<string>(['how_to'])
+
+const REPLY_MODE_OPTIONS = [
+ { value: 'private_note' as const, label: 'Private note' },
+ { value: 'bot_reply' as const, label: 'AI reply' },
+]
+
export function AISection(): JSX.Element {
- const { aiSuggestionsEnabled, aiSuggestionsLoading, aiDiagnosticsEnabled, aiDiagnosticsLoading } =
- useValues(supportSettingsLogic)
- const { setAiSuggestionsEnabled, setAiDiagnosticsEnabled } = useActions(supportSettingsLogic)
+ const {
+ aiSuggestionsEnabled,
+ aiSuggestionsLoading,
+ aiDiagnosticsEnabled,
+ aiDiagnosticsLoading,
+ aiEnabledChannels,
+ aiResolutionChannels,
+ aiReplyModes,
+ } = useValues(supportSettingsLogic)
+ const { setAiSuggestionsEnabled, setAiDiagnosticsEnabled, setAiResolutionChannels, setAiReplyMode } =
+ useActions(supportSettingsLogic)
return (
<SceneSection
@@ -29,21 +57,98 @@ export function AISection(): JSX.Element {
knowledge source.
</p>
</LemonCard>
- <LemonCard hoverEffect={false} className="flex flex-col gap-y-3 max-w-[800px] px-4 py-3">
- <LemonSwitch
- checked={aiDiagnosticsEnabled}
- onChange={(checked) => setAiDiagnosticsEnabled(checked)}
- loading={aiDiagnosticsLoading}
- disabledReason={!aiSuggestionsEnabled ? 'Enable AI suggestions first' : undefined}
- label="Allow the agent to investigate ticket data"
- />
- <p className="text-xs text-muted-alt mb-0">
- When enabled, tickets that report something broken let the agent query your project's data — events,
- error tracking, session recordings, and logs — to investigate the issue instead of relying on
- documentation alone. The agent has read-only access scoped to your project. Leave this off to keep
- suggestions grounded only in documentation and your business knowledge.
- </p>
- </LemonCard>
+ {aiSuggestionsEnabled && (
+ <LemonCard hoverEffect={false} className="flex flex-col gap-y-3 max-w-[800px] px-4 py-3">
+ <LemonSwitch
+ checked={aiDiagnosticsEnabled}
+ onChange={(checked) => setAiDiagnosticsEnabled(checked)}
+ loading={aiDiagnosticsLoading}
+ disabledReason={!aiSuggestionsEnabled ? 'Enable AI suggestions first' : undefined}
+ label="Allow the agent to investigate ticket data"
+ />
+ <p className="text-xs text-muted-alt mb-0">
+ When enabled, tickets that report something broken let the agent query your project's data —
+ events, error tracking, session recordings, and logs — to investigate the issue instead of
+ relying on documentation alone. The agent has read-only access scoped to your project. Leave
+ this off to keep suggestions grounded only in documentation and your business knowledge.
+ </p>
+ </LemonCard>
+ )}
+ {aiSuggestionsEnabled && aiEnabledChannels.length > 0 && (
+ <LemonCard hoverEffect={false} className="flex flex-col gap-y-3 max-w-[800px] px-4 py-3">
+ <h4 className="font-semibold text-sm mb-0">Allowed channels</h4>
+ <p className="text-xs text-muted-alt mb-0">
+ Choose which channels the AI resolution pipeline runs on. Unchecked channels will not receive AI
+ suggestions.
+ </p>
+ <div className="flex flex-col gap-y-2">
+ {aiEnabledChannels.map((channel) => (
+ <LemonCheckbox
+ key={channel}
+ checked={aiResolutionChannels.includes(channel)}
+ onChange={(checked) => {
+ const next = checked
+ ? [...aiResolutionChannels, channel]
+ : aiResolutionChannels.filter((c) => c !== channel)
+ setAiResolutionChannels(next)
+ }}
+ label={CHANNEL_LABELS[channel] ?? channel}
+ />
+ ))}
+ </div>
+ </LemonCard>
+ )}
+
+ {aiSuggestionsEnabled && aiResolutionChannels.length > 0 && (
+ <LemonCard hoverEffect={false} className="flex flex-col gap-y-3 max-w-[800px] px-4 py-3">
+ <h4 className="font-semibold text-sm mb-0">Reply behavior</h4>
+ <p className="text-xs text-muted-alt mb-0">
+ For each channel and ticket type, choose whether the AI posts a private note (visible only to
+ your team) or sends a safety-reviewed reply directly to the customer.
+ </p>
+ <p className="text-xs text-muted-alt mb-0">
+ <strong>Diagnostic and Account/Billing</strong> replies may include data from your project, so
+ they're always kept as private notes and can't be sent directly to the customer.
+ </p>
+ <div className="overflow-x-auto">
+ <table className="w-full text-xs">
+ <thead>
+ <tr>
+ <th className="text-left py-1 pr-3 font-medium text-muted-alt">Channel</th>
+ {TICKET_TYPES.map((tt) => (
+ <th key={tt} className="text-left py-1 px-2 font-medium text-muted-alt">
+ {aiTriageTicketTypeLabel[tt]}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {aiResolutionChannels.map((channel) => (
+ <tr key={channel} className="border-t border-border">
+ <td className="py-2 pr-3 font-medium">{CHANNEL_LABELS[channel] ?? channel}</td>
+ {TICKET_TYPES.map((tt) =>
+ PUBLISHABLE_TICKET_TYPES.has(tt) ? (
+ <td key={tt} className="py-2 px-2">
+ <LemonSelect
+ size="xsmall"
+ options={REPLY_MODE_OPTIONS}
+ value={aiReplyModes[channel]?.[tt] ?? 'private_note'}
+ onChange={(value) => setAiReplyMode(channel, tt, value)}
+ />
+ </td>
+ ) : (
+ <td key={tt} className="py-2 px-2 text-muted-alt">
+ Private note
+ </td>
+ )
+ )}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </LemonCard>
+ )}
</SceneSection>
)
}
diff --git a/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts b/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
index 95f497ca37ff..d3e8842fdc5c 100644
--- a/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
+++ b/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
@@ -110,6 +110,12 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
setAiSuggestionsLoading: (loading: boolean) => ({ loading }),
setAiDiagnosticsEnabled: (enabled: boolean) => ({ enabled }),
setAiDiagnosticsLoading: (loading: boolean) => ({ loading }),
+ setAiResolutionChannels: (channels: string[]) => ({ channels }),
+ setAiReplyMode: (channel: string, ticketType: string, mode: 'private_note' | 'bot_reply') => ({
+ channel,
+ ticketType,
+ mode,
+ }),
}),
reducers({
conversationsEnabledLoading: [
@@ -507,6 +513,46 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
(s) => [s.currentTeam],
(currentTeam): boolean => !!currentTeam?.conversations_settings?.ai_diagnostics_enabled,
],
+ aiEnabledChannels: [
+ (s) => [s.currentTeam, s.emailConfigs],
+ (currentTeam, emailConfigs): string[] => {
+ const cs = currentTeam?.conversations_settings
+ if (!cs) {
+ return []
+ }
+ const channels: string[] = []
+ channels.push('widget')
+ if (cs.slack_enabled) {
+ channels.push('slack')
+ }
+ if (emailConfigs.length > 0 || cs.email_enabled) {
+ channels.push('email')
+ }
+ if (cs.teams_enabled) {
+ channels.push('teams')
+ }
+ if (cs.github_enabled) {
+ channels.push('github')
+ }
+ return channels
+ },
+ ],
+ aiResolutionChannels: [
+ (s) => [s.currentTeam, s.aiEnabledChannels],
+ (currentTeam, aiEnabledChannels): string[] => {
+ const stored = currentTeam?.conversations_settings?.ai_resolution_channels
+ if (Array.isArray(stored)) {
+ return stored.filter((ch: string) => aiEnabledChannels.includes(ch))
+ }
+ return aiEnabledChannels
+ },
+ ],
+ aiReplyModes: [
+ (s) => [s.currentTeam],
+ (currentTeam): Record<string, Record<string, 'private_note' | 'bot_reply'>> => {
+ return currentTeam?.conversations_settings?.ai_reply_modes ?? {}
+ },
+ ],
}),
listeners(({ values, actions }) => ({
connectSlack: async ({ nextPath }) => {
@@ -897,6 +943,24 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([
},
})
},
+ setAiResolutionChannels: ({ channels }) => {
+ actions.updateCurrentTeam({
+ conversations_settings: {
+ ...values.currentTeam?.conversations_settings,
+ ai_resolution_channels: channels,
+ },
+ })
+ },
+ setAiReplyMode: ({ channel, ticketType, mode }) => {
+ const current = values.currentTeam?.conversations_settings?.ai_reply_modes ?? {}
+ const channelModes = { ...current[channel], [ticketType]: mode }
+ actions.updateCurrentTeam({
+ conversations_settings: {
+ ...values.currentTeam?.conversations_settings,
+ ai_reply_modes: { ...current, [channel]: channelModes },
+ },
+ })
+ },
connectGithub: async ({ integrationId }) => {
try {
// nosemgrep: prefer-codegen-api