: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(posthog-ai): Add Customer analytics agent mode (#62472)
Arthur Moreira de Deus6fc891984d1b
diff --git a/ee/hogai/chat_agent/mode_manager.py b/ee/hogai/chat_agent/mode_manager.pyindex a3fc34cd86a6..c23a4e441a52 100644--- a/ee/hogai/chat_agent/mode_manager.py+++ b/ee/hogai/chat_agent/mode_manager.py@@ -18,6 +18,7 @@ from ee.hogai.core.agent_modes.presets.ai_observability import (ai_observability_agent,chat_agent_plan_ai_observability_agent,)+from ee.hogai.core.agent_modes.presets.customer_analytics import customer_analytics_agentfrom ee.hogai.core.agent_modes.presets.error_tracking import chat_agent_plan_error_tracking_agent, error_tracking_agentfrom ee.hogai.core.agent_modes.presets.flags import chat_agent_plan_flags_agent, flags_agentfrom ee.hogai.core.agent_modes.presets.product_analytics import (@@ -35,7 +36,11 @@ from ee.hogai.core.agent_modes.presets.user_interview import ()from ee.hogai.core.agent_modes.prompt_builder import AgentPromptBuilderfrom ee.hogai.core.agent_modes.toolkit import AgentToolkit, AgentToolkitManager-from ee.hogai.utils.feature_flags import has_plan_mode_feature_flag, has_user_interview_mode_feature_flag+from ee.hogai.utils.feature_flags import (+ has_customer_analytics_mode_feature_flag,+ has_plan_mode_feature_flag,+ has_user_interview_mode_feature_flag,+)from ee.hogai.utils.types.base import AssistantState, NodePath# Execution and plan mode definitions - fictitious modes used to trigger transition in and out of plan mode@@ -99,6 +104,8 @@ def get_execution_mode_registry(team: Team, user: User) -> dict[AgentMode, Agentregistry = dict(DEFAULT_CHAT_AGENT_MODE_REGISTRY)if has_user_interview_mode_feature_flag(team, user):registry[AgentMode.USER_INTERVIEW] = user_interview_agent+ if has_customer_analytics_mode_feature_flag(team, user):+ registry[AgentMode.CUSTOMER_ANALYTICS] = customer_analytics_agentreturn registrydiff --git a/ee/hogai/chat_agent/test/test_mode_manager.py b/ee/hogai/chat_agent/test/test_mode_manager.pyindex a49c5e8865c0..9960ca1e5368 100644--- a/ee/hogai/chat_agent/test/test_mode_manager.py+++ b/ee/hogai/chat_agent/test/test_mode_manager.py@@ -233,6 +233,32 @@ class TestAgentToolkit(BaseTest):for unexpected in unexpected_modes:self.assertNotIn(unexpected, mode_names)+ @parameterized.expand(+ [+ # (customer_analytics_flag, should_be_present)+ [False, False],+ [True, True],+ ]+ )+ def test_mode_registry_gates_customer_analytics_on_feature_flag(self, flag_on, should_be_present):+ with patch("ee.hogai.chat_agent.mode_manager.has_customer_analytics_mode_feature_flag", return_value=flag_on):+ node_path = (NodePath(name=AssistantNodeName.ROOT, message_id="test_id", tool_call_id="test_tool_call_id"),)+ context_manager = AssistantContextManager(+ team=self.team, user=self.user, config=RunnableConfig(configurable={})+ )+ mode_manager = ChatAgentModeManager(+ team=self.team,+ user=self.user,+ node_path=node_path,+ context_manager=context_manager,+ state=AssistantState(messages=[HumanMessage(content="Test")]),+ )+ mode_names = [mode.value for mode in mode_manager.mode_registry.keys()]+ if should_be_present:+ self.assertIn("customer_analytics", mode_names)+ else:+ self.assertNotIn("customer_analytics", mode_names)+@parameterized.expand([# (plan_mode_flag, should_contain_plan_prompt)diff --git a/ee/hogai/context/account/__init__.py b/ee/hogai/context/account/__init__.pynew file mode 100644index 000000000000..94296af73766--- /dev/null+++ b/ee/hogai/context/account/__init__.py@@ -0,0 +1,3 @@+from .context import AccountContext++__all__ = ["AccountContext"]diff --git a/ee/hogai/context/account/context.py b/ee/hogai/context/account/context.pynew file mode 100644index 000000000000..58146c5451d5--- /dev/null+++ b/ee/hogai/context/account/context.py@@ -0,0 +1,141 @@+from django.core.exceptions import ObjectDoesNotExist, ValidationError++from posthog.models import Team+from posthog.models.group.util import get_group_by_key+from posthog.models.tagged_item import TaggedItem+from posthog.sync import database_sync_to_async++from products.customer_analytics.backend.models import Account+from products.notebooks.backend.models import Notebook, ResourceNotebook++from .prompts import (+ ACCOUNT_ANALYSIS_CONNECTED_TEMPLATE,+ ACCOUNT_ANALYSIS_GROUP_NOT_FOUND_TEMPLATE,+ ACCOUNT_ANALYSIS_NO_EXTERNAL_ID_TEMPLATE,+ ACCOUNT_ANALYSIS_NOT_CONFIGURED_TEMPLATE,+ ACCOUNT_CONTEXT_TEMPLATE,+ ACCOUNT_EXTERNAL_IDS_TEMPLATE,+ ACCOUNT_NOT_FOUND_TEMPLATE,+ ACCOUNT_NOTES_TEMPLATE,+ ACCOUNT_ROLES_TEMPLATE,+ ACCOUNT_TAGS_TEMPLATE,+)++_ROLE_LABELS = [("CSM", "csm"), ("Account executive", "account_executive"), ("Account owner", "account_owner")]+_EXTERNAL_ID_LABELS = [+ ("Stripe customer id", "stripe_customer_id"),+ ("HubSpot deal id", "hubspot_deal_id"),+ ("Billing id", "billing_id"),+ ("Salesforce id", "sfdc_id"),+ ("Zendesk id", "zendesk_id"),+ ("Slack channel id", "slack_channel_id"),+]+++class AccountContext:+ """+ Context class for customer accounts used across the assistant.++ Fetches an account and formats it for AI consumption, resolving the account→group link so the+ agent can scope usage and event analysis to the right group.+ """++ def __init__(self, team: Team, account_id: str | None = None, external_id: str | None = None):+ self._team = team+ self._account_id = account_id+ self._external_id = external_id++ async def aget_account(self) -> Account | None:+ try:+ if self._account_id:+ return await Account.objects.unscoped().aget(id=self._account_id, team=self._team)+ if self._external_id:+ return await Account.objects.unscoped().aget(external_id=self._external_id, team=self._team)+ return None+ except (Account.DoesNotExist, ValidationError, ValueError):+ return None++ def get_not_found_message(self) -> str:+ identifier = f"id={self._account_id}" if self._account_id else f"external_id={self._external_id}"+ return ACCOUNT_NOT_FOUND_TEMPLATE.format(identifier=identifier)++ @database_sync_to_async+ def format_account(self, account: Account) -> str:+ return ACCOUNT_CONTEXT_TEMPLATE.format(+ name=account.name,+ account_id=str(account.id),+ external_id=account.external_id or "Not set",+ created_at=account.created_at.isoformat() if account.created_at else "Unknown",+ roles_section=self._roles_section(account),+ external_ids_section=self._external_ids_section(account),+ tags_section=self._tags_section(account),+ notes_section=self._notes_section(account),+ analysis_section=self._analysis_section(account),+ ).strip()++ async def execute_and_format(self) -> str:+ account = await self.aget_account()+ if account is None:+ return self.get_not_found_message()+ return await self.format_account(account)++ def _roles_section(self, account: Account) -> str:+ properties = account.properties+ lines = [+ f"- {label}: {assignment.email} (user {assignment.id})"+ for label, field in _ROLE_LABELS+ if (assignment := getattr(properties, field)) is not None+ ]+ if not lines:+ return ""+ return "\n" + ACCOUNT_ROLES_TEMPLATE.format(roles_list="\n".join(lines))++ def _external_ids_section(self, account: Account) -> str:+ properties = account.properties+ lines = [f"- {label}: {value}" for label, field in _EXTERNAL_ID_LABELS if (value := getattr(properties, field))]+ if not lines:+ return ""+ return "\n" + ACCOUNT_EXTERNAL_IDS_TEMPLATE.format(ids_list="\n".join(lines))++ def _tags_section(self, account: Account) -> str:+ tags = sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True))+ if not tags:+ return ""+ return "\n" + ACCOUNT_TAGS_TEMPLATE.format(tags_list=", ".join(tags))++ def _notes_section(self, account: Account) -> str:+ links = (+ ResourceNotebook.objects.filter(+ account=account,+ notebook__deleted=False,+ notebook__visibility=Notebook.Visibility.INTERNAL,+ )+ .select_related("notebook")+ .order_by("-notebook__last_modified_at")+ )+ lines = [f'- "{link.notebook.title}" (short_id: {link.notebook.short_id})' for link in links]+ if not lines:+ return ""+ return "\n" + ACCOUNT_NOTES_TEMPLATE.format(notes_list="\n".join(lines))++ def _analysis_section(self, account: Account) -> str:+ group_type_index = self._account_group_type_index()+ if group_type_index is None:+ return ACCOUNT_ANALYSIS_NOT_CONFIGURED_TEMPLATE+ if not account.external_id:+ return ACCOUNT_ANALYSIS_NO_EXTERNAL_ID_TEMPLATE++ group = get_group_by_key(+ team_id=account.team_id, group_type_index=group_type_index, group_key=account.external_id+ )+ if group is None:+ return ACCOUNT_ANALYSIS_GROUP_NOT_FOUND_TEMPLATE.format(group_key=account.external_id)+ return ACCOUNT_ANALYSIS_CONNECTED_TEMPLATE.format(+ group_type_index=group_type_index, group_key=account.external_id+ )++ def _account_group_type_index(self) -> int | None:+ try:+ return self._team.customer_analytics_config.account_group_type_index+ except ObjectDoesNotExist:+ return Nonediff --git a/ee/hogai/context/account/prompts.py b/ee/hogai/context/account/prompts.pynew file mode 100644index 000000000000..ad2cb91e62bd--- /dev/null+++ b/ee/hogai/context/account/prompts.py@@ -0,0 +1,66 @@+ACCOUNT_CONTEXT_TEMPLATE = """+## Account: {name}++**ID:** {account_id}+**External ID:** {external_id}+**Created:** {created_at}+{roles_section}+{external_ids_section}+{tags_section}+{notes_section}++{analysis_section}+""".strip()++ACCOUNT_ROLES_TEMPLATE = """+### Roles+{roles_list}+""".strip()++ACCOUNT_EXTERNAL_IDS_TEMPLATE = """+### External-system ids+{ids_list}+""".strip()++ACCOUNT_TAGS_TEMPLATE = """+### Tags+{tags_list}+""".strip()++ACCOUNT_NOTES_TEMPLATE = """+### Saved notes+{notes_list}+""".strip()++# The analysis section carries the account→group link so it lands in conversation history+# before a switch_mode (which forwards only history). It is fenced and labelled internal so the+# agent uses it to scope analysis without surfacing the raw identifiers to the user.+ACCOUNT_ANALYSIS_CONNECTED_TEMPLATE = """+<account_analysis_context>+For your own analysis only — do not repeat these identifiers to the user.+This account is connected to its product data as group type index {group_type_index}, group key "{group_key}".+To answer questions about its usage, events, or feature flags, switch to product analytics or SQL and scope the analysis to this group. Its usage trends also live in the account's Usage tab in the Accounts list.+</account_analysis_context>+""".strip()++ACCOUNT_ANALYSIS_NO_EXTERNAL_ID_TEMPLATE = """+<account_analysis_context>+This account has no external ID, so it isn't linked to its product data and usage or event questions can't be answered yet. Ask the user to set the account's external ID to the organization's key in product data so it can be connected.+</account_analysis_context>+""".strip()++ACCOUNT_ANALYSIS_NOT_CONFIGURED_TEMPLATE = """+<account_analysis_context>+Customer analytics isn't connected to a group type for this project yet, so this account's usage and event data can't be analyzed. Ask the user to finish setup in Customer analytics > Accounts settings.+</account_analysis_context>+""".strip()++ACCOUNT_ANALYSIS_GROUP_NOT_FOUND_TEMPLATE = """+<account_analysis_context>+This account's external ID "{group_key}" doesn't match any known group in product data, so its usage and event data may be unavailable. Verify the external ID matches the organization's key in product data.+</account_analysis_context>+""".strip()++ACCOUNT_NOT_FOUND_TEMPLATE = """+Account with {identifier} was not found. Verify the account id or external id is correct, or use list_data with the account kind to find it.+""".strip()diff --git a/ee/hogai/context/account/test/__init__.py b/ee/hogai/context/account/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/ee/hogai/context/account/test/test_context.py b/ee/hogai/context/account/test/test_context.pynew file mode 100644index 000000000000..d3fa6576df58--- /dev/null+++ b/ee/hogai/context/account/test/test_context.py@@ -0,0 +1,170 @@+import uuid++from posthog.test.base import NonAtomicBaseTest+from unittest.mock import MagicMock, patch++from django.core.exceptions import ObjectDoesNotExist++from asgiref.sync import sync_to_async++from posthog.api.tagged_item import set_tags_on_object++from products.customer_analytics.backend.models import Account+from products.notebooks.backend.models import Notebook, ResourceNotebook++from ee.hogai.context.account.context import AccountContext+++class TestAccountContext(NonAtomicBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ async def _create_account(self, **kwargs) -> Account:+ return await sync_to_async(Account.objects.unscoped().create)(team=self.team, **kwargs)++ async def test_aget_account_by_id(self):+ account = await self._create_account(name="Acme Corp", external_id="acme-1")++ fetched = await AccountContext(team=self.team, account_id=str(account.id)).aget_account()++ assert fetched is not None+ assert fetched.id == account.id++ async def test_aget_account_by_external_id(self):+ account = await self._create_account(name="Acme Corp", external_id="acme-1")++ fetched = await AccountContext(team=self.team, external_id="acme-1").aget_account()++ assert fetched is not None+ assert fetched.id == account.id++ async def test_aget_account_invalid_id_returns_none(self):+ assert await AccountContext(team=self.team, account_id="not-a-uuid").aget_account() is None++ async def test_execute_and_format_not_found(self):+ result = await AccountContext(team=self.team, account_id=str(uuid.uuid4())).execute_and_format()++ assert "was not found" in result++ async def test_format_includes_basics(self):+ account = await self._create_account(name="Acme Corp", external_id="acme-1")++ result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)++ assert "## Account: Acme Corp" in result+ assert str(account.id) in result+ assert "acme-1" in result++ async def test_format_external_id_not_set(self):+ account = await self._create_account(name="Acme Corp")++ result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)++ assert "**External ID:** Not set" in result++ async def test_format_includes_roles(self):+ account = await self._create_account(+ name="Acme Corp",+ _properties={"csm": {"id": 42, "email": "[email protected]"}},+ )++ result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)++ assert "### Roles" in result+ assert "CSM: [email protected] (user 42)" in result++ async def test_format_includes_external_system_ids(self):+ account = await self._create_account(name="Acme Corp", _properties={"stripe_customer_id": "cus_123"})++ result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)++ assert "### External-system ids" in result+ assert "Stripe customer id: cus_123" in result++ async def test_format_includes_tags(self):+ account = await self._create_account(name="Acme Corp")+ await sync_to_async(set_tags_on_object)(["enterprise", "priority"], account)++ result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)++ assert "### Tags" in result+ assert "enterprise, priority" in result++ async def test_format_includes_saved_notes(self):+ account = await self._create_account(name="Acme Corp")+ notebook = await Notebook.objects.acreate(+ team=self.team,+ created_by=self.user,+ last_modified_by=self.user,+ visibility=Notebook.Visibility.INTERNAL,+ title="Q3 kickoff recap",+ )+ await ResourceNotebook.objects.acreate(notebook=notebook, account=account)++ result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)++ assert "### Saved notes" in result+ assert "Q3 kickoff recap" in result+ assert notebook.short_id in result++ async def test_analysis_connected_when_group_resolves(self):+ account = await self._create_account(name="Acme Corp", external_id="acme-1")++ with (+ patch.object(AccountContext, "_account_group_type_index", return_value=2),+ patch("ee.hogai.context.account.context.get_group_by_key", return_value=MagicMock()) as mock_lookup,+ ):+ result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)++ mock_lookup.assert_called_once()+ assert "<account_analysis_context>" in result+ assert "group type index 2" in result+ assert 'group key "acme-1"' in result++ async def test_analysis_not_configured_when_group_type_index_missing(self):+ account = await self._create_account(name="Acme Corp", external_id="acme-1")++ with (+ patch.object(AccountContext, "_account_group_type_index", return_value=None),+ patch("ee.hogai.context.account.context.get_group_by_key") as mock_lookup,+ ):+ result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)++ mock_lookup.assert_not_called()+ assert "isn't connected to a group type" in result++ async def test_analysis_no_external_id_when_account_unlinked(self):+ account = await self._create_account(name="Acme Corp")++ with (+ patch.object(AccountContext, "_account_group_type_index", return_value=2),+ patch("ee.hogai.context.account.context.get_group_by_key") as mock_lookup,+ ):+ result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)++ mock_lookup.assert_not_called()+ assert "has no external ID" in result++ async def test_analysis_group_not_found(self):+ account = await self._create_account(name="Acme Corp", external_id="acme-1")++ with (+ patch.object(AccountContext, "_account_group_type_index", return_value=2),+ patch("ee.hogai.context.account.context.get_group_by_key", return_value=None),+ ):+ result = await AccountContext(team=self.team, account_id=str(account.id)).format_account(account)++ assert "doesn't match any known group" in result++ async def test_reads_configured_group_type_index(self):+ team = MagicMock()+ team.customer_analytics_config.account_group_type_index = 7++ assert AccountContext(team=team)._account_group_type_index() == 7++ async def test_group_type_index_none_when_config_missing(self):+ class _TeamWithoutConfig:+ @property+ def customer_analytics_config(self):+ raise ObjectDoesNotExist++ assert AccountContext(team=_TeamWithoutConfig())._account_group_type_index() is None # type: ignore[arg-type]diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.pyindex 44e953289151..957ea5d76e95 100644--- a/ee/hogai/context/entity_search/context.py+++ b/ee/hogai/context/entity_search/context.py@@ -21,6 +21,7 @@ from posthog.sync import database_sync_to_asyncfrom products.actions.backend.models.action import Actionfrom products.alerts.backend.models.alert import AlertConfigurationfrom products.cohorts.backend.models.cohort import Cohort+from products.customer_analytics.backend.models import Accountfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -42,6 +43,7 @@ class EntityKind(StrEnum):NOTEBOOKS = "notebooks"SURVEYS = "surveys"ALERTS = "alerts"+ ACCOUNTS = "accounts"ALL = "all"@@ -55,6 +57,7 @@ SEARCH_KIND_TO_DATABASE_ENTITY_TYPE: dict[EntityKind, str] = {EntityKind.COHORTS: "cohort",EntityKind.SURVEYS: "survey",EntityKind.ALERTS: "alert_configuration",+ EntityKind.ACCOUNTS: "account",}ENTITY_MAP: dict[str, EntityConfig] = {@@ -218,6 +221,9 @@ class EntitySearchContext:elif entity_type == "insight":# Use specialized queryset filtered by recent view timereturn await self._list_insights(limit, offset)+ elif entity_type == "account":+ # Account uses a fail-closed manager, so it can't go through the shared FTS path+ return await self._list_accounts(limit, offset)else:# Fetch database entitiesdb_results, _, maybe_count = await database_sync_to_async(search_entities_fts, thread_sensitive=False)(@@ -337,6 +343,27 @@ class EntitySearchContext:return all_entities, total_count+ async def _list_accounts(self, limit: int = 100, offset: int = 0) -> tuple[list[dict[str, Any]], int]:+ """List customer accounts, newest first. Uses the unscoped manager since Account is fail-closed."""+ return await database_sync_to_async(self._list_accounts_sync, thread_sensitive=False)(limit, offset)++ def _list_accounts_sync(self, limit: int = 100, offset: int = 0) -> tuple[list[dict[str, Any]], int]:+ queryset = self.user_access_control.filter_queryset_by_access_level(+ Account.objects.unscoped().filter(team=self._team).order_by("-created_at")+ )+ total_count = queryset.count()+ accounts = list(queryset[offset : offset + limit].values("id", "name", "external_id"))++ all_entities: list[dict[str, Any]] = [+ {+ "type": "account",+ "result_id": str(account["id"]),+ "extra_fields": {"name": account["name"], "external_id": account["external_id"]},+ }+ for account in accounts+ ]+ return all_entities, total_count+def _get_entity_row_values(self, result: dict, extra_columns: list[str], include_type: bool) -> list[str]:"""Get the row values for an entity.@@ -424,5 +451,7 @@ class EntitySearchContext:return f"{base_url}/error_tracking/{result_id}"case "alert_configuration":return f"{base_url}/insights?tab=alerts&alert_id={result_id}"+ case "account":+ return f"{base_url}/customer_analytics/accounts"case _:raise ValueError(f"Unknown entity type: {entity_type}")diff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.pyindex 1723d605f2de..3ddf480177ec 100644--- a/ee/hogai/context/entity_search/test/test_context.py+++ b/ee/hogai/context/entity_search/test/test_context.py@@ -9,6 +9,7 @@ from parameterized import parameterizedfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort+from products.customer_analytics.backend.models import Accountfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -42,6 +43,7 @@ class TestEntitySearchContext(NonAtomicBaseTest):("survey", "test_survey_id", "/project/{team_id}/surveys/test_survey_id"),("error_tracking_issue", "test_issue_id", "/project/{team_id}/error_tracking/test_issue_id"),("notebook", "test_notebook_id", "/project/{team_id}/notebooks/test_notebook_id"),+ ("account", "test_account_id", "/project/{team_id}/customer_analytics/accounts"),])def test_build_url(self, entity_type, result_id, expected_path):@@ -369,6 +371,35 @@ class TestEntitySearchContext(NonAtomicBaseTest):assert total == 1assert entities[0]["extra_fields"]["name"] == "List Dashboard"+ async def test_list_entities_account(self):+ account = await Account.objects.unscoped().acreate(team=self.team, name="Acme Corp", external_id="acme-1")++ entities, total = await self.context.list_entities("account", limit=10, offset=0)++ assert total == 1+ assert len(entities) == 1+ assert entities[0]["type"] == "account"+ assert entities[0]["result_id"] == str(account.id)+ assert entities[0]["extra_fields"]["name"] == "Acme Corp"+ assert entities[0]["extra_fields"]["external_id"] == "acme-1"++ async def test_list_entities_account_pagination(self):+ for i in range(3):+ await Account.objects.unscoped().acreate(team=self.team, name=f"Account {i}")++ page1, total = await self.context.list_entities("account", limit=2, offset=0)+ page2, _ = await self.context.list_entities("account", limit=2, offset=2)++ assert total == 3+ assert len(page1) == 2+ assert len(page2) == 1++ async def test_list_entities_account_empty(self):+ entities, total = await self.context.list_entities("account", limit=10, offset=0)++ assert entities == []+ assert total == 0+async def test_list_entities_pagination(self):for i in range(5):insight = await Insight.objects.acreate(diff --git a/ee/hogai/core/agent_modes/presets/customer_analytics.py b/ee/hogai/core/agent_modes/presets/customer_analytics.pynew file mode 100644index 000000000000..bcdf5c550028--- /dev/null+++ b/ee/hogai/core/agent_modes/presets/customer_analytics.py@@ -0,0 +1,142 @@+from typing import TYPE_CHECKING++from posthog.schema import AgentMode++from products.customer_analytics.backend.max_tools import UpsertAccountNotebookTool, UpsertAccountTool++from ee.hogai.chat_agent.executables import ChatAgentExecutable, ChatAgentToolsExecutable+from ee.hogai.tools.todo_write import TodoWriteExample++from ..factory import AgentModeDefinition+from ..toolkit import AgentToolkit++if TYPE_CHECKING:+ from ee.hogai.tool import MaxTool+++CUSTOMER_ANALYTICS_MODE_DESCRIPTION = (+ "Specialized mode for managing customer accounts. An account represents a customer organization. "+ "Use this mode to create and update accounts, assign customer-success roles (CSM, account "+ "executive, account owner), set external-system identifiers and tags, and save and update notes "+ "(call recaps, meeting summaries, investigation recaps) on an account. "+ "Each account's usage is already available in the Accounts list — in the expanded row's Usage tab — "+ "so point users there rather than building a new insight for it. "+ "For other questions about an account's activity or behavior, first look up the account — reading "+ "it gives you the context needed to analyze it — then switch_mode to product analytics or SQL to "+ "run the analysis for that account. "+ "When the user investigates a single account across several turns — follow-up questions or digging "+ "into an issue — offer once to capture the investigation as a note: a timeline of what was checked "+ "and what you found, saved with upsert_account_notebook. If they decline, don't ask again. "+ "If an account is not connected to analytics yet, ask the user to finish connecting it in the "+ "Customer analytics > Accounts settings. "+ "Speak to users in terms of the account and its data; keep the underlying mechanics out of your responses."+)+++POSITIVE_EXAMPLE_ASSIGN_ROLE = """+User: Make Jane the CSM for Acme Corp+Assistant: Let me find the Acme Corp account first.+*Uses list_data with the account kind to find the account's id*+Assistant: Found it. I'll assign Jane as the CSM.+*Uses the upsert_account tool with action=update, account_id=<uuid>, properties={csm: {id, email}}*+""".strip()++POSITIVE_EXAMPLE_ASSIGN_ROLE_REASONING = """+1. The account must be looked up by its id before it can be updated.+2. Assigning a single role is a one-step task, so no todo list is needed.+3. The CSM assignment requires the assignee's user id and email.+""".strip()++POSITIVE_EXAMPLE_ACCOUNT_USAGE = """+User: How has Acme Corp's usage been lately?+Assistant: Let me open Acme Corp's usage.+*Opens the Acme Corp account's Usage tab in the Accounts list*+""".strip()++POSITIVE_EXAMPLE_ACCOUNT_USAGE_REASONING = """+1. Each account's usage already lives in its Usage tab in the Accounts list, so the assistant opens that directly instead of building a new insight.+2. Surfacing the existing view is faster and consistent with the rest of the product.+""".strip()++POSITIVE_EXAMPLE_ACCOUNT_ANALYTICS = """+User: Acme Corp had an MRR spike last month — help me understand why.+Assistant: Let me dig into what drove Acme Corp's spike.+*Creates a todo list:*+1. Look up the Acme Corp account (read_data with the account kind)+2. Switch to product analytics (or SQL) mode+3. Build an insight — branching off the account's existing usage view — comparing usage by product last month vs the prior period+4. Identify which products grew and summarize the likely driver of the spike+*Begins working on the first task*+""".strip()++POSITIVE_EXAMPLE_ACCOUNT_ANALYTICS_REASONING = """+1. This is a "why" question, not a "what" — the Usage tab shows the account's usage, but here the user wants the explanation behind an MRR change.+2. MRR is usage-based, so the answer ties to which products' usage grew; that needs a period-over-period comparison the built-in tabs don't provide.+3. The account is looked up first, then the analysis runs after switching to product analytics or SQL — reusing the existing usage view as a starting point rather than building from scratch.+""".strip()++POSITIVE_EXAMPLE_SAVE_NOTE = """+User: Save a recap on Acme Corp from today's call — they want SSO by Q3 and flagged slow dashboards.+Assistant: Let me find the Acme Corp account first.+*Uses list_data with the account kind to get the account's id*+Assistant: Saving the recap to Acme Corp's notes.+*Uses the upsert_account_notebook tool with action=create, account_id=<uuid>, title="Call recap", content="<markdown>"*+""".strip()++POSITIVE_EXAMPLE_SAVE_NOTE_REASONING = """+1. A note attaches to a specific account, so its id must be resolved before the note can be created.+2. Saving one note is a single step once the id is known, so no todo list is needed.+3. The recap is written as Markdown in the note body.+""".strip()++POSITIVE_EXAMPLE_DEEP_DIVE = """+User: (several questions into Acme Corp's activity drop) ...and how does that compare to last quarter?+Assistant: We're a few questions into Acme Corp's situation — want me to keep a recap of this investigation in the account's notes? I'd capture a timeline of what we've looked at and what we found.+User: Yes, please.+Assistant: Will do — I'll answer this, then save the recap.+*Answers the question, then uses the upsert_account_notebook tool with action=create, account_id=<uuid>, title="Activity drop investigation", content="<markdown timeline: questions explored, what was checked, findings>"*+""".strip()++POSITIVE_EXAMPLE_DEEP_DIVE_REASONING = """+1. Several turns focused on one account signal a deep-dive — the moment to offer to capture it, once, rather than on every turn.+2. The recap is post-hoc and opt-in: on agreement the assistant writes a single timeline note with upsert_account_notebook; if the user declines, it just continues.+3. Saving the recap is one step, so it needs no todo list of its own — though the investigation it summarizes may itself be todo-tracked.+""".strip()++POSITIVE_EXAMPLE_UPDATE_NOTE = """+User: Add to that recap — they also asked about SSO pricing.+Assistant: I'll update the recap.+*Uses the upsert_account_notebook tool with action=update, notebook_short_id=<from when the note was created>, content="<full updated markdown>"*+""".strip()++POSITIVE_EXAMPLE_UPDATE_NOTE_REASONING = """+1. Updating reuses the note's short_id from when it was created, so no fresh account lookup is needed.+2. content REPLACES the body, so the assistant sends the full updated note, not just the new line.+3. It's a single step, so no todo list is needed.+""".strip()+++class CustomerAnalyticsAgentToolkit(AgentToolkit):+ POSITIVE_TODO_EXAMPLES = [+ TodoWriteExample(example=POSITIVE_EXAMPLE_ASSIGN_ROLE, reasoning=POSITIVE_EXAMPLE_ASSIGN_ROLE_REASONING),+ TodoWriteExample(example=POSITIVE_EXAMPLE_ACCOUNT_USAGE, reasoning=POSITIVE_EXAMPLE_ACCOUNT_USAGE_REASONING),+ TodoWriteExample(+ example=POSITIVE_EXAMPLE_ACCOUNT_ANALYTICS, reasoning=POSITIVE_EXAMPLE_ACCOUNT_ANALYTICS_REASONING+ ),+ TodoWriteExample(example=POSITIVE_EXAMPLE_SAVE_NOTE, reasoning=POSITIVE_EXAMPLE_SAVE_NOTE_REASONING),+ TodoWriteExample(example=POSITIVE_EXAMPLE_DEEP_DIVE, reasoning=POSITIVE_EXAMPLE_DEEP_DIVE_REASONING),+ TodoWriteExample(example=POSITIVE_EXAMPLE_UPDATE_NOTE, reasoning=POSITIVE_EXAMPLE_UPDATE_NOTE_REASONING),+ ]++ @property+ def tools(self) -> list[type["MaxTool"]]:+ return [UpsertAccountTool, UpsertAccountNotebookTool]+++customer_analytics_agent = AgentModeDefinition(+ mode=AgentMode.CUSTOMER_ANALYTICS,+ mode_description=CUSTOMER_ANALYTICS_MODE_DESCRIPTION,+ toolkit_class=CustomerAnalyticsAgentToolkit,+ node_class=ChatAgentExecutable,+ tools_node_class=ChatAgentToolsExecutable,+)diff --git a/ee/hogai/core/agent_modes/presets/test/test_customer_analytics.py b/ee/hogai/core/agent_modes/presets/test/test_customer_analytics.pynew file mode 100644index 000000000000..bdcb78ee58ce--- /dev/null+++ b/ee/hogai/core/agent_modes/presets/test/test_customer_analytics.py@@ -0,0 +1,43 @@+from posthog.test.base import BaseTest++from langchain_core.runnables import RunnableConfig++from posthog.schema import AgentMode++from ee.hogai.context import AssistantContextManager+from ee.hogai.core.agent_modes.presets.customer_analytics import (+ CUSTOMER_ANALYTICS_MODE_DESCRIPTION,+ CustomerAnalyticsAgentToolkit,+ customer_analytics_agent,+)++# Raw mechanics of the account→group bridge that must never surface in user-facing+# prompt text — the mode is a façade. Tool descriptions may state external_id's meaning,+# but the mode description and trajectory examples must not expose the plumbing.+_LEAKY_TERMS = ["group_key", "$group_", "aggregation_group_type_index", "group_type_index"]+++class TestCustomerAnalyticsPreset(BaseTest):+ def test_mode_definition_wires_toolkit(self):+ self.assertEqual(customer_analytics_agent.mode, AgentMode.CUSTOMER_ANALYTICS)+ self.assertEqual(customer_analytics_agent.toolkit_class, CustomerAnalyticsAgentToolkit)++ def test_toolkit_exposes_account_tools(self):+ context_manager = AssistantContextManager(+ team=self.team, user=self.user, config=RunnableConfig(configurable={})+ )+ toolkit = CustomerAnalyticsAgentToolkit(team=self.team, user=self.user, context_manager=context_manager)+ tool_names = [tool.model_fields["name"].default for tool in toolkit.tools]++ self.assertIn("upsert_account", tool_names)+ self.assertIn("upsert_account_notebook", tool_names)++ def test_prompt_does_not_leak_bridge_mechanics(self):+ examples = "\n".join(+ f"{example.example}\n{example.reasoning}"+ for example in CustomerAnalyticsAgentToolkit.POSITIVE_TODO_EXAMPLES+ )+ surface_text = f"{CUSTOMER_ANALYTICS_MODE_DESCRIPTION}\n{examples}".lower()++ for term in _LEAKY_TERMS:+ self.assertNotIn(term.lower(), surface_text)diff --git a/ee/hogai/tools/read_data/prompts.py b/ee/hogai/tools/read_data/prompts.pyindex 66a7172e3e65..16067c413f84 100644--- a/ee/hogai/tools/read_data/prompts.py+++ b/ee/hogai/tools/read_data/prompts.py@@ -29,6 +29,20 @@ Some activity logs are organization-level — they are not tied to a specific prThese logs are always captured, but they are only included in query results when the project has the "Include organization-level activity" setting enabled. If the user asks about such changes and no results are found, let them know this setting may need to be turned on in Project settings > Activity log.""".strip()+READ_DATA_ACCOUNT_PROMPT = """+# Account++Retrieves a customer account by its UUID or external id, including its assigned roles (CSM, account executive, account owner), tags, external-system ids, and saved notes.++## Use this when:+- You need an account's details, role assignments, or saved notes.+- You need to look up an account before updating it, adding a note, or analyzing its data — reading it returns the context needed to scope an analysis to that account.++## Parameters:+- account_id: The UUID of the account (optional if external_id is provided).+- external_id: The account's external id (optional if account_id is provided).+""".strip()+READ_DATA_PROMPT = """Use this tool to read user data created in PostHog. This tool returns data that the user manually creates in PostHog.@@ -101,6 +115,8 @@ Retrieves an experiment by its numeric ID or by its feature flag's key.- id: The numeric ID of the experiment (optional if feature_flag_key is provided)- feature_flag_key: The key of the experiment's feature flag (optional if id is provided)+{{{account_prompt}}}+{{{activity_log_prompt}}}{{{billing_prompt}}}diff --git a/ee/hogai/tools/read_data/test/test_tool.py b/ee/hogai/tools/read_data/test/test_tool.pyindex 98da96f49d07..02ef37132962 100644--- a/ee/hogai/tools/read_data/test/test_tool.py+++ b/ee/hogai/tools/read_data/test/test_tool.py@@ -22,6 +22,7 @@ from products.ai_observability.backend.summarization.llm.schema import (SummarizationResponse,SummaryBullet,)+from products.customer_analytics.backend.models import Accountfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery@@ -33,7 +34,7 @@ from products.warehouse_sources.backend.models.credential import DataWarehouseCrfrom products.warehouse_sources.backend.models.table import DataWarehouseTablefrom ee.hogai.artifacts.types import ModelArtifactResult, StateArtifactResult-from ee.hogai.tool_errors import MaxToolAccessDeniedError, MaxToolRetryableError+from ee.hogai.tool_errors import MaxToolAccessDeniedError, MaxToolFatalError, MaxToolRetryableErrorfrom ee.hogai.tools.read_data.tool import ReadDataToolfrom ee.hogai.utils.types import AssistantStatefrom ee.hogai.utils.types.base import ArtifactRefMessage, NodePath@@ -838,6 +839,100 @@ class TestReadDataTool(BaseTest):assert "nonexistent-flag" in str(exc_info.value)+ def _context_manager_without_extras(self) -> MagicMock:+ context_manager = MagicMock()+ context_manager.check_user_has_billing_access = AsyncMock(return_value=False)+ context_manager.check_has_audit_logs_access = AsyncMock(return_value=False)+ return context_manager++ async def test_create_tool_class_with_account_flag(self):+ state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))++ with patch("ee.hogai.tools.read_data.tool.has_customer_analytics_mode_feature_flag", return_value=True):+ tool = await ReadDataTool.create_tool_class(+ team=self.team,+ user=self.user,+ state=state,+ context_manager=self._context_manager_without_extras(),+ )++ assert "Retrieves a customer account" in tool.description++ async def test_create_tool_class_without_account_flag(self):+ state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))++ with patch("ee.hogai.tools.read_data.tool.has_customer_analytics_mode_feature_flag", return_value=False):+ tool = await ReadDataTool.create_tool_class(+ team=self.team,+ user=self.user,+ state=state,+ context_manager=self._context_manager_without_extras(),+ )++ assert "Retrieves a customer account" not in tool.description++ async def test_read_account_by_id(self):+ account = await Account.objects.unscoped().acreate(team=self.team, name="Acme Corp", external_id="acme-1")+ state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))++ with patch("ee.hogai.tools.read_data.tool.has_customer_analytics_mode_feature_flag", return_value=True):+ tool = await ReadDataTool.create_tool_class(+ team=self.team,+ user=self.user,+ state=state,+ context_manager=self._context_manager_without_extras(),+ )+ result, artifact = await tool._arun_impl({"kind": "account", "account_id": str(account.id)})++ assert "Acme Corp" in result+ assert "acme-1" in result+ assert artifact is None++ async def test_read_account_by_external_id(self):+ await Account.objects.unscoped().acreate(team=self.team, name="Beta Inc", external_id="beta-9")+ state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))++ with patch("ee.hogai.tools.read_data.tool.has_customer_analytics_mode_feature_flag", return_value=True):+ tool = await ReadDataTool.create_tool_class(+ team=self.team,+ user=self.user,+ state=state,+ context_manager=self._context_manager_without_extras(),+ )+ result, _ = await tool._arun_impl({"kind": "account", "external_id": "beta-9"})++ assert "Beta Inc" in result++ async def test_read_account_not_found(self):+ state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))++ with patch("ee.hogai.tools.read_data.tool.has_customer_analytics_mode_feature_flag", return_value=True):+ tool = await ReadDataTool.create_tool_class(+ team=self.team,+ user=self.user,+ state=state,+ context_manager=self._context_manager_without_extras(),+ )+ with pytest.raises(MaxToolRetryableError) as exc_info:+ await tool._arun_impl({"kind": "account", "account_id": str(uuid4())})++ assert "was not found" in str(exc_info.value)++ async def test_read_account_is_fatal_when_flag_disabled(self):+ account = await Account.objects.unscoped().acreate(team=self.team, name="Acme Corp", external_id="acme-1")+ state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))++ tool = await ReadDataTool.create_tool_class(+ team=self.team,+ user=self.user,+ state=state,+ context_manager=self._context_manager_without_extras(),+ )++ with patch("ee.hogai.tools.read_data.tool.has_customer_analytics_mode_feature_flag", return_value=False):+ with pytest.raises(MaxToolFatalError):+ await tool._arun_impl({"kind": "account", "account_id": str(account.id)})+async def test_read_feature_flag_requires_id_or_key(self):"""Test that feature flag read requires either id or key."""state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))diff --git a/ee/hogai/tools/read_data/tool.py b/ee/hogai/tools/read_data/tool.pyindex 86ae81b43dfe..6bc7ad36f73d 100644--- a/ee/hogai/tools/read_data/tool.py+++ b/ee/hogai/tools/read_data/tool.py@@ -37,6 +37,7 @@ from products.posthog_ai.backend.models.assistant import AgentArtifactfrom ee.hogai.artifacts.types import ModelArtifactResultfrom ee.hogai.chat_agent.sql.mixins import HogQLDatabaseMixin+from ee.hogai.context.account import AccountContextfrom ee.hogai.context.activity_log.context import ActivityLogContextfrom ee.hogai.context.context import AssistantContextManagerfrom ee.hogai.context.dashboard.context import DashboardContext, DashboardInsightContext@@ -54,11 +55,13 @@ from ee.hogai.tools.read_data.prompts import (BILLING_INSUFFICIENT_ACCESS_PROMPT,DASHBOARD_NOT_FOUND_PROMPT,INSIGHT_NOT_FOUND_PROMPT,+ READ_DATA_ACCOUNT_PROMPT,READ_DATA_ACTIVITY_LOG_PROMPT,READ_DATA_BILLING_PROMPT,READ_DATA_PROMPT,READ_DATA_WAREHOUSE_SCHEMA_PROMPT,)+from ee.hogai.utils.feature_flags import has_customer_analytics_mode_feature_flagfrom ee.hogai.utils.prompt import format_prompt_stringfrom ee.hogai.utils.query import validate_assistant_queryfrom ee.hogai.utils.types.base import ArtifactRefMessage, AssistantState, NodePath@@ -149,6 +152,14 @@ class ReadExperiment(BaseModel):feature_flag_key: str | None = Field(default=None, description="The key of the experiment's feature flag.")+class ReadAccount(BaseModel):+ """Retrieves a customer account by its UUID or external id, including roles, tags, external-system ids, and saved notes."""++ kind: Literal["account"] = "account"+ account_id: str | None = Field(default=None, description="The UUID of the account.")+ external_id: str | None = Field(default=None, description="The external id of the account.")++class ReadActivityLog(BaseModel):"""Retrieves recent activity log entries showing who changed what and when in this project."""@@ -201,6 +212,7 @@ ReadDataQuery = (| ReadSurvey| ReadFeatureFlag| ReadExperiment+ | ReadAccount| ReadActivityLog| ReadLLMTrace)@@ -252,6 +264,10 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):prompt_vars["activity_log_prompt"] = READ_DATA_ACTIVITY_LOG_PROMPTkinds.append(ReadActivityLog)+ if has_customer_analytics_mode_feature_flag(team, user):+ prompt_vars["account_prompt"] = READ_DATA_ACCOUNT_PROMPT+ kinds.append(ReadAccount)+base_kinds: tuple[type[BaseModel], ...] = (ReadDataWarehouseSchema,ReadDataWarehouseTableSchema,@@ -325,6 +341,10 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):return await self._read_feature_flag(schema.id, schema.key), Nonecase ReadExperiment() as schema:return await self._read_experiment(schema.id, schema.feature_flag_key), None+ case ReadAccount() as schema:+ if not has_customer_analytics_mode_feature_flag(self._team, self._user):+ raise MaxToolFatalError("Account data is not available for this project.")+ return await self._read_account(schema.account_id, schema.external_id), Nonecase ReadActivityLog() as schema:if not await self._context_manager.check_has_audit_logs_access():raise MaxToolFatalError(ACTIVITY_LOG_INSUFFICIENT_ACCESS_PROMPT)@@ -642,6 +662,23 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):await self.check_object_access(experiment, "viewer", resource="experiment", action="read")return await context.format_experiment(experiment)+ async def _read_account(self, account_id: str | None, external_id: str | None) -> str:+ if account_id is None and external_id is None:+ raise MaxToolRetryableError("You must provide either 'account_id' or 'external_id' to read an account.")++ context = AccountContext(+ team=self._team,+ account_id=account_id,+ external_id=external_id,+ )++ account = await context.aget_account()+ if account is None:+ raise MaxToolRetryableError(context.get_not_found_message())++ await self.check_object_access(account, "viewer", resource="account", action="read")+ return await context.format_account(account)+async def _read_activity_log(self,scope: str | None,diff --git a/ee/hogai/tools/test/test_list_data.py b/ee/hogai/tools/test/test_list_data.pyindex 57bffdbdacd3..20470b5be283 100644--- a/ee/hogai/tools/test/test_list_data.py+++ b/ee/hogai/tools/test/test_list_data.py@@ -81,6 +81,18 @@ class TestListDataTool(ClickhouseTestMixin, NonAtomicBaseTest):with self.assertRaises(ValueError):await self.tool._arun_impl(kind="invalid_kind", limit=100, offset=0)+ async def test_list_entities_accounts_routes_to_account(self):+ """The accounts kind maps to the account database entity type."""+ with patch("ee.hogai.tools.list_data.EntitySearchContext") as MockEntitySearchContext:+ mock_instance = MagicMock()+ mock_instance.list_entities = AsyncMock(return_value=([], 0))+ mock_instance.format_entities = MagicMock(return_value="")+ MockEntitySearchContext.return_value = mock_instance++ await self.tool._arun_impl(kind="accounts", limit=100, offset=0)++ mock_instance.list_entities.assert_called_once_with("account", 100, 0)+async def test_list_entities_default_pagination(self):"""Test that list entities uses default pagination values."""entities_data = [diff --git a/ee/hogai/utils/feature_flags.py b/ee/hogai/utils/feature_flags.pyindex 6a7c9d9f5e1d..778cc44c78b7 100644--- a/ee/hogai/utils/feature_flags.py+++ b/ee/hogai/utils/feature_flags.py@@ -113,6 +113,16 @@ def has_user_interview_mode_feature_flag(team: Team, user: User) -> bool:)+def has_customer_analytics_mode_feature_flag(team: Team, user: User) -> bool:+ return posthoganalytics.feature_enabled(+ "customer-analytics-csp",+ str(user.distinct_id),+ groups={"organization": str(team.organization_id)},+ group_properties={"organization": {"id": str(team.organization_id)}},+ send_feature_flag_events=False,+ )++def get_llm_gateway_variant(team: Team, user: User) -> LlmGatewayVariant:variant = cast("str | bool | None",diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 96f0415347df..971071bfbc83 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -563,7 +563,8 @@"flags","llm_analytics","sandbox",- "user_interview"+ "user_interview",+ "customer_analytics"],"type": "string"},@@ -3862,7 +3863,10 @@"marketing_suggest_conversion_goals","marketing_suggest_utm_mappings","summarize_replay_vision_summaries",- "draft_replay_vision_scanner_prompt"+ "draft_replay_vision_scanner_prompt",+ "upsert_account",+ "upsert_account_notebook",+ "open_account"],"type": "string"},diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.tsindex d1cb3dae6c0b..510e6aec0326 100644--- a/frontend/src/queries/schema/schema-assistant-messages.ts+++ b/frontend/src/queries/schema/schema-assistant-messages.ts@@ -517,6 +517,9 @@ export type AssistantTool =| 'marketing_suggest_utm_mappings'| 'summarize_replay_vision_summaries'| 'draft_replay_vision_scanner_prompt'+ | 'upsert_account'+ | 'upsert_account_notebook'+ | 'open_account'export enum AgentMode {ProductAnalytics = 'product_analytics',@@ -531,6 +534,7 @@ export enum AgentMode {AIObservability = 'llm_analytics',Sandbox = 'sandbox',UserInterview = 'user_interview',+ CustomerAnalytics = 'customer_analytics',}export enum SlashCommandName {diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsxindex 546a7a951b55..7d54e3afeed6 100644--- a/frontend/src/scenes/max/max-constants.tsx+++ b/frontend/src/scenes/max/max-constants.tsx@@ -10,6 +10,7 @@ import {IconMemory,IconNotebook,IconNotification,+ IconPeople,IconPlug,IconSearch,IconShuffle,@@ -620,6 +621,48 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {return 'Filtering issues...'},},+ upsert_account: {+ name: 'Manage accounts',+ description: 'Manage accounts by creating them or updating roles, properties, and tags',+ product: Scene.CustomerAnalytics,+ icon: iconForType('cohort'),+ modes: [AgentMode.CustomerAnalytics],+ displayFormatter: (toolCall) => {+ const action = toolCall.args?.action+ const isUpdate = isObject(action) && 'action' in action && action.action === 'update'+ if (isUpdate) {+ return toolCall.status === 'completed' ? 'Updated account' : 'Updating account...'+ }+ return toolCall.status === 'completed' ? 'Created account' : 'Creating account...'+ },+ },+ upsert_account_notebook: {+ name: 'Manage account notes',+ description: 'Manage account notes — call recaps, summaries, or edits to an existing note',+ product: Scene.CustomerAnalytics,+ icon: iconForType('notebook'),+ modes: [AgentMode.CustomerAnalytics],+ displayFormatter: (toolCall) => {+ const action = toolCall.args?.action+ const isUpdate = isObject(action) && 'action' in action && action.action === 'update'+ if (isUpdate) {+ return toolCall.status === 'completed' ? 'Updated account note' : 'Updating account note...'+ }+ return toolCall.status === 'completed' ? 'Created account note' : 'Creating account note...'+ },+ },+ open_account: {+ name: 'Open account',+ description: 'Open account details and tabs',+ product: Scene.CustomerAnalytics,+ icon: <IconPeople />,+ displayFormatter: (toolCall) => {+ if (toolCall.status === 'completed') {+ return 'Opened account'+ }+ return 'Opening account...'+ },+ },search_error_tracking_issues: {name: 'Search issues',description: 'Search issues in error tracking',@@ -1314,6 +1357,14 @@ export const MODE_DEFINITIONS: Record<scenes: new Set([Scene.UserInterviews, Scene.UserInterview, Scene.UserInterviewResponse]),flag: 'USER_INTERVIEWS',},+ [AgentMode.CustomerAnalytics]: {+ name: 'Customer analytics',+ description:+ 'Works with your customer accounts — assign owners, review notes and usage, and dig into account data.',+ icon: iconForType('cohort'),+ scenes: new Set([Scene.CustomerAnalytics]),+ flag: 'CUSTOMER_ANALYTICS_CSP',+ },}export const SPECIAL_MODES: Record<string, ModeDefinition> = {diff --git a/posthog/schema.py b/posthog/schema.pyindex fc2f8f2bbe53..92400e90354a 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -51,6 +51,7 @@ class AgentMode(StrEnum):LLM_ANALYTICS = "llm_analytics"SANDBOX = "sandbox"USER_INTERVIEW = "user_interview"+ CUSTOMER_ANALYTICS = "customer_analytics"class AggregationAxisFormat(StrEnum):@@ -810,6 +811,9 @@ class AssistantTool(StrEnum):MARKETING_SUGGEST_UTM_MAPPINGS = "marketing_suggest_utm_mappings"SUMMARIZE_REPLAY_VISION_SUMMARIES = "summarize_replay_vision_summaries"DRAFT_REPLAY_VISION_SCANNER_PROMPT = "draft_replay_vision_scanner_prompt"+ UPSERT_ACCOUNT = "upsert_account"+ UPSERT_ACCOUNT_NOTEBOOK = "upsert_account_notebook"+ OPEN_ACCOUNT = "open_account"class AssistantToolCall(BaseModel):diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 4e7ff8a8c55f..b7a739b918a7 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -145,6 +145,7 @@ export type MessageApiContextualTools = { [key: string]: unknown }* * `llm_analytics` - llm_analytics* * `sandbox` - sandbox* * `user_interview` - user_interview+ * * `customer_analytics` - customer_analytics*/export type AgentModeEnumApi = (typeof AgentModeEnumApi)[keyof typeof AgentModeEnumApi]@@ -161,6 +162,7 @@ export const AgentModeEnumApi = {LlmAnalytics: 'llm_analytics',Sandbox: 'sandbox',UserInterview: 'user_interview',+ CustomerAnalytics: 'customer_analytics',} as const/**diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.tsindex ccb7860f878b..3f41a2ccd5e9 100644--- a/products/conversations/frontend/generated/api.zod.ts+++ b/products/conversations/frontend/generated/api.zod.ts@@ -42,10 +42,11 @@ export const ConversationsCreateBody = /* @__PURE__ */ zod'llm_analytics','sandbox','user_interview',+ 'customer_analytics',]).optional().describe(- '\* `product_analytics` - product_analytics\n\* `sql` - sql\n\* `session_replay` - session_replay\n\* `error_tracking` - error_tracking\n\* `plan` - plan\n\* `execution` - execution\n\* `survey` - survey\n\* `research` - research\n\* `flags` - flags\n\* `llm_analytics` - llm_analytics\n\* `sandbox` - sandbox\n\* `user_interview` - user_interview'+ '\* `product_analytics` - product_analytics\n\* `sql` - sql\n\* `session_replay` - session_replay\n\* `error_tracking` - error_tracking\n\* `plan` - plan\n\* `execution` - execution\n\* `survey` - survey\n\* `research` - research\n\* `flags` - flags\n\* `llm_analytics` - llm_analytics\n\* `sandbox` - sandbox\n\* `user_interview` - user_interview\n\* `customer_analytics` - customer_analytics'),is_sandbox: zod.boolean().default(conversationsCreateBodyIsSandboxDefault),resume_payload: zod.unknown().optional(),diff --git a/products/customer_analytics/backend/max_tools/__init__.py b/products/customer_analytics/backend/max_tools/__init__.pynew file mode 100644index 000000000000..1eda5669328a--- /dev/null+++ b/products/customer_analytics/backend/max_tools/__init__.py@@ -0,0 +1,5 @@+from products.customer_analytics.backend.max_tools.open_account import OpenAccountTool+from products.customer_analytics.backend.max_tools.upsert_account import UpsertAccountTool+from products.customer_analytics.backend.max_tools.upsert_account_notebook import UpsertAccountNotebookTool++__all__ = ["OpenAccountTool", "UpsertAccountNotebookTool", "UpsertAccountTool"]diff --git a/products/customer_analytics/backend/max_tools/open_account.py b/products/customer_analytics/backend/max_tools/open_account.pynew file mode 100644index 000000000000..5ed6fb74a491--- /dev/null+++ b/products/customer_analytics/backend/max_tools/open_account.py@@ -0,0 +1,66 @@+from textwrap import dedent+from typing import Any, Literal++from django.core.exceptions import ValidationError++from pydantic import BaseModel, Field++from posthog.rbac.user_access_control import AccessControlLevel+from posthog.scopes import APIScopeObject++from products.customer_analytics.backend.models import Account++from ee.hogai.tool import MaxTool++OPEN_ACCOUNT_TOOL_DESCRIPTION = dedent("""+ Open an account in the Accounts list and jump to one of its tabs — Notes, Users, or Usage.++ Use this to show the user an account's existing usage (the Usage tab) instead of building a new+ insight, or to surface its notes or related users. Identify the account by name or external id;+ `tab` defaults to usage. The account must be in the list the user is currently viewing.+ """).strip()+++class OpenAccountToolArgs(BaseModel):+ account: str = Field(description="The account to open — its name or external id.")+ tab: Literal["notes", "users", "usage"] = Field(+ default="usage",+ description="Which tab to open: notes, users, or usage. Defaults to usage.",+ )+++class OpenAccountTool(MaxTool):+ name: str = "open_account"+ description: str = OPEN_ACCOUNT_TOOL_DESCRIPTION+ args_schema: type[BaseModel] = OpenAccountToolArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("account", "viewer")]++ async def _arun_impl(self, account: str, tab: str = "usage") -> tuple[str, dict[str, Any]]:+ resolved = await self._resolve_account(account)+ if resolved is None:+ return f"Couldn't find an account matching '{account}'.", {"error": "account_not_found"}+ await self.check_object_access(resolved, "viewer", resource="account", action="read")+ return (+ f"Opened {resolved.name}'s {tab} tab.",+ {+ "account_id": str(resolved.id),+ "account_name": resolved.name,+ "external_id": resolved.external_id,+ "tab": tab,+ },+ )++ async def _resolve_account(self, account: str) -> Account | None:+ account = account.strip()+ if not account:+ return None+ accounts = Account.objects.unscoped().filter(team=self._team)+ try:+ match = await accounts.filter(external_id=account).afirst()+ if match is None:+ match = await accounts.filter(name__iexact=account).afirst()+ return match+ except (ValidationError, ValueError):+ return Nonediff --git a/products/customer_analytics/backend/max_tools/test_open_account.py b/products/customer_analytics/backend/max_tools/test_open_account.pynew file mode 100644index 000000000000..2949f61363b3--- /dev/null+++ b/products/customer_analytics/backend/max_tools/test_open_account.py@@ -0,0 +1,61 @@+import pytest+from posthog.test.base import BaseTest++from asgiref.sync import sync_to_async+from langchain_core.runnables import RunnableConfig++from posthog.models import Team++from products.customer_analytics.backend.max_tools.open_account import OpenAccountTool+from products.customer_analytics.backend.models import Account+++class TestOpenAccountTool(BaseTest):+ def setUp(self):+ super().setUp()+ self._config: RunnableConfig = {"configurable": {"team": self.team, "user": self.user}}++ def _tool(self) -> OpenAccountTool:+ return OpenAccountTool(team=self.team, user=self.user, config=self._config)++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_resolves_by_external_id_defaulting_to_usage_tab(self):+ account = await sync_to_async(Account.objects.unscoped().create)(+ team=self.team, name="Acme Corp", external_id="acme-123"+ )++ content, artifact = await self._tool()._arun_impl(account="acme-123")++ assert "Acme Corp" in content+ assert artifact["account_id"] == str(account.id)+ assert artifact["external_id"] == "acme-123"+ assert artifact["tab"] == "usage"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_resolves_by_name_case_insensitive_and_keeps_tab(self):+ account = await sync_to_async(Account.objects.unscoped().create)(team=self.team, name="Acme Corp")++ _, artifact = await self._tool()._arun_impl(account="acme corp", tab="notes")++ assert artifact["account_id"] == str(account.id)+ assert artifact["tab"] == "notes"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_unknown_account_returns_error(self):+ content, artifact = await self._tool()._arun_impl(account="nonexistent")++ assert "Couldn't find" in content+ assert artifact["error"] == "account_not_found"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_account_from_other_team_is_not_found(self):+ other_team = await sync_to_async(lambda: Team.objects.create(organization=self.organization))()+ await sync_to_async(Account.objects.unscoped().create)(team=other_team, name="Foreign", external_id="foreign-1")++ _, artifact = await self._tool()._arun_impl(account="foreign-1")++ assert artifact["error"] == "account_not_found"diff --git a/products/customer_analytics/backend/max_tools/test_upsert_account.py b/products/customer_analytics/backend/max_tools/test_upsert_account.pynew file mode 100644index 000000000000..cd6f9cb0e0b1--- /dev/null+++ b/products/customer_analytics/backend/max_tools/test_upsert_account.py@@ -0,0 +1,126 @@+import uuid++import pytest+from posthog.test.base import BaseTest++from asgiref.sync import sync_to_async+from langchain_core.runnables import RunnableConfig++from posthog.models import TaggedItem, Team++from products.customer_analytics.backend.max_tools.upsert_account import (+ AccountAssignment,+ AccountPropertiesInput,+ CreateAccountAction,+ UpdateAccountAction,+ UpsertAccountTool,+)+from products.customer_analytics.backend.models import Account+++class TestUpsertAccountTool(BaseTest):+ def setUp(self):+ super().setUp()+ self._config: RunnableConfig = {"configurable": {"team": self.team, "user": self.user}}++ def _tool(self) -> UpsertAccountTool:+ return UpsertAccountTool(team=self.team, user=self.user, config=self._config)++ async def _tags_for(self, account: Account) -> list[str]:+ return await sync_to_async(+ lambda: sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True))+ )()++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_create_account(self):+ content, artifact = await self._tool()._arun_impl(+ action=CreateAccountAction(name="Acme Corp", external_id="acme-1")+ )++ assert "created successfully" in content+ account = await sync_to_async(Account.objects.unscoped().get)(id=artifact["account_id"])+ assert account.name == "Acme Corp"+ assert account.external_id == "acme-1"+ assert account.team_id == self.team.id+ assert account.created_by_id == self.user.id++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_create_with_properties_and_tags(self):+ _, artifact = await self._tool()._arun_impl(+ action=CreateAccountAction(+ name="Acme Corp",+ properties=AccountPropertiesInput(csm=AccountAssignment(id=self.user.id, email=self.user.email)),+ tags=["enterprise", "priority"],+ )+ )++ account = await sync_to_async(Account.objects.unscoped().get)(id=artifact["account_id"])+ assert account._properties["csm"] == {"id": self.user.id, "email": self.user.email}+ assert await self._tags_for(account) == ["enterprise", "priority"]++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_create_duplicate_external_id_returns_error(self):+ await self._tool()._arun_impl(action=CreateAccountAction(name="Acme", external_id="dup-1"))++ _, artifact = await self._tool()._arun_impl(action=CreateAccountAction(name="Acme 2", external_id="dup-1"))++ assert artifact["error"] == "duplicate_external_id"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_update_assigns_role_and_merges_properties(self):+ account = await sync_to_async(Account.objects.unscoped().create)(+ team=self.team, name="Acme Corp", _properties={"csm": {"id": 1, "email": "[email protected]"}}+ )++ _, artifact = await self._tool()._arun_impl(+ action=UpdateAccountAction(+ account_id=str(account.id),+ properties=AccountPropertiesInput(+ account_owner=AccountAssignment(id=self.user.id, email=self.user.email)+ ),+ )+ )++ refreshed = await sync_to_async(Account.objects.unscoped().get)(id=account.id)+ assert refreshed._properties["csm"] == {"id": 1, "email": "[email protected]"}+ assert refreshed._properties["account_owner"] == {"id": self.user.id, "email": self.user.email}++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_update_replaces_tags(self):+ _, created = await self._tool()._arun_impl(action=CreateAccountAction(name="Acme", tags=["old"]))+ account = await sync_to_async(Account.objects.unscoped().get)(id=created["account_id"])++ await self._tool()._arun_impl(action=UpdateAccountAction(account_id=str(account.id), tags=["new"]))++ assert await self._tags_for(account) == ["new"]++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_update_unknown_account_returns_error(self):+ _, artifact = await self._tool()._arun_impl(action=UpdateAccountAction(account_id=str(uuid.uuid4()), name="x"))++ assert artifact["error"] == "account_not_found"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_update_with_no_fields_returns_error(self):+ account = await sync_to_async(Account.objects.unscoped().create)(team=self.team, name="Acme")++ _, artifact = await self._tool()._arun_impl(action=UpdateAccountAction(account_id=str(account.id)))++ assert artifact["error"] == "no_changes"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_update_account_from_other_team_is_not_found(self):+ other_team = await sync_to_async(lambda: Team.objects.create(organization=self.organization))()+ account = await sync_to_async(Account.objects.unscoped().create)(team=other_team, name="Foreign")++ _, artifact = await self._tool()._arun_impl(action=UpdateAccountAction(account_id=str(account.id), name="x"))++ assert artifact["error"] == "account_not_found"diff --git a/products/customer_analytics/backend/max_tools/test_upsert_account_notebook.py b/products/customer_analytics/backend/max_tools/test_upsert_account_notebook.pynew file mode 100644index 000000000000..c9ea0fff979b--- /dev/null+++ b/products/customer_analytics/backend/max_tools/test_upsert_account_notebook.py@@ -0,0 +1,153 @@+import uuid++import pytest+from posthog.test.base import BaseTest++from asgiref.sync import sync_to_async+from langchain_core.runnables import RunnableConfig++from posthog.models import Team++from products.customer_analytics.backend.max_tools.upsert_account_notebook import (+ CreateAccountNotebookAction,+ UpdateAccountNotebookAction,+ UpsertAccountNotebookTool,+)+from products.customer_analytics.backend.models import Account+from products.notebooks.backend.models import Notebook, ResourceNotebook+++class TestUpsertAccountNotebookTool(BaseTest):+ def setUp(self):+ super().setUp()+ self._config: RunnableConfig = {"configurable": {"team": self.team, "user": self.user}}++ def _tool(self) -> UpsertAccountNotebookTool:+ return UpsertAccountNotebookTool(team=self.team, user=self.user, config=self._config)++ async def _create_note(+ self, account: Account, title: str = "Q3 recap", content: str = "# Summary\n\nSSO by Q3."+ ) -> str:+ _, artifact = await self._tool()._arun_impl(+ action=CreateAccountNotebookAction(account_id=str(account.id), title=title, content=content)+ )+ return artifact["notebook_short_id"]++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_create_links_internal_notebook_to_account(self):+ account = await sync_to_async(Account.objects.unscoped().create)(team=self.team, name="Acme Corp")++ content, artifact = await self._tool()._arun_impl(+ action=CreateAccountNotebookAction(+ account_id=str(account.id), title="Q3 call recap", content="# Summary\n\nThey want SSO by Q3."+ )+ )++ assert "Acme Corp" in content+ assert artifact["account_id"] == str(account.id)++ notebook = await sync_to_async(Notebook.objects.get)(short_id=artifact["notebook_short_id"])+ assert notebook.team_id == self.team.id+ assert notebook.visibility == Notebook.Visibility.INTERNAL+ assert notebook.created_by_id == self.user.id+ assert notebook.title == "Q3 call recap"+ assert notebook.content["type"] == "doc"+ assert notebook.content["content"]+ assert notebook.text_content == "# Summary\n\nThey want SSO by Q3."+ assert notebook.version == 0++ linked = await sync_to_async(ResourceNotebook.objects.filter(notebook=notebook, account=account).exists)()+ assert linked++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_create_blank_markdown_falls_back_to_empty_paragraph(self):+ account = await sync_to_async(Account.objects.unscoped().create)(team=self.team, name="Beta Inc")++ _, artifact = await self._tool()._arun_impl(+ action=CreateAccountNotebookAction(account_id=str(account.id), title="Empty", content="")+ )++ notebook = await sync_to_async(Notebook.objects.get)(short_id=artifact["notebook_short_id"])+ assert notebook.content == {"type": "doc", "content": [{"type": "paragraph"}]}++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_create_account_not_found_returns_error(self):+ content, artifact = await self._tool()._arun_impl(+ action=CreateAccountNotebookAction(account_id=str(uuid.uuid4()), title="x", content="y")+ )++ assert "not found" in content+ assert artifact["error"] == "account_not_found"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_create_account_from_other_team_is_not_found(self):+ other_team = await sync_to_async(lambda: Team.objects.create(organization=self.organization))()+ account = await sync_to_async(Account.objects.unscoped().create)(team=other_team, name="Foreign")++ _, artifact = await self._tool()._arun_impl(+ action=CreateAccountNotebookAction(account_id=str(account.id), title="x", content="y")+ )++ assert artifact["error"] == "account_not_found"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_update_changes_title_and_content_and_bumps_version(self):+ account = await sync_to_async(Account.objects.unscoped().create)(team=self.team, name="Acme Corp")+ short_id = await self._create_note(account)++ content, artifact = await self._tool()._arun_impl(+ action=UpdateAccountNotebookAction(+ notebook_short_id=short_id,+ title="Q3 recap (updated)",+ content="# Summary\n\nSSO by Q3.\n\n## Pricing\n\nAsked about SSO pricing.",+ )+ )++ assert "Acme Corp" in content+ assert artifact["notebook_short_id"] == short_id++ notebook = await sync_to_async(Notebook.objects.get)(short_id=short_id)+ assert notebook.title == "Q3 recap (updated)"+ assert notebook.text_content is not None and "Pricing" in notebook.text_content+ assert notebook.version == 1++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_update_with_no_fields_returns_error(self):+ _, artifact = await self._tool()._arun_impl(action=UpdateAccountNotebookAction(notebook_short_id="abc123"))++ assert artifact["error"] == "no_changes"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_update_unknown_notebook_returns_error(self):+ _, artifact = await self._tool()._arun_impl(+ action=UpdateAccountNotebookAction(notebook_short_id="zzzzzzzzzzzz", content="x")+ )++ assert artifact["error"] == "notebook_not_found"++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_update_notebook_from_other_team_is_not_found(self):+ def _make_foreign_note() -> str:+ other_team = Team.objects.create(organization=self.organization)+ other_account = Account.objects.unscoped().create(team=other_team, name="Foreign")+ notebook = Notebook.objects.create(+ team=other_team, title="Foreign", content={}, visibility=Notebook.Visibility.INTERNAL+ )+ ResourceNotebook.objects.create(notebook=notebook, account=other_account)+ return notebook.short_id++ foreign_short_id = await sync_to_async(_make_foreign_note)()++ _, artifact = await self._tool()._arun_impl(+ action=UpdateAccountNotebookAction(notebook_short_id=foreign_short_id, content="x")+ )++ assert artifact["error"] == "notebook_not_found"diff --git a/products/customer_analytics/backend/max_tools/upsert_account.py b/products/customer_analytics/backend/max_tools/upsert_account.pynew file mode 100644index 000000000000..92d697e096f2--- /dev/null+++ b/products/customer_analytics/backend/max_tools/upsert_account.py@@ -0,0 +1,215 @@+from textwrap import dedent+from typing import Any, Literal, Union++from django.core.exceptions import ValidationError+from django.db import IntegrityError, transaction++from asgiref.sync import sync_to_async+from pydantic import BaseModel, ConfigDict, Field++from posthog.api.tagged_item import set_tags_on_object+from posthog.exceptions_capture import capture_exception+from posthog.rbac.user_access_control import AccessControlLevel+from posthog.scopes import APIScopeObject++from products.customer_analytics.backend.models import Account++from ee.hogai.tool import MaxTool++UPSERT_ACCOUNT_TOOL_DESCRIPTION = dedent("""+ Use this tool to create a new customer account or update an existing one.++ An account represents a customer organization. Its `external_id` must be the id PostHog uses to+ identify that organization in group analytics (its group key) — this is what links the account to+ its usage and activity data, so it must match exactly. Do NOT put a CRM or billing id here; record+ those with the dedicated properties (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id,+ zendesk_id).++ # Actions+ - **create**: Create a new account (requires `name`).+ - **update**: Edit an existing account (requires `account_id`; all other fields optional).++ # Finding an account to update+ Resolve `account_id` (a UUID) first via `read_data`/`list_data` with the account kind.++ # Properties+ `properties` carries typed fields. Assignment fields (csm, account_executive, account_owner) take+ an object `{id, email}` (the PostHog user id and email) or null to clear. External-system ids+ (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id) are strings.+ On **update**, only the property keys you pass are changed (others are preserved); pass a key as+ null to clear it.++ # Tags+ Pass `tags` to set the account's tags. On update this REPLACES the existing tag set.++ # Examples+ - "Add an account for Acme Corp whose PostHog group key is acme-123": action=create, name="Acme Corp", external_id="acme-123"+ - "Assign Jane (user 42, [email protected]) as CSM for that account": action=update, account_id=<uuid>,+ properties={csm: {id: 42, email: "[email protected]"}}+ - "Tag it enterprise and priority": action=update, account_id=<uuid>, tags=["enterprise", "priority"]+ """).strip()+++class AccountAssignment(BaseModel):+ model_config = ConfigDict(extra="forbid")+ id: int = Field(description="PostHog user id of the assignee")+ email: str = Field(description="Email of the assignee")+++class AccountPropertiesInput(BaseModel):+ model_config = ConfigDict(extra="forbid")+ csm: AccountAssignment | None = Field(default=None, description="Customer success manager assignment")+ account_executive: AccountAssignment | None = Field(default=None, description="Account executive assignment")+ account_owner: AccountAssignment | None = Field(default=None, description="Account owner assignment")+ stripe_customer_id: str | None = Field(default=None, description="Stripe customer id")+ hubspot_deal_id: str | None = Field(default=None, description="HubSpot deal id")+ billing_id: str | None = Field(default=None, description="Billing system id")+ sfdc_id: str | None = Field(default=None, description="Salesforce id")+ zendesk_id: str | None = Field(default=None, description="Zendesk id")+++class CreateAccountAction(BaseModel):+ action: Literal["create"] = "create"+ name: str = Field(description="Human-readable account name, e.g. 'Acme Corp'")+ external_id: str | None = Field(+ default=None,+ description=(+ "The id PostHog uses to identify this organization in group analytics (its group key). "+ "Links the account to its usage and activity data, so it must match exactly. Do not put a "+ "CRM/billing id here — record those with the properties fields. Optional but strongly "+ "recommended."+ ),+ )+ tags: list[str] | None = Field(default=None, description="Tag names to attach to the account")+ properties: AccountPropertiesInput | None = Field(default=None, description="Typed account properties")+++class UpdateAccountAction(BaseModel):+ action: Literal["update"] = "update"+ account_id: str = Field(description="UUID of the account to update")+ name: str | None = Field(default=None, description="New account name")+ external_id: str | None = Field(+ default=None,+ description="New external id — the organization's group key in PostHog, not a CRM/billing id.",+ )+ tags: list[str] | None = Field(default=None, description="Replaces the account's existing tags")+ properties: AccountPropertiesInput | None = Field(+ default=None, description="Property keys to merge; pass a key as null to clear it"+ )+++UpsertAccountAction = Union[CreateAccountAction, UpdateAccountAction]+++class UpsertAccountToolArgs(BaseModel):+ action: UpsertAccountAction = Field(+ description="Create a new account or update an existing one.",+ discriminator="action",+ )+++class UpsertAccountTool(MaxTool):+ name: str = "upsert_account"+ description: str = UPSERT_ACCOUNT_TOOL_DESCRIPTION+ args_schema: type[BaseModel] = UpsertAccountToolArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("account", "editor")]++ async def _arun_impl(self, action: UpsertAccountAction) -> tuple[str, dict[str, Any]]:+ if isinstance(action, CreateAccountAction):+ return await self._handle_create(action)+ return await self._handle_update(action)++ async def _handle_create(self, action: CreateAccountAction) -> tuple[str, dict[str, Any]]:+ properties = action.properties.model_dump(exclude_unset=True) if action.properties is not None else {}+ try:+ account = await self._create_account(action, properties)+ except IntegrityError:+ return f"An account with external_id '{action.external_id}' already exists for this team.", {+ "error": "duplicate_external_id",+ }+ except Exception as e:+ capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})+ return f"Failed to create account: {str(e)}", {"error": "creation_failed", "details": str(e)}++ return (+ f"Account '{account.name}' created successfully.",+ self._artifact(account),+ )++ async def _handle_update(self, action: UpdateAccountAction) -> tuple[str, dict[str, Any]]:+ account = await self._resolve_account(action.account_id)+ if account is None:+ return f"Account '{action.account_id}' not found.", {"error": "account_not_found"}++ await self.check_object_access(account, "editor", resource="account", action="edit")++ if action.name is None and action.external_id is None and action.tags is None and action.properties is None:+ return "No changes provided. Specify at least one field to update.", {"error": "no_changes"}++ try:+ account = await self._update_account(account, action)+ except IntegrityError:+ return f"An account with external_id '{action.external_id}' already exists for this team.", {+ "error": "duplicate_external_id",+ }+ except Exception as e:+ capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})+ return f"Failed to update account: {str(e)}", {"error": "update_failed", "details": str(e)}++ return (+ f"Account '{account.name}' updated successfully.",+ self._artifact(account),+ )++ @staticmethod+ def _artifact(account: Account) -> dict[str, Any]:+ return {+ "account_id": str(account.id),+ "name": account.name,+ "external_id": account.external_id,+ }++ async def _resolve_account(self, account_id: str) -> Account | None:+ account_id = str(account_id).strip()+ if not account_id:+ return None+ try:+ return await Account.objects.unscoped().aget(id=account_id, team=self._team)+ except (Account.DoesNotExist, ValidationError, ValueError):+ return None++ @sync_to_async+ def _create_account(self, action: CreateAccountAction, properties: dict[str, Any]) -> Account:+ with transaction.atomic():+ account = Account.objects.unscoped().create(+ team=self._team,+ created_by=self._user,+ name=action.name[:400],+ external_id=(action.external_id[:400] if action.external_id else None),+ _properties=properties,+ )+ if action.tags is not None:+ set_tags_on_object(action.tags, account)+ return account++ @sync_to_async+ def _update_account(self, account: Account, action: UpdateAccountAction) -> Account:+ with transaction.atomic():+ update_fields: list[str] = []+ if action.name is not None:+ account.name = action.name[:400]+ update_fields.append("name")+ if action.external_id is not None:+ account.external_id = action.external_id[:400] or None+ update_fields.append("external_id")+ if action.properties is not None:+ merged = {**(account._properties or {}), **action.properties.model_dump(exclude_unset=True)}+ account._properties = merged+ update_fields.append("_properties")+ if update_fields:+ account.save(update_fields=update_fields)+ if action.tags is not None:+ set_tags_on_object(action.tags, account)+ return accountdiff --git a/products/customer_analytics/backend/max_tools/upsert_account_notebook.py b/products/customer_analytics/backend/max_tools/upsert_account_notebook.pynew file mode 100644index 000000000000..3cc45d35e528--- /dev/null+++ b/products/customer_analytics/backend/max_tools/upsert_account_notebook.py@@ -0,0 +1,185 @@+from textwrap import dedent+from typing import Any, Literal, Union++from django.core.exceptions import ValidationError+from django.db import transaction+from django.utils import timezone++from asgiref.sync import sync_to_async+from pydantic import BaseModel, Field++from posthog.exceptions_capture import capture_exception+from posthog.rbac.user_access_control import AccessControlLevel+from posthog.scopes import APIScopeObject++from products.customer_analytics.backend.models import Account+from products.notebooks.backend.models import Notebook, ResourceNotebook++from ee.hogai.tool import MaxTool+from ee.hogai.tools.create_notebook.tiptap import markdown_to_tiptap_nodes++UPSERT_ACCOUNT_NOTEBOOK_TOOL_DESCRIPTION = dedent("""+ Create or update a note attached to a customer account — a call recap, a meeting summary, an+ investigation timeline, or any free-form context worth persisting. Notes appear under the+ account's Notes tab in the Accounts list. Write the note body (`content`) in Markdown.++ # Actions+ - **create**: Add a new note to an account (requires `account_id`, a UUID). If you only have a+ name, resolve the account first with read_data/list_data using the account kind.+ - **update**: Revise an existing note (requires `notebook_short_id`). Pass a new `title` and/or+ `content`; `content` REPLACES the existing body, so send the full updated note, not just the+ change. Use the short_id returned when the note was created.+ """).strip()+++def _tiptap_doc(markdown: str) -> dict[str, Any]:+ return {"type": "doc", "content": markdown_to_tiptap_nodes(markdown) or [{"type": "paragraph"}]}+++class CreateAccountNotebookAction(BaseModel):+ action: Literal["create"] = "create"+ account_id: str = Field(description="UUID of the account to attach the note to.")+ title: str = Field(description="Short, descriptive title, e.g. 'Q3 kickoff call recap'.")+ content: str = Field(description="The note body in Markdown.")+++class UpdateAccountNotebookAction(BaseModel):+ action: Literal["update"] = "update"+ notebook_short_id: str = Field(description="short_id of the account note to update.")+ title: str | None = Field(default=None, description="New title; leave unset to keep the current one.")+ content: str | None = Field(+ default=None,+ description="New note body in Markdown; replaces the existing content. Leave unset to keep it.",+ )+++UpsertAccountNotebookAction = Union[CreateAccountNotebookAction, UpdateAccountNotebookAction]+++class UpsertAccountNotebookToolArgs(BaseModel):+ action: UpsertAccountNotebookAction = Field(+ description="Create a new account note or update an existing one.",+ discriminator="action",+ )+++class UpsertAccountNotebookTool(MaxTool):+ name: str = "upsert_account_notebook"+ description: str = UPSERT_ACCOUNT_NOTEBOOK_TOOL_DESCRIPTION+ args_schema: type[BaseModel] = UpsertAccountNotebookToolArgs++ def get_required_resource_access(self) -> list[tuple[APIScopeObject, AccessControlLevel]]:+ return [("account", "editor")]++ async def _arun_impl(self, action: UpsertAccountNotebookAction) -> tuple[str, dict[str, Any]]:+ if isinstance(action, CreateAccountNotebookAction):+ return await self._handle_create(action)+ return await self._handle_update(action)++ async def _handle_create(self, action: CreateAccountNotebookAction) -> tuple[str, dict[str, Any]]:+ account = await self._resolve_account(action.account_id)+ if account is None:+ return f"Account '{action.account_id}' not found.", {"error": "account_not_found"}++ await self.check_object_access(account, "editor", resource="account", action="edit")++ try:+ notebook = await self._create_notebook(account, action)+ except Exception as e:+ capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})+ return f"Failed to create the note: {str(e)}", {"error": "creation_failed", "details": str(e)}++ return f"Created the note '{notebook.title}' on {account.name}.", self._artifact(notebook, account)++ async def _handle_update(self, action: UpdateAccountNotebookAction) -> tuple[str, dict[str, Any]]:+ if action.title is None and action.content is None:+ return "No changes provided. Specify a new title or content.", {"error": "no_changes"}++ resolved = await self._resolve_account_notebook(action.notebook_short_id)+ if resolved is None:+ return f"Account note '{action.notebook_short_id}' not found.", {"error": "notebook_not_found"}+ notebook, account = resolved++ await self.check_object_access(account, "editor", resource="account", action="edit")++ try:+ notebook = await self._update_notebook(notebook, action)+ except Exception as e:+ capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})+ return f"Failed to update the note: {str(e)}", {"error": "update_failed", "details": str(e)}++ return f"Updated the note '{notebook.title}' on {account.name}.", self._artifact(notebook, account)++ @staticmethod+ def _artifact(notebook: Notebook, account: Account) -> dict[str, Any]:+ return {+ "account_id": str(account.id),+ "account_name": account.name,+ "external_id": account.external_id,+ "notebook_short_id": notebook.short_id,+ "title": notebook.title,+ }++ async def _resolve_account(self, account_id: str) -> Account | None:+ account_id = str(account_id).strip()+ if not account_id:+ return None+ try:+ return await Account.objects.unscoped().aget(id=account_id, team=self._team)+ except (Account.DoesNotExist, ValidationError, ValueError):+ return None++ async def _resolve_account_notebook(self, short_id: str) -> tuple[Notebook, Account] | None:+ short_id = str(short_id).strip()+ if not short_id:+ return None+ try:+ link = (+ await ResourceNotebook.objects.filter(+ notebook__short_id=short_id,+ notebook__team=self._team,+ notebook__deleted=False,+ notebook__visibility=Notebook.Visibility.INTERNAL,+ account__isnull=False,+ )+ .select_related("notebook", "account")+ .afirst()+ )+ except (ValidationError, ValueError):+ return None+ if link is None or link.account is None:+ return None+ return link.notebook, link.account++ @sync_to_async+ def _create_notebook(self, account: Account, action: CreateAccountNotebookAction) -> Notebook:+ with transaction.atomic():+ notebook = Notebook.objects.create(+ team=self._team,+ created_by=self._user,+ last_modified_by=self._user,+ visibility=Notebook.Visibility.INTERNAL,+ title=action.title[:256],+ text_content=action.content,+ content=_tiptap_doc(action.content),+ )+ ResourceNotebook.objects.create(notebook=notebook, account=account)+ return notebook++ @sync_to_async+ def _update_notebook(self, notebook: Notebook, action: UpdateAccountNotebookAction) -> Notebook:+ with transaction.atomic():+ locked = Notebook.objects.select_for_update().get(pk=notebook.pk)+ locked.last_modified_at = timezone.now()+ locked.last_modified_by = self._user+ update_fields = ["last_modified_at", "last_modified_by"]+ if action.title is not None:+ locked.title = action.title[:256]+ update_fields.append("title")+ if action.content is not None:+ locked.content = _tiptap_doc(action.content)+ locked.text_content = action.content+ locked.version = locked.version + 1+ update_fields += ["content", "text_content", "version"]+ locked.save(update_fields=update_fields)+ return lockeddiff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 6fbbcbaf729b..b3b2f5f86a82 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -1,6 +1,94 @@# Accounts — agent guide-Guidance for agents working on the Accounts area of Customer analytics (`products/customer_analytics/frontend/components/Accounts/`). Scope is the **Accounts list** only, not the rest of Customer analytics.+Development guide for the Accounts area of Customer analytics (`products/customer_analytics/frontend/components/Accounts/`).+Scope is the **Accounts list** only, not the rest of Customer analytics.+This file should carry the full context needed to work here — architecture, data flow, conventions, and analytics — not just events.++> **Keep this guide current.** Whenever you change the Accounts area — add or refactor a component, logic, tab, event, filter, query column, or behavior — update this file in the same change so it stays an accurate map of how the Accounts list works.++## What this is++An **Account** is a customer organization. The list is a HogQL-backed table over the `system.accounts` table, with per-row expansion into Notes / Users / Usage, inline role assignment (CSM, AE, owner), configurable columns, overview metric tiles, shareable views, and a Max (AI) contextual tool for opening accounts.++`Account.external_id` is the PostHog **group key** — it's how an account joins to its group-analytics data (usage, events, feature flags). Treat it as the account's analytics identity, not a CRM id (CRM/billing ids live in account properties). The account→group bridge lives in the backend query runner and the agent mode, not here — see [Backend touchpoints](#backend-touchpoints). Keep this mechanism out of any user-facing copy (it's a façade — see the agent mode preset).++## Architecture++The scene renders `AccountsTabContent`, which binds one `dataNodeLogic` (key `ACCOUNTS_HOGQL_DATA_NODE_KEY`, from `../../constants`) to the query built by `accountsLogic.hogqlQuery`. Everything else reads from that bound data node or from the logics below.++```text+AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, accountsLogic.hogqlQuery.source)+├── AccountsMaxTools registers the `open_account` Max contextual tool → accountsLogic.openAccount+├── AccountsTabFilters search / tags / role filters / "unassigned only"+├── AccountsOverviewTilesButton + AccountsColumnConfigurator+├── AccountsOverviewTiles metric tiles across the filtered set+└── AccountsHogQLTable the DataTable; per-column renderers; controlled row expansion+ └── AccountNotebooksExpansion expanded row: Useful links + LemonTabs(Notes/Users/Usage)+ ├── (notes) in-place LemonTable of linked notebooks (accountNotebooksLogic, keyed by accountId)+ ├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId)+ └── (usage) AccountBillingExpansion kind="usage" (accountBillingLogic — a saved billing-usage insight)+```++### Logics and what each owns++| Logic | Owns |+| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `accountsLogic` | The hub. Search (debounced), tag/role filters, sort, inline role assignment, the `hogqlQuery` selector, shareable URL-hash view state, and `openAccount` (the Max entry point). `connect`s column-config, overview-tiles, and expansion logics. |+| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), the column-picker groups built from the DB schema + data-warehouse joins, and the per-team saved column config (`columnConfigurations` API). |+| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |+| `accountsOverviewTilesLogic` | The overview metric tiles (persisted per team); feeds `metrics` into the query. |+| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`). |+| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). |+| `accountBillingLogic` | Billing/usage data behind the Usage tab. |+| `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |++## Data & query model++`accountsLogic.hogqlQuery` builds a `DataTableNode` wrapping an `AccountsQuery` (`select`, plus optional `search`, `tagNames`, role filters, `allRolesUnassigned`, `filterExpression`, `metrics`, `orderBy`). The backend runner (`accounts_query_runner`) returns **rows as arrays** aligned to `visibleColumnNames`. Two cell shapes matter:++- **`name` column** (mandatory, `ACCOUNTS_NAME_COLUMN`) — emitted as `tuple(name, external_id, id)`, read as `{ name, external_id, id }`. This is the row's identity: `id` (the account PK) drives expansion/scroll/role updates; `external_id` is the copy-able group key. `getNameCell()` in `AccountsHogQLTable.tsx` is the canonical accessor; never assume a column index.+- **role columns** (`csm`, `account_executive`, `account_owner`) — emitted as `tuple(id, email)`, rendered with `MemberSelect`. Sorting these uses `tupleElement(col, 2)` (email) so visual order matches.++Default columns (`ACCOUNTS_HOGQL_DEFAULT_SELECT`): `name`, `tag_names`, `notebook_count`, `csm`, `account_executive`, `account_owner`. The name column is force-kept (`ensureNameColumn`) — removing it breaks identity, scroll, and role edits. Extra columns come from account properties, lazy/virtual-table joins under `system.accounts`, data-warehouse joins, or freeform SQL — all assembled by `buildAccountColumnGroups`.++Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemoved`), else the backend gets an `orderBy` referencing a missing alias.++## The expanded row++`AccountsHogQLTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `usage` (`AccountExpansionTab`) plus the Useful links sidebar. Active tab comes from `activeTabFor(accountId)` (defaults to `notes`).++The Usage tab renders an existing saved billing-usage insight — **point users to it, don't rebuild usage as a new insight.**++## Shareable view state++`accountsLogic` mirrors the full view (search, tags, roles, unassigned, sort, columns, tile filter) into the URL hash `#view=...` via `actionToUrl`/`urlToAction`, so a copied URL reproduces the exact list. Only non-default values are serialized. A shared link's `columns` win over the per-user saved column config (`accountsColumnConfigLogic` enforces this when its async saved-config load resolves by checking the live URL).++## Max / agent integration++The Accounts list exposes one contextual tool, `open_account`, so Max can show an account on screen.++1. Backend `OpenAccountTool` (`products/customer_analytics/backend/max_tools/open_account.py`) resolves the account by `external_id` or name and returns `{ account_id, account_name, external_id, tab }`.+2. `AccountsMaxTools.tsx` registers it with `useMaxTool({ identifier: 'open_account', callback })`; the callback calls `accountsLogic.openAccount(accountId, externalId, name, tab)`.+3. `accountsLogic.openAccount`:+ - **Reveal** — if the account isn't in the current results (checks the bound data node's rows by name-cell `id`), it clears the excluding filters and searches by `external_id`/name so the row will render. This avoids a silent no-op when Max references an account that's filtered out.+ - **Expand** — dispatches `openAccountTab(accountId, tab)` (programmatic; deliberately does **not** fire the tab-viewed event).+ - **Scroll** — polls for the row's `[data-account-id]` node (revealing triggers an async refetch, so it may not exist yet) and smooth-scrolls it into view (`block: 'center'`). Runs through `cache.disposables` keyed `scrollToAccount` (a second open cancels a pending scroll), one-shot via `pauseOnPageHidden: false`. The scroll anchor is `data-account-id={id}` on the name cell in `AccountsHogQLTable.tsx` — keep it there.++The tool is registered for the page regardless of agent mode. The Customer analytics agent mode and the account→group bridge live in the backend (see below); keep their mechanics out of user-facing copy.++### Backend touchpoints++- `products/customer_analytics/backend/models` — the `Account` model (`external_id` = group key).+- `products/customer_analytics/backend/` — `accounts_query_runner` (builds the list rows + cell tuples).+- `products/customer_analytics/backend/max_tools/` — `OpenAccountTool` and other account Max tools.+- `ee/hogai/core/agent_modes/presets/customer_analytics.py` — the Customer analytics agent mode (gated by the `customer-analytics-csp` flag).++## Conventions++- **kea, not hooks** — business logic lives in the logics above; components are thin views. The one DOM concession is the `data-account-id` anchor for scroll. Resources needing cleanup (the scroll poll) go through `cache.disposables`, never a bare `setTimeout` + `beforeUnmount`.+- **Guard network triggers against double-submission** — role assignment disables its control while saving (`isRoleSaving`); follow the same pattern for any new mutation.+- **Capture exceptions** — wrap API calls and report failures with `posthog.captureException(error, { scope: '...' })` plus a `lemonToast`.+- **Tests & stories** — logics have `*.test.ts` siblings (`accountsLogic.test.ts`, etc.); `AccountsTab.stories.tsx` covers the rendered table. Add coverage alongside new behavior.## Analytics events@@ -15,20 +103,20 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions### Tracked events-| Event | Fires from | Properties |-| --------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `customer analytics accounts list viewed` | `accountsLogic` `afterMount` | _(none — funnel anchor; account count and saved-config aren't loaded at mount)_ |-| `customer analytics accounts filter changed` | `accountsLogic` `reportFilterChange` listener (dispatched by the filter controls) | `filter_type` (`tag` \| `csm` \| `account_executive` \| `account_owner` \| `unassigned_only`), `value`, `is_cleared`, `active_filter_count`; for `tag` also `tag_count` |-| `customer analytics accounts searched` | `accountsLogic` `setSearchInput` listener (post-debounce) | `query_length`, `has_query`, `active_filter_count` |-| `customer analytics accounts refreshed` | `accountsLogic` `refresh` | `has_search`, `active_filter_count`, `sort_column` |-| `customer analytics accounts sorted` | `accountsLogic` `toggleSort` | `column`, `direction` (`asc` \| `desc` \| `cleared`) |-| `customer analytics accounts columns saved` | `accountsColumnConfigLogic` `saveColumns` (success, only when changed) | `column_count`, `columns`, `added_count`, `removed_count`, `reordered` |-| `customer analytics accounts overview tiles edited` | `accountsOverviewTilesLogic` editor close (diffed vs open snapshot, only when changed) | `tiles_added`, `tiles_removed`, `tiles_updated`, `reordered`, `tile_count_before`, `tile_count_after` |-| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner`), `is_assigned`, `assigned_user_id`, `source` (always `list_row` today) |-| `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` | `link_key`, `has_destination` |-| `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |-| `customer analytics account tab viewed` | `AccountNotebooksExpansion.tsx` `LemonTabs` `onChange` | `tab` (`notes` \| `users`) |-| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |+| Event | Fires from | Properties |+| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `customer analytics accounts list viewed` | `accountsLogic` `afterMount` | _(none — funnel anchor; account count and saved-config aren't loaded at mount)_ |+| `customer analytics accounts filter changed` | `accountsLogic` `reportFilterChange` listener (dispatched by the filter controls) | `filter_type` (`tag` \| `csm` \| `account_executive` \| `account_owner` \| `unassigned_only`), `value`, `is_cleared`, `active_filter_count`; for `tag` also `tag_count` |+| `customer analytics accounts searched` | `accountsLogic` `setSearchInput` listener (post-debounce) | `query_length`, `has_query`, `active_filter_count` |+| `customer analytics accounts refreshed` | `accountsLogic` `refresh` | `has_search`, `active_filter_count`, `sort_column` |+| `customer analytics accounts sorted` | `accountsLogic` `toggleSort` | `column`, `direction` (`asc` \| `desc` \| `cleared`) |+| `customer analytics accounts columns saved` | `accountsColumnConfigLogic` `saveColumns` (success, only when changed) | `column_count`, `columns`, `added_count`, `removed_count`, `reordered` |+| `customer analytics accounts overview tiles edited` | `accountsOverviewTilesLogic` editor close (diffed vs open snapshot, only when changed) | `tiles_added`, `tiles_removed`, `tiles_updated`, `reordered`, `tile_count_before`, `tile_count_after` |+| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner`), `is_assigned`, `assigned_user_id`, `source` (always `list_row` today) |+| `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` | `link_key`, `has_destination` |+| `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |+| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `usage`) |+| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |> **Keep this table up to date.** Whenever you add, rename, or remove a `posthog.capture()` event in the Accounts area — or change its properties — update this table in the same change. An agent reading this file should be able to trust it as the source of truth for what the Accounts list reports.diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsxindex 9bd7be4d6233..957006f5f843 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx@@ -1,6 +1,5 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'import posthog from 'posthog-js'-import { useState } from 'react'import { IconGraph, IconPeople, IconPiggyBank, IconReceipt } from '@posthog/icons'import {@@ -24,6 +23,7 @@ import { AccountBillingExpansion } from './AccountBillingExpansion'import { accountLinksLogic } from './accountLinksLogic'import { accountNotebooksLogic } from './accountNotebooksLogic'import { AccountRelatedUsersExpansion } from './AccountRelatedUsersExpansion'+import { accountsExpansionLogic } from './accountsExpansionLogic'import { AccountsEvents } from './constants'import { EditAccountLinksButton } from './EditAccountLinksButton'@@ -95,7 +95,9 @@ export function AccountNotebooksExpansion({}): JSX.Element {const logic = accountNotebooksLogic({ accountId })const { notebooks, notebooksLoading } = useValues(logic)- const [activeTab, setActiveTab] = useState<'notes' | 'users' | 'usage'>('notes')+ const { activeTabFor } = useValues(accountsExpansionLogic)+ const { setActiveTab } = useActions(accountsExpansionLogic)+ const activeTab = activeTabFor(accountId)const columns: LemonTableColumns<AccountNotebookApi> = [{@@ -163,10 +165,7 @@ export function AccountNotebooksExpansion({<div className="flex-1 min-w-0"><LemonTabsactiveKey={activeTab}- onChange={(tab) => {- setActiveTab(tab)- posthog.capture(AccountsEvents.TabViewed, { tab })- }}+ onChange={(tab) => setActiveTab(accountId, tab)}size="small"tabs={[{diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsxindex 9dd6c0c31149..80586e1f1804 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx@@ -17,6 +17,7 @@ import { QueryContext, QueryContextColumn, QueryContextColumnComponent } from '~import { ACCOUNTS_HOGQL_DATA_NODE_KEY } from '../../constants'import { AccountNotebooksExpansion } from './AccountNotebooksExpansion'import { ACCOUNTS_NAME_COLUMN, accountsColumnConfigLogic } from './accountsColumnConfigLogic'+import { accountsExpansionLogic } from './accountsExpansionLogic'import { AccountRoleKey, accountsLogic } from './accountsLogic'type AccountAssignment = { id: number; email: string } | null@@ -82,7 +83,7 @@ function NameCell({ record }: { record: unknown }): JSX.Element {const name = cell?.name ?? ''const externalId = cell?.external_id ?? ''return (- <div className="flex flex-col min-w-40">+ <div className="flex flex-col min-w-40" data-account-id={cell?.id}><span className="font-medium">{name}</span>{externalId ? (<CopyToClipboardInline@@ -242,10 +243,28 @@ function useContextColumns(): Record<string, QueryContextColumn> {function useExpandable(): QueryContext<DataTableNode>['expandable'] {const { visibleColumnNames } = useValues(accountsColumnConfigLogic)+ const { expandedAccountIds } = useValues(accountsExpansionLogic)+ const { toggleAccountExpanded } = useActions(accountsExpansionLogic)return useMemo(() => ({noIndent: true,expandedRowClassName: '[&>td]:overflow-visible!',+ isRowExpanded: ({ result }) => {+ const cell = getNameCell(result, visibleColumnNames)+ return !!cell && expandedAccountIds.includes(cell.id)+ },+ onRowExpand: ({ result }) => {+ const cell = getNameCell(result, visibleColumnNames)+ if (cell) {+ toggleAccountExpanded(cell.id)+ }+ },+ onRowCollapse: ({ result }) => {+ const cell = getNameCell(result, visibleColumnNames)+ if (cell) {+ toggleAccountExpanded(cell.id)+ }+ },expandedRowRender: ({ result }) => {const cell = getNameCell(result, visibleColumnNames)return cell ? (@@ -253,7 +272,7 @@ function useExpandable(): QueryContext<DataTableNode>['expandable'] {) : null},}),- [visibleColumnNames]+ [visibleColumnNames, expandedAccountIds, toggleAccountExpanded])}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsMaxTools.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsMaxTools.tsxnew file mode 100644index 000000000000..fdbd1fa69289--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountsMaxTools.tsx@@ -0,0 +1,33 @@+import { useActions } from 'kea'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { useMaxTool } from 'scenes/max/useMaxTool'++import { AccountExpansionTab } from './accountsExpansionLogic'+import { accountsLogic } from './accountsLogic'++interface OpenAccountResult {+ account_id?: string+ account_name?: string+ external_id?: string | null+ tab?: AccountExpansionTab+ error?: string+}++export function AccountsMaxTools(): JSX.Element | null {+ const { openAccount } = useActions(accountsLogic)++ useMaxTool({+ identifier: 'open_account',+ context: {},+ callback: (result: OpenAccountResult) => {+ if (result?.error || !result.account_id) {+ lemonToast.error("Couldn't open that account.")+ return+ }+ openAccount(result.account_id, result.external_id ?? null, result.account_name ?? '', result.tab ?? 'usage')+ },+ })++ return null+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsxindex 4637e76c311b..400a48933ed2 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabContent.tsx@@ -6,6 +6,7 @@ import { ACCOUNTS_HOGQL_DATA_NODE_KEY } from '../../constants'import { AccountsColumnConfigurator } from './AccountsColumnConfigurator'import { AccountsHogQLTable } from './AccountsHogQLTable'import { accountsLogic } from './accountsLogic'+import { AccountsMaxTools } from './AccountsMaxTools'import { AccountsOverviewTiles } from './AccountsOverviewTiles'import { AccountsOverviewTilesButton } from './AccountsOverviewTilesButton'import { AccountsTabFilters } from './AccountsTabFilters'@@ -22,6 +23,7 @@ export function AccountsTabContent(): JSX.Element {}}><div className="flex flex-col gap-3">+ <AccountsMaxTools /><AccountsTabFilters /><div className="flex justify-end gap-2"><AccountsOverviewTilesButton />diff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.tsnew file mode 100644index 000000000000..2e1cd7bbe5bf--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts@@ -0,0 +1,56 @@+import { actions, kea, listeners, path, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import type { accountsExpansionLogicType } from './accountsExpansionLogicType'+import { AccountsEvents } from './constants'++export type AccountExpansionTab = 'notes' | 'users' | 'usage'++export const DEFAULT_ACCOUNT_TAB: AccountExpansionTab = 'notes'++export const accountsExpansionLogic = kea<accountsExpansionLogicType>([+ path(['scenes', 'customerAnalytics', 'accounts', 'accountsExpansionLogic']),+ actions({+ toggleAccountExpanded: (accountId: string) => ({ accountId }),+ setActiveTab: (accountId: string, tab: AccountExpansionTab) => ({ accountId, tab }),+ openAccountTab: (accountId: string, tab: AccountExpansionTab) => ({ accountId, tab }),+ }),+ reducers({+ expandedAccountIds: [+ [] as string[],+ {+ toggleAccountExpanded: (state, { accountId }) =>+ state.includes(accountId) ? state.filter((id) => id !== accountId) : [...state, accountId],+ openAccountTab: (state, { accountId }) => (state.includes(accountId) ? state : [...state, accountId]),+ },+ ],+ activeTabByAccount: [+ {} as Record<string, AccountExpansionTab>,+ {+ setActiveTab: (state, { accountId, tab }) => ({ ...state, [accountId]: tab }),+ openAccountTab: (state, { accountId, tab }) => ({ ...state, [accountId]: tab }),+ },+ ],+ }),+ selectors({+ isAccountExpanded: [+ (s) => [s.expandedAccountIds],+ (expandedAccountIds) =>+ (accountId: string): boolean =>+ expandedAccountIds.includes(accountId),+ ],+ activeTabFor: [+ (s) => [s.activeTabByAccount],+ (activeTabByAccount) =>+ (accountId: string): AccountExpansionTab =>+ activeTabByAccount[accountId] ?? DEFAULT_ACCOUNT_TAB,+ ],+ }),+ listeners({+ // Only genuine user tab clicks report engagement. Programmatic navigation+ // (openAccountTab) deliberately does not, to avoid phantom events.+ setActiveTab: ({ tab }) => {+ posthog.capture(AccountsEvents.TabViewed, { tab })+ },+ }),+])diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.tsindex b5c3a28640f6..2faaef84e07b 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts@@ -18,13 +18,23 @@ import type {} from 'products/customer_analytics/frontend/generated/api.schemas'import { ACCOUNTS_HOGQL_DATA_NODE_KEY, CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'-import { ACCOUNTS_HOGQL_DEFAULT_SELECT, accountsColumnConfigLogic } from './accountsColumnConfigLogic'+import {+ ACCOUNTS_HOGQL_DEFAULT_SELECT,+ ACCOUNTS_NAME_COLUMN,+ accountsColumnConfigLogic,+} from './accountsColumnConfigLogic'+import { AccountExpansionTab, accountsExpansionLogic } from './accountsExpansionLogic'import type { accountsLogicType } from './accountsLogicType'import { accountsOverviewTilesLogic, TileFilter } from './accountsOverviewTilesLogic'import { AccountsEvents } from './constants'export const SEARCH_DEBOUNCE_MS = 300+// Revealing an off-screen account triggers an async refetch, so its row may not+// be in the DOM yet — poll briefly for it before scrolling.+const SCROLL_TO_ACCOUNT_POLL_MS = 100+const SCROLL_TO_ACCOUNT_MAX_ATTEMPTS = 40+interface SortLikeValues {sortOrder: AccountSortOrdervisibleColumnNames: string[]@@ -127,6 +137,8 @@ export const accountsLogic = kea<accountsLogicType>([['setSelectColumns', 'selectColumn', 'unselectColumn', 'moveColumn', 'resetColumns'],accountsOverviewTilesLogic,['setTileFilter'],+ accountsExpansionLogic,+ ['openAccountTab'],],})),actions({@@ -152,6 +164,12 @@ export const accountsLogic = kea<accountsLogicType>([roleUpdateStarted: (accountId: string, role: AccountRoleKey) => ({ accountId, role }),roleUpdateFinished: (accountId: string, role: AccountRoleKey) => ({ accountId, role }),replaceAccount: (account: AccountApi) => ({ account }),+ openAccount: (accountId: string, externalId: string | null, name: string, tab: AccountExpansionTab) => ({+ accountId,+ externalId,+ name,+ tab,+ }),}),reducers({searchInput: [@@ -384,7 +402,7 @@ export const accountsLogic = kea<accountsLogicType>([},],}),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, cache }) => ({setSearchInput: async ({ query }, breakpoint) => {await breakpoint(SEARCH_DEBOUNCE_MS)actions.setSearchQuery(query)@@ -517,6 +535,64 @@ export const accountsLogic = kea<accountsLogicType>([actions.roleUpdateFinished(accountId, role)}},+ openAccount: ({ accountId, externalId, name, tab }) => {+ const dataNode = dataNodeLogic.findMounted({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY })+ const results = (dataNode?.values.response as { results?: unknown[] } | undefined)?.results+ const rows = Array.isArray(results) ? results : []+ const nameIndex = values.visibleColumnNames.indexOf(ACCOUNTS_NAME_COLUMN)+ const isVisible =+ nameIndex >= 0 &&+ rows.some((row) => {+ const cell = Array.isArray(row) ? (row as unknown[])[nameIndex] : undefined+ return !!cell && typeof cell === 'object' && (cell as { id?: string }).id === accountId+ })+ // Reveal the account if it isn't currently shown, so the expanded row actually renders.+ if (!isVisible) {+ if (values.tagsFilter.length > 0) {+ actions.setTagsFilter([])+ }+ if (values.allRolesUnassigned) {+ actions.setAllRolesUnassigned(false)+ }+ if (values.csmFilter.length > 0) {+ actions.setCsmFilter([])+ }+ if (values.accountExecutiveFilter.length > 0) {+ actions.setAccountExecutiveFilter([])+ }+ if (values.accountOwnerFilter.length > 0) {+ actions.setAccountOwnerFilter([])+ }+ const term = externalId || name+ if (term) {+ actions.setSearchQuery(term)+ }+ }+ actions.openAccountTab(accountId, tab)+ // Keyed so a second open cancels a still-pending scroll. One-shot, so+ // it opts out of pause-on-hidden rather than re-scrolling on tab return.+ cache.disposables.add(+ () => {+ let attempts = 0+ let timer: number | undefined+ const scrollWhenReady = (): void => {+ const row = document.querySelector(`[data-account-id="${accountId}"]`)+ if (row) {+ row.scrollIntoView({ behavior: 'smooth', block: 'center' })+ return+ }+ attempts += 1+ if (attempts < SCROLL_TO_ACCOUNT_MAX_ATTEMPTS) {+ timer = window.setTimeout(scrollWhenReady, SCROLL_TO_ACCOUNT_POLL_MS)+ }+ }+ scrollWhenReady()+ return () => window.clearTimeout(timer)+ },+ 'scrollToAccount',+ { pauseOnPageHidden: false }+ )+ },})),afterMount(() => {posthog.capture(AccountsEvents.ListViewed)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 694e1b4b2092..1af43cf9ddf5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -7187,6 +7187,7 @@ export namespace Schemas {* * `llm_analytics` - llm_analytics* * `sandbox` - sandbox* * `user_interview` - user_interview+ * * `customer_analytics` - customer_analytics*/export type AgentModeEnum = typeof AgentModeEnum[keyof typeof AgentModeEnum];@@ -7204,6 +7205,7 @@ export namespace Schemas {LlmAnalytics: 'llm_analytics',Sandbox: 'sandbox',UserInterview: 'user_interview',+ CustomerAnalytics: 'customer_analytics',} as const;export interface AggregatedSpanRow {diff --git a/tach.toml b/tach.tomlindex e230b9200739..0602c7cee59b 100644--- a/tach.toml+++ b/tach.toml@@ -39,6 +39,7 @@ depends_on = ["products.actions","products.alerts","products.cdp",+ "products.customer_analytics","products.dashboards","products.data_modeling","products.error_tracking",