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): Deep-link account links instead of the list (#64361)

Arthur Moreira de Deus8ca3212b401c
diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.py
index 4a965559b02c..0de77a2fd5d1 100644
--- a/ee/hogai/context/entity_search/context.py
+++ b/ee/hogai/context/entity_search/context.py
@@ -23,6 +23,7 @@ from posthog.sync import database_sync_to_async
from products.actions.backend.models.action import Action
from products.alerts.backend.models.alert import AlertConfiguration
from products.cohorts.backend.models.cohort import Cohort
+from products.customer_analytics.backend.account_urls import build_account_deeplink
from products.customer_analytics.backend.models import Account
from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
@@ -557,6 +558,7 @@ class EntitySearchContext:
case "alert_configuration":
return f"{base_url}/insights?tab=alerts&alert_id={result_id}"
case "account":
- return f"{base_url}/customer_analytics/accounts"
+ # Deep-link to the specific account (filtered + expanded) rather than the bare list.
+ return f"{base_url}{build_account_deeplink(account_id=result_id)}"
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.py
index 6c5f0b99c23b..a1df8b635f76 100644
--- a/ee/hogai/context/entity_search/test/test_context.py
+++ b/ee/hogai/context/entity_search/test/test_context.py
@@ -50,7 +50,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"),
+ ("account", "test_account_id", "/project/{team_id}/customer_analytics/accounts/test_account_id"),
]
)
def test_build_url(self, entity_type, result_id, expected_path):
diff --git a/ee/hogai/core/agent_modes/presets/customer_analytics.py b/ee/hogai/core/agent_modes/presets/customer_analytics.py
index e1321e5db37e..f57089511ee5 100644
--- a/ee/hogai/core/agent_modes/presets/customer_analytics.py
+++ b/ee/hogai/core/agent_modes/presets/customer_analytics.py
@@ -32,6 +32,8 @@ CUSTOMER_ANALYTICS_MODE_DESCRIPTION = (
"analytics or SQL. "
"For a quick 'show me usage' ask, point users to the account's Usage tab in the Accounts list rather "
"than building a new insight. "
+ "When you give the user a link to an account, link to that specific account so it opens directly, not "
+ "to the bare accounts list. "
"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. "
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/buildNotificationSourcePath.test.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/buildNotificationSourcePath.test.ts
index 95cc870da32b..11c2ef0bd437 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/buildNotificationSourcePath.test.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/buildNotificationSourcePath.test.ts
@@ -88,7 +88,7 @@ describe('buildNotificationSourcePath', () => {
})
it('uses the source_url deep-link for customer_analytics (no source_id→path mapping)', () => {
- const deepLink = '/customer_analytics/accounts#open=%7B%22id%22%3A%22acc-9%22%2C%22tab%22%3A%22usage%22%7D'
+ const deepLink = '/customer_analytics/accounts/acc-9/usage'
const result = buildNotificationSourcePath(
makeNotification({
source_type: 'customer_analytics',
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 011bad44a051..a9cfed57648e 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -206,6 +206,8 @@ export const productRoutes: Record<string, [string, string]> = {
'/support/settings': ['SupportSettings', 'supportSettings'],
'/customer_analytics/dashboard': ['CustomerAnalytics', 'customerAnalyticsDashboard'],
'/customer_analytics/accounts': ['CustomerAnalytics', 'customerAnalyticsAccounts'],
+ '/customer_analytics/accounts/:accountId': ['CustomerAnalytics', 'customerAnalyticsAccounts'],
+ '/customer_analytics/accounts/:accountId/:tab': ['CustomerAnalytics', 'customerAnalyticsAccounts'],
'/customer_analytics/journeys/new': ['CustomerJourneyBuilder', 'customerJourneyBuilder'],
'/customer_analytics/journeys/templates': ['CustomerJourneyTemplates', 'customerJourneyTemplates'],
'/customer_analytics/journeys/:id/edit': ['CustomerJourneyBuilder', 'customerJourneyEdit'],
@@ -905,6 +907,8 @@ export const productUrls = {
customerAnalytics: (): string => '/customer_analytics',
customerAnalyticsDashboard: (): string => '/customer_analytics/dashboard',
customerAnalyticsAccounts: (): string => '/customer_analytics/accounts',
+ customerAnalyticsAccount: (accountId: string, tab?: string): string =>
+ `/customer_analytics/accounts/${accountId}${tab ? `/${tab}` : ''}`,
customerAnalyticsJourneys: (): string => '/customer_analytics/journeys',
customerAnalyticsConfiguration: (): string => '/customer_analytics/configuration',
customerJourneyBuilder: (): string => '/customer_analytics/journeys/new',
diff --git a/frontend/src/scenes/notebooks/notebookSceneLogic.ts b/frontend/src/scenes/notebooks/notebookSceneLogic.ts
index b4ea3d79f3aa..1a4835292bae 100644
--- a/frontend/src/scenes/notebooks/notebookSceneLogic.ts
+++ b/frontend/src/scenes/notebooks/notebookSceneLogic.ts
@@ -42,7 +42,7 @@ export const notebookSceneLogic = kea<notebookSceneLogicType>([
? {
key: Scene.CustomerAnalytics,
name: 'Accounts',
- path: urls.customerAnalyticsAccounts(),
+ path: urls.customerAnalyticsAccount(notebook.parent_resource.id),
iconType: 'group',
}
: {
diff --git a/products/customer_analytics/backend/account_urls.py b/products/customer_analytics/backend/account_urls.py
new file mode 100644
index 000000000000..75d8ece50fa3
--- /dev/null
+++ b/products/customer_analytics/backend/account_urls.py
@@ -0,0 +1,23 @@
+from urllib.parse import quote
+
+# Project-relative base path to the Customer analytics accounts list. In-app navigation adds the
+# project prefix via the router; callers that need an absolute URL (e.g. agent context) prepend it.
+ACCOUNTS_LIST_PATH = "/customer_analytics/accounts"
+
+
+def build_account_deeplink(*, account_id: str, tab: str | None = None) -> str:
+ """Build a deep link that opens a specific account in the Customer analytics accounts list —
+ filtered to it, expanded, and (optionally) on a given tab.
+
+ Returns the project-relative path `/customer_analytics/accounts/<id>[/<tab>]`. The accounts list
+ reads these route params (see the `:accountId/:tab` patterns in `customer_analytics/manifest.tsx`),
+ filters the list to the account by id, expands it, and opens `tab` (an account expansion tab such
+ as "usage"; omit it for the default tab).
+
+ This is the single source of truth for the Python side of the deep-link format — keep it in sync
+ with the route rather than constructing the path elsewhere.
+ """
+ path = f"{ACCOUNTS_LIST_PATH}/{quote(str(account_id), safe='')}"
+ if tab:
+ path = f"{path}/{quote(tab, safe='')}"
+ return path
diff --git a/products/customer_analytics/backend/services/usage_spike_notifications.py b/products/customer_analytics/backend/services/usage_spike_notifications.py
index e7763e30a863..73ea21acf4bf 100644
--- a/products/customer_analytics/backend/services/usage_spike_notifications.py
+++ b/products/customer_analytics/backend/services/usage_spike_notifications.py
@@ -1,12 +1,11 @@
-import json
from typing import Any
-from urllib.parse import quote
import structlog
import posthoganalytics
from posthog.exceptions_capture import capture_exception
+from products.customer_analytics.backend.account_urls import build_account_deeplink
from products.customer_analytics.backend.constants import CUSTOMER_ANALYTICS_CSP_FLAG
from products.customer_analytics.backend.models import Account
from products.notifications.backend.facade.api import (
@@ -66,7 +65,8 @@ def notify_managers_of_usage_spike(
title = f"Usage spike: {account.name}"[:TITLE_MAX_LENGTH]
body = _build_body(spikes, detected_at)[:BODY_MAX_LENGTH]
- source_url = _build_source_url(account)
+ # Project-relative; the notifications side panel adds the project prefix on navigation.
+ source_url = build_account_deeplink(account_id=str(account.id), tab="usage")
for user_id in manager_user_ids:
_notify_manager(
@@ -82,23 +82,6 @@ def notify_managers_of_usage_spike(
logger.exception("usage_spike.dispatch_failed", spike_id=spike_id)
-def _build_source_url(account: Account) -> str:
- # Deep-link straight to the account's expanded row on the Usage tab. Project-relative on purpose:
- # the notifications side panel adds the project prefix when navigating (same-project push or the
- # cross-project urls.project(...) wrapper), so a `/project/<id>` prefix here would double up. The
- # `#open=` hash mirrors kea-router's encoding (JSON.stringify + percent-encoding) so the accounts
- # list consumes it on load — see AccountsOpenUrlState in accountsLogic.ts. external_id/name let the
- # list reveal the account when it's off-screen; id drives the expand and scroll.
- open_state: dict[str, str] = {"id": str(account.id)}
- if account.external_id:
- open_state["externalId"] = account.external_id
- if account.name:
- open_state["name"] = account.name
- open_state["tab"] = "usage"
- encoded = quote(json.dumps(open_state, separators=(",", ":")), safe="")
- return f"/customer_analytics/accounts#open={encoded}"
-
-
def _find_account(
*,
team_id: int,
diff --git a/products/customer_analytics/backend/test/test_account_urls.py b/products/customer_analytics/backend/test/test_account_urls.py
new file mode 100644
index 000000000000..3dc89fbe969b
--- /dev/null
+++ b/products/customer_analytics/backend/test/test_account_urls.py
@@ -0,0 +1,20 @@
+from unittest import TestCase
+
+from parameterized import parameterized
+
+from products.customer_analytics.backend.account_urls import build_account_deeplink
+
+
+class TestBuildAccountDeeplink(TestCase):
+ def test_id_only_omits_tab(self):
+ assert build_account_deeplink(account_id="acc-1") == "/customer_analytics/accounts/acc-1"
+
+ def test_with_tab(self):
+ assert build_account_deeplink(account_id="acc-1", tab="usage") == "/customer_analytics/accounts/acc-1/usage"
+
+ @parameterized.expand([(None,), ("",)])
+ def test_falsy_tab_is_omitted(self, tab):
+ assert build_account_deeplink(account_id="acc-1", tab=tab) == "/customer_analytics/accounts/acc-1"
+
+ def test_special_characters_are_percent_encoded(self):
+ assert build_account_deeplink(account_id="a/b", tab="x y") == "/customer_analytics/accounts/a%2Fb/x%20y"
diff --git a/products/customer_analytics/backend/test/test_usage_spike_notifications.py b/products/customer_analytics/backend/test/test_usage_spike_notifications.py
index 27da8378bbde..3c7752a80747 100644
--- a/products/customer_analytics/backend/test/test_usage_spike_notifications.py
+++ b/products/customer_analytics/backend/test/test_usage_spike_notifications.py
@@ -1,6 +1,3 @@
-import json
-from urllib.parse import unquote
-
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -121,27 +118,5 @@ class TestNotifyManagersOfUsageSpike(BaseTest):
assert data.source_id == "spike-1"
assert data.title == "Usage spike: Acme Corp"
assert data.body == "events 3.2× (up) — detected 2026-06-09"
-
- base, _, fragment = data.source_url.partition("#")
- # Project-relative: the notifications side panel adds the project prefix on navigation.
- assert base == "/customer_analytics/accounts"
- assert fragment.startswith("open=")
- assert json.loads(unquote(fragment[len("open=") :])) == {
- "id": str(account.id),
- "externalId": "org-123",
- "name": "Acme Corp",
- "tab": "usage",
- }
-
- def test_source_url_omits_missing_external_id(self, mock_create, _mock_dispatched):
- account = self._create_account_with_managers(csm_id=101, ae_id=None)
- account.properties = {**account.properties.model_dump(mode="json"), "billing_id": "bill-9"}
- account.save()
- self._notify_managers(billing_id="bill-9")
-
- fragment = mock_create.call_args.args[0].source_url.partition("#")[2]
- assert json.loads(unquote(fragment[len("open=") :])) == {
- "id": str(account.id),
- "name": "Acme Corp",
- "tab": "usage",
- }
+ # Project-relative path; the notifications side panel adds the project prefix on navigation.
+ assert data.source_url == f"/customer_analytics/accounts/{account.id}/usage"
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index d4e15ef28f39..8aca11927d91 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -64,9 +64,18 @@ The Usage tab renders an existing saved billing-usage insight — **point users
`accountsLogic` mirrors the full view (search, tags, unassigned, assigned-to, 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. The "assigned to" filter persists as concrete `assignedTo` ids (not a `mine` flag), so a link shared with a colleague resolves to the **same** accounts for them as for the sharer; the legacy `mine: true` hash is still read and resolved to the current user's id for backward compatibility. 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).
-### Deep-link to one account (`#open=`)
+### Deep-link to one account (path route)
-Separate from the persistent `#view=` state, a **one-shot** `#open={id, externalId, name, tab}` hash (`AccountsOpenUrlState`) lands directly on a single account: `urlToAction` reads it and dispatches `openAccount` (reveal + expand + tab + scroll — the same entry point Max uses). `tab` is validated against `ACCOUNT_EXPANSION_TABS`, falling back to `DEFAULT_ACCOUNT_TAB`. It self-clears — `openAccount`'s reveal calls `setSearchQuery`, which rewrites the hash to `#view=` only, dropping `open` so it never re-triggers. The usage-spike notification (`backend/services/usage_spike_notifications.py`) builds this URL (project-relative — the notifications side panel adds the project prefix) with `tab: 'usage'`; keep the Python encoding in sync with kea-router (`JSON.stringify` + percent-encoding). The notification path is routed through `buildNotificationSourcePath` in `sidePanelNotificationsLogic.tsx`, which has **no** `customer_analytics` entry in `SOURCE_TYPE_TO_PATH` precisely so the precise `source_url` deep-link wins instead of a static accounts-list path.
+`/customer_analytics/accounts/:accountId/:tab` opens a single account directly (separate from the persistent `#view=` filter state). `accountsLogic.urlToAction` reads the route params, validates the id (UUID) and tab (against `ACCOUNT_EXPANSION_TABS`, default `DEFAULT_ACCOUNT_TAB`), sets `accountIdFilter` — which ANDs `toString(id) = '<id>'` into the query's `filterExpression`, filtering the list to just that account — and opens the tab via `openAccountTab`. Returning to the bare `/customer_analytics/accounts` clears `accountIdFilter`. Because it filters by the PK, the id alone is enough; no name/external_id is needed in the link.
+
+**Build the URL via the canonical helpers, never hand-build the path:**
+
+- Frontend: `urls.customerAnalyticsAccount(accountId, tab?)` (in the product manifest). Used by the notebook→Accounts breadcrumb.
+- Backend: `build_account_deeplink(account_id, tab=None)` in `backend/account_urls.py` — the single source of truth for the Python side, returning `/customer_analytics/accounts/<id>[/<tab>]`. Used by the usage-spike notification (`backend/services/usage_spike_notifications.py`, `tab='usage'`) and by the agent's entity-search results (`ee/hogai/context/entity_search/context.py`), so when Max/MCP references an account it found, the link opens that account rather than the list.
+
+Anywhere we know the account, prefer a deep-link over the bare list. The notification path is routed through `buildNotificationSourcePath` in `sidePanelNotificationsLogic.tsx`, which has **no** `customer_analytics` entry in `SOURCE_TYPE_TO_PATH` precisely so the precise `source_url` deep-link wins instead of a static accounts-list path. The notification `source_url` is project-relative — the notifications side panel adds the project prefix on navigation.
+
+(Separately, `openAccount` — reveal + expand + scroll **within the current list** — remains the Max contextual-tool entry point for surfacing an account during an active session. It's not URL-driven.)
## Saved views
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index 49022599048a..1a23f10c79c5 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -357,63 +357,54 @@ describe('accountsLogic', () => {
})
})
- describe('deep link (open hash param)', () => {
- // The usage-spike notification links here with `#open={id,externalId,name,tab}`.
- it('expands the targeted account on the requested tab and reveals it', async () => {
- router.actions.push(
- urls.customerAnalyticsAccounts(),
- {},
- { open: { id: 'acc-9', externalId: 'ext-9', name: 'Acme Nine', tab: 'usage' } }
- )
+ describe('deep link (path route)', () => {
+ // `/customer_analytics/accounts/:accountId/:tab` filters the list to one account and opens a tab.
+ const ACCOUNT_ID = '0190da51-0b0e-7000-8000-000000000001'
+
+ const filterExpressionOf = (source: unknown): string | undefined => (source as AccountsQuery).filterExpression
+
+ it('filters the list to the account, expands it, and opens the requested tab', async () => {
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage'))
await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.accountIdFilter).toBe(ACCOUNT_ID)
+ expect(filterExpressionOf(logic.values.hogqlQuery.source)).toContain(`toString(id) = '${ACCOUNT_ID}'`)
const expansion = accountsExpansionLogic.findMounted()
- expect(expansion?.values.expandedAccountIds).toContain('acc-9')
- expect(expansion?.values.activeTabByAccount['acc-9']).toBe('usage')
- // Revealed via the external id so an off-screen account still renders.
- expect(logic.values.searchQuery).toBe('ext-9')
+ expect(expansion?.values.expandedAccountIds).toContain(ACCOUNT_ID)
+ expect(expansion?.values.activeTabByAccount[ACCOUNT_ID]).toBe('usage')
})
- it('falls back to the default tab when the hash tab is invalid', async () => {
- router.actions.push(urls.customerAnalyticsAccounts(), {}, { open: { id: 'acc-9', tab: 'bogus' } })
+ it('defaults the tab when the path omits it', async () => {
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID))
await expectLogic(logic).toFinishAllListeners()
const expansion = accountsExpansionLogic.findMounted()
- expect(expansion?.values.activeTabByAccount['acc-9']).toBe(DEFAULT_ACCOUNT_TAB)
+ expect(expansion?.values.activeTabByAccount[ACCOUNT_ID]).toBe(DEFAULT_ACCOUNT_TAB)
})
- it('self-clears the open hash after consuming it', async () => {
- router.actions.push(
- urls.customerAnalyticsAccounts(),
- {},
- { open: { id: 'acc-9', externalId: 'ext-9', name: 'Acme Nine', tab: 'usage' } }
- )
+ it('falls back to the default tab for an unknown tab', async () => {
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'bogus'))
await expectLogic(logic).toFinishAllListeners()
- expect(router.values.hashParams.open).toBeUndefined()
- expect(router.values.hashParams.view).toEqual({ search: 'ext-9' })
+ const expansion = accountsExpansionLogic.findMounted()
+ expect(expansion?.values.activeTabByAccount[ACCOUNT_ID]).toBe(DEFAULT_ACCOUNT_TAB)
})
- it('ignores an open hash with no account id', async () => {
- router.actions.push(urls.customerAnalyticsAccounts(), {}, { open: { tab: 'usage' } })
+ it('ignores a non-UUID account id', async () => {
+ router.actions.push(urls.customerAnalyticsAccount('not-a-uuid', 'usage'))
await expectLogic(logic).toFinishAllListeners()
- const expansion = accountsExpansionLogic.findMounted()
- expect(expansion?.values.expandedAccountIds ?? []).toEqual([])
+ expect(logic.values.accountIdFilter).toBeNull()
})
- it('opens from a raw deep-link string (as the notification panel pushes it)', async () => {
- // navigateToNotification does router.actions.push(path) with the hash embedded in the
- // string — kea-router must decode `#open=<json>` back into a hashParams object.
- const encoded = encodeURIComponent(
- JSON.stringify({ id: 'acc-9', externalId: 'ext-9', name: 'Acme Nine', tab: 'usage' })
- )
- router.actions.push(`${urls.customerAnalyticsAccounts()}#open=${encoded}`)
+ it('clears the account filter when returning to the bare list', async () => {
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage'))
await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.accountIdFilter).toBe(ACCOUNT_ID)
- const expansion = accountsExpansionLogic.findMounted()
- expect(expansion?.values.expandedAccountIds).toContain('acc-9')
- expect(expansion?.values.activeTabByAccount['acc-9']).toBe('usage')
+ router.actions.push(urls.customerAnalyticsAccounts())
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.accountIdFilter).toBeNull()
})
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index 4fee1ea4b503..1445fcc139b8 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -3,6 +3,7 @@ import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { isUUIDLike } from 'lib/utils/guards'
import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -120,17 +121,6 @@ export interface AccountsViewUrlState {
tileFilter?: TileFilter
}
-// One-shot directive to open a specific account on load (`#open=...`). Used by
-// deep links from elsewhere (e.g. usage-spike notifications) to land directly on
-// an account's expanded row and tab. Distinct from the persistent `#view=` state:
-// it's consumed once and dropped from the URL when the reveal rewrites the hash.
-export interface AccountsOpenUrlState {
- id: string
- externalId?: string | null
- name?: string
- tab?: AccountExpansionTab
-}
-
export const accountsLogic = kea<accountsLogicType>([
path(['scenes', 'customerAnalytics', 'accounts', 'accountsLogic']),
connect(() => ({
@@ -183,6 +173,9 @@ export const accountsLogic = kea<accountsLogicType>([
name,
tab,
}),
+ // Restrict the list to a single account by id — drives the `/accounts/:accountId/:tab`
+ // path route. null clears it (back to the full list).
+ setAccountIdFilter: (accountId: string | null) => ({ accountId }),
}),
reducers({
searchInput: [
@@ -216,6 +209,12 @@ export const accountsLogic = kea<accountsLogicType>([
setAssignedToFilter: (_, { value }) => value,
},
],
+ accountIdFilter: [
+ null as string | null,
+ {
+ setAccountIdFilter: (_, { accountId }) => accountId,
+ },
+ ],
sortOrder: [
null as AccountSortOrder,
{
@@ -322,6 +321,7 @@ export const accountsLogic = kea<accountsLogicType>([
s.tagsFilter,
s.allRolesUnassigned,
s.assignedToFilter,
+ s.accountIdFilter,
s.tileFilter,
s.overviewMetrics,
s.sortOrder,
@@ -332,6 +332,7 @@ export const accountsLogic = kea<accountsLogicType>([
tagsFilter: string[],
allRolesUnassigned: boolean,
assignedToFilter: RoleFilterValue,
+ accountIdFilter: string | null,
tileFilter: TileFilter | null,
overviewMetrics: string[],
sortOrder: AccountSortOrder,
@@ -358,8 +359,18 @@ export const accountsLogic = kea<accountsLogicType>([
if (assignedToFilter.length > 0) {
source.assignedToUserIds = assignedToFilter
}
+ // Combine the overview-tile filter with the single-account filter (path route). The
+ // id is the account PK; compare it stringified, matching how the name-cell id is built.
+ // accountIdFilter is only ever a validated UUID (set from the route), so it's injection-safe.
+ const filterExpressions: string[] = []
if (tileFilter) {
- source.filterExpression = tileFilter.expression
+ filterExpressions.push(tileFilter.expression)
+ }
+ if (accountIdFilter) {
+ filterExpressions.push(`toString(id) = '${accountIdFilter}'`)
+ }
+ if (filterExpressions.length > 0) {
+ source.filterExpression = filterExpressions.map((expr) => `(${expr})`).join(' AND ')
}
if (sortOrder) {
const expr = deriveAccountsOrderByExpr(sortOrder.column)
@@ -574,64 +585,78 @@ export const accountsLogic = kea<accountsLogicType>([
setTileFilter: toUrl,
}
}),
- urlToAction(({ actions, values }) => ({
- [urls.customerAnalyticsAccounts()]: (_, __, hashParams): void => {
- const view: AccountsViewUrlState =
- hashParams?.view && typeof hashParams.view === 'object' ? hashParams.view : {}
-
- const search = view.search ?? ''
- if (search !== values.searchQuery) {
- actions.setSearchQuery(search)
+ urlToAction(({ actions, values }) => {
+ // Path route `/accounts/:accountId/:tab`: filter the list to one account and open the tab.
+ // Neither setter is wired into actionToUrl, so the URL stays on the path (no navigate-away).
+ const openAccountByPath = (accountId: string | undefined, rawTab?: string): void => {
+ // Guard the path param before it's interpolated into the HogQL id filter.
+ if (!accountId || !isUUIDLike(accountId)) {
+ return
}
-
- const tags = view.tags ?? []
- if (!objectsEqual(tags, values.tagsFilter)) {
- actions.setTagsFilter(tags)
+ const tab =
+ rawTab && ACCOUNT_EXPANSION_TABS.includes(rawTab as AccountExpansionTab)
+ ? (rawTab as AccountExpansionTab)
+ : DEFAULT_ACCOUNT_TAB
+ if (values.accountIdFilter !== accountId) {
+ actions.setAccountIdFilter(accountId)
}
+ actions.openAccountTab(accountId, tab)
+ }
+ return {
+ [urls.customerAnalyticsAccounts()]: (_, __, hashParams): void => {
+ const view: AccountsViewUrlState =
+ hashParams?.view && typeof hashParams.view === 'object' ? hashParams.view : {}
- const unassigned = view.unassigned ?? false
- if (unassigned !== values.allRolesUnassigned) {
- actions.setAllRolesUnassigned(unassigned)
- }
+ const search = view.search ?? ''
+ if (search !== values.searchQuery) {
+ actions.setSearchQuery(search)
+ }
- const assignedTo = normalizeRoleFilter(view.assignedTo)
- // Back-compat: legacy links encoded the viewer-relative `mine: true`;
- // resolve it to the opener's own id so old shared links still work.
- const legacyMine =
- !assignedTo.length && view.mine && values.currentUserId !== null ? [values.currentUserId] : []
- const nextAssignedTo = assignedTo.length ? assignedTo : legacyMine
- if (!objectsEqual(nextAssignedTo, values.assignedToFilter)) {
- actions.setAssignedToFilter(nextAssignedTo)
- }
+ const tags = view.tags ?? []
+ if (!objectsEqual(tags, values.tagsFilter)) {
+ actions.setTagsFilter(tags)
+ }
- const sort = view.sort ?? null
- if (!objectsEqual(sort, values.sortOrder)) {
- actions.setSortOrder(sort)
- }
+ const unassigned = view.unassigned ?? false
+ if (unassigned !== values.allRolesUnassigned) {
+ actions.setAllRolesUnassigned(unassigned)
+ }
- // A shared link's columns win over the per-user saved column config;
- // accountsColumnConfigLogic enforces this by reading the URL when its
- // async saved-config load resolves.
- if (view.columns && !objectsEqual(view.columns, values.selectColumns)) {
- actions.setSelectColumns(view.columns)
- }
+ const assignedTo = normalizeRoleFilter(view.assignedTo)
+ // Back-compat: legacy links encoded the viewer-relative `mine: true`;
+ // resolve it to the opener's own id so old shared links still work.
+ const legacyMine =
+ !assignedTo.length && view.mine && values.currentUserId !== null ? [values.currentUserId] : []
+ const nextAssignedTo = assignedTo.length ? assignedTo : legacyMine
+ if (!objectsEqual(nextAssignedTo, values.assignedToFilter)) {
+ actions.setAssignedToFilter(nextAssignedTo)
+ }
- const tileFilter = view.tileFilter ?? null
- if (!objectsEqual(tileFilter, values.tileFilter)) {
- actions.setTileFilter(tileFilter)
- }
+ const sort = view.sort ?? null
+ if (!objectsEqual(sort, values.sortOrder)) {
+ actions.setSortOrder(sort)
+ }
- // Deep link: open (reveal + expand + tab + scroll) a specific account.
- // openAccount's reveal rewrites the hash to `#view=` only, so `open`
- // self-clears and never re-triggers.
- const open: AccountsOpenUrlState | null =
- hashParams?.open && typeof hashParams.open === 'object' && typeof hashParams.open.id === 'string'
- ? hashParams.open
- : null
- if (open) {
- const tab = open.tab && ACCOUNT_EXPANSION_TABS.includes(open.tab) ? open.tab : DEFAULT_ACCOUNT_TAB
- actions.openAccount(open.id, open.externalId ?? null, open.name ?? '', tab)
- }
- },
- })),
+ // A shared link's columns win over the per-user saved column config;
+ // accountsColumnConfigLogic enforces this by reading the URL when its
+ // async saved-config load resolves.
+ if (view.columns && !objectsEqual(view.columns, values.selectColumns)) {
+ actions.setSelectColumns(view.columns)
+ }
+
+ const tileFilter = view.tileFilter ?? null
+ if (!objectsEqual(tileFilter, values.tileFilter)) {
+ actions.setTileFilter(tileFilter)
+ }
+
+ // Back on the bare list — drop any single-account path filter.
+ if (values.accountIdFilter !== null) {
+ actions.setAccountIdFilter(null)
+ }
+ },
+ [urls.customerAnalyticsAccount(':accountId')]: ({ accountId }): void => openAccountByPath(accountId),
+ [urls.customerAnalyticsAccount(':accountId', ':tab')]: ({ accountId, tab }): void =>
+ openAccountByPath(accountId, tab),
+ }
+ }),
])
diff --git a/products/customer_analytics/manifest.tsx b/products/customer_analytics/manifest.tsx
index d0916cdb213a..244d0909f9bb 100644
--- a/products/customer_analytics/manifest.tsx
+++ b/products/customer_analytics/manifest.tsx
@@ -37,6 +37,10 @@ export const manifest: ProductManifest = {
routes: {
'/customer_analytics/dashboard': ['CustomerAnalytics', 'customerAnalyticsDashboard'],
'/customer_analytics/accounts': ['CustomerAnalytics', 'customerAnalyticsAccounts'],
+ // Deep-link to a single account (filtered + expanded), optionally on a given tab. Same scene key
+ // as the list so the accounts tab activates; accountsLogic reads the params.
+ '/customer_analytics/accounts/:accountId': ['CustomerAnalytics', 'customerAnalyticsAccounts'],
+ '/customer_analytics/accounts/:accountId/:tab': ['CustomerAnalytics', 'customerAnalyticsAccounts'],
'/customer_analytics/journeys/new': ['CustomerJourneyBuilder', 'customerJourneyBuilder'],
'/customer_analytics/journeys/templates': ['CustomerJourneyTemplates', 'customerJourneyTemplates'],
'/customer_analytics/journeys/:id/edit': ['CustomerJourneyBuilder', 'customerJourneyEdit'],
@@ -55,6 +59,9 @@ export const manifest: ProductManifest = {
customerAnalytics: (): string => '/customer_analytics',
customerAnalyticsDashboard: (): string => '/customer_analytics/dashboard',
customerAnalyticsAccounts: (): string => '/customer_analytics/accounts',
+ // Path-based deep link to one account: filters the list to it, expands it, opens `tab`.
+ customerAnalyticsAccount: (accountId: string, tab?: string): string =>
+ `/customer_analytics/accounts/${accountId}${tab ? `/${tab}` : ''}`,
customerAnalyticsJourneys: (): string => '/customer_analytics/journeys',
customerAnalyticsConfiguration: (): string => '/customer_analytics/configuration',
customerJourneyBuilder: (): string => '/customer_analytics/journeys/new',
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index c9415499ceff..599363342456 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -67,7 +67,10 @@ tools:
account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id,
zendesk_id), `tags`, and creation/update metadata. Pass `tags` (JSON-encoded array, e.g.
`["enterprise","priority"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve`
- for a single account by id.
+ for a single account by id. To link a user to a specific account rather than the bare list, deep-link it
+ with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of
+ notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the list to that
+ account, expands it, and opens the tab.
param_overrides:
tags:
description: >
@@ -173,7 +176,9 @@ tools:
description: >
Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm,
account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id,
- zendesk_id external identifiers) and `tags`.
+ zendesk_id external identifiers) and `tags`. To link a user to this account rather than the bare list,
+ deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is
+ optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).
feature_flag: customer-analytics-csp
accounts-update:
operation: accounts_update
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 73a1581d7352..16d20ac0961c 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -30,7 +30,7 @@
"feature_flag": "customer-analytics-csp"
},
"accounts-list": {
- "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (assignment fields csm, account_executive, account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id.",
+ "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (assignment fields csm, account_executive, account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id. To link a user to a specific account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the list to that account, expands it, and opens the tab.",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "List accounts",
@@ -120,7 +120,7 @@
"feature_flag": "customer-analytics-csp"
},
"accounts-retrieve": {
- "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm, account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`.",
+ "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm, account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`. To link a user to this account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "Get account",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c533c0eee374..ccd4a7d88270 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -30,7 +30,7 @@
"feature_flag": "customer-analytics-csp"
},
"accounts-list": {
- "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (assignment fields csm, account_executive, account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id.",
+ "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (assignment fields csm, account_executive, account_owner and external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id. To link a user to a specific account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the list to that account, expands it, and opens the tab.",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "List accounts",
@@ -120,7 +120,7 @@
"feature_flag": "customer-analytics-csp"
},
"accounts-retrieve": {
- "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm, account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`.",
+ "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (csm, account_executive, account_owner assignments plus stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`. To link a user to this account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "Get account",