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.

fix(posthogai): check billing server-side for /ticket eligibility (#67734)

Christiaan Hendriksen1098cced3a10
diff --git a/ee/hogai/chat_agent/prompts/base.py b/ee/hogai/chat_agent/prompts/base.py
index daa7aad22693..5d3902e44fd0 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.
+- `/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.
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.py
index 88a20dcc02fe..b3362d5f5770 100644
--- a/ee/hogai/chat_agent/slash_commands/commands/ticket/command.py
+++ b/ee/hogai/chat_agent/slash_commands/commands/ticket/command.py
@@ -12,7 +12,7 @@ from langchain_core.messages import (
)
from langchain_core.runnables import RunnableConfig
-from posthog.schema import AssistantMessage, HumanMessage, MaxBillingContext, MaxBillingContextSubscriptionLevel
+from posthog.schema import AssistantMessage, HumanMessage
from ee.hogai.chat_agent.slash_commands.commands import SlashCommand
from ee.hogai.core.agent_modes.compaction_manager import AnthropicConversationCompactionManager
@@ -40,8 +40,8 @@ class TicketCommand(SlashCommand):
months_since_creation = (timezone.now() - org_created_at).days / 30
return months_since_creation < 3
- async def _can_create_ticket(self, config: RunnableConfig) -> bool:
- """Check if user's subscription allows ticket creation."""
+ 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
@@ -49,26 +49,28 @@ class TicketCommand(SlashCommand):
if await self._is_organization_new():
return True
- billing_context_data = config.get("configurable", {}).get("billing_context")
- if not billing_context_data:
- return False
-
- billing_context = MaxBillingContext.model_validate(billing_context_data)
+ return await self._has_paid_plan_or_active_trial()
- has_paid_subscription = billing_context.subscription_level in (
- MaxBillingContextSubscriptionLevel.PAID,
- MaxBillingContextSubscriptionLevel.CUSTOM,
- )
- has_active_trial = billing_context.trial is not None and billing_context.trial.is_active
+ async def _has_paid_plan_or_active_trial(self) -> bool:
+ """
+ Check the plan tier derived from the organization's synced billing entitlements.
- return has_paid_subscription or has_active_trial
+ `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(config):
+ 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.",
+ 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()),
)
]
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.py
index 71677b263531..18ac7b99bca4 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,165 +1,101 @@
from datetime import timedelta
-import pytest
from posthog.test.base import BaseTest
-from unittest.mock import AsyncMock, patch
+from unittest.mock import patch
from django.utils import timezone
from asgiref.sync import sync_to_async
from langchain_core.runnables import RunnableConfig
+from parameterized import parameterized
from posthog.schema import AssistantMessage, HumanMessage
from ee.hogai.chat_agent.slash_commands.commands.ticket import TicketCommand
from ee.hogai.utils.types import AssistantState
+UPGRADE_MARKER = "paid plans"
+DESCRIBE_ISSUE_MARKER = "describe your issue"
-def _make_billing_context(subscription_level: str = "paid", trial_active: bool = False):
- return {
- "subscription_level": subscription_level,
- "has_active_subscription": subscription_level != "free",
- "products": [],
- "settings": {"autocapture_on": True, "active_destinations": 0},
- "trial": {"is_active": trial_active, "expires_at": None, "target": None} if trial_active else None,
- }
+PAID_FEATURES = [{"key": "alerts", "name": "Alerts"}]
class TestTicketCommand(BaseTest):
def setUp(self):
super().setUp()
- # Default to old organization (more than 3 months) for consistent test behavior
+ # 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)
- @pytest.mark.asyncio
- @patch.object(TicketCommand, "_summarize_conversation")
- async def test_execute_returns_summary(self, mock_summarize):
- """Test that /ticket returns the conversation summary."""
- mock_summarize.return_value = "Summary of the conversation"
-
- state = AssistantState(
- messages=[
- HumanMessage(content="How do I create an insight?"),
- AssistantMessage(content="You can create an insight by...", id="1"),
- HumanMessage(content="/ticket"),
- ]
- )
- config = RunnableConfig(
- configurable={
- "thread_id": "test-conversation-id",
- "trace_id": "test-trace-id",
- "billing_context": _make_billing_context("paid"),
- }
- )
-
- result = await self.command.execute(config, state)
-
- self.assertEqual(len(result.messages), 1)
- message = result.messages[0]
- assert isinstance(message, AssistantMessage)
- assert isinstance(message.content, str)
- self.assertEqual(message.content, "Summary of the conversation")
- mock_summarize.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_execute_first_message_prompts_for_input(self):
- """Test that /ticket as first message prompts user to describe issue."""
- state = AssistantState(
- messages=[
- HumanMessage(content="/ticket"),
- ]
- )
- config = RunnableConfig(
- configurable={"thread_id": "test-conversation-id", "billing_context": _make_billing_context("paid")}
- )
-
- result = await self.command.execute(config, state)
-
- self.assertEqual(len(result.messages), 1)
- message = result.messages[0]
- assert isinstance(message, AssistantMessage)
- assert isinstance(message.content, str)
- self.assertIn("describe your issue", message.content.lower())
-
- @pytest.mark.asyncio
- async def test_execute_free_user_returns_upgrade_message(self):
- """Test that /ticket returns upgrade message for free users."""
- state = AssistantState(messages=[HumanMessage(content="/ticket")])
- config = RunnableConfig(
- configurable={"thread_id": "test-conversation-id", "billing_context": _make_billing_context("free")}
- )
-
- result = await self.command.execute(config, state)
-
- self.assertEqual(len(result.messages), 1)
- message = result.messages[0]
- assert isinstance(message, AssistantMessage)
- assert isinstance(message.content, str)
- self.assertIn("paid plans", message.content)
+ def _config(self) -> RunnableConfig:
+ return RunnableConfig(configurable={"thread_id": "test-conversation-id"})
- @pytest.mark.asyncio
- async def test_execute_no_billing_context_returns_upgrade_message(self):
- """Test that /ticket returns upgrade message when no billing context."""
- state = AssistantState(messages=[HumanMessage(content="/ticket")])
- config = 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")])
- result = await self.command.execute(config, state)
+ def set_features() -> None:
+ self.team.organization.available_product_features = available_product_features
+ self.team.organization.save()
- self.assertEqual(len(result.messages), 1)
+ 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)
- self.assertIn("paid plans", message.content)
+ return message
- @pytest.mark.asyncio
@patch.object(TicketCommand, "_summarize_conversation")
- async def test_execute_custom_subscription_allowed(self, mock_summarize):
- """Test that /ticket works for custom subscription level."""
- mock_summarize.return_value = "Summary"
+ async def test_execute_returns_summary(self, mock_summarize):
+ mock_summarize.return_value = "Summary of the conversation"
state = AssistantState(
messages=[
- HumanMessage(content="Issue"),
- AssistantMessage(content="Response", id="1"),
+ HumanMessage(content="How do I create an insight?"),
+ AssistantMessage(content="You can create an insight by...", id="1"),
HumanMessage(content="/ticket"),
]
)
- config = RunnableConfig(
- configurable={"thread_id": "test-conversation-id", "billing_context": _make_billing_context("custom")}
- )
- result = await self.command.execute(config, state)
+ message = await self._execute_with_features(PAID_FEATURES, state=state)
- message = result.messages[0]
- assert isinstance(message, AssistantMessage)
- self.assertNotIn("paid plans", message.content)
+ self.assertEqual(message.content, "Summary of the conversation")
+ mock_summarize.assert_called_once()
- @pytest.mark.asyncio
- async def test_execute_active_trial_allowed(self):
- """Test that /ticket works for users with active trial."""
- state = AssistantState(messages=[HumanMessage(content="/ticket")])
- config = RunnableConfig(
- configurable={
- "thread_id": "test-conversation-id",
- "billing_context": _make_billing_context("free", trial_active=True),
- }
- )
+ 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)()
- result = await self.command.execute(config, state)
+ message = await self._execute_with_features(None)
- message = result.messages[0]
- assert isinstance(message, AssistantMessage)
- assert isinstance(message.content, str)
- self.assertIn("describe your issue", message.content.lower())
+ self.assertIn(DESCRIBE_ISSUE_MARKER, message.content.lower())
def test_is_first_message_with_only_ticket_command(self):
- """Test that _is_first_message returns True when only /ticket is present."""
state = AssistantState(messages=[HumanMessage(content="/ticket")])
self.assertTrue(self.command._is_first_message(state))
def test_is_first_message_with_prior_conversation(self):
- """Test that _is_first_message returns False when there's prior conversation."""
state = AssistantState(
messages=[
HumanMessage(content="How do I create an insight?"),
@@ -169,48 +105,12 @@ class TestTicketCommand(BaseTest):
)
self.assertFalse(self.command._is_first_message(state))
- @pytest.mark.asyncio
async def test_is_organization_new_returns_true_for_recent_org(self):
- """Test that _is_organization_new returns True for org created less than 3 months ago."""
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())
- @pytest.mark.asyncio
async def test_is_organization_new_returns_false_for_old_org(self):
- """Test that _is_organization_new returns False for org created more than 3 months ago."""
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())
-
- @pytest.mark.asyncio
- @patch.object(TicketCommand, "_is_organization_new", new_callable=AsyncMock, return_value=True)
- async def test_execute_new_org_free_user_allowed(self, mock_is_new):
- """Test that /ticket works for free users in new organizations."""
- state = AssistantState(messages=[HumanMessage(content="/ticket")])
- config = RunnableConfig(
- configurable={"thread_id": "test-conversation-id", "billing_context": _make_billing_context("free")}
- )
-
- result = await self.command.execute(config, state)
-
- message = result.messages[0]
- assert isinstance(message, AssistantMessage)
- assert isinstance(message.content, str)
- self.assertIn("describe your issue", message.content.lower())
-
- @pytest.mark.asyncio
- @patch.object(TicketCommand, "_is_organization_new", new_callable=AsyncMock, return_value=False)
- async def test_execute_old_org_free_user_blocked(self, mock_is_new):
- """Test that /ticket returns upgrade message for free users in old organizations."""
- state = AssistantState(messages=[HumanMessage(content="/ticket")])
- config = RunnableConfig(
- configurable={"thread_id": "test-conversation-id", "billing_context": _make_billing_context("free")}
- )
-
- result = await self.command.execute(config, state)
-
- message = result.messages[0]
- assert isinstance(message, AssistantMessage)
- assert isinstance(message.content, str)
- self.assertIn("paid plans", message.content)
diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.ts
index 9401ca442d0b..0eee6612c29b 100644
--- a/frontend/src/scenes/max/maxThreadLogic.test.ts
+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts
@@ -1781,6 +1781,8 @@ 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 () => {
@@ -1790,6 +1792,7 @@ describe('maxThreadLogic', () => {
expect(names).toContain(SlashCommandName.SlashRemember)
expect(names).toContain(SlashCommandName.SlashUsage)
expect(names).toContain(SlashCommandName.SlashFeedback)
+ expect(names).toContain(SlashCommandName.SlashTicket)
})
})
diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsx
index a06441186588..4b08a3a700db 100644
--- a/frontend/src/scenes/max/maxThreadLogic.tsx
+++ b/frontend/src/scenes/max/maxThreadLogic.tsx
@@ -82,7 +82,7 @@ import {
getModeDisplayName,
} from './max-constants'
import { PENDING_AI_PROMPT_KEY } from './max-storage-keys'
-import { MaxBillingContext, MaxBillingContextSubscriptionLevel, maxBillingContextLogic } from './maxBillingContextLogic'
+import { MaxBillingContext, maxBillingContextLogic } from './maxBillingContextLogic'
import { maxGlobalLogic } from './maxGlobalLogic'
import { SCENE_PANEL_ID, SIDE_PANEL_PANEL_ID, maxLogic } from './maxLogic'
import type { maxThreadLogicType } from './maxThreadLogicType'
@@ -2124,20 +2124,13 @@ export const maxThreadLogic = kea<maxThreadLogicType>([
],
filteredCommands: [
- (s) => [s.question, s.featureFlags, s.threadLoading, s.billingContext, s.conversation],
+ (s) => [s.question, s.featureFlags, s.threadLoading, s.conversation],
(
question: string,
featureFlags: Record<string, boolean | string>,
threadLoading: boolean,
- billingContext: MaxBillingContext | null,
conversation: Conversation | null
): SlashCommand[] => {
- const hasPaidPlan =
- billingContext?.subscription_level === MaxBillingContextSubscriptionLevel.PAID ||
- billingContext?.subscription_level === MaxBillingContextSubscriptionLevel.CUSTOM ||
- billingContext?.trial?.is_active ||
- process.env.NODE_ENV === 'development'
-
// Sandbox runtime drops core-memory commands; LangGraph keeps the full set.
const isSandboxRuntime = conversation?.agent_runtime === 'sandbox'
@@ -2146,7 +2139,6 @@ export const maxThreadLogic = kea<maxThreadLogicType>([
command.name.toLowerCase().startsWith(question.toLowerCase()) &&
(!command.flag || featureFlags[command.flag]) &&
(!command.requiresIdle || !threadLoading) &&
- (!command.requiresPaidPlan || hasPaidPlan) &&
(!command.hiddenInSandbox || !isSandboxRuntime)
)
},
diff --git a/frontend/src/scenes/max/slash-commands.tsx b/frontend/src/scenes/max/slash-commands.tsx
index f9f203618c03..baca6c15fcdd 100644
--- a/frontend/src/scenes/max/slash-commands.tsx
+++ b/frontend/src/scenes/max/slash-commands.tsx
@@ -14,8 +14,6 @@ export interface SlashCommand {
flag?: FeatureFlagKey
/** If true, this command is only available when the conversation is idle (not streaming) */
requiresIdle?: boolean
- /** If true, this command is only available for users on paid plans or with an active trial */
- requiresPaidPlan?: boolean
/**
* If true, this command is hidden for sandbox-runtime conversations.
* Core-memory commands (`/init`, `/remember`) are not yet supported under sandbox AI.
@@ -54,6 +52,5 @@ export const MAX_SLASH_COMMANDS: SlashCommand[] = [
description: 'Create a support ticket with a summary of this conversation',
icon: <IconSupport />,
requiresIdle: true,
- requiresPaidPlan: true,
},
]
diff --git a/frontend/src/scenes/max/ticketUtils.test.ts b/frontend/src/scenes/max/ticketUtils.test.ts
new file mode 100644
index 000000000000..7ee21ba25026
--- /dev/null
+++ b/frontend/src/scenes/max/ticketUtils.test.ts
@@ -0,0 +1,33 @@
+import { ThreadMessage } from './maxLogic'
+import { getTicketSummaryData } 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 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.'
+
+describe('getTicketSummaryData', () => {
+ it('does not treat an eligibility denial as a ticket summary', () => {
+ const thread = [
+ human('How do I create an insight?'),
+ ai('You can create an insight by...'),
+ human('/ticket'),
+ ai(DENIAL),
+ ]
+
+ expect(getTicketSummaryData(thread, false)).toBeNull()
+ })
+
+ it('returns the summary when the response after /ticket is a real summary', () => {
+ const thread = [
+ human('How do I create an insight?'),
+ ai('You can create an insight by...'),
+ human('/ticket'),
+ ai(SUMMARY),
+ ]
+
+ expect(getTicketSummaryData(thread, false)).toEqual({ summary: SUMMARY, messageIndex: 3 })
+ })
+})
diff --git a/frontend/src/scenes/max/ticketUtils.ts b/frontend/src/scenes/max/ticketUtils.ts
index be0471225780..19954d7e9e26 100644
--- a/frontend/src/scenes/max/ticketUtils.ts
+++ b/frontend/src/scenes/max/ticketUtils.ts
@@ -93,7 +93,8 @@ export function getTicketSummaryData(
responseMessage?.type === 'ai' &&
'content' in responseMessage &&
responseMessage.content &&
- !responseMessage.content.includes("I'll help you create a support ticket")
+ !responseMessage.content.includes("I'll help you create a support ticket") &&
+ !responseMessage.content.includes('is available for customers on paid plans')
) {
// Check if user continued the conversation (sent another message after the summary)
// or if a ticket was already created