Skip to content

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

feat(customer-analytics): open accounts by external id (#101885)

Arthur Moreira de Deus55623ac3a6b8
diff --git a/docs/internal/customer-analytics-account-links.md b/docs/internal/customer-analytics-account-links.md
new file mode 100644
index 000000000000..c54fb2b09c41
--- /dev/null
+++ b/docs/internal/customer-analytics-account-links.md
@@ -0,0 +1,57 @@
+# Account links
+
+Customer analytics supports two account URL forms within the current project:
+
+- `/customer_analytics/accounts/:accountId` identifies an account by its internal UUID.
+- `/customer_analytics/accounts/by-external-id/:externalId` identifies an account by its exact external ID.
+
+Both URLs open the same account detail scene when `customer-analytics-account-scene` is enabled.
+Append a tab name, such as `/usage`, to open that tab.
+Tab changes preserve the identifier form, query parameters, and URL hash.
+Existing internal links continue to use the account UUID.
+
+## External ID encoding
+
+Use `urls.customerAnalyticsAccountByExternalId(externalId, tab)` to build external-ID links.
+The helper encodes the external ID as one URL segment.
+For example, the external ID `example/account` becomes `example%2Faccount` in the path.
+Case and spaces are significant.
+
+The route uses a local wildcard because the router's named parameters do not accept all external-ID characters.
+The scene reads the raw path and decodes the external ID once.
+An encoded slash remains part of the ID, rather than a tab separator.
+A literal percent sequence must remain distinct from the character it could encode.
+
+Accounts with no external ID require a UUID link.
+Use UUID links for empty external IDs and IDs equal to `.` or `..`; browsers can normalize dot-only path segments before routing.
+
+## API lookup
+
+The external route loads the account through:
+
+```text
+GET /api/projects/:projectId/accounts/by_external_id/?external_id=...
+```
+
+The API accepts a required, nonempty string of at most 400 characters.
+Use URL query encoding for this value, not path encoding.
+The generated `accountsByExternalIdRetrieve` client handles query encoding.
+The API preserves case and whitespace and matches only `external_id` within the project.
+It does not fall back to the account UUID, even when the external ID is a UUID string.
+
+The endpoint returns the same account response as UUID retrieval, including tags and notebooks.
+It uses the same access controls and requires `account:read` for API credentials.
+Invalid input returns 400. Missing accounts and object-level access denial both return 404 so callers cannot distinguish restricted external IDs.
+
+## Scene behavior
+
+The external route waits for the current feature flags before loading, so cached flags cannot cause a premature legacy redirect.
+It makes one account lookup request and keeps the result in the existing scene logic.
+It does not resolve a UUID and then request the same account again.
+Related panels still make their own requests.
+Presence, tag edits, and nested account APIs use the returned `account.id`, never the external ID.
+Presence starts after external-ID resolution succeeds.
+
+The scene keeps external-ID links unchanged while the detail scene is enabled.
+With the detail-scene flag disabled, a successful lookup redirects to the existing UUID route for the legacy Accounts view.
+Loading failures retain the existing retry and not-found states.
diff --git a/docs/internal/customer-analytics-account-presence.md b/docs/internal/customer-analytics-account-presence.md
index 1300c39a4ebd..f61eef85741f 100644
--- a/docs/internal/customer-analytics-account-presence.md
+++ b/docs/internal/customer-analytics-account-presence.md
@@ -2,7 +2,7 @@
Account detail pages show avatars for other active teammates who can read the same account.
-The browser sends `POST /api/projects/:team_id/accounts/:account_id/presence/` when the page opens and every 30 seconds while the tab is visible. The request has no body. The server derives the viewer identity from the authenticated user.
+The browser sends `POST /api/projects/:team_id/accounts/:account_id/presence/` when the page opens and every 30 seconds while the tab is visible. For an [external-ID account link](customer-analytics-account-links.md), heartbeats start after the account lookup succeeds and use the returned account UUID. The request has no body. The server derives the viewer identity from the authenticated user.
Each heartbeat updates an account-scoped Redis roster. A viewer expires after 90 seconds without another heartbeat. Hidden tabs and unmounted pages stop heartbeats, so another viewer can remain visible for up to 90 seconds after leaving.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1b19f65b9aea..54b88a8048e3 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7012,6 +7012,10 @@ snapshots:
hash: v1.k794b7964.32d5329bf4ce6055010743914ec226973cc4d455a70581692f97d8cae13c04f1.4Zd5MpCXYXWDIegWaghLkfmgRx11JTVSpbyCab_3_YU
scenes-app-customer-analytics-account-detail--default--light:
hash: v1.k794b7964.3a6ffd58e88bdd30817bc9c6b1c2c9f9bae8825975c121157efb3bd6fbba9f39.81lpbCyMf0S_9mRYZFcT97ecch6YY1--yoxMK2hI-xU
+ scenes-app-customer-analytics-account-detail--external-id--dark:
+ hash: v1.k794b7964.090e775f774e8bdae503cc210948f5ce1fe1aabe89c6a0b1b1353967eafaf293.DIOrnSXEMRt92ojJZ9_n74wkPzytjdqzeDJc8o4687c
+ scenes-app-customer-analytics-account-detail--external-id--light:
+ hash: v1.k794b7964.152409fdf0caeaafb9988a592ffa02ae7447352c3a6cac7adea2b59262754052.oOzz88WC10NSA__e7bWSr26aB_blhvaKHt9ZJX9pSn8
scenes-app-customer-analytics-account-detail--narrow--dark:
hash: v1.k794b7964.31ffca7eb6c59cf545dd8f16e7a532149448b95c65444aa14d5e776a0875dafd.lULK4-DoenY3SeZK1Sfr50doCkqdIbyl9U35M4ah00g
scenes-app-customer-analytics-account-detail--narrow--light:
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 62f3cea57b71..a107b5139147 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -108,6 +108,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/my-tickets': ['MyTickets', 'myTickets'],
'/customer_analytics/dashboard': ['CustomerAnalytics', 'customerAnalyticsDashboard'],
'/customer_analytics/accounts': ['CustomerAnalytics', 'customerAnalyticsAccounts'],
+ '/customer_analytics/accounts/by-external-id/*': ['CustomerAnalyticsAccount', 'customerAnalyticsAccount'],
'/customer_analytics/accounts/:accountId': ['CustomerAnalyticsAccount', 'customerAnalyticsAccount'],
'/customer_analytics/accounts/:accountId/:tab': ['CustomerAnalyticsAccount', 'customerAnalyticsAccount'],
'/customer_analytics/notes': ['CustomerAnalytics', 'customerAnalyticsNotes'],
@@ -1171,6 +1172,8 @@ export const productUrls = {
customerAnalyticsAccounts: (): string => '/customer_analytics/accounts',
customerAnalyticsAccount: (accountId: string, tab?: string): string =>
`/customer_analytics/accounts/${accountId}${tab ? `/${tab}` : ''}`,
+ customerAnalyticsAccountByExternalId: (externalId: string, tab?: string): string =>
+ `/customer_analytics/accounts/by-external-id/${encodeURIComponent(externalId)}${tab ? `/${tab}` : ''}`,
customerAnalyticsNotes: (): string => '/customer_analytics/notes',
customerAnalyticsAnnouncements: (): string => '/customer_analytics/announcements',
customerAnalyticsFeed: (): string => '/customer_analytics/feed',
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 1eb0954ea995..46dcf1134f85 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -3322,6 +3322,14 @@ def get_account_for_view(
return _to_account_view(account)
+def get_account_for_view_by_external_id(
+ *, team_id: int, external_id: str, user_access_control: "UserAccessControl", required_level: str | None
+) -> contracts.AccountView:
+ account = _account_detail_queryset(team_id).get(external_id=external_id)
+ _enforce_object_access(account, user_access_control, required_level)
+ return _to_account_view(account)
+
+
class _Unset(Enum):
UNSET = "unset"
@@ -3621,20 +3629,19 @@ def delete_account_for_view(
sync_event_stream_destination(stream, team=team, user=user)
+def _account_detail_queryset(team_id: int) -> QuerySet[Account]:
+ return Account.objects.for_team(team_id).prefetch_related(
+ Prefetch("notebooks", queryset=ResourceNotebook.objects.select_related("notebook")),
+ Prefetch("tagged_items", queryset=TaggedItem.objects.select_related("tag"), to_attr="prefetched_tags"),
+ )
+
+
def _get_account_for_detail(team_id: int, account_id: str) -> Account:
"""Team-scoped account fetch for detail/write paths (object-level access is enforced
separately). Prefetches notebooks + tags so the returned view renders without extra
queries, matching the old viewset's ``safely_get_queryset`` + tag-mixin prefetch.
Raises ``Account.DoesNotExist`` when not found in the team."""
- queryset = (
- Account.objects.unscoped()
- .filter(team_id=team_id)
- .prefetch_related(
- Prefetch("notebooks", queryset=ResourceNotebook.objects.select_related("notebook")),
- Prefetch("tagged_items", queryset=TaggedItem.objects.select_related("tag"), to_attr="prefetched_tags"),
- )
- )
- return _get_object_or_raise(queryset, account_id, Account)
+ return _get_object_or_raise(_account_detail_queryset(team_id), account_id, Account)
# --- AccountNotebook (nested under an account) ---
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 646d38f48f86..7174eb85399f 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -907,6 +907,16 @@ class CustomerJourneySerializer(DataclassSerializer):
fields = ["id", "insight", "name", "description", "created_at", "created_by", "updated_at"]
+class AccountByExternalIdQuerySerializer(serializers.Serializer):
+ external_id = serializers.CharField(
+ required=True,
+ allow_blank=False,
+ max_length=400,
+ trim_whitespace=False,
+ help_text="Exact external account identifier. Leading and trailing whitespace is significant.",
+ )
+
+
class AccountSerializer(DataclassSerializer):
"""A Customer Analytics account — a logical grouping used to assign customer-success ownership."""
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 180c8b44610a..29da19a290f6 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -65,6 +65,7 @@ from products.customer_analytics.backend.facade.constants import (
CUSTOMER_ANALYTICS_TRACK_RULES_FLAG,
)
from products.customer_analytics.backend.presentation.views.serializers import (
+ AccountByExternalIdQuerySerializer,
AccountChannelSummarySerializer,
AccountEmailThreadMessageSerializer,
AccountEmailThreadSerializer,
@@ -1723,6 +1724,31 @@ class AccountViewSet(
raise PermissionDenied()
return Response(AccountSerializer(instance=account).data)
+ @validated_request(
+ query_serializer=AccountByExternalIdQuerySerializer,
+ operation_id="accounts_by_external_id_retrieve",
+ responses={200: OpenApiResponse(response=AccountSerializer)},
+ )
+ @action(
+ methods=["GET"],
+ detail=False,
+ pagination_class=None,
+ required_scopes=["account:read"],
+ )
+ def by_external_id(self, request: ValidatedRequest, *args: object, **kwargs: object) -> Response:
+ try:
+ account = api.get_account_for_view_by_external_id(
+ team_id=self.team_id,
+ external_id=request.validated_query_data["external_id"],
+ user_access_control=self.user_access_control,
+ required_level=_object_required_level(request, write=False),
+ )
+ except api.Account_DoesNotExist:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ except api.ResourceForbiddenError:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(AccountSerializer(instance=account).data)
+
@extend_schema(
parameters=[_ACCOUNT_ID_PARAM],
request=None,
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index aabb5be93a0c..d889930acdb8 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -553,6 +553,88 @@ class TestAccountViewSet(APIBaseTest):
self.assertEqual(data["properties"]["stripe_customer_id"], "cus_123")
self.assertEqual(data["ignored_at"], ignored_at.isoformat().replace("+00:00", "Z"))
+ @parameterized.expand([(" source-account ",), (" ",), ("symbols / %2F ? # + 漢字",)])
+ def test_retrieve_by_external_id_returns_the_uuid_retrieve_response(self, external_id: str) -> None:
+ account = self._create_account(external_id=external_id)
+ self.client.patch(f"{self.endpoint_base}{account.id}/", {"tags": ["example-tag"]}, format="json")
+ self.client.post(f"{self.endpoint_base}{account.id}/notebooks/", {"title": "Example note"}, format="json")
+
+ uuid_response = self.client.get(f"{self.endpoint_base}{account.id}/")
+ external_id_response = self.client.get(
+ f"{self.endpoint_base}by_external_id/", data={"external_id": account.external_id}
+ )
+
+ self.assertEqual(status.HTTP_200_OK, uuid_response.status_code, uuid_response.json())
+ self.assertEqual(status.HTTP_200_OK, external_id_response.status_code, external_id_response.json())
+ self.assertEqual(external_id_response.json(), uuid_response.json())
+ self.assertEqual(external_id_response.json()["tags"], ["example-tag"])
+ self.assertEqual(len(external_id_response.json()["notebooks"]), 1)
+
+ @parameterized.expand([(True,), (False,)])
+ def test_retrieve_by_external_id_does_not_fall_back_to_uuid(self, has_external_match: bool) -> None:
+ uuid_account = self._create_account(name="UUID account")
+ external_id_account = (
+ self._create_account(name="External ID account", external_id=str(uuid_account.id))
+ if has_external_match
+ else None
+ )
+
+ response = self.client.get(f"{self.endpoint_base}by_external_id/", data={"external_id": str(uuid_account.id)})
+
+ if external_id_account:
+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
+ self.assertEqual(response.json()["id"], str(external_id_account.id))
+ else:
+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code, response.content)
+
+ @parameterized.expand([(True,), (False,)])
+ def test_retrieve_by_external_id_scopes_identical_external_ids_to_the_project(self, has_local_match: bool) -> None:
+ account = self._create_account(external_id="shared-external-id") if has_local_match else None
+ other_team = Team.objects.create(organization=self.organization)
+ Account.objects.for_team(other_team.id).create(
+ team=other_team, name="Other account", external_id="shared-external-id"
+ )
+
+ response = self.client.get(f"{self.endpoint_base}by_external_id/", data={"external_id": "shared-external-id"})
+
+ if account:
+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
+ self.assertEqual(response.json()["id"], str(account.id))
+ else:
+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code, response.content)
+
+ def test_retrieve_by_external_id_accepts_an_account_read_api_key(self) -> None:
+ account = self._create_account(external_id="read-key-account")
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="account read",
+ user=self.user,
+ secure_value=hash_key_value(token),
+ scopes=["account:read"],
+ scoped_teams=[],
+ scoped_organizations=[],
+ )
+ self.client.logout()
+
+ response = self.client.get(
+ f"{self.endpoint_base}by_external_id/",
+ data={"external_id": account.external_id},
+ headers={"authorization": f"Bearer {token}"},
+ )
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.content)
+ self.assertEqual(response.json()["id"], str(account.id))
+
+ def test_retrieve_by_external_id_rejects_a_missing_query_parameter(self) -> None:
+ response = self.client.get(f"{self.endpoint_base}by_external_id/")
+
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.content)
+
+ def test_retrieve_by_external_id_returns_404_when_not_found(self) -> None:
+ response = self.client.get(f"{self.endpoint_base}by_external_id/", data={"external_id": "missing-account"})
+
+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code, response.content)
+
def test_presence_returns_other_viewers_once_and_excludes_the_caller(self) -> None:
account = self._create_account()
teammate = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
@@ -1436,7 +1518,7 @@ class TestCustomerAnalyticsAccessControl(APIBaseTest):
self.journeys_url = f"/api/environments/{self.team.id}/customer_journeys/"
- self.account = Account.objects.unscoped().create(team=self.team, name="ACL Account")
+ self.account = Account.objects.unscoped().create(team=self.team, name="ACL Account", external_id="acl-account")
self.accounts_url = f"/api/environments/{self.team.id}/accounts/"
def _set_access_level(self, user: User, resource: str = "customer_analytics", access_level: str = "viewer") -> None:
@@ -1624,11 +1706,12 @@ class TestCustomerAnalyticsAccessControl(APIBaseTest):
response = self.client.post(self.accounts_url, {"name": "Inherited Account"}, format="json")
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
- def test_customer_analytics_none_blocks_account_list(self):
+ @parameterized.expand([("",), ("by_external_id/?external_id=acl-account",)])
+ def test_customer_analytics_none_blocks_account_reads(self, suffix: str) -> None:
self._set_access_level(self.no_access_user, resource="customer_analytics", access_level="none")
self.client.force_login(self.no_access_user)
- response = self.client.get(self.accounts_url)
+ response = self.client.get(f"{self.accounts_url}{suffix}")
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# -- Account notebooks inherit object-level access from the parent account --
@@ -1671,6 +1754,23 @@ class TestCustomerAnalyticsAccessControl(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ def test_account_by_external_id_404_when_object_access_denied(self) -> None:
+ AccessControl.objects.create(
+ team=self.team,
+ resource="account",
+ resource_id=str(self.account.id),
+ access_level="none",
+ organization_member=OrganizationMembership.objects.get(
+ user=self.viewer_user, organization=self.organization
+ ),
+ )
+ self._set_access_level(self.viewer_user, resource="account", access_level="viewer")
+ self.client.force_login(self.viewer_user)
+
+ response = self.client.get(f"{self.accounts_url}by_external_id/?external_id={self.account.external_id}")
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
class TestCustomPropertyDefinitionViewSet(APIBaseTest):
def setUp(self):
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 789b2d19a268..cd1bc29a2b6e 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -4298,6 +4298,15 @@ export type AccountsSupportTicketMessagesListParams = {
offset?: number
}
+export type AccountsByExternalIdRetrieveParams = {
+ /**
+ * Exact external account identifier. Leading and trailing whitespace is significant.
+ * @minLength 1
+ * @maxLength 400
+ */
+ external_id: string
+}
+
export type AnnouncementsListParams = {
/**
* Number of results to return per page.
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index ee3731e2a496..c1bd889c4c0b 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -22,6 +22,7 @@ import type {
AccountTrackRuleRunViewApi,
AccountTrackRulesConfigApi,
AccountTrackRulesRunsListParams,
+ AccountsByExternalIdRetrieveParams,
AccountsEmailThreadMessagesListParams,
AccountsEmailThreadsListParams,
AccountsListParams,
@@ -928,6 +929,33 @@ export const accountsSupportTicketMessagesList = async (
)
}
+export const getAccountsByExternalIdRetrieveUrl = (projectId: string, params: AccountsByExternalIdRetrieveParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/accounts/by_external_id/?${stringifiedParams}`
+ : `/api/projects/${projectId}/accounts/by_external_id/`
+}
+
+export const accountsByExternalIdRetrieve = async (
+ projectId: string,
+ params: AccountsByExternalIdRetrieveParams,
+ options?: RequestInit
+): Promise<AccountApi> => {
+ return apiMutator<AccountApi>(getAccountsByExternalIdRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getCustomerAnalyticsAccountsTableQueryCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/accounts_table_query/`
}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
index 4b00e540d581..1dae724fa6ec 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
@@ -9,7 +9,9 @@ import { mswDecorator } from '~/mocks/browser'
import type { CustomPropertyValueWriteApi, AccountRelationshipWriteApi } from '../../generated/api.schemas'
const ACCOUNT_ID = '11111111-2222-4333-8444-555555555555'
+const EXTERNAL_ACCOUNT_ID = 'spaces %2F slash / ? # + Unicode 漢字'
const ACCOUNT_RETRIEVE_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/'
+const ACCOUNT_BY_EXTERNAL_ID_ENDPOINT = 'api/projects/:team_id/accounts/by_external_id/'
const ACCOUNT_NOTEBOOKS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/notebooks/'
const ACCOUNT_PRESENCE_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/presence/'
const ACCOUNT_ICON_ENDPOINT = 'api/projects/:team_id/accounts/icon/'
@@ -22,7 +24,7 @@ const RELATIONSHIP_DEFINITIONS_ENDPOINT = 'api/projects/:team_id/account_relatio
const account = {
id: ACCOUNT_ID,
name: 'Example Labs',
- external_id: 'example_labs_42',
+ external_id: EXTERNAL_ACCOUNT_ID,
properties: {
website_domain: 'example.com',
email_domains: ['example.com'],
@@ -90,6 +92,10 @@ const meta: Meta = {
mswDecorator({
get: {
[ACCOUNT_RETRIEVE_ENDPOINT]: account,
+ [ACCOUNT_BY_EXTERNAL_ID_ENDPOINT]: ({ request }) =>
+ new URL(request.url).searchParams.get('external_id') === EXTERNAL_ACCOUNT_ID
+ ? account
+ : [400, null],
[ACCOUNT_NOTEBOOKS_ENDPOINT]: notebooks,
[ACCOUNT_ICON_ENDPOINT]: () =>
new Response(
@@ -156,6 +162,17 @@ export const Default: Story = {
render: () => <App />,
}
+export const ExternalId: Story = {
+ render: () => <App />,
+ parameters: {
+ pageUrl: urls.customerAnalyticsAccountByExternalId(EXTERNAL_ACCOUNT_ID, 'usage'),
+ testOptions: {
+ waitForSelector: ['[data-attr="customer-analytics-account-scene"]', '.ProfileBubbles'],
+ viewport: { width: 1280, height: 900 },
+ },
+ },
+}
+
export const Narrow: Story = {
render: () => <App />,
parameters: {
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx
index b763b00b6370..9995c77f23d8 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx
@@ -1,10 +1,12 @@
import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
import { LemonBanner, LemonSkeleton } from '@posthog/lemon-ui'
import { NotFound } from 'lib/components/NotFound'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'
import { SceneExport } from 'scenes/sceneTypes'
import { FeaturePreviewSceneGate } from '~/layout/scenes/components/FeaturePreviewSceneGate'
@@ -25,12 +27,26 @@ import {
CustomerAnalyticsAccountSceneLogicProps,
customerAnalyticsAccountSceneLogic,
} from './customerAnalyticsAccountSceneLogic'
+import {
+ isExternalAccountPath,
+ parseExternalAccountPath,
+ shouldRenderLegacyCustomerAnalyticsScene,
+} from './customerAnalyticsAccountSceneUtils'
export const scene: SceneExport<CustomerAnalyticsAccountSceneLogicProps> = {
component: CustomerAnalyticsAccountScene,
logic: customerAnalyticsAccountSceneLogic,
productKey: ProductKey.CUSTOMER_ANALYTICS,
- paramsToProps: ({ params: { accountId } }) => ({ accountId: accountId ?? '' }),
+ paramsToProps: ({ params: { _, accountId } }) => {
+ const projectId = getCurrentTeamIdOrNone()
+ if (_ !== undefined) {
+ const externalRoute = parseExternalAccountPath(router.values.location.pathname)
+ return externalRoute
+ ? { externalId: externalRoute.externalId, projectId }
+ : { invalidRoute: true, projectId }
+ }
+ return accountId ? { accountId, projectId } : { invalidRoute: true, projectId }
+ },
}
function getAccountLogoDomain(account: AccountApi): string | null {
@@ -38,12 +54,26 @@ function getAccountLogoDomain(account: AccountApi): string | null {
}
export function CustomerAnalyticsAccountScene(): JSX.Element {
- const { featureFlags } = useValues(featureFlagLogic)
+ const { featureFlags, receivedFeatureFlags } = useValues(featureFlagLogic)
+ const { location } = useValues(router)
+ const externalRouteRequested = isExternalAccountPath(location.pathname)
- if (!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]) {
+ if (
+ shouldRenderLegacyCustomerAnalyticsScene(
+ location.pathname,
+ !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]
+ )
+ ) {
return <CustomerAnalyticsScene />
}
+ if (!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE] && externalRouteRequested) {
+ if (!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {
+ return !receivedFeatureFlags ? <CustomerAnalyticsAccountSceneContent /> : <NotFound object="page" />
+ }
+ return <CustomerAnalyticsAccountSceneContent />
+ }
+
if (!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {
return <NotFound object="page" />
}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
index 8fd58313718c..a5884972ca34 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
@@ -11,26 +11,37 @@ import { initKeaTests } from '~/test/init'
import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'
import {
+ accountsByExternalIdRetrieve,
accountsPartialUpdate,
accountsPresenceCreate,
accountsRetrieve,
} from 'products/customer_analytics/frontend/generated/api'
import type { AccountApi, AccountPresenceViewerApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import { scene } from './CustomerAnalyticsAccountScene'
import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
+import {
+ parseExternalAccountPath,
+ shouldRenderLegacyCustomerAnalyticsScene,
+} from './customerAnalyticsAccountSceneUtils'
jest.mock('products/customer_analytics/frontend/generated/api', () => ({
...jest.requireActual('products/customer_analytics/frontend/generated/api'),
+ accountsByExternalIdRetrieve: jest.fn(),
accountsPartialUpdate: jest.fn(),
accountsPresenceCreate: jest.fn(),
accountsRetrieve: jest.fn(),
}))
+const mockAccountsByExternalIdRetrieve = accountsByExternalIdRetrieve as jest.MockedFunction<
+ typeof accountsByExternalIdRetrieve
+>
const mockAccountsPartialUpdate = accountsPartialUpdate as jest.MockedFunction<typeof accountsPartialUpdate>
const mockAccountsPresenceCreate = accountsPresenceCreate as jest.MockedFunction<typeof accountsPresenceCreate>
const mockAccountsRetrieve = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>
const ACCOUNT_ID = '0190da51-0b0e-7000-8000-000000000001'
+const PROJECT_ID = 999
const account: AccountApi = {
id: ACCOUNT_ID,
name: 'Test account',
@@ -70,6 +81,7 @@ describe('customerAnalyticsAccountSceneLogic', () => {
featureFlagLogic.mount()
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: true,
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]: true,
[FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS]: true,
[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS]: true,
})
@@ -77,7 +89,12 @@ describe('customerAnalyticsAccountSceneLogic', () => {
})
function mountLogic(): void {
- logic = customerAnalyticsAccountSceneLogic({ accountId: ACCOUNT_ID })
+ logic = customerAnalyticsAccountSceneLogic({ accountId: ACCOUNT_ID, projectId: PROJECT_ID })
+ logic.mount()
+ }
+
+ function mountExternalIdLogic(externalId: string): void {
+ logic = customerAnalyticsAccountSceneLogic({ externalId, projectId: PROJECT_ID })
logic.mount()
}
@@ -98,6 +115,31 @@ describe('customerAnalyticsAccountSceneLogic', () => {
expect(logic.values.breadcrumbs.at(-1)?.name).toBe(account.name)
})
+ it('loads a UUID account while the account scene flag is disabled', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: true,
+ })
+ mockAccountsRetrieve.mockResolvedValue(account)
+
+ mountLogic()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsRetrieve).toHaveBeenCalledWith(String(PROJECT_ID), ACCOUNT_ID)
+ })
+
+ it('loads a UUID account before feature flags resolve', async () => {
+ featureFlagLogic.unmount()
+ initKeaTests()
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID))
+ mockAccountsRetrieve.mockResolvedValue(account)
+ expect(featureFlagLogic.values.receivedFeatureFlags).toBe(false)
+
+ mountLogic()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsRetrieve).toHaveBeenCalledWith(String(PROJECT_ID), ACCOUNT_ID)
+ })
+
it('heartbeats account presence immediately, polls every 30 seconds, and clears it on failure', async () => {
jest.useFakeTimers()
const captureException = jest.spyOn(posthog, 'captureException')
@@ -110,7 +152,7 @@ describe('customerAnalyticsAccountSceneLogic', () => {
await Promise.resolve()
await Promise.resolve()
- expect(mockAccountsPresenceCreate).toHaveBeenCalledWith(String(logic.values.currentTeamId), ACCOUNT_ID)
+ expect(mockAccountsPresenceCreate).toHaveBeenCalledWith(String(PROJECT_ID), ACCOUNT_ID)
expect(logic.values.accountPresenceViewers).toEqual(viewers)
jest.advanceTimersByTime(30_000)
@@ -149,7 +191,7 @@ describe('customerAnalyticsAccountSceneLogic', () => {
mountLogic()
await staleRequestStarted.promise
- logic.actions.loadAccountPresence()
+ logic.actions.loadAccountPresence(ACCOUNT_ID)
await latestRequestStarted.promise
latestRequest.resolve(latestViewers)
@@ -174,6 +216,28 @@ describe('customerAnalyticsAccountSceneLogic', () => {
expect(captureException).not.toHaveBeenCalled()
})
+ it('finishes an invalid route without loading an account', async () => {
+ logic = customerAnalyticsAccountSceneLogic({ invalidRoute: true, projectId: PROJECT_ID })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.accountLoading).toBe(false)
+ expect(logic.values.isAccountMissing).toBe(true)
+ expect(mockAccountsRetrieve).not.toHaveBeenCalled()
+ expect(mockAccountsByExternalIdRetrieve).not.toHaveBeenCalled()
+ })
+
+ it('shows a load error when the current project is unavailable', async () => {
+ logic = customerAnalyticsAccountSceneLogic({ accountId: ACCOUNT_ID, projectId: null })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.accountLoading).toBe(false)
+ expect(logic.values.accountLoadError).toEqual(new Error('Could not determine the current project or account.'))
+ expect(logic.values.isAccountMissing).toBe(false)
+ expect(mockAccountsRetrieve).not.toHaveBeenCalled()
+ })
+
it('reports unexpected load failures', async () => {
const failure = new ApiError('Server error', 500)
const captureException = jest.spyOn(posthog, 'captureException')
@@ -229,7 +293,7 @@ describe('customerAnalyticsAccountSceneLogic', () => {
expect(logic.values.account?.tags).toEqual(['priority'])
expect(logic.values.tagsSaving).toBe(true)
await expectLogic(logic).toFinishAllListeners()
- expect(mockAccountsPartialUpdate).toHaveBeenCalledWith(String(logic.values.currentTeamId), ACCOUNT_ID, {
+ expect(mockAccountsPartialUpdate).toHaveBeenCalledWith(String(PROJECT_ID), ACCOUNT_ID, {
tags: ['priority'],
})
expect(logic.values.account).toEqual(updatedAccount)
@@ -288,6 +352,201 @@ describe('customerAnalyticsAccountSceneLogic', () => {
)
})
+ describe('external ID routes', () => {
+ it('does not render the legacy scene for an external route while flags are unresolved', () => {
+ expect(
+ shouldRenderLegacyCustomerAnalyticsScene(
+ urls.customerAnalyticsAccountByExternalId('unresolved account'),
+ false
+ )
+ ).toBe(false)
+ expect(shouldRenderLegacyCustomerAnalyticsScene(urls.customerAnalyticsAccount(ACCOUNT_ID), false)).toBe(
+ true
+ )
+ })
+
+ it.each([
+ 'spaces %2F slash / ? # + Unicode 漢字',
+ 'literal %2F sequence',
+ ' leading and trailing spaces ',
+ ' ',
+ ])('decodes the external ID exactly once: %s', (externalId) => {
+ const pathname = urls.customerAnalyticsAccountByExternalId(externalId, 'usage')
+
+ expect(parseExternalAccountPath(pathname)).toEqual({ externalId, tab: 'usage' })
+ })
+
+ it.each([
+ '/customer_analytics/accounts/by-external-id/%',
+ '/customer_analytics/accounts/by-external-id/',
+ '/customer_analytics/accounts/by-external-id/account/usage/extra',
+ ])('rejects malformed external account paths: %s', (pathname) => {
+ expect(parseExternalAccountPath(pathname)).toBeNull()
+ })
+
+ it('loads by external ID, preserves the encoded URL, and routes tabs through kea-router', async () => {
+ const externalId = 'spaces %2F slash / ? # + Unicode 漢字'
+ const externalUrl = urls.customerAnalyticsAccountByExternalId(externalId, 'usage')
+ const searchParams = { source: 'account-link' }
+ const hashParams = { view: { search: 'example' } }
+ mockAccountsByExternalIdRetrieve.mockResolvedValue(account)
+
+ router.actions.push(externalUrl, searchParams, hashParams)
+ expect(
+ scene.paramsToProps?.({ params: { _: externalId }, searchParams: {}, hashParams: {} })
+ ).toMatchObject({ externalId })
+ mountExternalIdLogic(externalId)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsByExternalIdRetrieve).toHaveBeenCalledTimes(1)
+ expect(mockAccountsByExternalIdRetrieve).toHaveBeenCalledWith(String(PROJECT_ID), {
+ external_id: externalId,
+ })
+ expect(mockAccountsRetrieve).not.toHaveBeenCalled()
+ expect(mockAccountsPresenceCreate).toHaveBeenCalledWith(String(PROJECT_ID), ACCOUNT_ID)
+ expect(logic.values.activeTab).toBe('usage')
+ expect(router.values.location.pathname).toBe(urls.currentProject(externalUrl))
+
+ logic.actions.setActiveTab('users')
+
+ expect(router.values.location.pathname).toBe(
+ urls.currentProject(urls.customerAnalyticsAccountByExternalId(externalId, 'users'))
+ )
+ expect(router.values.currentLocation.searchParams).toEqual(searchParams)
+ expect(router.values.currentLocation.hashParams).toEqual(hashParams)
+ })
+
+ it('uses the resolved account ID for external account mutations', async () => {
+ const externalId = 'external account'
+ mockAccountsByExternalIdRetrieve.mockResolvedValue(account)
+ mockAccountsPartialUpdate.mockResolvedValue({ ...account, tags: ['priority'] })
+
+ router.actions.push(urls.customerAnalyticsAccountByExternalId(externalId))
+ mountExternalIdLogic(externalId)
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.updateTags(['priority'])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsPartialUpdate).toHaveBeenCalledWith(String(PROJECT_ID), ACCOUNT_ID, {
+ tags: ['priority'],
+ })
+ })
+
+ it('does not load an external ID when customer analytics is unavailable', async () => {
+ const externalId = 'unavailable account'
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]: true,
+ })
+
+ router.actions.push(urls.customerAnalyticsAccountByExternalId(externalId))
+ mountExternalIdLogic(externalId)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsByExternalIdRetrieve).not.toHaveBeenCalled()
+ expect(mockAccountsPresenceCreate).not.toHaveBeenCalled()
+ })
+
+ it.each([true, false])(
+ 'waits for fresh flags before resolving with the detail scene enabled: %s',
+ async (accountSceneEnabled) => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: true })
+ featureFlagLogic.unmount()
+ initKeaTests()
+ featureFlagLogic.mount()
+ expect(featureFlagLogic.values.receivedFeatureFlags).toBe(false)
+ expect(featureFlagLogic.values.featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]).toBe(true)
+ const externalId = 'cached flag account'
+ const externalUrl = urls.customerAnalyticsAccountByExternalId(externalId, 'usage')
+ mockAccountsByExternalIdRetrieve.mockResolvedValue(account)
+ router.actions.push(externalUrl)
+ mountExternalIdLogic(externalId)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsByExternalIdRetrieve).not.toHaveBeenCalled()
+
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: true,
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]: accountSceneEnabled,
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsByExternalIdRetrieve).toHaveBeenCalledTimes(1)
+ expect(router.values.location.pathname).toBe(
+ urls.currentProject(
+ accountSceneEnabled ? externalUrl : urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage')
+ )
+ )
+ }
+ )
+
+ it('resolves an external account when customer analytics access arrives', async () => {
+ const externalId = 'deferred external account'
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]: true,
+ })
+ mockAccountsByExternalIdRetrieve.mockResolvedValue(account)
+
+ router.actions.push(urls.customerAnalyticsAccountByExternalId(externalId))
+ mountExternalIdLogic(externalId)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockAccountsByExternalIdRetrieve).not.toHaveBeenCalled()
+
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: true,
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]: true,
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsByExternalIdRetrieve).toHaveBeenCalledWith(String(PROJECT_ID), {
+ external_id: externalId,
+ })
+ })
+
+ it('redirects to the UUID detail route only when the detail scene flag is disabled', async () => {
+ const externalId = 'legacy account'
+ const externalUrl = urls.customerAnalyticsAccountByExternalId(externalId, 'usage')
+ const searchParams = { source: 'account-link' }
+ const hashParams = { view: { search: 'example' } }
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: true,
+ })
+ mockAccountsByExternalIdRetrieve.mockResolvedValue(account)
+
+ router.actions.push(externalUrl, searchParams, hashParams)
+ mountExternalIdLogic(externalId)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.location.pathname).toBe(
+ urls.currentProject(urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage'))
+ )
+ expect(router.values.currentLocation.searchParams).toEqual(searchParams)
+ expect(router.values.currentLocation.hashParams).toEqual(hashParams)
+ expect(mockAccountsPresenceCreate).not.toHaveBeenCalled()
+ })
+
+ it('ignores an external lookup that resolves after navigation', async () => {
+ const externalId = 'stale account'
+ const externalUrl = urls.customerAnalyticsAccountByExternalId(externalId)
+ const lookup = createDeferred<AccountApi>()
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: true,
+ })
+ mockAccountsByExternalIdRetrieve.mockReturnValueOnce(lookup.promise)
+
+ router.actions.push(externalUrl)
+ mountExternalIdLogic(externalId)
+ logic.unmount()
+ router.actions.push(urls.customerAnalyticsAccounts())
+
+ lookup.resolve(account)
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(router.values.location.pathname).toBe(urls.currentProject(urls.customerAnalyticsAccounts()))
+ })
+ })
+
describe('tab routing', () => {
beforeEach(async () => {
mockAccountsRetrieve.mockResolvedValue(account)
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
index 2d73cd6af929..d231c4801107 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
@@ -16,10 +16,10 @@ import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { ApiError } from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic, FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { Scene } from 'scenes/sceneTypes'
-import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { tagsModel } from '~/models/tagsModel'
@@ -32,16 +32,28 @@ import {
} from 'products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic'
import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'
import {
+ accountsByExternalIdRetrieve,
accountsPartialUpdate,
accountsPresenceCreate,
accountsRetrieve,
} from 'products/customer_analytics/frontend/generated/api'
import type { AccountApi, AccountPresenceViewerApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import { EXTERNAL_ACCOUNT_ROUTE_PATTERN, parseExternalAccountPath } from './customerAnalyticsAccountSceneUtils'
+
const ACCOUNT_PRESENCE_POLL_INTERVAL_MS = 30_000
export interface CustomerAnalyticsAccountSceneLogicProps {
- accountId: string
+ accountId?: string
+ externalId?: string
+ invalidRoute?: boolean
+ projectId?: number | null
+}
+
+function accountDetailUrl(props: CustomerAnalyticsAccountSceneLogicProps, tab?: string): string {
+ return props.externalId
+ ? urls.customerAnalyticsAccountByExternalId(props.externalId, tab)
+ : urls.customerAnalyticsAccount(props.accountId ?? '', tab)
}
function isAccountNotFound(error: unknown): boolean {
@@ -51,7 +63,7 @@ function isAccountNotFound(error: unknown): boolean {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface customerAnalyticsAccountSceneLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
- currentTeamId: number | null // teamLogic
+ receivedFeatureFlags: boolean // featureFlagLogic
account: AccountApi | null
accountLoadError: unknown
accountLoading: boolean
@@ -66,14 +78,21 @@ export interface customerAnalyticsAccountSceneLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface customerAnalyticsAccountSceneLogicActions {
+ setFeatureFlags: (
+ flags: string[],
+ variants: Record<string, boolean | string>
+ ) => {
+ flags: string[]
+ variants: Record<string, boolean | string>
+ } // featureFlagLogic
loadAccount: () => {
value: true
}
loadAccountFailure: (error: unknown) => {
error: unknown
}
- loadAccountPresence: () => {
- value: true
+ loadAccountPresence: (accountId: string) => {
+ accountId: string
}
loadAccountPresenceFailure: (error: unknown) => {
error: unknown
@@ -90,6 +109,9 @@ export interface customerAnalyticsAccountSceneLogicActions {
setActiveTab: (tab: AccountExpansionTab) => {
tab: AccountExpansionTab
}
+ startAccountPresencePolling: (accountId: string) => {
+ accountId: string
+ }
updateTags: (tags: string[]) => {
tags: string[]
}
@@ -103,7 +125,12 @@ export interface customerAnalyticsAccountSceneLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
activeTab: (requestedTab: string, featureFlags: FeatureFlagsSet) => AccountExpansionTab
- isAccountMissing: (account: AccountApi | null, accountLoading: boolean, accountLoadError: unknown) => boolean
+ isAccountMissing: (
+ account: AccountApi | null,
+ accountLoading: boolean,
+ accountLoadError: unknown,
+ arg: boolean
+ ) => boolean
breadcrumbs: (account: AccountApi | null) => Breadcrumb[]
}
}
@@ -126,16 +153,21 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
key,
]),
props({} as CustomerAnalyticsAccountSceneLogicProps),
- key((props) => props.accountId),
+ key(
+ (props) =>
+ `${props.projectId ?? 'unknown'}:${props.externalId ? 'external' : 'id'}:${props.externalId ?? props.accountId ?? 'invalid'}`
+ ),
connect(() => ({
- values: [teamLogic, ['currentTeamId'], featureFlagLogic, ['featureFlags']],
+ values: [featureFlagLogic, ['featureFlags', 'receivedFeatureFlags']],
+ actions: [featureFlagLogic, ['setFeatureFlags']],
})),
actions({
loadAccount: true,
loadAccountSuccess: (account: AccountApi) => ({ account }),
loadAccountFailure: (error: unknown) => ({ error }),
- loadAccountPresence: true,
+ loadAccountPresence: (accountId: string) => ({ accountId }),
loadAccountPresenceSuccess: (viewers: AccountPresenceViewerApi[]) => ({ viewers }),
+ startAccountPresencePolling: (accountId: string) => ({ accountId }),
loadAccountPresenceFailure: (error: unknown) => ({ error }),
setActiveTab: (tab: AccountExpansionTab) => ({ tab }),
restoreActiveTab: (tab: string | undefined) => ({ tab: tab ?? DEFAULT_ACCOUNT_TAB }),
@@ -204,9 +236,13 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
getVisibleAccountExpansionTab(requestedTab, featureFlags),
],
isAccountMissing: [
- (s) => [s.account, s.accountLoading, s.accountLoadError],
- (account: AccountApi | null, accountLoading: boolean, accountLoadError: unknown): boolean =>
- !account && !accountLoading && isAccountNotFound(accountLoadError),
+ (s, _) => [s.account, s.accountLoading, s.accountLoadError, (_, props) => props.invalidRoute === true],
+ (
+ account: AccountApi | null,
+ accountLoading: boolean,
+ accountLoadError: unknown,
+ invalidRoute: boolean
+ ): boolean => invalidRoute || (!account && !accountLoading && isAccountNotFound(accountLoadError)),
],
breadcrumbs: [
(s) => [s.account],
@@ -226,26 +262,85 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
],
}),
listeners(({ actions, cache, props, values }) => ({
- loadAccount: async () => {
+ setFeatureFlags: (_, __, ___, previousState) => {
+ const previousFeatureFlags = featureFlagLogic.selectors.featureFlags(previousState)
+ const previouslyReceivedFlags = featureFlagLogic.selectors.receivedFeatureFlags(previousState)
+ if (
+ props.externalId &&
+ (!previouslyReceivedFlags || !previousFeatureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) &&
+ values.featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP] &&
+ !values.account &&
+ !values.accountLoading
+ ) {
+ actions.loadAccount()
+ }
+ },
+ loadAccount: async (_, breakpoint) => {
try {
- actions.loadAccountSuccess(await accountsRetrieve(String(values.currentTeamId), props.accountId))
+ const projectId = props.projectId
+ const identifier = props.externalId ?? props.accountId
+ if (props.invalidRoute) {
+ actions.loadAccountFailure(null)
+ return
+ }
+ if (!projectId || !identifier) {
+ actions.loadAccountFailure(new Error('Could not determine the current project or account.'))
+ return
+ }
+ const account = props.externalId
+ ? await accountsByExternalIdRetrieve(String(projectId), { external_id: identifier })
+ : await accountsRetrieve(String(projectId), identifier)
+ await breakpoint()
+ actions.loadAccountSuccess(account)
} catch (error) {
+ if (error instanceof Error && isBreakpoint(error)) {
+ throw error
+ }
+ await breakpoint()
actions.loadAccountFailure(error)
}
},
+ loadAccountSuccess: ({ account }) => {
+ if (!props.externalId) {
+ return
+ }
+ if (!values.featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]) {
+ const externalRoute = parseExternalAccountPath(router.values.location.pathname)
+ router.actions.replace(
+ urls.customerAnalyticsAccount(account.id, externalRoute?.tab),
+ router.values.currentLocation.searchParams,
+ router.values.currentLocation.hashParams
+ )
+ return
+ }
+ actions.startAccountPresencePolling(account.id)
+ },
loadAccountFailure: ({ error }) => {
- if (isAccountNotFound(error)) {
+ if (error === null || isAccountNotFound(error)) {
return
}
posthog.captureException(error instanceof Error ? error : new Error('Could not load account'), {
scope: 'customerAnalyticsAccountSceneLogic.loadAccount',
})
},
- loadAccountPresence: async () => {
+ startAccountPresencePolling: ({ accountId }) => {
+ cache.disposables.add(() => {
+ actions.loadAccountPresence(accountId)
+ const intervalId = window.setInterval(
+ () => actions.loadAccountPresence(accountId),
+ ACCOUNT_PRESENCE_POLL_INTERVAL_MS
+ )
+ return () => window.clearInterval(intervalId)
+ }, 'accountPresencePolling')
+ },
+ loadAccountPresence: async ({ accountId }) => {
cache.accountPresenceRequestSequence = (cache.accountPresenceRequestSequence ?? 0) + 1
const requestSequence = cache.accountPresenceRequestSequence
try {
- const viewers = await accountsPresenceCreate(String(values.currentTeamId), props.accountId)
+ if (!props.projectId) {
+ return
+ }
+ const viewers = await accountsPresenceCreate(String(props.projectId), accountId)
if (requestSequence === cache.accountPresenceRequestSequence) {
actions.loadAccountPresenceSuccess(viewers)
}
@@ -259,9 +354,15 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
posthog.capture(AccountsEvents.TabViewed, { tab })
},
updateTags: async ({ tags }, breakpoint) => {
+ const accountId = values.account?.id
+ const projectId = props.projectId
+ if (!accountId || !projectId) {
+ actions.updateTagsDone(null)
+ return
+ }
try {
await breakpoint(300)
- const account = await accountsPartialUpdate(String(values.currentTeamId), props.accountId, { tags })
+ const account = await accountsPartialUpdate(String(projectId), accountId, { tags })
await breakpoint()
actions.updateTagsDone(account)
tagsModel.findMounted()?.actions.loadTags()
@@ -282,28 +383,38 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
})),
actionToUrl(({ props }) => ({
setActiveTab: ({ tab }) => [
- urls.customerAnalyticsAccount(props.accountId, tab === DEFAULT_ACCOUNT_TAB ? undefined : tab),
+ accountDetailUrl(props, tab === DEFAULT_ACCOUNT_TAB ? undefined : tab),
router.values.currentLocation.searchParams,
router.values.currentLocation.hashParams,
],
})),
- urlToAction(({ actions, props }) => ({
- [`${urls.customerAnalyticsAccount(props.accountId)}/:tab`]: ({ tab }) => {
- actions.restoreActiveTab(tab)
- },
- [urls.customerAnalyticsAccount(props.accountId)]: () => {
- actions.restoreActiveTab(DEFAULT_ACCOUNT_TAB)
- },
- })),
- afterMount(({ actions, cache }) => {
+ urlToAction(({ actions, props }) => {
+ if (props.externalId) {
+ return {
+ [EXTERNAL_ACCOUNT_ROUTE_PATTERN]: () => {
+ actions.restoreActiveTab(parseExternalAccountPath(router.values.location.pathname)?.tab)
+ },
+ }
+ }
+ return {
+ [`${accountDetailUrl(props)}/:tab`]: ({ tab }) => {
+ actions.restoreActiveTab(tab)
+ },
+ [accountDetailUrl(props)]: () => {
+ actions.restoreActiveTab(DEFAULT_ACCOUNT_TAB)
+ },
+ }
+ }),
+ afterMount(({ actions, props, values }) => {
+ if (
+ props.externalId &&
+ (!values.receivedFeatureFlags || !values.featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP])
+ ) {
+ return
+ }
actions.loadAccount()
- cache.disposables.add(() => {
- actions.loadAccountPresence()
- const intervalId = window.setInterval(
- () => actions.loadAccountPresence(),
- ACCOUNT_PRESENCE_POLL_INTERVAL_MS
- )
- return () => window.clearInterval(intervalId)
- }, 'accountPresencePolling')
+ if (props.accountId) {
+ actions.startAccountPresencePolling(props.accountId)
+ }
}),
])
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneUtils.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneUtils.ts
new file mode 100644
index 000000000000..2a86e052395c
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneUtils.ts
@@ -0,0 +1,31 @@
+export interface ExternalAccountRoute {
+ externalId: string
+ tab?: string
+}
+
+export const EXTERNAL_ACCOUNT_ROUTE_PATTERN = '/customer_analytics/accounts/by-external-id/*'
+
+export function isExternalAccountPath(pathname: string): boolean {
+ return pathname.includes('/customer_analytics/accounts/by-external-id/')
+}
+
+export function shouldRenderLegacyCustomerAnalyticsScene(pathname: string, accountSceneEnabled: boolean): boolean {
+ return !accountSceneEnabled && !isExternalAccountPath(pathname)
+}
+
+// kea-router decodes route captures before passing them to scenes. Read the raw pathname so an
+// encoded literal percent sequence is decoded once, while encoded slashes remain one identity segment.
+export function parseExternalAccountPath(pathname: string): ExternalAccountRoute | null {
+ const match = pathname.match(/\/customer_analytics\/accounts\/by-external-id\/([^/]+)(?:\/([^/]+))?\/?$/)
+ if (!match) {
+ return null
+ }
+
+ try {
+ const externalId = decodeURIComponent(match[1])
+ const tab = match[2] ? decodeURIComponent(match[2]) : undefined
+ return externalId ? { externalId, tab } : null
+ } catch {
+ return null
+ }
+}
diff --git a/products/customer_analytics/manifest.tsx b/products/customer_analytics/manifest.tsx
index cb0633b6dd07..024719e08e29 100644
--- a/products/customer_analytics/manifest.tsx
+++ b/products/customer_analytics/manifest.tsx
@@ -54,6 +54,8 @@ export const manifest: ProductManifest = {
routes: {
'/customer_analytics/dashboard': ['CustomerAnalytics', 'customerAnalyticsDashboard'],
'/customer_analytics/accounts': ['CustomerAnalytics', 'customerAnalyticsAccounts'],
+ // Match before UUID routes; the wildcard also accepts characters excluded from named segments.
+ '/customer_analytics/accounts/by-external-id/*': ['CustomerAnalyticsAccount', 'customerAnalyticsAccount'],
// The detail scene serves these paths behind its flag and falls back to the list for legacy deep links.
'/customer_analytics/accounts/:accountId': ['CustomerAnalyticsAccount', 'customerAnalyticsAccount'],
'/customer_analytics/accounts/:accountId/:tab': ['CustomerAnalyticsAccount', 'customerAnalyticsAccount'],
@@ -86,6 +88,8 @@ export const manifest: ProductManifest = {
// Account detail path. The flag-off scene falls back to the filtered, expanded Accounts list.
customerAnalyticsAccount: (accountId: string, tab?: string): string =>
`/customer_analytics/accounts/${accountId}${tab ? `/${tab}` : ''}`,
+ customerAnalyticsAccountByExternalId: (externalId: string, tab?: string): string =>
+ `/customer_analytics/accounts/by-external-id/${encodeURIComponent(externalId)}${tab ? `/${tab}` : ''}`,
customerAnalyticsNotes: (): string => '/customer_analytics/notes',
customerAnalyticsAnnouncements: (): string => '/customer_analytics/announcements',
customerAnalyticsFeed: (): string => '/customer_analytics/feed',
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index 97ca2a7bf18d..5917bfa27f54 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -114,6 +114,9 @@ tools:
account-track-rules-update:
operation: account_track_rules_update
enabled: false
+ accounts-by-external-id-retrieve:
+ operation: accounts_by_external_id_retrieve
+ enabled: false
accounts-create:
operation: accounts_create
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 80b06df4cbbc..5cee2ef5eea8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -98151,6 +98151,15 @@ export namespace Schemas {
offset?: number;
};
+ export type AccountsByExternalIdRetrieveParams = {
+ /**
+ * Exact external account identifier. Leading and trailing whitespace is significant.
+ * @minLength 1
+ * @maxLength 400
+ */
+ external_id: string;
+ };
+
export type ActionsListParams = {
/**
* Comma-separated list of creator user ids. Returns only actions created by these users.
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index ef1960a5a80e..66a530c18edd 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -364,6 +364,11 @@
"params": ["accountId"],
"scope": "project"
},
+ "customerAnalyticsAccountByExternalId": {
+ "template": "/customer_analytics/accounts/by-external-id/{externalId}",
+ "params": ["externalId"],
+ "scope": "project"
+ },
"customerAnalyticsAccounts": {
"template": "/customer_analytics/accounts",
"params": [],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
index f8048d32067d..4c9281ae96a7 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -13,7 +13,7 @@
"type": "object"
},
"url": {
- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/business-knowledge/settings\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/business-knowledge/settings\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
"type": "string"
}
},