:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(conversations): show the AI's evidence and make drafts actionable (#103748)
Alex Vcb6616962182
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1c146cf9bf54..609e6e713667 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10792,6 +10792,22 @@ snapshots:hash: v1.k794b7964.97190abf6b2cb1c02e955555559874e975140d4479843089f1a9535e6100a194.t9t3ni1Sd9qf56MyNquC5SbflzhcT9m5d3GyZhBkUZoscenes-app-stamphog-runs--runs-list-empty--light:hash: v1.k794b7964.e3f2449aaf242198553ecade4b10006f816108242c273060fa456e9504ee3fcf.vsiDO5c59UASwyXQZZtwifVbT-qaaUdTa-TxoKNSpmE+ scenes-app-support-aipanel--auto-sent--dark:+ hash: v1.k794b7964.07e3affbf3cd08afd226dbb511275935ff1c57068ee0fc26b087327a777fc787.L05NU4MU6m6USxVSPf7Q6h9pP6Q58rJHMYjTNCgXxpg+ scenes-app-support-aipanel--auto-sent--light:+ hash: v1.k794b7964.13ae85baf06876ab24cdbe1a99f3e7a7d53ec1c2970ce88f4566705a81f04611.Jd-0Qe9k1pTVDvrtEW6_ac5wLNKVdSyXUq8HlT5cEOk+ scenes-app-support-aipanel--awaiting-clarification--dark:+ hash: v1.k794b7964.2051e62bcb0ba9e312601856a1771b4bfbd9f6e50135aba65d7136b4b190b608.mTmg0OWRuKLv4QxBJO1vWco0MjhmDebmNese3ZkSVuY+ scenes-app-support-aipanel--awaiting-clarification--light:+ hash: v1.k794b7964.6873e4491c301b9ce004c6e50536c5d6387e80447f296f1bb001fc7f50f883ea.o6iSgLNLGEhqwzdaKoZeVsQi1wPkrI6nqH4B7k_l0ww+ scenes-app-support-aipanel--findings-only--dark:+ hash: v1.k794b7964.66f2025d216e19c519c125daad292493964b0e47a400fdedd25949acb98463c5.5c0VveovbSB8yvO3ibmrCGKMReeAxqY8HSpqW1GN1fw+ scenes-app-support-aipanel--findings-only--light:+ hash: v1.k794b7964.decd92b08b7ecf9b0c20834e18efc95d607a3331fa6301a60db228169c407988.Lbcu8gNKAgYq-H92y1eKEioRkP3MleRAxEP_-ZqDmrA+ scenes-app-support-aipanel--suggested--dark:+ hash: v1.k794b7964.6b6e47f7a6e819c6f5001b08535c3dff93cbad7acf5ebfeafeff9c5dcfc36189.lZn-6YFthsicyD42YSyFBP-KQ1ghbNYQ1C4uqgeTvlM+ scenes-app-support-aipanel--suggested--light:+ hash: v1.k794b7964.6c3b559141a22910e91279c6a78db5b3eb7c8c6fd603b0c9604dda0b18561f26.LPgQxRSVfVCglr43R6HXDc9tsTy6zB9W81t1WTzsB8Iscenes-app-support-supportplaybookeditor--customized--dark:hash: v1.k794b7964.56dd8c26993da8181fb09aa4d9868be1f5925885f1f1854ca38100636acdaaec.yjA6yaERFMxD3ydwD-uPOPa4qSoIgBECHwHq3wOm_1Escenes-app-support-supportplaybookeditor--customized--light:diff --git a/products/conversations/backend/ai/evidence.py b/products/conversations/backend/ai/evidence.pynew file mode 100644index 000000000000..6031c7303567--- /dev/null+++ b/products/conversations/backend/ai/evidence.py@@ -0,0 +1,135 @@+"""Hydrate AI citation refs into titles and links for the ticket AI panel."""++from __future__ import annotations++from urllib.parse import urlparse+from uuid import UUID++from posthog.dataclasses import frozen+from posthog.models.comment import Comment++from products.business_knowledge.backend.logic import GENERATED_KNOWLEDGE_ORIGIN+from products.business_knowledge.backend.models import KnowledgeChunk+from products.conversations.backend.models import Ticket++MAX_AI_SOURCES = 20+++@frozen+class AiSource:+ ref: str+ title: str+ source_id: str | None = None+ url: str | None = None+ is_generated: bool = False+ learned_from_ticket_number: int | None = None++ def to_dict(self) -> dict[str, object]:+ return {+ "ref": self.ref,+ "title": self.title,+ "source_id": self.source_id,+ "url": self.url,+ "is_generated": self.is_generated,+ "learned_from_ticket_number": self.learned_from_ticket_number,+ }+++def outbound_doc_url(ref: str) -> str | None:+ parsed = urlparse(ref.strip())+ if parsed.scheme in ("http", "https") and parsed.netloc:+ return ref.strip()+ return None+++def parse_chunk_id(ref: str) -> UUID | None:+ try:+ return UUID(ref.strip())+ except ValueError:+ return None+++def citations_for_ticket(ticket: Ticket, triage: dict[str, object]) -> list[str]:+ raw = triage.get("citations")+ if isinstance(raw, list):+ # An empty list is what the latest run stored, so the older comment below is stale.+ return [str(item) for item in raw if item][:MAX_AI_SOURCES]+ context = (+ Comment.objects.filter(+ team_id=ticket.team_id,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ item_context__author_type="AI",+ deleted=False,+ )+ .order_by("-created_at", "-id")+ .values_list("item_context", flat=True)+ .first()+ )+ if not isinstance(context, dict):+ return []+ stored = context.get("citations")+ if not isinstance(stored, list):+ return []+ return [str(item) for item in stored if item][:MAX_AI_SOURCES]+++def hydrate_ai_sources(*, team_id: int, citations: list[str]) -> list[AiSource]:+ ordered = [item.strip() for item in citations if item and str(item).strip()][:MAX_AI_SOURCES]+ if not ordered:+ return []++ chunk_ids = [chunk_id for ref in ordered if (chunk_id := parse_chunk_id(ref)) is not None]+ chunks_by_id: dict[UUID, KnowledgeChunk] = {}+ if chunk_ids:+ # Search drops UNKNOWN learned chunks. Citation footnotes still have to+ # resolve those rows so the agent can see what the draft used.+ chunks_by_id = {+ chunk.id: chunk+ for chunk in KnowledgeChunk.objects.for_team(team_id)+ .filter(id__in=chunk_ids)+ .select_related("source", "document")+ }++ sources: list[AiSource] = []+ for ref in ordered:+ chunk_id = parse_chunk_id(ref)+ if chunk_id is not None:+ chunk = chunks_by_id.get(chunk_id)+ if chunk is None:+ sources.append(AiSource(ref=ref, title="Knowledge source"))+ continue+ sources.append(_source_from_chunk(ref, chunk))+ continue+ url = outbound_doc_url(ref)+ if url is not None:+ sources.append(AiSource(ref=ref, title=_url_title(url), url=url))+ continue+ sources.append(AiSource(ref=ref, title=ref[:80]))+ return sources+++def _source_from_chunk(ref: str, chunk: KnowledgeChunk) -> AiSource:+ title = chunk.document.title or chunk.heading_path or chunk.source.name or "Knowledge source"+ metadata = chunk.document.metadata if isinstance(chunk.document.metadata, dict) else {}+ ticket_number = None+ if chunk.source.is_generated and metadata.get("origin") == GENERATED_KNOWLEDGE_ORIGIN:+ raw_number = metadata.get("ticket_number")+ if isinstance(raw_number, int) and raw_number > 0:+ ticket_number = raw_number+ elif isinstance(raw_number, str) and raw_number.isdigit() and int(raw_number) > 0:+ ticket_number = int(raw_number)+ return AiSource(+ ref=ref,+ title=title,+ source_id=str(chunk.source_id),+ is_generated=bool(chunk.source.is_generated),+ learned_from_ticket_number=ticket_number,+ )+++def _url_title(url: str) -> str:+ parsed = urlparse(url)+ host_path = f"{parsed.netloc}{parsed.path}".rstrip("/")+ label = host_path or url+ return label[:80]diff --git a/products/conversations/backend/ai/human_outcome.py b/products/conversations/backend/ai/human_outcome.pyindex 2c719d4def24..062b5b36b529 100644--- a/products/conversations/backend/ai/human_outcome.py+++ b/products/conversations/backend/ai/human_outcome.py@@ -8,7 +8,7 @@ from __future__ import annotationsfrom difflib import SequenceMatcherfrom typing import Literal-from django.db import transaction+from django.db import models, transactionfrom django.db.models import Q, QuerySetfrom posthog.models.comment import Comment@@ -17,6 +17,12 @@ from products.conversations.backend.models import TicketHumanOutcome = Literal["used", "edited", "ignored"]++class AiDraftHumanOutcome(models.TextChoices):+ USED = "used", "used"+ EDITED = "edited", "edited"++# Near-copy of the draft counts as used; some overlap as edited; the rest as ignored.USED_RATIO = 0.85EDITED_RATIO = 0.4@@ -31,6 +37,16 @@ def classify_human_outcome(ai_draft: str, human_reply: str) -> HumanOutcome:return "ignored"+def _inserted_draft_text(ai_note: Comment) -> str:+ context = ai_note.item_context or {}+ if context.get("persist_as") not in {"clarification", "findings"}:+ return ai_note.content or ""+ questions = context.get("clarifying_questions")+ if not isinstance(questions, list):+ return ai_note.content or ""+ return next((question.strip() for question in questions if isinstance(question, str) and question.strip()), "")++def _ticket_comments(*, team_id: int, ticket_id: str) -> QuerySet[Comment]:return Comment.objects.filter(team_id=team_id,@@ -47,6 +63,33 @@ def _public_human_comments(comments: QuerySet[Comment]) -> QuerySet[Comment]:)+def record_human_outcome(*, team_id: int, ticket_id: str, draft_message_id: str, outcome: HumanOutcome) -> bool:+ """Write `human_outcome` if unset, or upgrade `used` to `edited` after a composer edit."""+ with transaction.atomic():+ ticket = Ticket.objects.select_for_update().filter(id=ticket_id, team_id=team_id).first()+ if ticket is None:+ return False+ latest_ai_draft_id = (+ _ticket_comments(team_id=team_id, ticket_id=ticket_id)+ .filter(item_context__author_type="AI", item_context__is_private=True, deleted=False)+ .order_by("-created_at", "-id")+ .values_list("id", flat=True)+ .first()+ )+ if latest_ai_draft_id is None or str(latest_ai_draft_id) != draft_message_id:+ return False+ triage = dict(ticket.ai_triage or {})+ current = triage.get("human_outcome")+ if current == outcome:+ return True+ if current and not (current == "used" and outcome == "edited"):+ return False+ triage["human_outcome"] = outcome+ ticket.ai_triage = triage+ ticket.save(update_fields=["ai_triage", "updated_at"])+ return True++def maybe_record_human_outcome(*, team_id: int, ticket_id: str, comment_id: str, human_content: str) -> None:"""Set `ai_triage.human_outcome` on the first public human reply after the latest AI note."""if not human_content.strip():@@ -57,8 +100,7 @@ def maybe_record_human_outcome(*, team_id: int, ticket_id: str, comment_id: str,if ticket is None:returntriage = dict(ticket.ai_triage or {})- if triage.get("human_outcome"):- return+ current = triage.get("human_outcome")comments = _ticket_comments(team_id=team_id, ticket_id=ticket_id)this_comment = comments.filter(id=comment_id).first()@@ -71,7 +113,7 @@ def maybe_record_human_outcome(*, team_id: int, ticket_id: str, comment_id: str,# Only private AI notes are drafts a human can adopt. A public AI reply was auto-sent# to the customer, so a later human reply is a follow-up, not adoption of a draft.ai_note = (- comments.filter(item_context__author_type="AI", item_context__is_private=True)+ comments.filter(item_context__author_type="AI", item_context__is_private=True, deleted=False).filter(before_this).order_by("-created_at", "-id").first()@@ -84,6 +126,12 @@ def maybe_record_human_outcome(*, team_id: int, ticket_id: str, comment_id: str,if first_after is None or str(first_after.id) != str(comment_id):return- triage["human_outcome"] = classify_human_outcome(ai_note.content or "", human_content)+ classified = classify_human_outcome(_inserted_draft_text(ai_note), human_content)+ if current == classified:+ return+ if current and current != "used":+ return++ triage["human_outcome"] = classifiedticket.ai_triage = triageticket.save(update_fields=["ai_triage", "updated_at"])diff --git a/products/conversations/backend/ai/test_evidence.py b/products/conversations/backend/ai/test_evidence.pynew file mode 100644index 000000000000..79b241a5199f--- /dev/null+++ b/products/conversations/backend/ai/test_evidence.py@@ -0,0 +1,25 @@+from django.test import SimpleTestCase++from products.conversations.backend.ai.evidence import hydrate_ai_sources, outbound_doc_url, parse_chunk_id+++class TestAiSourceRefs(SimpleTestCase):+ def test_http_citation_is_outbound(self) -> None:+ assert outbound_doc_url("https://example.com/docs/sdk") == "https://example.com/docs/sdk"+ assert outbound_doc_url("http://example.com/a") == "http://example.com/a"++ def test_javascript_and_relative_refs_are_not_outbound(self) -> None:+ assert outbound_doc_url("javascript:alert(1)") is None+ assert outbound_doc_url("/business-knowledge/abc") is None+ assert outbound_doc_url("not a url") is None++ def test_uuid_refs_parse_and_other_strings_do_not(self) -> None:+ assert parse_chunk_id("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee") is not None+ assert parse_chunk_id("https://example.com/docs") is None++ def test_hydrate_keeps_url_citations_without_a_database(self) -> None:+ sources = hydrate_ai_sources(team_id=1, citations=["https://example.com/docs/sdk"])+ assert len(sources) == 1+ assert sources[0].url == "https://example.com/docs/sdk"+ assert sources[0].title == "example.com/docs/sdk"+ assert sources[0].source_id is Nonediff --git a/products/conversations/backend/ai/test_hydrate_ai_sources.py b/products/conversations/backend/ai/test_hydrate_ai_sources.pynew file mode 100644index 000000000000..7d4c900ea800--- /dev/null+++ b/products/conversations/backend/ai/test_hydrate_ai_sources.py@@ -0,0 +1,55 @@+import uuid+import datetime++from posthog.test.base import BaseTest++from products.business_knowledge.backend import logic+from products.business_knowledge.backend.models import KnowledgeChunk+from products.conversations.backend.ai.evidence import hydrate_ai_sources++_EVIDENCE_REVISION_AT = datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC)+++class TestHydrateAiSources(BaseTest):+ def test_learned_unknown_chunks_still_hydrate(self) -> None:+ generated = logic.create_generated_knowledge_document(+ logic.CreateGeneratedKnowledgeDocument(+ team_id=self.team.id,+ provider="conversations",+ ticket_id=uuid.UUID("10000000-0000-0000-0000-000000000001"),+ ticket_number=42,+ source_team_id=self.team.id,+ resolution_comment_id=uuid.UUID("20000000-0000-0000-0000-000000000002"),+ analysis_version="post_resolution_v1",+ title="Refund policy",+ content="Refunds are available within 30 days.",+ evidence_revision_at=_EVIDENCE_REVISION_AT,+ )+ )+ chunk_id = KnowledgeChunk.objects.unscoped().filter(document_id=generated.id).values_list("id", flat=True)[0]++ sources = hydrate_ai_sources(team_id=self.team.id, citations=[str(chunk_id)])++ assert len(sources) == 1+ assert sources[0].is_generated is True+ assert sources[0].learned_from_ticket_number == 42+ assert sources[0].source_id == str(generated.source_id)+ assert sources[0].title == "Refund policy"+ assert sources[0].url is None++ def test_preserves_citation_order_across_urls_and_chunks(self) -> None:+ text_source = logic.create_text_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Manual notes",+ text="Install the SDK from Project settings.",+ )+ chunk_id = KnowledgeChunk.objects.unscoped().filter(source_id=text_source.id).values_list("id", flat=True)[0]+ url = "https://example.com/docs/sdk"++ sources = hydrate_ai_sources(team_id=self.team.id, citations=[url, str(chunk_id)])++ assert [source.ref for source in sources] == [url, str(chunk_id)]+ assert sources[0].url == url+ assert sources[1].source_id == str(text_source.id)+ assert sources[1].is_generated is Falsediff --git a/products/conversations/backend/api/tests/test_ai_triage_api.py b/products/conversations/backend/api/tests/test_ai_triage_api.pynew file mode 100644index 000000000000..edf529138bed--- /dev/null+++ b/products/conversations/backend/api/tests/test_ai_triage_api.py@@ -0,0 +1,190 @@+from posthog.test.base import APIBaseTest++from rest_framework import status++from posthog.models.comment import Comment++from products.business_knowledge.backend import logic+from products.business_knowledge.backend.models import KnowledgeChunk+from products.conversations.backend.models import Ticket+from products.conversations.backend.models.constants import Channel, Status+++class TestAiHumanOutcomeAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.WIDGET,+ widget_session_id="ai-outcome-session",+ distinct_id="user-123",+ status=Status.OPEN,+ ai_triage={"status": "done", "result": "suggested"},+ )+ self.url = f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/ai_human_outcome/"+ self.draft = self._create_ai_draft("Current draft")++ def _create_ai_draft(self, content: str) -> Comment:+ return Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content=content,+ item_context={"author_type": "AI", "is_private": True},+ )++ def _payload(self, outcome: str) -> dict[str, str]:+ return {"message_id": str(self.draft.id), "outcome": outcome}++ def test_records_used(self) -> None:+ response = self.client.post(self.url, self._payload("used"), format="json")++ assert response.status_code == status.HTTP_202_ACCEPTED+ assert response.json()["outcome"] == "used"+ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "used"++ def test_upgrades_used_to_edited(self) -> None:+ self.client.post(self.url, self._payload("used"), format="json")++ response = self.client.post(self.url, self._payload("edited"), format="json")++ assert response.status_code == status.HTTP_202_ACCEPTED+ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "edited"++ def test_used_is_idempotent(self) -> None:+ self.client.post(self.url, self._payload("used"), format="json")++ response = self.client.post(self.url, self._payload("used"), format="json")++ assert response.status_code == status.HTTP_202_ACCEPTED+ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "used"++ def test_rejects_a_second_non_upgrade_write(self) -> None:+ self.client.post(self.url, self._payload("edited"), format="json")++ response = self.client.post(self.url, self._payload("used"), format="json")++ assert response.status_code == status.HTTP_409_CONFLICT+ assert response.json()["error_type"] == "ai_draft_outcome_conflict"+ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "edited"++ def test_rejects_ignored(self) -> None:+ response = self.client.post(self.url, self._payload("ignored"), format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ self.ticket.refresh_from_db()+ assert "human_outcome" not in self.ticket.ai_triage++ def test_rejects_an_outcome_for_an_old_draft(self) -> None:+ self._create_ai_draft("Newer draft")++ response = self.client.post(self.url, self._payload("used"), format="json")++ assert response.status_code == status.HTTP_409_CONFLICT+ assert response.json()["error_type"] == "ai_draft_outcome_conflict"+ self.ticket.refresh_from_db()+ assert "human_outcome" not in self.ticket.ai_triage+++class TestAiTriageSourcesAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.WIDGET,+ widget_session_id="ai-sources-session",+ distinct_id="user-123",+ status=Status.OPEN,+ )+ self.text_source = logic.create_text_source(+ team_id=self.team.id,+ created_by_id=self.user.id,+ name="Manual notes",+ text="Install the SDK from Project settings.",+ )+ self.chunk_id = str(+ KnowledgeChunk.objects.unscoped().filter(source_id=self.text_source.id).values_list("id", flat=True)[0]+ )++ def test_retrieve_hydrates_sources_from_triage_citations(self) -> None:+ Ticket.objects.filter(id=self.ticket.id).update(+ ai_triage={"status": "done", "result": "suggested", "citations": [self.chunk_id]}+ )++ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/")++ assert response.status_code == status.HTTP_200_OK+ sources = response.json()["ai_triage"]["sources"]+ assert len(sources) == 1+ assert sources[0]["source_id"] == str(self.text_source.id)+ assert sources[0]["is_generated"] is False++ def test_list_does_not_hydrate_sources(self) -> None:+ Ticket.objects.filter(id=self.ticket.id).update(+ ai_triage={"status": "done", "result": "suggested", "citations": [self.chunk_id]}+ )++ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/")++ assert response.status_code == status.HTTP_200_OK+ triage = response.json()["results"][0]["ai_triage"]+ assert "sources" not in triage+ assert triage["citations"] == [self.chunk_id]++ def _ai_comment(self, deleted: bool = False) -> Comment:+ return Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="Suggested reply",+ deleted=deleted,+ item_context={+ "author_type": "AI",+ "is_private": True,+ "citations": [self.chunk_id],+ },+ )++ def test_empty_stored_citations_do_not_fall_back_to_an_older_comment(self) -> None:+ self._ai_comment()+ Ticket.objects.filter(id=self.ticket.id).update(+ ai_triage={"status": "done", "result": "suggested", "citations": []}+ )++ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/")++ assert response.status_code == status.HTTP_200_OK+ assert "sources" not in response.json()["ai_triage"]++ def test_deleted_ai_comment_is_not_a_citation_fallback(self) -> None:+ self._ai_comment(deleted=True)+ Ticket.objects.filter(id=self.ticket.id).update(ai_triage={"status": "done", "result": "suggested"})++ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/")++ assert response.status_code == status.HTTP_200_OK+ assert "sources" not in response.json()["ai_triage"]++ def test_retrieve_falls_back_to_latest_ai_comment_citations(self) -> None:+ Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content="Suggested reply",+ item_context={+ "author_type": "AI",+ "is_private": True,+ "citations": [self.chunk_id],+ },+ )+ Ticket.objects.filter(id=self.ticket.id).update(ai_triage={"status": "done", "result": "suggested"})++ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/{self.ticket.id}/")++ assert response.status_code == status.HTTP_200_OK+ sources = response.json()["ai_triage"]["sources"]+ assert sources[0]["ref"] == self.chunk_iddiff --git a/products/conversations/backend/api/tests/test_signals.py b/products/conversations/backend/api/tests/test_signals.pyindex e49df91b9fbf..2336f6257673 100644--- a/products/conversations/backend/api/tests/test_signals.py+++ b/products/conversations/backend/api/tests/test_signals.py@@ -9,6 +9,7 @@ from parameterized import parameterizedfrom posthog.models.comment import Comment+from products.conversations.backend.ai.human_outcome import record_human_outcomefrom products.conversations.backend.models import (ConversationDeliveryPart,EmailChannel,@@ -57,13 +58,16 @@ class TestTicketMessageSignals(BaseTest):item_context={"author_type": "team", "is_private": is_private},)- def _create_ai_message(self, content: str, *, is_private: bool = True) -> Comment:+ def _create_ai_message(+ self, content: str, *, is_private: bool = True, deleted: bool = False, item_context: dict | None = None+ ) -> Comment:return Comment.objects.create(team=self.team,scope="conversations_ticket",item_id=str(self.ticket.id),content=content,- item_context={"author_type": "AI", "is_private": is_private},+ item_context={"author_type": "AI", "is_private": is_private, **(item_context or {})},+ deleted=deleted,)def test_customer_message_updates_stats(self, mock_on_commit):@@ -94,6 +98,54 @@ class TestTicketMessageSignals(BaseTest):self.ticket.refresh_from_db()assert self.ticket.ai_triage["human_outcome"] == "used"+ def test_used_draft_then_edited_send_upgrades_human_outcome(self, mock_on_commit):+ draft = "Add the snippet to the head of every page, then reload to send a pageview."+ ai_draft = self._create_ai_message(draft)+ record_human_outcome(+ team_id=self.team.id,+ ticket_id=str(self.ticket.id),+ draft_message_id=str(ai_draft.id),+ outcome="used",+ )+ self._create_team_message("Drop the recorder snippet on checkout only, then hard-refresh to send a pageview.")++ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "edited"++ def test_used_question_sent_unchanged_stays_used(self, mock_on_commit):+ question = "Which SDK are you using?"+ ai_draft = self._create_ai_message(+ f"Suggested question for the customer:\n- {question}\n\nChecked the docs.\n\nStill unknown:\n- SDK version",+ item_context={"persist_as": "clarification", "clarifying_questions": [question]},+ )+ record_human_outcome(+ team_id=self.team.id,+ ticket_id=str(self.ticket.id),+ draft_message_id=str(ai_draft.id),+ outcome="used",+ )+ self._create_team_message(question)++ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "used"++ def test_used_question_then_unrelated_send_is_ignored(self, mock_on_commit):+ question = "Which SDK are you using?"+ ai_draft = self._create_ai_message(+ f"Suggested question for the customer:\n- {question}",+ item_context={"persist_as": "clarification", "clarifying_questions": [question]},+ )+ record_human_outcome(+ team_id=self.team.id,+ ticket_id=str(self.ticket.id),+ draft_message_id=str(ai_draft.id),+ outcome="used",+ )+ self._create_team_message("We migrated this org to a new plan yesterday.")++ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "ignored"+def test_second_public_human_reply_does_not_overwrite_human_outcome(self, mock_on_commit):draft = "Add the snippet to the head of every page."self._create_ai_message(draft)@@ -125,6 +177,15 @@ class TestTicketMessageSignals(BaseTest):self.ticket.refresh_from_db()assert self.ticket.ai_triage["human_outcome"] == "used"+ def test_deleted_ai_note_is_not_the_similarity_target(self, mock_on_commit):+ draft = "Add the snippet to the head of every page."+ self._create_ai_message(draft)+ self._create_ai_message("A deleted unrelated draft.", deleted=True)+ self._create_team_message(draft)++ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "used"+def test_human_reply_before_ai_note_does_not_block_later_outcome(self, mock_on_commit):draft = "Add the snippet to the head of every page."self._create_team_message("Looking into this.")diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex de42d0bcdb3c..53a8bb234516 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -62,6 +62,8 @@ from products.access_control.backend.presentation.access_control import (AccessControlViewSetMixin,UserAccessControlSerializerMixin,)+from products.conversations.backend.ai.evidence import citations_for_ticket, hydrate_ai_sources+from products.conversations.backend.ai.human_outcome import AiDraftHumanOutcome, record_human_outcomefrom products.conversations.backend.api.serializers import TicketAssignmentSerializerfrom products.conversations.backend.api.ticket_filters import (AI_TRIAGE_FILTER_VALUES,@@ -114,8 +116,8 @@ TicketAssignee = UserTicketAssignee | RoleTicketAssigneeclass TicketErrorSerializer(serializers.Serializer):- detail = serializers.CharField()- error_type = serializers.CharField(required=False)+ detail = serializers.CharField(help_text="Human-readable error message.")+ error_type = serializers.CharField(required=False, help_text="Machine-readable error code.")class TicketMessageSerializer(serializers.Serializer):@@ -228,6 +230,16 @@ class AiFeedbackRequestSerializer(serializers.Serializer):)+class AiHumanOutcomeRequestSerializer(serializers.Serializer):+ """Payload for recording whether a human adopted an AI draft."""++ message_id = serializers.CharField(max_length=200, help_text="ID of the private AI draft being adopted.")+ outcome = serializers.ChoiceField(+ choices=AiDraftHumanOutcome.choices,+ help_text="used when the human inserts the draft as-is; edited after they change it in the composer.",+ )++class ComposeTicketSerializer(serializers.Serializer):recipient_email = serializers.EmailField(help_text="Recipient email address.",@@ -436,10 +448,27 @@ class TicketSerializer(UserAccessControlSerializerMixin, TaggedItemSerializerMix"Null when organization_id is unset."},"ai_triage": {- "help_text": "AI support pipeline triage and outcome (status, result, ticket_type, confidence, attempts, etc.)."+ "help_text": (+ "AI support pipeline triage and outcome (status, result, ticket_type, confidence, "+ "attempts, verdict, blocker, sources). Retrieve hydrates sources from citations."+ )},}+ def to_representation(self, instance: Ticket) -> dict[str, Any]:+ data = super().to_representation(instance)+ view = self.context.get("view")+ if getattr(view, "action", None) != "retrieve":+ return data+ triage = dict(data.get("ai_triage") or {})+ citations = citations_for_ticket(instance, triage)+ if citations:+ triage["sources"] = [+ source.to_dict() for source in hydrate_ai_sources(team_id=instance.team_id, citations=citations)+ ]+ data["ai_triage"] = triage+ return data+def get_email_to(self, obj: Ticket) -> str | None:config = getattr(obj, "email_config", None)if config is not None:@@ -665,6 +694,7 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessContro"compose","reply","ai_feedback",+ "ai_human_outcome","note","delete_note",]@@ -1711,6 +1741,37 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControreturn Response(status=drf_status.HTTP_202_ACCEPTED)+ @extend_schema(+ parameters=[TICKET_ID_PARAM],+ request=AiHumanOutcomeRequestSerializer,+ responses={+ 202: AiHumanOutcomeRequestSerializer,+ 409: OpenApiResponse(response=TicketErrorSerializer),+ },+ )+ @action(detail=True, methods=["post"])+ def ai_human_outcome(self, request, *args, **kwargs):+ """Record that a human used or edited the latest AI draft."""+ ticket = self.get_object()+ serializer = AiHumanOutcomeRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ outcome = serializer.validated_data["outcome"]+ recorded = record_human_outcome(+ team_id=self.team_id,+ ticket_id=str(ticket.id),+ draft_message_id=serializer.validated_data["message_id"],+ outcome=outcome,+ )+ if not recorded:+ return Response(+ {+ "detail": "The AI draft is no longer current or its outcome is already recorded.",+ "error_type": "ai_draft_outcome_conflict",+ },+ status=drf_status.HTTP_409_CONFLICT,+ )+ return Response(serializer.data, status=drf_status.HTTP_202_ACCEPTED)+@extend_schema(request=ComposeTicketSerializer,responses={diff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.pyindex dfc17c1c7e46..680ea061c849 100644--- a/products/conversations/backend/temporal/pipeline.py+++ b/products/conversations/backend/temporal/pipeline.py@@ -317,6 +317,11 @@ class SupportReplyWorkflow:"validator_confidence": validate.confidence,"coverage": validate.coverage,"grounded": validate.grounded,+ "citations": list(draft.citations),+ "investigation_summary": draft.investigation_summary,+ "unknowns": list(draft.unknowns),+ "clarifying_questions": list(draft.clarifying_questions),+ "missing": list(validate.missing),}for attempt in range(max_attempts):diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.pyindex 03cddc88ca76..20a51f9bd137 100644--- a/products/conversations/backend/temporal/tests/test_pipeline.py+++ b/products/conversations/backend/temporal/tests/test_pipeline.py@@ -526,6 +526,7 @@ async def test_blocker_aware_routing(assert persist_input.investigation_summary in persist_input.replylast_triage = mock_record_triage.call_args_list[-1][0][0].patchassert last_triage["result"] == expected_result+ assert last_triage["citations"] == sample_chunk_idsassert "draft_confidence" in last_triageassert "validator_confidence" in last_triageassert "blocker" in last_triagediff --git a/products/conversations/frontend/components/Chat/ChatView.tsx b/products/conversations/frontend/components/Chat/ChatView.tsxindex bd510fb913ca..9988cef84bde 100644--- a/products/conversations/frontend/components/Chat/ChatView.tsx+++ b/products/conversations/frontend/components/Chat/ChatView.tsx@@ -4,7 +4,14 @@ import { LemonCard } from '@posthog/lemon-ui'import { cn } from 'lib/utils/css-classes'-import type { AiReplyFeedbackRating, ChatMessage, Ticket, TicketChannel, TicketStatus } from '../../types'+import type {+ AITriageSource,+ AiReplyFeedbackRating,+ ChatMessage,+ Ticket,+ TicketChannel,+ TicketStatus,+} from '../../types'import { MessageInput } from './MessageInput'import { MessageList, type TimelineExtra } from './MessageList'@@ -81,6 +88,10 @@ export interface ChatViewProps {onCancelEdit?: () => voidfullEmailLoadingMessageId?: string | nullonViewFullEmail?: (messageId: string) => void+ composerPrefillAt?: number+ aiSources?: AITriageSource[]+ aiDraftApplying?: boolean+ onApplyAiDraft?: (message: ChatMessage) => void}export function ChatView({@@ -127,6 +138,10 @@ export function ChatView({onCancelEdit,fullEmailLoadingMessageId,onViewFullEmail,+ composerPrefillAt,+ aiSources,+ aiDraftApplying,+ onApplyAiDraft,}: ChatViewProps): JSX.Element {const listMinHeight = minHeight ?? (fillParent ? '0' : '400px')const listMaxHeight = maxHeight ?? (fillParent ? 'none' : '600px')@@ -160,6 +175,9 @@ export function ChatView({onDeleteMessage={onDeleteMessage}fullEmailLoadingMessageId={fullEmailLoadingMessageId}onViewFullEmail={onViewFullEmail}+ aiSources={aiSources}+ aiDraftApplying={aiDraftApplying}+ onApplyAiDraft={onApplyAiDraft}/><div className="border-t pt-3 shrink-0"><MessageInput@@ -183,6 +201,7 @@ export function ChatView({onCancelEdit={onCancelEdit}collapseUntilActive={collapseUntilActive}threadId={threadId}+ composerPrefillAt={composerPrefillAt}/></div></LemonCard>diff --git a/products/conversations/frontend/components/Chat/Message.test.tsx b/products/conversations/frontend/components/Chat/Message.test.tsxindex b2c6f86cf88d..cafb311f67de 100644--- a/products/conversations/frontend/components/Chat/Message.test.tsx+++ b/products/conversations/frontend/components/Chat/Message.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { fireEvent, render, screen } from '@testing-library/react'+import { cleanup, fireEvent, render, screen } from '@testing-library/react'import type { ChatMessage } from '../../types'import { Message } from './Message'@@ -12,6 +12,8 @@ jest.mock('../Editor', () => ({jest.mock('../Editor/richContentToHtml', () => ({ richContentToHtml: () => null }))describe('Message', () => {+ afterEach(cleanup)+it('loads the preserved full email body when one is available', () => {const onViewFullEmail = jest.fn()const message: ChatMessage = {@@ -28,4 +30,44 @@ describe('Message', () => {fireEvent.click(screen.getByText('View full email'))expect(onViewFullEmail).toHaveBeenCalledTimes(1)})++ it('prefills a private AI draft with Use as reply', () => {+ const onApplyAiDraft = jest.fn()+ const message: ChatMessage = {+ id: 'ai-draft',+ content: 'Add the snippet to every page.',+ authorType: 'AI',+ authorName: 'PostHog Assistant',+ createdAt: '2026-01-01T00:00:00Z',+ isPrivate: true,+ persistAs: 'reply',+ confidence: 0.64,+ citations: ['https://example.com/docs/sdk'],+ }++ render(<Message message={message} isCustomer={false} onApplyAiDraft={onApplyAiDraft} />)++ fireEvent.click(screen.getByText('Use as reply'))+ expect(onApplyAiDraft).toHaveBeenCalledTimes(1)+ expect(screen.getByText('64% confidence')).toBeInTheDocument()+ expect(screen.getByText('example.com/docs/sdk')).toBeInTheDocument()+ })++ it('offers Use question on a private clarifying draft', () => {+ const message: ChatMessage = {+ id: 'ai-question',+ content: 'Suggested question for the customer:\n- Which SDK?',+ authorType: 'AI',+ authorName: 'PostHog Assistant',+ createdAt: '2026-01-01T00:00:00Z',+ isPrivate: true,+ persistAs: 'clarification',+ clarifyingQuestions: ['Which SDK are you using?'],+ }++ render(<Message message={message} isCustomer={false} onApplyAiDraft={jest.fn()} />)++ expect(screen.getByText('Use question')).toBeInTheDocument()+ expect(screen.queryByText('Use as reply')).not.toBeInTheDocument()+ })})diff --git a/products/conversations/frontend/components/Chat/Message.tsx b/products/conversations/frontend/components/Chat/Message.tsxindex 85b5563f90f3..9428aab30ec1 100644--- a/products/conversations/frontend/components/Chat/Message.tsx+++ b/products/conversations/frontend/components/Chat/Message.tsx@@ -11,14 +11,16 @@ import {IconTrash,IconWarning,} from '@posthog/icons'-import { LemonButton, LemonInput, ProfilePicture, Tooltip } from '@posthog/lemon-ui'+import { LemonButton, LemonInput, LemonTag, Link, ProfilePicture, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { urls } from 'scenes/urls'-import type { AiReplyFeedbackRating, ChatMessage, MessageDeliveryStatus } from '../../types'+import type { AITriageSource, AiReplyFeedbackRating, ChatMessage, MessageDeliveryStatus } from '../../types'import { SupportMarkdown, SupportRichContentPreview } from '../Editor'import { richContentToHtml } from '../Editor/richContentToHtml'+import { aiDraftAction } from './aiDraftAction'import { TeamOnlyBadge } from './TeamOnlyBadge'export interface MessageProps {@@ -33,6 +35,29 @@ export interface MessageProps {onDelete?: () => voidfullEmailLoading?: booleanonViewFullEmail?: () => void+ aiSources?: AITriageSource[]+ aiDraftApplying?: boolean+ onApplyAiDraft?: () => void+}++function citationDisplay(ref: string, sources: AITriageSource[]): { title: string; to?: string; external?: boolean } {+ const source = sources.find((item) => item.ref === ref)+ if (source?.source_id) {+ return { title: source.title || ref, to: urls.businessKnowledgeSource(source.source_id) }+ }+ if (source?.url) {+ return { title: source.title || ref, to: source.url, external: true }+ }+ if (ref.startsWith('https://') || ref.startsWith('http://')) {+ try {+ const parsed = new URL(ref)+ return { title: `${parsed.host}${parsed.pathname}`.replace(/\/$/, '') || ref, to: ref, external: true }+ } catch {+ return { title: ref }+ }+ }+ // A non-URL ref that no source resolved is a knowledge chunk id; the raw UUID is noise.+ return { title: source?.title || 'Knowledge source' }}export function Message({@@ -47,10 +72,15 @@ export function Message({onDelete,fullEmailLoading = false,onViewFullEmail,+ aiSources = [],+ aiDraftApplying = false,+ onApplyAiDraft,}: MessageProps): JSX.Element {const isAgent = message.authorType === 'AI'const profileType = isAgent ? 'bot' : 'person'const isPrivate = message.isPrivate+ const draftAction = aiDraftAction(message)+ const citations = (message.citations ?? []).filter((item) => item.trim())const [feedbackText, setFeedbackText] = useState('')const [feedbackTextSubmitted, setFeedbackTextSubmitted] = useState(false)const wasRatedOnMount = useRef(!!aiReplyFeedbackRating)@@ -91,7 +121,7 @@ export function Message({where the robot glyph picks the colour up, and renders the name as a sibling —so the name is coloured from this row rather than through the component. */}<div- className={`flex items-center justify-between w-full gap-2 mb-1 ${+ className={`flex items-center justify-between w-full gap-2 mb-1 min-w-0 ${isAgent ? '[&_.profile-name]:text-ai' : ''}`}>@@ -103,8 +133,11 @@ export function Message({showName={true}className={isAgent ? 'text-ai' : undefined}/>- <div className="flex items-center gap-1.5">+ <div className="flex items-center gap-1.5 flex-wrap justify-end min-w-0">{isPrivate && <TeamOnlyBadge label="Private note" tone={isAgent ? 'agent' : 'teammate'} />}+ {isAgent && message.confidence != null && (+ <LemonTag size="small">{(message.confidence * 100).toFixed(0)}% confidence</LemonTag>+ )}<span className="text-xs text-muted-alt"><TZLabel time={message.createdAt} />{(message.version ?? 0) > 0 ? ' (edited)' : null}@@ -197,6 +230,47 @@ export function Message({</LemonButton></div>)}+ {draftAction && onApplyAiDraft && (+ <div className="mt-2">+ <LemonButton+ type="secondary"+ size="xsmall"+ loading={aiDraftApplying}+ disabledReason={aiDraftApplying ? 'Inserting draft' : undefined}+ onClick={onApplyAiDraft}+ // pinned: autocapture / Playwright key. Do not rename.+ data-attr={+ draftAction === 'question'+ ? 'ai-draft-use-question'+ : 'ai-draft-use-as-reply'+ }+ >+ {draftAction === 'question' ? 'Use question' : 'Use as reply'}+ </LemonButton>+ </div>+ )}+ {citations.length > 0 && (+ <ol className="mt-2 mb-0 pl-4 text-xs text-muted-alt space-y-0.5">+ {citations.map((ref, index) => {+ const display = citationDisplay(ref, aiSources)+ return (+ <li key={`${ref}-${index}`}>+ {display.to ? (+ <Link+ to={display.to}+ target={display.external ? '_blank' : undefined}+ className="break-all"+ >+ {display.title}+ </Link>+ ) : (+ <span className="break-all">{display.title}</span>+ )}+ </li>+ )+ })}+ </ol>+ )}</div>{showAiReplyFeedback && (<div className="mt-1.5 space-y-1.5">diff --git a/products/conversations/frontend/components/Chat/MessageInput.tsx b/products/conversations/frontend/components/Chat/MessageInput.tsxindex 71148b4595b6..d2ac1657fb63 100644--- a/products/conversations/frontend/components/Chat/MessageInput.tsx+++ b/products/conversations/frontend/components/Chat/MessageInput.tsx@@ -59,6 +59,8 @@ export interface MessageInputProps {collapseUntilActive?: boolean/** When this changes, the collapsed composer closes. Ticket navigation reuses the same mount. */threadId?: string+ /** When this changes, seed the editor from draftContent even if it is already mounted. */+ composerPrefillAt?: number}export function MessageInput({@@ -85,6 +87,7 @@ export function MessageInput({onCancelEdit,collapseUntilActive = false,threadId,+ composerPrefillAt = 0,}: MessageInputProps): JSX.Element {const [isEmpty, setIsEmpty] = useState(!draftContent)const [isUploading, setIsUploading] = useState(false)@@ -153,6 +156,19 @@ export function MessageInput({})}, [editingMessageId])+ useEffect(() => {+ if (!composerPrefillAt) {+ return+ }+ const editor = editorRef.current+ const content = draftContentRef.current+ if (!editor || content == null) {+ return+ }+ editor.setContent(content)+ queueMicrotask(() => setIsEmpty(editor.isEmpty()))+ }, [composerPrefillAt])+// Support controlled or uncontrolled isPrivateconst isPrivate = controlledIsPrivate ?? localIsPrivateconst setIsPrivate = onPrivateChange ?? setLocalIsPrivatediff --git a/products/conversations/frontend/components/Chat/MessageList.test.tsx b/products/conversations/frontend/components/Chat/MessageList.test.tsxindex 8f34e407b60a..7174e884a8ee 100644--- a/products/conversations/frontend/components/Chat/MessageList.test.tsx+++ b/products/conversations/frontend/components/Chat/MessageList.test.tsx@@ -10,8 +10,15 @@ import { MessageList } from './MessageList'jest.mock('./Message', () => {const React = jest.requireActual<typeof import('react')>('react')return {- Message: ({ message }: { message: ChatMessage }) =>- React.createElement('div', { 'data-attr': `message-${message.id}` }, message.content),+ Message: ({ message, onApplyAiDraft }: { message: ChatMessage; onApplyAiDraft?: () => void }) =>+ React.createElement(+ 'div',+ { 'data-attr': `message-${message.id}` },+ message.content,+ onApplyAiDraft+ ? React.createElement('button', { 'data-attr': `apply-${message.id}`, onClick: onApplyAiDraft })+ : null+ ),}})@@ -142,6 +149,32 @@ describe('MessageList', () => {expect(screen.queryByText(PILL)).not.toBeInTheDocument()})+ // Applying a draft records the outcome against the ticket's current AI run, so an older draft+ // must not offer the action — it would mark the newest run as used.+ it('offers the draft action on the newest AI draft only', () => {+ const draft = (id: string, createdAt: string): ChatMessage => ({+ id,+ content: `Draft ${id}`,+ authorType: 'AI',+ authorName: 'PostHog Assistant',+ createdAt,+ isPrivate: true,+ persistAs: 'reply',+ })++ render(+ <MessageList+ messages={[draft('old', '2026-01-01T00:00:00Z'), draft('new', '2026-01-01T00:05:00Z')]}+ messagesLoading={false}+ canEditTicket+ onApplyAiDraft={jest.fn()}+ />+ )++ expect(screen.getByTestId('apply-new')).toBeInTheDocument()+ expect(screen.queryByTestId('apply-old')).not.toBeInTheDocument()+ })+it('dismisses the pill once the reader scrolls back to the bottom themselves', () => {const { rerender } = render(<MessageList messages={[FIRST]} messagesLoading={false} />)scrollTo(SCROLLED_UP)diff --git a/products/conversations/frontend/components/Chat/MessageList.tsx b/products/conversations/frontend/components/Chat/MessageList.tsxindex 85b33a607317..0c6ce542099f 100644--- a/products/conversations/frontend/components/Chat/MessageList.tsx+++ b/products/conversations/frontend/components/Chat/MessageList.tsx@@ -4,7 +4,8 @@ import { LemonButton, Spinner } from '@posthog/lemon-ui'import { IconArrowDown } from 'lib/lemon-ui/icons'-import type { AiReplyFeedbackRating, ChatMessage, MessageDeliveryStatus } from '../../types'+import type { AITriageSource, AiReplyFeedbackRating, ChatMessage, MessageDeliveryStatus } from '../../types'+import { aiDraftAction } from './aiDraftAction'import { Message } from './Message'export interface MessageListProps {@@ -41,6 +42,9 @@ export interface MessageListProps {onDeleteMessage?: (messageId: string) => voidfullEmailLoadingMessageId?: string | nullonViewFullEmail?: (messageId: string) => void+ aiSources?: AITriageSource[]+ aiDraftApplying?: boolean+ onApplyAiDraft?: (message: ChatMessage) => void}/** A non-message entry in the thread, e.g. an agent's findings. `at` is what orders it among the@@ -75,6 +79,9 @@ export function MessageList({onDeleteMessage,fullEmailLoadingMessageId = null,onViewFullEmail,+ aiSources = [],+ aiDraftApplying = false,+ onApplyAiDraft,}: MessageListProps): JSX.Element {const messagesEndRef = useRef<HTMLDivElement>(null)const containerRef = useRef<HTMLDivElement>(null)@@ -202,6 +209,14 @@ export function MessageList({const deliveryStatusMap = getDeliveryStatusMap()+ // Applying a draft records the outcome against the ticket's current AI run, so only the+ // newest draft offers it. An older one would mark the wrong run as used.+ const latestAiDraftId =+ messages+ .filter((message) => aiDraftAction(message) !== null)+ .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())+ .at(-1)?.id ?? null+// Messages and extras share one chronological stream, so an agent's findings sit at the point in// the conversation they arrived rather than always at the bottom. Ties keep messages first, and// the original order within each kind, so a same-second reply never reshuffles.@@ -241,6 +256,13 @@ export function MessageList({? () => onViewFullEmail(message.id): undefined}+ aiSources={aiSources}+ aiDraftApplying={aiDraftApplying}+ onApplyAiDraft={+ canEditTicket && onApplyAiDraft && message.id === latestAiDraftId+ ? () => onApplyAiDraft(message)+ : undefined+ }/>),}diff --git a/products/conversations/frontend/components/Chat/aiDraftAction.test.ts b/products/conversations/frontend/components/Chat/aiDraftAction.test.tsnew file mode 100644index 000000000000..b1bb5faf15bd--- /dev/null+++ b/products/conversations/frontend/components/Chat/aiDraftAction.test.ts@@ -0,0 +1,51 @@+import type { ChatMessage } from '../../types'+import { aiDraftAction, aiDraftComposerHtml, aiDraftComposerText } from './aiDraftAction'++describe('aiDraftAction', () => {+ const base: Pick<ChatMessage, 'authorType' | 'isPrivate' | 'persistAs' | 'clarifyingQuestions' | 'content'> = {+ authorType: 'AI',+ isPrivate: true,+ content: 'Try adding the snippet to every page.',+ }++ it.each([+ ['suggested private reply', { persistAs: 'reply' as const }, 'reply'],+ ['legacy private note without persist_as', {}, 'reply'],+ ['private clarifying question', { persistAs: 'clarification' as const }, 'question'],+ [+ 'findings with a suggested question',+ { persistAs: 'findings' as const, clarifyingQuestions: ['Which SDK are you using?'] },+ 'question',+ ],+ ['findings without a question', { persistAs: 'findings' as const, clarifyingQuestions: [] }, null],+ ['public auto-sent reply', { isPrivate: false, persistAs: 'reply' as const }, null],+ ['public clarifying question', { isPrivate: false, persistAs: 'clarification' as const }, null],+ ['human private note', { authorType: 'human' as const }, null],+ ])('%s', (_name, overrides, expected) => {+ expect(aiDraftAction({ ...base, ...overrides })).toBe(expected)+ })++ // A draft repeats the customer's own words, so an image ref they wrote can reach it. Inserting+ // that into the composer would make the agent's browser fetch whichever host they picked.+ it.each([+ ['a customer-chosen host', 'https://tracker.example.com/pixel.png', 'Screenshot', false],+ ['an intranet host', 'http://10.0.0.5/status.png', '', false],+ ['a PostHog host', 'https://posthog.com/images/docs/sdk.png', 'SDK setup', true],+ ])('keeps a draft image only when the host is ours — %s: %s', (_name, source, alt, kept) => {+ const html = aiDraftComposerHtml({ ...base, content: `Here you go:\n\n` })++ expect(html.includes('<img')).toBe(kept)+ expect(html).toContain(kept ? source : alt || source)+ })++ it('prefills the first clarifying question instead of the findings note', () => {+ expect(+ aiDraftComposerText({+ ...base,+ persistAs: 'findings',+ content: 'Investigation notes\n\nSuggested question for the customer:\n- Which SDK?',+ clarifyingQuestions: ['Which SDK are you using?', 'Which project?'],+ })+ ).toBe('Which SDK are you using?')+ })+})diff --git a/products/conversations/frontend/components/Chat/aiDraftAction.ts b/products/conversations/frontend/components/Chat/aiDraftAction.tsnew file mode 100644index 000000000000..62581edc392f--- /dev/null+++ b/products/conversations/frontend/components/Chat/aiDraftAction.ts@@ -0,0 +1,59 @@+import { markdownToHtml } from 'lib/utils/markdown'+import { isTrustedPostHogUrl } from 'lib/utils/trustedUrl'++import type { ChatMessage } from '../../types'++export type AiDraftActionKind = 'reply' | 'question'++export function firstClarifyingQuestion(questions: unknown): string | null {+ if (!Array.isArray(questions)) {+ return null+ }+ for (const item of questions) {+ if (typeof item === 'string' && item.trim()) {+ return item.trim()+ }+ }+ return null+}++export function aiDraftAction(+ message: Pick<ChatMessage, 'authorType' | 'isPrivate' | 'persistAs' | 'clarifyingQuestions'>+): AiDraftActionKind | null {+ if (message.authorType !== 'AI' || !message.isPrivate) {+ return null+ }+ if (message.persistAs === 'clarification') {+ return 'question'+ }+ if (message.persistAs === 'findings') {+ return firstClarifyingQuestion(message.clarifyingQuestions) ? 'question' : null+ }+ return 'reply'+}++export function aiDraftComposerText(+ message: Pick<ChatMessage, 'content' | 'authorType' | 'isPrivate' | 'persistAs' | 'clarifyingQuestions'>+): string {+ if (aiDraftAction(message) === 'question') {+ return firstClarifyingQuestion(message.clarifyingQuestions) ?? message.content+ }+ return message.content+}++export function aiDraftComposerHtml(+ message: Pick<ChatMessage, 'content' | 'authorType' | 'isPrivate' | 'persistAs' | 'clarifyingQuestions'>+): string {+ // A draft repeats what the customer wrote, so an image ref in the ticket can reach it. The+ // composer loads images, which would make the agent's browser fetch a host the customer chose.+ // DOMParser gives an inert document, so nothing loads while the images are taken out.+ const parsed = new DOMParser().parseFromString(markdownToHtml(aiDraftComposerText(message)), 'text/html')+ for (const image of Array.from(parsed.querySelectorAll('img'))) {+ const source = image.getAttribute('src')+ if (isTrustedPostHogUrl(source ?? undefined)) {+ continue+ }+ image.replaceWith(parsed.createTextNode(image.getAttribute('alt') || source || ''))+ }+ return parsed.body.innerHTML+}diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex d456111b0530..519be5018cc3 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -190,7 +190,7 @@ export interface TicketApi {ai_resolved?: boolean/** @nullable */escalation_reason?: string | null- /** AI support pipeline triage and outcome (status, result, ticket_type, confidence, attempts, etc.). */+ /** AI support pipeline triage and outcome (status, result, ticket_type, confidence, attempts, verdict, blocker, sources). Retrieve hydrates sources from citations. */readonly ai_triage: unknownreadonly created_at: stringreadonly updated_at: string@@ -414,6 +414,40 @@ export interface AiFeedbackRequestApi {feedback_text?: string}+/**+ * * `used` - used+ * * `edited` - edited+ */+export type AiDraftHumanOutcomeEnumApi = (typeof AiDraftHumanOutcomeEnumApi)[keyof typeof AiDraftHumanOutcomeEnumApi]++export const AiDraftHumanOutcomeEnumApi = {+ Used: 'used',+ Edited: 'edited',+} as const++/**+ * Payload for recording whether a human adopted an AI draft.+ */+export interface AiHumanOutcomeRequestApi {+ /**+ * ID of the private AI draft being adopted.+ * @maxLength 200+ */+ message_id: string+ /** used when the human inserts the draft as-is; edited after they change it in the composer.+ *+ * * `used` - used+ * * `edited` - edited */+ outcome: AiDraftHumanOutcomeEnumApi+}++export interface TicketErrorApi {+ /** Human-readable error message. */+ detail: string+ /** Machine-readable error code. */+ error_type?: string+}+/*** A single message in a ticket thread (output-only).*/@@ -456,11 +490,6 @@ export interface TicketFullEmailApi {readonly content: string}-export interface TicketErrorApi {- detail: string- error_type?: string-}-/*** Payload for updating a private note on a ticket.*/diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.tsindex a0366fc3f899..55fc4f9e0bc1 100644--- a/products/conversations/frontend/generated/api.ts+++ b/products/conversations/frontend/generated/api.ts@@ -12,6 +12,7 @@ import type {AIContextAccountPropertyApi,AIReplyPlaybookApi,AiFeedbackRequestApi,+ AiHumanOutcomeRequestApi,BulkUpdateStatusRequestApi,BulkUpdateStatusResponseApi,BulkUpdateTagsUUIDRequestApi,@@ -211,6 +212,27 @@ export const conversationsTicketsAiFeedbackCreate = async (})}+export const getConversationsTicketsAiHumanOutcomeCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/conversations/tickets/${id}/ai_human_outcome/`+}++/**+ * Record that a human used or edited the latest AI draft.+ */+export const conversationsTicketsAiHumanOutcomeCreate = async (+ projectId: string,+ id: string,+ aiHumanOutcomeRequestApi: AiHumanOutcomeRequestApi,+ options?: RequestInit+): Promise<AiHumanOutcomeRequestApi> => {+ return apiMutator<AiHumanOutcomeRequestApi>(getConversationsTicketsAiHumanOutcomeCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(aiHumanOutcomeRequestApi),+ })+}+export const getConversationsTicketsMessagesListUrl = (projectId: string,id: string,diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.tsindex 85b5176dd6a6..2b7f5b02ed10 100644--- a/products/conversations/frontend/generated/api.zod.ts+++ b/products/conversations/frontend/generated/api.zod.ts@@ -139,6 +139,26 @@ export const ConversationsTicketsAiFeedbackCreateBody = /* @__PURE__ */ zod}).describe('Payload for recording reviewer feedback on an AI reply.')+/**+ * Record that a human used or edited the latest AI draft.+ */+export const conversationsTicketsAiHumanOutcomeCreateBodyMessageIdMax = 200++export const ConversationsTicketsAiHumanOutcomeCreateBody = /* @__PURE__ */ zod+ .object({+ message_id: zod+ .string()+ .max(conversationsTicketsAiHumanOutcomeCreateBodyMessageIdMax)+ .describe('ID of the private AI draft being adopted.'),+ outcome: zod+ .enum(['used', 'edited'])+ .describe('\* `used` - used\n\* `edited` - edited')+ .describe(+ 'used when the human inserts the draft as-is; edited after they change it in the composer.\n\n\* `used` - used\n\* `edited` - edited'+ ),+ })+ .describe('Payload for recording whether a human adopted an AI draft.')+/*** Update a private note on a ticket.*diff --git a/products/conversations/frontend/scenes/ticket/AIPanel.stories.tsx b/products/conversations/frontend/scenes/ticket/AIPanel.stories.tsxnew file mode 100644index 000000000000..f9f7d02f4b3d--- /dev/null+++ b/products/conversations/frontend/scenes/ticket/AIPanel.stories.tsx@@ -0,0 +1,130 @@+import type { Meta, StoryObj } from '@storybook/react'++import type { AITriage } from '../../types'+import { AIPanel } from './AIPanel'++const meta: Meta<typeof AIPanel> = {+ title: 'Scenes-App/Support/AIPanel',+ component: AIPanel,+ parameters: { layout: 'padded', viewMode: 'story' },+}+export default meta++type Story = StoryObj<typeof AIPanel>++const sdkSource = {+ ref: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',+ title: 'Install the JavaScript SDK',+ source_id: '11111111-1111-1111-1111-111111111111',+ url: null,+ is_generated: false,+ learned_from_ticket_number: null,+}++const learnedSource = {+ ref: 'bbbbbbbb-cccc-dddd-eeee-ffffffffffff',+ title: 'Refund policy',+ source_id: '22222222-2222-2222-2222-222222222222',+ url: null,+ is_generated: true,+ learned_from_ticket_number: 42,+}++const docsSource = {+ ref: 'https://example.com/docs/sdk',+ title: 'example.com/docs/sdk',+ source_id: null,+ url: 'https://example.com/docs/sdk',+ is_generated: false,+ learned_from_ticket_number: null,+}++function triage(overrides: AITriage): AITriage {+ return {+ ticket_type: 'how_to',+ confidence: 0.9,+ attempts: 1,+ started_at: '2026-09-21T12:00:00Z',+ finished_at: '2026-09-21T12:01:00Z',+ ...overrides,+ }+}++function Narrow({ children }: { children: React.ReactNode }): JSX.Element {+ return <div className="w-[520px]">{children}</div>+}++export const AutoSent: Story = {+ render: () => (+ <Narrow>+ <AIPanel+ aiTriage={triage({+ status: 'done',+ result: 'persisted',+ verdict: 'answerable',+ blocker: 'none',+ confidence: 0.92,+ sources: [sdkSource, docsSource],+ })}+ />+ </Narrow>+ ),+}++export const Suggested: Story = {+ render: () => (+ <Narrow>+ <AIPanel+ aiTriage={triage({+ status: 'done',+ result: 'suggested',+ verdict: 'answerable',+ blocker: 'none',+ confidence: 0.64,+ investigation_summary: 'Docs cover snippet install. The ticket did not say which pages.',+ unknowns: ['Which pages should get the snippet'],+ sources: [sdkSource],+ })}+ />+ </Narrow>+ ),+}++export const FindingsOnly: Story = {+ render: () => (+ <Narrow>+ <AIPanel+ aiTriage={triage({+ status: 'done',+ result: 'escalated_with_findings',+ verdict: 'blocked_on_knowledge',+ blocker: 'knowledge',+ confidence: 0.31,+ investigation_summary: 'Searched team docs and learned sources. No matching procedure.',+ unknowns: ['How this team handles SSO timeouts'],+ missing: ['SSO timeout runbook'],+ sources: [learnedSource],+ })}+ />+ </Narrow>+ ),+}++export const AwaitingClarification: Story = {+ render: () => (+ <Narrow>+ <AIPanel+ aiTriage={triage({+ status: 'awaiting_clarification',+ result: 'clarified',+ verdict: 'blocked_on_customer',+ blocker: 'customer_info',+ confidence: 0.4,+ investigation_summary: 'Need the SDK name before answering.',+ unknowns: ['Which SDK the customer is using'],+ sources: [sdkSource],+ })}+ />+ </Narrow>+ ),+}diff --git a/products/conversations/frontend/scenes/ticket/AIPanel.tsx b/products/conversations/frontend/scenes/ticket/AIPanel.tsxindex 6977963fc0d3..d3a0f17dabb8 100644--- a/products/conversations/frontend/scenes/ticket/AIPanel.tsx+++ b/products/conversations/frontend/scenes/ticket/AIPanel.tsx@@ -1,16 +1,21 @@import type { ReactNode } from 'react'-import { LemonCollapse, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'+import { LemonCollapse, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'+import { urls } from 'scenes/urls'import {type AITriage,+ type AITriageSource,+ aiTriageBlockerLabel,aiTriageResultLabel,aiTriageResultTagType,aiTriageStatusLabel,aiTriageTicketTypeDescription,aiTriageTicketTypeLabel,+ aiTriageVerdictLabel,+ ticketListAiTriage,} from '../../types'interface AIPanelProps {@@ -18,16 +23,14 @@ interface AIPanelProps {}function AITriageHeaderTag({ aiTriage }: { aiTriage?: AITriage }): JSX.Element | null {- if (!aiTriage?.status) {- return null- }- if (aiTriage.status === 'in_progress') {+ const display = ticketListAiTriage(aiTriage)+ if (display.kind === 'processing') {return <Spinner className="text-sm ml-1" />}- if (aiTriage.result) {+ if (display.kind === 'tag') {return (- <LemonTag type={aiTriageResultTagType(aiTriage.result)} size="small" className="ml-1">- {aiTriageResultLabel[aiTriage.result]}+ <LemonTag type={display.tagType} size="small" className="ml-1">+ {display.label}</LemonTag>)}@@ -36,9 +39,9 @@ function AITriageHeaderTag({ aiTriage }: { aiTriage?: AITriage }): JSX.Element |function AITriageRow({ label, children }: { label: string; children: ReactNode }): JSX.Element {return (- <div className="flex justify-between">- <span className="text-muted-alt">{label}</span>- {children}+ <div className="flex justify-between gap-2 min-w-0">+ <span className="text-muted-alt shrink-0">{label}</span>+ <span className="min-w-0 text-right break-words">{children}</span></div>)}@@ -50,7 +53,57 @@ function maybeTriageRow(return children ? [{ label, children }] : []}+function AITriageBulletList({ items }: { items: string[] }): JSX.Element {+ return (+ <ul className="m-0 pl-4 space-y-0.5 break-words">+ {items.map((item) => (+ <li key={item}>{item}</li>+ ))}+ </ul>+ )+}++function AISourceItem({ source }: { source: AITriageSource }): JSX.Element {+ const title = source.title || source.ref+ const name =+ source.source_id != null ? (+ <Link to={urls.businessKnowledgeSource(source.source_id)} className="truncate">+ {title}+ </Link>+ ) : source.url ? (+ <Link to={source.url} target="_blank" className="truncate">+ {title}+ </Link>+ ) : (+ <span className="truncate">{title}</span>+ )++ return (+ <li className="flex flex-col min-w-0 gap-0.5">+ <span className="flex items-center gap-1 min-w-0">+ {name}+ {source.is_generated ? (+ <LemonTag type="highlight" size="small">+ Learned+ </LemonTag>+ ) : null}+ </span>+ {source.is_generated && source.learned_from_ticket_number != null ? (+ <Link+ to={urls.supportTicketDetail(source.learned_from_ticket_number)}+ className="text-xs text-muted truncate"+ >+ Learned from ticket #{source.learned_from_ticket_number}+ </Link>+ ) : null}+ </li>+ )+}+function AITriageDetails({ aiTriage }: { aiTriage: AITriage }): JSX.Element {+ const unknowns = (aiTriage.unknowns ?? []).filter((item) => item.trim())+ const missing = (aiTriage.missing ?? []).filter((item) => item.trim())+ const sources = aiTriage.sources ?? []const rows = [...maybeTriageRow('Status',@@ -74,6 +127,16 @@ function AITriageDetails({ aiTriage }: { aiTriage: AITriage }): JSX.Element {</Tooltip>) : null),+ ...maybeTriageRow(+ 'Verdict',+ aiTriage.verdict ? <span>{aiTriageVerdictLabel[aiTriage.verdict] ?? aiTriage.verdict}</span> : null+ ),+ ...maybeTriageRow(+ 'Blocker',+ aiTriage.blocker && aiTriage.blocker !== 'none' ? (+ <span>{aiTriageBlockerLabel[aiTriage.blocker] ?? aiTriage.blocker}</span>+ ) : null+ ),...maybeTriageRow('Confidence',aiTriage.confidence != null ? <span>{(aiTriage.confidence * 100).toFixed(0)}%</span> : null@@ -92,12 +155,40 @@ function AITriageDetails({ aiTriage }: { aiTriage: AITriage }): JSX.Element {]return (- <div className="space-y-2 text-xs">+ <div className="space-y-2 text-xs min-w-0">{rows.map(({ label, children }) => (<AITriageRow key={label} label={label}>{children}</AITriageRow>))}+ {aiTriage.investigation_summary?.trim() ? (+ <div className="min-w-0">+ <div className="text-muted-alt">Investigation</div>+ <p className="m-0 mt-0.5 whitespace-pre-wrap break-words">{aiTriage.investigation_summary}</p>+ </div>+ ) : null}+ {unknowns.length > 0 ? (+ <div className="min-w-0">+ <div className="text-muted-alt">Still unknown</div>+ <AITriageBulletList items={unknowns} />+ </div>+ ) : null}+ {missing.length > 0 ? (+ <div className="min-w-0">+ <div className="text-muted-alt">Missing from knowledge</div>+ <AITriageBulletList items={missing} />+ </div>+ ) : null}+ {sources.length > 0 ? (+ <div className="min-w-0">+ <div className="text-muted-alt">Sources</div>+ <ul className="m-0 mt-0.5 pl-0 list-none space-y-1">+ {sources.map((source, index) => (+ <AISourceItem key={`${source.ref}-${index}`} source={source} />+ ))}+ </ul>+ </div>+ ) : null}</div>)}@@ -108,11 +199,12 @@ export function AIPanel({ aiTriage }: AIPanelProps): JSX.Element {return (<LemonCollapseclassName="bg-surface-primary"+ defaultActiveKey={hasData ? 'ai_triage' : undefined}panels={[{key: 'ai_triage',header: (- <span className="flex items-center">+ <span className="flex items-center min-w-0">AI triage<AITriageHeaderTag aiTriage={aiTriage} /></span>diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsxindex f06186035c17..a10909916352 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -112,6 +112,8 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemfullEmailContent,fullEmailContentLoading,fullEmailMessageId,+ composerPrefillAt,+ aiDraftApplying,} = useValues(logic)// The list's filters / saved view ride along in this page's query string// (the ticket row carries them through on navigation). Preserve them on the@@ -136,6 +138,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemdeleteMessage,loadFullEmail,closeFullEmail,+ applyAiDraft,} = useActions(logic)const { user } = useValues(userLogic)@@ -295,6 +298,10 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.ElemonCancelEdit={cancelEditingMessage}fullEmailLoadingMessageId={fullEmailContentLoading ? fullEmailMessageId : null}onViewFullEmail={loadFullEmail}+ composerPrefillAt={composerPrefillAt}+ aiSources={ticket?.ai_triage?.sources}+ aiDraftApplying={aiDraftApplying}+ onApplyAiDraft={applyAiDraft}/><div className="hidden @min-[48rem]/main-content: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.tsindex beef33c45a07..c23e4bc1f16d 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts@@ -46,6 +46,7 @@ jest.mock('~/lib/api', () => {conversationsTickets: {...actual.default?.conversationsTickets,submitAiFeedback: jest.fn().mockResolvedValue(undefined),+ submitAiHumanOutcome: jest.fn().mockResolvedValue(undefined),get: jest.fn(),update: jest.fn(),list: jest.fn().mockResolvedValue({ results: [] }),@@ -59,6 +60,7 @@ jest.mock('~/lib/api', () => {})jest.mock('products/conversations/frontend/generated/api', () => ({+ conversationsTicketsAiHumanOutcomeCreate: jest.fn().mockResolvedValue(undefined),conversationsTicketsMessagesFullEmailRetrieve: jest.fn().mockResolvedValue({ content: 'Full email body' }),conversationsTicketsNotesPartialUpdate: jest.fn().mockResolvedValue(undefined),conversationsTicketsNotesDestroy: jest.fn().mockResolvedValue(undefined),@@ -68,12 +70,14 @@ jest.mock('products/conversations/frontend/generated/api', () => ({import api from '~/lib/api'import {+ conversationsTicketsAiHumanOutcomeCreate,conversationsTicketsMessagesFullEmailRetrieve,conversationsTicketsNotesPartialUpdate,conversationsTicketsPartialUpdate,} from 'products/conversations/frontend/generated/api'const submitAiFeedbackMock = api.conversationsTickets.submitAiFeedback as jest.Mock+const submitAiHumanOutcomeMock = conversationsTicketsAiHumanOutcomeCreate as jest.Mockconst fullEmailRetrieveMock = conversationsTicketsMessagesFullEmailRetrieve as jest.Mockfunction makeAiComment(id: string, isPrivate: boolean = true): CommentType {@@ -236,6 +240,10 @@ describe('supportTicketSceneLogic chatMessages mapping', () => {logic.actions.setTicket({ ...makeTicket(), anonymous_traits: { name: 'Mark' } } as Ticket)})+ afterEach(() => {+ stopPolling(logic)+ })+// A thread reply from a second Teams/Slack participant must show its own author,// not fall back to the ticket requester's name.test.each<[string, Record<string, any>, string]>([@@ -270,6 +278,74 @@ describe('supportTicketSceneLogic chatMessages mapping', () => {expect(errorToast).toHaveBeenCalledWith("Couldn't load the full email. Try again.")errorToast.mockRestore()})++ it('maps AI citation and persist_as fields onto chat messages', () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PRODUCT_SUPPORT_AI_NOTES]: true })+ logic.actions.setMessages([+ {+ ...makeAiComment('msg-ai-1'),+ item_context: {+ author_type: 'AI',+ is_private: true,+ persist_as: 'reply',+ confidence: 0.64,+ citations: ['https://example.com/docs/sdk'],+ clarifying_questions: ['Which SDK?'],+ },+ } as unknown as CommentType,+ ])++ expect(logic.values.chatMessages[0]).toEqual(+ expect.objectContaining({+ persistAs: 'reply',+ confidence: 0.64,+ citations: ['https://example.com/docs/sdk'],+ clarifyingQuestions: ['Which SDK?'],+ })+ )+ })+})++describe('supportTicketSceneLogic applyAiDraft', () => {+ let logic: ReturnType<typeof supportTicketSceneLogic.build>++ beforeEach(() => {+ initKeaTests()+ submitAiHumanOutcomeMock.mockClear()+ logic = supportTicketSceneLogic({ id: 'new' })+ logic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PRODUCT_SUPPORT_AI_NOTES]: true })+ logic.actions.setTicket(makeTicket())+ })++ afterEach(() => {+ stopPolling(logic)+ })++ it('prefills a public reply and records used', async () => {+ const message = {+ id: 'msg-ai-1',+ content: 'Add the snippet to every page.',+ authorType: 'AI' as const,+ authorName: 'PostHog Assistant',+ createdAt: '2026-01-01T00:00:00Z',+ isPrivate: true,+ persistAs: 'reply' as const,+ }++ await expectLogic(logic, () => {+ logic.actions.applyAiDraft(message)+ }).toFinishAllListeners()++ expect(logic.values.draftIsPrivate).toBe(false)+ expect(logic.values.composerPrefillAt).toBe(1)+ expect(logic.values.aiDraftApplying).toBe(false)+ expect(logic.values.ticket?.ai_triage?.human_outcome).toBe('used')+ expect(submitAiHumanOutcomeMock).toHaveBeenCalledWith('997', 'ticket-1', {+ message_id: 'msg-ai-1',+ outcome: 'used',+ })+ })})describe('supportTicketSceneLogic AI note visibility', () => {diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex 3af3656c41c3..e7d28e297a1a 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -19,6 +19,7 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'+import { ApiError } from 'lib/api-error'import { commentsLogic } from 'lib/components/Comments/commentsLogic'import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'@@ -45,6 +46,7 @@ import type { Breadcrumb, CommentType, PersonType, UserType } from '~/types'import { ActivityScope, PropertyFilterType, PropertyOperator, Region } from '~/types'import {+ conversationsTicketsAiHumanOutcomeCreate,conversationsTicketsMessagesFullEmailRetrieve,conversationsTicketsNotesDestroy,conversationsTicketsNotesPartialUpdate,@@ -60,6 +62,7 @@ import type { FeatureFlagsSet } from '../../../../../frontend/src/lib/logic/featimport type { TeamPublicType, TeamType } from '../../../../../frontend/src/types'import { assigneeSelectLogic } from '../../components/Assignee'import type { Assignee, TicketAssignee } from '../../components/Assignee'+import { aiDraftComposerHtml } from '../../components/Chat/aiDraftAction'import { supportTicketCounterLogic } from '../../supportTicketCounterLogic'import { priorityOptions } from '../../types'import type { AiReplyFeedbackRating, ChatMessage, Ticket, TicketPriority, TicketStatus } from '../../types'@@ -225,10 +228,12 @@ export interface supportTicketSceneLogicValues {availableTags: string[] // tagsModelcurrentTeam: TeamPublicType | TeamType | null // teamLogicuser: UserType | null // userLogic+ aiDraftApplying: booleanassignee: TicketAssigneebreadcrumbs: Breadcrumb[]chatMessages: ChatMessage[]chatPanelWidth: (desiredSize: number | null) => number+ composerPrefillAt: numberdiscussionsEnabled: booleandraftContent: string | JSONContent | nulldraftIsPrivate: boolean@@ -280,6 +285,12 @@ export interface supportTicketSceneLogicActions {appendMessage: (message: CommentType) => {message: CommentType}+ applyAiDraft: (message: ChatMessage) => {+ message: ChatMessage+ }+ bumpComposerPrefill: () => {+ value: true+ }cancelEditingMessage: () => {value: true}@@ -405,6 +416,9 @@ export interface supportTicketSceneLogicActions {richContent: Record<string, unknown> | nullstatusAfterSend: TicketStatus | undefined}+ setAiDraftApplying: (applying: boolean) => {+ applying: boolean+ }setAssignee: (assignee: TicketAssignee) => {assignee: TicketAssignee}@@ -561,6 +575,10 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([pollDiscussionThread: true,+ applyAiDraft: (message: ChatMessage) => ({ message }),+ setAiDraftApplying: (applying: boolean) => ({ applying }),+ bumpComposerPrefill: true,+loadOlderMessages: true,setOlderMessages: (olderMessages: CommentType[]) => ({ olderMessages }),setOlderMessagesLoading: (loading: boolean) => ({ loading }),@@ -840,6 +858,19 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([setMessageSending: (_, { sending }) => sending,},],+ aiDraftApplying: [+ false,+ {+ applyAiDraft: () => true,+ setAiDraftApplying: (_, { applying }) => applying,+ },+ ],+ composerPrefillAt: [+ 0,+ {+ bumpComposerPrefill: (state) => state + 1,+ },+ ],draftContent: [null as string | JSONContent | null,{@@ -1092,6 +1123,26 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([emailDeliveryStatus: message.item_context?.email_delivery_status,fromZendesk: message.item_context?.from_zendesk === true,hasFullEmailContent: message.item_context?.has_full_email_content === true,+ citations: Array.isArray(message.item_context?.citations)+ ? message.item_context.citations.filter(+ (item: unknown): item is string => typeof item === 'string' && !!item+ )+ : undefined,+ confidence:+ typeof message.item_context?.confidence === 'number'+ ? message.item_context.confidence+ : undefined,+ persistAs:+ message.item_context?.persist_as === 'reply' ||+ message.item_context?.persist_as === 'findings' ||+ message.item_context?.persist_as === 'clarification'+ ? message.item_context.persist_as+ : undefined,+ clarifyingQuestions: Array.isArray(message.item_context?.clarifying_questions)+ ? message.item_context.clarifying_questions.filter(+ (item: unknown): item is string => typeof item === 'string'+ )+ : undefined,}})},@@ -1451,6 +1502,39 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([}actions.loadTickets()},+ applyAiDraft: async ({ message }) => {+ try {+ if (values.editingMessageId) {+ cache.noteEditActive = false+ actions.clearEditingMessage()+ }+ actions.setDraftIsPrivate(false)+ actions.setDraftContent(aiDraftComposerHtml(message))+ actions.bumpComposerPrefill()+ if (!values.ticket?.id) {+ return+ }+ try {+ await conversationsTicketsAiHumanOutcomeCreate(String(getCurrentTeamId()), values.ticket.id, {+ message_id: message.id,+ outcome: 'used',+ })+ const ticket = values.ticket+ if (ticket) {+ actions.setTicket({+ ...ticket,+ ai_triage: { ...ticket.ai_triage, human_outcome: 'used' },+ })+ }+ } catch (error: unknown) {+ if (!(error instanceof ApiError && error.status === 409)) {+ lemonToast.error("Couldn't record that you used the draft.")+ }+ }+ } finally {+ actions.setAiDraftApplying(false)+ }+ },startEditingMessage: ({ message }) => {// Only stash the composer draft on first enter; switching notes keeps the original stash.if (!cache.noteEditActive) {diff --git a/products/conversations/frontend/scenes/tickets/ticketColumns.test.ts b/products/conversations/frontend/scenes/tickets/ticketColumns.test.tsindex 39a1b82de676..4cacd45ec4c2 100644--- a/products/conversations/frontend/scenes/tickets/ticketColumns.test.ts+++ b/products/conversations/frontend/scenes/tickets/ticketColumns.test.ts@@ -1,29 +1,55 @@+import { ticketListAiTriage } from '../../types'import { TICKET_COLUMN_ORDER, TicketColumnKey, buildTicketColumns } from './ticketColumns'const keysOf = (visible: TicketColumnKey[], context: { aiEnabled: boolean; embedded: boolean }): string[] =>buildTicketColumns(visible, context).map((column) => ('key' in column ? String(column.key) : ''))-describe('buildTicketColumns', () => {- const all = TICKET_COLUMN_ORDER- const context = { aiEnabled: true, embedded: false }+describe('ticket columns', () => {+ describe('buildTicketColumns', () => {+ const all = TICKET_COLUMN_ORDER+ const context = { aiEnabled: true, embedded: false }- it.each([- ['hides a deselected column', ['ticket_number', 'status'], 'tags', false],- ['keeps a selected column', ['ticket_number', 'tags'], 'tags', true],- ['keeps the mandatory column even when deselected', ['tags'], 'ticket_number', true],- ])('%s', (_name, visible, key, expected) => {- expect(keysOf(visible as TicketColumnKey[], context).includes(key)).toBe(expected)- })+ it.each([+ ['hides a deselected column', ['ticket_number', 'status'], 'tags', false],+ ['keeps a selected column', ['ticket_number', 'tags'], 'tags', true],+ ['keeps the mandatory column even when deselected', ['tags'], 'ticket_number', true],+ ])('%s', (_name, visible, key, expected) => {+ expect(keysOf(visible as TicketColumnKey[], context).includes(key)).toBe(expected)+ })++ it.each([+ ['ai_triage', { aiEnabled: false, embedded: false }, 'ai_triage'],+ ['customer', { aiEnabled: true, embedded: true }, 'customer'],+ ])('never renders %s when the context excludes it', (_name, ctx, key) => {+ expect(keysOf(all, ctx)).not.toContain(key)+ })- it.each([- ['ai_triage', { aiEnabled: false, embedded: false }, 'ai_triage'],- ['customer', { aiEnabled: true, embedded: true }, 'customer'],- ])('never renders %s when the context excludes it', (_name, ctx, key) => {- expect(keysOf(all, ctx)).not.toContain(key)+ it('renders in canonical order regardless of selection order', () => {+ const shuffled: TicketColumnKey[] = ['updated_at', 'status', 'ticket_number', 'tags']+ expect(keysOf(shuffled, context)).toEqual(['ticket_number', 'status', 'tags', 'updated_at'])+ })})- it('renders in canonical order regardless of selection order', () => {- const shuffled: TicketColumnKey[] = ['updated_at', 'status', 'ticket_number', 'tags']- expect(keysOf(shuffled, context)).toEqual(['ticket_number', 'status', 'tags', 'updated_at'])+ describe('ticketListAiTriage', () => {+ it('shows awaiting clarification instead of the clarified result', () => {+ expect(+ ticketListAiTriage({+ status: 'awaiting_clarification',+ result: 'clarified',+ })+ ).toEqual({+ kind: 'tag',+ label: 'Waiting for the customer',+ tagType: 'warning',+ })+ })++ it('keeps the suggested-reply result when the run is done', () => {+ expect(ticketListAiTriage({ status: 'done', result: 'suggested' })).toEqual({+ kind: 'tag',+ label: 'Suggested reply',+ tagType: 'warning',+ })+ })})})diff --git a/products/conversations/frontend/scenes/tickets/ticketColumns.tsx b/products/conversations/frontend/scenes/tickets/ticketColumns.tsxindex 26f3f1f114a6..f4b4dbb7ea85 100644--- a/products/conversations/frontend/scenes/tickets/ticketColumns.tsx+++ b/products/conversations/frontend/scenes/tickets/ticketColumns.tsx@@ -14,13 +14,7 @@ import { ChannelsTag, getChannelThreadUrl } from '../../components/Channels/Chanimport { IdentityBadge } from '../../components/IdentityBadge/IdentityBadge'import { SlaDisplay } from '../../components/SlaDisplay/SlaDisplay'import { TicketPreviewPopover } from '../../components/TicketPreview/TicketPreviewPopover'-import {- type Ticket,- aiTriageProcessingLabel,- aiTriageResultLabel,- aiTriageResultTagType,- aiTriageTicketTypeLabel,-} from '../../types'+import { type Ticket, aiTriageProcessingLabel, aiTriageTicketTypeLabel, ticketListAiTriage } from '../../types'export type TicketColumnKey =| 'ticket_number'@@ -152,11 +146,11 @@ const TICKET_COLUMNS: Record<TicketColumnKey, TicketColumnDefinition> = {title: 'AI status',key: 'ai_triage',render: (_, ticket) => {- const triage = ticket.ai_triage- if (!triage || !triage.status) {+ const display = ticketListAiTriage(ticket.ai_triage)+ if (display.kind === 'empty') {return <span className="text-muted-alt text-xs">—</span>}- if (triage.status === 'in_progress') {+ if (display.kind === 'processing') {return (<span className="flex items-center gap-1 text-xs"><Spinner className="text-sm" />@@ -164,24 +158,19 @@ const TICKET_COLUMNS: Record<TicketColumnKey, TicketColumnDefinition> = {</span>)}- if (triage.result) {- const tooltipContent = [- triage.ticket_type &&- `Type: ${aiTriageTicketTypeLabel[triage.ticket_type] ?? triage.ticket_type}`,- triage.confidence != null && `Confidence: ${(triage.confidence * 100).toFixed(0)}%`,- triage.attempts != null && `Attempts: ${triage.attempts}`,- ]- .filter(Boolean)- .join(' · ')- return (- <Tooltip title={tooltipContent || undefined}>- <LemonTag type={aiTriageResultTagType(triage.result)}>- {aiTriageResultLabel[triage.result]}- </LemonTag>- </Tooltip>- )- }- return <span className="text-muted-alt text-xs">—</span>+ const triage = ticket.ai_triage+ const tooltipContent = [+ triage?.ticket_type && `Type: ${aiTriageTicketTypeLabel[triage.ticket_type] ?? triage.ticket_type}`,+ triage?.confidence != null && `Confidence: ${(triage.confidence * 100).toFixed(0)}%`,+ triage?.attempts != null && `Attempts: ${triage.attempts}`,+ ]+ .filter(Boolean)+ .join(' · ')+ return (+ <Tooltip title={tooltipContent || undefined}>+ <LemonTag type={display.tagType}>{display.label}</LemonTag>+ </Tooltip>+ )},},},diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex baa41f676699..9db1611b077a 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -54,6 +54,18 @@ export type TicketTagsMatch = 'any' | 'all'export type AITriageStatus = 'in_progress' | 'done' | 'awaiting_clarification'export type AITriageFilterValue = AiTriageResultEnumApiexport type AITriageResult = Exclude<AiTriageResultEnumApi, 'in_progress'>+export type AITriageVerdict = 'answerable' | 'blocked_on_customer' | 'blocked_on_knowledge' | 'out_of_scope'+export type AITriageBlocker = 'none' | 'customer_info' | 'knowledge' | 'contradiction'+export type AIPersistAs = 'reply' | 'findings' | 'clarification'++export interface AITriageSource {+ ref: string+ title: string+ source_id?: string | null+ url?: string | null+ is_generated?: boolean+ learned_from_ticket_number?: number | null+}export interface AITriage {schema_version?: number@@ -70,11 +82,13 @@ export interface AITriage {run_id?: stringai_trace_id?: stringmissing?: string[]- verdict?: 'answerable' | 'blocked_on_customer' | 'blocked_on_knowledge' | 'out_of_scope'- blocker?: 'none' | 'customer_info' | 'knowledge' | 'contradiction'+ verdict?: AITriageVerdict+ blocker?: AITriageBlockerunknowns?: string[]clarifying_questions?: string[]investigation_summary?: string+ citations?: string[]+ sources?: AITriageSource[]draft_confidence?: numbervalidator_confidence?: numbercoverage?: number@@ -227,6 +241,10 @@ export interface ChatMessage {* is rendered with external image auto-loading disabled. */fromZendesk?: booleanhasFullEmailContent?: boolean+ citations?: string[]+ confidence?: number+ persistAs?: AIPersistAs+ clarifyingQuestions?: string[]}export const statusOptions: { value: TicketStatus | 'all'; label: string }[] = [@@ -305,6 +323,20 @@ export const aiTriageStatusLabel: Record<AITriageStatus, string> = {awaiting_clarification: 'Waiting for the customer',}+export const aiTriageVerdictLabel: Record<AITriageVerdict, string> = {+ answerable: 'Answerable',+ blocked_on_customer: 'Needs customer info',+ blocked_on_knowledge: 'Needs knowledge',+ out_of_scope: 'Out of scope',+}++export const aiTriageBlockerLabel: Record<AITriageBlocker, string> = {+ none: 'None',+ customer_info: 'Customer info',+ knowledge: 'Knowledge',+ contradiction: 'Contradiction',+}+export const aiTriageProcessingLabel = 'Processing'export const aiTriageFilterOptions: { key: AITriageFilterValue; label: string }[] = [@@ -331,6 +363,31 @@ export function aiTriageResultTagType(result: AITriageResult): AITriageTagType {return AI_TRIAGE_RESULT_TAG_TYPE[result]}+export type TicketListAiTriage =+ | { kind: 'empty' }+ | { kind: 'processing' }+ | { kind: 'tag'; label: string; tagType: AITriageTagType }++export function ticketListAiTriage(triage: AITriage | undefined): TicketListAiTriage {+ if (!triage?.status) {+ return { kind: 'empty' }+ }+ if (triage.status === 'in_progress') {+ return { kind: 'processing' }+ }+ if (triage.status === 'awaiting_clarification') {+ return { kind: 'tag', label: aiTriageStatusLabel.awaiting_clarification, tagType: 'warning' }+ }+ if (triage.result) {+ return {+ kind: 'tag',+ label: aiTriageResultLabel[triage.result],+ tagType: aiTriageResultTagType(triage.result),+ }+ }+ return { kind: 'empty' }+}+export const aiTriageTicketTypeLabel: Record<string, string> = {how_to: 'How-to',diagnostic: 'Diagnostic',diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yamlindex 66c0bbb2f6f6..87936511a8e7 100644--- a/products/conversations/mcp/tools.yaml+++ b/products/conversations/mcp/tools.yaml@@ -18,6 +18,9 @@ tools:conversations-tickets-ai-feedback-create:operation: conversations_tickets_ai_feedback_createenabled: false+ conversations-tickets-ai-human-outcome-create:+ operation: conversations_tickets_ai_human_outcome_create+ enabled: falseconversations-tickets-bulk-update-status-create:operation: conversations_tickets_bulk_update_status_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 675ed2ef72c9..97b4fa354690 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -9846,6 +9846,18 @@ export namespace Schemas {created_at: string | null;}+ /**+ * * `used` - used+ * * `edited` - edited+ */+ export type AiDraftHumanOutcomeEnum = typeof AiDraftHumanOutcomeEnum[keyof typeof AiDraftHumanOutcomeEnum];+++ export const AiDraftHumanOutcomeEnum = {+ Used: 'used',+ Edited: 'edited',+ } as const;+/*** * `good` - good* * `bad` - bad@@ -9879,6 +9891,22 @@ export namespace Schemas {feedback_text?: string;}+ /**+ * Payload for recording whether a human adopted an AI draft.+ */+ export interface AiHumanOutcomeRequest {+ /**+ * ID of the private AI draft being adopted.+ * @maxLength 200+ */+ message_id: string;+ /** used when the human inserts the draft as-is; edited after they change it in the composer.+ *+ * * `used` - used+ * * `edited` - edited */+ outcome: AiDraftHumanOutcomeEnum;+ }+/*** * `persisted` - persisted* * `suggested` - suggested@@ -65676,7 +65704,7 @@ export namespace Schemas {ai_resolved?: boolean;/** @nullable */escalation_reason?: string | null;- /** AI support pipeline triage and outcome (status, result, ticket_type, confidence, attempts, etc.). */+ /** AI support pipeline triage and outcome (status, result, ticket_type, confidence, attempts, verdict, blocker, sources). Retrieve hydrates sources from citations. */readonly ai_triage: unknown;readonly created_at: string;readonly updated_at: string;@@ -95716,7 +95744,9 @@ export namespace Schemas {}export interface TicketError {+ /** Human-readable error message. */detail: string;+ /** Machine-readable error code. */error_type?: string;}