Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(support): remove zendesk ticket creation and the side panel flag (#76018)

posthog[bot]b7f63ef9ff56
diff --git a/ee/hogai/chat_agent/slash_commands/commands/ticket/prompts.py b/ee/hogai/chat_agent/slash_commands/commands/ticket/prompts.py
index 04778705db49..53bbb3511526 100644
--- a/ee/hogai/chat_agent/slash_commands/commands/ticket/prompts.py
+++ b/ee/hogai/chat_agent/slash_commands/commands/ticket/prompts.py
@@ -7,76 +7,22 @@ Your goal is to create a clear, concise summary that helps a support agent under
4. The current state of the issue
""".strip()
-# Keep in sync with TARGET_AREA_TO_NAME in frontend/src/lib/components/Support/supportLogic.ts.
-# The frontend validates the emitted key against that list; unknown keys parse as null and the
-# support form falls back to its default target area, so drift here degrades gracefully.
-SUPPORT_TICKET_TOPICS = """
-- login: Authentication (incl. login, sign-up, invites)
-- analytics_platform: Analytics platform features (incl. alerts, subscriptions, exports)
-- billing: Billing
-- cohorts: Cohorts
-- data_ingestion: Data ingestion
-- health_overview: Health overview
-- data_management: Data management (incl. events, actions, properties)
-- mobile: Mobile
-- notebooks: Notebooks
-- onboarding: Onboarding
-- platform_addons: Platform addons
-- sdk: SDK / implementation
-- setup-wizard: Setup wizard
-- ai_gateway: AI gateway
-- llm-analytics: AI observability / LLM analytics
-- apps: Apps (incl. integrations, plugins, webhooks)
-- batch_exports: Destinations (batch exports)
-- cdp_destinations: Destinations (real-time)
-- data_modeling: Data modeling (views, matviews, endpoints)
-- data_warehouse: Data warehouse (sources, incl. external integrations like Stripe, Hubspot, ad platforms)
-- error_tracking: Error tracking product
-- experiments: Experiments
-- feature_flags: Feature flags
-- group_analytics: Group analytics
-- customer_analytics: Customer analytics
-- heatmaps: Heatmaps
-- logs: Logs
-- posthog-ai: PostHog AI (the assistant itself)
-- posthog-mcp: PostHog MCP
-- analytics: Product analytics (incl. insights, dashboards)
-- revenue_analytics: Revenue analytics
-- session_replay: Session replay (incl. recordings)
-- signals: Signals
-- slack: Slack app
-- surveys: Surveys
-- toolbar: Toolbar
-- web_analytics: Web analytics
-- workflows: Workflows / messaging
-""".strip()
-
-SUPPORT_SUMMARIZER_USER_PROMPT = f"""
+SUPPORT_SUMMARIZER_USER_PROMPT = """
Create a brief, actionable summary of this conversation for a support ticket.
Format:
-- 2 or 3 labeled sections separated by blank lines
+- 2 labeled sections separated by blank lines
- Section 1: "**Issue**:" followed by the user's problem and relevant technical details (error messages, event names, property names, etc.)
- Section 2: "**Status**:" followed by what PostHog AI attempted and the current state of the request
-- Section 3 (optional): "**Topic**:" followed by exactly one topic key from the list below, chosen for the product area the user's issue is actually about
- Always refer to yourself as "PostHog AI" (never "the AI" or "I")
- Write in third person perspective
- Do NOT include bullet points or "Recommended next steps" sections
- Plain text only, no markdown formatting
-Topic selection:
-- Choose the topic for the product area the issue is about, NOT the channel it was reported through. Only use "posthog-ai" when the issue is about PostHog AI itself (e.g. the assistant gave wrong answers or misbehaved).
-- If no topic clearly fits, omit the "**Topic**:" section entirely so the user can pick one themselves.
-
-Valid topic keys:
-{SUPPORT_TICKET_TOPICS}
-
<good_example>
**Issue:** The user is trying to create a funnel insight to track their checkout flow but is seeing a "No data" message despite having events. They confirmed that the events "$pageview" and "purchase_completed" exist in their project with data from the last 7 days.
**Status:** PostHog AI helped verify the events exist and suggested checking the funnel step order and date range filters. The issue remains unresolved - the user still sees no data in their funnel even after adjusting the date range to 30 days.
-
-**Topic:** analytics
</good_example>
<bad_example>
@@ -91,17 +37,12 @@ The user asked about funnels and I helped them.
### Recommended next steps:
- Check the documentation
- Contact support if issues persist
-
-### Topic
-This was reported via PostHog AI so the topic is posthog-ai.
</bad_example>
<good_example>
**Issue:** The user reported that their PostHog session recordings are not capturing clicks on their React application. They are using posthog-js version 1.96.0 and have autocapture enabled. The console shows no errors.
**Status:** PostHog AI suggested checking that the "Record user sessions" toggle is enabled in project settings and verified the SDK initialization code looks correct. The user confirmed session recording is enabled but clicks are still not appearing in the recordings timeline.
-
-**Topic:** session_replay
</good_example>
<bad_example>
diff --git a/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.test.ts b/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.test.ts
index 2338a57abe9b..aa4bc79ac08b 100644
--- a/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.test.ts
+++ b/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.test.ts
@@ -6,7 +6,6 @@ import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { userLogic } from 'scenes/userLogic'
-import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { featurePreviewsLogic } from './featurePreviewsLogic'
@@ -26,11 +25,10 @@ describe('featurePreviewsLogic - submitEarlyAccessFeatureFeedback', () => {
beforeEach(() => {
jest.clearAllMocks()
- useMocks({
- post: {
- 'https://posthoghelp.zendesk.com/api/v2/requests.json': [200, { request: { id: 123 } }],
- },
- })
+ ;(posthog as any).conversations = {
+ isAvailable: () => true,
+ sendMessage: jest.fn().mockResolvedValue({ ticket_id: '123', ticket_status: 'open', created_at: '' }),
+ }
initKeaTests()
logic = featurePreviewsLogic()
logic.mount()
@@ -56,13 +54,10 @@ describe('featurePreviewsLogic - submitEarlyAccessFeatureFeedback failure', () =
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)
+ ;(posthog as any).conversations = {
+ isAvailable: () => true,
+ sendMessage: jest.fn().mockRejectedValue(new Error('network down')),
+ }
initKeaTests()
logic = featurePreviewsLogic()
logic.mount()
@@ -89,11 +84,6 @@ describe('featurePreviewsLogic - updateEarlyAccessFeatureEnrollment', () => {
// Set up the mock implementation for posthog
;(posthog as any).updateEarlyAccessFeatureEnrollment = mockUpdateEnrollment
- useMocks({
- post: {
- 'https://posthoghelp.zendesk.com/api/v2/requests.json': [200, {}],
- },
- })
initKeaTests()
logic = featurePreviewsLogic()
logic.mount()
@@ -130,11 +120,6 @@ describe('featurePreviewsLogic - conceptEnrollments reducer', () => {
jest.clearAllMocks()
;(posthog as any).updateEarlyAccessFeatureEnrollment = jest.fn()
- useMocks({
- post: {
- 'https://posthoghelp.zendesk.com/api/v2/requests.json': [200, {}],
- },
- })
initKeaTests()
logic = featurePreviewsLogic()
logic.mount()
@@ -176,11 +161,6 @@ describe('featurePreviewsLogic - submitConceptSurvey', () => {
;(posthog as any).capture = mockCapture
;(posthog as any).updateEarlyAccessFeatureEnrollment = mockUpdateEnrollment
- useMocks({
- post: {
- 'https://posthoghelp.zendesk.com/api/v2/requests.json': [200, {}],
- },
- })
initKeaTests()
logic = featurePreviewsLogic()
logic.mount()
@@ -271,11 +251,6 @@ describe('featurePreviewsLogic - updateEarlyAccessFeatureEnrollment (impersonate
// Set up the mock implementation for posthog
;(posthog as any).updateEarlyAccessFeatureEnrollment = mockUpdateEnrollment
- useMocks({
- post: {
- 'https://posthoghelp.zendesk.com/api/v2/requests.json': [200, {}],
- },
- })
initKeaTests()
logic = featurePreviewsLogic()
logic.mount()
diff --git a/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.tsx b/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.tsx
index 79b5a7c47337..f3cb4894a77e 100644
--- a/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.tsx
+++ b/frontend/src/layout/FeaturePreviews/featurePreviewsLogic.tsx
@@ -194,11 +194,9 @@ export const featurePreviewsLogic = kea<featurePreviewsLogicType>([
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',
- // The feature identity must live in the message itself: conversations tickets
- // carry no target_area, so without this the feedback arrives context-free
+ // The feature identity has to live in the message itself — a conversations
+ // ticket carries only the message, so without this the feedback arrives
+ // context-free
message: `Feedback on feature preview "${feature?.name ?? values.activeFeedbackFlagKey}":\n\n${message}`,
})
const ticketId = supportLogic.values.lastSubmittedTicketId
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport.tsx
index f33e44f3730e..1f11bbe53a13 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/support/SidePanelSupport.tsx
@@ -5,8 +5,6 @@ import { IconExpand45, IconFeatures, IconHelmet, IconMap, IconWarning } from '@p
import { LemonButton, Link } from '@posthog/lemon-ui'
import { incidentStatusLogic } from 'lib/components/HelpMenu/incidentStatusLogic'
-import { SupportForm } from 'lib/components/Support/SupportForm'
-import { supportLogic } from 'lib/components/Support/supportLogic'
import {
DEFAULT_PAID_RESPONSE_TIME,
PAY_AS_YOU_GO_RESPONSE_TIME,
@@ -251,89 +249,24 @@ const SupportResponseTimesTable = ({
)
}
-function SupportFormBlock({
- onCancel,
- billing,
- isSubmitting,
-}: {
- onCancel: () => void
- billing: BillingType | null | undefined
- isSubmitting: boolean
-}): JSX.Element {
- return (
- <Section title="Email an engineer">
- <SupportForm />
- <LemonButton
- form="support-modal-form"
- htmlType="submit"
- type="primary"
- data-attr="submit"
- fullWidth
- center
- className="mt-4"
- loading={isSubmitting}
- >
- Submit
- </LemonButton>
- <LemonButton
- form="support-modal-form"
- type="secondary"
- onClick={onCancel}
- fullWidth
- center
- className="mt-2 mb-4"
- >
- Cancel
- </LemonButton>
-
- <br />
-
- <div className="mb-2">
- <strong>Support is open Monday - Friday</strong>
- </div>
- <SupportResponseTimesTable billing={billing} isCompact={true} />
- </Section>
- )
-}
-
export function SidePanelSupport(): JSX.Element {
const { preflight } = useValues(preflightLogic)
- const { featureFlags } = useValues(featureFlagLogic)
useValues(userLogic)
- const {
- isEmailFormOpen,
- title: supportPanelTitle,
- targetArea,
- isSendSupportRequestSubmitting,
- } = useValues(supportLogic)
- const { closeEmailForm, openEmailForm, closeSupportForm, resetSendSupportRequest } = useActions(supportLogic)
const { openSidePanel, closeSidePanel } = useActions(sidePanelStateLogic)
const { billing, billingLoading, billingPlan } = useValues(billingLogic)
const { tickets, canCreateTicket } = useValues(sidepanelTicketsLogic)
- const useProductSupportSidePanel = featureFlags[FEATURE_FLAGS.PRODUCT_SUPPORT_SIDE_PANEL]
-
- // With the side panel on, a billing CTA grants an exemption that `canCreateTicket` already carries.
- // The `targetArea` arm is for the classic Zendesk form, which never reaches that listener.
- const canEmail = canCreateTicket || targetArea === 'billing'
const isCloudOrDev = preflight?.cloud || process.env.NODE_ENV === 'development'
- const showEmailSupport = isCloudOrDev && canEmail
const showMaxAI = isCloudOrDev
const isBillingLoaded = !billingLoading && billing !== undefined
// Free plans can't open new tickets, but tickets they already have (billing questions, PostHog AI
// bug reports) stay readable and repliable here
- const showTickets = isCloudOrDev && useProductSupportSidePanel && (canCreateTicket || tickets.length > 0)
-
- const handleOpenEmailForm = (): void => {
- if (showEmailSupport && isBillingLoaded) {
- openEmailForm()
- }
- }
+ const showTickets = isCloudOrDev && (canCreateTicket || tickets.length > 0)
return (
<div className="SidePanelSupport contents">
<SidePanelContentContainer>
- <SidePanelPaneHeader showCloseButton={false} title={isEmailFormOpen ? supportPanelTitle : 'Support'}>
+ <SidePanelPaneHeader showCloseButton={false} title="Support">
{showTickets && (
<LemonButton
size="xsmall"
@@ -349,154 +282,122 @@ export function SidePanelSupport(): JSX.Element {
)}
</SidePanelPaneHeader>
<div className="p-0 justify-start flex-none px-1 max-w-160 w-full mx-auto flex flex-col">
- {isEmailFormOpen && showEmailSupport && isBillingLoaded && !useProductSupportSidePanel ? (
- <SupportFormBlock
- billing={billing}
- isSubmitting={isSendSupportRequestSubmitting}
- onCancel={() => {
- closeEmailForm()
- closeSupportForm()
- resetSendSupportRequest()
- }}
- />
- ) : (
- <>
- {showMaxAI && isBillingLoaded && (
- <Section title="Ask PostHog AI">
- <div>
- <p>PostHog AI can now answer 80%+ of the support questions we receive! Nice.</p>
- <p>
- Let PostHog AI read 100s of pages of docs for you, write SQL queries and
- expressions, regex patterns, etc.
- </p>
- <LemonButton
- type="primary"
- fullWidth
- center
- onClick={() => {
- openSidePanel(SidePanelTab.Max)
- }}
- targetBlank={false}
- className="mt-2"
- >
- Chat with PostHog AI
- </LemonButton>
- </div>
- </Section>
- )}
-
- {showTickets && isBillingLoaded && (
- <Section title={canCreateTicket ? 'Contact us' : 'Your tickets'}>
- <StatusPageAlert />
- <SupportMessageOverride />
- <p>
- {canCreateTicket
- ? "Can't find what you need and PostHog AI unable to help? Message our support engineers."
- : 'You can keep replying to tickets you already have open.'}
- </p>
- <SidePanelTickets />
- </Section>
- )}
-
- {showEmailSupport && isBillingLoaded && !useProductSupportSidePanel && (
- <Section title="Contact us">
- <StatusPageAlert />
- <SupportMessageOverride />
- <p>Can't find what you need and PostHog AI unable to help?</p>
- <LemonButton
- type="secondary"
- fullWidth
- center
- onClick={handleOpenEmailForm}
- className="mt-2"
- disabled={billingLoading}
- >
- {billingLoading ? 'Loading...' : 'Email our support engineers'}
- </LemonButton>
- </Section>
- )}
-
- {!showEmailSupport && isBillingLoaded && (
- <Section title="">
- <h3>Can't find what you need in the docs?</h3>
- <p>
- With the free plan you can ask the community via the link below, or explore your
- upgrade choices for the ability to email a support engineer.
- </p>
- </Section>
- )}
-
- {/* Community forum */}
- <Section title="Ask the community">
+ {showMaxAI && isBillingLoaded && (
+ <Section title="Ask PostHog AI">
+ <div>
+ <p>PostHog AI can now answer 80%+ of the support questions we receive! Nice.</p>
<p>
- Questions about features, how-tos, or use cases? There are thousands of discussions
- in our community forums.
+ Let PostHog AI read 100s of pages of docs for you, write SQL queries and
+ expressions, regex patterns, etc.
</p>
<LemonButton
- type="secondary"
+ type="primary"
fullWidth
center
- to="https://posthog.com/questions"
- targetBlank
+ onClick={() => {
+ openSidePanel(SidePanelTab.Max)
+ }}
+ targetBlank={false}
className="mt-2"
>
- Ask the community
+ Chat with PostHog AI
</LemonButton>
- </Section>
-
- {/* Add support hours and table */}
- <div className="mb-2">
- <strong>Support is open Monday - Friday</strong>
</div>
- <SupportResponseTimesTable billing={billing} isCompact={true} />
- {billingPlan !== BillingPlan.Enterprise && (
- <div className="flex justify-end">
- <Link to={urls.organizationBilling([ProductKey.PLATFORM_AND_SUPPORT])}>
- Upgrade support plan
- </Link>
- </div>
- )}
-
- {/* Share feedback section */}
- <Section title="Share feedback">
- <ul>
- <li>
- <LemonButton
- type="secondary"
- status="alt"
- to="https://posthog.com/wip"
- icon={<IconHelmet />}
- targetBlank
- >
- See what we're building
- </LemonButton>
- </li>
- <li>
- <LemonButton
- type="secondary"
- status="alt"
- to="https://posthog.com/roadmap"
- icon={<IconMap />}
- targetBlank
- >
- Vote on our roadmap
- </LemonButton>
- </li>
- <li>
- <LemonButton
- type="secondary"
- status="alt"
- to="https://github.com/PostHog/posthog/issues/new?&labels=enhancement&template=feature_request.yml"
- icon={<IconFeatures />}
- targetBlank
- >
- Request a feature
- </LemonButton>
- </li>
- </ul>
- </Section>
- </>
+ </Section>
+ )}
+
+ {showTickets && isBillingLoaded && (
+ <Section title={canCreateTicket ? 'Contact us' : 'Your tickets'}>
+ <StatusPageAlert />
+ <SupportMessageOverride />
+ <p>
+ {canCreateTicket
+ ? "Can't find what you need and PostHog AI unable to help? Message our support engineers."
+ : 'You can keep replying to tickets you already have open.'}
+ </p>
+ <SidePanelTickets />
+ </Section>
)}
+
+ {!showTickets && isBillingLoaded && (
+ <Section title="">
+ <h3>Can't find what you need in the docs?</h3>
+ <p>
+ With the free plan you can ask the community via the link below, or explore your upgrade
+ choices to message our support engineers.
+ </p>
+ </Section>
+ )}
+
+ {/* Community forum */}
+ <Section title="Ask the community">
+ <p>
+ Questions about features, how-tos, or use cases? There are thousands of discussions in our
+ community forums.
+ </p>
+ <LemonButton
+ type="secondary"
+ fullWidth
+ center
+ to="https://posthog.com/questions"
+ targetBlank
+ className="mt-2"
+ >
+ Ask the community
+ </LemonButton>
+ </Section>
+
+ {/* Add support hours and table */}
+ <div className="mb-2">
+ <strong>Support is open Monday - Friday</strong>
+ </div>
+ <SupportResponseTimesTable billing={billing} isCompact={true} />
+ {billingPlan !== BillingPlan.Enterprise && (
+ <div className="flex justify-end">
+ <Link to={urls.organizationBilling([ProductKey.PLATFORM_AND_SUPPORT])}>
+ Upgrade support plan
+ </Link>
+ </div>
+ )}
+
+ {/* Share feedback section */}
+ <Section title="Share feedback">
+ <ul>
+ <li>
+ <LemonButton
+ type="secondary"
+ status="alt"
+ to="https://posthog.com/wip"
+ icon={<IconHelmet />}
+ targetBlank
+ >
+ See what we're building
+ </LemonButton>
+ </li>
+ <li>
+ <LemonButton
+ type="secondary"
+ status="alt"
+ to="https://posthog.com/roadmap"
+ icon={<IconMap />}
+ targetBlank
+ >
+ Vote on our roadmap
+ </LemonButton>
+ </li>
+ <li>
+ <LemonButton
+ type="secondary"
+ status="alt"
+ to="https://github.com/PostHog/posthog/issues/new?&labels=enhancement&template=feature_request.yml"
+ icon={<IconFeatures />}
+ targetBlank
+ >
+ Request a feature
+ </LemonButton>
+ </li>
+ </ul>
+ </Section>
</div>
</SidePanelContentContainer>
</div>
diff --git a/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.test.tsx b/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.test.tsx
index c81814d0bf0c..920051898619 100644
--- a/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.test.tsx
+++ b/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.test.tsx
@@ -265,10 +265,10 @@ describe('FeaturePreviewSceneGate', () => {
describe('request access', () => {
const CONFIG_WITH_SUPPORT: FeaturePreviewGateConfig = {
...BASE_CONFIG,
- supportTargetArea: 'customer_analytics',
+ offerRequestAccess: true,
}
- test('does not show "Request access" when config has no supportTargetArea', () => {
+ test('does not show "Request access" when config does not offer it', () => {
setupMocks({ earlyAccessFeatures: [] })
render(<FeaturePreviewSceneGate config={BASE_CONFIG}>{CHILDREN}</FeaturePreviewSceneGate>)
@@ -290,9 +290,7 @@ describe('FeaturePreviewSceneGate', () => {
render(<FeaturePreviewSceneGate config={CONFIG_WITH_SUPPORT}>{CHILDREN}</FeaturePreviewSceneGate>)
await userEvent.click(screen.getByText('Request access'))
- expect(mockOpenSupportForm).toHaveBeenCalledWith(
- expect.objectContaining({ kind: 'support', target_area: 'customer_analytics' })
- )
+ expect(mockOpenSupportForm).toHaveBeenCalledWith(expect.objectContaining({ kind: 'support' }))
})
})
diff --git a/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.tsx b/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.tsx
index f47f024c6c4e..f9ddd6ce9cef 100644
--- a/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.tsx
+++ b/frontend/src/layout/scenes/components/FeaturePreviewSceneGate.tsx
@@ -4,7 +4,7 @@ import { useEffect } from 'react'
import { LemonButton, LemonSwitch } from '@posthog/lemon-ui'
import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
-import { SupportTicketTargetArea, supportLogic } from 'lib/components/Support/supportLogic'
+import { supportLogic } from 'lib/components/Support/supportLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { sceneLogic } from 'scenes/sceneLogic'
@@ -78,13 +78,12 @@ function FeaturePreviewGateContent({ config }: { config: FeaturePreviewGateConfi
<LemonButton type="primary" to={urls.featurePreview(config.flag)}>
Open feature previews
</LemonButton>
- {config.supportTargetArea && preflight?.cloud && (
+ {config.offerRequestAccess && preflight?.cloud && (
<LemonButton
type="secondary"
onClick={() =>
openSupportForm({
kind: 'support',
- target_area: config.supportTargetArea as SupportTicketTargetArea,
message: `I'd like to request access to ${config.title}.`,
})
}
diff --git a/frontend/src/lib/components/Support/SupportForm.tsx b/frontend/src/lib/components/Support/SupportForm.tsx
index ee55d4aab212..4636d77e0bea 100644
--- a/frontend/src/lib/components/Support/SupportForm.tsx
+++ b/frontend/src/lib/components/Support/SupportForm.tsx
@@ -2,52 +2,16 @@ import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import { useRef } from 'react'
-import { IconBug, IconInfo, IconQuestion } from '@posthog/icons'
-import {
- LemonBanner,
- LemonInput,
- LemonSegmentedButton,
- LemonSegmentedButtonOption,
- Link,
- Tooltip,
- lemonToast,
-} from '@posthog/lemon-ui'
+import { LemonInput, lemonToast } from '@posthog/lemon-ui'
import { useUploadFiles } from 'lib/hooks/useUploadFiles'
-import { IconFeedback } from 'lib/lemon-ui/icons'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput/LemonFileInput'
-import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
-import { LemonSelect } from 'lib/lemon-ui/LemonSelect/LemonSelect'
import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea/LemonTextArea'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { userLogic } from 'scenes/userLogic'
-import {
- SEVERITY_LEVEL_TO_NAME,
- SUPPORT_TICKET_TEMPLATES,
- SupportTicketKind,
- TARGET_AREA_OPTIONS,
- supportLogic,
-} from './supportLogic'
-
-const SUPPORT_TICKET_OPTIONS: LemonSegmentedButtonOption<SupportTicketKind>[] = [
- {
- value: 'support',
- label: 'Question',
- icon: <IconQuestion />,
- },
- {
- value: 'feedback',
- label: 'Feedback',
- icon: <IconFeedback />,
- },
- {
- value: 'bug',
- label: 'Bug',
- icon: <IconBug />,
- },
-]
+import { SUPPORT_TICKET_TEMPLATES, SupportTicketKind, supportLogic } from './supportLogic'
const SUPPORT_TICKET_KIND_TO_PROMPT: Record<SupportTicketKind, string> = {
bug: "What's the bug?",
@@ -63,7 +27,7 @@ interface SupportFormProps {
}
export function SupportForm({ messageLabel, messagePlaceholder }: SupportFormProps = {}): JSX.Element | null {
- const { sendSupportRequest, conversationsFlagEnabled } = useValues(supportLogic)
+ const { sendSupportRequest } = 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
@@ -99,15 +63,6 @@ export function SupportForm({ messageLabel, messagePlaceholder }: SupportFormPro
},
})
- const changeKind = (kind: SupportTicketKind): void => {
- setSendSupportRequestValue('kind', kind)
- if (kind === 'bug') {
- setSendSupportRequestValue('severity_level', 'medium')
- } else {
- setSendSupportRequestValue('severity_level', 'low')
- }
- }
-
return (
<Form
logic={supportLogic}
@@ -126,62 +81,6 @@ export function SupportForm({ messageLabel, messagePlaceholder }: SupportFormPro
</LemonField>
</>
)}
- {!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
name="message"
label={
@@ -214,36 +113,6 @@ export function SupportForm({ messageLabel, messagePlaceholder }: SupportFormPro
</div>
)}
</LemonField>
- {!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>
- )}
</Form>
)
}
diff --git a/frontend/src/lib/components/Support/supportLogic.test.ts b/frontend/src/lib/components/Support/supportLogic.test.ts
index efe4c0fd99ef..aa0b085df159 100644
--- a/frontend/src/lib/components/Support/supportLogic.test.ts
+++ b/frontend/src/lib/components/Support/supportLogic.test.ts
@@ -1,9 +1,6 @@
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'
@@ -11,6 +8,7 @@ import { OrganizationBasicType, Region, SidePanelTab, TeamPublicType } from '~/t
import {
CONVERSATIONS_MESSAGE_MAX_LENGTH,
getPublicSupportSnippet,
+ SUPPORT_MESSAGE_PREVIEW_MAX_LENGTH,
SupportFormFields,
supportLogic,
} from './supportLogic'
@@ -73,7 +71,7 @@ describe('supportLogic', () => {
it('opens the side panel when target is sidePanel', async () => {
await expectLogic(logic, () => {
- logic.actions.openSupportForm({ kind: 'support', target_area: 'login', target: 'sidePanel' })
+ logic.actions.openSupportForm({ kind: 'support', target: 'sidePanel' })
}).toFinishAllListeners()
expect(sidePanelStateLogic.values.sidePanelOpen).toBe(true)
@@ -83,7 +81,7 @@ describe('supportLogic', () => {
it('opens the modal when target is modal', async () => {
await expectLogic(logic, () => {
- logic.actions.openSupportForm({ kind: 'support', target_area: 'login', target: 'modal' })
+ logic.actions.openSupportForm({ kind: 'support', target: 'modal' })
}).toFinishAllListeners()
expect(sidePanelStateLogic.values.sidePanelOpen).toBe(false)
@@ -93,7 +91,7 @@ describe('supportLogic', () => {
it('falls back to sidePanelAvailable when no target is given', async () => {
sidePanelStateLogic.actions.setSidePanelAvailable(false)
await expectLogic(logic, () => {
- logic.actions.openSupportForm({ kind: 'support', target_area: 'login' })
+ logic.actions.openSupportForm({ kind: 'support' })
}).toFinishAllListeners()
expect(sidePanelStateLogic.values.sidePanelOpen).toBe(false)
@@ -101,45 +99,28 @@ describe('supportLogic', () => {
})
})
- describe('submitSupportTicket routing', () => {
- const ZENDESK_URL = 'https://posthoghelp.zendesk.com/api/v2/requests.json'
+ describe('submitSupportTicket', () => {
const FORM_FIELDS: SupportFormFields = {
name: 'Max',
kind: 'bug',
- target_area: 'billing',
- severity_level: 'high',
+ billing_issue: true,
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 conversationsMock = (sendMessage: jest.Mock): void => {
+ ;(posthog as any).conversations = { isAvailable: () => true, sendMessage }
+ }
const aiTicketCaptures = (): unknown[][] =>
(posthog.capture as jest.Mock).mock.calls.filter(([event]) => event === 'posthog_ai_support_ticket_created')
- const enableConversationsFlag = (): void => {
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PRODUCT_SUPPORT_SIDE_PANEL]: true })
- }
-
- // Flag state leaks between tests through the window app context, so flag-off tests must
- // disable explicitly rather than rely on the default
- const disableConversationsFlag = (): void => {
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PRODUCT_SUPPORT_SIDE_PANEL]: false })
- }
+ const sendFailures = (): unknown[][] =>
+ (posthog.capture as jest.Mock).mock.calls.filter(([event]) => event === 'support ticket send failed')
beforeEach(() => {
- fetchMock = jest.fn(() =>
- Promise.resolve({
- ok: true,
- json: () => Promise.resolve({ request: { id: 123 } }),
- text: () => Promise.resolve(''),
- } as unknown as Response)
- )
- global.fetch = fetchMock
;(posthog.capture as jest.Mock).mockClear()
initKeaTests()
logic = supportLogic.build()
@@ -149,80 +130,35 @@ describe('supportLogic', () => {
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 () => {
+ it('sends the message through the conversations widget and records the ticket id', async () => {
const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })
- ;(posthog as any).conversations = { isAvailable: () => true, sendMessage }
- enableConversationsFlag()
+ conversationsMock(sendMessage)
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 () => {
+ it('appends exception context to the message so it survives on the ticket', async () => {
const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })
- ;(posthog as any).conversations = { isAvailable: () => true, sendMessage }
- enableConversationsFlag()
+ conversationsMock(sendMessage)
- await expectLogic(logic, () => {
- logic.actions.submitSupportTicket({
- ...FORM_FIELDS,
- exception_event: { uuid: 'exc-1', event: '$exception' },
- })
- }).toFinishAllListeners()
+ await logic.asyncActions.submitSupportTicket({
+ ...FORM_FIELDS,
+ exception_event: { uuid: 'exc-1', event: '$exception' },
+ })
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 () => {
+ it('accepts a submission with no topic or severity, since the form no longer collects them', async () => {
const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })
- ;(posthog as any).conversations = { isAvailable: () => true, sendMessage }
- enableConversationsFlag()
+ conversationsMock(sendMessage)
await expectLogic(logic, () => {
logic.actions.setSendSupportRequestValue('message', 'Just a message')
@@ -233,43 +169,104 @@ describe('supportLogic', () => {
expect(sendMessage.mock.calls[0][0]).toBe('Just a message')
})
- it('blocks an over-limit message client-side without sending or falling back to Zendesk', async () => {
+ it('blocks an over-limit message before it reaches the widget, and reports it', async () => {
const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })
- ;(posthog as any).conversations = { isAvailable: () => true, sendMessage }
- enableConversationsFlag()
+ conversationsMock(sendMessage)
await logic.asyncActions.submitSupportTicket({
...FORM_FIELDS,
message: 'a'.repeat(CONVERSATIONS_MESSAGE_MAX_LENGTH + 1),
})
- // Guarded before it leaves the browser: no widget send, and no Zendesk double-file
expect(sendMessage).not.toHaveBeenCalled()
- expect(zendeskCalls()).toHaveLength(0)
expect(logic.values.lastSubmittedTicketId).toBeNull()
+ // Rejecting client-side still loses the customer's message, so it is a reportable failure
+ // rather than a quiet no-op — this path used to emit nothing at all
+ expect(sendFailures()).toHaveLength(1)
+ expect(sendFailures()[0][1]).toMatchObject({ reason: 'message_too_long', had_draft: true })
})
- 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()
+ // The whole point of these events is that a responder can act on one from an alert without the
+ // ticket that never got created. That needs the draft and a way back into the session.
+ it('carries the draft and session context on a lost submit, so an alert is actionable', async () => {
+ ;(posthog.get_session_id as jest.Mock).mockReturnValue('sess-1')
+ // Project-scoped path, the shape posthog-js actually returns — see the snippet tests
+ ;(posthog.get_session_replay_url as jest.Mock).mockReturnValue(
+ `${window.location.origin}/project/sTMFPsFhdP1Ssg/replay/sess-1?t=30`
+ )
+ conversationsMock(jest.fn().mockRejectedValue(new Error('network down')))
+
+ await logic.asyncActions.submitSupportTicket({ ...FORM_FIELDS, message: 'Billing is broken' })
+
+ expect(sendFailures()[0][1]).toMatchObject({
+ surface: 'support_form',
+ reason: 'send_failed',
+ error: 'network down',
+ had_draft: true,
+ message_preview: 'Billing is broken',
+ message_truncated: false,
+ session_id: 'sess-1',
+ // Golinked for the same reason as the ticket snippet: staff-facing, not user-facing
+ session_replay_url: 'http://go/session/sess-1?t=30',
+ })
+ })
+
+ it('truncates a long draft rather than putting a whole document in an event property', async () => {
+ conversationsMock(jest.fn().mockResolvedValue(null))
+
+ await logic.asyncActions.submitSupportTicket({
+ ...FORM_FIELDS,
+ message: 'b'.repeat(SUPPORT_MESSAGE_PREVIEW_MAX_LENGTH + 500),
+ })
+
+ const properties = sendFailures()[0][1] as Record<string, any>
+ expect(properties.message_preview).toHaveLength(SUPPORT_MESSAGE_PREVIEW_MAX_LENGTH)
+ expect(properties.message_truncated).toBe(true)
+ // The real length still travels, so the preview being capped doesn't hide how much was lost
+ expect(properties.message_length).toBe(SUPPORT_MESSAGE_PREVIEW_MAX_LENGTH + 500)
+ })
+
+ // lastSubmittedTicketId staying null is how every caller detects failure, and there is no
+ // second channel to retry on, so each of these must report rather than silently drop. The
+ // reason has to survive too: it drives which advice the user gets.
+ it.each([
+ ['the widget declines to send', jest.fn().mockResolvedValue(null), 'widget_declined'],
+ ['the send throws', jest.fn().mockRejectedValue(new Error('network down')), 'send_failed'],
+ ])('reports a failure and files no ticket when %s', async (_case, sendMessage, expectedReason) => {
+ conversationsMock(sendMessage)
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()
+ expect(sendFailures()).toHaveLength(1)
+ expect(sendFailures()[0][1]).toMatchObject({ reason: expectedReason })
})
- // Regression guard: the AI /ticket handover event must fire from supportLogic once the ticket id
- // resolves. It previously lived in a component effect that raced the async conversations
- // round-trip and silently dropped the event once submissions were routed to conversations.
- it('captures posthog_ai_support_ticket_created once on the conversations path when AI context is present', async () => {
- const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })
- ;(posthog as any).conversations = { isAvailable: () => true, sendMessage }
- enableConversationsFlag()
+ it('waits for the lazily-loaded extension, then reports a failure if it never arrives', async () => {
+ ;(posthog as any).conversations = undefined
+
+ jest.useFakeTimers()
+ try {
+ const promise = logic.asyncActions.submitSupportTicket(FORM_FIELDS)
+ // Still waiting on the extension, so nothing is reported yet
+ expect(sendFailures()).toHaveLength(0)
+ await jest.runAllTimersAsync()
+ await promise
+ } finally {
+ jest.useRealTimers()
+ }
+
+ // Reported as unavailable, not as a failed send: a blocked script won't come back, so the
+ // user gets the email address instead of being told to retry
+ expect(sendFailures()).toHaveLength(1)
+ expect(sendFailures()[0][1]).toMatchObject({ reason: 'widget_unavailable' })
+ expect(logic.values.lastSubmittedTicketId).toBeNull()
+ })
+
+ // Regression guard: this event used to live in a component effect that raced the async
+ // conversations round-trip and silently dropped it. It belongs here, where the ticket id lands.
+ it('captures the AI ticket event once when the submission carries AI context', async () => {
+ conversationsMock(jest.fn().mockResolvedValue({ ticket_id: 't1' }))
await logic.asyncActions.submitSupportTicket({
...FORM_FIELDS,
@@ -292,32 +289,8 @@ describe('supportLogic', () => {
])
})
- it('captures posthog_ai_support_ticket_created on the Zendesk fallback path with the zendesk ticket id', async () => {
- // Flag off and no conversations extension → Zendesk path; fetchMock returns request id 123
- disableConversationsFlag()
- await logic.asyncActions.submitSupportTicket({
- ...FORM_FIELDS,
- ai_conversation_id: 'conv-2',
- ai_trace_id: null,
- })
-
- expect(aiTicketCaptures()).toEqual([
- [
- 'posthog_ai_support_ticket_created',
- {
- $ai_conversation_id: 'conv-2',
- $ai_session_id: 'conv-2',
- $ai_trace_id: null,
- $ai_support_ticket_id: '123',
- },
- ],
- ])
- })
-
- it('does not capture the AI ticket event for a regular (non-AI) submission', async () => {
- const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })
- ;(posthog as any).conversations = { isAvailable: () => true, sendMessage }
- enableConversationsFlag()
+ it('does not capture the AI ticket event for a regular submission', async () => {
+ conversationsMock(jest.fn().mockResolvedValue({ ticket_id: 't1' }))
await logic.asyncActions.submitSupportTicket(FORM_FIELDS)
diff --git a/frontend/src/lib/components/Support/supportLogic.ts b/frontend/src/lib/components/Support/supportLogic.ts
index 7c1e27de36f3..2ff66de3139b 100644
--- a/frontend/src/lib/components/Support/supportLogic.ts
+++ b/frontend/src/lib/components/Support/supportLogic.ts
@@ -3,34 +3,22 @@ import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import posthog from 'posthog-js'
-import { LemonSelectOptions } from '@posthog/lemon-ui'
-
-import api from 'lib/api'
-import { FEATURE_FLAGS } from 'lib/constants'
import { EMAIL_SUPPORT_BUTTON, 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'
-import { organizationLogic } from 'scenes/organizationLogic'
-import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import {
- AvailableFeature,
BillingPlan,
BillingPlanType,
OrganizationBasicType,
Region,
SidePanelTab,
- StartupProgramLabel,
TeamPublicType,
UserType,
} from '~/types'
-import type { BillingType, PreflightStatus } from '../../../types'
-import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'
+import type { BillingType } from '../../../types'
import { parseExceptionEvent } from './exceptionUtils'
import { openSupportModal } from './SupportModal'
import { getSupportResponseTime } from './supportResponseTime'
@@ -58,74 +46,22 @@ function getCurrentLocationLink(): string {
}
// The recording lives in PostHog's own telemetry project, which the reporting user is not a member
-// of, so this link is for PostHog staff triaging the ticket/issue — never the user. We rewrite to the
-// internal http://go/session/ golink to make that explicit. posthog-js returns a project-scoped path
-// (`/project/<token>/replay/<id>`), so pull the session id out of the `/replay/` segment rather than
-// assuming the URL starts with the current origin.
-function getSessionReplayLink(): string {
+// of, so this is for PostHog staff triaging the ticket or the alert — never the user. posthog-js
+// returns a project-scoped path (`/project/<token>/replay/<id>`), so pull the session id out of the
+// `/replay/` segment rather than assuming the URL starts with the current origin.
+function getSessionReplayGolink(): string | null {
const replayUrl = posthog.get_session_replay_url?.({ withTimestamp: true, timestampLookBack: 30 })
- if (!replayUrl) {
- return ''
- }
- const match = replayUrl.match(/\/replay\/([^/?#]+)([?#].*)?$/)
+ const match = replayUrl?.match(/\/replay\/([^/?#]+)([?#].*)?$/)
if (!match) {
- return ''
+ return null
}
const [, sessionId, queryAndHash] = match
- return `\nSession: http://go/session/${sessionId}${queryAndHash ?? ''}`
-}
-
-function getErrorTrackingLink(uuid?: string): string {
- const values = [
- {
- key: '$session_id',
- value: [posthog.get_session_id()],
- operator: 'exact',
- type: 'event',
- },
- ]
-
- if (uuid) {
- values.push({
- type: 'hogql',
- key: `uuid = '${uuid}'`,
- value: null,
- } as any)
- }
-
- const filterGroup = encodeURIComponent(
- JSON.stringify({
- type: 'AND',
- values: [
- {
- type: 'AND',
- values,
- },
- ],
- })
- )
-
- return `\nExceptions: https://us.posthog.com/project/2/error_tracking?filterGroup=${filterGroup}`
+ return `http://go/session/${sessionId}${queryAndHash ?? ''}`
}
-function getDjangoAdminLink(
- user: UserType | null,
- cloudRegion: Region | null | undefined,
- currentOrganization: OrganizationBasicType | null,
- currentTeam: TeamPublicType | null
-): string {
- if (!user || !cloudRegion) {
- return ''
- }
- const link = `https://${cloudRegion.toLowerCase()}.posthog.com/admin/posthog/user/${user.id}/change/`
- return `\nAdmin (internal): ${link} (organization ID ${currentOrganization?.id}: ${currentOrganization?.name}, project ID ${currentTeam?.id}: ${currentTeam?.name})`
-}
-
-function getBillingAdminLink(currentOrganization: OrganizationBasicType | null): string {
- if (!currentOrganization) {
- return ''
- }
- return `\nBilling admin (internal): http://go/billing/${currentOrganization.id}`
+function getSessionReplayLink(): string {
+ const golink = getSessionReplayGolink()
+ return golink ? `\nSession: ${golink}` : ''
}
const SUPPORT_TICKET_KIND_TO_TITLE: Record<SupportTicketKind, string> = {
@@ -134,9 +70,8 @@ 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.
+// The conversations extension loads lazily; poll briefly before sending so a fast submit right
+// after page load doesn't miss it. 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) {
@@ -152,9 +87,113 @@ async function waitForConversations(timeoutMs = 5000): Promise<boolean> {
// through posthog.conversations.sendMessage (the widget endpoint), so guard against the same cap.
export const CONVERSATIONS_MESSAGE_MAX_LENGTH = 10000
-// Shared over-limit guard for the conversations composer surfaces (support form + side panel). Shows
-// an error toast and returns true when the message exceeds the widget cap, so callers bail before
-// hitting the endpoint and surfacing only a generic send-failure toast.
+/** Where the customer was when support broke for them. */
+export type SupportFailureSurface =
+ | 'support_form' // the modal / side-panel support form (every "contact support" CTA)
+ | 'side_panel_composer' // the conversations composer in the support panel
+ | 'side_panel_tickets' // the panel's ticket list and message threads
+ | 'restore_form' // "email me a link to my tickets"
+
+/** Why a submitted message never became a ticket. Every one of these loses customer intent. */
+export type SupportSendFailureReason =
+ | 'widget_unavailable' // extension never loaded (ad blocker, network policy) — no retry will fix it
+ | 'widget_declined' // extension returned no response; nothing left the browser
+ | 'send_failed' // the request threw
+ | 'message_too_long' // rejected by the client-side cap before we tried
+ | 'not_entitled' // plan has no ticket channel, so the draft was dropped on the floor
+
+/** Why a support surface couldn't function. Nothing was submitted, so no message is at risk. */
+export type SupportLoadFailureReason =
+ | 'extension_missing' // posthog.conversations never showed up
+ | 'tickets_load_failed' // listing existing tickets threw
+ | 'thread_load_failed' // opening a ticket's messages threw
+ | 'restore_link_failed' // a request rather than a load, but the same "surface can't do its job"
+
+// Event properties are no place to store a document, so the draft an alert carries is capped.
+export const SUPPORT_MESSAGE_PREVIEW_MAX_LENGTH = 1000
+
+export const SUPPORT_WIDGET_UNAVAILABLE_MESSAGE =
+ "We can't load the support chat, which is usually an ad blocker or a network policy."
+
+// `current_url` is explicit rather than autocapture's `$current_url`, so an alert template reading
+// these properties doesn't depend on autocapture staying enabled.
+function supportFailureContext(): Record<string, any> {
+ return {
+ session_id: posthog.get_session_id?.() ?? null,
+ session_replay_url: getSessionReplayGolink(),
+ current_url: window.location.href,
+ }
+}
+
+function errorMessage(error: unknown): string | undefined {
+ if (error === undefined) {
+ return undefined
+ }
+ return error instanceof Error ? error.message : String(error)
+}
+
+// Always the same keys, so the event stays queryable whether or not anything had been typed
+function messagePreviewProperties(message?: string): Record<string, any> {
+ const draft = message?.trim() ?? ''
+ return {
+ had_draft: !!draft,
+ message_length: draft.length,
+ message_truncated: draft.length > SUPPORT_MESSAGE_PREVIEW_MAX_LENGTH,
+ message_preview: draft.slice(0, SUPPORT_MESSAGE_PREVIEW_MAX_LENGTH),
+ }
+}
+
+// Shares its event name with the widget endpoint's own rejections so one alert covers client and
+// server. Note the backend tags itself `channel_source`, not `channel`.
+export function captureSupportTicketFailed({
+ surface,
+ reason,
+ message,
+ error,
+ ...rest
+}: {
+ surface: SupportFailureSurface
+ reason: SupportSendFailureReason
+ message?: string
+ error?: unknown
+ kind?: SupportTicketKind | null
+ is_new_ticket?: boolean
+ can_create_ticket?: boolean
+}): void {
+ posthog.capture('support ticket send failed', {
+ channel: 'conversations',
+ surface,
+ reason,
+ error: errorMessage(error),
+ ...messagePreviewProperties(message),
+ ...supportFailureContext(),
+ ...rest,
+ })
+}
+
+// The rate signal for "support is broken for people", as opposed to the per-message loss above.
+export function captureSupportWidgetLoadFailed({
+ surface,
+ reason,
+ error,
+ ...rest
+}: {
+ surface: SupportFailureSurface
+ reason: SupportLoadFailureReason
+ error?: unknown
+ can_create_ticket?: boolean
+}): void {
+ posthog.capture('support widget load failed', {
+ surface,
+ reason,
+ error: errorMessage(error),
+ ...supportFailureContext(),
+ ...rest,
+ })
+}
+
+// Returns true when the message exceeds the cap the widget endpoint enforces, so callers can bail
+// before the network. Callers report it: the customer pressed send and has no ticket.
export function warnIfMessageTooLong(message: string): boolean {
if (message.length > CONVERSATIONS_MESSAGE_MAX_LENGTH) {
lemonToast.error(
@@ -165,6 +204,13 @@ export function warnIfMessageTooLong(message: string): boolean {
return false
}
+// The widget is a lazily-loaded posthog-js extension, so its absence is rarely something a retry
+// fixes — name the likely cause instead of saying "try again", and stay open because waiting won't
+// help. Only for users entitled to email us: a free plan has no email channel to point at.
+export function warnSupportWidgetUnavailable(): void {
+ lemonToast.error(SUPPORT_WIDGET_UNAVAILABLE_MESSAGE, { button: EMAIL_SUPPORT_BUTTON, autoClose: false })
+}
+
// 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
@@ -173,220 +219,10 @@ export function appendExceptionToMessage(message: string, exception_event?: Supp
if (!exception_event) {
return message
}
- return `${message}\n\n-----\nException: ${parseExceptionEvent(exception_event)}`
-}
-
-const TARGET_AREA_TO_NAME_GENERAL = [
- {
- value: 'login',
- 'data-attr': `support-form-target-area-login`,
- label: 'Authentication (incl. login, sign-up, invites)',
- },
- {
- value: 'analytics_platform',
- 'data-attr': `support-form-target-area-analytics_platform`,
- label: 'Analytics features (incl. alerts, subscriptions, exports, etc.)',
- },
- {
- value: 'billing',
- 'data-attr': `support-form-target-area-billing`,
- label: 'Billing',
- },
- {
- value: 'cohorts',
- 'data-attr': `support-form-target-area-cohorts`,
- label: 'Cohorts',
- },
- {
- value: 'data_ingestion',
- 'data-attr': `support-form-target-area-data_ingestion`,
- label: 'Data ingestion',
- },
- {
- value: 'health_overview',
- 'data-attr': `support-form-target-area-health_overview`,
- label: 'Health overview',
- },
- {
- value: 'data_management',
- 'data-attr': `support-form-target-area-data_management`,
- label: 'Data management (incl. events, actions, properties)',
- },
- {
- value: 'mobile',
- 'data-attr': `support-form-target-area-mobile`,
- label: 'Mobile',
- },
- {
- value: 'notebooks',
- 'data-attr': `support-form-target-area-notebooks`,
- label: 'Notebooks',
- },
- {
- value: 'onboarding',
- 'data-attr': `support-form-target-area-onboarding`,
- label: 'Onboarding',
- },
- {
- value: 'platform_addons',
- 'data-attr': `support-form-target-area-platform_addons`,
- label: 'Platform addons',
- },
- {
- value: 'sdk',
- 'data-attr': `support-form-target-area-onboarding`,
- label: 'SDK / Implementation',
- },
- {
- value: 'setup-wizard',
- 'data-attr': `support-form-target-area-setup-wizard`,
- label: 'Wizard',
- },
-] as const satisfies LemonSelectOptions<string>
-
-const TARGET_AREA_TO_NAME_PRODUCTS = [
- {
- value: 'ai_gateway',
- 'data-attr': `support-form-target-area-ai_gateway`,
- label: 'AI gateway',
- },
- {
- value: 'llm-analytics',
- 'data-attr': `support-form-target-area-llm-analytics`,
- label: 'AI observability',
- },
- {
- value: 'apps',
- 'data-attr': `support-form-target-area-apps`,
- label: 'Apps (incl. integrations, plugins, webhooks, and custom apps)',
- },
- {
- value: 'batch_exports',
- 'data-attr': `support-form-target-area-batch_exports`,
- label: 'Destinations (batch exports)',
- },
- {
- value: 'cdp_destinations',
- 'data-attr': `support-form-target-area-cdp_destinations`,
- label: 'Destinations (real-time)',
- },
- {
- value: 'data_modeling',
- 'data-attr': `support-form-target-area-data_modeling`,
- label: 'Data modeling (views, matviews, endpoints)',
- },
- {
- value: 'data_warehouse',
- 'data-attr': `support-form-target-area-data_warehouse`,
- label: 'Data warehouse (sources)',
- },
- {
- value: 'error_tracking',
- 'data-attr': `support-form-target-area-error_tracking`,
- label: 'Error tracking',
- },
- {
- value: 'experiments',
- 'data-attr': `support-form-target-area-experiments`,
- label: 'Experiments',
- },
- {
- value: 'feature_flags',
- 'data-attr': `support-form-target-area-feature_flags`,
- label: 'Feature flags',
- },
- {
- value: 'group_analytics',
- 'data-attr': `support-form-target-area-group-analytics`,
- label: 'Group analytics',
- },
- {
- value: 'customer_analytics',
- 'data-attr': `support-form-target-area-customer-analytics`,
- label: 'Customer analytics',
- },
- {
- value: 'heatmaps',
- 'data-attr': `support-form-target-area-heatmaps`,
- label: 'Heatmaps',
- },
- {
- value: 'logs',
- 'data-attr': `support-form-target-area-logs`,
- label: 'Logs',
- },
- {
- value: 'posthog-ai',
- 'data-attr': `support-form-target-area-posthog-ai`,
- label: 'PostHog AI',
- },
- {
- value: 'posthog-mcp',
- 'data-attr': `support-form-target-area-posthog-mcp`,
- label: 'PostHog MCP',
- },
- {
- value: 'analytics',
- 'data-attr': `support-form-target-area-analytics`,
- label: 'Product analytics (incl. insights, dashboards, etc.)',
- },
- {
- value: 'revenue_analytics',
- 'data-attr': `support-form-target-area-revenue-analytics`,
- label: 'Revenue analytics',
- },
- {
- value: 'session_replay',
- 'data-attr': `support-form-target-area-session_replay`,
- label: 'Session replay (incl. recordings)',
- },
- {
- value: 'signals',
- 'data-attr': `support-form-target-area-signals`,
- label: 'Inbox',
- },
- {
- value: 'slack',
- 'data-attr': `support-form-target-area-slack`,
- label: 'Slack app',
- },
- {
- value: 'surveys',
- 'data-attr': `support-form-target-area-surveys`,
- label: 'Surveys',
- },
- {
- value: 'toolbar',
- 'data-attr': `support-form-target-area-toolbar`,
- label: 'Toolbar',
- },
- {
- value: 'web_analytics',
- 'data-attr': `support-form-target-area-web_analytics`,
- label: 'Web analytics',
- },
- {
- value: 'workflows',
- 'data-attr': `support-form-target-area-workflows`,
- label: 'Workflows / Messaging',
- },
-] as const satisfies LemonSelectOptions<string>
-
-export const TARGET_AREA_TO_NAME = [
- { title: 'General', options: TARGET_AREA_TO_NAME_GENERAL },
- { title: 'Individual product', options: TARGET_AREA_TO_NAME_PRODUCTS },
-]
-
-// `key` is the label (not the value) so the searchable input shows readable text on edit, not the raw target_area
-export const TARGET_AREA_OPTIONS: { key: string; label: string; value: string }[] = TARGET_AREA_TO_NAME.flatMap(
- (group) => group.options.map((option) => ({ key: option.label, label: option.label, value: option.value }))
-)
-
-export const SEVERITY_LEVEL_TO_NAME = {
- critical: 'Outage, data loss, or data breach',
- high: 'Feature is not working at all',
- medium: 'Feature not working as expected',
- low: 'Question or feature request',
+ const exception = `Exception: ${parseExceptionEvent(exception_event)}`
+ // The separator divides the user's own words from the machine context, so it only earns its place
+ // when there are words above it — an error boundary CTA carries an exception and nothing else.
+ return message ? `${message}\n\n-----\n${exception}` : exception
}
export const SUPPORT_KIND_TO_SUBJECT = {
@@ -395,57 +231,10 @@ export const SUPPORT_KIND_TO_SUBJECT = {
support: 'Support Ticket',
}
-export type SupportTicketTargetArea =
- | (typeof TARGET_AREA_TO_NAME_GENERAL)[number]['value']
- | (typeof TARGET_AREA_TO_NAME_PRODUCTS)[number]['value']
-export type SupportTicketSeverityLevel = keyof typeof SEVERITY_LEVEL_TO_NAME
export type SupportTicketKind = keyof typeof SUPPORT_KIND_TO_SUBJECT
export type SupportTicketExceptionEvent = { uuid: string; event: string; properties?: Record<string, any> }
-export const getLabelBasedOnTargetArea = (target_area: SupportTicketTargetArea): null | string => {
- for (const category of TARGET_AREA_TO_NAME) {
- for (const option of category.options) {
- if (option.value === target_area) {
- return option.label
- }
- }
- }
- return null // Return null if the value is not found
-}
-
-export const URL_PATH_TO_TARGET_AREA: Record<string, SupportTicketTargetArea> = {
- 'ai-gateway': 'ai_gateway',
- insights: 'analytics',
- recordings: 'session_replay',
- replay: 'session_replay',
- dashboard: 'analytics',
- feature_flags: 'feature_flags',
- experiments: 'experiments',
- 'web-performance': 'session_replay',
- events: 'analytics',
- 'data-management': 'data_management',
- cohorts: 'cohorts',
- annotations: 'analytics',
- persons: 'analytics',
- groups: 'analytics',
- heatmaps: 'heatmaps',
- toolbar: 'toolbar',
- warehouse: 'data_warehouse',
- surveys: 'surveys',
- web: 'web_analytics',
- destination: 'cdp_destinations',
- destinations: 'cdp_destinations',
- transformation: 'cdp_destinations',
- transformations: 'cdp_destinations',
- source: 'data_warehouse',
- sources: 'data_warehouse',
- workflows: 'workflows',
- billing: 'billing',
- logs: 'logs',
- inbox: 'signals',
-}
-
export const SUPPORT_TICKET_TEMPLATES = {
bug: 'Please describe the bug you saw, and how to reproduce it.\n\nIf the bug appeared on a specific insight or dashboard, please include a link to it.',
feedback:
@@ -454,32 +243,6 @@ export const SUPPORT_TICKET_TEMPLATES = {
"Please explain as fully as possible what you're aiming to do, and what you'd like help with.\n\nIf your question involves an existing insight or dashboard, please include a link to it.",
}
-const SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS = {
- severity: 22084126888475,
- distinct_id: 22129191462555,
- target_area: 27242745654043,
- organization_id: 27031528411291,
- support_type: 26073267652251,
- account_owner: 37742340880411,
- exception_event: 39967113285659,
-} as const
-
-export function getURLPathToTargetArea(pathname: string): SupportTicketTargetArea | null {
- const pathParts = pathname.split('/')
-
- if (pathname.includes('pipeline/destinations/') && !pathname.includes('/hog-')) {
- return 'batch_exports'
- }
-
- for (const part of pathParts) {
- if (URL_PATH_TO_TARGET_AREA[part]) {
- return URL_PATH_TO_TARGET_AREA[part]
- }
- }
-
- return null
-}
-
export type SupportFormLogicProps = {
onClose?: () => void
}
@@ -488,12 +251,15 @@ export type SupportFormFields = {
name: string
email: string
kind: SupportTicketKind
- target_area: SupportTicketTargetArea | null
- severity_level: SupportTicketSeverityLevel | null
message: string
+ /**
+ * Billing questions are answered on every plan, so a billing CTA earns a support exemption even
+ * when the plan itself doesn't include support. This replaced an implicit `target_area === 'billing'`
+ * check, which stopped being expressible once triage fields were dropped.
+ */
+ billing_issue?: boolean
exception_event?: SupportTicketExceptionEvent
isEmailFormOpen?: boolean | 'true' | 'false'
- tags?: string[]
// Set when the ticket originates from a PostHog AI (/ticket, feedback) handover, so the created
// ticket can be attributed back to the conversation regardless of which submit path files it.
ai_conversation_id?: string | null
@@ -506,14 +272,11 @@ export interface supportLogicValues {
billing: BillingType | null // billingLogic
billingPlan: BillingPlan | null // billingLogic
supportPlans: BillingPlanType[] // billingLogic
- featureFlags: FeatureFlagsSet // featureFlagLogic
- isCurrentOrganizationNew: boolean // organizationLogic
- preflight: PreflightStatus | null // preflightLogic
sidePanelAvailable: boolean // sidePanelStateLogic
- hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic
user: UserType | null // userLogic
- conversationsFlagEnabled: boolean
+ isBillingIssue: boolean
isEmailFormOpen: boolean
+ isErrorReport: boolean
isSendSupportRequestSubmitting: boolean
isSendSupportRequestValid: boolean
isSupportFormOpen: boolean
@@ -534,7 +297,6 @@ export interface supportLogicValues {
sendSupportRequestValidationErrors: DeepPartialMap<SupportFormFields, ValidationErrorType>
showSendSupportRequestErrors: boolean
supportResponseTime: string | null
- targetArea: SupportTicketTargetArea | null
title: string
}
@@ -559,9 +321,6 @@ export interface supportLogicActions {
closeSupportForm: () => {
value: true
}
- ensureZendeskOrganization: () => {
- value: true
- }
openEmailForm: () => {
value: true
}
@@ -627,8 +386,8 @@ export interface supportLogicActions {
export interface supportLogicMeta {
__keaTypeGenInternalSelectorTypes: {
title: (arg: SupportFormFields) => string
- targetArea: (sendSupportRequest: SupportFormFields) => SupportTicketTargetArea | null
- conversationsFlagEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ isBillingIssue: (sendSupportRequest: SupportFormFields) => boolean
+ isErrorReport: (sendSupportRequest: SupportFormFields) => boolean
supportResponseTime: (
billing: BillingType | null,
billingPlan: BillingPlan | null,
@@ -652,18 +411,10 @@ export const supportLogic = kea<supportLogicType>([
values: [
userLogic,
['user'],
- preflightLogic,
- ['preflight'],
- userLogic,
- ['hasAvailableFeature'],
billingLogic,
['billing', 'billingPlan', 'supportPlans'],
- organizationLogic,
- ['isCurrentOrganizationNew'],
sidePanelStateLogic,
['sidePanelAvailable'],
- featureFlagLogic,
- ['featureFlags'],
],
actions: [sidePanelStateLogic, ['openSidePanel', 'setSidePanelOptions']],
})),
@@ -671,7 +422,6 @@ export const supportLogic = kea<supportLogicType>([
closeSupportForm: true,
openSupportForm: (values: Partial<SupportFormFields> & { target?: 'modal' | 'sidePanel' }) => values,
submitSupportTicket: (form: SupportFormFields) => form,
- ensureZendeskOrganization: true,
updateUrlParams: true,
openEmailForm: true,
closeEmailForm: true,
@@ -717,25 +467,17 @@ export const supportLogic = kea<supportLogicType>([
name: '',
email: '',
kind: 'support',
- severity_level: null,
- target_area: null,
message: '',
+ billing_issue: false,
} 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.conversationsFlagEnabled
+ errors: ({ name, email, message }) => {
return {
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: 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 ticket
formValues.name = values.user?.first_name ?? formValues.name ?? 'name not set'
formValues.email = values.user?.email ?? formValues.email ?? ''
await supportLogic.asyncActions.submitSupportTicket(formValues)
@@ -750,14 +492,15 @@ export const supportLogic = kea<supportLogicType>([
? SUPPORT_TICKET_KIND_TO_TITLE[sendSupportRequest.kind]
: 'Leave a message with PostHog',
],
- targetArea: [
+ isBillingIssue: [
(s) => [s.sendSupportRequest],
- (sendSupportRequest: SupportFormFields) => sendSupportRequest.target_area,
+ (sendSupportRequest: SupportFormFields) => !!sendSupportRequest.billing_issue,
],
- conversationsFlagEnabled: [
- (s) => [s.featureFlags],
- (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): boolean =>
- !!featureFlags[FEATURE_FLAGS.PRODUCT_SUPPORT_SIDE_PANEL],
+ // A crash we surfaced ourselves. The error boundary offers to email an engineer, so this
+ // earns a support exemption the same way a billing question does — see canCreateTicket.
+ isErrorReport: [
+ (s) => [s.sendSupportRequest],
+ (sendSupportRequest: SupportFormFields) => !!sendSupportRequest.exception_event,
],
supportResponseTime: [
(s) => [s.billing, s.billingPlan, s.supportPlans, s.user],
@@ -779,12 +522,7 @@ export const supportLogic = kea<supportLogicType>([
updateUrlParams: async () => {
// Only include non-text fields in the URL parameters
// This prevents focus loss when typing in text fields
- const panelOptions = [
- values.sendSupportRequest.kind ?? '',
- values.sendSupportRequest.target_area ?? '',
- values.sendSupportRequest.severity_level ?? '',
- values.isEmailFormOpen ?? 'false',
- ].join(':')
+ const panelOptions = [values.sendSupportRequest.kind ?? '', values.isEmailFormOpen ?? 'false'].join(':')
if (panelOptions !== ':') {
actions.setSidePanelOptions(panelOptions)
@@ -795,25 +533,19 @@ export const supportLogic = kea<supportLogicType>([
email,
isEmailFormOpen,
kind,
- target_area,
- severity_level,
message,
exception_event,
+ billing_issue,
target,
}: Partial<SupportFormFields> & { target?: 'modal' | 'sidePanel' }) => {
- let area = target_area ?? getURLPathToTargetArea(window.location.pathname)
- if (!userLogic.values.user) {
- area = 'login'
- }
kind = kind ?? 'support'
actions.resetSendSupportRequest({
name: name ?? '',
email: email ?? '',
kind,
- target_area: area,
- severity_level: severity_level ?? null,
message: message ?? values.sendSupportRequest.message ?? '',
exception_event,
+ billing_issue: billing_issue ?? false,
})
if (isEmailFormOpen === 'true' || isEmailFormOpen === true) {
@@ -824,8 +556,7 @@ export const supportLogic = kea<supportLogicType>([
const useSidePanel = target ? target === 'sidePanel' : values.sidePanelAvailable
if (useSidePanel) {
- const panelOptions = [kind ?? '', area ?? ''].join(':')
- actions.openSidePanel(SidePanelTab.Support, panelOptions === ':' ? undefined : panelOptions)
+ actions.openSidePanel(SidePanelTab.Support, kind || undefined)
} else {
openSupportModal()
}
@@ -833,12 +564,12 @@ export const supportLogic = kea<supportLogicType>([
actions.updateUrlParams()
},
submitSupportTicket: async (formValues: SupportFormFields) => {
- const { name, email, kind, target_area, severity_level, message, exception_event, tags } = formValues
+ const { name, email, kind, message, exception_event } = formValues
const { ai_conversation_id, ai_trace_id, ai_feedback_rating } = formValues
// Attribute PostHog AI (/ticket, feedback) handovers to the conversation. The ticket id
- // only exists once a submit path resolves — capturing from here means it fires no matter
- // which path files the ticket, instead of relying on a component effect that races the
+ // only exists once the send resolves — capturing from here means it fires no matter which
+ // caller triggered the submit, instead of relying on a component effect that races the
// async conversations round-trip and silently drops the event.
const captureAiSupportTicket = (ticketId: string | number): void => {
if (!ai_conversation_id) {
@@ -853,337 +584,80 @@ export const supportLogic = kea<supportLogicType>([
})
}
- // 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())) {
- // Measure the full outgoing payload (message plus any appended exception) so the
- // guard matches what the widget endpoint actually receives and rejects
- const outgoingMessage = appendExceptionToMessage(message, exception_event)
- if (warnIfMessageTooLong(outgoingMessage)) {
- return
- }
- try {
- const response = await posthog.conversations!.sendMessage(
- outgoingMessage,
- { 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)
- captureAiSupportTicket(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)
- posthog.capture('support ticket send failed', {
- channel: 'conversations',
- error: e instanceof Error ? e.message : String(e),
- kind,
- target_area,
- message_length: message?.length,
- current_url_length: window.location.href.length,
- })
- lemonToast.error("Oops, the message couldn't be sent. Please try again in a moment.", {
- button: EMAIL_SUPPORT_BUTTON,
- })
+ // Conversations is the only channel, so every failure has to be reported rather than
+ // rerouted. `reason` splits "the widget never loaded" (usually permanent for that browser)
+ // from "the send failed" (usually transient), because they need different advice and the
+ // volume of each tells us whether the email fallback is carrying real traffic.
+ const sendFailed = (reason: SupportSendFailureReason, error?: unknown): void => {
+ captureSupportTicketFailed({ surface: 'support_form', reason, message, error, kind })
+ if (reason === 'widget_unavailable') {
+ warnSupportWidgetUnavailable()
return
}
+ lemonToast.error("Oops, the message couldn't be sent. Please try again in a moment.", {
+ button: EMAIL_SUPPORT_BUTTON,
+ })
}
- // 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.conversationsFlagEnabled
- const zendesk_ticket_uuid = uuid()
- const subject =
- SUPPORT_KIND_TO_SUBJECT[kind ?? 'support'] +
- ': ' +
- (target_area
- ? (getLabelBasedOnTargetArea(target_area) ?? `${target_area} (feature preview)`)
- : 'General') +
- ' (' +
- zendesk_ticket_uuid +
- ')'
- const cloudRegion = preflightLogic.values.preflight?.region
-
- const billing = billingLogic.values.billing
- const billingPlan = billingLogic.values.billingPlan
-
- let planLevelTag = 'plan_free'
-
- const knownEnterpriseOrgIds = ['018713f3-8d56-0000-32fa-75ce97e6662f']
- const isKnownEnterpriseOrg = knownEnterpriseOrgIds.includes(userLogic?.values?.user?.organization?.id || '')
-
- const isNewOrganization = values.isCurrentOrganizationNew
-
- const hasBoostTrial = billing?.trial?.status === 'active' && billing.trial?.target === 'boost'
- const hasScaleTrial = billing?.trial?.status === 'active' && billing.trial?.target === 'scale'
- const hasEnterpriseTrial = billing?.trial?.status === 'active' && billing.trial?.target === 'enterprise'
-
- if (isKnownEnterpriseOrg || hasEnterpriseTrial || billingPlan === BillingPlan.Enterprise) {
- planLevelTag = 'plan_enterprise'
- } else if (isNewOrganization) {
- planLevelTag = 'plan_onboarding'
- } else if (hasScaleTrial) {
- planLevelTag = 'plan_scale'
- } else if (hasBoostTrial) {
- planLevelTag = 'plan_boost'
- } else if (billingPlan) {
- switch (billingPlan) {
- case BillingPlan.Scale:
- planLevelTag = 'plan_scale'
- break
- case BillingPlan.Boost:
- planLevelTag = 'plan_boost'
- break
- case BillingPlan.Teams:
- planLevelTag = 'plan_teams_legacy'
- break
- case BillingPlan.Paid:
- const projectedAmount = parseFloat(billing?.projected_total_amount_usd_with_limit || '0')
- const shouldMarkAsFree = projectedAmount === 0
-
- planLevelTag = shouldMarkAsFree ? 'plan_pay-as-you-go_free' : 'plan_pay-as-you-go_paying'
- break
- case BillingPlan.Free:
- planLevelTag = 'plan_free'
- break
- }
- }
-
- const startupProgramLabel = billing?.startup_program_label
- if (startupProgramLabel === StartupProgramLabel.YC) {
- planLevelTag = 'plan_yc'
- } else if (startupProgramLabel === StartupProgramLabel.Startup) {
- planLevelTag = 'plan_startup'
+ if (!(await waitForConversations())) {
+ sendFailed('widget_unavailable')
+ return
}
- const { accountOwner } = billingLogic.values
-
- const ownerName = accountOwner?.name?.toLowerCase().replace(/[^a-z0-9]/g, '_') || 'unassigned'
- const accountOwnerTag = `owner_${ownerName}`
-
- const payload = {
- request: {
- requester: { name: name, email: email },
- subject: subject,
- tags: [
- planLevelTag,
- accountOwnerTag,
- ...(conversationsFallback ? ['conversations_fallback'] : []),
- ...(tags || []),
- ],
- custom_fields: [
- {
- id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.severity,
- value: severity_level,
- },
- {
- id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.distinct_id,
- value: posthog.get_distinct_id(),
- },
- {
- id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.target_area,
- value: target_area ?? '',
- },
- {
- id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.organization_id,
- value: userLogic?.values?.user?.organization?.id ?? '',
- },
- {
- id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.support_type,
- value: values.hasAvailableFeature(AvailableFeature.PRIORITY_SUPPORT)
- ? 'priority_support'
- : values.hasAvailableFeature(AvailableFeature.EMAIL_SUPPORT)
- ? 'email_support'
- : 'free_support',
- },
- {
- id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.account_owner,
- value: accountOwner?.name || 'unassigned',
- },
- {
- id: SUPPORT_TICKET_CUSTOM_FIELD_IDENTIFIERS.exception_event,
- value: exception_event ? parseExceptionEvent(exception_event) : '',
- },
- ],
- comment: {
- body:
- message +
- `\n\n-----` +
- `\nKind: ${kind ?? 'support'}` +
- `\nTarget area: ${target_area ?? 'General'}` +
- `\nReport event: http://go/ticketByUUID/${zendesk_ticket_uuid}` +
- getSessionReplayLink() +
- getErrorTrackingLink(exception_event?.uuid) +
- getCurrentLocationLink() +
- getDjangoAdminLink(
- userLogic.values.user,
- cloudRegion,
- organizationLogic.values.currentOrganization,
- teamLogic.values.currentTeam
- ) +
- (target_area === 'billing' || target_area === 'login' || target_area === 'onboarding'
- ? getBillingAdminLink(organizationLogic.values.currentOrganization)
- : '') +
- (cloudRegion && teamLogic.values.currentTeam
- ? '\nPersons-on-events mode for project: ' +
- (teamLogic.values.currentTeam.modifiers?.personsOnEventsMode ??
- teamLogic.values.currentTeam.default_modifiers?.personsOnEventsMode ??
- 'unknown')
- : ''),
- },
- },
+ // Measure the full outgoing payload (message plus any appended exception) so the guard
+ // matches what the widget endpoint actually receives and rejects
+ const outgoingMessage = appendExceptionToMessage(message, exception_event)
+ if (warnIfMessageTooLong(outgoingMessage)) {
+ captureSupportTicketFailed({
+ surface: 'support_form',
+ reason: 'message_too_long',
+ message: outgoingMessage,
+ kind,
+ })
+ return
}
-
try {
- const zendeskRequestBody = JSON.stringify(payload, undefined, 4)
-
- // First attempt with standard fetch (unchanged from original)
- const response = await fetch('https://posthoghelp.zendesk.com/api/v2/requests.json', {
- method: 'POST',
- body: zendeskRequestBody,
- headers: { 'Content-Type': 'application/json' },
- })
-
- // If the fetch request fails, try the Beacon API as a fallback
- if (!response.ok) {
- console.warn('Fetch attempt to submit support ticket failed, trying Beacon API as fallback')
-
- // Detect Firefox
- const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1
-
- // Try Beacon API
- const beaconSuccess = navigator.sendBeacon(
- 'https://posthoghelp.zendesk.com/api/v2/requests.json',
- zendeskRequestBody
- )
-
- if (beaconSuccess) {
- // Track success
- const properties = {
- zendesk_ticket_uuid,
- kind,
- target_area,
- message,
- submission_method: 'beacon',
- browser: isFirefox ? 'firefox' : 'other',
- }
- posthog.capture('support_ticket', properties)
- 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 success
- actions.closeSupportForm()
- actions.resetSendSupportRequest()
- return
- }
-
- // If both fetch and beacon fail, show the original error message
- const error = new Error(`There was an error creating the support ticket with zendesk.`)
- const extra: Record<string, any> = { zendeskBody: zendeskRequestBody }
- Object.entries(payload).forEach(([key, value]) => {
- extra[`payload_${key}`] = value
- })
- const body = await response.text()
- const contexts = {
- response: {
- status_code: response.status,
- data: body,
- body_size: body?.length,
- },
- }
- posthog.captureException(error, {
- ...extra,
- ...contexts,
- })
- posthog.capture('support ticket send failed', {
- channel: 'zendesk',
- error: error.message,
- status_code: response.status,
- kind,
- target_area,
- message_length: message?.length,
- current_url_length: window.location.href.length,
- })
- lemonToast.error(
- `Oops, the message couldn't be sent. Please change your browser's privacy level to the standard or default level, then try again. (E.g. In Firefox: Settings > Privacy & Security > Standard)`,
- { button: EMAIL_SUPPORT_BUTTON }
- )
- // Don't close the form or reset the data so user can try again
+ const response = await posthog.conversations!.sendMessage(
+ outgoingMessage,
+ { name: name || undefined, email: email || undefined },
+ true // every form submission starts a new ticket
+ )
+ if (!response) {
+ // The extension declined to send (e.g. it became unavailable between the wait
+ // above and this call) — nothing left the browser
+ sendFailed('widget_declined')
return
}
-
- const json = await response.json()
-
- const zendesk_ticket_id = json.request.id
- const zendesk_ticket_link = `https://posthoghelp.zendesk.com/agent/tickets/${zendesk_ticket_id}`
- const properties = {
- zendesk_ticket_uuid,
- kind,
- target_area,
- message,
- zendesk_ticket_id,
- zendesk_ticket_link,
- }
- posthog.capture('support_ticket', properties)
- lemonToast.success("Got the message! If we have follow-up information for you, we'll reply via email.")
-
- actions.ensureZendeskOrganization()
- actions.setLastSubmittedTicketId(zendesk_ticket_id)
- captureAiSupportTicket(zendesk_ticket_id)
-
- // Only close and reset the form on success
+ // 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)
+ captureAiSupportTicket(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()
} catch (e) {
+ // The request may have reached the server even though the response failed, so don't
+ // retry here — that could file the ticket twice
posthog.captureException(e)
- posthog.capture('support ticket send failed', {
- channel: 'zendesk',
- error: e instanceof Error ? e.message : String(e),
- kind,
- target_area,
- message_length: message?.length,
- current_url_length: window.location.href.length,
- })
-
- // More helpful error message
- // Use the same error message regardless of browser
- lemonToast.error(
- `Oops, the message couldn't be sent. Please change your browser's privacy level to the standard or default level, then try again. (E.g. In Firefox: Settings > Privacy & Security > Standard)`,
- { button: EMAIL_SUPPORT_BUTTON }
- )
- // Don't close the form or reset the data so user can try again
+ sendFailed('send_failed', e)
}
},
@@ -1202,28 +676,5 @@ export const supportLogic = kea<supportLogicType>([
actions.updateUrlParams()
}
},
-
- ensureZendeskOrganization: async () => {
- try {
- const currentOrganization = organizationLogic.values.currentOrganization
-
- if (!currentOrganization?.id || !currentOrganization?.name) {
- return
- }
-
- await api.create('/api/support/ensure-zendesk-organization', {
- organization_id: currentOrganization.id,
- organization_name: currentOrganization.name,
- })
- } catch (error) {
- posthog.captureException(error, {
- context: 'zendesk_organization_creation',
- organization_id: organizationLogic.values.currentOrganization?.id,
- organization_name: organizationLogic.values.currentOrganization?.name,
- error_message: error instanceof Error ? error.message : String(error),
- error_status: error && typeof error === 'object' && 'status' in error ? error.status : undefined,
- })
- }
- },
})),
])
diff --git a/frontend/src/lib/components/Support/supportRouterLogic.ts b/frontend/src/lib/components/Support/supportRouterLogic.ts
index 5c2b9405bf2b..fc7c20c038e9 100644
--- a/frontend/src/lib/components/Support/supportRouterLogic.ts
+++ b/frontend/src/lib/components/Support/supportRouterLogic.ts
@@ -6,13 +6,7 @@ import { sceneLogic } from 'scenes/sceneLogic'
import { SidePanelTab } from '~/types'
-import {
- getLabelBasedOnTargetArea,
- SEVERITY_LEVEL_TO_NAME,
- SUPPORT_KIND_TO_SUBJECT,
- supportLogic,
- TARGET_AREA_TO_NAME,
-} from './supportLogic'
+import { SUPPORT_KIND_TO_SUBJECT, supportLogic } from './supportLogic'
// Mirrors navigationLogic's `mode === 'full'` (the condition that mounts <SidePanel />), derived from
// sources supportLogic can't import without a billingLogic init cycle. Keep here, not in supportLogic.
@@ -43,13 +37,14 @@ export const supportRouterLogic = kea<supportRouterLogicType>([
const [panel, ...panelOptions] = (hashParams['panel'] ?? '').split(':')
if (panel === SidePanelTab.Support) {
- const [kind, area, severity, isEmailFormOpen] = panelOptions
+ // `kind` is the only routable field left. Links written before the triage fields were
+ // removed carry `kind:area:severity:isEmailFormOpen`, so read the flag by value rather
+ // than by position — positionally, an old link's area would land in its slot.
+ const [kind] = panelOptions
supportLogic.actions.openSupportForm({
kind: Object.keys(SUPPORT_KIND_TO_SUBJECT).includes(kind) ? kind : null,
- target_area: getLabelBasedOnTargetArea(area) ? area : null,
- severity_level: Object.keys(SEVERITY_LEVEL_TO_NAME).includes(severity) ? severity : null,
- isEmailFormOpen: isEmailFormOpen ?? 'false',
+ isEmailFormOpen: panelOptions.includes('true') ? 'true' : 'false',
target,
})
return
@@ -57,12 +52,10 @@ export const supportRouterLogic = kea<supportRouterLogicType>([
// Legacy supportModal param
if ('supportModal' in hashParams) {
- const [kind, area, severity] = (hashParams['supportModal'] || '').split(':')
+ const [kind] = (hashParams['supportModal'] || '').split(':')
supportLogic.actions.openSupportForm({
kind: Object.keys(SUPPORT_KIND_TO_SUBJECT).includes(kind) ? kind : null,
- target_area: Object.keys(TARGET_AREA_TO_NAME).includes(area) ? area : null,
- severity_level: Object.keys(SEVERITY_LEVEL_TO_NAME).includes(severity) ? severity : null,
target,
})
}
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 0e31c5799f2b..0e94d95bbfb9 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -445,7 +445,6 @@ export const FEATURE_FLAGS = {
PRODUCT_SUPPORT_CREATE_TICKET: 'product-support-create-ticket', // owner: @veryayskiy #team-conversations
PRODUCT_SUPPORT_GITHUB_CHANNEL: 'product-support-github-channel', // owner: @veryayskiy #team-conversations
PRODUCT_SUPPORT_IMPORT_TICKETS: 'product-support-import-tickets', // owner: @veryayskiy #team-conversations
- PRODUCT_SUPPORT_SIDE_PANEL: 'product-support-side-panel', // owner: @veryayskiy #team-conversations
PRODUCT_SUPPORT_SLACK_NOTIFY_ON_MEMBERS: 'product-support-slack-notify-on-members', // owner: @veryayskiy #team-conversations
PRODUCT_SUPPORT_TEAMS_ENABLED: 'product-support-teams-enabled', // owner: @veryayskiy #team-conversations
PRODUCT_TOURS: 'product-tours-2025', // owner: @adboio #team-surveys
diff --git a/frontend/src/scenes/authentication/invite-signup/variants/legacy/LegacyInviteSignup.tsx b/frontend/src/scenes/authentication/invite-signup/variants/legacy/LegacyInviteSignup.tsx
index ba0cc2aa38b8..5bc037fd01cc 100644
--- a/frontend/src/scenes/authentication/invite-signup/variants/legacy/LegacyInviteSignup.tsx
+++ b/frontend/src/scenes/authentication/invite-signup/variants/legacy/LegacyInviteSignup.tsx
@@ -249,7 +249,6 @@ function UnauthenticatedAcceptInvite({ invite }: { invite: PrevalidatedInvite })
e.preventDefault()
openSupportForm({
kind: 'support',
- target_area: 'login',
email: invite.target_email,
})
}}
diff --git a/frontend/src/scenes/authentication/invite-signup/variants/paper-desk/PaperDeskInviteSignup.tsx b/frontend/src/scenes/authentication/invite-signup/variants/paper-desk/PaperDeskInviteSignup.tsx
index 64c172fe80e5..bcfe8d86081a 100644
--- a/frontend/src/scenes/authentication/invite-signup/variants/paper-desk/PaperDeskInviteSignup.tsx
+++ b/frontend/src/scenes/authentication/invite-signup/variants/paper-desk/PaperDeskInviteSignup.tsx
@@ -166,7 +166,7 @@ function InviteNewUser({ invite }: { invite: PrevalidatedInvite }): JSX.Element
{signupManualErrors.generic.detail || 'Could not complete your signup.'}{' '}
<Link
data-attr="invite-signup-error-contact-support"
- onClick={() => openSupportForm({ kind: 'support', target_area: 'login' })}
+ onClick={() => openSupportForm({ kind: 'support' })}
className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"
>
Need help?
@@ -463,12 +463,7 @@ function InviteInvalid(): JSX.Element {
Try again
</LemonButton>
) : null}
- <LemonButton
- size="large"
- center
- fullWidth
- onClick={() => openSupportForm({ kind: 'bug', target_area: 'login' })}
- >
+ <LemonButton size="large" center fullWidth onClick={() => openSupportForm({ kind: 'bug' })}>
Contact support
</LemonButton>
</div>
diff --git a/frontend/src/scenes/authentication/login-2fa/Login2FA.tsx b/frontend/src/scenes/authentication/login-2fa/Login2FA.tsx
index e20c3933a759..c16ba4993aa0 100644
--- a/frontend/src/scenes/authentication/login-2fa/Login2FA.tsx
+++ b/frontend/src/scenes/authentication/login-2fa/Login2FA.tsx
@@ -36,7 +36,6 @@ export function Login2FA(): JSX.Element {
e.preventDefault()
openSupportForm({
kind: 'support',
- target_area: 'login',
})
}}
>
diff --git a/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx b/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx
index 0a16531ebb3a..b46c4490fd1c 100644
--- a/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx
+++ b/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx
@@ -125,7 +125,6 @@ function Login(): JSX.Element {
e.preventDefault()
openSupportForm({
kind: 'support',
- target_area: 'login',
email: login.email,
})
}}
diff --git a/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx b/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx
index 55f018b32f8d..12116df3175d 100644
--- a/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx
+++ b/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx
@@ -108,7 +108,6 @@ function Login(): JSX.Element {
e.preventDefault()
openSupportForm({
kind: 'support',
- target_area: 'login',
email: login.email,
})
}}
diff --git a/frontend/src/scenes/authentication/shared/SupportModalButton.tsx b/frontend/src/scenes/authentication/shared/SupportModalButton.tsx
index 71f874f774b5..ff412f9adc53 100644
--- a/frontend/src/scenes/authentication/shared/SupportModalButton.tsx
+++ b/frontend/src/scenes/authentication/shared/SupportModalButton.tsx
@@ -3,14 +3,14 @@ import { useActions, useValues } from 'kea'
import { IconBug, IconQuestion } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
-import { SupportTicketKind, SupportTicketTargetArea, supportLogic } from 'lib/components/Support/supportLogic'
+import { SupportTicketKind, supportLogic } from 'lib/components/Support/supportLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
interface SupportModalButtonProps {
name?: string
email?: string
kind?: SupportTicketKind
- target_area?: SupportTicketTargetArea
+ billingIssue?: boolean
label?: string
}
@@ -18,7 +18,7 @@ export function SupportModalButton({
name,
email,
kind = 'bug',
- target_area = 'login',
+ billingIssue = false,
label = 'Report an issue',
}: SupportModalButtonProps): JSX.Element | null {
const { openSupportForm } = useActions(supportLogic)
@@ -33,7 +33,7 @@ export function SupportModalButton({
name,
email,
kind,
- target_area,
+ billing_issue: billingIssue,
})
}}
icon={kind === 'bug' ? <IconBug /> : <IconQuestion />}
diff --git a/frontend/src/scenes/authentication/signup/signupForm/SignupForm.tsx b/frontend/src/scenes/authentication/signup/signupForm/SignupForm.tsx
index 2999effd87af..a3ec54f342f2 100644
--- a/frontend/src/scenes/authentication/signup/signupForm/SignupForm.tsx
+++ b/frontend/src/scenes/authentication/signup/signupForm/SignupForm.tsx
@@ -43,7 +43,7 @@ export function SignupForm(): JSX.Element | null {
data-attr="login-error-contact-support"
onClick={(e) => {
e.preventDefault()
- openSupportForm({ kind: 'support', target_area: 'login', email: signupPanelEmail.email })
+ openSupportForm({ kind: 'support', email: signupPanelEmail.email })
}}
>
Contact us
diff --git a/frontend/src/scenes/authentication/signup/signupForm/TurnstileChallenge.tsx b/frontend/src/scenes/authentication/signup/signupForm/TurnstileChallenge.tsx
index 7d002be93d6e..b81f9af123ad 100644
--- a/frontend/src/scenes/authentication/signup/signupForm/TurnstileChallenge.tsx
+++ b/frontend/src/scenes/authentication/signup/signupForm/TurnstileChallenge.tsx
@@ -64,7 +64,6 @@ export function TurnstileChallenge({ siteKey, onSuccess, tokenReceived, email }:
e.preventDefault()
openSupportForm({
kind: 'support',
- target_area: 'login',
email,
})
}}
diff --git a/frontend/src/scenes/authentication/signup/variants/paper-desk/PaperDeskSignup.tsx b/frontend/src/scenes/authentication/signup/variants/paper-desk/PaperDeskSignup.tsx
index 947bf42c6ac5..2d6e9b3bacc4 100644
--- a/frontend/src/scenes/authentication/signup/variants/paper-desk/PaperDeskSignup.tsx
+++ b/frontend/src/scenes/authentication/signup/variants/paper-desk/PaperDeskSignup.tsx
@@ -383,7 +383,6 @@ function SignupProfilePanel(): JSX.Element {
e.preventDefault()
openSupportForm({
kind: 'support',
- target_area: 'login',
email: signupPanelEmail.email,
})
}}
diff --git a/frontend/src/scenes/authentication/verify-email/variants/legacy/LegacyVerifyEmail.tsx b/frontend/src/scenes/authentication/verify-email/variants/legacy/LegacyVerifyEmail.tsx
index b76d29e4dfcf..5a589cdbe955 100644
--- a/frontend/src/scenes/authentication/verify-email/variants/legacy/LegacyVerifyEmail.tsx
+++ b/frontend/src/scenes/authentication/verify-email/variants/legacy/LegacyVerifyEmail.tsx
@@ -34,7 +34,7 @@ const SupportButtons = ({ disabledReason }: SupportButtonsProps): JSX.Element =>
type="primary"
disabledReason={disabledReason}
onClick={() => {
- openSupportForm({ kind: 'bug', target_area: 'login' })
+ openSupportForm({ kind: 'bug' })
}}
>
Contact support
diff --git a/frontend/src/scenes/authentication/verify-email/variants/paper-desk/PaperDeskVerifyEmail.tsx b/frontend/src/scenes/authentication/verify-email/variants/paper-desk/PaperDeskVerifyEmail.tsx
index a8b05608c75a..64fb8d06f520 100644
--- a/frontend/src/scenes/authentication/verify-email/variants/paper-desk/PaperDeskVerifyEmail.tsx
+++ b/frontend/src/scenes/authentication/verify-email/variants/paper-desk/PaperDeskVerifyEmail.tsx
@@ -93,7 +93,6 @@ function NotSeeingIt(): JSX.Element {
onClick={() =>
openSupportForm({
kind: 'bug',
- target_area: 'login',
})
}
>
@@ -180,7 +179,6 @@ function VerifyEmail(): JSX.Element {
onClick={() =>
openSupportForm({
kind: 'bug',
- target_area: 'login',
})
}
>
diff --git a/frontend/src/scenes/billing/Billing.tsx b/frontend/src/scenes/billing/Billing.tsx
index 601d5c2d18da..5278d8f4fb22 100644
--- a/frontend/src/scenes/billing/Billing.tsx
+++ b/frontend/src/scenes/billing/Billing.tsx
@@ -110,7 +110,7 @@ export function Billing(): JSX.Element {
'There was an issue retrieving your current billing information. If this message persists, please '
}
{preflight?.cloud ? (
- <Link onClick={() => openSupportForm({ kind: 'bug', target_area: 'billing' })}>
+ <Link onClick={() => openSupportForm({ kind: 'bug', billing_issue: true })}>
submit a bug report
</Link>
) : (
diff --git a/frontend/src/scenes/billing/BillingEarlyAccessBanner.tsx b/frontend/src/scenes/billing/BillingEarlyAccessBanner.tsx
index 4800cb5d7004..bc6d07b0c26e 100644
--- a/frontend/src/scenes/billing/BillingEarlyAccessBanner.tsx
+++ b/frontend/src/scenes/billing/BillingEarlyAccessBanner.tsx
@@ -29,7 +29,7 @@ export function BillingEarlyAccessBanner(): JSX.Element {
onClick={() =>
openSupportForm({
kind: 'support',
- target_area: 'billing',
+ billing_issue: true,
isEmailFormOpen: true,
})
}
diff --git a/frontend/src/scenes/billing/ConfirmDowngradeModal.tsx b/frontend/src/scenes/billing/ConfirmDowngradeModal.tsx
index ec6aaea37db3..79b9095432d1 100644
--- a/frontend/src/scenes/billing/ConfirmDowngradeModal.tsx
+++ b/frontend/src/scenes/billing/ConfirmDowngradeModal.tsx
@@ -116,7 +116,7 @@ export function ConfirmDowngradeModal({ product }: { product: BillingProductV2Ad
<Link
onClick={() => {
hideConfirmDowngradeModal()
- openSupportForm({ target_area: 'billing' })
+ openSupportForm({ billing_issue: true })
}}
>
Request a refund instead.
diff --git a/frontend/src/scenes/billing/PurchaseCreditsModal.tsx b/frontend/src/scenes/billing/PurchaseCreditsModal.tsx
index dc3ab8357f70..3793e6a42acd 100644
--- a/frontend/src/scenes/billing/PurchaseCreditsModal.tsx
+++ b/frontend/src/scenes/billing/PurchaseCreditsModal.tsx
@@ -236,7 +236,7 @@ export const PurchaseCreditsModal = (): JSX.Element | null => {
<Link
onClick={() => {
showPurchaseCreditsModal(false)
- openSupportForm({ kind: 'support', target_area: 'billing' })
+ openSupportForm({ kind: 'support', billing_issue: true })
}}
>
Get support
diff --git a/frontend/src/scenes/billing/UnsubscribeCard.tsx b/frontend/src/scenes/billing/UnsubscribeCard.tsx
index 21e95bb3b938..aec2e54d8bfe 100644
--- a/frontend/src/scenes/billing/UnsubscribeCard.tsx
+++ b/frontend/src/scenes/billing/UnsubscribeCard.tsx
@@ -30,7 +30,7 @@ export const UnsubscribeCard = ({ product }: { product: BillingProductV2Type }):
reduce your bill
</Link>{' '}
or{' '}
- <Link to="" onClick={() => openSupportForm({ target_area: 'billing', isEmailFormOpen: true })}>
+ <Link to="" onClick={() => openSupportForm({ billing_issue: true, isEmailFormOpen: true })}>
chat with support.
</Link>{' '}
Check out more about our pricing on our{' '}
diff --git a/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx b/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx
index 72fea009233a..f03c3ef838da 100644
--- a/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx
+++ b/frontend/src/scenes/billing/UnsubscribeSurveyModal.tsx
@@ -258,7 +258,7 @@ export const UnsubscribeSurveyModal = ({
target="_blank"
onClick={() => {
reportSurveyDismissed(surveyID)
- openSupportForm({ target_area: 'billing', isEmailFormOpen: true })
+ openSupportForm({ billing_issue: true, isEmailFormOpen: true })
}}
>
chat with support
diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricErrorState.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricErrorState.tsx
index 6dbf9ead2e7c..628022c7d311 100644
--- a/frontend/src/scenes/experiments/MetricsView/new/MetricErrorState.tsx
+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricErrorState.tsx
@@ -90,7 +90,6 @@ export const MetricErrorState = ({
onClick={() =>
openSupportForm({
kind: 'bug',
- target_area: 'experiments',
})
}
>
diff --git a/frontend/src/scenes/health/HealthScene.tsx b/frontend/src/scenes/health/HealthScene.tsx
index 111cfb4d568e..2f5fbc32250c 100644
--- a/frontend/src/scenes/health/HealthScene.tsx
+++ b/frontend/src/scenes/health/HealthScene.tsx
@@ -82,7 +82,7 @@ export const HealthScene = (): JSX.Element => {
icon={<IconSupport />}
type="secondary"
size="small"
- onClick={() => openSupportForm({ kind: 'support', target_area: 'health_overview' })}
+ onClick={() => openSupportForm({ kind: 'support' })}
>
Get help from our team
</LemonButton>
diff --git a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
index 80e14064588d..377fbcd209cb 100644
--- a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
@@ -546,7 +546,7 @@ export function InsightTimeoutState({ queryId }: { queryId?: string | null }): J
you're still having issues,{' '}
<Link
onClick={() => {
- openSupportForm({ kind: 'bug', target_area: 'analytics' })
+ openSupportForm({ kind: 'bug' })
}}
>
let us know
@@ -712,7 +712,7 @@ export function InsightErrorState({
<Link
data-attr="insight-error-bug-report"
onClick={() => {
- openSupportForm({ kind: 'bug', target_area: 'analytics' })
+ openSupportForm({ kind: 'bug' })
}}
>
If this persists, submit a bug report.
diff --git a/frontend/src/scenes/max/FeedbackPrompt.tsx b/frontend/src/scenes/max/FeedbackPrompt.tsx
index 02e10394b898..9fec71bd985a 100644
--- a/frontend/src/scenes/max/FeedbackPrompt.tsx
+++ b/frontend/src/scenes/max/FeedbackPrompt.tsx
@@ -34,7 +34,7 @@ export function FeedbackPrompt({ conversationId, traceId }: FeedbackPromptProps)
const submitInFlightRef = useRef(false)
- const { sendSupportRequest, lastSubmittedTicketId, conversationsFlagEnabled } = useValues(supportLogic)
+ const { sendSupportRequest, lastSubmittedTicketId } = useValues(supportLogic)
const { resetSendSupportRequest } = useActions(supportLogic)
const { user } = useValues(userLogic)
@@ -102,8 +102,6 @@ export function FeedbackPrompt({ conversationId, traceId }: FeedbackPromptProps)
name: '',
email: '',
kind: 'feedback',
- target_area: 'posthog-ai',
- severity_level: 'low',
message: feedbackText,
ai_conversation_id: conversationId,
ai_trace_id: traceId,
@@ -124,16 +122,6 @@ export function FeedbackPrompt({ conversationId, traceId }: FeedbackPromptProps)
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
setTicketMessageText(sendSupportRequest.message)
const ticketIdBefore = supportLogic.values.lastSubmittedTicketId
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index 7ffc73fd1cf0..5c437cf8632e 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -328,7 +328,6 @@ function LegacyThread({ showTrailers }: { showTrailers: boolean }): JSX.Element
conversationId={conversationId}
traceId={traceId}
summary={ticketSummaryData.summary}
- targetArea={ticketSummaryData.targetArea}
/>
))}
</React.Fragment>
diff --git a/frontend/src/scenes/max/TicketPrompt.tsx b/frontend/src/scenes/max/TicketPrompt.tsx
index 6d9fd787a0b9..cbb1b2720d4b 100644
--- a/frontend/src/scenes/max/TicketPrompt.tsx
+++ b/frontend/src/scenes/max/TicketPrompt.tsx
@@ -4,7 +4,7 @@ import { useRef, useState } from 'react'
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 { supportLogic } from 'lib/components/Support/supportLogic'
import { userLogic } from 'scenes/userLogic'
import { maxThreadLogic } from './maxThreadLogic'
@@ -17,8 +17,6 @@ interface TicketPromptProps {
summary?: string
/** If provided, pre-populate the input field with this text */
initialText?: string
- /** Target area inferred from the conversation; falls back to product analytics when absent */
- targetArea?: SupportTicketTargetArea | null
}
/**
@@ -27,19 +25,13 @@ interface TicketPromptProps {
* 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({
- conversationId,
- traceId,
- summary,
- initialText,
- targetArea,
-}: TicketPromptProps): JSX.Element {
+export function TicketPrompt({ conversationId, traceId, summary, initialText }: 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, conversationsFlagEnabled, supportResponseTime } = useValues(supportLogic)
+ const { sendSupportRequest, supportResponseTime } = useValues(supportLogic)
const { resetSendSupportRequest, closeSupportForm } = useActions(supportLogic)
const { appendMessageToConversation } = useActions(maxThreadLogic)
const { user } = useValues(userLogic)
@@ -66,10 +58,7 @@ export function TicketPrompt({
name: '',
email: '',
kind: 'bug',
- target_area: targetArea ?? 'analytics',
- severity_level: 'low',
message: summary ? '' : issueText,
- tags: ['raised_from_posthog_ai_chat'],
ai_conversation_id: conversationId,
ai_trace_id: traceId,
})
@@ -87,16 +76,6 @@ export function TicketPrompt({
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
diff --git a/frontend/src/scenes/max/ticketUtils.test.ts b/frontend/src/scenes/max/ticketUtils.test.ts
index eb416961a439..61d16f584b16 100644
--- a/frontend/src/scenes/max/ticketUtils.test.ts
+++ b/frontend/src/scenes/max/ticketUtils.test.ts
@@ -5,14 +5,12 @@ import {
formatTicketConfirmationMessage,
getTicketSummaryData,
isTicketConfirmationMessage,
- parseTicketTargetArea,
} from './ticketUtils'
const human = (content: string): ThreadMessage => ({ type: 'human', content }) as unknown as ThreadMessage
const ai = (content: string): ThreadMessage => ({ type: 'ai', content }) as unknown as ThreadMessage
const SUMMARY = 'PostHog AI Support Ticket Summary:\n\nIssue: Session recordings are not appearing in the dashboard.'
-const SUMMARY_WITH_TOPIC = `${SUMMARY}\n\n**Topic:** session_replay`
const DENIAL =
'The `/ticket` command is available for customers on paid plans or active trials. You can upgrade your plan in the billing settings, or ask the community at https://posthog.com/questions for help. If your issue is about billing, you can always contact our support team through the in-app help panel.'
@@ -37,22 +35,7 @@ describe('ticketUtils', () => {
ai(SUMMARY),
]
- expect(getTicketSummaryData(thread, false)).toEqual({ summary: SUMMARY, messageIndex: 3, targetArea: null })
- })
-
- it('extracts the target area from the summary topic line', () => {
- const thread = [
- human('My recordings are missing'),
- ai('Let me check that...'),
- human('/ticket'),
- ai(SUMMARY_WITH_TOPIC),
- ]
-
- expect(getTicketSummaryData(thread, false)).toEqual({
- summary: SUMMARY_WITH_TOPIC,
- messageIndex: 3,
- targetArea: 'session_replay',
- })
+ expect(getTicketSummaryData(thread, false)).toEqual({ summary: SUMMARY, messageIndex: 3 })
})
})
@@ -116,29 +99,4 @@ describe('ticketUtils', () => {
)
})
})
-
- describe('parseTicketTargetArea', () => {
- it.each([
- ['bold topic line with valid area', 'Issue: foo\n\n**Topic:** data_warehouse', 'data_warehouse'],
- ['plain topic line with valid area', 'Issue: foo\n\nTopic: session_replay', 'session_replay'],
- ['case and whitespace variations', 'Issue: foo\n\ntopic: Data_Warehouse ', 'data_warehouse'],
- ['trailing period is stripped', 'Issue: foo\n\nTopic: session_replay.', 'session_replay'],
- [
- 'trailing parenthetical is ignored',
- 'Issue: foo\n\n**Topic:** data_warehouse (Stripe integration)',
- 'data_warehouse',
- ],
- [
- 'trailing comma and prose are ignored',
- 'Issue: foo\n\nTopic: feature_flags, most likely',
- 'feature_flags',
- ],
- ['unknown area is rejected', 'Issue: foo\n\nTopic: quantum_computing', null],
- ['unknown area with trailing prose is rejected', 'Issue: foo\n\nTopic: quantum_computing (maybe)', null],
- ['no topic line', 'Issue: foo\n\nStatus: bar', null],
- ['topic mentioned mid-sentence is ignored', 'Issue: the topic: billing came up in chat', null],
- ])('%s', (_name, content, expected) => {
- expect(parseTicketTargetArea(content)).toBe(expected)
- })
- })
})
diff --git a/frontend/src/scenes/max/ticketUtils.ts b/frontend/src/scenes/max/ticketUtils.ts
index 34dee4583ec7..cd26a59dd09f 100644
--- a/frontend/src/scenes/max/ticketUtils.ts
+++ b/frontend/src/scenes/max/ticketUtils.ts
@@ -1,12 +1,9 @@
-import { SupportTicketTargetArea, TARGET_AREA_OPTIONS } from 'lib/components/Support/supportLogic'
-
import { ThreadMessage } from './maxLogic'
export interface TicketSummaryData {
summary?: string
discarded?: boolean
messageIndex: number
- targetArea?: SupportTicketTargetArea | null
}
export interface TicketPromptData {
@@ -27,31 +24,6 @@ export function formatTicketConfirmationMessage(ticketId: string, responseTime:
return `${TICKET_CONFIRMATION_LEAD}.\nYour ticket ID is #${ticketId}.\n${closingLine}`
}
-/**
- * Parses the "Topic: <area>" line the /ticket summarizer appends, returning the
- * target area only if it matches a known support target area.
- */
-export function parseTicketTargetArea(content: string): SupportTicketTargetArea | null {
- for (const rawLine of content.split('\n')) {
- const line = rawLine.replace(/\*/g, '').trim()
- const match = line.match(/^topic:\s*(.+)$/i)
- if (match) {
- // Keys are single whitespace-free tokens, so take the first token and strip trailing
- // punctuation — the model sometimes appends a period or parenthetical
- const area = match[1]
- .trim()
- .split(/\s+/)[0]
- .replace(/[.,;:!?)\]]+$/, '')
- .toLowerCase()
- if (TARGET_AREA_OPTIONS.some((option) => option.value === area)) {
- return area as SupportTicketTargetArea
- }
- return null
- }
- }
- return null
-}
-
/**
* Extracts the text after "/ticket " from a message, if any.
*/
@@ -166,7 +138,6 @@ export function getTicketSummaryData(
return {
summary,
messageIndex: ticketCommandIndex + 1,
- targetArea: parseTicketTargetArea(responseMessage.content),
}
}
}
diff --git a/frontend/src/scenes/onboarding/legacy/OnboardingStep.tsx b/frontend/src/scenes/onboarding/legacy/OnboardingStep.tsx
index 78c57beff523..dd38b80814de 100644
--- a/frontend/src/scenes/onboarding/legacy/OnboardingStep.tsx
+++ b/frontend/src/scenes/onboarding/legacy/OnboardingStep.tsx
@@ -108,10 +108,7 @@ export const OnboardingStep = ({
{children}
<div className="mt-8 flex justify-end gap-x-2">
{showHelpButton && (
- <LemonButton
- type="secondary"
- onClick={() => openSupportForm({ kind: 'support', target_area: 'onboarding' })}
- >
+ <LemonButton type="secondary" onClick={() => openSupportForm({ kind: 'support' })}>
Need help?
</LemonButton>
)}
diff --git a/frontend/src/scenes/organization/Deactivated.tsx b/frontend/src/scenes/organization/Deactivated.tsx
index fd8273034162..27c43a94e300 100644
--- a/frontend/src/scenes/organization/Deactivated.tsx
+++ b/frontend/src/scenes/organization/Deactivated.tsx
@@ -24,7 +24,7 @@ export function OrganizationDeactivated(): JSX.Element {
<div className="flex flex-col gap-4 items-center text-center">
<HedgehogStop className="w-52 h-52" />
<h3>Your organization has been deactivated. {isNotActiveReason}</h3>
- <SupportModalButton kind="support" target_area="billing" label="Contact support" />
+ <SupportModalButton kind="support" billingIssue label="Contact support" />
</div>
</LemonCard>
</div>
diff --git a/frontend/src/scenes/organization/PendingDeletion.tsx b/frontend/src/scenes/organization/PendingDeletion.tsx
index db7e2f57f939..1da85dad2bfa 100644
--- a/frontend/src/scenes/organization/PendingDeletion.tsx
+++ b/frontend/src/scenes/organization/PendingDeletion.tsx
@@ -70,7 +70,7 @@ export function OrganizationPendingDeletion(): JSX.Element {
</LemonButton>
</Popover>
)}
- <SupportModalButton kind="support" target_area="login" label="Contact support" />
+ <SupportModalButton kind="support" label="Contact support" />
</div>
</LemonCard>
</div>
diff --git a/frontend/src/scenes/project/PendingDeletion.tsx b/frontend/src/scenes/project/PendingDeletion.tsx
index cd892b62e5a8..8e5b3498320a 100644
--- a/frontend/src/scenes/project/PendingDeletion.tsx
+++ b/frontend/src/scenes/project/PendingDeletion.tsx
@@ -80,7 +80,7 @@ export function ProjectPendingDeletion(): JSX.Element {
</Popover>
)}
</div>
- <SupportModalButton kind="support" target_area="login" label="Contact support" />
+ <SupportModalButton kind="support" label="Contact support" />
</div>
</LemonCard>
</div>
diff --git a/frontend/src/scenes/web-analytics/SessionAttributionExplorer/SessionAttributionExplorerScene.tsx b/frontend/src/scenes/web-analytics/SessionAttributionExplorer/SessionAttributionExplorerScene.tsx
index fbd43350313d..9be9205b10df 100644
--- a/frontend/src/scenes/web-analytics/SessionAttributionExplorer/SessionAttributionExplorerScene.tsx
+++ b/frontend/src/scenes/web-analytics/SessionAttributionExplorer/SessionAttributionExplorerScene.tsx
@@ -221,7 +221,6 @@ export function SessionAttributionExplorer(): JSX.Element {
openSupportForm({
kind: 'feedback',
isEmailFormOpen: true,
- target_area: 'web_analytics',
})
}
>
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index d397eee0c7ca..e6e86bcc5fc0 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -7630,11 +7630,11 @@ export interface FeaturePreviewGateConfig {
description: string
docsURL?: string
/**
- * Support ticket target area for the "Request access" action. Set this for betas that aren't
- * self-serve early-access features, so the gated state offers a way to request access instead
- * of dead-ending on the feature previews page.
+ * Offer a "Request access" support CTA. Set this for betas that aren't self-serve early-access
+ * features, so the gated state offers a way to request access instead of dead-ending on the
+ * feature previews page.
*/
- supportTargetArea?: string
+ offerRequestAccess?: boolean
}
export interface ProductManifest {
diff --git a/posthog/api/zendesk_orgcheck.py b/posthog/api/zendesk_orgcheck.py
deleted file mode 100644
index 64bf3e1ba9c9..000000000000
--- a/posthog/api/zendesk_orgcheck.py
+++ /dev/null
@@ -1,117 +0,0 @@
-import base64
-from typing import cast
-
-from django.conf import settings
-
-import requests
-import structlog
-from rest_framework.decorators import api_view, permission_classes
-from rest_framework.permissions import IsAuthenticated
-from rest_framework.request import Request
-from rest_framework.response import Response
-
-from posthog.models import User
-from posthog.utils import capture_exception
-
-logger = structlog.get_logger(__name__)
-
-
-def get_zendesk_auth_headers():
- email = settings.ZENDESK_ADMIN_EMAIL
- token = settings.ZENDESK_API_TOKEN
-
- if not email or not token:
- raise ValueError("ZENDESK_ADMIN_EMAIL and ZENDESK_API_TOKEN must be set")
-
- basic_token = base64.b64encode(f"{email}/token:{token}".encode("ascii")).decode("ascii")
- return {"Authorization": f"Basic {basic_token}"}
-
-
-@api_view(["POST"])
-@permission_classes([IsAuthenticated])
-def ensure_zendesk_organization(request: Request) -> Response:
- try:
- data = request.data
- org_id = data.get("organization_id")
- org_name = data.get("organization_name")
- user = cast(User, request.user)
-
- # Validate that the user can only submit for their own organization
- if user.current_organization_id and str(org_id) != str(user.current_organization_id):
- capture_exception(
- Exception("User attempted to create Zendesk organization for different organization"),
- {
- "user_org_id": user.current_organization_id,
- "requested_org_id": org_id,
- "user_email": user.email,
- },
- )
- return Response({"status": "success"})
-
- if not org_id or not org_name:
- capture_exception(
- Exception("Missing organization_id or organization_name in Zendesk org creation request"),
- {
- "org_id": org_id,
- "org_name": org_name,
- "user_email": user.email,
- },
- )
- return Response({"status": "success"})
-
- subdomain = settings.ZENDESK_SUBDOMAIN
- if not subdomain:
- capture_exception(
- Exception("ZENDESK_SUBDOMAIN not configured for Zendesk org creation"),
- {
- "org_id": org_id,
- "org_name": org_name,
- "user_email": user.email,
- },
- )
- return Response({"status": "success"})
-
- base_url = f"https://{subdomain}.zendesk.com/api/v2"
- auth_headers = get_zendesk_auth_headers()
-
- search_url = f"{base_url}/organizations/search.json"
- search_params = {"external_id": org_id}
-
- search_response = requests.get(search_url, headers=auth_headers, params=search_params, timeout=10)
-
- if search_response.status_code == 200:
- search_data = search_response.json()
- organizations = search_data.get("organizations", [])
- if organizations and len(organizations) > 0:
- return Response({"status": "success"})
-
- create_url = f"{base_url}/organizations.json"
- create_payload = {
- "organization": {
- "name": org_name,
- "external_id": org_id,
- "organization_fields": {"ph_external_id_org": org_id},
- }
- }
-
- requests.post(
- create_url, headers={**auth_headers, "Content-Type": "application/json"}, json=create_payload, timeout=10
- )
-
- return Response({"status": "success"})
-
- except Exception as e:
- capture_exception(
- e,
- {
- "org_id": org_id,
- "org_name": org_name,
- "user_email": user.email,
- },
- )
- logger.warning(
- "ZenDesk organization creation failed",
- error=str(e),
- org_id=org_id,
- )
- return Response({"status": "success"})
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index 2e796a4a6795..c9b63ed76aed 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -66,10 +66,6 @@ STAMPHOG_GITHUB_APP_SLUG = get_from_env("STAMPHOG_GITHUB_APP_SLUG", "")
# when a legitimate dependency host is missing — never a way to open the sandbox wide.
STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS = get_list(get_from_env("STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS", ""))
-ZENDESK_ADMIN_EMAIL = get_from_env("ZENDESK_ADMIN_EMAIL", "")
-ZENDESK_API_TOKEN = get_from_env("ZENDESK_API_TOKEN", "")
-ZENDESK_SUBDOMAIN = get_from_env("ZENDESK_SUBDOMAIN", "posthoghelp")
-
META_ADS_APP_CLIENT_ID = get_from_env("META_ADS_APP_CLIENT_ID", "")
META_ADS_APP_CLIENT_SECRET = get_from_env("META_ADS_APP_CLIENT_SECRET", "")
diff --git a/posthog/urls.py b/posthog/urls.py
index df7813a8cb7c..2c0b6f27ef88 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -39,7 +39,6 @@ from posthog.api.sdk_health import sdk_health
from posthog.api.two_factor_qrcode import CacheAwareQRGeneratorView
from posthog.api.utils import hostname_in_allowed_url_list
from posthog.api.web_experiment import web_experiments
-from posthog.api.zendesk_orgcheck import ensure_zendesk_organization
from posthog.constants import PERMITTED_FORUM_DOMAINS
from posthog.exceptions_capture import capture_exception
from posthog.models import User
@@ -509,7 +508,6 @@ urlpatterns = [
"api/projects/<int:parent_lookup_team_id>/property_access_controls/",
include("products.access_control.backend.presentation.urls"),
),
- opt_slash_path("api/support/ensure-zendesk-organization", csrf_exempt(ensure_zendesk_organization)),
path(
"api/streamlit_bridge/query/",
csrf_exempt(StreamlitBridgeView.as_view()),
diff --git a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts
index beeab554f624..8bf4ababf2bc 100644
--- a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts
+++ b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts
@@ -2,9 +2,10 @@ import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
import { CONVERSATIONS_MESSAGE_MAX_LENGTH, supportLogic } from 'lib/components/Support/supportLogic'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { billingLogic } from 'scenes/billing/billingLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { initKeaTests } from '~/test/init'
import { BillingType } from '~/types'
@@ -29,8 +30,6 @@ describe('sidepanelTicketsLogic', () => {
.fn()
.mockResolvedValue({ ticket_id: 't1', ticket_status: 'open', created_at: '2026-07-21T00:00:00Z' }),
}
- featureFlagLogic.mount()
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PRODUCT_SUPPORT_SIDE_PANEL]: true })
supportLogic.mount()
billingLogic.mount()
// Tickets can be created unless a test drops the plan; set it up front, since the async
@@ -43,10 +42,28 @@ describe('sidepanelTicketsLogic', () => {
delete (posthog as any).conversations
})
+ // We don't support self-hosted, and the conversations extension is cloud-only — but this logic
+ // mounts there anyway, because the tickets scene declares it in its SceneExport. Left ungated it
+ // retries a widget that never arrives and then tells a self-hosted user to email us, contradicting
+ // the community-forum message the scene itself renders.
+ it('does not touch the conversations widget on self-hosted', async () => {
+ preflightLogic.mount()
+ preflightLogic.actions.loadPreflightSuccess({ cloud: false, is_debug: false } as any)
+ ;(posthog.capture as jest.Mock).mockClear()
+
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect((posthog as any).conversations.getTickets).not.toHaveBeenCalled()
+ expect(
+ (posthog.capture as jest.Mock).mock.calls.filter(([event]) => event === 'support widget load failed')
+ ).toHaveLength(0)
+ })
+
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',
@@ -74,7 +91,6 @@ describe('sidepanelTicketsLogic', () => {
await expectLogic(logic, () => {
supportLogic.actions.openSupportForm({
kind: 'support',
- target_area: 'analytics',
isEmailFormOpen: true,
target: 'sidePanel',
})
@@ -85,10 +101,10 @@ describe('sidepanelTicketsLogic', () => {
})
it.each([
- ['analytics', 'list'],
+ ['a general CTA lands on the list view', false, 'list'],
// Billing problems are answered on every plan
- ['billing', 'new'],
- ])('on a free plan, a %s support CTA lands on the %s view', async (targetArea, expectedView) => {
+ ['a billing CTA lands on the composer', true, 'new'],
+ ])('on a free plan, %s', async (_name, billingIssue, expectedView) => {
logic = sidepanelTicketsLogic.build()
logic.mount()
await expectLogic(logic).toFinishAllListeners()
@@ -98,7 +114,7 @@ describe('sidepanelTicketsLogic', () => {
await expectLogic(logic, () => {
supportLogic.actions.openSupportForm({
kind: 'bug',
- target_area: targetArea as 'analytics' | 'billing',
+ billing_issue: billingIssue as boolean,
isEmailFormOpen: true,
message: 'It broke',
target: 'sidePanel',
@@ -110,6 +126,119 @@ describe('sidepanelTicketsLogic', () => {
expect(supportLogic.values.isEmailFormOpen).toBe(false)
})
+ // An ineligible plan is turned away before a composer ever opens, so what's lost is the intent to
+ // reach us rather than anything typed. Modelled on a real CTA (FeedbackNotice, the session
+ // attribution explorer): they pass no message, so `had_draft` must not claim otherwise.
+ it('reports the turned-away intent when an ineligible plan hits a support CTA', async () => {
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ setSubscriptionLevel('free')
+ ;(posthog.capture as jest.Mock).mockClear()
+
+ await expectLogic(logic, () => {
+ supportLogic.actions.openSupportForm({ kind: 'bug', isEmailFormOpen: true, target: 'sidePanel' })
+ }).toFinishAllListeners()
+
+ const failures = (posthog.capture as jest.Mock).mock.calls.filter(
+ ([event]) => event === 'support ticket send failed'
+ )
+ expect(failures).toHaveLength(1)
+ expect(failures[0][1]).toMatchObject({
+ reason: 'not_entitled',
+ can_create_ticket: false,
+ had_draft: false,
+ })
+ // The composer never opened, so there is no draft to report — asserting this stops the field
+ // from quietly starting to carry a stale leftover from an earlier form interaction
+ expect(failures[0][1]).toMatchObject({ message_preview: '', message_length: 0 })
+ })
+
+ // Half the billing CTAs (Billing.tsx, ConfirmDowngradeModal, PurchaseCreditsModal) open the panel
+ // without setting isEmailFormOpen, so they never reach `startTicketFromSupportForm`. The exemption
+ // has to hold for them too, or a free plan lands on a panel with no composer and no explanation.
+ it('grants the billing exemption to a CTA that never opens the composer', async () => {
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ setSubscriptionLevel('free')
+ expect(logic.values.canCreateTicket).toBe(false)
+
+ await expectLogic(logic, () => {
+ supportLogic.actions.openSupportForm({ kind: 'bug', billing_issue: true, target: 'sidePanel' })
+ }).toFinishAllListeners()
+
+ expect(logic.values.canCreateTicket).toBe(true)
+ })
+
+ // The error boundary offers to "email an engineer" on a crash. Blocking that on plan would break a
+ // promise we just made on screen, and a crash we surfaced ourselves is always worth hearing about.
+ it('lets an ineligible plan report a crash from the error boundary', async () => {
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ setSubscriptionLevel('free')
+ expect(logic.values.canCreateTicket).toBe(false)
+ ;(posthog.capture as jest.Mock).mockClear()
+
+ await expectLogic(logic, () => {
+ supportLogic.actions.openSupportForm({
+ kind: 'bug',
+ isEmailFormOpen: true,
+ exception_event: { uuid: 'exc-1', event: '$exception' },
+ target: 'sidePanel',
+ })
+ }).toFinishAllListeners()
+
+ expect(logic.values.canCreateTicket).toBe(true)
+ expect(logic.values.view).toBe('new')
+ // Nothing was turned away, so there is no lost-submit to report
+ expect(
+ (posthog.capture as jest.Mock).mock.calls.filter(([event]) => event === 'support ticket send failed')
+ ).toHaveLength(0)
+ })
+
+ // Covers the live `isErrorReport` arm rather than the sticky reducer: a CTA that carries an
+ // exception without opening the composer never reaches `startTicketFromSupportForm`, which is
+ // exactly how three billing CTAs silently lost their exemption.
+ it('grants the exemption to a crash report that never opens the composer', async () => {
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ setSubscriptionLevel('free')
+ expect(logic.values.canCreateTicket).toBe(false)
+
+ await expectLogic(logic, () => {
+ supportLogic.actions.openSupportForm({
+ kind: 'bug',
+ exception_event: { uuid: 'exc-1', event: '$exception' },
+ target: 'sidePanel',
+ })
+ }).toFinishAllListeners()
+
+ expect(logic.values.hasSupportExemption).toBe(false)
+ expect(logic.values.canCreateTicket).toBe(true)
+ })
+
+ // The crash card promises "we'll attach the exception ID, stack trace and session replay". It sends
+ // an exception and no message, so a prefill guarded on the message alone dropped it silently.
+ it('carries the exception into the composer even when the CTA sends no message', async () => {
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ supportLogic.actions.openSupportForm({
+ kind: 'bug',
+ isEmailFormOpen: true,
+ exception_event: { uuid: 'exc-1', event: '$exception' },
+ target: 'sidePanel',
+ })
+ }).toFinishAllListeners()
+
+ expect(JSON.stringify(logic.values.newTicketDraft)).toContain('Exception')
+ })
+
it('keeps the billing exemption after the support form resets, so backing out of the composer is not a dead end', async () => {
logic = sidepanelTicketsLogic.build()
logic.mount()
@@ -120,14 +249,14 @@ describe('sidepanelTicketsLogic', () => {
await expectLogic(logic, () => {
supportLogic.actions.openSupportForm({
kind: 'support',
- target_area: 'billing',
+ billing_issue: true,
isEmailFormOpen: true,
target: 'sidePanel',
})
}).toFinishAllListeners()
- // supportLogic has already cleared target_area by now, so an exemption read off it would be gone
- expect(supportLogic.values.targetArea).toBeNull()
+ // supportLogic has already cleared billing_issue by now, so an exemption read off it would be gone
+ expect(supportLogic.values.isBillingIssue).toBe(false)
expect(logic.values.canCreateTicket).toBe(true)
logic.actions.setView('list')
@@ -146,7 +275,6 @@ describe('sidepanelTicketsLogic', () => {
supportLogic.actions.openSupportForm({
kind: 'bug',
- target_area: 'analytics',
isEmailFormOpen: true,
message: 'It broke',
target: 'sidePanel',
@@ -174,6 +302,69 @@ describe('sidepanelTicketsLogic', () => {
expect(supportLogic.values.pendingViewTicket).toBeNull()
})
+ // The panel already shows free plans the community and upgrade options, and they have no email
+ // channel, so warning them the chat failed would offer support they don't actually get.
+ it.each([
+ ['warns an entitled plan', 'paid', true],
+ ['stays quiet on a free plan', 'free', false],
+ ])('when the widget never loads, %s', async (_case, subscriptionLevel, expectWarning) => {
+ const errorToast = jest.spyOn(lemonToast, 'error').mockReturnValue('' as never)
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ // After the mount, so the fixture loads don't put the paid plan back. canCreateTicket also
+ // passes for orgs under three months old, so age the org out to make "free" really unentitled.
+ setSubscriptionLevel(subscriptionLevel as 'paid' | 'free')
+ organizationLogic.actions.loadCurrentOrganizationSuccess({
+ ...organizationLogic.values.currentOrganization,
+ created_at: '2020-01-01T00:00:00Z',
+ } as never)
+
+ // Spending the retry budget is the only way into this branch, and burning it through 20 real
+ // timer cycles races the fixture loads
+ delete (posthog as any).conversations
+ logic.cache.conversationsRetries = 20
+ ;(posthog.capture as jest.Mock).mockClear()
+
+ await expectLogic(logic, () => {
+ logic.actions.loadTickets()
+ }).toFinishAllListeners()
+
+ // Recorded either way, so the failure rate stays visible even where we don't interrupt
+ const loadFailures = (posthog.capture as jest.Mock).mock.calls.filter(
+ ([event]) => event === 'support widget load failed'
+ )
+ expect(loadFailures).toHaveLength(1)
+ expect(loadFailures[0][1]).toMatchObject({ can_create_ticket: expectWarning })
+ expect(errorToast).toHaveBeenCalledTimes(expectWarning ? 1 : 0)
+ errorToast.mockRestore()
+ })
+
+ it('reports a missing widget instead of silently dropping the composed message', async () => {
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ ;(posthog.capture as jest.Mock).mockClear()
+
+ // The extension can go missing after mount (blocked script, teardown). Sending used to return
+ // early with no toast and no loading state, leaving the typed message stranded.
+ delete (posthog as any).conversations
+ const onSuccess = jest.fn()
+
+ await expectLogic(logic, () => {
+ logic.actions.sendMessage('please help', onSuccess)
+ }).toFinishAllListeners()
+
+ expect(onSuccess).not.toHaveBeenCalled()
+ expect(logic.values.messageSending).toBe(false)
+ const failures = (posthog.capture as jest.Mock).mock.calls.filter(
+ ([event]) => event === 'support ticket send failed'
+ )
+ expect(failures).toHaveLength(1)
+ expect(failures[0][1]).toMatchObject({ reason: 'widget_unavailable' })
+ })
+
it('blocks an over-limit message client-side but sends a normal one', async () => {
logic = sidepanelTicketsLogic.build()
logic.mount()
@@ -193,4 +384,30 @@ describe('sidepanelTicketsLogic', () => {
expect(send).toHaveBeenCalledTimes(1)
expect(logic.values.messageSending).toBe(false)
})
+
+ // A declined send is the case the widget endpoint can't report for us — nothing reached it — and
+ // the reply the customer typed only exists in this composer, so the event has to carry it.
+ it('reports a declined send from the composer with the reply that was lost', async () => {
+ logic = sidepanelTicketsLogic.build()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ ;(posthog as any).conversations.sendMessage = jest.fn().mockResolvedValue(null)
+ ;(posthog.capture as jest.Mock).mockClear()
+ const onSuccess = jest.fn()
+
+ await expectLogic(logic, () => {
+ logic.actions.sendMessage('here is the error I get', onSuccess)
+ }).toFinishAllListeners()
+
+ expect(onSuccess).not.toHaveBeenCalled()
+ const failures = (posthog.capture as jest.Mock).mock.calls.filter(
+ ([event]) => event === 'support ticket send failed'
+ )
+ expect(failures).toHaveLength(1)
+ expect(failures[0][1]).toMatchObject({
+ surface: 'side_panel_composer',
+ reason: 'widget_declined',
+ message_preview: 'here is the error I get',
+ })
+ })
})
diff --git a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts
index 82d2532992e9..ebed531a310d 100644
--- a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts
+++ b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts
@@ -15,21 +15,24 @@ import { router } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
-import { appendExceptionToMessage, supportLogic, warnIfMessageTooLong } from 'lib/components/Support/supportLogic'
-import { FEATURE_FLAGS } from 'lib/constants'
+import {
+ appendExceptionToMessage,
+ captureSupportTicketFailed,
+ captureSupportWidgetLoadFailed,
+ SUPPORT_WIDGET_UNAVAILABLE_MESSAGE,
+ supportLogic,
+ warnIfMessageTooLong,
+ warnSupportWidgetUnavailable,
+} from 'lib/components/Support/supportLogic'
import { EMAIL_SUPPORT_BUTTON, lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { billingLogic } from 'scenes/billing/billingLogic'
import { organizationLogic } from 'scenes/organizationLogic'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import type { BillingType } from '~/types'
-import type {
- SupportFormFields,
- SupportTicketTargetArea,
-} from '../../../../../frontend/src/lib/components/Support/supportLogic'
-import type { FeatureFlagsSet } from '../../../../../frontend/src/lib/logic/featureFlagLogic'
+import type { SupportFormFields } from '../../../../../frontend/src/lib/components/Support/supportLogic'
import type {
ChatMessage,
ConversationMessage,
@@ -61,10 +64,12 @@ function messageToRichContent(message: string): JSONContent {
export interface sidepanelTicketsLogicValues {
billing: BillingType | null // billingLogic
billingLoading: boolean // billingLogic
- featureFlags: FeatureFlagsSet // featureFlagLogic
isCurrentOrganizationNew: boolean // organizationLogic
+ isCloudOrDev: boolean | undefined // preflightLogic
sidePanelOpen: boolean // sidePanelStateLogic
+ isBillingIssue: boolean // supportLogic
isEmailFormOpen: boolean // supportLogic
+ isErrorReport: boolean // supportLogic
pendingViewTicket: {
created_at: string
id: string
@@ -72,13 +77,11 @@ export interface sidepanelTicketsLogicValues {
} | null // supportLogic
sendSupportRequest: SupportFormFields // supportLogic
supportResponseTime: string | null // supportLogic
- targetArea: SupportTicketTargetArea | null // supportLogic
canCreateTicket: boolean
currentTicket: ConversationTicket | null
- hasBillingExemption: boolean
hasMoreMessages: boolean
+ hasSupportExemption: boolean
isBillingResolved: boolean
- isEnabled: boolean
messageSending: boolean
messages: ChatMessage[]
messagesLoading: boolean
@@ -109,7 +112,7 @@ export interface sidepanelTicketsLogicActions {
resetSendSupportRequest: (values?: SupportFormFields | undefined) => {
values?: SupportFormFields
} // supportLogic
- grantBillingExemption: () => {
+ grantSupportExemption: () => {
value: true
}
initTickets: () => {
@@ -187,12 +190,13 @@ export interface sidepanelTicketsLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sidepanelTicketsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- isEnabled: (featureFlags: FeatureFlagsSet) => boolean
totalUnreadCount: (tickets: ConversationTicket[]) => number
canCreateTicket: (
billing: BillingType | null,
isCurrentOrganizationNew: boolean,
- hasBillingExemption: boolean
+ hasSupportExemption: boolean,
+ isBillingIssue: boolean,
+ isErrorReport: boolean
) => boolean
isBillingResolved: (billing: BillingType | null, billingLoading: boolean) => boolean
}
@@ -211,14 +215,21 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
values: [
sidePanelStateLogic,
['sidePanelOpen'],
- featureFlagLogic,
- ['featureFlags'],
supportLogic,
- ['isEmailFormOpen', 'sendSupportRequest', 'pendingViewTicket', 'targetArea', 'supportResponseTime'],
+ [
+ 'isEmailFormOpen',
+ 'sendSupportRequest',
+ 'pendingViewTicket',
+ 'isBillingIssue',
+ 'isErrorReport',
+ 'supportResponseTime',
+ ],
billingLogic,
['billing', 'billingLoading'],
organizationLogic,
['isCurrentOrganizationNew'],
+ preflightLogic,
+ ['isCloudOrDev'],
],
actions: [
supportLogic,
@@ -228,7 +239,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
],
})),
actions({
- grantBillingExemption: true,
+ grantSupportExemption: true,
initTickets: true,
loadTickets: true,
startPolling: true,
@@ -331,23 +342,18 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
setRestoreState: () => null,
},
],
- // Held for the life of the open panel rather than read off supportLogic's `targetArea`, which
- // resets the moment the intent is consumed — a plan that can't open tickets would otherwise
- // lose the exemption mid-compose, and with it the composer it was just granted
- hasBillingExemption: [
+ // Held for the life of the open panel rather than read off the support request, which resets
+ // the moment the intent is consumed — a plan that can't open tickets would otherwise lose the
+ // exemption mid-compose, and with it the composer it was just granted
+ hasSupportExemption: [
false as boolean,
{
- grantBillingExemption: () => true,
+ grantSupportExemption: () => true,
closeSidePanel: () => false,
},
],
}),
selectors({
- isEnabled: [
- (s) => [s.featureFlags],
- (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): boolean =>
- !!featureFlags[FEATURE_FLAGS.PRODUCT_SUPPORT_SIDE_PANEL],
- ],
totalUnreadCount: [
(s) => [s.tickets],
(tickets: ConversationTicket[]) => tickets.reduce((sum, t) => sum + (t.unread_count ?? 0), 0),
@@ -356,8 +362,14 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
// the account isn't — free plans can end up with tickets via billing questions or PostHog AI
// bug reports, and abandoning those threads helps nobody.
canCreateTicket: [
- (s) => [s.billing, s.isCurrentOrganizationNew, s.hasBillingExemption],
- (billing: BillingType | null, isCurrentOrganizationNew: boolean, hasBillingExemption: boolean): boolean => {
+ (s) => [s.billing, s.isCurrentOrganizationNew, s.hasSupportExemption, s.isBillingIssue, s.isErrorReport],
+ (
+ billing: BillingType | null,
+ isCurrentOrganizationNew: boolean,
+ hasSupportExemption: boolean,
+ isBillingIssue: boolean,
+ isErrorReport: boolean
+ ): boolean => {
const hasSupportTrial =
billing?.trial?.status === 'active' &&
['boost', 'scale', 'enterprise'].includes(billing.trial?.target ?? '')
@@ -366,7 +378,14 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
billing?.subscription_level === 'custom' ||
hasSupportTrial ||
isCurrentOrganizationNew ||
- hasBillingExemption
+ // Billing questions are answered on every plan, and a crash we surfaced ourselves
+ // is always worth hearing about — the error boundary offers to email an engineer,
+ // so blocking that would break a promise we just made. Read live from the request
+ // as well as the sticky reducer: CTAs that don't open the composer never reach
+ // `startTicketFromSupportForm`, so the reducer alone would miss them.
+ isBillingIssue ||
+ isErrorReport ||
+ hasSupportExemption
)
},
],
@@ -403,7 +422,16 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
}
},
loadTickets: async () => {
- if (!values.isEnabled) {
+ // We don't support self-hosted, and the conversations extension is cloud-only — both the
+ // panel and the tickets scene already render a community-forum message instead. This logic
+ // still mounts there (the scene declares it in its SceneExport), so without this it would
+ // retry a widget that will never arrive and then tell a self-hosted user to email us.
+ //
+ // Explicitly `=== false` rather than falsy: `isCloudOrDev` is undefined until preflight
+ // resolves, and treating that as self-hosted would block the first load on cloud. Retries
+ // re-read it, so a self-hosted instance stops as soon as preflight lands — well inside the
+ // 20 attempts it takes to warn.
+ if (values.isCloudOrDev === false) {
return
}
if (cache.conversationsRetryTimer) {
@@ -415,6 +443,22 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
if ((cache.conversationsRetries ?? 0) < 20) {
cache.conversationsRetries = (cache.conversationsRetries ?? 0) + 1
cache.conversationsRetryTimer = window.setTimeout(() => actions.loadTickets(), 500)
+ } else if (!cache.conversationsUnavailableWarned) {
+ // Out of retries. Kept separate from the send-failure event because nothing was
+ // submitted here, and recorded even when we stay quiet so the rate is measurable.
+ cache.conversationsUnavailableWarned = true
+ captureSupportWidgetLoadFailed({
+ surface: 'side_panel_tickets',
+ reason: 'extension_missing',
+ can_create_ticket: values.canCreateTicket,
+ })
+ // Only warn people who could act on it. A free plan has no email fallback, and the
+ // panel already shows them the community and upgrade options, so a toast offering
+ // to email us would promise a channel they don't get. Warn while entitlement is
+ // still unresolved, matching how the composer opens rather than drop a message.
+ if (values.canCreateTicket || !values.isBillingResolved) {
+ warnSupportWidgetUnavailable()
+ }
}
return
}
@@ -430,14 +474,22 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
}
} catch (e) {
console.error('Failed to load tickets:', e)
+ // Reported because a customer who can't see their tickets can't reply to support on
+ // them either, and the toast alone left us blind to how often that happens
+ captureSupportWidgetLoadFailed({
+ surface: 'side_panel_tickets',
+ reason: 'tickets_load_failed',
+ error: e,
+ can_create_ticket: values.canCreateTicket,
+ })
lemonToast.error('Failed to load tickets.')
} finally {
actions.setTicketsLoading(false)
}
},
startPolling: () => {
- // Only poll if feature is enabled and page is visible
- if (!values.isEnabled || document.visibilityState !== 'visible') {
+ // Only poll while the page is visible
+ if (document.visibilityState !== 'visible') {
return
}
// Clear any existing poll timer
@@ -455,7 +507,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
}
},
loadMessages: async ({ ticketId }) => {
- if (!values.isEnabled || !ticketId || !posthog.conversations) {
+ if (!ticketId || !posthog.conversations) {
return
}
actions.setMessagesLoading(true)
@@ -492,16 +544,41 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
actions.setHasMoreMessages(false)
} catch (e) {
console.error('Failed to load messages:', e)
+ // A thread that won't open is a customer who can't continue a conversation they
+ // already started, so it belongs in the same rate signal as a dead panel
+ captureSupportWidgetLoadFailed({
+ surface: 'side_panel_tickets',
+ reason: 'thread_load_failed',
+ error: e,
+ })
lemonToast.error('Failed to load messages. Please try again.')
} finally {
actions.setMessagesLoading(false)
}
},
sendMessage: async ({ content, onSuccess }) => {
- if (!values.isEnabled || !content.trim() || values.messageSending || !posthog.conversations) {
+ if (!content.trim() || values.messageSending) {
+ return
+ }
+ // Bailing quietly here left the button un-loaded and the typed message sitting in the box
+ // with no explanation, which is the worst version of this now conversations is the only channel
+ if (!posthog.conversations) {
+ captureSupportTicketFailed({
+ surface: 'side_panel_composer',
+ reason: 'widget_unavailable',
+ message: content,
+ is_new_ticket: values.view === 'new',
+ })
+ warnSupportWidgetUnavailable()
return
}
if (warnIfMessageTooLong(content)) {
+ captureSupportTicketFailed({
+ surface: 'side_panel_composer',
+ reason: 'message_too_long',
+ message: content,
+ is_new_ticket: values.view === 'new',
+ })
return
}
actions.setMessageSending(true)
@@ -530,17 +607,26 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
onSuccess()
} else {
// A null response means nothing was sent, so surface it instead of silently
- // resetting. Server-rejected sends are captured server-side (widget endpoint),
- // so we only warn the user here rather than emitting a duplicate failure event.
- lemonToast.error('Failed to send message. Please try again.')
+ // resetting. The widget endpoint reports its own rejections under the same event
+ // name, but it can't see a send the extension declined to make — and only the
+ // client still holds the draft, which is the part a responder needs.
+ captureSupportTicketFailed({
+ surface: 'side_panel_composer',
+ reason: 'widget_declined',
+ message: content,
+ is_new_ticket: values.view === 'new',
+ })
+ lemonToast.error('Failed to send message. Please try again.', {
+ button: EMAIL_SUPPORT_BUTTON,
+ })
}
} catch (e) {
console.error('Failed to send message:', e)
- posthog.capture('support ticket send failed', {
- channel: 'conversations',
- error: e instanceof Error ? e.message : String(e),
- message_length: content.length,
- current_url_length: window.location.href.length,
+ captureSupportTicketFailed({
+ surface: 'side_panel_composer',
+ reason: 'send_failed',
+ message: content,
+ error: e,
is_new_ticket: values.view === 'new',
})
lemonToast.error('Failed to send message. Please try again.', { button: EMAIL_SUPPORT_BUTTON })
@@ -549,7 +635,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
}
},
markAsRead: async ({ ticketId }) => {
- if (!values.isEnabled || !ticketId || !posthog.conversations) {
+ if (!ticketId || !posthog.conversations) {
return
}
try {
@@ -565,33 +651,40 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
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
+ // supportLogic, which 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
- }
- // Billing problems are answered on every plan, so that CTA earns an exemption even when
- // the plan itself doesn't include support
- if (values.targetArea === 'billing') {
- actions.grantBillingExemption()
+ // Billing problems are answered on every plan, and a crash the error boundary surfaced is
+ // always worth hearing about, so both earn an exemption even when the plan excludes support
+ if (values.isBillingIssue || values.isErrorReport) {
+ actions.grantSupportExemption()
} else if (values.isBillingResolved && !values.canCreateTicket) {
// Still consume the intent (see below), just without opening the composer — the panel
// explains why and points at the community and upgrade options instead. Only ever on a
// known-ineligible plan: consuming is irreversible, so while entitlement is still
- // unknown we open the composer rather than drop someone's message on the floor.
+ // unknown we open the composer rather than turn someone away on a maybe.
+ //
+ // No draft is passed, and that's not an omission: this runs the moment a CTA fires,
+ // before any composer is on screen, so nothing has been typed yet. Every CTA that
+ // reaches here passes no message either. What's lost is the customer's intent to
+ // reach us, which is what the event records.
+ captureSupportTicketFailed({
+ surface: 'support_form',
+ reason: 'not_entitled',
+ kind: values.sendSupportRequest?.kind,
+ can_create_ticket: false,
+ })
actions.closeEmailForm()
actions.closeSupportForm()
actions.resetSendSupportRequest()
return
}
const request = values.sendSupportRequest
- const message = request?.message
- if (message) {
- actions.setNewTicketDraft(
- messageToRichContent(appendExceptionToMessage(message, request?.exception_event))
- )
+ // Guarding on the message alone dropped the exception, because an error boundary CTA
+ // carries an exception and no message — and its crash card promises we attach it
+ const draft = appendExceptionToMessage(request?.message ?? '', request?.exception_event)
+ if (draft) {
+ actions.setNewTicketDraft(messageToRichContent(draft))
}
actions.setView('new')
// Consume the support-form intent fully (or supportRouterLogic keeps treating the form as
@@ -608,11 +701,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
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'],
@@ -626,6 +715,13 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
requestRestoreLink: async ({ email }) => {
const conversations = posthog.conversations as any
if (!conversations?.requestRestoreLink) {
+ // Returning quietly left the button idle with no explanation. This form already renders
+ // restoreError inline, which beats a toast for something the user has to act on.
+ captureSupportWidgetLoadFailed({ surface: 'restore_form', reason: 'extension_missing' })
+ actions.setRestoreError(
+ `${SUPPORT_WIDGET_UNAVAILABLE_MESSAGE} Try turning it off for this site and reloading.`
+ )
+ actions.setRestoreState('error')
return
}
actions.setRestoreState('sending')
@@ -633,6 +729,9 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
await conversations.requestRestoreLink(email)
actions.setRestoreState('sent')
} catch (e: any) {
+ // Someone who lost their tickets and can't get the restore link has no way back to a
+ // conversation they already started, so it's worth the same visibility as a dead panel
+ captureSupportWidgetLoadFailed({ surface: 'restore_form', reason: 'restore_link_failed', error: e })
const message =
e?.status === 429
? 'Too many requests. Please try again later.'
@@ -676,27 +775,11 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([
}
},
})),
- subscriptions(({ actions, values }) => ({
- isEnabled: (enabled: boolean) => {
- if (!enabled) {
- 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()
- }
- },
+ subscriptions(({ actions }) => ({
sidePanelOpen: (open: boolean) => {
// Only on open — a close-triggered fetch is wasted (nothing renders the result), and the
// full-screen tickets scene closes the panel as it opens, which would double-fetch
- if (open && values.isEnabled) {
+ if (open) {
actions.loadTickets()
}
},
@@ -724,10 +807,15 @@ 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 here
- actions.initTickets()
+ actions.initTickets()
+ // A cold load of a `#panel=support:...:true` URL can set these before this logic mounts, so
+ // the isEmailFormOpen/pendingViewTicket subscriptions above only fire on change and would
+ // otherwise miss them — re-consume here too.
+ if (values.isEmailFormOpen) {
+ actions.startTicketFromSupportForm()
+ }
+ if (values.pendingViewTicket) {
+ actions.openPendingTicket()
}
}),
])
diff --git a/products/conversations/frontend/scenes/myTickets/MyTicketsScene.tsx b/products/conversations/frontend/scenes/myTickets/MyTicketsScene.tsx
index 7bcbcfbaca44..758ca1f8fc29 100644
--- a/products/conversations/frontend/scenes/myTickets/MyTicketsScene.tsx
+++ b/products/conversations/frontend/scenes/myTickets/MyTicketsScene.tsx
@@ -24,14 +24,13 @@ const PANE_MIN_HEIGHT = 'min(400px, calc(100svh - 16rem))'
const PANE_MAX_HEIGHT = 'calc(100svh - 16rem)'
export function MyTicketsScene(): JSX.Element {
- const { view, currentTicket, newTicketDraftRevision, isEnabled, isBillingResolved } =
- useValues(sidepanelTicketsLogic)
+ const { view, currentTicket, newTicketDraftRevision, isBillingResolved } = useValues(sidepanelTicketsLogic)
const { preflight } = useValues(preflightLogic)
const hasIdentityMode = !!window.JS_POSTHOG_IDENTITY_DISTINCT_ID
const isCloudOrDev = preflight?.cloud || process.env.NODE_ENV === 'development'
- if (!isEnabled || !isCloudOrDev) {
+ if (!isCloudOrDev) {
return (
<SceneContent>
<SceneTitleSection
diff --git a/products/customer_analytics/frontend/featurePreviewGate.ts b/products/customer_analytics/frontend/featurePreviewGate.ts
index 14effd4a1ab8..a2e2047158d5 100644
--- a/products/customer_analytics/frontend/featurePreviewGate.ts
+++ b/products/customer_analytics/frontend/featurePreviewGate.ts
@@ -8,5 +8,5 @@ export const customerAnalyticsFeaturePreviewGate: FeaturePreviewGateConfig = {
description:
'Get context about your customers. Is the number of signups going up? Are we converting free users to paid users? Need to know what the power users of a feature are? We got you covered. Customer analytics is currently in beta — request access below and our team will get you set up.',
docsURL: 'https://posthog.com/docs/customer-analytics',
- supportTargetArea: 'customer_analytics',
+ offerRequestAccess: true,
}
diff --git a/products/legal_documents/frontend/scenes/LegalDocumentNewScene.tsx b/products/legal_documents/frontend/scenes/LegalDocumentNewScene.tsx
index eb97be51372f..7750a7d9aeb1 100644
--- a/products/legal_documents/frontend/scenes/LegalDocumentNewScene.tsx
+++ b/products/legal_documents/frontend/scenes/LegalDocumentNewScene.tsx
@@ -189,7 +189,7 @@ export function LegalDocumentNewScene(): JSX.Element {
to=""
onClick={() =>
openSupportForm({
- target_area: 'billing',
+ billing_issue: true,
isEmailFormOpen: true,
})
}