:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(posthog-ai): enforce support-panel eligibility for /ticket (#73435)
Christiaan Hendriksen1938319d2e8e
diff --git a/ee/hogai/chat_agent/prompts/base.py b/ee/hogai/chat_agent/prompts/base.pyindex 693575edf377..5505a48c76d2 100644--- a/ee/hogai/chat_agent/prompts/base.py+++ b/ee/hogai/chat_agent/prompts/base.py@@ -85,7 +85,7 @@ PostHog AI supports slash commands. They are real app features handled by PostHo- `/remember [information]` - Append information verbatim to project-level core memory.- `/usage` - Show PostHog AI credit usage for the current conversation and billing period. Do not claim this command is fabricated, unavailable, or made up.- `/feedback [feedback]` - Send feedback about the PostHog AI experience.-- `/ticket` - Create a support ticket from the current conversation when enough context is available. Requires a paid plan or an active trial, though newly created organizations also qualify; the command checks eligibility itself and points ineligible users to the community at https://posthog.com/questions. Only steer users to the community instead of `/ticket` when the billing context clearly shows a free plan with no active trial and the organization is not newly created; when unsure, suggest `/ticket`. Billing problems are an exception: any organization, free or paid, can contact support about billing through the in-app help panel, so point users with billing issues there rather than to the community.+- `/ticket` - Create a support ticket from the current conversation when enough context is available. Requires a paid plan or an active trial, though newly created organizations also qualify; the app only offers the command to eligible customers and points others to the community at https://posthog.com/questions. Only steer users to the community instead of `/ticket` when the billing context clearly shows a free plan with no active trial and the organization is not newly created; when unsure, suggest `/ticket`, but mention it needs a paid plan or trial. If a user says `/ticket` is unavailable, blocked, or told them they need a paid plan, treat them as ineligible: point them to the community instead of suggesting the command again. Billing problems are an exception: any organization, free or paid, can contact support about billing through the in-app help panel, so point users with billing issues there rather than to the community.If a user asks about one of these commands, explain what the command does. If they report a command result looks wrong, treat the command as real and help debug the result.</slash_commands>diff --git a/ee/hogai/chat_agent/slash_commands/commands/ticket/command.py b/ee/hogai/chat_agent/slash_commands/commands/ticket/command.pyindex 599300e2090e..29bec2b0a909 100644--- a/ee/hogai/chat_agent/slash_commands/commands/ticket/command.py+++ b/ee/hogai/chat_agent/slash_commands/commands/ticket/command.py@@ -1,10 +1,6 @@from collections.abc import Sequencefrom uuid import uuid4-from django.conf import settings-from django.utils import timezone--from asgiref.sync import sync_to_asyncfrom langchain_core.messages import (HumanMessage as LangchainHumanMessage,SystemMessage,@@ -30,52 +26,8 @@ class TicketCommand(SlashCommand):_window_manager = AnthropicConversationCompactionManager()- async def _is_organization_new(self) -> bool:- """Check if the organization was created less than 3 months ago."""- # `self._team.organization` is a FK access that hits the DB when not prefetched,- # so it must be wrapped to be safe inside this async context.- org_created_at = await sync_to_async(lambda: self._team.organization.created_at)()- if not org_created_at:- return False- months_since_creation = (timezone.now() - org_created_at).days / 30- return months_since_creation < 3-- async def _can_create_ticket(self) -> bool:- """Check if the organization's subscription allows ticket creation."""- # Enable ticket creation in local dev- if settings.DEBUG:- return True-- if await self._is_organization_new():- return True-- return await self._has_paid_plan_or_active_trial()-- async def _has_paid_plan_or_active_trial(self) -> bool:- """- Check the plan tier derived from the organization's synced billing entitlements.-- `available_product_features` is kept up to date by every billing load, and active- trials grant the trial plan's features, so a non-free tier means a paid or custom- subscription or an active trial. Reading it locally keeps the slow billing service- API out of the conversation turn. Organizations with no synced entitlements are- denied, so missing data fails closed.- """- # `self._team.organization` is a FK access that hits the DB when not prefetched,- # so it must be wrapped to be safe inside this async context.- return await sync_to_async(lambda: self._team.organization.get_plan_tier() != "free")()-async def execute(self, config: RunnableConfig, state: AssistantState) -> PartialAssistantState:- if not await self._can_create_ticket():- return PartialAssistantState(- messages=[- AssistantMessage(- content="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.",- id=str(uuid4()),- )- ]- )-+ # Eligibility is enforced client-side (canCreateSupportTicket), like the support panel and its widget endpoint.if self._is_first_message(state):return PartialAssistantState(messages=[diff --git a/ee/hogai/chat_agent/slash_commands/commands/ticket/test/test_ticket.py b/ee/hogai/chat_agent/slash_commands/commands/ticket/test/test_ticket.pyindex 18ac7b99bca4..45bd15473a0f 100644--- a/ee/hogai/chat_agent/slash_commands/commands/ticket/test/test_ticket.py+++ b/ee/hogai/chat_agent/slash_commands/commands/ticket/test/test_ticket.py@@ -1,52 +1,24 @@-from datetime import timedelta-from posthog.test.base import BaseTestfrom unittest.mock import patch-from django.utils import timezone--from asgiref.sync import sync_to_asyncfrom langchain_core.runnables import RunnableConfig-from parameterized import parameterizedfrom posthog.schema import AssistantMessage, HumanMessagefrom ee.hogai.chat_agent.slash_commands.commands.ticket import TicketCommandfrom ee.hogai.utils.types import AssistantState-UPGRADE_MARKER = "paid plans"DESCRIBE_ISSUE_MARKER = "describe your issue"-PAID_FEATURES = [{"key": "alerts", "name": "Alerts"}]-class TestTicketCommand(BaseTest):def setUp(self):super().setUp()- # Old organization by default, so eligibility is decided by plan tier rather than the new-org grace period- self.team.organization.created_at = timezone.now() - timedelta(days=100)- self.team.organization.save()self.command = TicketCommand(self.team, self.user)def _config(self) -> RunnableConfig:return RunnableConfig(configurable={"thread_id": "test-conversation-id"})- async def _execute_with_features(- self, available_product_features: list | None, state: AssistantState | None = None- ) -> AssistantMessage:- state = state or AssistantState(messages=[HumanMessage(content="/ticket")])-- def set_features() -> None:- self.team.organization.available_product_features = available_product_features- self.team.organization.save()-- await sync_to_async(set_features)()- result = await self.command.execute(self._config(), state)- message = result.messages[0]- assert isinstance(message, AssistantMessage)- assert isinstance(message.content, str)- return message-@patch.object(TicketCommand, "_summarize_conversation")async def test_execute_returns_summary(self, mock_summarize):mock_summarize.return_value = "Summary of the conversation"@@ -58,37 +30,19 @@ class TestTicketCommand(BaseTest):])- message = await self._execute_with_features(PAID_FEATURES, state=state)-+ result = await self.command.execute(self._config(), state)+ message = result.messages[0]+ assert isinstance(message, AssistantMessage)self.assertEqual(message.content, "Summary of the conversation")mock_summarize.assert_called_once()async def test_execute_first_message_prompts_for_input(self):- message = await self._execute_with_features(PAID_FEATURES)-- self.assertIn(DESCRIBE_ISSUE_MARKER, message.content.lower())-- @parameterized.expand(- [- ("paid_entitlements", PAID_FEATURES, True),- ("no_entitlements", [], False),- ("entitlements_never_synced", None, False),- ]- )- async def test_eligibility_follows_plan_tier(self, _name, available_product_features, allowed):- message = await self._execute_with_features(available_product_features)-- if allowed:- self.assertIn(DESCRIBE_ISSUE_MARKER, message.content.lower())- else:- self.assertIn(UPGRADE_MARKER, message.content)-- async def test_new_org_allowed_without_entitlements(self):- self.team.organization.created_at = timezone.now() - timedelta(days=30)- await sync_to_async(self.team.organization.save)()-- message = await self._execute_with_features(None)+ state = AssistantState(messages=[HumanMessage(content="/ticket")])+ result = await self.command.execute(self._config(), state)+ message = result.messages[0]+ assert isinstance(message, AssistantMessage)+ assert isinstance(message.content, str)self.assertIn(DESCRIBE_ISSUE_MARKER, message.content.lower())def test_is_first_message_with_only_ticket_command(self):@@ -104,13 +58,3 @@ class TestTicketCommand(BaseTest):])self.assertFalse(self.command._is_first_message(state))-- async def test_is_organization_new_returns_true_for_recent_org(self):- self.team.organization.created_at = timezone.now() - timedelta(days=30)- await sync_to_async(self.team.organization.save)()- self.assertTrue(await self.command._is_organization_new())-- async def test_is_organization_new_returns_false_for_old_org(self):- self.team.organization.created_at = timezone.now() - timedelta(days=100)- await sync_to_async(self.team.organization.save)()- self.assertFalse(await self.command._is_organization_new())diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsxindex bd385493c84b..8d6b0204d3f7 100644--- a/frontend/src/scenes/max/Thread.tsx+++ b/frontend/src/scenes/max/Thread.tsx@@ -207,18 +207,20 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul*/function LegacyThread({ showTrailers }: { showTrailers: boolean }): JSX.Element | null {const { conversationLoading, messagesLoading, conversationId } = useValues(maxLogic)- const { threadGrouped, streamingActive, threadLoading, sandboxEntries } = useValues(maxThreadLogic)+ const { threadGrouped, streamingActive, threadLoading, sandboxEntries, canCreateTicket } = useValues(maxThreadLogic)const sandboxModeEnabled = useFeatureFlag('PHAI_SANDBOX_MODE')const { isPromptVisible, isDetailedFeedbackVisible, isThankYouVisible, traceId } = useFeedback(conversationId)+ // Gated on eligibility so the create-ticket affordance never renders for orgs the support+ // panel would turn away — e.g. from an old conversation that contains a past /ticket summary.const ticketPromptData = useMemo(- () => getTicketPromptData(threadGrouped, streamingActive),- [threadGrouped, streamingActive]+ () => (canCreateTicket ? getTicketPromptData(threadGrouped, streamingActive) : { needed: false }),+ [threadGrouped, streamingActive, canCreateTicket])const ticketSummaryData = useMemo(- () => getTicketSummaryData(threadGrouped, streamingActive),- [threadGrouped, streamingActive]+ () => (canCreateTicket ? getTicketSummaryData(threadGrouped, streamingActive) : null),+ [threadGrouped, streamingActive, canCreateTicket])return (conversationLoading || messagesLoading) && threadGrouped.length === 0 ? (diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.tsindex faa83e5bcd1c..40f6c5e27e23 100644--- a/frontend/src/scenes/max/maxThreadLogic.test.ts+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts@@ -8,10 +8,12 @@ import React from 'react'import api, { ApiError } from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'+import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'import { NotebookTarget } from 'scenes/notebooks/types'+import { organizationLogic } from 'scenes/organizationLogic'import { sceneLogic } from 'scenes/sceneLogic'import { Scene } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -28,7 +30,7 @@ import {SlashCommandName,} from '~/queries/schema/schema-assistant-messages'import { initKeaTests } from '~/test/init'-import { Conversation, ConversationDetail, ConversationStatus, ConversationType } from '~/types'+import { Conversation, ConversationDetail, ConversationStatus, ConversationType, OrganizationType } from '~/types'import { attachedContextLogic, runStreamLogic } from 'products/posthog_ai/frontend/api/logics'import { RuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'@@ -821,6 +823,23 @@ describe('maxThreadLogic', () => {expect(logic.values.queuedMessages).toEqual([{ ...queueMessage, content: 'Updated' }])})+ it('blocks editing a queued message into /ticket for orgs that cannot contact support', async () => {+ const updateSpy = jest.spyOn(api.conversations.queue, 'update')+ const toastSpy = jest.spyOn(lemonToast, 'warning')++ logic.actions.setConversation(MOCK_IN_PROGRESS_CONVERSATION)+ logic.actions.setQueuedMessages([+ { id: 'queue-1', content: 'Original', created_at: new Date().toISOString() },+ ])+ logic.actions.setQueueLimit(2)++ logic.actions.updateQueuedMessage('queue-1', '/ticket')+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(updateSpy).not.toHaveBeenCalled()+ expect(toastSpy).toHaveBeenCalled()+ })+it('deletes queued messages from the API', async () => {const queueMessage = {id: 'queue-1',@@ -1871,21 +1890,60 @@ describe('maxThreadLogic', () => {expect(names).not.toContain(SlashCommandName.SlashRemember)expect(names).toContain(SlashCommandName.SlashUsage)expect(names).toContain(SlashCommandName.SlashFeedback)- // /ticket must be offered even when no billing context is available — the backend decides eligibility- expect(names).toContain(SlashCommandName.SlashTicket)})- it('keeps the full command set for langgraph conversations', async () => {+ it('keeps the core-memory commands for langgraph conversations', async () => {setRuntime('langgraph')const names = logic.values.filteredCommands.map((c) => c.name)expect(names).toContain(SlashCommandName.SlashInit)expect(names).toContain(SlashCommandName.SlashRemember)expect(names).toContain(SlashCommandName.SlashUsage)expect(names).toContain(SlashCommandName.SlashFeedback)+ })++ it('hides /ticket for organizations that cannot contact support', () => {+ setRuntime('langgraph')+ const names = logic.values.filteredCommands.map((c) => c.name)+ expect(names).not.toContain(SlashCommandName.SlashTicket)+ })++ it('offers /ticket once the org is eligible to contact support', () => {+ setRuntime('langgraph')+ organizationLogic.actions.loadCurrentOrganizationSuccess({+ created_at: dayjs().toISOString(),+ } as OrganizationType)+ const names = logic.values.filteredCommands.map((c) => c.name)expect(names).toContain(SlashCommandName.SlashTicket)})})+ describe('ticket command send gate', () => {+ it('blocks sending /ticket for orgs that cannot contact support, even typed by hand', async () => {+ const streamSpy = mockStream()+ const toastSpy = jest.spyOn(lemonToast, 'warning')++ await expectLogic(logic, () => {+ logic.actions.askMax('/ticket')+ }).toNotHaveDispatchedActions(['streamConversation'])++ expect(streamSpy).not.toHaveBeenCalled()+ expect(toastSpy).toHaveBeenCalled()+ })++ it('sends /ticket for orgs that are eligible to contact support', async () => {+ const streamSpy = mockStream()+ organizationLogic.actions.loadCurrentOrganizationSuccess({+ created_at: dayjs().toISOString(),+ } as OrganizationType)++ await expectLogic(logic, () => {+ logic.actions.askMax('/ticket')+ }).toDispatchActions(['streamConversation'])++ expect(streamSpy).toHaveBeenCalledWith(expect.objectContaining({ content: '/ticket' }), expect.any(Object))+ })+ })+describe('command selection and activation', () => {beforeEach(() => {logic = maxThreadLogic({ conversationId: MOCK_CONVERSATION_ID, panelId: 'test' })diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex 4a1af9f0be04..89deed838637 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -26,9 +26,11 @@ import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { uuid } from 'lib/utils/dom'+import { billingLogic } from 'scenes/billing/billingLogic'import { maxContextLogic } from 'scenes/max/maxContextLogic'import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'import { NotebookTarget } from 'scenes/notebooks/types'+import { organizationLogic } from 'scenes/organizationLogic'import { sceneLogic } from 'scenes/sceneLogic'import { Scene } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -77,6 +79,7 @@ import { isPiTaskRuntime } from 'products/posthog_ai/frontend/types/taskTypes'import type { PermissionRequestRecord } from '../../../../products/posthog_ai/frontend/types/streamTypes'import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'+import type { BillingType } from '../../types'import { handsFreeLogic } from './handsFreeLogic'import { summariseAssistantThread } from './handsFreeUtils'import {@@ -92,7 +95,8 @@ import { maxGlobalLogic } from './maxGlobalLogic'import { SCENE_PANEL_ID, SIDE_PANEL_PANEL_ID, maxLogic } from './maxLogic'import { AttachedContext, MaxUIContext } from './maxTypes'import { posthogAiContextLogic } from './posthogAiContextLogic'-import { MAX_SLASH_COMMANDS, SlashCommand } from './slash-commands'+import { MAX_SLASH_COMMANDS, SlashCommand, SlashCommandName } from './slash-commands'+import { canCreateSupportTicket, isTicketCommand } from './ticketUtils'import { getToolCallDescriptionAndWidgetDef } from './toolCallDisplay'import {activeSceneLogicHasMaxContext,@@ -130,6 +134,15 @@ export interface MaxThreadLogicProps {skipInitialLoad?: boolean}+function showTicketIneligibleToast(): void {+ lemonToast.warning('Support tickets require a paid plan or an active trial. You can ask the community instead.', {+ button: {+ label: 'Ask the community',+ action: () => window.open('https://posthog.com/questions', '_blank'),+ },+ })+}+async function shouldBlockPendingPiTask(pendingBindTaskId: string): Promise<boolean> {try {const pendingTask = await api.tasks.get(pendingBindTaskId)@@ -147,6 +160,7 @@ async function shouldBlockPendingPiTask(pendingBindTaskId: string): Promise<bool// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface maxThreadLogicValues {+ billing: BillingType | null // billingLogicfeatureFlags: FeatureFlagsSet // featureFlagLogicbillingContext: MaxBillingContext | null // maxBillingContextLogiccompiledContext: MaxUIContext | null // maxContextLogic@@ -162,6 +176,7 @@ export interface maxThreadLogicValues {parentConversationId: string | null // maxLogicpendingBindTaskId: string | null // maxLogicquestion: string // maxLogic+ isCurrentOrganizationNew: boolean // organizationLogicsandboxAttachments: AttachedContext[] // posthogAiContextLogicpendingSandboxPermissionRequest: PermissionRequestRecord | null // runStreamLogicsandboxCurrentMode: string | null // runStreamLogic@@ -176,6 +191,7 @@ export interface maxThreadLogicValues {activeMultiQuestionForm: MultiQuestionForm | nullagentMode: AgentMode | nullagentModeLockedByUser: boolean+ canCreateTicket: booleancancelCount: numbercancelLoading: booleancontextDisabledReason: string | undefined@@ -676,11 +692,13 @@ export interface maxThreadLogicMeta {question: string,queueDisabledReason: string | undefined) => string | undefined+ canCreateTicket: (billing: BillingType | null, isCurrentOrganizationNew: boolean) => booleanfilteredCommands: (question: string,featureFlags: FeatureFlagsSet,threadLoading: boolean,- conversation: Conversation | null+ conversation: Conversation | null,+ canCreateTicket: boolean) => SlashCommand[]showDeepResearchModeToggle: (conversation: Conversation | null, featureFlags: FeatureFlagsSet) => booleanshowContextUI: (conversation: Conversation | null, featureFlags: FeatureFlagsSet) => boolean@@ -741,6 +759,10 @@ export const maxThreadLogic = kea<maxThreadLogicType>([['compiledContext'],maxBillingContextLogic,['billingContext'],+ billingLogic,+ ['billing'],+ organizationLogic,+ ['isCurrentOrganizationNew'],featureFlagLogic,['featureFlags'],sceneLogic,@@ -1774,6 +1796,13 @@ export const maxThreadLogic = kea<maxThreadLogicType>([actions.setQueueLimit(0)return}+ // askMax (currently the only caller) already gates /ticket before enqueueing; this guards+ // the queue mutation itself so future callers can't slip an ineligible /ticket into the+ // queue, which drains server-side where the command is not gated.+ if (isTicketCommand(content) && !canCreateSupportTicket(values.billing, values.isCurrentOrganizationNew)) {+ showTicketIneligibleToast()+ return+ }try {const queuePayload: {content: string@@ -1817,6 +1846,12 @@ export const maxThreadLogic = kea<maxThreadLogicType>([actions.setQueueLimit(0)return}+ // The queued-message edit UI calls this directly, without going through askMax, and the+ // queue drains server-side — so an edit to /ticket must be gated here.+ if (isTicketCommand(content) && !canCreateSupportTicket(values.billing, values.isCurrentOrganizationNew)) {+ showTicketIneligibleToast()+ return+ }try {const queue = await api.conversations.queue.update(values.conversation.id, queueId, content)actions.setQueuedMessages(queue.messages)@@ -1898,6 +1933,16 @@ export const maxThreadLogic = kea<maxThreadLogicType>([if (values.conversationId !== values.activeThreadKey) {return}+ // Enforced here (not just hidden from the autocomplete) so typing /ticket by hand+ // can't create a ticket the support panel would refuse.+ if (+ prompt &&+ isTicketCommand(prompt) &&+ !canCreateSupportTicket(values.billing, values.isCurrentOrganizationNew)+ ) {+ showTicketIneligibleToast()+ return+ }if (isPiTaskRuntime(values.conversation?.task?.runtime)) {return}@@ -2810,13 +2855,20 @@ export const maxThreadLogic = kea<maxThreadLogicType>([},],+ canCreateTicket: [+ (s) => [s.billing, s.isCurrentOrganizationNew],+ (billing: BillingType | null, isCurrentOrganizationNew: boolean): boolean =>+ canCreateSupportTicket(billing, isCurrentOrganizationNew),+ ],+filteredCommands: [- (s) => [s.question, s.featureFlags, s.threadLoading, s.conversation],+ (s) => [s.question, s.featureFlags, s.threadLoading, s.conversation, s.canCreateTicket],(question: string,featureFlags: Record<string, boolean | string>,threadLoading: boolean,- conversation: Conversation | null+ conversation: Conversation | null,+ canCreateTicket: boolean): SlashCommand[] => {// Sandbox runtime drops core-memory commands; LangGraph keeps the full set.const isSandboxRuntime = conversation?.agent_runtime === 'sandbox'@@ -2826,7 +2878,9 @@ export const maxThreadLogic = kea<maxThreadLogicType>([command.name.toLowerCase().startsWith(question.toLowerCase()) &&(!command.flag || featureFlags[command.flag]) &&(!command.requiresIdle || !threadLoading) &&- (!command.hiddenInSandbox || !isSandboxRuntime)+ (!command.hiddenInSandbox || !isSandboxRuntime) &&+ // /ticket mirrors the in-app support panel: only offer it to eligible orgs.+ (command.name !== SlashCommandName.SlashTicket || canCreateTicket))},],diff --git a/frontend/src/scenes/max/ticketUtils.test.ts b/frontend/src/scenes/max/ticketUtils.test.tsindex 2f07c62225de..db421572c7d8 100644--- a/frontend/src/scenes/max/ticketUtils.test.ts+++ b/frontend/src/scenes/max/ticketUtils.test.ts@@ -1,9 +1,14 @@+import type { BillingType } from '~/types'+import { ThreadMessage } from './maxLogic'import {appendTicketMetadata,+ canCreateSupportTicket,composeTicketBody,formatTicketConfirmationMessage,+ getTicketPromptData,getTicketSummaryData,+ isTicketCommand,isTicketConfirmationMessage,} from './ticketUtils'@@ -16,6 +21,17 @@ const DENIAL =describe('ticketUtils', () => {describe('getTicketSummaryData', () => {+ it('does not treat a near-miss like /tickets as a ticket command', () => {+ const thread = [+ human('How do I create an insight?'),+ ai('You can create an insight by...'),+ human('/tickets'),+ ai("/tickets isn't a recognized slash command. You might be looking for /ticket (singular)."),+ ]++ expect(getTicketSummaryData(thread, false)).toBeNull()+ })+it('does not treat an eligibility denial as a ticket summary', () => {const thread = [human('How do I create an insight?'),@@ -39,6 +55,19 @@ describe('ticketUtils', () => {})})+ describe('getTicketPromptData', () => {+ const prompt = "I'll help you create a support ticket"++ it.each([+ ['plain command with text', '/ticket sync failed', 'sync failed'],+ ['leading whitespace still prefills the text', ' /ticket sync failed', 'sync failed'],+ ['bare command has no prefill', '/ticket', undefined],+ ])('%s', (_name, content, expectedInitialText) => {+ const thread = [human(content), ai(prompt)]+ expect(getTicketPromptData(thread, false)).toEqual({ needed: true, initialText: expectedInitialText })+ })+ })+describe('formatTicketConfirmationMessage', () => {it('promises the response time the plan covers', () => {expect(formatTicketConfirmationMessage('4321', '48 hours')).toBe(@@ -62,6 +91,70 @@ describe('ticketUtils', () => {})})+ describe('canCreateSupportTicket', () => {+ const billing = (partial: Partial<BillingType>): BillingType => partial as BillingType++ it.each([+ ['paid subscription', billing({ subscription_level: 'paid' }), false, true],+ ['custom subscription', billing({ subscription_level: 'custom' }), false, true],+ [+ 'free with active boost trial',+ billing({+ subscription_level: 'free',+ trial: { status: 'active', target: 'boost' } as BillingType['trial'],+ }),+ false,+ true,+ ],+ [+ 'free with active scale trial',+ billing({+ subscription_level: 'free',+ trial: { status: 'active', target: 'scale' } as BillingType['trial'],+ }),+ false,+ true,+ ],+ [+ 'free with active enterprise trial',+ billing({+ subscription_level: 'free',+ trial: { status: 'active', target: 'enterprise' } as BillingType['trial'],+ }),+ false,+ true,+ ],+ [+ 'free with expired trial',+ billing({+ subscription_level: 'free',+ trial: { status: 'expired', target: 'boost' } as BillingType['trial'],+ }),+ false,+ false,+ ],+ ['free without trial', billing({ subscription_level: 'free' }), false, false],+ ['free but organization is new', billing({ subscription_level: 'free' }), true, true],+ ['billing not loaded, organization not new', null, false, false],+ ['billing not loaded, organization new', null, true, true],+ ])('%s', (_name, billingValue, isOrgNew, expected) => {+ expect(canCreateSupportTicket(billingValue, isOrgNew)).toBe(expected)+ })+ })++ describe('isTicketCommand', () => {+ it.each([+ ['/ticket', true],+ ['/ticket my recordings are broken', true],+ [' /ticket ', true],+ ['/tickets', false],+ ['/feedback', false],+ ['tell me about /ticket', false],+ ])('%s', (content, expected) => {+ expect(isTicketCommand(content)).toBe(expected)+ })+ })+describe('composeTicketBody', () => {it.each([[diff --git a/frontend/src/scenes/max/ticketUtils.ts b/frontend/src/scenes/max/ticketUtils.tsindex 355de8a30f71..7b905c0ac73b 100644--- a/frontend/src/scenes/max/ticketUtils.ts+++ b/frontend/src/scenes/max/ticketUtils.ts@@ -1,5 +1,37 @@+import type { BillingType } from '~/types'+import { ThreadMessage } from './maxLogic'+/**+ * Whether a composer submission is the /ticket slash command.+ */+export function isTicketCommand(content: string): boolean {+ const trimmed = content.trim()+ return trimmed === '/ticket' || trimmed.startsWith('/ticket ')+}++/**+ * Mirrors the paid-support entitlement in `canCreateTicket` (sidepanelTicketsLogic.ts), so /ticket does+ * not create tickets for orgs the support panel would turn away. Keep the two in sync.+ *+ * Two differences from the panel are deliberate. The panel also admits an otherwise ineligible org on+ * `isBillingIssue`, `isErrorReport`, and `hasSupportExemption`, which are set by the support-form and+ * error-boundary entry points that carry those intents, and a chat thread reaches none of them. And the+ * panel waits for `isBillingResolved` before turning anyone away, whereas a null `billing` reads as+ * ineligible here, so an ineligible org gets no window while entitlement is still loading.+ */+export function canCreateSupportTicket(billing: BillingType | null, isCurrentOrganizationNew: boolean): boolean {+ const hasActiveTrial =+ billing?.trial?.status === 'active' &&+ (billing.trial.target === 'boost' || billing.trial.target === 'scale' || billing.trial.target === 'enterprise')+ return (+ billing?.subscription_level === 'paid' ||+ billing?.subscription_level === 'custom' ||+ hasActiveTrial ||+ isCurrentOrganizationNew+ )+}+export interface TicketSummaryData {summary?: stringdiscarded?: boolean@@ -28,8 +60,9 @@ export function formatTicketConfirmationMessage(ticketId: string, responseTime:* Extracts the text after "/ticket " from a message, if any.*/function extractTicketText(content: string): string | undefined {- if (content.startsWith('/ticket ')) {- const text = content.slice('/ticket '.length).trim()+ const trimmed = content.trim()+ if (trimmed.startsWith('/ticket ')) {+ const text = trimmed.slice('/ticket '.length).trim()return text || undefined}return undefined@@ -52,7 +85,7 @@ export function getTicketPromptData(threadGrouped: ThreadMessage[], streamingActconst isInitialTicketPrompt =firstMessage?.type === 'human' &&'content' in firstMessage &&- firstMessage.content.startsWith('/ticket') &&+ isTicketCommand(firstMessage.content) &&lastMessage?.type === 'ai' &&'content' in lastMessage &&lastMessage.content.includes("I'll help you create a support ticket")@@ -91,7 +124,7 @@ export function getTicketSummaryData(let ticketCommandIndex = -1for (let i = threadGrouped.length - 1; i >= 0; i--) {const msg = threadGrouped[i]- if (msg?.type === 'human' && 'content' in msg && msg.content.startsWith('/ticket')) {+ if (msg?.type === 'human' && 'content' in msg && isTicketCommand(msg.content)) {ticketCommandIndex = ibreak}