: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): create ticket (#58392)
Alex V8bf657334fbb
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 0c52e18a723a..0b4f39e56891 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -6590,6 +6590,16 @@ const api = {async suggestReply(ticketId: string): Promise<{ suggestion: string }> {return await new ApiRequest().conversationsTicket(ticketId).withAction('suggest_reply').create({ data: {} })},++ async compose(data: {+ message: string+ recipient_email: string+ email_config_id: string+ email_subject?: string+ rich_content?: Record<string, unknown> | null+ }): Promise<{ id: string; ticket_number: number }> {+ return await new ApiRequest().conversationsTickets().withAction('compose').create({ data })+ },},llmPrompts: {diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 9a1e28c9a9a4..1005f4df2509 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -423,6 +423,7 @@ export const FEATURE_FLAGS = {PRODUCT_BUSINESS_KNOWLEDGE: 'product-business-knowledge', // owner: @veryayskiy #team-conversationsPRODUCT_SELECTION_SCREEN_VARIANT: 'product-selection-screen-variant', // owner: @fercgomes #team-growth multivariate=control,spotlight,multiproductPRODUCT_SUPPORT_AI_SUGGESTION: 'product-support-ai-suggestion', // owner: @veryayskiy #team-conversations+ PRODUCT_SUPPORT_CREATE_TICKET: 'product-support-create-ticket', // owner: @veryayskiy #team-conversationsPRODUCT_SUPPORT_GITHUB_CHANNEL: 'product-support-github-channel', // owner: @veryayskiy #team-conversationsPRODUCT_SUPPORT_SIDE_PANEL: 'product-support-side-panel', // owner: @veryayskiy #team-conversationsPRODUCT_SUPPORT_TEAMS_ENABLED: 'product-support-teams-enabled', // owner: @veryayskiy #team-conversationsdiff --git a/posthog/models/person/util.py b/posthog/models/person/util.pyindex 9673b4d0fbfd..c0c7777c643b 100644--- a/posthog/models/person/util.py+++ b/posthog/models/person/util.py@@ -6,6 +6,7 @@ from typing import Optional, TypeVar, Union, castfrom uuid import UUIDfrom zoneinfo import ZoneInfo+from django.db.models import Qfrom django.db.models.query import Prefetch, QuerySetfrom django.db.models.signals import post_delete, post_savefrom django.dispatch import receiver@@ -557,6 +558,23 @@ def get_person_by_distinct_id(team_id: int, distinct_id: str) -> Optional[Person)+def get_person_by_email_property(team_id: int, email: str) -> Optional[Person]:+ """Look up a person by their properties email value.++ Checks common key variants: ``email``, ``Email``, ``$email``.+ No personhog RPC exists for property-based search — uses ORM directly.+ When a personhog RPC is added, convert to _personhog_routed.+ """+ return (+ Person.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm+ .filter(+ Q(properties__email=email) | Q(**{"properties__Email": email}) | Q(**{"properties__$email": email}),+ team_id=team_id,+ )+ .first()+ )++def get_person_by_pk_or_uuid(team_id: int, key: str) -> Optional[Person]:"""Look up a person by UUID or integer PK, routing through personhog when enabled."""try:diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 973e9c349b65..c3cba51c66e9 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -988,6 +988,16 @@ class EmailSendTestThrottle(UserRateThrottle):rate = "6/minute"+class ComposeTicketBurstThrottle(UserRateThrottle):+ scope = "compose_ticket_burst"+ rate = "10/minute"+++class ComposeTicketSustainedThrottle(UserRateThrottle):+ scope = "compose_ticket_sustained"+ rate = "60/hour"++class TeamsAdminGraphThrottle(UserRateThrottle):"""Protect the bot's per-tenant Graph API quota. The TeamsTeamsView /diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex fbbf10a1c938..56b0ac0f5b7d 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -34,9 +34,18 @@ from posthog.models import OrganizationMembershipfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.comment import Commentfrom posthog.models.person.person import Person-from posthog.models.person.util import get_persons_by_distinct_ids+from posthog.models.person.util import (+ get_person_by_distinct_id,+ get_person_by_email_property,+ get_persons_by_distinct_ids,+)from posthog.permissions import APIScopePermission, PostHogFeatureFlagPermission-from posthog.rate_limit import AIBurstRateThrottle, AISustainedRateThrottle+from posthog.rate_limit import (+ AIBurstRateThrottle,+ AISustainedRateThrottle,+ ComposeTicketBurstThrottle,+ ComposeTicketSustainedThrottle,+)from posthog.utils import relative_date_parsefrom products.conversations.backend.ai.suggest import NoMessagesError, suggest_reply@@ -51,7 +60,7 @@ from products.conversations.backend.events import (capture_ticket_priority_changed,capture_ticket_status_changed,)-from products.conversations.backend.models import Ticket, TicketAssignment+from products.conversations.backend.models import EmailChannel, Ticket, TicketAssignmentfrom products.conversations.backend.models.constants import Channel, ChannelDetail, Priority, Statusfrom ee.models.rbac.role import Role@@ -68,6 +77,49 @@ class SuggestReplyErrorSerializer(serializers.Serializer):error_type = serializers.CharField(required=False)+class ComposeTicketSerializer(serializers.Serializer):+ recipient_email = serializers.EmailField(+ help_text="Recipient email address.",+ )+ recipient_distinct_id = serializers.CharField(+ required=False,+ max_length=400,+ help_text="PostHog distinct_id to link the ticket to a person. Falls back to recipient_email.",+ )+ email_subject = serializers.CharField(+ required=False,+ max_length=500,+ help_text="Email subject line.",+ )+ email_config_id = serializers.UUIDField(+ help_text="ID of the EmailChannel to send from.",+ )+ message = serializers.CharField(+ max_length=5000,+ help_text="Message content in markdown.",+ )+ rich_content = serializers.JSONField(+ required=False,+ allow_null=True,+ help_text="TipTap rich content JSON for formatted messages.",+ )++ def validate_message(self, value: str) -> str:+ if not value or not value.strip():+ raise serializers.ValidationError("Message content is required.")+ return value.strip()++ def validate_rich_content(self, value: object) -> object:+ if value is not None and len(json.dumps(value)) > 100_000:+ raise serializers.ValidationError("Rich content too large (max 100KB).")+ return value+++class ComposeTicketResponseSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="Created ticket UUID.")+ ticket_number = serializers.IntegerField(help_text="Human-readable ticket number.")++class TicketPagination(pagination.LimitOffsetPagination):default_limit = 100max_limit = 1000@@ -369,11 +421,25 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Modif did in distinct_ids_set:distinct_id_to_person[did] = person- # Attach person to each ticket (dynamic attribute for serialization)for ticket in tickets:if ticket.distinct_id:ticket.person = distinct_id_to_person.get(ticket.distinct_id)+ # Fallback: for email-channel tickets with no person match,+ # try matching on properties.email (handles cases where the+ # person's distinct_id differs from their email address)+ unmatched = [+ t+ for t in tickets+ if t.distinct_id and not getattr(t, "person", None) and t.channel_source == Channel.EMAIL and t.email_from+ ]+ for ticket in unmatched:+ email = ticket.email_from+ if email:+ found = get_person_by_email_property(self.team_id, email)+ if found is not None:+ ticket.person = found+@extend_schema(parameters=[OpenApiParameter(@@ -760,6 +826,98 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Modreturn Response({"count": count})+ @extend_schema(+ request=ComposeTicketSerializer,+ responses={+ 201: OpenApiResponse(response=ComposeTicketResponseSerializer),+ 400: OpenApiResponse(response=SuggestReplyErrorSerializer),+ },+ )+ @action(+ detail=False,+ methods=["POST"],+ pagination_class=None,+ throttle_classes=[ComposeTicketBurstThrottle, ComposeTicketSustainedThrottle],+ )+ def compose(self, request, *args, **kwargs):+ """Create a new outbound ticket and send the first message to the customer."""+ serializer = ComposeTicketSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ team = self.team++ if not team.conversations_enabled:+ return Response(+ {"detail": "Conversations is not enabled."},+ status=drf_status.HTTP_400_BAD_REQUEST,+ )++ settings = team.conversations_settings or {}++ if not settings.get("email_enabled"):+ return Response(+ {"detail": "Email channel is not enabled."},+ status=drf_status.HTTP_400_BAD_REQUEST,+ )++ email_config = EmailChannel.objects.filter(+ id=data["email_config_id"],+ team=team,+ domain_verified=True,+ ).first()+ if not email_config:+ return Response(+ {"detail": "Email configuration not found or domain not verified."},+ status=drf_status.HTTP_400_BAD_REQUEST,+ )++ recipient_email = data["recipient_email"]+ distinct_id = data.get("recipient_distinct_id", "") or recipient_email++ person = get_person_by_distinct_id(team.id, distinct_id)+ if person is None and distinct_id == recipient_email:+ person = get_person_by_email_property(team.id, recipient_email)+ if person is not None and person.distinct_ids:+ distinct_id = person.distinct_ids[0]++ with transaction.atomic():+ ticket = Ticket.objects.create_with_number(+ team=team,+ channel_source=Channel.EMAIL,+ distinct_id=distinct_id,+ status=Status.OPEN,+ widget_session_id=str(uuid.uuid4()),+ email_config=email_config,+ email_from=data["recipient_email"],+ email_subject=data.get("email_subject", ""),+ )++ Comment.objects.create(+ team=team,+ created_by=request.user,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content=data["message"],+ rich_content=data.get("rich_content"),+ item_context={"author_type": "human", "is_private": False},+ )++ try:+ report_user_action(+ request.user,+ "support ticket composed",+ {"channel_source": Channel.EMAIL},+ team=team,+ request=request,+ )+ except Exception as e:+ capture_exception(e, {"ticket_id": str(ticket.id)})++ return Response(+ {"id": str(ticket.id), "ticket_number": ticket.ticket_number},+ status=drf_status.HTTP_201_CREATED,+ )+def validate_assignee(assignee) -> None:"""Validate assignee payload structure."""diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.pyindex abca07603604..676880de015b 100644--- a/products/conversations/backend/tasks.py+++ b/products/conversations/backend/tasks.py@@ -485,8 +485,9 @@ def send_email_reply(txt_body = contenthtml_body = f"<p>{html_mod.escape(content)}</p>"- subject = ticket.email_subject or "Re: Your support request"- if not subject.lower().startswith("re:"):+ subject = ticket.email_subject or "Your support request"+ is_reply = latest_mapping is not None+ if is_reply and not subject.lower().startswith("re:"):subject = f"Re: {subject}"from_email = formataddr((config.from_name or author_name, config.from_email))diff --git a/products/conversations/frontend/components/ComposeTicket/ComposeTicketButton.tsx b/products/conversations/frontend/components/ComposeTicket/ComposeTicketButton.tsxnew file mode 100644index 000000000000..becc0df8337f--- /dev/null+++ b/products/conversations/frontend/components/ComposeTicket/ComposeTicketButton.tsx@@ -0,0 +1,81 @@+import { useActions, useValues } from 'kea'+import { router } from 'kea-router'+import { useState } from 'react'++import { IconPlus } from '@posthog/icons'+import { LemonButton, LemonButtonProps } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { Popover } from 'lib/lemon-ui/Popover'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { composeTicketLogic } from './composeTicketLogic'+import { ComposeTicketModal } from './ComposeTicketModal'++interface ComposeTicketButtonProps {+ size?: LemonButtonProps['size']+ type?: LemonButtonProps['type']+}++export function ComposeTicketButton({+ size = 'small',+ type = 'primary',+}: ComposeTicketButtonProps): JSX.Element | null {+ const { currentTeam } = useValues(teamLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const { openComposeModal } = useActions(composeTicketLogic)+ const [showDisabledPopover, setShowDisabledPopover] = useState(false)+ const conversationsEnabled = !!currentTeam?.conversations_enabled++ if (!featureFlags[FEATURE_FLAGS.PRODUCT_SUPPORT_CREATE_TICKET]) {+ return null+ }++ return (+ <>+ <Popover+ visible={showDisabledPopover}+ onClickOutside={() => setShowDisabledPopover(false)}+ overlay={+ <div className="p-3 max-w-xs flex flex-col gap-2">+ <p className="m-0 text-sm">+ Conversations are not enabled for this project. Enable them in settings to start writing to+ customers.+ </p>+ <LemonButton+ type="primary"+ size="small"+ onClick={() => {+ setShowDisabledPopover(false)+ router.actions.push(urls.supportSettings())+ }}+ fullWidth+ center+ >+ Go to settings+ </LemonButton>+ </div>+ }+ >+ <LemonButton+ type={type}+ size={size}+ icon={<IconPlus />}+ onClick={() => {+ if (conversationsEnabled) {+ openComposeModal()+ } else {+ setShowDisabledPopover(true)+ }+ }}+ data-attr="compose-ticket-button"+ >+ New ticket+ </LemonButton>+ </Popover>+ <ComposeTicketModal />+ </>+ )+}diff --git a/products/conversations/frontend/components/ComposeTicket/ComposeTicketModal.tsx b/products/conversations/frontend/components/ComposeTicket/ComposeTicketModal.tsxnew file mode 100644index 000000000000..23df3105a13b--- /dev/null+++ b/products/conversations/frontend/components/ComposeTicket/ComposeTicketModal.tsx@@ -0,0 +1,95 @@+import { useActions, useValues } from 'kea'+import { useRef } from 'react'++import { LemonButton, LemonInput, LemonModal, LemonSelect } from '@posthog/lemon-ui'++import { RichContentEditorType } from 'lib/components/RichContentEditor/types'++import { SupportEditor, serializeToMarkdown } from '../Editor'+import { composeTicketLogic } from './composeTicketLogic'++export function ComposeTicketModal(): JSX.Element | null {+ const { isOpen, recipientEmail, emailSubject, emailConfigId, emailConfigs, emailConfigsLoading, composingLoading } =+ useValues(composeTicketLogic)+ const { closeComposeModal, setRecipientEmail, setEmailSubject, setEmailConfigId, submitCompose } =+ useActions(composeTicketLogic)++ const editorRef = useRef<RichContentEditorType | null>(null)+ const verifiedEmailConfigs = emailConfigs.filter((c) => c.domain_verified)++ const emailConfigOptions = verifiedEmailConfigs.map((c) => ({+ value: c.id,+ label: `${c.from_name} <${c.from_email}>`,+ }))++ const handleSubmit = (): void => {+ const richContent = editorRef.current?.getJSON() ?? null+ const content = richContent ? serializeToMarkdown(richContent) : ''+ submitCompose(content, richContent as Record<string, unknown> | null)+ }++ return (+ <LemonModal+ isOpen={isOpen}+ onClose={closeComposeModal}+ title="New outbound ticket"+ footer={+ <>+ <LemonButton type="secondary" onClick={closeComposeModal}>+ Cancel+ </LemonButton>+ <LemonButton type="primary" onClick={handleSubmit} loading={composingLoading}>+ Send+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-3 min-w-[500px]">+ <div className="flex flex-col gap-1">+ <label className="font-semibold text-xs">From</label>+ <LemonSelect+ value={emailConfigId || undefined}+ options={emailConfigOptions}+ onChange={(value) => value && setEmailConfigId(value)}+ placeholder={emailConfigsLoading ? 'Loading...' : 'Select sender address...'}+ loading={emailConfigsLoading}+ fullWidth+ />+ </div>++ <div className="flex flex-col gap-1">+ <label className="font-semibold text-xs">To</label>+ <LemonInput+ type="email"+ value={recipientEmail}+ onChange={setRecipientEmail}+ placeholder="[email protected]"+ fullWidth+ />+ </div>++ <div className="flex flex-col gap-1">+ <label className="font-semibold text-xs">Subject</label>+ <LemonInput+ value={emailSubject}+ onChange={setEmailSubject}+ placeholder="Email subject (optional)"+ fullWidth+ />+ </div>++ <div className="flex flex-col gap-1">+ <label className="font-semibold text-xs">Message</label>+ <SupportEditor+ placeholder="Type your message..."+ onCreate={(editor) => {+ editorRef.current = editor+ }}+ onPressCmdEnter={handleSubmit}+ minRows={5}+ />+ </div>+ </div>+ </LemonModal>+ )+}diff --git a/products/conversations/frontend/components/ComposeTicket/composeTicketLogic.ts b/products/conversations/frontend/components/ComposeTicket/composeTicketLogic.tsnew file mode 100644index 000000000000..ebeea436762c--- /dev/null+++ b/products/conversations/frontend/components/ComposeTicket/composeTicketLogic.ts@@ -0,0 +1,127 @@+import { actions, kea, listeners, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'+import { router } from 'kea-router'++import { lemonToast } from '@posthog/lemon-ui'++import api from 'lib/api'+import { urls } from 'scenes/urls'++import type { EmailConfigStatus } from '../../scenes/settings/supportSettingsLogic'+import type { composeTicketLogicType } from './composeTicketLogicType'++export const composeTicketLogic = kea<composeTicketLogicType>([+ path(['products', 'conversations', 'frontend', 'components', 'ComposeTicket', 'composeTicketLogic']),+ actions({+ openComposeModal: true,+ closeComposeModal: true,+ setRecipientEmail: (email: string) => ({ email }),+ setEmailSubject: (subject: string) => ({ subject }),+ setEmailConfigId: (configId: string) => ({ configId }),+ resetForm: true,+ submitCompose: (message: string, richContent: Record<string, unknown> | null) => ({ message, richContent }),+ submitComposeFinished: true,+ }),+ reducers({+ isOpen: [+ false,+ {+ openComposeModal: () => true,+ closeComposeModal: () => false,+ resetForm: () => false,+ },+ ],+ recipientEmail: [+ '',+ {+ setRecipientEmail: (_, { email }) => email,+ resetForm: () => '',+ },+ ],+ emailSubject: [+ '',+ {+ setEmailSubject: (_, { subject }) => subject,+ resetForm: () => '',+ },+ ],+ emailConfigId: [+ '',+ {+ setEmailConfigId: (_, { configId }) => configId,+ resetForm: () => '',+ },+ ],+ composingLoading: [+ false,+ {+ submitCompose: () => true,+ submitComposeFinished: () => false,+ resetForm: () => false,+ },+ ],+ }),+ loaders({+ emailConfigs: [+ [] as EmailConfigStatus[],+ {+ loadEmailConfigs: async (): Promise<EmailConfigStatus[]> => {+ try {+ // nosemgrep: prefer-codegen-api+ const response = await api.get('api/conversations/v1/email/status')+ return response.configs || []+ } catch {+ return []+ }+ },+ },+ ],+ }),+ listeners(({ actions, values }) => ({+ openComposeModal: () => {+ actions.loadEmailConfigs()+ },+ submitCompose: async ({ message, richContent }) => {+ const { recipientEmail, emailSubject, emailConfigId } = values++ if (!message.trim()) {+ lemonToast.error('Message is required.')+ actions.submitComposeFinished()+ return+ }++ if (!recipientEmail) {+ lemonToast.error('Recipient email is required.')+ actions.submitComposeFinished()+ return+ }++ if (!emailConfigId) {+ lemonToast.error('Please select a "From" email address.')+ actions.submitComposeFinished()+ return+ }++ try {+ const result = await api.conversationsTickets.compose({+ message,+ recipient_email: recipientEmail,+ email_config_id: emailConfigId,+ ...(emailSubject ? { email_subject: emailSubject } : {}),+ ...(richContent ? { rich_content: richContent } : {}),+ })++ lemonToast.success('Ticket created successfully.')+ actions.resetForm()+ router.actions.push(urls.supportTicketDetail(result.ticket_number))+ } catch (error: unknown) {+ const detail =+ error && typeof error === 'object' && 'detail' in error+ ? (error as { detail: string }).detail+ : 'Failed to create ticket.'+ lemonToast.error(detail)+ actions.submitComposeFinished()+ }+ },+ })),+])diff --git a/products/conversations/frontend/components/ComposeTicket/index.ts b/products/conversations/frontend/components/ComposeTicket/index.tsnew file mode 100644index 000000000000..c20de2f08571--- /dev/null+++ b/products/conversations/frontend/components/ComposeTicket/index.ts@@ -0,0 +1,3 @@+export { ComposeTicketButton } from './ComposeTicketButton'+export { ComposeTicketModal } from './ComposeTicketModal'+export { composeTicketLogic } from './composeTicketLogic'diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 85381fddc828..0d1b10e1049c 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -611,6 +611,37 @@ export interface BulkUpdateTagsResponseApi {skipped: BulkUpdateTagsErrorApi[]}+export interface ComposeTicketApi {+ /** Recipient email address. */+ recipient_email: string+ /**+ * PostHog distinct_id to link the ticket to a person. Falls back to recipient_email.+ * @maxLength 400+ */+ recipient_distinct_id?: string+ /**+ * Email subject line.+ * @maxLength 500+ */+ email_subject?: string+ /** ID of the EmailChannel to send from. */+ email_config_id: string+ /**+ * Message content in markdown.+ * @maxLength 5000+ */+ message: string+ /** TipTap rich content JSON for formatted messages. */+ rich_content?: unknown+}++export interface ComposeTicketResponseApi {+ /** Created ticket UUID. */+ id: string+ /** Human-readable ticket number. */+ ticket_number: number+}+export type ConversationsListParams = {/*** Number of results to return per page.diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.tsindex 4c64387d97c3..5935ab219ab8 100644--- a/products/conversations/frontend/generated/api.ts+++ b/products/conversations/frontend/generated/api.ts@@ -11,6 +11,8 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'import type {BulkUpdateTagsRequestApi,BulkUpdateTagsResponseApi,+ ComposeTicketApi,+ ComposeTicketResponseApi,ConversationApi,ConversationsListParams,ConversationsTicketsListParams,@@ -472,6 +474,26 @@ export const conversationsTicketsBulkUpdateTagsCreate = async (})}+export const getConversationsTicketsComposeCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/conversations/tickets/compose/`+}++/**+ * Create a new outbound ticket and send the first message to the customer.+ */+export const conversationsTicketsComposeCreate = async (+ projectId: string,+ composeTicketApi: ComposeTicketApi,+ options?: RequestInit+): Promise<ComposeTicketResponseApi> => {+ return apiMutator<ComposeTicketResponseApi>(getConversationsTicketsComposeCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(composeTicketApi),+ })+}+export const getConversationsTicketsUnreadCountRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/conversations/tickets/unread_count/`}diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.tsindex 1b04efb1a731..d803d94d61d6 100644--- a/products/conversations/frontend/generated/api.zod.ts+++ b/products/conversations/frontend/generated/api.zod.ts@@ -212,3 +212,29 @@ export const ConversationsTicketsBulkUpdateTagsCreateBody = /* @__PURE__ */ zod.),tags: zod.array(zod.string()).describe('Tag names to add, remove, or set.'),})++/**+ * Create a new outbound ticket and send the first message to the customer.+ */+export const conversationsTicketsComposeCreateBodyRecipientDistinctIdMax = 400++export const conversationsTicketsComposeCreateBodyEmailSubjectMax = 500++export const conversationsTicketsComposeCreateBodyMessageMax = 5000++export const ConversationsTicketsComposeCreateBody = /* @__PURE__ */ zod.object({+ recipient_email: zod.email().describe('Recipient email address.'),+ recipient_distinct_id: zod+ .string()+ .max(conversationsTicketsComposeCreateBodyRecipientDistinctIdMax)+ .optional()+ .describe('PostHog distinct_id to link the ticket to a person. Falls back to recipient_email.'),+ email_subject: zod+ .string()+ .max(conversationsTicketsComposeCreateBodyEmailSubjectMax)+ .optional()+ .describe('Email subject line.'),+ email_config_id: zod.uuid().describe('ID of the EmailChannel to send from.'),+ message: zod.string().max(conversationsTicketsComposeCreateBodyMessageMax).describe('Message content in markdown.'),+ rich_content: zod.unknown().optional().describe('TipTap rich content JSON for formatted messages.'),+})diff --git a/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx b/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsxindex 21fc73b5a3ca..d0d7065d0d85 100644--- a/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx+++ b/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx@@ -38,6 +38,7 @@ import {AssigneeSelect,} from '../../components/Assignee'import { ChannelsTag } from '../../components/Channels/ChannelsTag'+import { ComposeTicketButton } from '../../components/ComposeTicket'import { ConversationsDisabledBanner } from '../../components/ConversationsDisabledBanner'import { SavedViewsButton } from '../../components/SavedViews/SavedViewsButton'import { ScenesTabs } from '../../components/ScenesTabs'@@ -525,6 +526,7 @@ export function SupportTicketsScene(): JSX.Element {resourceType={{type: 'conversation',}}+ actions={<ComposeTicketButton />}/><ScenesTabs />{conversationsDisabled ? <ConversationsDisabledBanner /> : null}diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yamlindex 499a8d7c7962..d45ee339914e 100644--- a/products/conversations/mcp/tools.yaml+++ b/products/conversations/mcp/tools.yaml@@ -42,6 +42,9 @@ tools:conversations-tickets-bulk-update-tags-create:operation: conversations_tickets_bulk_update_tags_createenabled: false+ conversations-tickets-compose-create:+ operation: conversations_tickets_compose_create+ enabled: falseconversations-tickets-create:operation: conversations_tickets_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b4201f9e6384..2e5f8ccb0bbf 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -7587,6 +7587,37 @@ export namespace Schemas {value: string;}+ export interface ComposeTicket {+ /** Recipient email address. */+ recipient_email: string;+ /**+ * PostHog distinct_id to link the ticket to a person. Falls back to recipient_email.+ * @maxLength 400+ */+ recipient_distinct_id?: string;+ /**+ * Email subject line.+ * @maxLength 500+ */+ email_subject?: string;+ /** ID of the EmailChannel to send from. */+ email_config_id: string;+ /**+ * Message content in markdown.+ * @maxLength 5000+ */+ message: string;+ /** TipTap rich content JSON for formatted messages. */+ rich_content?: unknown;+ }++ export interface ComposeTicketResponse {+ /** Created ticket UUID. */+ id: string;+ /** Human-readable ticket number. */+ ticket_number: number;+ }+/*** * `won` - won* `lost` - lost