:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): add "My accounts" filter to notes tab (#68769)
Jonathan Lua84965bab563
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 515d93c58944..bb4aa33bb4fc 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -1489,12 +1489,21 @@ def list_account_notes_for_view(search: str | None = None,account_id: UUID | str | None = None,created_by_ids: list[int] | None = None,+ assigned_to_ids: list[int] | None = None,) -> tuple[list[contracts.AccountNoteView], int]:"""Team-wide account notes (internal notebooks linked to accounts), newest-modified first,restricted to accounts the caller can read. ``search`` matches note title/content (full-text)and account name (substring). ``account_id`` narrows to one account, ``created_by_ids`` to- notes authored by the given users. Returns ``(page, total_count)``."""- accessible_account_ids = _accounts_queryset(team_id, user_access_control).values_list("id", flat=True)+ notes authored by the given users, ``assigned_to_ids`` to notes on accounts whose CSM or+ account executive is one of the given users. Returns ``(page, total_count)``."""+ accounts = _accounts_queryset(team_id, user_access_control)+ if assigned_to_ids:+ # "Assigned to" means CSM or AE (account_owner excluded), matching the accounts list+ # HogQL runner's ASSIGNED_ROLE_KEYS.+ accounts = accounts.filter(+ Q(_properties__csm__id__in=assigned_to_ids) | Q(_properties__account_executive__id__in=assigned_to_ids)+ )+ accessible_account_ids = accounts.values_list("id", flat=True)notes, count = notebooks.list_team_account_notes(team_id,account_ids=accessible_account_ids,diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 344236d9982f..a965a339b0e2 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -823,6 +823,34 @@ def _synthesize_notebook_content(text_content, existing_content):return None+# Module-level (not ViewSet static methods) so the ``list[int]`` return annotation resolves to+# the builtin: the ViewSets define a ``list`` method that shadows ``list`` inside the class body.+def _parse_int_ids_param(request: Request, name: str) -> list[int]:+ """Parse a repeated or comma-joined integer-id query param (e.g. ``created_by`` / ``assigned_to``).++ The generated client serializes an array as a single comma-joined value; accept that+ and the repeated-param form alike."""+ ids: list[int] = []+ for value in request.query_params.getlist(name):+ for part in value.split(","):+ part = part.strip()+ if not part:+ continue+ if not part.isdigit():+ raise ValidationError({name: "Must be a comma-separated list of numeric user IDs."})+ ids.append(int(part))+ return ids+++def _parse_uuid_param(request: Request, name: str) -> UUID | None:+ if raw := request.query_params.get(name):+ try:+ return UUID(raw)+ except ValueError:+ raise ValidationError({name: "Must be a valid UUID."})+ return None++@extend_schema(tags=["customer_analytics"])class AccountNotesViewSet(TeamAndOrgViewSetMixin,@@ -859,26 +887,18 @@ class AccountNotesViewSet(required=False,description="Only return notes created by these user IDs (repeat the param per user).",),+ OpenApiParameter(+ name="assigned_to",+ type=OpenApiTypes.INT,+ many=True,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Only return notes on accounts assigned to these user IDs "+ "(the account's CSM or account executive; repeat the param per user).",+ ),],)def list(self, request: Request, *args, **kwargs) -> Response:- # The generated client serializes the array as a single comma-joined value; accept that- # and the repeated-param form alike.- created_by_ids = []- for value in request.query_params.getlist("created_by"):- for part in value.split(","):- part = part.strip()- if not part:- continue- if not part.isdigit():- raise ValidationError({"created_by": "Must be a comma-separated list of numeric user IDs."})- created_by_ids.append(int(part))- account_id: UUID | None = None- if raw_account_id := request.query_params.get("account_id"):- try:- account_id = UUID(raw_account_id)- except ValueError:- raise ValidationError({"account_id": "Must be a valid UUID."})return self._paginate_via_facade(request,lambda offset, limit: api.list_account_notes_for_view(@@ -887,8 +907,9 @@ class AccountNotesViewSet(offset=offset,limit=limit,search=request.query_params.get("search", "").strip() or None,- account_id=account_id,- created_by_ids=created_by_ids or None,+ account_id=_parse_uuid_param(request, "account_id"),+ created_by_ids=_parse_int_ids_param(request, "created_by") or None,+ assigned_to_ids=_parse_int_ids_param(request, "assigned_to") or None,),AccountNoteSerializer,)diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex 8f1c37c34b03..ef18db5e2f98 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -2016,6 +2016,7 @@ class TestAccountNotesViewSet(APIBaseTest):("account_id", "not-a-uuid"),("created_by", "alice"),("created_by", "alice,bob"),+ ("assigned_to", "alice"),])def test_list_rejects_malformed_filter(self, param, value):@@ -2023,6 +2024,35 @@ class TestAccountNotesViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ def test_list_filter_by_assigned_to(self):+ # "My accounts" on the Notes tab: notes on accounts where the user is CSM or AE.+ # account_owner is deliberately not treated as "assigned" (mirrors the accounts list).+ csm_account = Account.objects.unscoped().create(+ team=self.team, name="CSM Co", _properties={"csm": {"id": self.user.id, "email": self.user.email}}+ )+ ae_account = Account.objects.unscoped().create(+ team=self.team,+ name="AE Co",+ _properties={"account_executive": {"id": self.user.id, "email": self.user.email}},+ )+ owner_account = Account.objects.unscoped().create(+ team=self.team,+ name="Owner Co",+ _properties={"account_owner": {"id": self.user.id, "email": self.user.email}},+ )+ other_account = Account.objects.unscoped().create(+ team=self.team, name="Other Co", _properties={"csm": {"id": 999999, "email": "[email protected]"}}+ )+ self._link_note(title="CSM note", account=csm_account)+ self._link_note(title="AE note", account=ae_account)+ self._link_note(title="Owner note", account=owner_account)+ self._link_note(title="Other note", account=other_account)++ response = self.client.get(f"{self.endpoint_base}?assigned_to={self.user.id}")++ titles = {n["title"] for n in response.json()["results"]}+ self.assertEqual(titles, {"CSM note", "AE note"})+@parameterized.expand([("single", "{uid}"),diff --git a/products/customer_analytics/frontend/components/AccountNotes/AccountNotesTabContent.tsx b/products/customer_analytics/frontend/components/AccountNotes/AccountNotesTabContent.tsxindex ef7d436a63c2..be2ba4878fc9 100644--- a/products/customer_analytics/frontend/components/AccountNotes/AccountNotesTabContent.tsx+++ b/products/customer_analytics/frontend/components/AccountNotes/AccountNotesTabContent.tsx@@ -26,13 +26,15 @@ export function AccountNotesTabContent(): JSX.Element {search,createdByFilter,createdByCurrentUser,+ assignedToCurrentUser,accountFilter,pagination,} = useValues(accountNotesLogic)- const { setSearch, setCreatedByFilter, setCreatedByCurrentUser, reportFilterChange } = useActions(accountNotesLogic)+ const { setSearch, setCreatedByFilter, setCreatedByCurrentUser, setAssignedToCurrentUser, reportFilterChange } =+ useActions(accountNotesLogic)const { selectNotebook } = useActions(notebookPanelLogic)- const hasFilters = !!search || createdByFilter.length > 0 || accountFilter !== null+ const hasFilters = !!search || createdByFilter.length > 0 || assignedToCurrentUser || accountFilter !== nullconst columns: LemonTableColumns<AccountNoteApi> = [{@@ -137,6 +139,16 @@ export function AccountNotesTabContent(): JSX.Element {info="Shortcut for Created by: you — notes you created"data-attr="account-notes-my-notes-filter"/>+ <LemonCheckbox+ checked={assignedToCurrentUser}+ onChange={(value) => {+ setAssignedToCurrentUser(value)+ reportFilterChange('my_accounts')+ }}+ label="My accounts"+ info="Notes on accounts where you are the CSM or account executive"+ data-attr="account-notes-my-accounts-filter"+ /></div>{accountNotesResponse === null ? (// Dedicated initial-load state (mirrors AccountOpportunitiesExpansion); thediff --git a/products/customer_analytics/frontend/components/AccountNotes/accountNotesLogic.test.ts b/products/customer_analytics/frontend/components/AccountNotes/accountNotesLogic.test.tsnew file mode 100644index 000000000000..66d3cc6a4148--- /dev/null+++ b/products/customer_analytics/frontend/components/AccountNotes/accountNotesLogic.test.ts@@ -0,0 +1,110 @@+import { expectLogic } from 'kea-test-utils'++import { userLogic } from 'scenes/userLogic'++import { initKeaTests } from '~/test/init'+import type { UserType } from '~/types'++import { accountNotesList, accountsList } from 'products/customer_analytics/frontend/generated/api'++import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'+import { accountNotesLogic } from './accountNotesLogic'++jest.mock('products/customer_analytics/frontend/generated/api', () => ({+ accountNotesList: jest.fn(),+ accountsList: jest.fn(),+}))++const mockAccountNotesList = accountNotesList as jest.MockedFunction<typeof accountNotesList>+const mockAccountsList = accountsList as jest.MockedFunction<typeof accountsList>++const CURRENT_USER_ID = 42++describe('accountNotesLogic', () => {+ let logic: ReturnType<typeof accountNotesLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.resetAllMocks()+ mockAccountNotesList.mockResolvedValue({ count: 0, results: [] } as any)+ mockAccountsList.mockResolvedValue({ count: 0, results: [] } as any)+ // mineOnly is persisted to localStorage on the shared scene logic; isolate tests.+ localStorage.clear()+ userLogic.actions.loadUserSuccess({ id: CURRENT_USER_ID } as unknown as UserType)+ })++ afterEach(() => {+ logic?.unmount()+ localStorage.clear()+ })++ // "My accounts" (assigned-to-me) is shared with the Accounts tab via the scene logic's+ // mineOnly toggle; "My notes" (created-by-me) is notes-only and must stay independent.+ it('"My accounts" resolves to the current user, sends assigned_to, and syncs the shared toggle', async () => {+ logic = accountNotesLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.setAssignedToCurrentUser(true)+ }).toFinishAllListeners()++ expect(logic.values.assignedToFilter).toEqual([CURRENT_USER_ID])+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(true)+ expect(mockAccountNotesList).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({ assigned_to: [CURRENT_USER_ID] })+ )+ })++ it('"My notes" does not touch the shared "My accounts" toggle', async () => {+ logic = accountNotesLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.setCreatedByCurrentUser(true)+ }).toFinishAllListeners()++ expect(logic.values.createdByCurrentUser).toBe(true)+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(false)+ })++ it('restores "My accounts" from the shared toggle on mount', async () => {+ customerAnalyticsSceneLogic.mount()+ customerAnalyticsSceneLogic.actions.setMineOnly(true)++ logic = accountNotesLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.assignedToCurrentUser).toBe(true)+ expect(mockAccountNotesList).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ assigned_to: [CURRENT_USER_ID] })+ )+ })++ // Regression: a fresh page load can mount this logic before userLogic resolves the user,+ // so afterMount can't apply the persisted choice (currentUserId null). The user resolving+ // later must still apply it — otherwise the returning user sees all notes until they toggle.+ it('applies a persisted "My accounts" choice when the user resolves after mount', async () => {+ logic = accountNotesLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ // Persisted choice present but not yet applied (user was unknown during restore).+ customerAnalyticsSceneLogic.actions.setMineOnly(true)+ expect(logic.values.assignedToCurrentUser).toBe(false)++ await expectLogic(logic, () => {+ userLogic.actions.loadUserSuccess({ id: CURRENT_USER_ID } as unknown as UserType)+ }).toFinishAllListeners()++ expect(logic.values.assignedToFilter).toEqual([CURRENT_USER_ID])+ expect(mockAccountNotesList).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({ assigned_to: [CURRENT_USER_ID] })+ )+ })+})diff --git a/products/customer_analytics/frontend/components/AccountNotes/accountNotesLogic.ts b/products/customer_analytics/frontend/components/AccountNotes/accountNotesLogic.tsindex b2a61a7d900d..02cec42ae9a7 100644--- a/products/customer_analytics/frontend/components/AccountNotes/accountNotesLogic.ts+++ b/products/customer_analytics/frontend/components/AccountNotes/accountNotesLogic.ts@@ -14,6 +14,7 @@ import type {PaginatedAccountNoteListApi,} from 'products/customer_analytics/frontend/generated/api.schemas'+import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'import { AccountsEvents, type NotesTabFilterType } from '../Accounts/constants'import type { accountNotesLogicType } from './accountNotesLogicType'@@ -25,7 +26,8 @@ export type AccountFilterOption = { id: string; name: string }export const accountNotesLogic = kea<accountNotesLogicType>([path(['products', 'customer_analytics', 'frontend', 'components', 'AccountNotes', 'accountNotesLogic']),connect(() => ({- values: [teamLogic, ['currentTeamId'], userLogic, ['user']],+ values: [teamLogic, ['currentTeamId'], userLogic, ['user'], customerAnalyticsSceneLogic, ['mineOnly']],+ actions: [customerAnalyticsSceneLogic, ['setMineOnly'], userLogic, ['loadUserSuccess']],})),actions({loadAccountNotes: true,@@ -33,6 +35,9 @@ export const accountNotesLogic = kea<accountNotesLogicType>([setPage: (page: number) => ({ page }),setCreatedByFilter: (userIds: number[]) => ({ userIds }),setCreatedByCurrentUser: (value: boolean) => ({ value }),+ setAssignedToFilter: (userIds: number[]) => ({ userIds }),+ // Shortcut for the "My accounts" checkbox — resolves to the current user's id.+ setAssignedToCurrentUser: (value: boolean) => ({ value }),setAccountFilter: (account: AccountFilterOption | null) => ({ account }),setAccountSearch: (query: string) => ({ query }),reportFilterChange: (filterType: NotesTabFilterType) => ({ filterType }),@@ -47,6 +52,7 @@ export const accountNotesLogic = kea<accountNotesLogicType>([search: values.search || undefined,account_id: values.accountFilter?.id,created_by: values.createdByFilter.length ? values.createdByFilter : undefined,+ assigned_to: values.assignedToFilter.length ? values.assignedToFilter : undefined,limit: RESULTS_PER_PAGE,offset: (values.page - 1) * RESULTS_PER_PAGE,})@@ -73,6 +79,7 @@ export const accountNotesLogic = kea<accountNotesLogicType>([reducers({search: ['', { setSearch: (_, { search }) => search }],createdByFilter: [[] as number[], { setCreatedByFilter: (_, { userIds }) => userIds }],+ assignedToFilter: [[] as number[], { setAssignedToFilter: (_, { userIds }) => userIds }],accountFilter: [null as AccountFilterOption | null, { setAccountFilter: (_, { account }) => account }],accountSearch: ['', { setAccountSearch: (_, { query }) => query }],page: [@@ -81,6 +88,7 @@ export const accountNotesLogic = kea<accountNotesLogicType>([setPage: (_, { page }) => page,setSearch: () => 1,setCreatedByFilter: () => 1,+ setAssignedToFilter: () => 1,setAccountFilter: () => 1,},],@@ -97,6 +105,13 @@ export const accountNotesLogic = kea<accountNotesLogicType>([(createdByFilter: number[], currentUserId: number | null): boolean =>currentUserId !== null && createdByFilter.length === 1 && createdByFilter[0] === currentUserId,],+ // "My accounts" is the same shorthand over the assigned-to filter (accounts where I'm+ // CSM or AE). Shared with the Accounts tab via customerAnalyticsSceneLogic.mineOnly.+ assignedToCurrentUser: [+ (s) => [s.assignedToFilter, s.currentUserId],+ (assignedToFilter: number[], currentUserId: number | null): boolean =>+ currentUserId !== null && assignedToFilter.length === 1 && assignedToFilter[0] === currentUserId,+ ],pagination: [(s) => [s.page, s.accountNotesResponse],(page: number, response: PaginatedAccountNoteListApi | null): PaginationManual => ({@@ -142,10 +157,27 @@ export const accountNotesLogic = kea<accountNotesLogicType>([setCreatedByCurrentUser: ({ value }) => {actions.setCreatedByFilter(value && values.currentUserId !== null ? [values.currentUserId] : [])},+ setAssignedToFilter: () => {+ actions.loadAccountNotes()+ // Keep the shared "mine only" ("My accounts") toggle in step so switching to the+ // Accounts tab reflects the same choice.+ actions.setMineOnly(values.assignedToCurrentUser)+ },+ setAssignedToCurrentUser: ({ value }) => {+ actions.setAssignedToFilter(value && values.currentUserId !== null ? [values.currentUserId] : [])+ },+ // A fresh page load can mount this logic before userLogic resolves the user, leaving+ // currentUserId null in afterMount so the persisted "My accounts" choice can't be+ // applied. Re-apply it once the user arrives (skip if already applied or turned off).+ loadUserSuccess: () => {+ if (values.mineOnly && values.currentUserId !== null && !values.assignedToCurrentUser) {+ actions.setAssignedToCurrentUser(true)+ }+ },setAccountFilter: () => actions.loadAccountNotes(),setAccountSearch: ({ query }) => actions.loadAccountOptions({ query }),// Captures live in a dedicated report action (dispatched by the controls only) so the- // "My notes" shortcut cascading into setCreatedByFilter doesn't double-fire events.+ // "My notes"/"My accounts" shortcuts cascading into the raw filters don't double-fire events.reportFilterChange: ({ filterType }) => {const properties: Record<string, string | number | boolean> = { filter_type: filterType }if (filterType === 'created_by') {@@ -153,6 +185,9 @@ export const accountNotesLogic = kea<accountNotesLogicType>([properties.user_count = values.createdByFilter.length} else if (filterType === 'account') {properties.is_cleared = values.accountFilter === null+ } else if (filterType === 'my_accounts') {+ properties.value = values.assignedToCurrentUser+ properties.is_cleared = !values.assignedToCurrentUser} else {properties.value = values.createdByCurrentUserproperties.is_cleared = !values.createdByCurrentUser@@ -167,9 +202,15 @@ export const accountNotesLogic = kea<accountNotesLogicType>([posthog.captureException(error)},})),- afterMount(({ actions }) => {+ afterMount(({ actions, values }) => {posthog.capture(AccountsEvents.NotesTabViewed)- actions.loadAccountNotes()+ // Restore the shared "My accounts" choice from the other tab. Setting the assigned-to+ // filter triggers the initial notes load, so only fall back to a bare load when it's off.+ if (values.mineOnly && values.currentUserId !== null) {+ actions.setAssignedToCurrentUser(true)+ } else {+ actions.loadAccountNotes()+ }actions.loadAccountOptions({ query: '' })}),])diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 08d71a79418c..ed64af9409cc 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -49,7 +49,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc## Data & query model-`accountsLogic.hogqlQuery` builds a `DataTableNode` wrapping an `AccountsQuery` for the list rows (`select`, plus optional `search`, `tagNames`, `allRolesUnassigned`, `assignedToUserIds`, `filterExpression`, `orderBy`). The overview-tile `metrics` are **not** on this query — `accountsLogic.metricsQuery` is a separate metrics-only `AccountsQuery` (`metrics` set, no `select`; `null` when there are no tiles) that the backend runner answers with its own aggregation query, so the tiles load without blocking the rows. Both queries share filters via `applyAccountFilters`. The backend runner (`accounts_query_runner`) returns **rows as arrays** aligned to `visibleColumnNames`, and tile aggregations in `metricsResults`. `assignedToUserIds` is the "assigned to" filter — a list of user ids the runner expands into `csm IN ids OR account_executive IN ids` (the single user-facing role filter; there are no separate per-role CSM/AE/owner filters). The `allRolesUnassigned` flag (the "Unassigned only" option, surfaced inside the "Assigned to" picker — mutually exclusive with picking people via the cascade in `accountsLogic` listeners) restricts to accounts with no csm/AE/owner. The "My accounts" checkbox is a client-side shortcut: `accountsLogic` resolves it to `[currentUserId]` (from `userLogic`) before the query is sent, so the backend only ever receives explicit ids and a shared URL resolves to the same accounts for every viewer. Two cell shapes matter:+`accountsLogic.hogqlQuery` builds a `DataTableNode` wrapping an `AccountsQuery` for the list rows (`select`, plus optional `search`, `tagNames`, `allRolesUnassigned`, `assignedToUserIds`, `filterExpression`, `orderBy`). The overview-tile `metrics` are **not** on this query — `accountsLogic.metricsQuery` is a separate metrics-only `AccountsQuery` (`metrics` set, no `select`; `null` when there are no tiles) that the backend runner answers with its own aggregation query, so the tiles load without blocking the rows. Both queries share filters via `applyAccountFilters`. The backend runner (`accounts_query_runner`) returns **rows as arrays** aligned to `visibleColumnNames`, and tile aggregations in `metricsResults`. `assignedToUserIds` is the "assigned to" filter — a list of user ids the runner expands into `csm IN ids OR account_executive IN ids` (the single user-facing role filter; there are no separate per-role CSM/AE/owner filters). The `allRolesUnassigned` flag (the "Unassigned only" option, surfaced inside the "Assigned to" picker — mutually exclusive with picking people via the cascade in `accountsLogic` listeners) restricts to accounts with no csm/AE/owner. The "My accounts" checkbox is a client-side shortcut: `accountsLogic` resolves it to `[currentUserId]` (from `userLogic`) before the query is sent, so the backend only ever receives explicit ids and a shared URL resolves to the same accounts for every viewer. Its on/off state is mirrored into a shared `mineOnly` toggle on `customerAnalyticsSceneLogic` (localStorage-persisted, like `filterTestAccounts`) so the choice carries over to the Notes tab's own "My accounts" checkbox and back — `setAssignedToFilter` keeps `mineOnly` in step, and when the accounts URL carries no explicit `assignedTo` in its `#view` hash the filter falls back to `mineOnly` → `[currentUserId]`. (On the Notes tab "My accounts" filters notes to those on accounts assigned to you, via the `assigned_to` param on the account-notes endpoint; "My notes" there is the separate created-by shortcut and is not shared.) Two cell shapes matter:- **`name` column** (mandatory, `ACCOUNTS_NAME_COLUMN`) — emitted as `tuple(name, external_id, id)`, read as `{ name, external_id, id }`. This is the row's identity: `id` (the account PK) drives expansion/scroll/role updates; `external_id` is the copy-able group key. `getNameCell()` in `AccountsHogQLTable.tsx` is the canonical accessor; never assume a column index. In `NameCell` the name renders as the prominent (`font-semibold`) primary label: a plain click opens the account details inline (toggles the row's expansion via `accountsExpansionLogic`, firing `AccountOpened` on open), while the `<Link>` href points at `urls.customerAnalyticsAccount(id)` so cmd/ctrl-click opens the account's deep-link page in a new tab. The `external_id` sits beneath it as de-emphasized (`text-xs text-muted`) copy-to-clipboard text.- **role columns** (`csm`, `account_executive`, `account_owner`) — emitted as `tuple(id, email)`, rendered with `MemberSelect`. Sorting these uses `tupleElement(col, 2)` (email) so visual order matches.@@ -159,35 +159,35 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions### Tracked events-| Event | Fires from | Properties |-| -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `customer analytics accounts list viewed` | `accountsLogic` `afterMount` | _(none — funnel anchor; account count and saved-config aren't loaded at mount)_ |-| `customer analytics accounts filter changed` | `accountsLogic` `reportFilterChange` listener (dispatched by the filter controls) | `filter_type` (`tag` \| `unassigned_only` \| `my_accounts` \| `assigned_to`), `value`, `is_cleared`, `active_filter_count`; for `tag` also `tag_count`; for `assigned_to` also `role_count` |-| `customer analytics accounts searched` | `accountsLogic` `setSearchInput` listener (post-debounce) | `query_length`, `has_query`, `active_filter_count` |-| `customer analytics accounts refreshed` | `accountsLogic` `refresh` | `has_search`, `active_filter_count`, `sort_column` |-| `customer analytics accounts sorted` | `accountsLogic` `toggleSort` | `column`, `direction` (`asc` \| `desc` \| `cleared`) |-| `customer analytics accounts account opened` | `AccountsHogQLTable.tsx` `NameCell` account-name `<Link>` `onClick` (only when the row expands, not when it collapses) | _(none — the row's `id` is customer PII-adjacent and kept out)_ |-| ~~`customer analytics accounts columns saved`~~ | _Deprecated — no longer emitted. Column changes are now saved as part of a view (see view events below)._ | _n/a_ |-| `customer analytics accounts overview tiles edited` | `accountsOverviewTilesLogic` editor close (diffed vs open snapshot, only when changed) | `tiles_added`, `tiles_removed`, `tiles_updated`, `reordered`, `tile_count_before`, `tile_count_after` |-| `customer analytics accounts overview tiles localstorage read` | `accountsOverviewTilesLogic` `afterMount` (only when a legacy custom value exists) | `tile_count` — **tombstone**: a legacy localStorage tiles value was read; once this stops firing, no browser still carries one and the read path can be removed |-| `customer analytics accounts view saved` | `accountsViewsLogic` `submitNewViewForm` listener (success) | `visibility` (`private` \| `shared`) |-| `customer analytics accounts view updated` | `accountsViewsLogic` `updateViewSuccess` listener | _(none)_ |-| `customer analytics accounts view selected` | `accountsViewsLogic` `applyView` listener | `visibility` |-| `customer analytics accounts view deleted` | `accountsViewsLogic` `deleteViewSuccess` listener | _(none)_ |-| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner`), `is_assigned`, `assigned_user_id`, `source` (always `list_row` today) |-| `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` | `link_key`, `has_destination` |-| `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |-| `customer analytics accounts note created` | `accountNotebooksLogic` `createNoteSuccess` listener | `notebook_short_id` |-| `customer analytics accounts notes searched` | `accountNotebooksLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |-| `customer analytics accounts notes sorted` | `accountNotebooksLogic` `setSorting` listener | `column` (`created_at` \| `created_by` \| null), `direction` (`asc` \| `desc` \| `cleared`) |-| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `usage` \| `spend` \| `opportunities`) |-| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |-| `customer analytics account opportunity clicked` | `AccountOpportunitiesExpansion.tsx` opportunity name `<Link>` `onClick` | _(none — CRM record id/url kept out)_ |-| `customer analytics notes tab viewed` | `accountNotesLogic` (`../AccountNotes/`) `afterMount` — the top-level Notes tab, not the per-account expansion | _(none — funnel anchor)_ |-| `customer analytics notes tab searched` | `accountNotesLogic` `setSearch` listener (post-debounce) | `has_query`, `query_length` (no raw text) |-| `customer analytics notes tab filtered` | `accountNotesLogic` `reportFilterChange` listener (dispatched by the filter controls only, so the "My notes" cascade doesn't double-fire) | `filter_type` (`created_by` \| `account` \| `my_notes`), `is_cleared`; for `created_by` also `user_count`; for `my_notes` also `value` (no account id/name logged) |-| `customer analytics notes tab note clicked` | `AccountNotesTabContent.tsx` note title `<Link>` `onClick` (opens side panel) | `notebook_short_id` |-| `customer analytics notes tab account clicked` | `AccountNotesTabContent.tsx` account `<Link>` `onClick` | `account_id` |+| Event | Fires from | Properties |+| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `customer analytics accounts list viewed` | `accountsLogic` `afterMount` | _(none — funnel anchor; account count and saved-config aren't loaded at mount)_ |+| `customer analytics accounts filter changed` | `accountsLogic` `reportFilterChange` listener (dispatched by the filter controls) | `filter_type` (`tag` \| `unassigned_only` \| `my_accounts` \| `assigned_to`), `value`, `is_cleared`, `active_filter_count`; for `tag` also `tag_count`; for `assigned_to` also `role_count` |+| `customer analytics accounts searched` | `accountsLogic` `setSearchInput` listener (post-debounce) | `query_length`, `has_query`, `active_filter_count` |+| `customer analytics accounts refreshed` | `accountsLogic` `refresh` | `has_search`, `active_filter_count`, `sort_column` |+| `customer analytics accounts sorted` | `accountsLogic` `toggleSort` | `column`, `direction` (`asc` \| `desc` \| `cleared`) |+| `customer analytics accounts account opened` | `AccountsHogQLTable.tsx` `NameCell` account-name `<Link>` `onClick` (only when the row expands, not when it collapses) | _(none — the row's `id` is customer PII-adjacent and kept out)_ |+| ~~`customer analytics accounts columns saved`~~ | _Deprecated — no longer emitted. Column changes are now saved as part of a view (see view events below)._ | _n/a_ |+| `customer analytics accounts overview tiles edited` | `accountsOverviewTilesLogic` editor close (diffed vs open snapshot, only when changed) | `tiles_added`, `tiles_removed`, `tiles_updated`, `reordered`, `tile_count_before`, `tile_count_after` |+| `customer analytics accounts overview tiles localstorage read` | `accountsOverviewTilesLogic` `afterMount` (only when a legacy custom value exists) | `tile_count` — **tombstone**: a legacy localStorage tiles value was read; once this stops firing, no browser still carries one and the read path can be removed |+| `customer analytics accounts view saved` | `accountsViewsLogic` `submitNewViewForm` listener (success) | `visibility` (`private` \| `shared`) |+| `customer analytics accounts view updated` | `accountsViewsLogic` `updateViewSuccess` listener | _(none)_ |+| `customer analytics accounts view selected` | `accountsViewsLogic` `applyView` listener | `visibility` |+| `customer analytics accounts view deleted` | `accountsViewsLogic` `deleteViewSuccess` listener | _(none)_ |+| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner`), `is_assigned`, `assigned_user_id`, `source` (always `list_row` today) |+| `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` | `link_key`, `has_destination` |+| `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |+| `customer analytics accounts note created` | `accountNotebooksLogic` `createNoteSuccess` listener | `notebook_short_id` |+| `customer analytics accounts notes searched` | `accountNotebooksLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |+| `customer analytics accounts notes sorted` | `accountNotebooksLogic` `setSorting` listener | `column` (`created_at` \| `created_by` \| null), `direction` (`asc` \| `desc` \| `cleared`) |+| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `usage` \| `spend` \| `opportunities`) |+| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |+| `customer analytics account opportunity clicked` | `AccountOpportunitiesExpansion.tsx` opportunity name `<Link>` `onClick` | _(none — CRM record id/url kept out)_ |+| `customer analytics notes tab viewed` | `accountNotesLogic` (`../AccountNotes/`) `afterMount` — the top-level Notes tab, not the per-account expansion | _(none — funnel anchor)_ |+| `customer analytics notes tab searched` | `accountNotesLogic` `setSearch` listener (post-debounce) | `has_query`, `query_length` (no raw text) |+| `customer analytics notes tab filtered` | `accountNotesLogic` `reportFilterChange` listener (dispatched by the filter controls only, so the "My notes"/"My accounts" cascade doesn't double-fire) | `filter_type` (`created_by` \| `account` \| `my_notes` \| `my_accounts`), `is_cleared`; for `created_by` also `user_count`; for `my_notes`/`my_accounts` also `value` (no account id/name logged) |+| `customer analytics notes tab note clicked` | `AccountNotesTabContent.tsx` note title `<Link>` `onClick` (opens side panel) | `notebook_short_id` |+| `customer analytics notes tab account clicked` | `AccountNotesTabContent.tsx` account `<Link>` `onClick` | `account_id` |> **Keep this table up to date.** Whenever you add, rename, or remove a `posthog.capture()` event in the Accounts area — or change its properties — update this table in the same change. An agent reading this file should be able to trust it as the source of truth for what the Accounts list reports.diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.test.tsxindex 559f341dd694..548b724f4aa9 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.test.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.test.tsx@@ -26,6 +26,9 @@ describe('AccountsTabFilters', () => {},})initKeaTests()+ // The shared "my accounts" (mineOnly) toggle persists to localStorage; clear it so a+ // value set by one test can't bleed into the next (which would pre-check the checkbox).+ localStorage.clear()logic = accountsLogic()logic.mount()})@@ -33,6 +36,7 @@ describe('AccountsTabFilters', () => {afterEach(() => {logic.unmount()cleanup()+ localStorage.clear()})function renderFilters(): void {diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.tsindex 10aa1cccd6c8..fbf2eb661c88 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts@@ -13,6 +13,7 @@ import type { UserBasicType, UserType } from '~/types'import { accountsPartialUpdate, accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'import {ACCOUNTS_HOGQL_DEFAULT_SELECT,ACCOUNTS_NAME_COLUMN,@@ -65,12 +66,16 @@ describe('accountsLogic', () => {beforeEach(() => {initKeaTests()jest.resetAllMocks()+ // accountsLogic connects to the (localStorage-persisted) shared scene logic;+ // clear it so a "mine only" write in one test can't leak into the next.+ localStorage.clear()logic = accountsLogic()logic.mount()})afterEach(() => {logic.unmount()+ localStorage.clear()})it('starts with empty filters', () => {@@ -204,6 +209,75 @@ describe('accountsLogic', () => {expect(logic.values.assignedToFilter).toEqual([CURRENT_USER_ID])expect(logic.values.assignedToCurrentUser).toBe(true)})++ // The "mine only" choice is held in the shared scene logic so it survives a+ // switch to the Notes tab. These guard the two-way link between the accounts+ // assigned-to filter and that shared toggle.+ describe('shared "mine only" toggle', () => {+ it('toggling "My accounts" writes the shared toggle', async () => {+ await expectLogic(logic, () => {+ logic.actions.setAssignedToCurrentUser(true)+ }).toFinishAllListeners()+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(true)++ await expectLogic(logic, () => {+ logic.actions.setAssignedToCurrentUser(false)+ }).toFinishAllListeners()+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(false)+ })++ it('picking explicit assignees clears the shared toggle', async () => {+ customerAnalyticsSceneLogic.actions.setMineOnly(true)+ await expectLogic(logic, () => {+ logic.actions.setAssignedToFilter([7])+ }).toFinishAllListeners()+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(false)+ })++ it('restores "my accounts" from the shared toggle when the URL has no view hash', async () => {+ customerAnalyticsSceneLogic.actions.setMineOnly(true)+ router.actions.push(urls.customerAnalyticsAccounts())+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.assignedToFilter).toEqual([CURRENT_USER_ID])+ expect(logic.values.assignedToCurrentUser).toBe(true)+ })++ it('an explicit shared link still wins over the shared toggle', async () => {+ customerAnalyticsSceneLogic.actions.setMineOnly(true)+ router.actions.push(urls.customerAnalyticsAccounts(), {}, { view: { assignedTo: [7] } })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.assignedToFilter).toEqual([7])+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(false)+ })++ // Regression: on a fresh load the logic can run URL restore before userLogic+ // resolves the user (currentUserId null), so the persisted choice can't be applied+ // then. The user resolving later must apply it, without clearing the preference.+ it('applies the persisted "my accounts" choice when the user resolves after restore', async () => {+ customerAnalyticsSceneLogic.actions.setMineOnly(true)+ expect(logic.values.assignedToFilter).toEqual([])++ await expectLogic(logic, () => {+ userLogic.actions.loadUserSuccess(buildUser({ id: CURRENT_USER_ID }) as unknown as UserType)+ }).toFinishAllListeners()++ expect(logic.values.assignedToFilter).toEqual([CURRENT_USER_ID])+ expect(customerAnalyticsSceneLogic.values.mineOnly).toBe(true)+ })++ it('the user resolving does not override an explicit assigned-to from the URL', async () => {+ router.actions.push(urls.customerAnalyticsAccounts(), {}, { view: { assignedTo: [7] } })+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => {+ userLogic.actions.loadUserSuccess(buildUser({ id: CURRENT_USER_ID }) as unknown as UserType)+ }).toFinishAllListeners()++ expect(logic.values.assignedToFilter).toEqual([7])+ })+ })})describe('sortOrder', () => {diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.tsindex 9507678cffdd..95ce9e6eda13 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts@@ -24,6 +24,7 @@ import {ACCOUNTS_METRICS_DATA_NODE_KEY,CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,} from '../../constants'+import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'import {ACCOUNTS_HOGQL_DEFAULT_SELECT,ACCOUNTS_NAME_COLUMN,@@ -177,6 +178,8 @@ export const accountsLogic = kea<accountsLogicType>([['selectColumns', 'visibleColumnNames'],accountsOverviewTilesLogic,['metrics as overviewMetrics', 'tileFilter'],+ customerAnalyticsSceneLogic,+ ['mineOnly'],],actions: [accountsColumnConfigLogic,@@ -185,6 +188,10 @@ export const accountsLogic = kea<accountsLogicType>([['setTileFilter'],accountsExpansionLogic,['openAccountTab'],+ customerAnalyticsSceneLogic,+ ['setMineOnly'],+ userLogic,+ ['loadUserSuccess'],],})),actions({@@ -508,6 +515,25 @@ export const accountsLogic = kea<accountsLogicType>([if (value.length > 0 && values.allRolesUnassigned) {actions.setAllRolesUnassigned(false)}+ // Keep the shared "mine only" toggle in step with the assigned-to filter+ // (set via the "My accounts" shortcut or the assigned-to picker) so+ // switching to the Notes tab reflects the same choice.+ actions.setMineOnly(values.assignedToCurrentUser)+ },+ // The "My accounts" restore needs the current user's id. On a fresh page load this+ // logic can mount before userLogic resolves the user (currentUserId still null during+ // URL restore), so the persisted choice can't be applied then. Re-apply it once the+ // user arrives — only when the URL carried no explicit assignment and nothing else has+ // set the filter, so a shared link or an explicit pick always wins.+ loadUserSuccess: () => {+ if (+ values.mineOnly &&+ values.currentUserId !== null &&+ !values.assignedToFilter.length &&+ !values.allRolesUnassigned+ ) {+ actions.setAssignedToFilter([values.currentUserId])+ }},toggleSort: ({ column }) => {const current = values.sortOrder@@ -693,8 +719,21 @@ export const accountsLogic = kea<accountsLogicType>([// 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)) {+ // 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)}diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.tsindex 58efa8eda596..3a0788cd7ac0 100644--- a/products/customer_analytics/frontend/components/Accounts/constants.ts+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts@@ -56,4 +56,4 @@ export const AccountsEvents = {NotesTabAccountClicked: 'customer analytics notes tab account clicked',} as const-export type NotesTabFilterType = 'created_by' | 'account' | 'my_notes'+export type NotesTabFilterType = 'created_by' | 'account' | 'my_notes' | 'my_accounts'diff --git a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.tsindex f6de97a614cc..6ef978acaa66 100644--- a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts+++ b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts@@ -101,6 +101,10 @@ export const customerAnalyticsSceneLogic = kea<customerAnalyticsSceneLogicType>(setBusinessType: (businessType: BusinessType) => ({ businessType }),setSelectedGroupType: (selectedGroupType: number) => ({ selectedGroupType }),setFilterTestAccounts: (filterTestAccounts: boolean) => ({ filterTestAccounts }),+ // Shared "My accounts" (assigned-to-me) toggle backing the checkbox on both the+ // Accounts and Notes tabs. Held here (not per-tab) so the choice persists as the+ // user switches between them.+ setMineOnly: (mineOnly: boolean) => ({ mineOnly }),}),reducers(() => ({dateFilter: [@@ -135,6 +139,13 @@ export const customerAnalyticsSceneLogic = kea<customerAnalyticsSceneLogicType>(setFilterTestAccounts: (_, { filterTestAccounts }) => filterTestAccounts,},],+ mineOnly: [+ false,+ persistConfig,+ {+ setMineOnly: (_, { mineOnly }) => mineOnly,+ },+ ],})),selectors({activeTab: [diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 8e90149e1c97..d9f3a3d78389 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -813,6 +813,10 @@ export type AccountNotesListParams = {* Only return notes linked to this account.*/account_id?: string+ /**+ * Only return notes on accounts assigned to these user IDs (the account's CSM or account executive; repeat the param per user).+ */+ assigned_to?: number[]/*** Only return notes created by these user IDs (repeat the param per user).*/diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 62644e4fce6d..bc5cc4597332 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -61391,6 +61391,10 @@ export namespace Schemas {* Only return notes linked to this account.*/account_id?: string;+ /**+ * Only return notes on accounts assigned to these user IDs (the account's CSM or account executive; repeat the param per user).+ */+ assigned_to?: number[];/*** Only return notes created by these user IDs (repeat the param per user).*/