:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(conversations): make ticket reply UI honest about email delivery (#69209)
Abigailc5d12090bb93
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d258c7dd0b10..cf452a510011 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6087,9 +6087,9 @@ snapshots:scenes-app-mcp-analytics--sessions--light:hash: v1.k794b7964.8a6b42b3e994bb9f035951d84f071f2d7c20756f9745281f61e3383133bd5bb5.GxtTX98b-FQFH6zFqQLhs-oEq7qO_vVqKjJS-CBN77Uscenes-app-mcp-analytics--tool-quality--dark:- hash: v1.k794b7964.6f5a4a5ffb216309a2db8c0e3f27560058f556e93624699e25a960efb03c569b.CZfkEDjT7nwC_oOWfYXVWwuB6LK1LpYCitM8ot_YfhM+ hash: v1.k794b7964.d4227f0ef61e4a1f092fde543c1a8dc62f0f05e0488f2b15fc9f3c3f902954e8.DsFDnzZRkS66upVNo75VlLqrgFFhXOXF8aJVLUtBZ1sscenes-app-mcp-analytics--tool-quality--light:- hash: v1.k794b7964.ad0afc1d54e6b1e1636b111f6b5441963db055864379e1546baa8044638441c1.d5yYULnG731hp03Bh0veJtL14UcVQ27Nwz448eTDDiM+ hash: v1.k794b7964.04a9b39c28f16ad4b5a1b2625115e68768273cc7b66548fcbc5754a8f48aaac6.varhLyKH9GufBWEUlArceEOjryAzqMHvXgGzy-6VecYscenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--dark:hash: v1.k794b7964.2d8dc7d50a9b0bb18090a2e5c29368e12754c133f5029fba10515afca766c9a4.6cPWYhvNfeMHrXHSOz8R-IvwxmTOlpko0UXkl4g920Iscenes-app-mcp-analytics-dashboard-cards--daily-calls-and-errors--light:diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.pyindex 08a428950572..dc9c0e908bc1 100644--- a/products/conversations/backend/api/tests/test_email_endpoints.py+++ b/products/conversations/backend/api/tests/test_email_endpoints.py@@ -918,6 +918,51 @@ class TestSendEmailReplyMultiConfig(BaseTest):assert outbox.status == EmailOutboxMessage.Status.SENTassert outbox.sent_at is not None+ @parameterized.expand(+ [+ ("email_disabled", "email disabled for team"),+ ("no_email_config", "no email config"),+ ("no_customer_email", "no customer email"),+ ]+ )+ @patch("products.conversations.backend.tasks.send_mime")+ def test_undeliverable_reply_fails_visibly(self, name: str, expected_error: str, mock_send_mime: MagicMock):+ from products.conversations.backend.tasks import send_email_reply++ config = self._create_config("[email protected]", "aaa111")+ if name == "email_disabled":+ ticket = self._create_ticket(config)+ self.team.conversations_settings = {"email_enabled": False}+ self.team.save()+ elif name == "no_email_config":+ ticket = self._create_ticket(None)+ else:+ ticket = self._create_ticket(config)+ ticket.email_from = None+ ticket.save(update_fields=["email_from"])++ comment = Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content="Reply from agent",+ created_by=self.user,+ item_context={"author_type": "support"},+ )+ # The signal must create the row even for undeliverable replies; skipping it would+ # leave the reply with no delivery record at all.+ outbox = EmailOutboxMessage.objects.filter(comment=comment).first()+ assert outbox is not None++ send_email_reply(str(outbox.id))+ outbox.refresh_from_db()++ assert outbox.status == EmailOutboxMessage.Status.FAILED_PERMANENT+ assert outbox.last_error == expected_error+ mock_send_mime.assert_not_called()+ comment.refresh_from_db()+ assert (comment.item_context or {}).get("email_delivery_status") == "failed"+@parameterized.expand([# name, error raised by send_mime, whether it flips the domain back to unverifieddiff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex 618ab046d72d..d39c43bfcd50 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -1992,7 +1992,12 @@ class TestTicketReplyAPI(APIBaseTest):assert comment.created_by == self.userassert comment.scope == "conversations_ticket"assert comment.item_id == str(self.ticket.id)- assert comment.item_context == {"author_type": "support", "is_private": is_private}+ expected_context = {"author_type": "support", "is_private": is_private}+ if not is_private:+ # Public replies on an email ticket always get an outbox row; this team has no+ # email channel, so delivery fails immediately and stamps the comment.+ expected_context["email_delivery_status"] = "failed"+ assert comment.item_context == expected_contextdef test_reply_defaults_is_private_to_false(self, mock_on_commit):response = self.client.post(self.url, {"message": "Hi"}, format="json")diff --git a/products/conversations/backend/signals.py b/products/conversations/backend/signals.pyindex f6ee4237a16b..cf9eacd02862 100644--- a/products/conversations/backend/signals.py+++ b/products/conversations/backend/signals.py@@ -391,12 +391,13 @@ def send_email_reply_on_team_message(sender, instance: Comment, created: bool, *.filter(id=item_id, team_id=team_id, channel_source=Channel.EMAIL).first())- if not ticket or not ticket.email_from:+ if not ticket:return- settings_dict = ticket.team.conversations_settings or {}- if not settings_dict.get("email_enabled"):- return+ # Deliverability verdicts (team email_enabled, customer address, channel config) are NOT+ # checked here: every customer-facing reply on an email ticket gets an outbox row, and+ # _process_outbox_row fails undeliverable ones with a reason. Skipping row creation instead+ # would leave the reply looking sent in the agent UI, with no record of why nothing went out.config = ticket.email_configinbound_domain = get_instance_setting("CONVERSATIONS_EMAIL_INBOUND_DOMAIN") or (config.domain if config else None)diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.pyindex 57b81e826b8b..bfd2c836c0e2 100644--- a/products/conversations/backend/tasks.py+++ b/products/conversations/backend/tasks.py@@ -661,6 +661,10 @@ def _process_outbox_row(outbox: EmailOutboxMessage) -> None:config = ticket.email_configcomment = outbox.comment+ settings_dict = ticket.team.conversations_settings or {}+ if not settings_dict.get("email_enabled"):+ _mark_outbox_failed(outbox, "email disabled for team")+ returnif not config:_mark_outbox_failed(outbox, "no email config")return@@ -763,7 +767,7 @@ def _claim_outbox_row(outbox_id: str) -> EmailOutboxMessage | None:# nullable email_config FK, and Postgres can't FOR UPDATE an outer-join side.outbox = (EmailOutboxMessage.objects.select_for_update(skip_locked=True, of=("self",))- .select_related("ticket", "ticket__email_config", "comment", "comment__created_by")+ .select_related("ticket", "ticket__team", "ticket__email_config", "comment", "comment__created_by").filter(id=outbox_id, status=EmailOutboxMessage.Status.PENDING).filter(models.Q(locked_until__isnull=True) | models.Q(locked_until__lte=now)).first()@@ -808,7 +812,7 @@ def flush_pending_email_replies() -> None:with transaction.atomic():batch = list(EmailOutboxMessage.objects.select_for_update(skip_locked=True, of=("self",))- .select_related("ticket", "ticket__email_config", "comment", "comment__created_by")+ .select_related("ticket", "ticket__team", "ticket__email_config", "comment", "comment__created_by").filter(status=EmailOutboxMessage.Status.PENDING, next_attempt_at__lte=now).filter(models.Q(locked_until__isnull=True) | models.Q(locked_until__lte=now)).order_by("next_attempt_at")[:EMAIL_OUTBOX_FLUSH_BATCH_SIZE]diff --git a/products/conversations/frontend/components/Chat/ChatView.tsx b/products/conversations/frontend/components/Chat/ChatView.tsxindex 35c6c224951e..f6bb21cf6089 100644--- a/products/conversations/frontend/components/Chat/ChatView.tsx+++ b/products/conversations/frontend/components/Chat/ChatView.tsx@@ -34,6 +34,8 @@ export interface ChatViewProps {onPrivateChange?: (isPrivate: boolean) => void/** Extra actions rendered next to the send button in MessageInput */extraActions?: React.ReactNode+ /** Blocks sending customer-facing messages (private notes stay available) */+ replyDisabledReason?: string | JSX.ElementlatestAiMessageId?: string | nullfeedbackByMessageId?: Record<string, AiReplyFeedbackRating>showAiReplyFeedback?: boolean@@ -59,6 +61,7 @@ export function ChatView({isPrivate,onPrivateChange,extraActions,+ replyDisabledReason,latestAiMessageId,feedbackByMessageId,showAiReplyFeedback,@@ -96,6 +99,7 @@ export function ChatView({isPrivate={isPrivate}onPrivateChange={onPrivateChange}extraActions={extraActions}+ replyDisabledReason={replyDisabledReason}/></div></LemonCard>diff --git a/products/conversations/frontend/components/Chat/MessageInput.tsx b/products/conversations/frontend/components/Chat/MessageInput.tsxindex 8152b11733b8..efd7bdea25ec 100644--- a/products/conversations/frontend/components/Chat/MessageInput.tsx+++ b/products/conversations/frontend/components/Chat/MessageInput.tsx@@ -26,6 +26,8 @@ export interface MessageInputProps {onPrivateChange?: (isPrivate: boolean) => void/** Extra actions rendered next to the send button */extraActions?: React.ReactNode+ /** Blocks sending customer-facing messages (private notes stay available). Shown as the button's disabled tooltip. */+ replyDisabledReason?: string | JSX.Element}export function MessageInput({@@ -40,6 +42,7 @@ export function MessageInput({isPrivate: controlledIsPrivate,onPrivateChange,extraActions,+ replyDisabledReason,}: MessageInputProps): JSX.Element {const [isEmpty, setIsEmpty] = useState(!draftContent)const [isUploading, setIsUploading] = useState(false)@@ -55,6 +58,10 @@ export function MessageInput({const setIsPrivate = onPrivateChange ?? setLocalIsPrivateconst handleSubmit = (): void => {+ // Guards the Cmd+Enter path too, not just the (disabled) button+ if (replyDisabledReason && !isPrivate) {+ return+ }if (editorRef.current && !isEmpty) {const richContent = editorRef.current.getJSON()const content = serializeToMarkdown(richContent)@@ -121,7 +128,15 @@ export function MessageInput({type="primary"onClick={handleSubmit}loading={messageSending}- disabledReason={isEmpty ? 'No message' : isUploading ? 'Uploading image...' : undefined}+ disabledReason={+ replyDisabledReason && !isPrivate+ ? replyDisabledReason+ : isEmpty+ ? 'No message'+ : isUploading+ ? 'Uploading image...'+ : undefined+ }>{isPrivate ? 'Attach' : buttonText}</LemonButton>diff --git a/products/conversations/frontend/scenes/settings/ZendeskImportSection.tsx b/products/conversations/frontend/scenes/settings/ZendeskImportSection.tsxindex 894c4a9bdf67..2c8016c065f9 100644--- a/products/conversations/frontend/scenes/settings/ZendeskImportSection.tsx+++ b/products/conversations/frontend/scenes/settings/ZendeskImportSection.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { LemonButton, LemonCard, LemonInput, LemonSelect, LemonTag } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonCard, LemonInput, LemonSelect, LemonTag } from '@posthog/lemon-ui'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'import { OrganizationMembershipLevel } from 'lib/constants'@@ -141,6 +141,13 @@ function ZendeskImportForm(): JSX.Element {]}/></LemonField.Pure>+ {defaultEmailChannelId === null && !isImportRunning && (+ <LemonBanner type="warning">+ Without a default inbox, tickets whose Zendesk address doesn't match one of your connected support+ addresses are imported without an email channel. Agents won't be able to reply to those customers by+ email, and the reply box on those tickets will be disabled.+ </LemonBanner>+ )}<div><LemonButtontype="primary"diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsxindex fcf9362c7f4c..ba0b5971ace3 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -84,6 +84,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemsnoozedUntil,knowledgeGaps,knowledgeGapsLoading,+ emailReplyBlockedReason,latestAiMessage,feedbackByMessageId,} = useValues(logic)@@ -106,6 +107,30 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elemconst { currentTeam } = useValues(teamLogic)const aiSuggestionsEnabled = !!currentTeam?.conversations_settings?.ai_suggestions_enabled+ const conversationsSettingsUrl = urls.settings('environment-conversations', 'conversations-general')+ const replyDisabledReason: JSX.Element | undefined = emailReplyBlockedReason+ ? {+ email_disabled: (+ <>+ Replies can't be emailed because this project has no connected email channel.{' '}+ <Link to={conversationsSettingsUrl}>Connect an email address</Link> to reply to this customer.+ </>+ ),+ no_recipient: (+ <>+ This ticket has no customer email address, so a reply can't be delivered. You can still attach a+ private note.+ </>+ ),+ no_channel: (+ <>+ This ticket isn't linked to any of your email channels, so replies can't be sent.{' '}+ <Link to={conversationsSettingsUrl}>Manage email channels</Link>+ </>+ ),+ }[emailReplyBlockedReason]+ : undefined+const chatPanelRef = useRef<HTMLDivElement>(null)const resizerLogicProps: ResizerLogicProps = {@@ -184,6 +209,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemonDraftChange={setDraftContent}isPrivate={draftIsPrivate}onPrivateChange={setDraftIsPrivate}+ replyDisabledReason={replyDisabledReason}minHeight="min(400px, calc(100svh - 20rem))"maxHeight="calc(100svh - 20rem)"latestAiMessageId={latestAiMessage?.id ?? null}diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.tsindex 26459f6f08a8..f23904c4e82e 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts@@ -4,7 +4,7 @@ import { initKeaTests } from '~/test/init'import type { CommentType } from '~/types'import type { Ticket } from '../../types'-import { supportTicketSceneLogic } from './supportTicketSceneLogic'+import { EmailReplyBlockedReason, getEmailReplyBlockedReason, supportTicketSceneLogic } from './supportTicketSceneLogic'const FEEDBACK_STORAGE_KEY = 'conversations_ai_reply_feedback'@@ -142,3 +142,39 @@ describe('supportTicketSceneLogic ai reply feedback', () => {expect(logic.values.feedbackByMessageId['msg-ai-1']).toBe('good')})})++type GateTicket = Pick<Ticket, 'channel_source' | 'email_from' | 'email_to'>++const emailTicket = (overrides: Partial<GateTicket> = {}): GateTicket => ({+ channel_source: 'email',+ email_from: '[email protected]',+ email_to: '[email protected]',+ ...overrides,+})++describe('getEmailReplyBlockedReason', () => {+ // Each gate mirrors a backend condition that silently drops delivery: removing one+ // reintroduces replies that save as comments but never reach the customer, while+ // breaking the channel_source guard would disable the reply box on non-email tickets.+ test.each<[string, GateTicket | null, { email_enabled?: boolean } | null, EmailReplyBlockedReason | null]>([+ ['widget tickets are never blocked', emailTicket({ channel_source: 'widget' }), null, null],+ ['no ticket loaded yet', null, { email_enabled: true }, null],+ ['email disabled on team', emailTicket(), { email_enabled: false }, 'email_disabled'],+ ['conversations settings missing', emailTicket(), null, 'email_disabled'],+ [+ 'no customer address (e.g. imported ticket with deleted requester)',+ emailTicket({ email_from: null }),+ { email_enabled: true },+ 'no_recipient',+ ],+ [+ 'no email channel attached (e.g. imported ticket without default inbox)',+ emailTicket({ email_to: null }),+ { email_enabled: true },+ 'no_channel',+ ],+ ['fully configured email ticket', emailTicket(), { email_enabled: true }, null],+ ])('%s', (_name, ticket, settings, expected) => {+ expect(getEmailReplyBlockedReason(ticket, settings)).toBe(expected)+ })+})diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex 18cb32cff3be..dd1dd0719b08 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -7,6 +7,7 @@ import { lemonToast } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'import { getCurrentTeamId } from 'lib/utils/getAppContext'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { impersonationNoticeLogic } from '~/layout/navigation/ImpersonationNotice/impersonationNoticeLogic'@@ -120,12 +121,39 @@ function createExceptionsQuery(sessionId?: string, ticketCreatedAt?: string): Da}}+/** Why a customer-facing email reply on this ticket can never be delivered. */+export type EmailReplyBlockedReason = 'email_disabled' | 'no_recipient' | 'no_channel'++/**+ * Mirrors the backend gates in send_email_reply_on_team_message / _process_outbox_row:+ * a reply that fails any of these is saved as a comment but never delivered.+ */+export function getEmailReplyBlockedReason(+ ticket: Pick<Ticket, 'channel_source' | 'email_from' | 'email_to'> | null,+ conversationsSettings: { email_enabled?: boolean } | null | undefined+): EmailReplyBlockedReason | null {+ if (ticket?.channel_source !== 'email') {+ return null+ }+ if (!conversationsSettings?.email_enabled) {+ return 'email_disabled'+ }+ if (!ticket.email_from) {+ return 'no_recipient'+ }+ if (!ticket.email_to) {+ return 'no_channel'+ }+ return null+}+export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([path(['products', 'conversations', 'frontend', 'scenes', 'ticket', 'supportTicketSceneLogic']),props({ id: 'new' as string | number }),key((props) => props.id),connect(() => ({actions: [supportTicketsSceneLogic, ['loadTickets']],+ values: [teamLogic, ['currentTeam']],})),actions({loadTicket: true,@@ -377,6 +405,11 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([],}),selectors({+ emailReplyBlockedReason: [+ (s) => [s.ticket, s.currentTeam],+ (ticket, currentTeam): EmailReplyBlockedReason | null =>+ getEmailReplyBlockedReason(ticket, currentTeam?.conversations_settings),+ ],hasUnsavedChanges: [(s) => [s.status, s.priority, s.assignee, s.tags, s.snoozedUntil, s.ticket],(status, priority, assignee, tags, snoozedUntil, ticket): boolean => {@@ -632,7 +665,9 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([},{})- lemonToast.success(isPrivate ? 'Private message sent' : 'Message sent')+ // "Added", not "sent": email delivery is async (outbox + Celery) and can still fail+ // after this API call succeeds; the per-message delivery status is the send signal.+ lemonToast.success(isPrivate ? 'Private note added' : 'Reply added')actions.setMessageSending(false)onSuccess?.()if (!isPrivate) {