: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): route in-app support submissions to conversations when flag on (#70726)
Abigail2dab4a66f3d1
diff --git a/frontend/src/layout/FeaturePreviews/FeaturePreviews.tsx b/frontend/src/layout/FeaturePreviews/FeaturePreviews.tsxindex 8337ad0078d8..add9b4db3e1e 100644--- a/frontend/src/layout/FeaturePreviews/FeaturePreviews.tsx+++ b/frontend/src/layout/FeaturePreviews/FeaturePreviews.tsx@@ -1,5 +1,5 @@import { useActions, useAsyncActions, useValues } from 'kea'-import { useLayoutEffect, useState } from 'react'+import { useEffect, useLayoutEffect, useState } from 'react'import { IconBell, IconCheck } from '@posthog/icons'import { LemonBanner, LemonButton, LemonInput, LemonSwitch, LemonTextArea, Link } from '@posthog/lemon-ui'@@ -216,6 +216,15 @@ function FeaturePreview({ feature, warning }: FeaturePreviewProps): JSX.Elementconst [feedback, setFeedback] = useState('')+ // Clear the draft when this card's feedback panel closes (success or cancel). A failed submit+ // leaves the panel open (activeFeedbackFlagKey is unchanged on failure), so the text is kept+ // for a retry rather than lost.+ useEffect(() => {+ if (!isFeedbackActive) {+ setFeedback('')+ }+ }, [isFeedbackActive])+return (<PreviewCardfeature={feature}@@ -270,9 +279,9 @@ function FeaturePreview({ feature, warning }: FeaturePreviewProps): JSX.ElementonChange={(value) => setFeedback(value)}onKeyDown={(e) => {if (e.key === 'Enter' && e.metaKey) {- void submitEarlyAccessFeatureFeedback(feedback).then(() => {- setFeedback('')- })+ // Clearing on success is handled when the panel closes; a failed+ // submit keeps the panel open so the text survives for a retry+ void submitEarlyAccessFeatureFeedback(feedback)} else if (e.key === 'Escape') {cancelEarlyAccessFeatureFeedback()setFeedback('')@@ -293,9 +302,9 @@ function FeaturePreview({ feature, warning }: FeaturePreviewProps): JSX.Element<LemonButtontype="primary"onClick={() => {- void submitEarlyAccessFeatureFeedback(feedback).then(() => {- setFeedback('')- })+ // Clearing on success is handled when the panel closes; a failed+ // submit keeps the panel open so the text survives for a retry+ void submitEarlyAccessFeatureFeedback(feedback)}}loading={activeFeedbackFlagKeyLoading}className="flex-1"diff --git a/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.test.ts b/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.test.tsindex b3d9b6dbea21..63a9cd9b17ee 100644--- a/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.test.ts+++ b/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.test.ts@@ -28,7 +28,7 @@ describe('featurePreviewsLogic - submitEarlyAccessFeatureFeedback', () => {useMocks({post: {- 'https://posthoghelp.zendesk.com/api/v2/requests.json': [200, {}],+ 'https://posthoghelp.zendesk.com/api/v2/requests.json': [200, { request: { id: 123 } }],},})initKeaTests()@@ -51,6 +51,34 @@ describe('featurePreviewsLogic - submitEarlyAccessFeatureFeedback', () => {})})+describe('featurePreviewsLogic - submitEarlyAccessFeatureFeedback failure', () => {+ let logic: ReturnType<typeof featurePreviewsLogic.build>++ beforeEach(() => {+ jest.clearAllMocks()+ useMocks({+ post: {+ // Zendesk rejects the ticket; with no beacon fallback the support submit reports failure+ 'https://posthoghelp.zendesk.com/api/v2/requests.json': [500, {}],+ },+ })+ ;(navigator as any).sendBeacon = jest.fn(() => false)+ initKeaTests()+ logic = featurePreviewsLogic()+ logic.mount()+ userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)+ })++ test('keeps the feedback panel open so the text survives for a retry', async () => {+ logic.actions.beginEarlyAccessFeatureFeedback('test')+ await logic.asyncActions.submitEarlyAccessFeatureFeedback('important feedback')++ // The submit failed, so activeFeedbackFlagKey stays set — the panel (and the component's+ // local draft) survive. On success it would be cleared to null, closing the panel.+ await expectLogic(logic).toMatchValues({ activeFeedbackFlagKey: 'test', activeFeedbackFlagKeyLoading: false })+ })+})+describe('featurePreviewsLogic - updateEarlyAccessFeatureEnrollment', () => {let logic: ReturnType<typeof featurePreviewsLogic.build>const mockUpdateEnrollment = jest.fn()diff --git a/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.tsx b/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.tsxindex e98e277d4995..067d8a6b3b35 100644--- a/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.tsx+++ b/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.tsx@@ -28,7 +28,7 @@ export const featurePreviewsLogic = kea<featurePreviewsLogicType>([path(['layout', 'FeaturePreviews', 'featurePreviewsLogic']),connect(() => ({values: [featureFlagLogic, ['featureFlags'], userLogic, ['user']],- actions: [supportLogic, ['submitZendeskTicket'], teamLogic, ['addProductIntentForCrossSell']],+ actions: [supportLogic, ['submitSupportTicket'], teamLogic, ['addProductIntentForCrossSell']],})),actions({setSearchTerm: (searchTerm: string) => ({ searchTerm }),@@ -63,16 +63,28 @@ export const featurePreviewsLogic = kea<featurePreviewsLogicType>([if (!values.activeFeedbackFlagKey) {throw new Error('Cannot submit early access feature feedback without an active flag key')}- await supportLogic.asyncActions.submitZendeskTicket({+ const feature = values.rawEarlyAccessFeatures.find(+ (f) => f.flagKey === values.activeFeedbackFlagKey+ )+ // submitSupportTicket sets lastSubmittedTicketId only on success (it swallows+ // failures with an error toast), so compare it before/after to tell them apart+ const ticketIdBefore = supportLogic.values.lastSubmittedTicketId+ await supportLogic.asyncActions.submitSupportTicket({name: values.user.first_name,email: values.user.email,kind: 'feedback',// NOTE: We don't know which area the flag should be - for now we just override it to be the key...target_area: values.activeFeedbackFlagKey as any,severity_level: 'low',- message,+ // The feature identity must live in the message itself: conversations tickets+ // carry no target_area, so without this the feedback arrives context-free+ message: `Feedback on feature preview "${feature?.name ?? values.activeFeedbackFlagKey}":\n\n${message}`,})- return null+ const ticketId = supportLogic.values.lastSubmittedTicketId+ const succeeded = ticketId != null && ticketId !== ticketIdBefore+ // On success clear the active key (closes the panel); on failure keep it open so+ // the user's text survives for a retry (supportLogic already showed the error)+ return succeeded ? null : values.activeFeedbackFlagKey},},],diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport.tsxindex 6f8600080c2a..5b331400c613 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport.tsx@@ -389,7 +389,10 @@ export function SidePanelSupport(): JSX.Element {<Section title="Contact us"><StatusPageAlert /><SupportMessageOverride />- <p>Can't find what you need and PostHog AI unable to help?</p>+ <p>+ Can't find what you need and PostHog AI unable to help? Message our support+ engineers.+ </p><SidePanelTickets /></Section>)}diff --git a/frontend/src/lib/components/Support/SupportForm.tsx b/frontend/src/lib/components/Support/SupportForm.tsxindex c2530995b427..1b36de3248e2 100644--- a/frontend/src/lib/components/Support/SupportForm.tsx+++ b/frontend/src/lib/components/Support/SupportForm.tsx@@ -56,7 +56,7 @@ const SUPPORT_TICKET_KIND_TO_PROMPT: Record<SupportTicketKind, string> = {}export function SupportForm(): JSX.Element | null {- const { sendSupportRequest } = useValues(supportLogic)+ const { sendSupportRequest, conversationsFlagEnabled } = useValues(supportLogic)const { setSendSupportRequestValue } = useActions(supportLogic)const { objectStorageAvailable } = useValues(preflightLogic)// the support model can be shown when logged out, file upload is not offered to anonymous users@@ -119,57 +119,61 @@ export function SupportForm(): JSX.Element | null {</LemonField></>)}- <LemonField name="kind" label="Message type">- <LemonSegmentedButton onChange={changeKind} fullWidth options={SUPPORT_TICKET_OPTIONS} />- </LemonField>- <div className="flex gap-2 flex-col">- <div className="flex justify-between items-center">- <label className="LemonLabel">- Topic- <Tooltip title="Route your request to the appropriate team.">- <span>- <IconInfo className="opacity-75" />- </span>- </Tooltip>- </label>- <Link- target="_blank"- disableDocsPanel- to="https://posthog.com/handbook/engineering/feature-ownership"- >- Feature ownership- </Link>- </div>- <LemonField name="target_area">- {({ value, onChange }) => (- <Tooltip- title={- !user- ? 'Please login to your account before opening a ticket unrelated to authentication issues.'- : undefined- }- >- <span className="block">- <LemonInputSelect- mode="single"- fullWidth- disabled={!user}- placeholder="Search for a topic"- data-attr="support-form-target-area"- options={TARGET_AREA_OPTIONS}- value={value ? [value] : []}- onChange={([newValue]) => onChange(newValue ?? null)}- />- </span>- </Tooltip>+ {!conversationsFlagEnabled && (+ <>+ <LemonField name="kind" label="Message type">+ <LemonSegmentedButton onChange={changeKind} fullWidth options={SUPPORT_TICKET_OPTIONS} />+ </LemonField>+ <div className="flex gap-2 flex-col">+ <div className="flex justify-between items-center">+ <label className="LemonLabel">+ Topic+ <Tooltip title="Route your request to the appropriate team.">+ <span>+ <IconInfo className="opacity-75" />+ </span>+ </Tooltip>+ </label>+ <Link+ target="_blank"+ disableDocsPanel+ to="https://posthog.com/handbook/engineering/feature-ownership"+ >+ Feature ownership+ </Link>+ </div>+ <LemonField name="target_area">+ {({ value, onChange }) => (+ <Tooltip+ title={+ !user+ ? 'Please login to your account before opening a ticket unrelated to authentication issues.'+ : undefined+ }+ >+ <span className="block">+ <LemonInputSelect+ mode="single"+ fullWidth+ disabled={!user}+ placeholder="Search for a topic"+ data-attr="support-form-target-area"+ options={TARGET_AREA_OPTIONS}+ value={value ? [value] : []}+ onChange={([newValue]) => onChange(newValue ?? null)}+ />+ </span>+ </Tooltip>+ )}+ </LemonField>+ </div>+ {sendSupportRequest.target_area === 'error_tracking' && (+ <LemonBanner type="warning">+ This topic is for our Error Tracking <i>product</i>. If you're reporting an error in PostHog+ please choose the relevant topic so your submission is sent to the correct team.+ </LemonBanner>)}- </LemonField>- </div>- {sendSupportRequest.target_area === 'error_tracking' && (- <LemonBanner type="warning">- This topic is for our Error Tracking <i>product</i>. If you're reporting an error in PostHog please- choose the relevant topic so your submission is sent to the correct team.- </LemonBanner>+ </>)}<LemonFieldname="message"@@ -196,34 +200,36 @@ export function SupportForm(): JSX.Element | null {</div>)}</LemonField>- <div className="flex gap-2 flex-col">- <div className="flex justify-between items-center">- <label className="LemonLabel">- Severity level- <Tooltip title="Severity levels help us prioritize your request.">- <span>- <IconInfo className="opacity-75" />- </span>- </Tooltip>- </label>- <Link- target="_blank"- disableDocsPanel- to="https://posthog.com/docs/support-options#severity-levels"- >- Definitions- </Link>+ {!conversationsFlagEnabled && (+ <div className="flex gap-2 flex-col">+ <div className="flex justify-between items-center">+ <label className="LemonLabel">+ Severity level+ <Tooltip title="Severity levels help us prioritize your request.">+ <span>+ <IconInfo className="opacity-75" />+ </span>+ </Tooltip>+ </label>+ <Link+ target="_blank"+ disableDocsPanel+ to="https://posthog.com/docs/support-options#severity-levels"+ >+ Definitions+ </Link>+ </div>+ <LemonField name="severity_level">+ <LemonSelect+ fullWidth+ options={Object.entries(SEVERITY_LEVEL_TO_NAME).map(([key, value]) => ({+ label: value,+ value: key,+ }))}+ />+ </LemonField></div>- <LemonField name="severity_level">- <LemonSelect- fullWidth- options={Object.entries(SEVERITY_LEVEL_TO_NAME).map(([key, value]) => ({- label: value,- value: key,- }))}- />- </LemonField>- </div>+ )}</Form>)}diff --git a/frontend/src/lib/components/Support/supportLogic.test.ts b/frontend/src/lib/components/Support/supportLogic.test.tsindex 7197bccba0f7..b2ee0af4f397 100644--- a/frontend/src/lib/components/Support/supportLogic.test.ts+++ b/frontend/src/lib/components/Support/supportLogic.test.ts@@ -1,11 +1,14 @@import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { initKeaTests } from '~/test/init'import { OrganizationBasicType, Region, SidePanelTab, TeamPublicType } from '~/types'-import { getPublicSupportSnippet, supportLogic } from './supportLogic'+import { getPublicSupportSnippet, SupportFormFields, supportLogic } from './supportLogic'import * as SupportModal from './SupportModal'// supportLogic and SupportModal import each other, so jest.mock('./SupportModal') leaves supportLogic@@ -90,4 +93,141 @@ describe('supportLogic', () => {expect(openSupportModal).toHaveBeenCalledTimes(1)})})++ describe('submitSupportTicket routing', () => {+ const ZENDESK_URL = 'https://posthoghelp.zendesk.com/api/v2/requests.json'+ const FORM_FIELDS: SupportFormFields = {+ name: 'Max',+ email: '[email protected]',+ kind: 'bug',+ target_area: 'billing',+ severity_level: 'high',+ message: 'Help!',+ }++ let logic: ReturnType<typeof supportLogic.build>+ const savedFetch = global.fetch+ let fetchMock: jest.Mock++ const zendeskCalls = (): unknown[][] => fetchMock.mock.calls.filter(([url]) => url === ZENDESK_URL)++ const enableConversationsFlag = (): void => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PRODUCT_SUPPORT_SIDE_PANEL]: true })+ }++ beforeEach(() => {+ fetchMock = jest.fn(() =>+ Promise.resolve({+ ok: true,+ json: () => Promise.resolve({ request: { id: 123 } }),+ text: () => Promise.resolve(''),+ } as unknown as Response)+ )+ global.fetch = fetchMock+ initKeaTests()+ logic = supportLogic.build()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ delete (posthog as any).conversations+ global.fetch = savedFetch+ })++ it('creates a conversations ticket instead of a Zendesk one when the flag is on', async () => {+ const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })+ ;(posthog as any).conversations = { isAvailable: () => true, sendMessage }+ enableConversationsFlag()++ await logic.asyncActions.submitSupportTicket(FORM_FIELDS)++ expect(sendMessage).toHaveBeenCalledTimes(1)+ expect(sendMessage).toHaveBeenCalledWith('Help!', { name: 'Max', email: '[email protected]' }, true)+ expect(zendeskCalls()).toHaveLength(0)+ expect(logic.values.lastSubmittedTicketId).toBe('t1')+ })++ it.each([+ ['the flag is off', false, { isAvailable: () => true, sendMessage: jest.fn() }],+ [+ 'sendMessage reports unavailable without sending',+ true,+ { isAvailable: () => true, sendMessage: jest.fn().mockResolvedValue(null) },+ ],+ ])('files exactly one Zendesk ticket when %s', async (_case, flagOn, conversations) => {+ ;(posthog as any).conversations = conversations+ if (flagOn) {+ enableConversationsFlag()+ }++ await expectLogic(logic, () => {+ logic.actions.submitSupportTicket(FORM_FIELDS)+ }).toFinishAllListeners()++ expect(zendeskCalls()).toHaveLength(1)+ })++ it('waits for the lazily-loaded extension before falling back to Zendesk', async () => {+ ;(posthog as any).conversations = undefined+ enableConversationsFlag()++ jest.useFakeTimers()+ try {+ const promise = (logic.asyncActions as any).submitSupportTicket(FORM_FIELDS)+ // No Zendesk request yet — the submit is still waiting for the extension+ expect(zendeskCalls()).toHaveLength(0)+ await jest.runAllTimersAsync()+ await promise+ } finally {+ jest.useRealTimers()+ }++ expect(zendeskCalls()).toHaveLength(1)+ })++ it('preserves exception context on the conversations ticket message', async () => {+ const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })+ ;(posthog as any).conversations = { isAvailable: () => true, sendMessage }+ enableConversationsFlag()++ await expectLogic(logic, () => {+ logic.actions.submitSupportTicket({+ ...FORM_FIELDS,+ exception_event: { uuid: 'exc-1', event: '$exception' },+ })+ }).toFinishAllListeners()++ expect(sendMessage.mock.calls[0][0]).toContain('Help!')+ expect(sendMessage.mock.calls[0][0]).toContain('Exception:')+ })++ it('accepts a form submission without severity or topic when the flag is on, as those fields are hidden', async () => {+ const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })+ ;(posthog as any).conversations = { isAvailable: () => true, sendMessage }+ enableConversationsFlag()++ await expectLogic(logic, () => {+ logic.actions.setSendSupportRequestValue('message', 'Just a message')+ logic.actions.submitSendSupportRequest()+ }).toFinishAllListeners()++ expect(sendMessage).toHaveBeenCalledTimes(1)+ expect(sendMessage.mock.calls[0][0]).toBe('Just a message')+ })++ it('does not fall back to Zendesk when sendMessage throws, to avoid double-filing', async () => {+ ;(posthog as any).conversations = {+ isAvailable: () => true,+ sendMessage: jest.fn().mockRejectedValue(new Error('network down')),+ }+ enableConversationsFlag()++ await logic.asyncActions.submitSupportTicket(FORM_FIELDS)++ // lastSubmittedTicketId stays null on failure — callers use this to detect the failure+ expect(zendeskCalls()).toHaveLength(0)+ expect(logic.values.lastSubmittedTicketId).toBeNull()+ })+ })})diff --git a/frontend/src/lib/components/Support/supportLogic.ts b/frontend/src/lib/components/Support/supportLogic.tsindex de2443180df2..29b754fa457c 100644--- a/frontend/src/lib/components/Support/supportLogic.ts+++ b/frontend/src/lib/components/Support/supportLogic.ts@@ -5,7 +5,9 @@ import posthog from 'posthog-js'import { LemonSelectOptions } from '@posthog/lemon-ui'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { preflightLogic } from 'lib/logic/preflightLogic'import { uuid } from 'lib/utils/dom'import { billingLogic } from 'scenes/billing/billingLogic'@@ -121,6 +123,31 @@ const SUPPORT_TICKET_KIND_TO_TITLE: Record<SupportTicketKind, string> = {bug: 'Report a bug',}+// The conversations extension loads lazily; poll briefly before deciding how to route so a fast+// submit right after page load doesn't miss it and fall back to Zendesk. Resolves as soon as it's+// available, or after the timeout.+async function waitForConversations(timeoutMs = 5000): Promise<boolean> {+ const intervalMs = 250+ for (let waited = 0; waited < timeoutMs; waited += intervalMs) {+ if (posthog.conversations?.isAvailable()) {+ return true+ }+ await new Promise((resolve) => setTimeout(resolve, intervalMs))+ }+ return !!posthog.conversations?.isAvailable()+}++// Conversations tickets carry just the user's message (like the side panel composer), but for bug+// reports we still fold the exception in so it survives on email-channel tickets and when the+// agent's session-scoped exceptions panel can't resolve it. Mirrors how feature-preview feedback+// names its feature in the message body.+export function appendExceptionToMessage(message: string, exception_event?: SupportTicketExceptionEvent): string {+ if (!exception_event) {+ return message+ }+ return `${message}\n\n-----\nException: ${parseExceptionEvent(exception_event)}`+}+const TARGET_AREA_TO_NAME_GENERAL = [{value: 'login',@@ -457,18 +484,22 @@ export const supportLogic = kea<supportLogicType>([['isCurrentOrganizationNew'],sidePanelStateLogic,['sidePanelAvailable'],+ featureFlagLogic,+ ['featureFlags'],],actions: [sidePanelStateLogic, ['openSidePanel', 'setSidePanelOptions']],})),actions(() => ({closeSupportForm: true,openSupportForm: (values: Partial<SupportFormFields> & { target?: 'modal' | 'sidePanel' }) => values,- submitZendeskTicket: (form: SupportFormFields) => form,+ submitSupportTicket: (form: SupportFormFields) => form,ensureZendeskOrganization: true,updateUrlParams: true,openEmailForm: true,closeEmailForm: true,setLastSubmittedTicketId: (ticketId: string | null) => ({ ticketId }),+ viewConversationsTicket: (ticket: { id: string; status: string; created_at: string }) => ({ ticket }),+ clearPendingViewTicket: true,})),reducers(() => ({isSupportFormOpen: [@@ -492,6 +523,15 @@ export const supportLogic = kea<supportLogicType>([openSupportForm: () => null, // Reset when opening a new form},],+ // A conversations ticket the side panel should open on when it next renders — set when the+ // user clicks "View" on a submission toast, consumed by sidepanelTicketsLogic+ pendingViewTicket: [+ null as { id: string; status: string; created_at: string } | null,+ {+ viewConversationsTicket: (_, { ticket }) => ticket,+ clearPendingViewTicket: () => null,+ },+ ],})),forms(({ values }) => ({sendSupportRequest: {@@ -504,20 +544,23 @@ export const supportLogic = kea<supportLogicType>([message: '',} as SupportFormFields,errors: ({ name, email, message, kind, target_area, severity_level }) => {+ // Conversations tickets are just a message, like the side panel composer — the+ // triage fields only exist on the Zendesk form+ const requiresTriageFields = !values.conversationsFlagEnabledreturn {name: !values.user && !name ? 'Please enter your name' : undefined,email: !values.user && !email ? 'Please enter your email' : undefined,message: !message ? 'Please enter a message' : undefined,- kind: !kind ? 'Please choose' : undefined,- severity_level: !severity_level ? 'Please choose' : undefined,- target_area: !target_area ? 'Please choose' : undefined,+ kind: requiresTriageFields && !kind ? 'Please choose' : undefined,+ severity_level: requiresTriageFields && !severity_level ? 'Please choose' : undefined,+ target_area: requiresTriageFields && !target_area ? 'Please choose' : undefined,}},submit: async (formValues) => {// name must be present for zendesk to accept the ticketformValues.name = values.user?.first_name ?? formValues.name ?? 'name not set'formValues.email = values.user?.email ?? formValues.email ?? ''- await supportLogic.asyncActions.submitZendeskTicket(formValues)+ await supportLogic.asyncActions.submitSupportTicket(formValues)},},})),@@ -533,6 +576,10 @@ export const supportLogic = kea<supportLogicType>([(s) => [s.sendSupportRequest],(sendSupportRequest: SupportFormFields) => sendSupportRequest.target_area,],+ conversationsFlagEnabled: [+ (s) => [s.featureFlags],+ (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.PRODUCT_SUPPORT_SIDE_PANEL],+ ],}),listeners(({ actions, props, values }) => ({updateUrlParams: async () => {@@ -591,16 +638,61 @@ export const supportLogic = kea<supportLogicType>([actions.updateUrlParams()},- submitZendeskTicket: async ({- name,- email,- kind,- target_area,- severity_level,- message,- exception_event,- tags,- }: SupportFormFields) => {+ submitSupportTicket: async (formValues: SupportFormFields) => {+ const { name, email, kind, target_area, severity_level, message, exception_event, tags } = formValues++ // Conversations is where support is headed, so wait for the extension rather than racing+ // it to the (temporary) Zendesk fallback+ if (values.conversationsFlagEnabled && (await waitForConversations())) {+ try {+ const response = await posthog.conversations!.sendMessage(+ appendExceptionToMessage(message, exception_event),+ { name: name || undefined, email: email || undefined },+ true // every form submission starts a new ticket+ )+ if (response) {+ // No support_ticket capture here: the backend fires $conversation_ticket_created+ // for every new ticket, so a client-side event would double-count+ actions.setLastSubmittedTicketId(response.ticket_id)+ lemonToast.success(+ values.sidePanelAvailable+ ? 'Got the message! You can view replies from our support engineers in the support panel.'+ : "Got the message! Our support engineers will follow up by email if there's more to share.",+ values.sidePanelAvailable+ ? {+ button: {+ label: 'View',+ action: () =>+ actions.viewConversationsTicket({+ id: response.ticket_id,+ status: response.ticket_status,+ created_at: response.created_at,+ }),+ },+ }+ : undefined+ )+ actions.closeEmailForm()+ actions.closeSupportForm()+ actions.resetSendSupportRequest()+ return+ }+ // null means the extension declined to send (not available) — nothing left the+ // browser, so falling through to Zendesk cannot double-file the ticket+ } catch (e) {+ // The request may have reached the server even though the response failed, so+ // don't fall back to Zendesk here — that could file the ticket twice+ posthog.captureException(e)+ lemonToast.error("Oops, the message couldn't be sent. Please try again in a moment.", {+ hideButton: true,+ })+ return+ }+ }++ // Fallback path: conversations flag off, or the extension never loaded. Tag flag-on+ // fallbacks so the (rare) volume is visible while Zendesk is being retired.+ const conversationsFallback = values.conversationsFlagEnabledconst zendesk_ticket_uuid = uuid()const subject =SUPPORT_KIND_TO_SUBJECT[kind ?? 'support'] +@@ -674,7 +766,12 @@ export const supportLogic = kea<supportLogicType>([request: {requester: { name: name, email: email },subject: subject,- tags: [planLevelTag, accountOwnerTag, ...(tags || [])],+ tags: [+ planLevelTag,+ accountOwnerTag,+ ...(conversationsFallback ? ['conversations_fallback'] : []),+ ...(tags || []),+ ],custom_fields: [{id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.severity,@@ -713,8 +810,8 @@ export const supportLogic = kea<supportLogicType>([body:message +`\n\n-----` +- `\nKind: ${kind}` +- `\nTarget area: ${target_area}` ++ `\nKind: ${kind ?? 'support'}` ++ `\nTarget area: ${target_area ?? 'General'}` +`\nReport event: http://go/ticketByUUID/${zendesk_ticket_uuid}` +getSessionReplayLink() +getErrorTrackingLink(exception_event?.uuid) +@@ -841,6 +938,10 @@ export const supportLogic = kea<supportLogicType>([}},+ viewConversationsTicket: () => {+ actions.openSidePanel(SidePanelTab.Support)+ },+closeSupportForm: () => {// Form is only reset by explicit Cancel button or successful submissionprops.onClose?.()diff --git a/frontend/src/scenes/max/FeedbackPrompt.tsx b/frontend/src/scenes/max/FeedbackPrompt.tsxindex 5eb50fa1a543..ab6489e286a2 100644--- a/frontend/src/scenes/max/FeedbackPrompt.tsx+++ b/frontend/src/scenes/max/FeedbackPrompt.tsx@@ -31,7 +31,7 @@ export function FeedbackPrompt({ conversationId, traceId }: FeedbackPromptProps)const [isSupportModalOpen, setIsSupportModalOpen] = useState(false)const { sendSupportRequest, lastSubmittedTicketId } = useValues(supportLogic)- const { resetSendSupportRequest, setSendSupportRequestValue, submitSendSupportRequest } = useActions(supportLogic)+ const { resetSendSupportRequest, setSendSupportRequestValue } = useActions(supportLogic)// Track when we're waiting for ticket submission to completeconst [pendingTicketSubmission, setPendingTicketSubmission] = useState(false)@@ -112,15 +112,26 @@ export function FeedbackPrompt({ conversationId, traceId }: FeedbackPromptProps)return message ? `${message}\n\n----\n${metadataLines.join('\n')}` : metadataLines.join('\n')}- function handleSupportFormSubmit(): void {+ async function handleSupportFormSubmit(): Promise<void> {setTicketMessageText(sendSupportRequest.message)const finalMessage = appendMetadataToMessage(sendSupportRequest.message)setSendSupportRequestValue('message', finalMessage)- setTicketIdBeforeSubmission(lastSubmittedTicketId)+ const ticketIdBefore = supportLogic.values.lastSubmittedTicketId+ setTicketIdBeforeSubmission(ticketIdBefore)setPendingTicketSubmission(true)recordFeedbackShown()- submitSendSupportRequest()+ try {+ await supportLogic.asyncActions.submitSendSupportRequest()+ } catch {+ // Failure is detected below via the unchanged ticket id+ }+ // Success closes the modal via the effect watching lastSubmittedTicketId. If no ticket was+ // created, the submit failed — clear the pending state so the modal doesn't hang (the error+ // toast already showed and the text stays for a retry).+ if (supportLogic.values.lastSubmittedTicketId === ticketIdBefore) {+ setPendingTicketSubmission(false)+ }}function handleSupportModalCancel(): void {@@ -138,7 +149,7 @@ export function FeedbackPrompt({ conversationId, traceId }: FeedbackPromptProps)<LemonButton type="secondary" onClick={handleSupportModalCancel}>Cancel</LemonButton>- <LemonButton type="primary" data-attr="submit" onClick={handleSupportFormSubmit}>+ <LemonButton type="primary" data-attr="submit" onClick={() => void handleSupportFormSubmit()}>Submit</LemonButton></div>diff --git a/frontend/src/scenes/max/TicketPrompt.tsx b/frontend/src/scenes/max/TicketPrompt.tsxindex 0817478662cc..f7accc94252a 100644--- a/frontend/src/scenes/max/TicketPrompt.tsx+++ b/frontend/src/scenes/max/TicketPrompt.tsx@@ -33,8 +33,7 @@ export function TicketPrompt({ conversationId, traceId, summary, initialText }:const [isSupportModalOpen, setIsSupportModalOpen] = useState(false)const { sendSupportRequest, lastSubmittedTicketId } = useValues(supportLogic)- const { resetSendSupportRequest, setSendSupportRequestValue, submitSendSupportRequest, closeSupportForm } =- useActions(supportLogic)+ const { resetSendSupportRequest, setSendSupportRequestValue, closeSupportForm } = useActions(supportLogic)const { appendMessageToConversation } = useActions(maxThreadLogic)const [pendingTicketSubmission, setPendingTicketSubmission] = useState(false)@@ -89,14 +88,25 @@ export function TicketPrompt({ conversationId, traceId, summary, initialText }:setIsSupportModalOpen(true)}- function handleSupportFormSubmit(): void {+ async function handleSupportFormSubmit(): Promise<void> {setIsSubmitting(true)const finalMessage = appendMetadataToMessage(sendSupportRequest.message)setSendSupportRequestValue('message', finalMessage)- setTicketIdBeforeSubmission(lastSubmittedTicketId)+ const ticketIdBefore = supportLogic.values.lastSubmittedTicketId+ setTicketIdBeforeSubmission(ticketIdBefore)setPendingTicketSubmission(true)- submitSendSupportRequest()+ try {+ await supportLogic.asyncActions.submitSendSupportRequest()+ } 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) {+ setIsSubmitting(false)+ setPendingTicketSubmission(false)+ }}function handleSupportModalCancel(): void {@@ -119,7 +129,7 @@ export function TicketPrompt({ conversationId, traceId, summary, initialText }:<LemonButtontype="primary"data-attr="submit"- onClick={handleSupportFormSubmit}+ onClick={() => void handleSupportFormSubmit()}loading={isSubmitting}>Submitdiff --git a/products/conversations/frontend/components/SidePanel/NewTicket.tsx b/products/conversations/frontend/components/SidePanel/NewTicket.tsxindex aa786bad2e1c..566cb57db5d1 100644--- a/products/conversations/frontend/components/SidePanel/NewTicket.tsx+++ b/products/conversations/frontend/components/SidePanel/NewTicket.tsx@@ -7,7 +7,7 @@ import { MessageInput } from '../Chat/MessageInput'import { sidepanelTicketsLogic } from './sidepanelTicketsLogic'export function NewTicket(): JSX.Element {- const { messageSending } = useValues(sidepanelTicketsLogic)+ const { messageSending, newTicketDraft } = useValues(sidepanelTicketsLogic)const { sendMessage, setView } = useActions(sidepanelTicketsLogic)return (@@ -22,12 +22,16 @@ export function NewTicket(): JSX.Element {<span className="font-semibold">New ticket</span></div>+ {/* draftContent seeds the editor from a prefilled CTA; no onDraftChange, since routing+ typing back through the logic (which keys this component) would remount on every+ keystroke and drop focus. The draft is a one-shot initial value. */}<MessageInputonSendMessage={(content, _richContent, _isPrivate, onSuccess) => sendMessage(content, onSuccess)}messageSending={messageSending}- placeholder="Describe what you need help with and our team will get back to you."+ placeholder="Describe what you need help with and our support engineers will get back to you."buttonText="Submit ticket"minRows={4}+ draftContent={newTicketDraft}/></div>)diff --git a/products/conversations/frontend/components/SidePanel/SidePanelTickets.tsx b/products/conversations/frontend/components/SidePanel/SidePanelTickets.tsxindex 029874991156..9c3677e0227d 100644--- a/products/conversations/frontend/components/SidePanel/SidePanelTickets.tsx+++ b/products/conversations/frontend/components/SidePanel/SidePanelTickets.tsx@@ -7,14 +7,16 @@ import { Ticket } from './Ticket'import { TicketsList } from './TicketsList'export function SidePanelTickets(): JSX.Element {- const { view } = useValues(sidepanelTicketsLogic)+ const { view, newTicketDraftRevision } = useValues(sidepanelTicketsLogic)const hasIdentityMode = !!window.JS_POSTHOG_IDENTITY_DISTINCT_IDreturn (<div>{view === 'list' && <TicketsList />}{view === 'ticket' && <Ticket />}- {view === 'new' && <NewTicket />}+ {/* Key on the draft revision so a prefill injected while the composer is already open+ remounts the editor (it only reads initial content at creation) */}+ {view === 'new' && <NewTicket key={newTicketDraftRevision} />}{view === 'restore' && !hasIdentityMode && <RestoreTickets />}</div>)diff --git a/products/conversations/frontend/components/SidePanel/TicketsList.tsx b/products/conversations/frontend/components/SidePanel/TicketsList.tsxindex 9b9756daa4ba..4cb1a91f55fe 100644--- a/products/conversations/frontend/components/SidePanel/TicketsList.tsx+++ b/products/conversations/frontend/components/SidePanel/TicketsList.tsx@@ -59,7 +59,7 @@ export function TicketsList(): JSX.Element {{tickets.length === 0 ? (<div className="text-center text-muted-alt py-8"><p>No tickets yet.</p>- <p className="text-sm">Create a new ticket to get help from our team.</p>+ <p className="text-sm">Create a new ticket to get help from our support engineers.</p></div>) : (<div className="flex flex-col gap-1 mt-2">diff --git a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.tsnew file mode 100644index 000000000000..01424feabe32--- /dev/null+++ b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts@@ -0,0 +1,91 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { supportLogic } from 'lib/components/Support/supportLogic'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'++import { sidepanelTicketsLogic } from './sidepanelTicketsLogic'++describe('sidepanelTicketsLogic', () => {+ let logic: ReturnType<typeof sidepanelTicketsLogic.build>++ beforeEach(() => {+ initKeaTests()+ ;(posthog as any).conversations = {+ isAvailable: () => true,+ getTickets: jest.fn().mockResolvedValue({ results: [] }),+ getMessages: jest.fn().mockResolvedValue({ messages: [], has_more: false }),+ markAsRead: jest.fn().mockResolvedValue({}),+ }+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PRODUCT_SUPPORT_SIDE_PANEL]: true })+ supportLogic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ delete (posthog as any).conversations+ })++ it('opens the composer with the prefilled message when the support form intent exists at mount', async () => {+ supportLogic.actions.openSupportForm({+ kind: 'bug',+ target_area: 'analytics',+ isEmailFormOpen: true,+ message: 'It broke',+ target: 'sidePanel',+ })++ logic = sidepanelTicketsLogic.build()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.view).toBe('new')+ expect(JSON.stringify(logic.values.newTicketDraft)).toContain('It broke')+ expect(supportLogic.values.isEmailFormOpen).toBe(false)++ // Leaving the composer clears the prefill so a later blank "New ticket" starts empty+ logic.actions.setView('list')+ expect(logic.values.newTicketDraft).toBeNull()+ })++ it('switches to the composer when the support form opens while already mounted', async () => {+ logic = sidepanelTicketsLogic.build()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.view).toBe('list')++ await expectLogic(logic, () => {+ supportLogic.actions.openSupportForm({+ kind: 'support',+ target_area: 'billing',+ isEmailFormOpen: true,+ target: 'sidePanel',+ })+ }).toFinishAllListeners()++ expect(logic.values.view).toBe('new')+ expect(supportLogic.values.isEmailFormOpen).toBe(false)+ })++ it('opens the specific ticket thread when a submission toast "View" is clicked', async () => {+ logic = sidepanelTicketsLogic.build()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => {+ supportLogic.actions.viewConversationsTicket({+ id: 'ticket-1',+ status: 'open',+ created_at: '2026-07-13T00:00:00Z',+ })+ }).toFinishAllListeners()++ expect(logic.values.view).toBe('ticket')+ expect(logic.values.currentTicket?.id).toBe('ticket-1')+ expect(supportLogic.values.pendingViewTicket).toBeNull()+ })+})diff --git a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.tsindex 1d7730b2b130..bca4ac1bf432 100644--- a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts+++ b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts@@ -1,8 +1,10 @@+import { JSONContent } from '@tiptap/core'import { actions, beforeUnmount, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { router } from 'kea-router'import { subscriptions } from 'kea-subscriptions'import posthog from 'posthog-js'+import { appendExceptionToMessage, supportLogic } from 'lib/components/Support/supportLogic'import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -27,10 +29,31 @@ function removeRestoreTokenFromUrl(): void {}}+function messageToRichContent(message: string): JSONContent {+ return {+ type: 'doc',+ content: message.split('\n').map((line) => ({+ type: 'paragraph',+ ...(line ? { content: [{ type: 'text', text: line }] } : {}),+ })),+ }+}+export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([path(['products', 'conversations', 'frontend', 'components', 'SidePanel', 'sidepanelTicketsLogic']),connect(() => ({- values: [sidePanelStateLogic, ['sidePanelOpen'], featureFlagLogic, ['featureFlags']],+ values: [+ sidePanelStateLogic,+ ['sidePanelOpen'],+ featureFlagLogic,+ ['featureFlags'],+ supportLogic,+ ['isEmailFormOpen', 'sendSupportRequest', 'pendingViewTicket'],+ ],+ actions: [+ supportLogic,+ ['closeEmailForm', 'closeSupportForm', 'clearPendingViewTicket', 'resetSendSupportRequest'],+ ],})),actions({initTickets: true,@@ -47,6 +70,9 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([setMessageSending: (sending: boolean) => ({ sending }),setView: (view: SidePanelViewState) => ({ view }),setCurrentTicket: (ticket: ConversationTicket) => ({ ticket }),+ setNewTicketDraft: (content: JSONContent | null) => ({ content }),+ startTicketFromSupportForm: true,+ openPendingTicket: true,sendMessage: (content: string, onSuccess: () => void) => ({ content, onSuccess }),requestRestoreLink: (email: string) => ({ email }),restoreFromUrlToken: (token: string) => ({ token }),@@ -90,6 +116,22 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([setCurrentTicket: (_, { ticket }) => ticket,},],+ newTicketDraft: [+ null as JSONContent | null,+ {+ setNewTicketDraft: (_, { content }) => content,+ // Clear once we leave the composer so a later blank "New ticket" doesn't show a stale prefill+ setView: (state, { view }) => (view === 'new' ? state : null),+ },+ ],+ // Bumped only when a draft is injected via setNewTicketDraft (a prefilled CTA), so NewTicket+ // remounts to pick up the seeded content. Plain typing never calls this, so it doesn't remount.+ newTicketDraftRevision: [+ 0,+ {+ setNewTicketDraft: (state) => state + 1,+ },+ ],messagesLoading: [false,{@@ -296,6 +338,51 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([actions.loadMessages(ticket.id)actions.markAsRead(ticket.id)},+ // "Contact support" CTAs (error boundaries, empty states, etc.) open the support form via+ // supportLogic; with conversations enabled they should land in this composer instead, carrying+ // any prefilled message with them+ startTicketFromSupportForm: () => {+ // When disabled, do nothing — the classic modal/form flow owns this case+ if (!values.isEnabled) {+ return+ }+ const request = values.sendSupportRequest+ const message = request?.message+ if (message) {+ actions.setNewTicketDraft(+ messageToRichContent(appendExceptionToMessage(message, request?.exception_event))+ )+ }+ actions.setView('new')+ // Consume the support-form intent fully (or supportRouterLogic keeps treating the form as+ // open and ignores future URL-driven opens), and reset so a stale message can't resurface+ // prefilled on a later CTA that carries none+ actions.closeEmailForm()+ actions.closeSupportForm()+ actions.resetSendSupportRequest()+ },+ // "View" on a submission toast (Max AI, feature-preview feedback, etc.) should land in the+ // created ticket's thread, matching where the composer flow leaves you+ openPendingTicket: () => {+ const pending = values.pendingViewTicket+ if (!pending) {+ return+ }+ // Clear before the enabled-guard so a stale intent can't be consumed on a later mount+ actions.clearPendingViewTicket()+ if (!values.isEnabled) {+ return+ }+ actions.setCurrentTicket({+ id: pending.id,+ status: pending.status as ConversationTicket['status'],+ message_count: 1,+ created_at: pending.created_at,+ unread_count: 0,+ last_message_at: pending.created_at,+ })+ actions.loadTickets()+ },requestRestoreLink: async ({ email }) => {const conversations = posthog.conversations as anyif (!conversations?.requestRestoreLink) {@@ -355,12 +442,32 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([return}actions.initTickets()+ // Flags can resolve after a support intent was already set (cold load of a+ // #panel=support:...:true URL fires openSupportForm before flags arrive). The+ // isEmailFormOpen/pendingViewTicket subscriptions early-returned while disabled, so+ // re-consume here now that we're enabled.+ if (values.isEmailFormOpen) {+ actions.startTicketFromSupportForm()+ }+ if (values.pendingViewTicket) {+ actions.openPendingTicket()+ }},sidePanelOpen: () => {if (values.isEnabled) {actions.loadTickets()}},+ isEmailFormOpen: (open: boolean) => {+ if (open) {+ actions.startTicketFromSupportForm()+ }+ },+ pendingViewTicket: (pending: { id: string } | null) => {+ if (pending) {+ actions.openPendingTicket()+ }+ },})),beforeUnmount(({ actions, cache }) => {actions.stopPolling()@@ -376,6 +483,8 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([}),afterMount(({ values, actions }) => {if (values.isEnabled) {+ // initTickets re-consumes any pending support intent (isEmailFormOpen/pendingViewTicket),+ // so no need to repeat that hereactions.initTickets()}}),