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.

fix(customer-analytics): make account deep links resolve (#78307)

Arthur Moreira de Deus59bfd418d289
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index fb503f7a68fa..c5df8301e447 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -125,7 +125,20 @@ The Notes tab is server-paginated, searchable, and sortable (all via `accountNot
### Deep-link to one account (path route)
-`/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.
+`/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`, 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.
+
+A set `accountIdFilter` **replaces** the rest of the query's filters rather than ANDing with them: `applyAccountFilters` emits `toString(id) = '<id>'` alone and returns.
+A deep link has to resolve to its account for whoever opens it, and the viewer's own filters (a restored saved view, the localStorage-persisted "my accounts" toggle) would otherwise exclude it and land them on an empty list.
+
+Two things conspire to bounce a deep link back to the unfiltered list, so keep both in mind when touching URL sync:
+
+- `actionToUrl` mirrors view state into the hash on ~14 setters, and those setters also fire while state is being _restored_ (the default-column upgrade once relationship definitions load, `accountsViewsLogic`'s auto-restored saved view) — not just on user edits.
+ So it writes back to `accountsPathToWriteBackTo(accountIdFilter)`, the path we are already on, never a hardcoded list path.
+- Because the deep-link path can therefore carry a `#view=` hash, its `urlToAction` handlers restore that hash too — but only when one is present.
+ An absent hash there means "just open the account", not "reset the list".
**Build the URL via the canonical helpers, never hand-build the path:**
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index ab00f6c559fa..5c94daf75d6b 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -605,6 +605,34 @@ describe('accountsLogic', () => {
expect(logic.values.accountIdFilter).toBeNull()
})
+ it('resolves to the account even when the viewer has filters of their own', async () => {
+ logic.actions.setSearchQuery('something else')
+ logic.actions.setAssignedToFilter([99])
+
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID))
+ await expectLogic(logic).toFinishAllListeners()
+
+ const source = logic.values.hogqlQuery.source as AccountsQuery
+ expect(filterExpressionOf(source)).toBe(`(toString(id) = '${ACCOUNT_ID}')`)
+ expect(source.search).toBeUndefined()
+ expect(source.assignedToUserIds).toBeUndefined()
+ })
+
+ it('survives a view-state restore rewriting the URL', async () => {
+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage'))
+ await expectLogic(logic).toFinishAllListeners()
+ const deepLinkPath = router.values.location.pathname
+
+ // Landing on a deep link, the saved-view restore and the default-column upgrade both
+ // dispatch the setters that mirror view state into the URL. They must not rewrite the
+ // path, or the link bounces to the unfiltered list before the user sees the account.
+ accountsColumnConfigLogic.findMounted()!.actions.setSelectColumns([ACCOUNTS_NAME_COLUMN, 'csm'])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(router.values.location.pathname).toBe(deepLinkPath)
+ expect(logic.values.accountIdFilter).toBe(ACCOUNT_ID)
+ })
+
it('clears the account filter when returning to the bare list', async () => {
router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage'))
await expectLogic(logic).toFinishAllListeners()
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index 3d52ef382727..bf960f738794 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -4,6 +4,7 @@ import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { isUUIDLike } from 'lib/utils/guards'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { objectsEqual } from 'lib/utils/objects'
import { membersLogic } from 'scenes/organization/membersLogic'
import { teamLogic } from 'scenes/teamLogic'
@@ -108,6 +109,15 @@ interface AccountQueryFilters {
// Shared filter clauses for the list-rows query and the overview-metrics query,
// so both always aggregate/list over the exact same set of accounts.
function applyAccountFilters(source: AccountsQuery, filters: AccountQueryFilters): void {
+ // A deep link pins the list to one account by its PK, and it has to resolve to that account for
+ // whoever opens it. The viewer's own filters — a restored saved view, the persisted "my accounts"
+ // toggle — would otherwise AND with the id and leave them on an empty list, so the pin wins alone.
+ // The id is only ever a validated UUID (set from the route), so it's injection-safe. Compare it
+ // stringified, matching how the name-cell id is built.
+ if (filters.accountIdFilter) {
+ source.filterExpression = `(toString(id) = '${filters.accountIdFilter}')`
+ return
+ }
const trimmed = filters.searchQuery.trim()
if (trimmed) {
source.search = trimmed
@@ -121,16 +131,10 @@ function applyAccountFilters(source: AccountsQuery, filters: AccountQueryFilters
if (filters.assignedToFilter.length > 0) {
source.assignedToUserIds = filters.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 (filters.tileFilter) {
filterExpressions.push(filters.tileFilter.expression)
}
- if (filters.accountIdFilter) {
- filterExpressions.push(`toString(id) = '${filters.accountIdFilter}'`)
- }
filterExpressions.push(
...customPropertyFiltersToExpressions(filters.customPropertyFilters, filters.customPropertyDefinitionsById)
)
@@ -141,6 +145,17 @@ function applyAccountFilters(source: AccountsQuery, filters: AccountQueryFilters
export const savingRoleKey = (accountId: string, column: string): string => `${accountId}:${column}`
+// Which accounts path the shareable view state gets written back to. It must be the path we are
+// already on: the setters that mirror view state into the URL also fire while state is being
+// restored (the default-column upgrade once relationship definitions load, the auto-restored saved
+// view), so pointing them at the list would bounce a single-account deep link to the unfiltered
+// list moments after it opened. Returns the live pathname so the deep link keeps its `/:tab`.
+function accountsPathToWriteBackTo(accountIdFilter: string | null): string {
+ const pathname = removeProjectIdIfPresent(router.values.location.pathname)
+ const deepLinkPath = accountIdFilter ? urls.customerAnalyticsAccount(accountIdFilter) : null
+ return deepLinkPath && pathname.startsWith(deepLinkPath) ? pathname : urls.customerAnalyticsAccounts()
+}
+
// Shareable view state encoded into the URL hash (`#view=...`) so a copied URL
// reproduces the exact accounts list a colleague is looking at. Only non-default
// values are serialized, keeping the hash empty for the default view.
@@ -997,7 +1012,7 @@ export const accountsLogic = kea<accountsLogicType>([
// Mirror the full view into the URL hash so the link is shareable.
// Search params are preserved untouched — the parent scene owns those.
const toUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => [
- urls.customerAnalyticsAccounts(),
+ accountsPathToWriteBackTo(values.accountIdFilter),
router.values.searchParams,
objectsEqual(values.viewUrlState, {}) ? {} : { view: values.viewUrlState },
{ replace: true },
@@ -1021,7 +1036,8 @@ export const accountsLogic = kea<accountsLogicType>([
}),
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).
+ // The URL stays on the path — neither setter is wired into actionToUrl, and the setters that
+ // are keep the current path (see `accountsPathToWriteBackTo`).
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)) {
@@ -1036,85 +1052,98 @@ export const accountsLogic = kea<accountsLogicType>([
}
actions.openAccountTab(accountId, tab)
}
- return {
- [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)
- }
+ const restoreView = (view: AccountsViewUrlState): void => {
+ const search = view.search ?? ''
+ if (search !== values.searchQuery) {
+ actions.setSearchQuery(search)
+ }
- const tags = view.tags ?? []
- if (!objectsEqual(tags, values.tagsFilter)) {
- actions.setTagsFilter(tags)
- }
+ const tags = view.tags ?? []
+ if (!objectsEqual(tags, values.tagsFilter)) {
+ actions.setTagsFilter(tags)
+ }
- const customProperties = Array.isArray(view.customProperties) ? view.customProperties : []
- if (!objectsEqual(customProperties, values.customPropertyFilters)) {
- actions.setCustomPropertyFilters(customProperties)
- }
+ const customProperties = Array.isArray(view.customProperties) ? view.customProperties : []
+ if (!objectsEqual(customProperties, values.customPropertyFilters)) {
+ actions.setCustomPropertyFilters(customProperties)
+ }
- const unassigned = view.unassigned ?? false
- if (unassigned !== values.allRolesUnassigned) {
- actions.setAllRolesUnassigned(unassigned)
- }
+ const unassigned = view.unassigned ?? false
+ if (unassigned !== values.allRolesUnassigned) {
+ actions.setAllRolesUnassigned(unassigned)
+ }
- 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] : []
- // With no explicit assignment in the hash (e.g. arriving via the tab
- // link), fall back to the shared "mine only" toggle so the choice made
- // on the Notes tab carries over.
- const sharedMine =
- !assignedTo.length && !view.mine && values.mineOnly && values.currentUserId !== null
- ? [values.currentUserId]
- : []
- // The persisted "my accounts" intent can't be resolved until the user id is
- // known. If the user hasn't loaded yet, leave the filter untouched (rather than
- // writing an empty one, which would cascade to setMineOnly(false) and clobber the
- // preference) and let the loadUserSuccess listener apply it once the user resolves.
- const mineRestorePending =
- !assignedTo.length && !view.mine && values.mineOnly && values.currentUserId === null
- const nextAssignedTo = assignedTo.length ? assignedTo : legacyMine.length ? legacyMine : sharedMine
- if (!mineRestorePending && !objectsEqual(nextAssignedTo, values.assignedToFilter)) {
- actions.setAssignedToFilter(nextAssignedTo)
- }
+ 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] : []
+ // With no explicit assignment in the hash (e.g. arriving via the tab
+ // link), fall back to the shared "mine only" toggle so the choice made
+ // on the Notes tab carries over.
+ const sharedMine =
+ !assignedTo.length && !view.mine && values.mineOnly && values.currentUserId !== null
+ ? [values.currentUserId]
+ : []
+ // The persisted "my accounts" intent can't be resolved until the user id is
+ // known. If the user hasn't loaded yet, leave the filter untouched (rather than
+ // writing an empty one, which would cascade to setMineOnly(false) and clobber the
+ // preference) and let the loadUserSuccess listener apply it once the user resolves.
+ const mineRestorePending =
+ !assignedTo.length && !view.mine && values.mineOnly && values.currentUserId === null
+ const nextAssignedTo = assignedTo.length ? assignedTo : legacyMine.length ? legacyMine : sharedMine
+ if (!mineRestorePending && !objectsEqual(nextAssignedTo, values.assignedToFilter)) {
+ actions.setAssignedToFilter(nextAssignedTo)
+ }
- const sort = view.sort ?? null
- if (!objectsEqual(sort, values.sortOrder)) {
- actions.setSortOrder(sort)
- }
+ const sort = view.sort ?? null
+ if (!objectsEqual(sort, values.sortOrder)) {
+ actions.setSortOrder(sort)
+ }
- // 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)
- }
+ // 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 columnDisplay =
- view.columnDisplay && typeof view.columnDisplay === 'object' ? view.columnDisplay : {}
- if (!objectsEqual(columnDisplay, values.columnDisplay)) {
- actions.setColumnDisplayConfig(columnDisplay)
- }
+ const columnDisplay = view.columnDisplay && typeof view.columnDisplay === 'object' ? view.columnDisplay : {}
+ if (!objectsEqual(columnDisplay, values.columnDisplay)) {
+ actions.setColumnDisplayConfig(columnDisplay)
+ }
- const tileFilter = view.tileFilter ?? null
- if (!objectsEqual(tileFilter, values.tileFilter)) {
- actions.setTileFilter(tileFilter)
- }
+ const tileFilter = view.tileFilter ?? null
+ if (!objectsEqual(tileFilter, values.tileFilter)) {
+ actions.setTileFilter(tileFilter)
+ }
+ }
+ const viewFromHash = (hashParams: Record<string, any> | undefined): AccountsViewUrlState =>
+ hashParams?.view && typeof hashParams.view === 'object' ? hashParams.view : {}
+ return {
+ [urls.customerAnalyticsAccounts()]: (_, __, hashParams): void => {
+ restoreView(viewFromHash(hashParams))
// 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),
+ // A deep link carries the same shareable `#view=` hash, but only restore it when it's
+ // actually there — an absent hash on this route means "just open the account", not
+ // "reset the list", so the saved view stays in charge.
+ [urls.customerAnalyticsAccount(':accountId')]: ({ accountId }, __, hashParams): void => {
+ if (hashParams?.view) {
+ restoreView(viewFromHash(hashParams))
+ }
+ openAccountByPath(accountId)
+ },
+ [urls.customerAnalyticsAccount(':accountId', ':tab')]: ({ accountId, tab }, __, hashParams): void => {
+ if (hashParams?.view) {
+ restoreView(viewFromHash(hashParams))
+ }
+ openAccountByPath(accountId, tab)
+ },
}
}),
])