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 usage-spike alert to usage tab (#64349)

Arthur Moreira de Deus3d47eabecb07
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 87a6180ddba2..95cc870da32b 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
@@ -87,6 +87,18 @@ describe('buildNotificationSourcePath', () => {
expect(result).toBe('/dashboard/legacy')
})
+ 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 result = buildNotificationSourcePath(
+ makeNotification({
+ source_type: 'customer_analytics',
+ source_id: 'spike-1',
+ source_url: deepLink,
+ })
+ )
+ expect(result).toBe(deepLink)
+ })
+
it('falls back to source_url when source_type is unrecognized', () => {
const result = buildNotificationSourcePath(
makeNotification({
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx
index 0a9b8b5b3f7b..20d12b598924 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic.tsx
@@ -46,7 +46,11 @@ const SSE_RETRY_ATTEMPTS = 3
const SSE_RETRY_INITIAL_DELAY_MS = 30000
const SSE_RETRY_BACKOFF_MULTIPLIER = 4
-const SOURCE_TYPE_TO_PATH: Record<NotificationEventSourceTypeEnumApi, (id: string) => string> = {
+// Maps each source type to a path builder from `source_id`, or `null` to fall through to the
+// backend-provided `source_url` (customer_analytics carries a precise account deep-link a
+// source_id→path mapping can't build). Kept as a full `Record` — not `Partial` — so adding a
+// `NotificationEventSourceTypeEnumApi` value fails the build until it's handled here.
+const SOURCE_TYPE_TO_PATH: Record<NotificationEventSourceTypeEnumApi, ((id: string) => string) | null> = {
replay: (id) => urls.replaySingle(id),
notebook: (id) => urls.notebook(id),
insight: (id) => urls.insightView(id as InsightShortId),
@@ -55,7 +59,7 @@ const SOURCE_TYPE_TO_PATH: Record<NotificationEventSourceTypeEnumApi, (id: strin
survey: (id) => urls.survey(id),
experiment: (id) => urls.experiment(id),
error_tracking: (id) => urls.errorTrackingIssue(id),
- customer_analytics: () => urls.customerAnalyticsAccounts(),
+ customer_analytics: null,
}
export interface NotificationGroup {
@@ -77,10 +81,11 @@ export function groupKey(n: InAppNotification): string {
}
export function buildNotificationSourcePath(notification: InAppNotification): string | null {
- if (notification.source_type && notification.source_id && notification.source_type in SOURCE_TYPE_TO_PATH) {
- return SOURCE_TYPE_TO_PATH[notification.source_type as NotificationEventSourceTypeEnumApi](
- notification.source_id
- )
+ const toPath = notification.source_type
+ ? SOURCE_TYPE_TO_PATH[notification.source_type as NotificationEventSourceTypeEnumApi]
+ : undefined
+ if (toPath && notification.source_id) {
+ return toPath(notification.source_id)
}
return notification.source_url || null
}
diff --git a/products/customer_analytics/backend/services/usage_spike_notifications.py b/products/customer_analytics/backend/services/usage_spike_notifications.py
index 7aeb90f35c40..e7763e30a863 100644
--- a/products/customer_analytics/backend/services/usage_spike_notifications.py
+++ b/products/customer_analytics/backend/services/usage_spike_notifications.py
@@ -1,4 +1,6 @@
+import json
from typing import Any
+from urllib.parse import quote
import structlog
import posthoganalytics
@@ -64,8 +66,7 @@ def notify_managers_of_usage_spike(
title = f"Usage spike: {account.name}"[:TITLE_MAX_LENGTH]
body = _build_body(spikes, detected_at)[:BODY_MAX_LENGTH]
- # No per-account detail route exists, so deep-link to the accounts list.
- source_url = f"/project/{account.team.project_id}/customer_analytics/accounts"
+ source_url = _build_source_url(account)
for user_id in manager_user_ids:
_notify_manager(
@@ -81,6 +82,23 @@ 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_usage_spike_notifications.py b/products/customer_analytics/backend/test/test_usage_spike_notifications.py
index 792990a44f17..27da8378bbde 100644
--- a/products/customer_analytics/backend/test/test_usage_spike_notifications.py
+++ b/products/customer_analytics/backend/test/test_usage_spike_notifications.py
@@ -1,3 +1,6 @@
+import json
+from urllib.parse import unquote
+
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -118,4 +121,27 @@ 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"
- assert data.source_url == f"/project/{self.team.project_id}/customer_analytics/accounts"
+
+ 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",
+ }
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index b440fb6ef39a..d4e15ef28f39 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -64,6 +64,10 @@ 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=`)
+
+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.
+
## Saved views
A saved view is a named snapshot of the full Accounts list state (columns, sort, filters, overview tiles).
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts
index 35c8c7ca7215..69454761aea0 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts
@@ -6,6 +6,8 @@ import { AccountsEvents } from './constants'
export type AccountExpansionTab = 'notes' | 'users' | 'usage' | 'spend'
+export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = ['notes', 'users', 'usage', 'spend']
+
export const DEFAULT_ACCOUNT_TAB: AccountExpansionTab = 'notes'
export const accountsExpansionLogic = kea<accountsExpansionLogicType>([
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index 82980a75f8a8..49022599048a 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -18,6 +18,7 @@ import {
ACCOUNTS_NAME_COLUMN,
accountsColumnConfigLogic,
} from './accountsColumnConfigLogic'
+import { DEFAULT_ACCOUNT_TAB, accountsExpansionLogic } from './accountsExpansionLogic'
import { accountsLogic, savingRoleKey } from './accountsLogic'
// `hogqlQuery.source` is typed as the full DataTableNode source union; this logic
@@ -356,6 +357,66 @@ 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' } }
+ )
+ await expectLogic(logic).toFinishAllListeners()
+
+ 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')
+ })
+
+ 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' } })
+ await expectLogic(logic).toFinishAllListeners()
+
+ const expansion = accountsExpansionLogic.findMounted()
+ expect(expansion?.values.activeTabByAccount['acc-9']).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' } }
+ )
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.hashParams.open).toBeUndefined()
+ expect(router.values.hashParams.view).toEqual({ search: 'ext-9' })
+ })
+
+ it('ignores an open hash with no account id', async () => {
+ router.actions.push(urls.customerAnalyticsAccounts(), {}, { open: { tab: 'usage' } })
+ await expectLogic(logic).toFinishAllListeners()
+
+ const expansion = accountsExpansionLogic.findMounted()
+ expect(expansion?.values.expandedAccountIds ?? []).toEqual([])
+ })
+
+ 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}`)
+ await expectLogic(logic).toFinishAllListeners()
+
+ const expansion = accountsExpansionLogic.findMounted()
+ expect(expansion?.values.expandedAccountIds).toContain('acc-9')
+ expect(expansion?.values.activeTabByAccount['acc-9']).toBe('usage')
+ })
+ })
+
describe('updateAccountRole', () => {
const existingAccount = buildAccount()
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index f09ac3317cb2..4fee1ea4b503 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -24,7 +24,12 @@ import {
ACCOUNTS_NAME_COLUMN,
accountsColumnConfigLogic,
} from './accountsColumnConfigLogic'
-import { AccountExpansionTab, accountsExpansionLogic } from './accountsExpansionLogic'
+import {
+ ACCOUNT_EXPANSION_TABS,
+ AccountExpansionTab,
+ accountsExpansionLogic,
+ DEFAULT_ACCOUNT_TAB,
+} from './accountsExpansionLogic'
import type { accountsLogicType } from './accountsLogicType'
import { accountsOverviewTilesLogic, TileFilter } from './accountsOverviewTilesLogic'
import { normalizeRoleFilter } from './accountsViewState'
@@ -115,6 +120,17 @@ 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(() => ({
@@ -604,6 +620,18 @@ export const accountsLogic = kea<accountsLogicType>([
if (!objectsEqual(tileFilter, values.tileFilter)) {
actions.setTileFilter(tileFilter)
}
+
+ // 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)
+ }
},
})),
])