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 ai reply reviewer feedback (#69212)

Alex V733998c338e8
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index f9f86bc890ca..5dab268f4e3d 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -7099,6 +7099,13 @@ const api = {
.withAction('bulk_update_status')
.create({ data: { ids, status: ticketStatus } })
},
+
+ async submitAiFeedback(
+ ticketId: string,
+ data: { message_id: string; rating: 'good' | 'bad'; feedback_text?: string }
+ ): Promise<void> {
+ await new ApiRequest().conversationsTicket(ticketId).withAction('ai_feedback').create({ data })
+ },
},
llmPrompts: {
diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.py
index e799d360be84..618ab046d72d 100644
--- a/products/conversations/backend/api/tests/test_tickets.py
+++ b/products/conversations/backend/api/tests/test_tickets.py
@@ -2076,3 +2076,78 @@ class TestTicketReplyAPI(APIBaseTest):
serializer = TicketReplyRequestSerializer(data={"message": "hi", "rich_content": {"amount": Decimal("1.2")}})
assert not serializer.is_valid()
assert "rich_content" in serializer.errors
+
+
[email protected](transaction, "on_commit", side_effect=immediate_on_commit)
+class TestAiFeedbackAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.ticket = Ticket.objects.create_with_number(
+ team=self.team,
+ channel_source=Channel.WIDGET,
+ widget_session_id="ai-feedback-session",
+ distinct_id="user-123",
+ status=Status.OPEN,
+ ai_triage={
+ "status": "done",
+ "result": "persisted",
+ "confidence": 0.92,
+ "ai_trace_id": "trace-abc",
+ },
+ )
+ self.url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/ai_feedback/"
+
+ @patch("products.conversations.backend.api.tickets.posthoganalytics.capture")
+ def test_ai_feedback_captures_metric_on_rating(self, mock_capture, mock_on_commit):
+ response = self.client.post(
+ self.url,
+ {"message_id": "msg-1", "rating": "good"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_202_ACCEPTED
+ mock_capture.assert_called_once()
+ _, kwargs = mock_capture.call_args
+ assert kwargs["event"] == "$ai_metric"
+ assert kwargs["properties"]["$ai_metric_name"] == "reviewer_quality"
+ assert kwargs["properties"]["$ai_metric_value"] == 1
+ assert kwargs["properties"]["$ai_trace_id"] == "trace-abc"
+ assert kwargs["properties"]["ticket_id"] == str(self.ticket.id)
+ assert kwargs["properties"]["message_id"] == "msg-1"
+ assert kwargs["properties"]["ai_triage_result"] == "persisted"
+ assert kwargs["properties"]["confidence"] == 0.92
+
+ @parameterized.expand(
+ [
+ ("bad_without_text", {"message_id": "msg-1", "rating": "bad"}, "$ai_metric", 0),
+ (
+ "bad_with_text",
+ {"message_id": "msg-1", "rating": "bad", "feedback_text": "Wrong answer"},
+ "$ai_feedback",
+ None,
+ ),
+ ]
+ )
+ @patch("products.conversations.backend.api.tickets.posthoganalytics.capture")
+ def test_ai_feedback_metric_vs_text_are_mutually_exclusive(
+ self, _name, payload, expected_event, expected_metric_value, mock_capture, mock_on_commit
+ ):
+ response = self.client.post(self.url, payload, format="json")
+ assert response.status_code == status.HTTP_202_ACCEPTED
+ mock_capture.assert_called_once()
+ _, kwargs = mock_capture.call_args
+ assert kwargs["event"] == expected_event
+ if expected_event == "$ai_metric":
+ assert kwargs["properties"]["$ai_metric_value"] == expected_metric_value
+ assert "$ai_feedback_text" not in kwargs["properties"]
+ else:
+ assert kwargs["properties"]["$ai_feedback_text"] == "Wrong answer"
+ assert "$ai_metric_name" not in kwargs["properties"]
+ assert kwargs["properties"]["$ai_trace_id"] == "trace-abc"
+
+ def test_ai_feedback_rejects_invalid_rating(self, mock_on_commit):
+ response = self.client.post(
+ self.url,
+ {"message_id": "msg-1", "rating": "meh"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.py
index 054dedd5bca8..ea47e6db8161 100644
--- a/products/conversations/backend/api/tickets.py
+++ b/products/conversations/backend/api/tickets.py
@@ -4,6 +4,7 @@ import json
import uuid
from collections.abc import Sequence
from datetime import timedelta
+from typing import Any
from django.db import transaction
from django.db.models import CharField, Exists, OuterRef, Q, QuerySet, Sum
@@ -12,6 +13,7 @@ from django.http import Http404
from django.utils import timezone
import structlog
+import posthoganalytics
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_view
from rest_framework import (
@@ -116,6 +118,16 @@ class TicketReplyRequestSerializer(serializers.Serializer):
return value
+class AiFeedbackRequestSerializer(serializers.Serializer):
+ """Payload for recording reviewer feedback on an AI reply."""
+
+ message_id = serializers.CharField(max_length=200, help_text="ID of the AI message being rated.")
+ rating = serializers.ChoiceField(choices=["good", "bad"], help_text="Reviewer rating: good or bad.")
+ feedback_text = serializers.CharField(
+ required=False, allow_blank=True, max_length=2000, help_text="Optional text explaining a bad rating."
+ )
+
+
class ComposeTicketSerializer(serializers.Serializer):
recipient_email = serializers.EmailField(
help_text="Recipient email address.",
@@ -340,7 +352,7 @@ TICKET_ID_PARAM = OpenApiParameter(
class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "ticket"
scope_object_read_actions = ["list", "retrieve", "unread_count", "messages"]
- scope_object_write_actions = ["create", "update", "partial_update", "patch", "compose", "reply"]
+ scope_object_write_actions = ["create", "update", "partial_update", "patch", "compose", "reply", "ai_feedback"]
queryset = Ticket.objects.all()
serializer_class = TicketSerializer
permission_classes = [IsAuthenticated, APIScopePermission]
@@ -1136,6 +1148,53 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Mod
status=drf_status.HTTP_201_CREATED,
)
+ @extend_schema(
+ parameters=[TICKET_ID_PARAM],
+ request=AiFeedbackRequestSerializer,
+ responses={202: None},
+ )
+ @action(detail=True, methods=["post"])
+ def ai_feedback(self, request, *args, **kwargs):
+ """Record reviewer feedback on an AI reply, captured to the internal analytics project."""
+ ticket = self.get_object()
+ serializer = AiFeedbackRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+
+ ai_triage = ticket.ai_triage or {}
+ trace_id = ai_triage.get("ai_trace_id")
+ distinct_id = f"reviewer:{request.user.distinct_id}"
+
+ feedback_text = data.get("feedback_text", "").strip()
+
+ if feedback_text and data["rating"] == "bad":
+ feedback_properties: dict[str, Any] = {
+ "$ai_feedback_text": feedback_text,
+ "ai_product": "conversations",
+ "ticket_id": str(ticket.id),
+ "message_id": data["message_id"],
+ "ai_triage_result": ai_triage.get("result"),
+ "confidence": ai_triage.get("confidence"),
+ }
+ if trace_id:
+ feedback_properties["$ai_trace_id"] = trace_id
+ posthoganalytics.capture(distinct_id=distinct_id, event="$ai_feedback", properties=feedback_properties)
+ else:
+ properties: dict[str, Any] = {
+ "$ai_metric_name": "reviewer_quality",
+ "$ai_metric_value": 1 if data["rating"] == "good" else 0,
+ "ai_product": "conversations",
+ "ticket_id": str(ticket.id),
+ "message_id": data["message_id"],
+ "ai_triage_result": ai_triage.get("result"),
+ "confidence": ai_triage.get("confidence"),
+ }
+ if trace_id:
+ properties["$ai_trace_id"] = trace_id
+ posthoganalytics.capture(distinct_id=distinct_id, event="$ai_metric", properties=properties)
+
+ return Response(status=drf_status.HTTP_202_ACCEPTED)
+
@extend_schema(
request=ComposeTicketSerializer,
responses={
diff --git a/products/conversations/frontend/components/Chat/ChatView.tsx b/products/conversations/frontend/components/Chat/ChatView.tsx
index 6f86ee6b5dc2..35c6c224951e 100644
--- a/products/conversations/frontend/components/Chat/ChatView.tsx
+++ b/products/conversations/frontend/components/Chat/ChatView.tsx
@@ -2,7 +2,7 @@ import { JSONContent } from '@tiptap/core'
import { LemonCard } from '@posthog/lemon-ui'
-import type { ChatMessage, Ticket } from '../../types'
+import type { AiReplyFeedbackRating, ChatMessage, Ticket } from '../../types'
import { MessageInput } from './MessageInput'
import { MessageList } from './MessageList'
@@ -34,6 +34,10 @@ export interface ChatViewProps {
onPrivateChange?: (isPrivate: boolean) => void
/** Extra actions rendered next to the send button in MessageInput */
extraActions?: React.ReactNode
+ latestAiMessageId?: string | null
+ feedbackByMessageId?: Record<string, AiReplyFeedbackRating>
+ showAiReplyFeedback?: boolean
+ onSubmitAiReplyFeedback?: (messageId: string, rating: AiReplyFeedbackRating, feedbackText?: string) => void
}
export function ChatView({
@@ -55,6 +59,10 @@ export function ChatView({
isPrivate,
onPrivateChange,
extraActions,
+ latestAiMessageId,
+ feedbackByMessageId,
+ showAiReplyFeedback,
+ onSubmitAiReplyFeedback,
}: ChatViewProps): JSX.Element {
const listMinHeight = minHeight ?? '400px'
const listMaxHeight = maxHeight ?? '600px'
@@ -73,6 +81,10 @@ export function ChatView({
maxHeight={listMaxHeight}
unreadCustomerCount={unreadCustomerCount}
showDeliveryStatus={showDeliveryStatus}
+ latestAiMessageId={latestAiMessageId}
+ feedbackByMessageId={feedbackByMessageId}
+ showAiReplyFeedback={showAiReplyFeedback}
+ onSubmitAiReplyFeedback={onSubmitAiReplyFeedback}
/>
<div className="border-t pt-3">
<MessageInput
diff --git a/products/conversations/frontend/components/Chat/Message.tsx b/products/conversations/frontend/components/Chat/Message.tsx
index 8da2729f13d2..0c62855af073 100644
--- a/products/conversations/frontend/components/Chat/Message.tsx
+++ b/products/conversations/frontend/components/Chat/Message.tsx
@@ -1,23 +1,66 @@
import { JSONContent } from '@tiptap/core'
+import { useRef, useState } from 'react'
-import { IconCopy, IconLock, IconWarning } from '@posthog/icons'
-import { LemonButton, ProfilePicture, Tooltip } from '@posthog/lemon-ui'
+import {
+ IconCopy,
+ IconLock,
+ IconThumbsDown,
+ IconThumbsDownFilled,
+ IconThumbsUp,
+ IconThumbsUpFilled,
+ IconWarning,
+} from '@posthog/icons'
+import { LemonButton, LemonInput, ProfilePicture, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
-import type { ChatMessage, MessageDeliveryStatus } from '../../types'
+import type { AiReplyFeedbackRating, ChatMessage, MessageDeliveryStatus } from '../../types'
import { SupportMarkdown, SupportRichContentPreview } from '../Editor'
export interface MessageProps {
message: ChatMessage
isCustomer: boolean
deliveryStatus?: MessageDeliveryStatus
+ showAiReplyFeedback?: boolean
+ aiReplyFeedbackRating?: AiReplyFeedbackRating | null
+ onSubmitAiReplyFeedback?: (rating: AiReplyFeedbackRating, feedbackText?: string) => void
}
-export function Message({ message, isCustomer, deliveryStatus }: MessageProps): JSX.Element {
+export function Message({
+ message,
+ isCustomer,
+ deliveryStatus,
+ showAiReplyFeedback = false,
+ aiReplyFeedbackRating = null,
+ onSubmitAiReplyFeedback,
+}: MessageProps): JSX.Element {
const profileType = message.authorType === 'AI' ? 'bot' : 'person'
const isPrivate = message.isPrivate
+ const [feedbackText, setFeedbackText] = useState('')
+ const [feedbackTextSubmitted, setFeedbackTextSubmitted] = useState(false)
+ const wasRatedOnMount = useRef(!!aiReplyFeedbackRating)
+ const showBadFeedbackInput =
+ showAiReplyFeedback &&
+ aiReplyFeedbackRating === 'bad' &&
+ !wasRatedOnMount.current &&
+ !feedbackTextSubmitted &&
+ !!onSubmitAiReplyFeedback
+
+ function submitRating(rating: AiReplyFeedbackRating): void {
+ if (aiReplyFeedbackRating || !onSubmitAiReplyFeedback) {
+ return
+ }
+ onSubmitAiReplyFeedback(rating)
+ }
+
+ function submitBadFeedbackText(): void {
+ if (!feedbackText.trim() || !onSubmitAiReplyFeedback) {
+ return
+ }
+ onSubmitAiReplyFeedback('bad', feedbackText.trim())
+ setFeedbackTextSubmitted(true)
+ }
return (
<div className={`flex ${isCustomer ? 'mr-10' : 'flex-row-reverse ml-10'} mb-4`}>
@@ -74,6 +117,76 @@ export function Message({ message, isCustomer, deliveryStatus }: MessageProps):
</SupportMarkdown>
)}
</div>
+ {showAiReplyFeedback && (
+ <div className="mt-1.5 space-y-1.5">
+ <div className="flex items-center gap-1">
+ {aiReplyFeedbackRating !== 'bad' && (
+ <LemonButton
+ icon={
+ aiReplyFeedbackRating === 'good' ? (
+ <IconThumbsUpFilled />
+ ) : (
+ <IconThumbsUp />
+ )
+ }
+ type="tertiary"
+ size="xsmall"
+ tooltip="Good reply"
+ disabledReason={
+ aiReplyFeedbackRating ? 'Feedback already recorded' : undefined
+ }
+ onClick={() => submitRating('good')}
+ data-attr="ai-reply-feedback-good"
+ />
+ )}
+ {aiReplyFeedbackRating !== 'good' && (
+ <LemonButton
+ icon={
+ aiReplyFeedbackRating === 'bad' ? (
+ <IconThumbsDownFilled />
+ ) : (
+ <IconThumbsDown />
+ )
+ }
+ type="tertiary"
+ size="xsmall"
+ tooltip="Bad reply"
+ disabledReason={
+ aiReplyFeedbackRating ? 'Feedback already recorded' : undefined
+ }
+ onClick={() => submitRating('bad')}
+ data-attr="ai-reply-feedback-bad"
+ />
+ )}
+ </div>
+ {showBadFeedbackInput && (
+ <div className="flex w-full gap-1.5 items-center">
+ <LemonInput
+ placeholder="What was wrong with this reply?"
+ fullWidth
+ size="small"
+ value={feedbackText}
+ onChange={setFeedbackText}
+ onPressEnter={submitBadFeedbackText}
+ autoFocus
+ />
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={submitBadFeedbackText}
+ disabledReason={
+ !feedbackText.trim() ? 'Please type a few words' : undefined
+ }
+ >
+ Submit
+ </LemonButton>
+ </div>
+ )}
+ {aiReplyFeedbackRating === 'bad' && feedbackTextSubmitted && (
+ <span className="text-xs text-muted-alt">Thanks for your feedback</span>
+ )}
+ </div>
+ )}
<div className="flex items-center justify-end gap-1">
{message.emailDeliveryStatus === 'failed' ? (
<Tooltip title="We couldn't deliver this email reply. Please check the email channel settings and contact support if the issue persists.">
diff --git a/products/conversations/frontend/components/Chat/MessageList.tsx b/products/conversations/frontend/components/Chat/MessageList.tsx
index 459f4436978a..7621ff8a09aa 100644
--- a/products/conversations/frontend/components/Chat/MessageList.tsx
+++ b/products/conversations/frontend/components/Chat/MessageList.tsx
@@ -2,7 +2,7 @@ import { useEffect, useRef } from 'react'
import { Spinner } from '@posthog/lemon-ui'
-import type { ChatMessage, MessageDeliveryStatus } from '../../types'
+import type { AiReplyFeedbackRating, ChatMessage, MessageDeliveryStatus } from '../../types'
import { Message } from './Message'
export interface MessageListProps {
@@ -21,6 +21,13 @@ export interface MessageListProps {
unreadCustomerCount?: number
/** Whether to show delivery status on team messages */
showDeliveryStatus?: boolean
+ /** ID of the latest AI message eligible for reviewer feedback */
+ latestAiMessageId?: string | null
+ /** Recorded reviewer feedback keyed by message id */
+ feedbackByMessageId?: Record<string, AiReplyFeedbackRating>
+ /** Whether AI reply feedback controls are enabled */
+ showAiReplyFeedback?: boolean
+ onSubmitAiReplyFeedback?: (messageId: string, rating: AiReplyFeedbackRating, feedbackText?: string) => void
}
export function MessageList({
@@ -36,6 +43,10 @@ export function MessageList({
isCustomerView = false,
unreadCustomerCount = 0,
showDeliveryStatus = false,
+ latestAiMessageId = null,
+ feedbackByMessageId = {},
+ showAiReplyFeedback = false,
+ onSubmitAiReplyFeedback,
}: MessageListProps): JSX.Element {
const messagesEndRef = useRef<HTMLDivElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
@@ -120,6 +131,18 @@ export function MessageList({
message={message}
isCustomer={isCustomerView ? !isCustomer : isCustomer}
deliveryStatus={deliveryStatusMap.get(message.id)}
+ showAiReplyFeedback={
+ showAiReplyFeedback &&
+ message.id === latestAiMessageId &&
+ message.authorType === 'AI'
+ }
+ aiReplyFeedbackRating={feedbackByMessageId[message.id] ?? null}
+ onSubmitAiReplyFeedback={
+ onSubmitAiReplyFeedback
+ ? (rating, feedbackText) =>
+ onSubmitAiReplyFeedback(message.id, rating, feedbackText)
+ : undefined
+ }
/>
)
})}
diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.ts
index 704b08b15314..96c45aee33fe 100644
--- a/products/conversations/frontend/generated/api.schemas.ts
+++ b/products/conversations/frontend/generated/api.schemas.ts
@@ -834,6 +834,38 @@ export interface PatchedTicketApi {
tags?: unknown[]
}
+/**
+ * * `good` - good
+ * * `bad` - bad
+ */
+export type RatingEnumApi = (typeof RatingEnumApi)[keyof typeof RatingEnumApi]
+
+export const RatingEnumApi = {
+ Good: 'good',
+ Bad: 'bad',
+} as const
+
+/**
+ * Payload for recording reviewer feedback on an AI reply.
+ */
+export interface AiFeedbackRequestApi {
+ /**
+ * ID of the AI message being rated.
+ * @maxLength 200
+ */
+ message_id: string
+ /** Reviewer rating: good or bad.
+ *
+ * * `good` - good
+ * * `bad` - bad */
+ rating: RatingEnumApi
+ /**
+ * Optional text explaining a bad rating.
+ * @maxLength 2000
+ */
+ feedback_text?: string
+}
+
/**
* A single message in a ticket thread (output-only).
*/
diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.ts
index d0419d7db510..99f75b7d1974 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 {
+ AiFeedbackRequestApi,
BulkUpdateStatusRequestApi,
BulkUpdateStatusResponseApi,
BulkUpdateTagsRequestApi,
@@ -408,6 +409,27 @@ export const conversationsTicketsDestroy = async (
})
}
+export const getConversationsTicketsAiFeedbackCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/conversations/tickets/${id}/ai_feedback/`
+}
+
+/**
+ * Record reviewer feedback on an AI reply, captured to the internal analytics project.
+ */
+export const conversationsTicketsAiFeedbackCreate = async (
+ projectId: string,
+ id: string,
+ aiFeedbackRequestApi: AiFeedbackRequestApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getConversationsTicketsAiFeedbackCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(aiFeedbackRequestApi),
+ })
+}
+
export const getConversationsTicketsMessagesListUrl = (
projectId: string,
id: string,
diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.ts
index 1cd612dbffb8..fc2c056ee713 100644
--- a/products/conversations/frontend/generated/api.zod.ts
+++ b/products/conversations/frontend/generated/api.zod.ts
@@ -254,6 +254,31 @@ export const ConversationsTicketsPartialUpdateBody = /* @__PURE__ */ zod
})
.describe('Serializer mixin that handles tags for objects.')
+/**
+ * Record reviewer feedback on an AI reply, captured to the internal analytics project.
+ */
+export const conversationsTicketsAiFeedbackCreateBodyMessageIdMax = 200
+
+export const conversationsTicketsAiFeedbackCreateBodyFeedbackTextMax = 2000
+
+export const ConversationsTicketsAiFeedbackCreateBody = /* @__PURE__ */ zod
+ .object({
+ message_id: zod
+ .string()
+ .max(conversationsTicketsAiFeedbackCreateBodyMessageIdMax)
+ .describe('ID of the AI message being rated.'),
+ rating: zod
+ .enum(['good', 'bad'])
+ .describe('\* `good` - good\n\* `bad` - bad')
+ .describe('Reviewer rating: good or bad.\n\n\* `good` - good\n\* `bad` - bad'),
+ feedback_text: zod
+ .string()
+ .max(conversationsTicketsAiFeedbackCreateBodyFeedbackTextMax)
+ .optional()
+ .describe('Optional text explaining a bad rating.'),
+ })
+ .describe('Payload for recording reviewer feedback on an AI reply.')
+
/**
* Post a reply or internal note to a ticket.
*
diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
index 6ed616c2952a..fcf9362c7f4c 100644
--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
@@ -84,6 +84,8 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
snoozedUntil,
knowledgeGaps,
knowledgeGapsLoading,
+ latestAiMessage,
+ feedbackByMessageId,
} = useValues(logic)
const {
setStatus,
@@ -97,6 +99,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
setDraftContent,
setDraftIsPrivate,
dismissKnowledgeGap,
+ submitAiReplyFeedback,
} = useActions(logic)
const { user } = useValues(userLogic)
@@ -183,6 +186,10 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
onPrivateChange={setDraftIsPrivate}
minHeight="min(400px, calc(100svh - 20rem))"
maxHeight="calc(100svh - 20rem)"
+ latestAiMessageId={latestAiMessage?.id ?? null}
+ feedbackByMessageId={feedbackByMessageId}
+ showAiReplyFeedback={aiSuggestionsEnabled}
+ onSubmitAiReplyFeedback={submitAiReplyFeedback}
/>
<div className="hidden lg:block">
<Resizer {...resizerLogicProps} className="z-20" />
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts
new file mode 100644
index 000000000000..26459f6f08a8
--- /dev/null
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts
@@ -0,0 +1,144 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+import type { CommentType } from '~/types'
+
+import type { Ticket } from '../../types'
+import { supportTicketSceneLogic } from './supportTicketSceneLogic'
+
+const FEEDBACK_STORAGE_KEY = 'conversations_ai_reply_feedback'
+
+jest.mock('~/lib/api', () => {
+ const actual = jest.requireActual('~/lib/api')
+ return {
+ __esModule: true,
+ default: {
+ ...actual.default,
+ conversationsTickets: {
+ ...actual.default?.conversationsTickets,
+ submitAiFeedback: jest.fn().mockResolvedValue(undefined),
+ },
+ },
+ }
+})
+
+import api from '~/lib/api'
+
+const submitAiFeedbackMock = api.conversationsTickets.submitAiFeedback as jest.Mock
+
+function makeAiComment(id: string): CommentType {
+ return {
+ id,
+ content: 'AI reply body',
+ scope: 'conversations_ticket',
+ item_id: 'ticket-1',
+ item_context: { author_type: 'AI', is_private: true },
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ } as unknown as CommentType
+}
+
+function makeTicket(): Ticket {
+ return {
+ id: 'ticket-1',
+ ticket_number: 42,
+ distinct_id: 'user-1',
+ status: 'open',
+ channel_source: 'widget',
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ message_count: 1,
+ ai_triage: {
+ status: 'done',
+ result: 'persisted',
+ confidence: 0.92,
+ ai_trace_id: 'trace-abc',
+ },
+ } as Ticket
+}
+
+describe('supportTicketSceneLogic ai reply feedback', () => {
+ let logic: ReturnType<typeof supportTicketSceneLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ localStorage.removeItem(FEEDBACK_STORAGE_KEY)
+ submitAiFeedbackMock.mockClear()
+ logic = supportTicketSceneLogic({ id: 'new' })
+ logic.mount()
+ logic.actions.setTicket(makeTicket())
+ logic.actions.setMessages([makeAiComment('msg-ai-1')])
+ })
+
+ afterEach(() => {
+ localStorage.removeItem(FEEDBACK_STORAGE_KEY)
+ })
+
+ it('selects the latest AI message', async () => {
+ await expectLogic(logic).toMatchValues({
+ latestAiMessage: expect.objectContaining({ id: 'msg-ai-1', authorType: 'AI' }),
+ })
+ })
+
+ it('calls backend relay on good feedback', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.submitAiReplyFeedback('msg-ai-1', 'good')
+ })
+ .toDispatchActions(['recordAiReplyFeedback'])
+ .toMatchValues({
+ feedbackByMessageId: { 'msg-ai-1': 'good' },
+ })
+
+ expect(submitAiFeedbackMock).toHaveBeenCalledTimes(1)
+ expect(submitAiFeedbackMock).toHaveBeenCalledWith('ticket-1', {
+ message_id: 'msg-ai-1',
+ rating: 'good',
+ })
+ })
+
+ it('calls backend relay on bad rating and feedback text separately', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.submitAiReplyFeedback('msg-ai-1', 'bad')
+ })
+ .toDispatchActions(['recordAiReplyFeedback'])
+ .toMatchValues({
+ feedbackByMessageId: { 'msg-ai-1': 'bad' },
+ })
+
+ expect(submitAiFeedbackMock).toHaveBeenCalledTimes(1)
+ expect(submitAiFeedbackMock).toHaveBeenCalledWith('ticket-1', {
+ message_id: 'msg-ai-1',
+ rating: 'bad',
+ })
+
+ submitAiFeedbackMock.mockClear()
+
+ logic.actions.submitAiReplyFeedback('msg-ai-1', 'bad', 'Wrong answer')
+
+ // Wait for async listener
+ await new Promise((r) => setTimeout(r, 10))
+
+ expect(submitAiFeedbackMock).toHaveBeenCalledTimes(1)
+ expect(submitAiFeedbackMock).toHaveBeenCalledWith('ticket-1', {
+ message_id: 'msg-ai-1',
+ rating: 'bad',
+ feedback_text: 'Wrong answer',
+ })
+ })
+
+ it('dedupes repeated rating submissions for the same message', async () => {
+ logic.actions.submitAiReplyFeedback('msg-ai-1', 'good')
+
+ // Wait for async listener
+ await new Promise((r) => setTimeout(r, 10))
+ submitAiFeedbackMock.mockClear()
+
+ logic.actions.submitAiReplyFeedback('msg-ai-1', 'bad')
+
+ // Wait for async listener
+ await new Promise((r) => setTimeout(r, 10))
+
+ expect(submitAiFeedbackMock).not.toHaveBeenCalled()
+ expect(logic.values.feedbackByMessageId['msg-ai-1']).toBe('good')
+ })
+})
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
index 34b878ec737e..18cb32cff3be 100644
--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
@@ -25,7 +25,14 @@ import {
import type { TicketAssignee } from '../../components/Assignee'
import { supportTicketCounterLogic } from '../../supportTicketCounterLogic'
-import type { ChatMessage, KnowledgeGapSuggestion, Ticket, TicketPriority, TicketStatus } from '../../types'
+import type {
+ AiReplyFeedbackRating,
+ ChatMessage,
+ KnowledgeGapSuggestion,
+ Ticket,
+ TicketPriority,
+ TicketStatus,
+} from '../../types'
import { supportTicketsSceneLogic } from '../tickets/supportTicketsSceneLogic'
import type { supportTicketSceneLogicType } from './supportTicketSceneLogicType'
@@ -166,6 +173,16 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
// Draft message state (persists across tab switches)
setDraftContent: (content: JSONContent | null) => ({ content }),
setDraftIsPrivate: (isPrivate: boolean) => ({ isPrivate }),
+
+ submitAiReplyFeedback: (messageId: string, rating: AiReplyFeedbackRating, feedbackText?: string) => ({
+ messageId,
+ rating,
+ feedbackText,
+ }),
+ recordAiReplyFeedback: (messageId: string, rating: AiReplyFeedbackRating) => ({
+ messageId,
+ rating,
+ }),
}),
loaders(({ values, props }) => ({
person: [
@@ -348,6 +365,16 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
setDraftIsPrivate: (_, { isPrivate }) => isPrivate,
},
],
+ feedbackByMessageId: [
+ {} as Record<string, AiReplyFeedbackRating>,
+ { persist: true, storageKey: 'conversations_ai_reply_feedback' },
+ {
+ recordAiReplyFeedback: (state, { messageId, rating }) => ({
+ ...state,
+ [messageId]: rating,
+ }),
+ },
+ ],
}),
selectors({
hasUnsavedChanges: [
@@ -449,6 +476,17 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
return createExceptionsQuery(ticket.session_id, ticket.created_at)
},
],
+ latestAiMessage: [
+ (s) => [s.chatMessages],
+ (chatMessages: ChatMessage[]): ChatMessage | null => {
+ for (let i = chatMessages.length - 1; i >= 0; i--) {
+ if (chatMessages[i].authorType === 'AI') {
+ return chatMessages[i]
+ }
+ }
+ return null
+ },
+ ],
}),
listeners(({ actions, values, props, cache }) => ({
loadTicket: async () => {
@@ -617,6 +655,35 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
lemonToast.error('Failed to dismiss suggestion')
}
},
+ submitAiReplyFeedback: async ({ messageId, rating, feedbackText }) => {
+ const ticket = values.ticket
+ if (!ticket) {
+ return
+ }
+ try {
+ if (feedbackText) {
+ if (rating !== 'bad') {
+ return
+ }
+ await api.conversationsTickets.submitAiFeedback(ticket.id, {
+ message_id: messageId,
+ rating,
+ feedback_text: feedbackText,
+ })
+ return
+ }
+ if (values.feedbackByMessageId[messageId]) {
+ return
+ }
+ await api.conversationsTickets.submitAiFeedback(ticket.id, {
+ message_id: messageId,
+ rating,
+ })
+ actions.recordAiReplyFeedback(messageId, rating)
+ } catch {
+ lemonToast.error('Failed to submit feedback')
+ }
+ },
})),
afterMount(({ actions, props }) => {
if (props.id !== 'new') {
diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.ts
index 6a93cad49e0a..65d002b0fe1f 100644
--- a/products/conversations/frontend/types.ts
+++ b/products/conversations/frontend/types.ts
@@ -47,9 +47,12 @@ export interface AITriage {
finished_at?: string
workflow_id?: string
run_id?: string
+ ai_trace_id?: string
missing?: string[]
}
+export type AiReplyFeedbackRating = 'good' | 'bad'
+
export type GapSuggestionStatus = 'pending' | 'accepted' | 'dismissed'
export interface KnowledgeGapSuggestion {
diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yaml
index 7a75c297785f..0d2239021d58 100644
--- a/products/conversations/mcp/tools.yaml
+++ b/products/conversations/mcp/tools.yaml
@@ -9,6 +9,9 @@ feature: conversations
url_prefix: /conversations/tickets
ui_apps: {}
tools:
+ conversations-tickets-ai-feedback-create:
+ operation: conversations_tickets_ai_feedback_create
+ enabled: false
conversations-tickets-bulk-update-status-create:
operation: conversations_tickets_bulk_update_status_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6ddedf83f660..d4d5c85fa8d4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8743,6 +8743,39 @@ export namespace Schemas {
HistogramQuantile: 'histogram_quantile',
} as const;
+ /**
+ * * `good` - good
+ * * `bad` - bad
+ */
+ export type RatingEnum = typeof RatingEnum[keyof typeof RatingEnum];
+
+
+ export const RatingEnum = {
+ Good: 'good',
+ Bad: 'bad',
+ } as const;
+
+ /**
+ * Payload for recording reviewer feedback on an AI reply.
+ */
+ export interface AiFeedbackRequest {
+ /**
+ * ID of the AI message being rated.
+ * @maxLength 200
+ */
+ message_id: string;
+ /** Reviewer rating: good or bad.
+ *
+ * * `good` - good
+ * * `bad` - bad */
+ rating: RatingEnum;
+ /**
+ * Optional text explaining a bad rating.
+ * @maxLength 2000
+ */
+ feedback_text?: string;
+ }
+
export interface InsightsThresholdBounds {
/** Alert fires when the value drops below this number. */
lower?: number | null;