:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(web-analytics): Add Web analytics nudge to PostHog AI (#61998)
Jordan Mryyan44bc335b4ec0
diff --git a/ee/hogai/api/serializers.py b/ee/hogai/api/serializers.pyindex 176ab17873a0..404094e080cb 100644--- a/ee/hogai/api/serializers.py+++ b/ee/hogai/api/serializers.py@@ -22,6 +22,7 @@ _conversation_fields = ["id","status","title",+ "topic","user","created_at","updated_at",diff --git a/ee/hogai/core/runner.py b/ee/hogai/core/runner.pyindex 26cc4bcb4e51..65b8628bc0c1 100644--- a/ee/hogai/core/runner.py+++ b/ee/hogai/core/runner.py@@ -600,6 +600,8 @@ class BaseAgentRunner(ABC):if isinstance(update, ConversationTitleAction):self._conversation.title = update.title+ if update.topic is not None:+ self._conversation.topic = update.topicself._pending_conversation_update = Truereturn Nonediff --git a/ee/hogai/core/title_generator/nodes.py b/ee/hogai/core/title_generator/nodes.pyindex 5345b360f889..95501bfdc393 100644--- a/ee/hogai/core/title_generator/nodes.py+++ b/ee/hogai/core/title_generator/nodes.py@@ -1,19 +1,31 @@+import logging+from typing import cast+from langchain_core.output_parsers import StrOutputParserfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.runnables import RunnableConfigfrom langgraph.config import get_stream_writer+from pydantic import BaseModel, Fieldfrom posthog.schema import HumanMessagefrom products.posthog_ai.backend.models.assistant import Conversationfrom ee.hogai.core.node import AssistantNode-from ee.hogai.core.title_generator.prompts import TITLE_GENERATION_PROMPT+from ee.hogai.core.title_generator.prompts import TITLE_AND_TOPIC_GENERATION_PROMPT, TITLE_GENERATION_PROMPTfrom ee.hogai.llm import MaxChatOpenAI+from ee.hogai.utils.feature_flags import has_conversation_topic_feature_flagfrom ee.hogai.utils.helpers import find_last_message_of_typefrom ee.hogai.utils.types import AssistantState, PartialAssistantStatefrom ee.hogai.utils.types.base import ConversationTitleAction+logger = logging.getLogger(__name__)+++class TitleAndTopic(BaseModel):+ title: str = Field(description="A crisp conversation title, ≤ 8 words, sentence case.")+ topic: Conversation.Topic = Field(description="The PostHog product domain the user's first question is about.")+class TitleGeneratorNode(AssistantNode):def run(self, state: AssistantState, config: RunnableConfig) -> PartialAssistantState | None:@@ -25,37 +37,69 @@ class TitleGeneratorNode(AssistantNode):if not conversation or conversation.title:return None- runnable = (- ChatPromptTemplate.from_messages([("system", TITLE_GENERATION_PROMPT), ("user", "{user_input}")])- | self._model- | StrOutputParser()- )-- title = runnable.invoke({"user_input": human_message.content}, config=config)+ if has_conversation_topic_feature_flag(self._team, self._user):+ title, topic = self._generate_title_and_topic(human_message.content, config)+ else:+ title, topic = self._generate_title_only(human_message.content, config), Noneconversation.title = title[: Conversation.TITLE_MAX_LENGTH].strip()+ if topic is not None:+ conversation.topic = topicconversation.save()- # Emit the title to the stream so the frontend can display it immediately+ # Emit the title and topic to the stream so the frontend updates immediatelytry:writer = get_stream_writer()except RuntimeError:pass # Not in a streaming context (e.g. testing)else:- writer(ConversationTitleAction(title=conversation.title))+ writer(ConversationTitleAction(title=conversation.title, topic=conversation.topic))return None- @property- def _model(self):+ def _generate_title_only(self, user_input: str, config: RunnableConfig) -> str:+ runnable = (+ ChatPromptTemplate.from_messages([("system", TITLE_GENERATION_PROMPT), ("user", "{user_input}")])+ | self._model+ | StrOutputParser()+ )+ return runnable.invoke({"user_input": user_input}, config=config)++ def _generate_title_and_topic(self, user_input: str, config: RunnableConfig) -> tuple[str, str | None]:+ try:+ runnable = (+ ChatPromptTemplate.from_messages(+ [("system", TITLE_AND_TOPIC_GENERATION_PROMPT), ("user", "{user_input}")]+ )+ | self._topic_model+ )+ result = cast(TitleAndTopic, runnable.invoke({"user_input": user_input}, config=config))+ return result.title, result.topic+ except Exception:+ # Never break title generation on a classification failure, fall back to title-only.+ logger.exception("title_topic_generation_failed, falling back to title-only")+ return self._generate_title_only(user_input, config), None++ def _build_model(self, *, max_completion_tokens: int, topic_classification: bool) -> MaxChatOpenAI:return MaxChatOpenAI(model="gpt-4.1-nano",temperature=0.7,- max_completion_tokens=100,+ max_completion_tokens=max_completion_tokens,user=self._user,team=self._team,streaming=False,stream_usage=False,disable_streaming=True,billable=True,+ posthog_properties={"topic_classification": topic_classification},+ )++ @property+ def _model(self):+ return self._build_model(max_completion_tokens=100, topic_classification=False)++ @property+ def _topic_model(self):+ return self._build_model(max_completion_tokens=200, topic_classification=True).with_structured_output(+ TitleAndTopic, method="json_schema", include_raw=False)diff --git a/ee/hogai/core/title_generator/prompts.py b/ee/hogai/core/title_generator/prompts.pyindex a7be986d4c30..36e1172f8776 100644--- a/ee/hogai/core/title_generator/prompts.py+++ b/ee/hogai/core/title_generator/prompts.py@@ -10,3 +10,29 @@ Given the brief below, output one title that:- Use sentence case, preserving all-caps acronyms (e.g. SQL, API).Respond with the title only—no explanations.""".strip()+++TITLE_AND_TOPIC_GENERATION_PROMPT = """+You generate a crisp conversation title AND classify the conversation's product domain.++For the title, output one title that:+– Captures the core intent in ≤ 8 words.+– Uses clear, action-oriented language (gerund verbs up front where possible).+– Avoids jargon unless it adds clarity for product engineers.+– Sounds friendly but professional (imagine a Slack channel name).+– Uses sentence case (first letter capitalized), preserving all-caps acronyms (e.g. SQL, API).+– Avoids empty adjectives.++For the topic, pick the single PostHog product domain the user's question is about:+– web_analytics: pageviews, visitors, traffic sources/channels, referrers, UTMs, bounce rate, sessions, geography, devices/browsers, web vitals, marketing analytics.+– product_analytics: trends, funnels, retention, paths, user behavior on custom events, dashboards/insights not specific to web traffic.+– session_replay: watching/finding session recordings.+– surveys: survey questions, responses, NPS.+– feature_flags: flag rollouts, targeting.+– experiments: A/B tests, experiment results.+– error_tracking: exceptions, errors, stack traces, issues.+– data_warehouse: external data sources, SQL over warehouse tables, data imports.+– other: anything that does not clearly fit the above.++Prefer web_analytics when the question is about website/visitor/traffic-style web metrics, even if it could also be answered with a generic trend.+""".strip()diff --git a/ee/hogai/core/title_generator/test/test_title_generator.py b/ee/hogai/core/title_generator/test/test_title_generator.pyindex 594fb4c17766..ae62d44b3918 100644--- a/ee/hogai/core/title_generator/test/test_title_generator.py+++ b/ee/hogai/core/title_generator/test/test_title_generator.py@@ -2,17 +2,22 @@ from posthog.test.base import BaseTestfrom unittest.mock import Mock, patchfrom langchain_core.messages import AIMessage as LangchainAIMessage+from langchain_core.runnables import RunnableLambdafrom posthog.schema import HumanMessagefrom products.posthog_ai.backend.models.assistant import Conversation-from ee.hogai.core.title_generator.nodes import TitleGeneratorNode+from ee.hogai.core.title_generator.nodes import TitleAndTopic, TitleGeneratorNodefrom ee.hogai.utils.tests import FakeChatOpenAIfrom ee.hogai.utils.types import AssistantStatefrom ee.hogai.utils.types.base import ConversationTitleAction+def _raise(_):+ raise RuntimeError("boom")++class TestTitleGenerator(BaseTest):def setUp(self):super().setUp()@@ -148,6 +153,76 @@ class TestTitleGenerator(BaseTest):self.conversation.refresh_from_db()self.assertEqual(self.conversation.title, "Some title")+ def test_classifies_topic_when_flag_enabled(self):+ fake = RunnableLambda(lambda _: TitleAndTopic(title="Traffic last week", topic="web_analytics"))+ with (+ patch("ee.hogai.core.title_generator.nodes.has_conversation_topic_feature_flag", return_value=True),+ patch.object(TitleGeneratorNode, "_topic_model", new=fake),+ ):+ node = TitleGeneratorNode(self.team, self.user)+ node.run(+ AssistantState(messages=[HumanMessage(content="How many people visited my site?")]),+ {"configurable": {"thread_id": self.conversation.id}},+ )+ self.conversation.refresh_from_db()+ self.assertEqual(self.conversation.title, "Traffic last week")+ self.assertEqual(self.conversation.topic, "web_analytics")++ def test_does_not_classify_topic_when_flag_disabled(self):+ with (+ patch("ee.hogai.core.title_generator.nodes.has_conversation_topic_feature_flag", return_value=False),+ patch.object(+ TitleGeneratorNode,+ "_model",+ new=RunnableLambda(lambda _: LangchainAIMessage(content="Plain title")),+ ),+ ):+ node = TitleGeneratorNode(self.team, self.user)+ node.run(+ AssistantState(messages=[HumanMessage(content="How many people visited my site?")]),+ {"configurable": {"thread_id": self.conversation.id}},+ )+ self.conversation.refresh_from_db()+ self.assertEqual(self.conversation.title, "Plain title")+ self.assertIsNone(self.conversation.topic)++ def test_emits_topic_in_conversation_title_action(self):+ written = []+ mock_writer = Mock(side_effect=lambda action: written.append(action))+ fake = RunnableLambda(lambda _: TitleAndTopic(title="Survey responses", topic="surveys"))+ with (+ patch("ee.hogai.core.title_generator.nodes.has_conversation_topic_feature_flag", return_value=True),+ patch.object(TitleGeneratorNode, "_topic_model", new=fake),+ patch("ee.hogai.core.title_generator.nodes.get_stream_writer", return_value=mock_writer),+ ):+ node = TitleGeneratorNode(self.team, self.user)+ node.run(+ AssistantState(messages=[HumanMessage(content="Show me my NPS")]),+ {"configurable": {"thread_id": self.conversation.id}},+ )+ self.assertEqual(len(written), 1)+ self.assertIsInstance(written[0], ConversationTitleAction)+ self.assertEqual(written[0].topic, "surveys")++ def test_falls_back_to_title_only_when_topic_generation_fails(self):+ with (+ patch("ee.hogai.core.title_generator.nodes.has_conversation_topic_feature_flag", return_value=True),+ patch.object(TitleGeneratorNode, "_topic_model", new=RunnableLambda(_raise)),+ patch.object(+ TitleGeneratorNode,+ "_model",+ new=RunnableLambda(lambda _: LangchainAIMessage(content="Fallback title")),+ ),+ ):+ node = TitleGeneratorNode(self.team, self.user)+ node.run(+ AssistantState(messages=[HumanMessage(content="How many people visited my site?")]),+ {"configurable": {"thread_id": self.conversation.id}},+ )+ self.conversation.refresh_from_db()+ self.assertEqual(self.conversation.title, "Fallback title")+ self.assertIsNone(self.conversation.topic)+def test_handles_json_content_without_error(self):"""Test that title generation works when user message contains JSON with curly braces."""json_content = """Hi Max,diff --git a/ee/hogai/utils/feature_flags.py b/ee/hogai/utils/feature_flags.pyindex 778cc44c78b7..d9a8f0f1b0b1 100644--- a/ee/hogai/utils/feature_flags.py+++ b/ee/hogai/utils/feature_flags.py@@ -43,6 +43,16 @@ def has_task_tool_feature_flag(team: Team, user: User) -> bool:)+def has_conversation_topic_feature_flag(team: Team, user: User) -> bool:+ return posthoganalytics.feature_enabled(+ "posthog-ai-web-analytics-nudge",+ str(user.distinct_id),+ groups={"organization": str(team.organization_id)},+ group_properties={"organization": {"id": str(team.organization_id)}},+ send_feature_flag_events=False,+ )++def has_memory_tool_feature_flag(team: Team, user: User) -> bool:return posthoganalytics.feature_enabled("phai-memory-tool",diff --git a/ee/hogai/utils/types/base.py b/ee/hogai/utils/types/base.pyindex bba7fda5f204..8c54ce8422b4 100644--- a/ee/hogai/utils/types/base.py+++ b/ee/hogai/utils/types/base.py@@ -615,6 +615,7 @@ class UpdateAction(BaseModel):class ConversationTitleAction(BaseModel):type: Literal["CONVERSATION_TITLE"] = "CONVERSATION_TITLE"title: str+ topic: str | None = NoneAssistantActionUnion = (diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex e6132bac7d36..2e70d39855d5 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -372,6 +372,7 @@ export const FEATURE_FLAGS = {MAX_BILLING_CONTEXT: 'max-billing-context', // owner: @pawel-cebula #team-billingMAX_DEEP_RESEARCH: 'max-deep-research', // owner: @kappa90 #team-posthog-aiMAX_HANDS_FREE: 'max-hands-free', // owner: #team-posthog-ai+ MAX_WEB_ANALYTICS_NUDGE: 'posthog-ai-web-analytics-nudge', // owner: @jordanm-posthog #team-web-analyticsMCP_ANALYTICS: 'mcp-analytics', // owner: #project-mcp-analyticsMCP_ANALYTICS_INTENT_ROUTING: 'mcp-analytics-intent-routing', // owner: #project-mcp-analyticsMCP_HINTS: 'mcp-hints', // owner: @rafaeelaudibert #team-growth multivariate=control,testdiff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsxindex d60a5a0afe33..5842be0246f4 100644--- a/frontend/src/scenes/max/Thread.tsx+++ b/frontend/src/scenes/max/Thread.tsx@@ -70,6 +70,7 @@ import { PendingApproval, Region } from '~/types'import { LogEntry } from 'products/tasks/frontend/lib/parse-logs'import { FeedbackDisplay } from './components/FeedbackDisplay'+import { MaxWebAnalyticsNudge } from './components/MaxWebAnalyticsNudge'import { ContextSummary } from './Context'import { DangerousOperationApprovalCard } from './DangerousOperationApprovalCard'import { FeedbackPrompt } from './FeedbackPrompt'@@ -707,6 +708,9 @@ function Message({}return null // We currently skip other types of messages})()}+ {isFinal && isLastInGroup && message.status === 'completed' && (+ <MaxWebAnalyticsNudge message={message} />+ )}{isLastInGroup && message.status === 'error' && (<MessageTemplate type="ai" boxClassName="border-warning"><div className="flex items-center gap-1.5">diff --git a/frontend/src/scenes/max/components/MaxWebAnalyticsNudge.tsx b/frontend/src/scenes/max/components/MaxWebAnalyticsNudge.tsxnew file mode 100644index 000000000000..b48c1eb9dc45--- /dev/null+++ b/frontend/src/scenes/max/components/MaxWebAnalyticsNudge.tsx@@ -0,0 +1,56 @@+import { useActions, useValues } from 'kea'++import { LemonButton } from '@posthog/lemon-ui'++import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'++import { maxWebAnalyticsNudgeLogic } from '../logics/maxWebAnalyticsNudgeLogic'+import { maxLogic, ThreadMessage } from '../maxLogic'+import { maxThreadLogic } from '../maxThreadLogic'+import { MessageTemplate } from '../messages/MessageTemplate'++export interface MaxWebAnalyticsNudgeProps {+ message: ThreadMessage+}++export function MaxWebAnalyticsNudge({ message }: MaxWebAnalyticsNudgeProps): JSX.Element | null {+ const { threadGrouped, isSharedThread, threadLoading, conversation } = useValues(maxThreadLogic)+ const { conversationId } = useValues(maxLogic)++ const logic = maxWebAnalyticsNudgeLogic({+ messageId: message.id ?? conversationId ?? 'nudge',+ threadGrouped,+ isCompleted: message.status === 'completed' && !threadLoading,+ isSharedThread,+ conversationId,+ conversationTopic: conversation?.topic ?? null,+ })+ const { shouldShowNudge } = useValues(logic)+ const { nudgeClicked, nudgeDismissed } = useActions(logic)++ if (!shouldShowNudge) {+ return null+ }++ return (+ <MessageTemplate type="ai" boxClassName="border-accent">+ <div className="flex items-start gap-2">+ <span className="text-lg shrink-0">{iconForType('web_analytics')}</span>+ <div className="flex flex-col gap-1.5">+ <span className="text-sm">+ Want the full picture? Web analytics breaks down pageviews, traffic sources, and more in one+ place.+ </span>+ <div className="flex gap-2">+ <LemonButton type="primary" size="small" onClick={nudgeClicked}>+ View in Web analytics+ </LemonButton>+ <LemonButton type="tertiary" size="small" onClick={nudgeDismissed}>+ Dismiss+ </LemonButton>+ </div>+ </div>+ </div>+ </MessageTemplate>+ )+}diff --git a/frontend/src/scenes/max/logics/maxWebAnalyticsNudgeLogic.test.ts b/frontend/src/scenes/max/logics/maxWebAnalyticsNudgeLogic.test.tsnew file mode 100644index 000000000000..0ddd0939cab1--- /dev/null+++ b/frontend/src/scenes/max/logics/maxWebAnalyticsNudgeLogic.test.ts@@ -0,0 +1,467 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { dayjs } from 'lib/dayjs'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { Scene } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { recentItemsModel } from '~/models/recentItemsModel'+import { AssistantMessageType } from '~/queries/schema/schema-assistant-messages'+import { NodeKind } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import type { ThreadMessage } from '../maxThreadLogic'+import { maxWebAnalyticsNudgeLogic, MaxWebAnalyticsNudgeLogicProps } from './maxWebAnalyticsNudgeLogic'+import { maxWebAnalyticsNudgeSessionLogic } from './maxWebAnalyticsNudgeSessionLogic'++const WEB_CHART_MESSAGE: ThreadMessage = {+ type: AssistantMessageType.Artifact,+ content: {+ content_type: 'visualization',+ query: {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],+ },+ },+} as any++const NON_WEB_MESSAGE: ThreadMessage = {+ type: AssistantMessageType.Assistant,+ content: 'hi',+} as any++function humanMessage(content: string): ThreadMessage {+ return { type: AssistantMessageType.Human, content } as any+}++function buildProps(overrides: Partial<MaxWebAnalyticsNudgeLogicProps> = {}): MaxWebAnalyticsNudgeLogicProps {+ return {+ messageId: 'msg-1',+ threadGrouped: [WEB_CHART_MESSAGE],+ isCompleted: true,+ isSharedThread: false,+ conversationId: 'conv-1',+ conversationTopic: null,+ ...overrides,+ }+}++function setFlagVariant(variant: string): void {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MAX_WEB_ANALYTICS_NUDGE]: variant })+}++function setFlagAbsent(): void {+ featureFlagLogic.actions.setFeatureFlags([], {})+}++function setRecentVisit(scene: string, daysAgo: number): void {+ recentItemsModel.actions.loadSceneLogViewsSuccess({ [scene]: dayjs().subtract(daysAgo, 'days').toISOString() })+}++function setNoRecentVisit(): void {+ recentItemsModel.actions.loadSceneLogViewsSuccess({})+}++describe('maxWebAnalyticsNudgeLogic', () => {+ let logic: ReturnType<typeof maxWebAnalyticsNudgeLogic.build>++ beforeEach(() => {+ initKeaTests()+ window.sessionStorage.clear()++ jest.spyOn(api.fileSystemLogView, 'list').mockReturnValue(new Promise(() => undefined))+ jest.spyOn(api.fileSystem, 'list').mockReturnValue(new Promise(() => undefined))++ featureFlagLogic.mount()+ maxWebAnalyticsNudgeSessionLogic.mount()+ recentItemsModel.mount()+ })++ afterEach(() => {+ logic?.unmount()+ maxWebAnalyticsNudgeSessionLogic.unmount()+ recentItemsModel.unmount()+ featureFlagLogic.unmount()+ window.sessionStorage.clear()+ jest.restoreAllMocks()+ })++ describe('visitedWebAnalyticsRecently', () => {+ it.each([+ ['WebAnalytics visited 5 days ago', Scene.WebAnalytics, 5, true],+ ['WebAnalytics visited 40 days ago', Scene.WebAnalytics, 40, false],+ ['MarketingAnalytics visited 5 days ago', Scene.MarketingAnalytics, 5, true],+ ])('%s returns %s', (_label, scene, daysAgo, expected) => {+ setRecentVisit(scene as string, daysAgo)+ setFlagVariant('test')+ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()+ expect(logic.values.visitedWebAnalyticsRecently).toBe(expected)+ })++ it('returns false when no scene views are recorded', () => {+ setNoRecentVisit()+ setFlagVariant('test')+ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()+ expect(logic.values.visitedWebAnalyticsRecently).toBe(false)+ })+ })++ describe('isWebAnalyticsAnswer', () => {+ beforeEach(() => {+ setNoRecentVisit()+ setFlagVariant('test')+ })++ it('returns true for a web analytics chart message', () => {+ logic = maxWebAnalyticsNudgeLogic(buildProps({ threadGrouped: [WEB_CHART_MESSAGE] }))+ logic.mount()+ expect(logic.values.isWebAnalyticsAnswer).toBe(true)+ })++ it('returns true when the chart is not the last message in the group (chart + trailing summary text)', () => {+ logic = maxWebAnalyticsNudgeLogic(buildProps({ threadGrouped: [WEB_CHART_MESSAGE, NON_WEB_MESSAGE] }))+ logic.mount()+ expect(logic.values.isWebAnalyticsAnswer).toBe(true)+ expect(logic.values.trigger).toBe('chart')+ })++ it('returns true when group is non-web but question text is web analytics related', () => {+ logic = maxWebAnalyticsNudgeLogic(+ buildProps({ threadGrouped: [humanMessage('where is my traffic coming from?'), NON_WEB_MESSAGE] })+ )+ logic.mount()+ expect(logic.values.isWebAnalyticsAnswer).toBe(true)+ })++ it('returns true for a "visited my website" question with no chart signals', () => {+ logic = maxWebAnalyticsNudgeLogic(+ buildProps({+ threadGrouped: [humanMessage('How many people visited my website last week?'), NON_WEB_MESSAGE],+ })+ )+ logic.mount()+ expect(logic.values.isWebAnalyticsAnswer).toBe(true)+ })++ it('returns false when group is non-web and question text has no web keywords', () => {+ logic = maxWebAnalyticsNudgeLogic(+ buildProps({ threadGrouped: [humanMessage('how many users signed up?'), NON_WEB_MESSAGE] })+ )+ logic.mount()+ expect(logic.values.isWebAnalyticsAnswer).toBe(false)+ })++ it('returns true when the conversation topic is web_analytics, even with a non-web group and question', () => {+ logic = maxWebAnalyticsNudgeLogic(+ buildProps({+ threadGrouped: [humanMessage('how many users signed up?'), NON_WEB_MESSAGE],+ conversationTopic: 'web_analytics',+ })+ )+ logic.mount()+ expect(logic.values.isWebAnalyticsAnswer).toBe(true)+ })++ it('a non-web conversation topic does not by itself make it a web analytics answer', () => {+ logic = maxWebAnalyticsNudgeLogic(+ buildProps({+ threadGrouped: [humanMessage('how many users signed up?'), NON_WEB_MESSAGE],+ conversationTopic: 'product_analytics',+ })+ )+ logic.mount()+ expect(logic.values.isWebAnalyticsAnswer).toBe(false)+ })+ })++ describe('trigger', () => {+ beforeEach(() => {+ setNoRecentVisit()+ setFlagVariant('test')+ })++ it('returns "chart" for a web analytics chart message', () => {+ logic = maxWebAnalyticsNudgeLogic(buildProps({ threadGrouped: [WEB_CHART_MESSAGE] }))+ logic.mount()+ expect(logic.values.trigger).toBe('chart')+ })++ it('returns "question" when only the question text matched (non-web group + web question)', () => {+ logic = maxWebAnalyticsNudgeLogic(+ buildProps({ threadGrouped: [humanMessage('show me my top pages'), NON_WEB_MESSAGE] })+ )+ logic.mount()+ expect(logic.values.trigger).toBe('question')+ })++ it('returns "topic" when the conversation topic is web_analytics (authoritative over chart)', () => {+ logic = maxWebAnalyticsNudgeLogic(+ buildProps({ threadGrouped: [WEB_CHART_MESSAGE], conversationTopic: 'web_analytics' })+ )+ logic.mount()+ expect(logic.values.trigger).toBe('topic')+ })+ })++ describe('isEligible', () => {+ beforeEach(() => {+ setNoRecentVisit()+ setFlagVariant('test')+ })++ it('is true when all conditions hold', () => {+ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()+ expect(logic.values.isEligible).toBe(true)+ })++ it.each([+ ['isCompleted is false', { isCompleted: false }],+ ['isSharedThread is true', { isSharedThread: true }],+ ] as [string, Partial<MaxWebAnalyticsNudgeLogicProps>][])('is false when %s', (_label, propsOverride) => {+ logic = maxWebAnalyticsNudgeLogic(buildProps(propsOverride))+ logic.mount()+ expect(logic.values.isEligible).toBe(false)+ })++ it('is false when visitedWebAnalyticsRecently is true', () => {+ setRecentVisit(Scene.WebAnalytics, 5)+ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()+ expect(logic.values.isEligible).toBe(false)+ })+ })++ describe('isEligible when sceneLogViewsHasLoaded is false', () => {+ it('is false when sceneLogViewsHasLoaded is false', () => {+ setFlagVariant('test')++ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()++ expect(logic.values.sceneLogViewsHasLoaded).toBe(false)+ expect(logic.values.isEligible).toBe(false)+ })+ })++ describe('shouldShowNudge', () => {+ beforeEach(() => {+ setNoRecentVisit()+ })++ it('is true when variant is "test", eligible, and fresh session', () => {+ setFlagVariant('test')+ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()+ expect(logic.values.shouldShowNudge).toBe(true)+ })++ it('is false when variant is "control"', () => {+ setFlagVariant('control')+ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()+ expect(logic.values.shouldShowNudge).toBe(false)+ })++ it('is false when flag is not enrolled', () => {+ setFlagAbsent()+ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()+ expect(logic.values.shouldShowNudge).toBe(false)+ })++ it('is false after nudgeDismissed', async () => {+ setFlagVariant('test')+ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.nudgeDismissed()+ }).toMatchValues({ shouldShowNudge: false })+ })++ it('is false when shownForMessageId already equals a DIFFERENT message id', () => {+ maxWebAnalyticsNudgeSessionLogic.actions.hydrateFromStorage({+ shownForMessageId: 'other-msg',+ dismissed: false,+ eligibleReported: false,+ })++ setFlagVariant('test')+ logic = maxWebAnalyticsNudgeLogic(buildProps({ messageId: 'msg-1' }))+ logic.mount()+ expect(logic.values.shouldShowNudge).toBe(false)+ })++ it('is true when shownForMessageId equals this message id', () => {+ maxWebAnalyticsNudgeSessionLogic.actions.hydrateFromStorage({+ shownForMessageId: 'msg-1',+ dismissed: false,+ eligibleReported: false,+ })++ setFlagVariant('test')+ logic = maxWebAnalyticsNudgeLogic(buildProps({ messageId: 'msg-1' }))+ logic.mount()+ expect(logic.values.shouldShowNudge).toBe(true)+ })+ })++ describe('posthog.capture reporting', () => {+ let captureSpy: jest.SpyInstance++ beforeEach(() => {+ captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ setNoRecentVisit()+ })++ afterEach(() => {+ captureSpy.mockRestore()+ })++ it('fires both "eligible" and "shown" exactly once for variant "test" on mount', () => {+ setFlagVariant('test')+ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()++ const expectedProperties = {+ conversation_id: 'conv-1',+ message_id: 'msg-1',+ variant: 'test',+ trigger: 'chart',+ }+ expect(captureSpy).toHaveBeenCalledWith('posthog ai web analytics nudge eligible', expectedProperties)+ expect(captureSpy).toHaveBeenCalledWith('posthog ai web analytics nudge shown', expectedProperties)+ expect(+ captureSpy.mock.calls.filter((c) => c[0] === 'posthog ai web analytics nudge eligible')+ ).toHaveLength(1)+ expect(captureSpy.mock.calls.filter((c) => c[0] === 'posthog ai web analytics nudge shown')).toHaveLength(1)+ })++ it('fires "eligible" only (no "shown") for variant "control"', () => {+ setFlagVariant('control')+ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()++ expect(captureSpy).toHaveBeenCalledWith(+ 'posthog ai web analytics nudge eligible',+ expect.objectContaining({ variant: 'control' })+ )+ expect(captureSpy).not.toHaveBeenCalledWith('posthog ai web analytics nudge shown', expect.anything())+ })++ it('fires neither event when not enrolled in the flag', () => {+ setFlagAbsent()+ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()++ expect(captureSpy).not.toHaveBeenCalledWith('posthog ai web analytics nudge eligible', expect.anything())+ expect(captureSpy).not.toHaveBeenCalledWith('posthog ai web analytics nudge shown', expect.anything())+ })+ })++ describe('nudgeClicked and nudgeDismissed actions', () => {+ let captureSpy: jest.SpyInstance++ beforeEach(() => {+ captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ setNoRecentVisit()+ setFlagVariant('test')+ logic = maxWebAnalyticsNudgeLogic(buildProps())+ logic.mount()+ captureSpy.mockClear()+ })++ afterEach(() => {+ captureSpy.mockRestore()+ })++ it('nudgeClicked fires the clicked event with reportProperties', async () => {+ await expectLogic(logic, () => {+ logic.actions.nudgeClicked()+ })++ expect(captureSpy).toHaveBeenCalledWith('posthog ai web analytics nudge clicked', {+ conversation_id: 'conv-1',+ message_id: 'msg-1',+ variant: 'test',+ trigger: 'chart',+ })+ })++ it('nudgeClicked navigates to web analytics so the chat moves to the side panel', async () => {+ const pushSpy = jest.spyOn(router.actions, 'push')++ await expectLogic(logic, () => {+ logic.actions.nudgeClicked()+ })++ expect(pushSpy).toHaveBeenCalledWith(urls.webAnalytics(), { utm_source: 'posthog-ai-nudge' })+ })++ it('nudgeDismissed fires the dismissed event and flips shouldShowNudge to false', async () => {+ expect(logic.values.shouldShowNudge).toBe(true)++ await expectLogic(logic, () => {+ logic.actions.nudgeDismissed()+ }).toMatchValues({ shouldShowNudge: false })++ expect(captureSpy).toHaveBeenCalledWith('posthog ai web analytics nudge dismissed', {+ conversation_id: 'conv-1',+ message_id: 'msg-1',+ variant: 'test',+ trigger: 'chart',+ })+ })+ })++ describe('once-per-session deduplication', () => {+ let captureSpy: jest.SpyInstance+ let logic2: ReturnType<typeof maxWebAnalyticsNudgeLogic.build>++ beforeEach(() => {+ captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ setNoRecentVisit()+ setFlagVariant('test')+ })++ afterEach(() => {+ logic2?.unmount()+ captureSpy.mockRestore()+ })++ it('does not fire eligible or shown again for a second message, and shouldShowNudge is false on it', async () => {+ logic = maxWebAnalyticsNudgeLogic(buildProps({ messageId: 'msg-1' }))+ logic.mount()++ const eligibleCalls1 = captureSpy.mock.calls.filter(+ (c) => c[0] === 'posthog ai web analytics nudge eligible'+ ).length+ const shownCalls1 = captureSpy.mock.calls.filter(+ (c) => c[0] === 'posthog ai web analytics nudge shown'+ ).length+ expect(eligibleCalls1).toBe(1)+ expect(shownCalls1).toBe(1)++ captureSpy.mockClear()++ logic2 = maxWebAnalyticsNudgeLogic(buildProps({ messageId: 'msg-2' }))+ logic2.mount()++ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(+ captureSpy.mock.calls.filter((c) => c[0] === 'posthog ai web analytics nudge eligible')+ ).toHaveLength(0)+ expect(captureSpy.mock.calls.filter((c) => c[0] === 'posthog ai web analytics nudge shown')).toHaveLength(0)++ expect(logic2.values.shouldShowNudge).toBe(false)+ })+ })+})diff --git a/frontend/src/scenes/max/logics/maxWebAnalyticsNudgeLogic.ts b/frontend/src/scenes/max/logics/maxWebAnalyticsNudgeLogic.tsnew file mode 100644index 000000000000..ba4866dc5d91--- /dev/null+++ b/frontend/src/scenes/max/logics/maxWebAnalyticsNudgeLogic.ts@@ -0,0 +1,214 @@+import { actions, afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'+import { router } from 'kea-router'+import { subscriptions } from 'kea-subscriptions'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { dayjs } from 'lib/dayjs'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { Scene } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { recentItemsModel } from '~/models/recentItemsModel'+import { HumanMessage } from '~/queries/schema/schema-assistant-messages'+import { ConversationTopic } from '~/types'++import { maxGlobalLogic } from '../maxGlobalLogic'+import type { ThreadMessage } from '../maxThreadLogic'+import { isHumanMessage } from '../utils'+import { isWebAnalyticsRelatedMessage, isWebAnalyticsRelatedQuestion } from '../utils/detectWebAnalyticsQuery'+import type { maxWebAnalyticsNudgeLogicType } from './maxWebAnalyticsNudgeLogicType'+import { maxWebAnalyticsNudgeSessionLogic } from './maxWebAnalyticsNudgeSessionLogic'++const WEB_ANALYTICS_RECENT_DAYS = 30++const WEB_ANALYTICS_SCENE_REFS: string[] = [+ Scene.WebAnalytics,+ Scene.WebAnalyticsPageReports,+ Scene.WebAnalyticsWebVitals,+ Scene.WebAnalyticsHealth,+ Scene.WebAnalyticsLive,+ Scene.MarketingAnalytics,+]++function getFinalAnswerGroup(messages: ThreadMessage[]): ThreadMessage[] {+ const group: ThreadMessage[] = []+ for (let i = messages.length - 1; i >= 0; i--) {+ if (isHumanMessage(messages[i])) {+ break+ }+ group.unshift(messages[i])+ }+ return group+}++export type NudgeTrigger = 'topic' | 'chart' | 'question'++export interface MaxWebAnalyticsNudgeLogicProps {+ messageId: string+ threadGrouped: ThreadMessage[]+ isCompleted: boolean+ isSharedThread: boolean+ conversationId: string | null+ // Domain classified by PostHog AI (from the conversation's first question); authoritative when present.+ conversationTopic: ConversationTopic | null+}++export interface NudgeReportProperties {+ conversation_id: string | null+ message_id: string+ variant: string | null+ trigger: NudgeTrigger+}++export const maxWebAnalyticsNudgeLogic = kea<maxWebAnalyticsNudgeLogicType>([+ path(['scenes', 'max', 'logics', 'maxWebAnalyticsNudgeLogic']),+ props({} as MaxWebAnalyticsNudgeLogicProps),+ key((props) => props.messageId),++ connect(() => ({+ values: [+ featureFlagLogic,+ ['featureFlags'],+ recentItemsModel,+ ['sceneLogViewsByRef', 'sceneLogViewsHasLoaded'],+ maxWebAnalyticsNudgeSessionLogic,+ ['shownForMessageId', 'dismissedThisSession', 'eligibleReportedThisSession'],+ ],+ actions: [maxWebAnalyticsNudgeSessionLogic, ['markNudgeShown', 'markNudgeDismissed', 'markEligibleReported']],+ })),++ actions({+ nudgeClicked: true,+ nudgeDismissed: true,+ evaluateReporting: true,+ }),++ selectors({+ variant: [+ (s) => [s.featureFlags],+ (featureFlags): string | null => {+ const value = featureFlags[FEATURE_FLAGS.MAX_WEB_ANALYTICS_NUDGE]+ return typeof value === 'string' ? value : null+ },+ ],+ finalAnswerGroup: [+ (_s, p) => [p.threadGrouped],+ (threadGrouped: ThreadMessage[]): ThreadMessage[] => getFinalAnswerGroup(threadGrouped),+ ],+ lastHumanQuestion: [+ (_s, p) => [p.threadGrouped],+ (threadGrouped: ThreadMessage[]): string | null =>+ (threadGrouped.filter(isHumanMessage).pop() as HumanMessage | undefined)?.content ?? null,+ ],+ groupHasWebChart: [+ (s) => [s.finalAnswerGroup],+ (finalAnswerGroup: ThreadMessage[]): boolean => finalAnswerGroup.some(isWebAnalyticsRelatedMessage),+ ],+ topicIsWebAnalytics: [+ (_s, p) => [p.conversationTopic],+ (conversationTopic: ConversationTopic | null): boolean => conversationTopic === 'web_analytics',+ ],+ trigger: [+ (s) => [s.topicIsWebAnalytics, s.groupHasWebChart],+ (topicIsWebAnalytics: boolean, groupHasWebChart: boolean): NudgeTrigger =>+ topicIsWebAnalytics ? 'topic' : groupHasWebChart ? 'chart' : 'question',+ ],+ isWebAnalyticsAnswer: [+ (s) => [s.topicIsWebAnalytics, s.groupHasWebChart, s.lastHumanQuestion],+ (topicIsWebAnalytics: boolean, groupHasWebChart: boolean, lastHumanQuestion: string | null): boolean =>+ topicIsWebAnalytics || groupHasWebChart || isWebAnalyticsRelatedQuestion(lastHumanQuestion),+ ],+ visitedWebAnalyticsRecently: [+ (s) => [s.sceneLogViewsByRef],+ (sceneLogViewsByRef: Record<string, string>): boolean => {+ const cutoff = dayjs().subtract(WEB_ANALYTICS_RECENT_DAYS, 'days')+ return WEB_ANALYTICS_SCENE_REFS.some((ref) => {+ const viewedAt = sceneLogViewsByRef[ref]+ return !!viewedAt && dayjs(viewedAt).isAfter(cutoff)+ })+ },+ ],+ isEligible: [+ (s, p) => [+ s.isWebAnalyticsAnswer,+ s.visitedWebAnalyticsRecently,+ s.sceneLogViewsHasLoaded,+ p.isCompleted,+ p.isSharedThread,+ ],+ (+ isWebAnalyticsAnswer: boolean,+ visitedRecently: boolean,+ sceneLogViewsHasLoaded: boolean,+ isCompleted: boolean,+ isSharedThread: boolean+ ): boolean =>+ isWebAnalyticsAnswer && !visitedRecently && sceneLogViewsHasLoaded && isCompleted && !isSharedThread,+ ],+ shouldShowNudge: [+ (s, p) => [s.isEligible, s.variant, s.dismissedThisSession, s.shownForMessageId, p.messageId],+ (+ isEligible: boolean,+ variant: string | null,+ dismissed: boolean,+ shownForMessageId: string | null,+ messageId: string+ ): boolean =>+ isEligible &&+ variant === 'test' &&+ !dismissed &&+ (shownForMessageId === null || shownForMessageId === messageId),+ ],+ reportProperties: [+ (s, p) => [s.variant, s.trigger, p.conversationId, p.messageId],+ (+ variant: string | null,+ trigger: NudgeTrigger,+ conversationId: string | null,+ messageId: string+ ): NudgeReportProperties => ({+ conversation_id: conversationId,+ message_id: messageId,+ variant,+ trigger,+ }),+ ],+ }),++ listeners(({ props, values, actions }) => ({+ nudgeClicked: () => {+ posthog.capture('posthog ai web analytics nudge clicked', values.reportProperties)+ // Move the chat into the side panel so it survives navigating away to web analytics.+ maxGlobalLogic.findMounted()?.actions.openSidePanelMax(props.conversationId ?? undefined)+ router.actions.push(urls.webAnalytics(), { utm_source: 'posthog-ai-nudge' })+ },+ nudgeDismissed: () => {+ posthog.capture('posthog ai web analytics nudge dismissed', values.reportProperties)+ actions.markNudgeDismissed()+ },+ evaluateReporting: () => {+ if (+ values.isEligible &&+ !values.eligibleReportedThisSession &&+ (values.variant === 'control' || values.variant === 'test')+ ) {+ actions.markEligibleReported()+ posthog.capture('posthog ai web analytics nudge eligible', values.reportProperties)+ }+ if (values.shouldShowNudge && values.shownForMessageId === null) {+ actions.markNudgeShown(props.messageId)+ posthog.capture('posthog ai web analytics nudge shown', values.reportProperties)+ }+ },+ })),++ subscriptions(({ actions }) => ({+ isEligible: () => actions.evaluateReporting(),+ shouldShowNudge: () => actions.evaluateReporting(),+ })),++ afterMount(({ actions }) => {+ actions.evaluateReporting()+ }),+])diff --git a/frontend/src/scenes/max/logics/maxWebAnalyticsNudgeSessionLogic.ts b/frontend/src/scenes/max/logics/maxWebAnalyticsNudgeSessionLogic.tsnew file mode 100644index 000000000000..ec9538fd5ef1--- /dev/null+++ b/frontend/src/scenes/max/logics/maxWebAnalyticsNudgeSessionLogic.ts@@ -0,0 +1,95 @@+import { actions, afterMount, kea, listeners, path, reducers } from 'kea'++import { permanentlyMount } from 'lib/utils/kea-logic-builders'++import type { maxWebAnalyticsNudgeSessionLogicType } from './maxWebAnalyticsNudgeSessionLogicType'++const STORAGE_KEY = 'posthog-ai-web-analytics-nudge-session'++export interface NudgeSessionState {+ shownForMessageId: string | null+ dismissed: boolean+ eligibleReported: boolean+}++const EMPTY_STATE: NudgeSessionState = {+ shownForMessageId: null,+ dismissed: false,+ eligibleReported: false,+}++function readState(): NudgeSessionState {+ try {+ const raw = window.sessionStorage.getItem(STORAGE_KEY)+ if (!raw) {+ return EMPTY_STATE+ }+ return { ...EMPTY_STATE, ...(JSON.parse(raw) as Partial<NudgeSessionState>) }+ } catch {+ return EMPTY_STATE+ }+}++function writeState(state: NudgeSessionState): void {+ try {+ window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(state))+ } catch {+ return+ }+}++export const maxWebAnalyticsNudgeSessionLogic = kea<maxWebAnalyticsNudgeSessionLogicType>([+ path(['scenes', 'max', 'logics', 'maxWebAnalyticsNudgeSessionLogic']),++ actions({+ markNudgeShown: (messageId: string) => ({ messageId }),+ markNudgeDismissed: true,+ markEligibleReported: true,+ hydrateFromStorage: (state: NudgeSessionState) => ({ state }),+ }),++ reducers({+ shownForMessageId: [+ null as string | null,+ {+ markNudgeShown: (_, { messageId }) => messageId,+ hydrateFromStorage: (_, { state }) => state.shownForMessageId,+ },+ ],+ dismissedThisSession: [+ false,+ {+ markNudgeDismissed: () => true,+ hydrateFromStorage: (_, { state }) => state.dismissed,+ },+ ],+ eligibleReportedThisSession: [+ false,+ {+ markEligibleReported: () => true,+ hydrateFromStorage: (_, { state }) => state.eligibleReported,+ },+ ],+ }),++ listeners(({ values }) => {+ const persist = (): void => {+ writeState({+ shownForMessageId: values.shownForMessageId,+ dismissed: values.dismissedThisSession,+ eligibleReported: values.eligibleReportedThisSession,+ })+ }+ return {+ markNudgeShown: persist,+ markNudgeDismissed: persist,+ markEligibleReported: persist,+ }+ }),++ afterMount(({ actions }) => {+ actions.hydrateFromStorage(readState())+ }),++ permanentlyMount(),+])diff --git a/frontend/src/scenes/max/utils/detectWebAnalyticsQuery.test.ts b/frontend/src/scenes/max/utils/detectWebAnalyticsQuery.test.tsnew file mode 100644index 000000000000..235296a07ee1--- /dev/null+++ b/frontend/src/scenes/max/utils/detectWebAnalyticsQuery.test.ts@@ -0,0 +1,203 @@+import { AssistantMessageType } from '~/queries/schema/schema-assistant-messages'+import { NodeKind } from '~/queries/schema/schema-general'+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'++import { ThreadMessage } from '../maxThreadLogic'+import {+ isWebAnalyticsRelatedMessage,+ isWebAnalyticsRelatedQuery,+ isWebAnalyticsRelatedQuestion,+} from './detectWebAnalyticsQuery'++const pageviewTrends = {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],+} as any++const referrerBreakdownTrends = {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: 'click' }],+ breakdownFilter: { breakdown: '$referring_domain' },+} as any++const currentUrlPropertyTrends = {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: 'click' }],+ properties: [+ {+ key: '$current_url',+ type: PropertyFilterType.Event,+ operator: PropertyOperator.IContains,+ value: 'pricing',+ },+ ],+} as any++const nestedUtmGroupTrends = {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: 'click' }],+ properties: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.Or,+ values: [+ {+ key: 'utm_source',+ type: PropertyFilterType.Event,+ operator: PropertyOperator.Exact,+ value: 'google',+ },+ ],+ },+ ],+ },+} as any++const pageviewPaths = {+ kind: NodeKind.PathsQuery,+ pathsFilter: { includeEventTypes: ['$pageview'] },+} as any++const insightVizWrappingPageview = {+ kind: NodeKind.InsightVizNode,+ source: pageviewTrends,+} as any++const dataVizWithPathname = {+ kind: NodeKind.DataVisualizationNode,+ source: {+ kind: NodeKind.HogQLQuery,+ query: "SELECT count() FROM events WHERE properties.$pathname = '/home'",+ },+} as any++const webOverviewQuery = { kind: NodeKind.WebOverviewQuery } as any++const nonWebTrends = {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: 'signed_up' }],+ properties: [+ {+ key: 'plan',+ type: PropertyFilterType.Event,+ operator: PropertyOperator.Exact,+ value: 'pro',+ },+ ],+} as any++const nonWebFunnel = {+ kind: NodeKind.FunnelsQuery,+ series: [+ { kind: NodeKind.EventsNode, event: 'signed_up' },+ { kind: NodeKind.EventsNode, event: 'activated' },+ ],+} as any++describe('detectWebAnalyticsQuery', () => {+ describe('isWebAnalyticsRelatedQuery', () => {+ it.each([+ ['pageview trends series', pageviewTrends],+ ['referring_domain breakdown', referrerBreakdownTrends],+ ['current_url property filter', currentUrlPropertyTrends],+ ['nested utm_source property group', nestedUtmGroupTrends],+ ['pageview paths includeEventTypes', pageviewPaths],+ ['insightVizNode wrapping pageview trends', insightVizWrappingPageview],+ ['dataVisualizationNode with $pathname sql', dataVizWithPathname],+ ['bare WebOverviewQuery', webOverviewQuery],+ ])('returns true for %s', (_label, query) => {+ expect(isWebAnalyticsRelatedQuery(query)).toBe(true)+ })++ it.each([+ ['non-web trends', nonWebTrends],+ ['non-web funnel', nonWebFunnel],+ ['null', null],+ ['undefined', undefined],+ ['malformed empty object', {} as any],+ ])('returns false for %s', (_label, query) => {+ expect(isWebAnalyticsRelatedQuery(query)).toBe(false)+ })++ it('does not throw on deeply malformed input', () => {+ const malformed = { kind: NodeKind.TrendsQuery, series: [{ kind: NodeKind.GroupNode }] } as any+ expect(() => isWebAnalyticsRelatedQuery(malformed)).not.toThrow()+ expect(isWebAnalyticsRelatedQuery(malformed)).toBe(false)+ })+ })++ describe('isWebAnalyticsRelatedQuestion', () => {+ it.each([+ 'where is my traffic coming from?',+ 'show me pageviews',+ 'what is my bounce rate',+ 'top pages last week',+ ])('returns true for %s', (text) => {+ expect(isWebAnalyticsRelatedQuestion(text)).toBe(true)+ })++ it.each([+ 'how many users signed up?',+ 'revenue by month',+ 'how did our email campaign perform?',+ 'did users visit the new onboarding flow?',+ '',+ ])('returns false for %s', (text) => {+ expect(isWebAnalyticsRelatedQuestion(text)).toBe(false)+ })++ it.each([null, undefined])('returns false for nullish input', (text) => {+ expect(isWebAnalyticsRelatedQuestion(text)).toBe(false)+ })+ })++ describe('isWebAnalyticsRelatedMessage', () => {+ it('returns true for an artifact visualization with a web analytics related query', () => {+ const message = {+ type: AssistantMessageType.Artifact,+ content: {+ content_type: 'visualization',+ query: pageviewTrends,+ },+ } as any as ThreadMessage+ expect(isWebAnalyticsRelatedMessage(message)).toBe(true)+ })++ it('returns true for a multi-visualization where one viz is web analytics related', () => {+ const message = {+ type: AssistantMessageType.MultiVisualization,+ visualizations: [+ { query: '', answer: nonWebTrends },+ { query: '', answer: pageviewTrends },+ ],+ } as any as ThreadMessage+ expect(isWebAnalyticsRelatedMessage(message)).toBe(true)+ })++ it('returns true for a legacy visualization message with a web analytics related answer', () => {+ const message = {+ type: AssistantMessageType.Visualization,+ query: '',+ answer: pageviewTrends,+ } as any as ThreadMessage+ expect(isWebAnalyticsRelatedMessage(message)).toBe(true)+ })++ it('returns false for a plain assistant text message', () => {+ const message = {+ type: AssistantMessageType.Assistant,+ content: 'Here is your answer',+ } as any as ThreadMessage+ expect(isWebAnalyticsRelatedMessage(message)).toBe(false)+ })++ it('returns false for a multi-visualization with no web signals', () => {+ const message = {+ type: AssistantMessageType.MultiVisualization,+ visualizations: [{ query: '', answer: nonWebTrends }],+ } as any as ThreadMessage+ expect(isWebAnalyticsRelatedMessage(message)).toBe(false)+ })+ })+})diff --git a/frontend/src/scenes/max/utils/detectWebAnalyticsQuery.ts b/frontend/src/scenes/max/utils/detectWebAnalyticsQuery.tsnew file mode 100644index 000000000000..dea17aaa6c60--- /dev/null+++ b/frontend/src/scenes/max/utils/detectWebAnalyticsQuery.ts@@ -0,0 +1,289 @@+import { BreakdownFilter, EventsNode, GroupNode, QuerySchema, TrendsQuery } from '~/queries/schema/schema-general'+import {+ isActionsNode,+ isDataVisualizationNode,+ isEventsNode,+ isFunnelsQuery,+ isGroupNode,+ isHogQLQuery,+ isInsightVizNode,+ isLifecycleQuery,+ isPathsQuery,+ isRetentionQuery,+ isStickinessQuery,+ isTrendsQuery,+ isWebGoalsQuery,+ isWebOverviewQuery,+ isWebStatsTableQuery,+ isWebVitalsPathBreakdownQuery,+ isWebVitalsQuery,+} from '~/queries/utils'+import { AnyPropertyFilter, PropertyGroupFilter, PropertyGroupFilterValue, RetentionEntity } from '~/types'++import { ThreadMessage } from '../maxThreadLogic'+import {+ isArtifactMessage,+ isMultiVisualizationMessage,+ isVisualizationArtifactContent,+ visualizationTypeToQuery,+} from '../utils'++const SIGNAL_EVENTS: ReadonlySet<string> = new Set(['$pageview', '$pageleave', '$screen', '$web_vitals'])++const SIGNAL_PROPERTY_KEYS: ReadonlySet<string> = new Set([+ '$pathname',+ '$current_url',+ '$host',+ '$referrer',+ '$referring_domain',+ 'utm_source',+ 'utm_medium',+ 'utm_campaign',+ 'utm_content',+ 'utm_term',+ '$geoip_country_code',+ '$geoip_country_name',+ '$geoip_city_name',+ '$geoip_subdivision_1_name',+ '$geoip_continent_code',+ '$browser',+ '$browser_version',+ '$os',+ '$os_version',+ '$device_type',+ '$screen_height',+ '$screen_width',+ '$channel_type',+ '$entry_pathname',+ '$entry_referring_domain',+ '$entry_utm_source',+ '$session_entry_url',+ '$web_vitals_LCP_value',+ '$web_vitals_FCP_value',+ '$web_vitals_CLS_value',+ '$web_vitals_INP_value',+])++const QUESTION_KEYWORDS: readonly string[] = [+ 'web analytics',+ 'traffic',+ 'website',+ 'visitors',+ 'unique visitor',+ 'pageview',+ 'page view',+ 'bounce rate',+ 'session duration',+ 'traffic source',+ 'referrer',+ 'referring domain',+ 'utm',+ 'marketing campaign',+ 'channel',+ 'web vitals',+ 'core web vitals',+ 'top pages',+ 'landing page',+ 'entry page',+ 'exit page',+ 'marketing analytics',+]++const MAX_DEPTH = 6++function isSignalEvent(value: string | null | undefined): boolean {+ return !!value && SIGNAL_EVENTS.has(value)+}++function isSignalPropertyKey(key: unknown): boolean {+ return typeof key === 'string' && SIGNAL_PROPERTY_KEYS.has(key)+}++function hogQLStringHasSignal(sql: string): boolean {+ for (const key of SIGNAL_PROPERTY_KEYS) {+ if (sql.includes(key)) {+ return true+ }+ }+ for (const event of SIGNAL_EVENTS) {+ if (sql.includes(event)) {+ return true+ }+ }+ return false+}++function propertyFilterHasSignal(filter: AnyPropertyFilter): boolean {+ return isSignalPropertyKey((filter as { key?: unknown }).key)+}++function propertiesHaveSignal(+ properties: AnyPropertyFilter[] | PropertyGroupFilter | PropertyGroupFilterValue | undefined | null,+ depth: number+): boolean {+ if (!properties || depth > MAX_DEPTH) {+ return false+ }+ if (Array.isArray(properties)) {+ return properties.some((filter) => propertyFilterHasSignal(filter))+ }+ const values = (properties as PropertyGroupFilter | PropertyGroupFilterValue).values+ if (!Array.isArray(values)) {+ return false+ }+ return values.some((value) => {+ if (value && typeof value === 'object' && 'values' in value && Array.isArray(value.values)) {+ return propertiesHaveSignal(value as PropertyGroupFilterValue, depth + 1)+ }+ return propertyFilterHasSignal(value as AnyPropertyFilter)+ })+}++function entityHasSignal(+ entity: EventsNode | GroupNode | { event?: string | null; name?: string },+ depth: number+): boolean {+ if (depth > MAX_DEPTH) {+ return false+ }+ if (isGroupNode(entity)) {+ return entity.nodes?.some((node) => entityHasSignal(node, depth + 1)) ?? false+ }+ if (isEventsNode(entity) && (isSignalEvent(entity.event) || isSignalEvent(entity.name))) {+ return true+ }+ if (isActionsNode(entity) && isSignalEvent(entity.name)) {+ return true+ }+ const node = entity as EventsNode+ return propertiesHaveSignal(node.properties, depth + 1) || propertiesHaveSignal(node.fixedProperties, depth + 1)+}++function seriesHasSignal(series: TrendsQuery['series'] | undefined): boolean {+ return series?.some((entity) => entityHasSignal(entity, 0)) ?? false+}++function breakdownHasSignal(breakdownFilter: BreakdownFilter | undefined): boolean {+ if (!breakdownFilter) {+ return false+ }+ const { breakdown, breakdowns } = breakdownFilter+ if (Array.isArray(breakdown)) {+ if (breakdown.some((value) => isSignalPropertyKey(value))) {+ return true+ }+ } else if (isSignalPropertyKey(breakdown)) {+ return true+ }+ return breakdowns?.some((entry) => isSignalPropertyKey(entry?.property)) ?? false+}++function retentionEntityHasSignal(entity: RetentionEntity | undefined): boolean {+ if (!entity) {+ return false+ }+ return isSignalEvent(typeof entity.id === 'string' ? entity.id : undefined) || isSignalEvent(entity.name)+}++function insightQueryHasSignal(query: QuerySchema): boolean {+ const base = query as TrendsQuery+ if (seriesHasSignal(base.series)) {+ return true+ }+ if (propertiesHaveSignal(base.properties, 0)) {+ return true+ }+ if (breakdownHasSignal(base.breakdownFilter)) {+ return true+ }+ if (isRetentionQuery(query)) {+ if (+ retentionEntityHasSignal(query.retentionFilter?.targetEntity) ||+ retentionEntityHasSignal(query.retentionFilter?.returningEntity)+ ) {+ return true+ }+ }+ if (isPathsQuery(query)) {+ const pathsFilter = query.pathsFilter+ if (pathsFilter?.includeEventTypes?.some((eventType) => eventType === '$pageview')) {+ return true+ }+ if (pathsFilter?.pathsHogQLExpression && hogQLStringHasSignal(pathsFilter.pathsHogQLExpression)) {+ return true+ }+ }+ return false+}++function queryHasSignal(query: QuerySchema): boolean {+ if (+ isWebOverviewQuery(query) ||+ isWebStatsTableQuery(query) ||+ isWebGoalsQuery(query) ||+ isWebVitalsQuery(query) ||+ isWebVitalsPathBreakdownQuery(query)+ ) {+ return true+ }+ if (isInsightVizNode(query)) {+ const source = query.source+ return !!source && queryHasSignal(source as QuerySchema)+ }+ if (isDataVisualizationNode(query)) {+ const sql = query.source?.query+ return typeof sql === 'string' && hogQLStringHasSignal(sql)+ }+ if (isHogQLQuery(query)) {+ return typeof query.query === 'string' && hogQLStringHasSignal(query.query)+ }+ if (+ isTrendsQuery(query) ||+ isFunnelsQuery(query) ||+ isRetentionQuery(query) ||+ isLifecycleQuery(query) ||+ isStickinessQuery(query) ||+ isPathsQuery(query)+ ) {+ return insightQueryHasSignal(query)+ }+ return false+}++export function isWebAnalyticsRelatedQuestion(text: string | null | undefined): boolean {+ if (!text) {+ return false+ }+ const lowered = text.toLowerCase()+ return QUESTION_KEYWORDS.some((keyword) => lowered.includes(keyword))+}++export function isWebAnalyticsRelatedQuery(query: QuerySchema | null | undefined): boolean {+ if (!query) {+ return false+ }+ try {+ return queryHasSignal(query)+ } catch {+ return false+ }+}++export function isWebAnalyticsRelatedMessage(message: ThreadMessage): boolean {+ try {+ if (isArtifactMessage(message) && isVisualizationArtifactContent(message.content)) {+ return isWebAnalyticsRelatedQuery(visualizationTypeToQuery(message.content))+ }+ if (isMultiVisualizationMessage(message)) {+ return message.visualizations.some((viz) => isWebAnalyticsRelatedQuery(visualizationTypeToQuery(viz)))+ }+ if ('answer' in message) {+ return isWebAnalyticsRelatedQuery(+ visualizationTypeToQuery(message as Parameters<typeof visualizationTypeToQuery>[0])+ )+ }+ return false+ } catch {+ return false+ }+}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 88dda083c963..91883d48d590 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -7041,11 +7041,24 @@ export interface ConversationQueueResponse {max_queue_messages: number}+export type ConversationTopic =+ | 'web_analytics'+ | 'product_analytics'+ | 'session_replay'+ | 'surveys'+ | 'feature_flags'+ | 'experiments'+ | 'error_tracking'+ | 'data_warehouse'+ | 'other'+export interface Conversation {id: stringuser: UserBasicTypestatus: ConversationStatustitle: string | null+ /** Product domain classified from the first question; drives contextual nudges. */+ topic?: ConversationTopic | nullcreated_at: string | nullupdated_at: string | nulltype: ConversationTypediff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 72269effcc75..6f2d990ac0b4 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -20,6 +20,31 @@ export const ConversationStatusApi = {Canceling: 'canceling',} as const+/**+ * * `web_analytics` - Web analytics+ * * `product_analytics` - Product analytics+ * * `session_replay` - Session replay+ * * `surveys` - Surveys+ * * `feature_flags` - Feature flags+ * * `experiments` - Experiments+ * * `error_tracking` - Error tracking+ * * `data_warehouse` - Data warehouse+ * * `other` - Other+ */+export type TopicEnumApi = (typeof TopicEnumApi)[keyof typeof TopicEnumApi]++export const TopicEnumApi = {+ WebAnalytics: 'web_analytics',+ ProductAnalytics: 'product_analytics',+ SessionReplay: 'session_replay',+ Surveys: 'surveys',+ FeatureFlags: 'feature_flags',+ Experiments: 'experiments',+ ErrorTracking: 'error_tracking',+ DataWarehouse: 'data_warehouse',+ Other: 'other',+} as const+/*** * `engineering` - Engineering* * `data` - Data@@ -98,6 +123,18 @@ export interface ConversationMinimalApi {* @nullable*/readonly title: string | null+ /** Product domain the conversation is about, classified from the first question.+ *+ * * `web_analytics` - Web analytics+ * * `product_analytics` - Product analytics+ * * `session_replay` - Session replay+ * * `surveys` - Surveys+ * * `feature_flags` - Feature flags+ * * `experiments` - Experiments+ * * `error_tracking` - Error tracking+ * * `data_warehouse` - Data warehouse+ * * `other` - Other */+ readonly topic: TopicEnumApi | nullreadonly user: UserBasicApi/** @nullable */readonly created_at: string | null@@ -197,6 +234,18 @@ export interface ConversationApi {* @nullable*/readonly title: string | null+ /** Product domain the conversation is about, classified from the first question.+ *+ * * `web_analytics` - Web analytics+ * * `product_analytics` - Product analytics+ * * `session_replay` - Session replay+ * * `surveys` - Surveys+ * * `feature_flags` - Feature flags+ * * `experiments` - Experiments+ * * `error_tracking` - Error tracking+ * * `data_warehouse` - Data warehouse+ * * `other` - Other */+ readonly topic: TopicEnumApi | nullreadonly user: UserBasicApi/** @nullable */readonly created_at: string | null@@ -250,6 +299,18 @@ export interface PatchedConversationApi {* @nullable*/readonly title?: string | null+ /** Product domain the conversation is about, classified from the first question.+ *+ * * `web_analytics` - Web analytics+ * * `product_analytics` - Product analytics+ * * `session_replay` - Session replay+ * * `surveys` - Surveys+ * * `feature_flags` - Feature flags+ * * `experiments` - Experiments+ * * `error_tracking` - Error tracking+ * * `data_warehouse` - Data warehouse+ * * `other` - Other */+ readonly topic?: TopicEnumApi | nullreadonly user?: UserBasicApi/** @nullable */readonly created_at?: string | nulldiff --git a/products/posthog_ai/backend/migrations/0003_conversation_topic.py b/products/posthog_ai/backend/migrations/0003_conversation_topic.pynew file mode 100644index 000000000000..ac8234f1a996--- /dev/null+++ b/products/posthog_ai/backend/migrations/0003_conversation_topic.py@@ -0,0 +1,33 @@+# Generated by Django 5.2.14 on 2026-06-05 21:24++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog_ai", "0002_migrate_posthog_ai_models"),+ ]++ operations = [+ migrations.AddField(+ model_name="conversation",+ name="topic",+ field=models.CharField(+ blank=True,+ choices=[+ ("web_analytics", "Web analytics"),+ ("product_analytics", "Product analytics"),+ ("session_replay", "Session replay"),+ ("surveys", "Surveys"),+ ("feature_flags", "Feature flags"),+ ("experiments", "Experiments"),+ ("error_tracking", "Error tracking"),+ ("data_warehouse", "Data warehouse"),+ ("other", "Other"),+ ],+ help_text="Product domain the conversation is about, classified from the first question.",+ max_length=64,+ null=True,+ ),+ ),+ ]diff --git a/products/posthog_ai/backend/migrations/max_migration.txt b/products/posthog_ai/backend/migrations/max_migration.txtindex e249f03108e9..5e8f520ca572 100644--- a/products/posthog_ai/backend/migrations/max_migration.txt+++ b/products/posthog_ai/backend/migrations/max_migration.txt@@ -1 +1 @@-0002_migrate_posthog_ai_models+0003_conversation_topicdiff --git a/products/posthog_ai/backend/models/assistant.py b/products/posthog_ai/backend/models/assistant.pyindex deba504ebed1..484b57bf768f 100644--- a/products/posthog_ai/backend/models/assistant.py+++ b/products/posthog_ai/backend/models/assistant.py@@ -46,6 +46,19 @@ class Conversation(UUIDTModel, DeletedMetaFields):DEEP_RESEARCH = "deep_research", "Deep research"SLACK = "slack", "Slack"+ class Topic(models.TextChoices):+ """Product domain a conversation is about, classified from the first question (see title generator)."""++ WEB_ANALYTICS = "web_analytics", "Web analytics"+ PRODUCT_ANALYTICS = "product_analytics", "Product analytics"+ SESSION_REPLAY = "session_replay", "Session replay"+ SURVEYS = "surveys", "Surveys"+ FEATURE_FLAGS = "feature_flags", "Feature flags"+ EXPERIMENTS = "experiments", "Experiments"+ ERROR_TRACKING = "error_tracking", "Error tracking"+ DATA_WAREHOUSE = "data_warehouse", "Data warehouse"+ OTHER = "other", "Other"+user = models.ForeignKey(User, on_delete=models.CASCADE)team = models.ForeignKey(Team, on_delete=models.CASCADE)created_at = models.DateTimeField(auto_now_add=True, null=True)@@ -58,6 +71,13 @@ class Conversation(UUIDTModel, DeletedMetaFields):help_text="Title of the conversation.",max_length=TITLE_MAX_LENGTH,)+ topic = models.CharField(+ null=True,+ blank=True,+ choices=Topic,+ max_length=64,+ help_text="Product domain the conversation is about, classified from the first question.",+ )is_internal = models.BooleanField(null=True,default=False,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 866a4ca9e79b..e64d7b15c06f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -11516,6 +11516,32 @@ export namespace Schemas {Canceling: 'canceling',} as const;+ /**+ * * `web_analytics` - Web analytics+ * * `product_analytics` - Product analytics+ * * `session_replay` - Session replay+ * * `surveys` - Surveys+ * * `feature_flags` - Feature flags+ * * `experiments` - Experiments+ * * `error_tracking` - Error tracking+ * * `data_warehouse` - Data warehouse+ * * `other` - Other+ */+ export type TopicEnum = typeof TopicEnum[keyof typeof TopicEnum];+++ export const TopicEnum = {+ WebAnalytics: 'web_analytics',+ ProductAnalytics: 'product_analytics',+ SessionReplay: 'session_replay',+ Surveys: 'surveys',+ FeatureFlags: 'feature_flags',+ Experiments: 'experiments',+ ErrorTracking: 'error_tracking',+ DataWarehouse: 'data_warehouse',+ Other: 'other',+ } as const;+/*** * `assistant` - Assistant* * `tool_call` - Tool call@@ -11540,6 +11566,18 @@ export namespace Schemas {* @nullable*/readonly title: string | null;+ /** Product domain the conversation is about, classified from the first question.+ *+ * * `web_analytics` - Web analytics+ * * `product_analytics` - Product analytics+ * * `session_replay` - Session replay+ * * `surveys` - Surveys+ * * `feature_flags` - Feature flags+ * * `experiments` - Experiments+ * * `error_tracking` - Error tracking+ * * `data_warehouse` - Data warehouse+ * * `other` - Other */+ readonly topic: TopicEnum | null;readonly user: UserBasic;/** @nullable */readonly created_at: string | null;@@ -11581,6 +11619,18 @@ export namespace Schemas {* @nullable*/readonly title: string | null;+ /** Product domain the conversation is about, classified from the first question.+ *+ * * `web_analytics` - Web analytics+ * * `product_analytics` - Product analytics+ * * `session_replay` - Session replay+ * * `surveys` - Surveys+ * * `feature_flags` - Feature flags+ * * `experiments` - Experiments+ * * `error_tracking` - Error tracking+ * * `data_warehouse` - Data warehouse+ * * `other` - Other */+ readonly topic: TopicEnum | null;readonly user: UserBasic;/** @nullable */readonly created_at: string | null;@@ -29083,6 +29133,18 @@ export namespace Schemas {* @nullable*/readonly title?: string | null;+ /** Product domain the conversation is about, classified from the first question.+ *+ * * `web_analytics` - Web analytics+ * * `product_analytics` - Product analytics+ * * `session_replay` - Session replay+ * * `surveys` - Surveys+ * * `feature_flags` - Feature flags+ * * `experiments` - Experiments+ * * `error_tracking` - Error tracking+ * * `data_warehouse` - Data warehouse+ * * `other` - Other */+ readonly topic?: TopicEnum | null;readonly user?: UserBasic;/** @nullable */readonly created_at?: string | null;