:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(posthog-ai): stop /ticket creating duplicate and blank tickets (#72932)
Christiaan Hendriksenbe1c5e65b6f5
diff --git a/frontend/src/lib/components/Support/SupportForm.tsx b/frontend/src/lib/components/Support/SupportForm.tsxindex 1b36de3248e2..ee55d4aab212 100644--- a/frontend/src/lib/components/Support/SupportForm.tsx+++ b/frontend/src/lib/components/Support/SupportForm.tsx@@ -55,7 +55,14 @@ const SUPPORT_TICKET_KIND_TO_PROMPT: Record<SupportTicketKind, string> = {support: 'What can we help you with?',}-export function SupportForm(): JSX.Element | null {+interface SupportFormProps {+ /** Overrides the message field label (e.g. "Anything to add?" for the PostHog AI ticket flow) */+ messageLabel?: string+ /** Overrides the message field placeholder */+ messagePlaceholder?: string+}++export function SupportForm({ messageLabel, messagePlaceholder }: SupportFormProps = {}): JSX.Element | null {const { sendSupportRequest, conversationsFlagEnabled } = useValues(supportLogic)const { setSendSupportRequestValue } = useActions(supportLogic)const { objectStorageAvailable } = useValues(preflightLogic)@@ -177,12 +184,19 @@ export function SupportForm(): JSX.Element | null {)}<LemonFieldname="message"- label={sendSupportRequest.kind ? SUPPORT_TICKET_KIND_TO_PROMPT[sendSupportRequest.kind] : 'Content'}+ label={+ messageLabel ??+ (sendSupportRequest.kind ? SUPPORT_TICKET_KIND_TO_PROMPT[sendSupportRequest.kind] : 'Content')+ }>{(props) => (<div ref={dropRef} className="flex flex-col gap-2" onPaste={handlePaste}><LemonTextArea- placeholder={SUPPORT_TICKET_TEMPLATES[sendSupportRequest.kind] ?? 'Type your message here'}+ placeholder={+ messagePlaceholder ??+ SUPPORT_TICKET_TEMPLATES[sendSupportRequest.kind] ??+ 'Type your message here'+ }data-attr="support-form-content-input"minRows={5}{...props}diff --git a/frontend/src/lib/components/Support/supportLogic.ts b/frontend/src/lib/components/Support/supportLogic.tsindex 0aafa1e415f2..bd7ed2bb7e03 100644--- a/frontend/src/lib/components/Support/supportLogic.ts+++ b/frontend/src/lib/components/Support/supportLogic.ts@@ -1066,6 +1066,10 @@ export const supportLogic = kea<supportLogicType>([lemonToast.success("Got the message! If we have follow-up information for you, we'll reply via email.")+ // The beacon response is opaque, so the Zendesk ticket id is unknown here;+ // the client-generated uuid (also embedded in the subject) marks success for+ // callers watching lastSubmittedTicketId+ actions.setLastSubmittedTicketId(zendesk_ticket_uuid)// Only close and reset the form on successactions.closeSupportForm()actions.resetSendSupportRequest()diff --git a/frontend/src/scenes/max/TicketPrompt.tsx b/frontend/src/scenes/max/TicketPrompt.tsxindex fc1fa150d865..bc70a832ef64 100644--- a/frontend/src/scenes/max/TicketPrompt.tsx+++ b/frontend/src/scenes/max/TicketPrompt.tsx@@ -1,12 +1,14 @@import { useActions, useValues } from 'kea'-import { useCallback, useEffect, useState } from 'react'+import { useRef, useState } from 'react'-import { LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'+import { LemonButton, LemonInput, LemonModal, lemonToast } from '@posthog/lemon-ui'import { SupportForm } from 'lib/components/Support/SupportForm'import { SupportTicketTargetArea, supportLogic } from 'lib/components/Support/supportLogic'+import { userLogic } from 'scenes/userLogic'import { maxThreadLogic } from './maxThreadLogic'+import { appendTicketMetadata, composeTicketBody } from './ticketUtils'function formatConfirmationMessage(ticketId: string): string {return `I've created a support ticket for you.\nYour ticket ID is #${ticketId}.\nOur support team will get back to you soon!`@@ -25,7 +27,8 @@ interface TicketPromptProps {/*** In-chat support ticket form for the /ticket command.- * - If `summary` is provided: shows "Create support ticket" button with pre-filled summary+ * - If `summary` is provided: shows a "Create support ticket" button; the modal attaches the AI+ * summary as context and offers an optional "anything to add" note* - If no `summary`: shows input field for user to describe their issue*/export function TicketPrompt({@@ -37,55 +40,39 @@ export function TicketPrompt({}: TicketPromptProps): JSX.Element {const [issueText, setIssueText] = useState(initialText ?? '')const [isSubmitting, setIsSubmitting] = useState(false)+ const [hasSubmitted, setHasSubmitted] = useState(false)const [isSupportModalOpen, setIsSupportModalOpen] = useState(false)- const { sendSupportRequest, lastSubmittedTicketId } = useValues(supportLogic)- const { resetSendSupportRequest, setSendSupportRequestValue, closeSupportForm } = useActions(supportLogic)+ const { sendSupportRequest, conversationsFlagEnabled } = useValues(supportLogic)+ const { resetSendSupportRequest, closeSupportForm } = useActions(supportLogic)const { appendMessageToConversation } = useActions(maxThreadLogic)+ const { user } = useValues(userLogic)- const [pendingTicketSubmission, setPendingTicketSubmission] = useState(false)- const [ticketIdBeforeSubmission, setTicketIdBeforeSubmission] = useState<string | null>(null)+ const submitInFlightRef = useRef(false)- const messageContent = summary || issueText+ function handleTicketCreated(ticketId: string): void {+ // Persist the confirmation message and add it to the thread+ const confirmationMessage = formatConfirmationMessage(ticketId)+ appendMessageToConversation(confirmationMessage)- const handleTicketCreated = useCallback(- (ticketId: string): void => {- // The posthog_ai_support_ticket_created event is captured in supportLogic once the ticket- // id resolves, so it fires on every submit path (see ai_conversation_id below).-- // Persist the confirmation message and add it to the thread- const confirmationMessage = formatConfirmationMessage(ticketId)- appendMessageToConversation(confirmationMessage)-- setIsSupportModalOpen(false)- setIsSubmitting(false)- closeSupportForm()- },- [appendMessageToConversation, closeSupportForm]- )-- useEffect(() => {- if (pendingTicketSubmission && lastSubmittedTicketId && lastSubmittedTicketId !== ticketIdBeforeSubmission) {- handleTicketCreated(lastSubmittedTicketId)- setPendingTicketSubmission(false)- }- }, [lastSubmittedTicketId, pendingTicketSubmission, ticketIdBeforeSubmission, handleTicketCreated])-- function appendMetadataToMessage(message: string): string {- const metadataLines = [`Conversation ID: ${conversationId}`, traceId ? `Trace ID: ${traceId}` : null].filter(- Boolean- )- return message ? `${message}\n\n----\n${metadataLines.join('\n')}` : metadataLines.join('\n')+ submitInFlightRef.current = false+ setHasSubmitted(true)+ setIsSupportModalOpen(false)+ setIsSubmitting(false)+ closeSupportForm()}function openSupportModal(): void {+ if (hasSubmitted) {+ return+ }resetSendSupportRequest({name: '',email: '',kind: 'bug',target_area: targetArea ?? 'analytics',severity_level: 'low',- message: messageContent,+ message: summary ? '' : issueText,tags: ['raised_from_posthog_ai_chat'],ai_conversation_id: conversationId,ai_trace_id: traceId,@@ -94,29 +81,56 @@ export function TicketPrompt({}async function handleSupportFormSubmit(): Promise<void> {- setIsSubmitting(true)+ if (submitInFlightRef.current || hasSubmitted) {+ return+ }- const finalMessage = appendMetadataToMessage(sendSupportRequest.message)- setSendSupportRequestValue('message', finalMessage)+ const body = composeTicketBody({ note: sendSupportRequest.message, summary })+ const finalMessage = appendTicketMetadata(body, { conversationId, traceId })+ if (!finalMessage) {+ lemonToast.error('Please add a description before creating a ticket.')+ return+ }+ // The Zendesk form variant requires the triage fields the kea-forms validator would have+ // enforced before this direct submit+ if (+ !conversationsFlagEnabled &&+ (!sendSupportRequest.kind || !sendSupportRequest.target_area || !sendSupportRequest.severity_level)+ ) {+ lemonToast.error('Please choose a message type, topic, and severity level.')+ return+ }++ submitInFlightRef.current = true+ setIsSubmitting(true)const ticketIdBefore = supportLogic.values.lastSubmittedTicketId- setTicketIdBeforeSubmission(ticketIdBefore)- setPendingTicketSubmission(true)try {- await supportLogic.asyncActions.submitSendSupportRequest()+ await supportLogic.asyncActions.submitSupportTicket({+ ...sendSupportRequest,+ name: user?.first_name ?? sendSupportRequest.name ?? 'name not set',+ email: user?.email ?? sendSupportRequest.email ?? '',+ message: finalMessage,+ })} catch {// Failure is detected below via the unchanged ticket id}- // Success is handled by the effect watching lastSubmittedTicketId. If no ticket was created,- // the submit failed — stop the spinner so the user can retry (the error toast already showed).- if (supportLogic.values.lastSubmittedTicketId === ticketIdBefore) {+ const ticketIdAfter = supportLogic.values.lastSubmittedTicketId+ if (ticketIdAfter && ticketIdAfter !== ticketIdBefore) {+ handleTicketCreated(ticketIdAfter)+ } else {+ // Submit failed (the error toast already showed) — allow a retry with the note untouched+ submitInFlightRef.current = falsesetIsSubmitting(false)- setPendingTicketSubmission(false)}}function handleSupportModalCancel(): void {+ // The in-flight request cannot be aborted, so closing now would re-arm the submit+ // controls and allow a duplicate ticket+ if (submitInFlightRef.current) {+ return+ }setIsSupportModalOpen(false)- setPendingTicketSubmission(false)setIsSubmitting(false)closeSupportForm()}@@ -128,7 +142,11 @@ export function TicketPrompt({title="Create support ticket"footer={<div className="flex items-center gap-2">- <LemonButton type="secondary" onClick={handleSupportModalCancel}>+ <LemonButton+ type="secondary"+ onClick={handleSupportModalCancel}+ disabledReason={isSubmitting ? 'Submitting your ticket…' : undefined}+ >Cancel</LemonButton><LemonButton@@ -136,13 +154,28 @@ export function TicketPrompt({data-attr="submit"onClick={() => void handleSupportFormSubmit()}loading={isSubmitting}+ disabledReason={hasSubmitted ? 'Ticket already created' : undefined}>Submit</LemonButton></div>}>- <SupportForm />+ {summary && (+ <div className="flex flex-col gap-1 mb-3">+ <p className="m-0 font-medium">PostHog AI's analysis</p>+ <p className="m-0 text-xs text-secondary">This is attached to your ticket for our support team.</p>+ <div className="max-h-40 overflow-y-auto p-2 border border-border rounded bg-bg-light text-sm whitespace-pre-wrap">+ {summary}+ </div>+ </div>+ )}+ <SupportForm+ messageLabel={summary ? 'Anything to add? (optional)' : undefined}+ messagePlaceholder={+ summary ? 'Add anything that would help our support team understand your issue' : undefined+ }+ /></LemonModal>)@@ -151,7 +184,12 @@ export function TicketPrompt({return (<><div className="flex gap-2 ml-1 mt-1">- <LemonButton type="primary" size="small" onClick={openSupportModal}>+ <LemonButton+ type="primary"+ size="small"+ onClick={openSupportModal}+ disabledReason={hasSubmitted ? 'Ticket already created' : undefined}+ >Create support ticket</LemonButton></div>@@ -169,12 +207,27 @@ export function TicketPrompt({placeholder="What do you need help with?"value={issueText}onChange={setIssueText}- onPressEnter={openSupportModal}+ onPressEnter={() => {+ if (issueText.trim()) {+ openSupportModal()+ }+ }}fullWidthautoFocus/><div className="flex gap-2">- <LemonButton type="primary" size="small" onClick={openSupportModal} disabled={!issueText.trim()}>+ <LemonButton+ type="primary"+ size="small"+ onClick={openSupportModal}+ disabledReason={+ hasSubmitted+ ? 'Ticket already created'+ : !issueText.trim()+ ? 'Describe your issue first'+ : undefined+ }+ >Create support ticket</LemonButton></div>diff --git a/frontend/src/scenes/max/ticketUtils.test.ts b/frontend/src/scenes/max/ticketUtils.test.tsindex 661ad0d64bc2..c49248ae9572 100644--- a/frontend/src/scenes/max/ticketUtils.test.ts+++ b/frontend/src/scenes/max/ticketUtils.test.ts@@ -1,5 +1,5 @@import { ThreadMessage } from './maxLogic'-import { getTicketSummaryData, parseTicketTargetArea } from './ticketUtils'+import { appendTicketMetadata, composeTicketBody, getTicketSummaryData, parseTicketTargetArea } from './ticketUtils'const human = (content: string): ThreadMessage => ({ type: 'human', content }) as unknown as ThreadMessageconst ai = (content: string): ThreadMessage => ({ type: 'ai', content }) as unknown as ThreadMessage@@ -49,6 +49,44 @@ describe('ticketUtils', () => {})})+ describe('composeTicketBody', () => {+ it.each([+ [+ 'note leads with summary attached',+ 'It still repros in prod',+ SUMMARY,+ `It still repros in prod\n\n----\nPostHog AI's analysis:\n${SUMMARY}`,+ ],+ ['summary alone when note is empty', '', SUMMARY, SUMMARY],+ ['summary alone when note is whitespace', ' ', SUMMARY, SUMMARY],+ ['note alone when no summary', 'Recordings are missing', undefined, 'Recordings are missing'],+ ['empty when neither note nor summary', ' ', undefined, ''],+ ])('%s', (_name, note, summary, expected) => {+ expect(composeTicketBody({ note, summary })).toBe(expected)+ })+ })++ describe('appendTicketMetadata', () => {+ const ids = { conversationId: 'conv-1', traceId: 'trace-1' }++ it('returns empty string for an empty body so metadata alone is never submitted', () => {+ expect(appendTicketMetadata('', ids)).toBe('')+ expect(appendTicketMetadata(' ', ids)).toBe('')+ })++ it('appends conversation and trace ids to a non-empty body', () => {+ expect(appendTicketMetadata('My issue', ids)).toBe(+ 'My issue\n\n----\nConversation ID: conv-1\nTrace ID: trace-1'+ )+ })++ it('omits the trace line when there is no trace id', () => {+ expect(appendTicketMetadata('My issue', { conversationId: 'conv-1', traceId: null })).toBe(+ 'My issue\n\n----\nConversation ID: conv-1'+ )+ })+ })+describe('parseTicketTargetArea', () => {it.each([['bold topic line with valid area', 'Issue: foo\n\n**Topic:** data_warehouse', 'data_warehouse'],diff --git a/frontend/src/scenes/max/ticketUtils.ts b/frontend/src/scenes/max/ticketUtils.tsindex cb192e75d40f..f329fa53f2c6 100644--- a/frontend/src/scenes/max/ticketUtils.ts+++ b/frontend/src/scenes/max/ticketUtils.ts@@ -165,6 +165,37 @@ export function getTicketSummaryData(return null}+/**+ * Builds the ticket body from the user's own note and, when present, PostHog AI's summary.+ * The user's note leads so a human framing is always on top; the AI summary is attached as+ * supporting context. Returns an empty string when there is nothing to send.+ */+export function composeTicketBody({ note, summary }: { note: string; summary?: string }): string {+ const trimmedNote = note.trim()+ if (summary) {+ return trimmedNote ? `${trimmedNote}\n\n----\nPostHog AI's analysis:\n${summary}` : summary+ }+ return trimmedNote+}++/**+ * Appends the conversation and trace identifiers to a ticket body. Returns an empty string when+ * the body is empty, so metadata alone can never be submitted as a ticket.+ */+export function appendTicketMetadata(+ body: string,+ { conversationId, traceId }: { conversationId: string; traceId: string | null }+): string {+ const trimmedBody = body.trim()+ if (!trimmedBody) {+ return ''+ }+ const metadataLines = [`Conversation ID: ${conversationId}`, traceId ? `Trace ID: ${traceId}` : null].filter(+ Boolean+ )+ return `${trimmedBody}\n\n----\n${metadataLines.join('\n')}`+}+/*** Checks if a message is a ticket confirmation message.*/