: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(actions): paginate actions list with server-side tag and creator filters (#69028)
Matt Puae81593edd9e4
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 5e67227516b1..bd8f8f6c093d 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2648,7 +2648,7 @@ const api = {async migrate(id: ActionType['id']): Promise<HogFunctionType> {return await new ApiRequest().actionsDetail(id).withAction('migrate').create()},- async list(params?: string): Promise<PaginatedResponse<ActionType>> {+ async list(params?: string): Promise<CountedPaginatedResponse<ActionType>> {return await new ApiRequest().actions().withQueryString(params).get()},async listMatchingPluginConfigs(diff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.pyindex 7fa7e05aefc3..6ed53bec37f8 100644--- a/products/actions/backend/api/action.py+++ b/products/actions/backend/api/action.py@@ -569,6 +569,26 @@ class ActionViewSet(return Nonereturn value if value >= 0 else None+ _ORDERING_WHITELIST = {"name", "created_at", "pinned_at", "created_by"}++ def _ordering_from_request(self, request: request.Request) -> list[str] | None:+ raw = request.query_params.get("ordering")+ if not raw:+ return None+ field = raw.lstrip("-")+ if field not in self._ORDERING_WHITELIST:+ return None+ prefix = "-" if raw.startswith("-") else ""+ # created_by is a FK, so sort by the creator's full name rather than the raw id.+ ordering: list[str]+ if field == "created_by":+ ordering = [f"{prefix}created_by__first_name", f"{prefix}created_by__last_name"]+ else:+ ordering = [f"{prefix}{field}"]+ if field != "name":+ ordering.append("name") # stable tiebreak within equal values+ return ordering+@extend_schema(parameters=[OpenApiParameter(@@ -580,25 +600,65 @@ class ActionViewSet(OpenApiParameter("search", OpenApiTypes.STR, description="Case-insensitive substring match on the action name."),+ OpenApiParameter(+ "created_by",+ OpenApiTypes.STR,+ description="Comma-separated list of creator user ids. Returns only actions created by these users.",+ ),+ OpenApiParameter(+ "tags",+ OpenApiTypes.STR,+ description='JSON-encoded array of tag names, e.g. ["billing","beta"]. Returns actions having any of these tags.',+ ),+ OpenApiParameter(+ "ordering",+ OpenApiTypes.STR,+ description="Field to order by (name, created_at, pinned_at, created_by). Prefix with '-' for descending.",+ ),])def list(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:# :HACKY: we need to override this viewset method until actions support# better pagination in the taxonomic filter and on the actions page.#- # `limit`/`offset`/`search` are opt-in: with no params we still return the- # full, ordered list so the actions page and taxonomic filter keep working- # unchanged. API/MCP consumers can pass them to avoid pulling every action- # at once (a project can have thousands), which otherwise overflows the- # context window of LLM clients calling the `actions-get-all` MCP tool.+ # `limit`/`offset`/`search`/`created_by`/`tags`/`ordering` are opt-in: with+ # no params we still return the full, ordered list so the taxonomic filter+ # and other in-memory consumers of the shared actions list keep working+ # unchanged. The actions page and API/MCP consumers pass them to avoid+ # pulling every action at once (a project can have thousands), which+ # otherwise overflows the context window of LLM clients calling the+ # `actions-get-all` MCP tool.actions = self.filter_queryset(self.get_queryset())search = request.query_params.get("search")if search:actions = actions.filter(name__icontains=search)+ created_by = request.query_params.get("created_by")+ if created_by:+ creator_ids = [int(v) for v in created_by.split(",") if v.strip().isdigit()]+ if creator_ids:+ actions = actions.filter(created_by_id__in=creator_ids)++ tags = request.query_params.get("tags")+ if tags:+ try:+ tags_list = json.loads(tags)+ except (json.JSONDecodeError, TypeError):+ tags_list = None+ if tags_list:+ actions = actions.filter(tagged_items__tag__name__in=tags_list).distinct()++ ordering = self._ordering_from_request(request)+ if ordering:+ actions = actions.order_by(*ordering)+offset = self._parse_non_negative_int(request.query_params.get("offset")) or 0limit = self._parse_non_negative_int(request.query_params.get("limit"))+ # Only pay for a COUNT query when actually paginating. The full-list default+ # (no `limit`) is a hot path shared with the taxonomic filter, so we derive the+ # count from the serialized results there instead of hitting the DB again.+ count = actions.count() if limit is not None else Noneif limit is not None:actions = actions[offset : offset + limit]elif offset:@@ -614,4 +674,7 @@ class ActionViewSet(for a in actions_list:a["reference_count"] = ref_counts.get(a["id"], 0)- return Response({"results": actions_list})+ if count is None:+ count = offset + len(actions_list)++ return Response({"count": count, "results": actions_list})diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.pyindex bc01c04ebf2c..fb3c3ca3e93d 100644--- a/products/actions/backend/api/test/test_action.py+++ b/products/actions/backend/api/test/test_action.py@@ -370,6 +370,60 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual([action["name"] for action in response.json()["results"]], expected_names)+ def test_list_count_reflects_full_filtered_set_not_the_page(self) -> None:+ for name in ["alpha", "beta", "gamma", "delta"]:+ Action.objects.create(team=self.team, name=name)++ response = self.client.get(f"/api/projects/{self.team.id}/actions/?limit=2")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 4)+ self.assertEqual(len(response.json()["results"]), 2)++ def test_listing_actions_filters_by_created_by(self) -> None:+ other = User.objects.create_and_join(self.organization, "[email protected]", "")+ Action.objects.create(team=self.team, name="mine", created_by=self.user)+ Action.objects.create(team=self.team, name="theirs", created_by=other)++ mine = self.client.get(f"/api/projects/{self.team.id}/actions/?created_by={self.user.id}")+ self.assertEqual({a["name"] for a in mine.json()["results"]}, {"mine"})+ self.assertEqual(mine.json()["count"], 1)++ both = self.client.get(f"/api/projects/{self.team.id}/actions/?created_by={self.user.id},{other.id}")+ self.assertEqual({a["name"] for a in both.json()["results"]}, {"mine", "theirs"})++ def test_listing_actions_filters_by_tags(self) -> None:+ # One action carries both filtered tags; the tag join yields a row per matching tag, so+ # without .distinct() it would appear (and count) twice. The untagged action guards that+ # the filter actually excludes non-matches.+ tagged = Action.objects.create(team=self.team, name="tagged action")+ Action.objects.create(team=self.team, name="untagged action")+ for name in ["billing", "beta"]:+ tag = Tag.objects.create(name=name, team_id=self.team.id)+ tagged.tagged_items.create(tag_id=tag.id)++ response = self.client.get(f'/api/projects/{self.team.id}/actions/?tags=["billing","beta"]')+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([a["name"] for a in response.json()["results"]], ["tagged action"])+ self.assertEqual(response.json()["count"], 1)++ @parameterized.expand(+ [+ ("valid_field", "name", ["alpha", "beta", "gamma"]),+ # Non-whitelisted input is ignored rather than passed to order_by (no 500, no injection).+ ("rejected_field", "created_by__password", ["gamma", "alpha", "beta"]),+ ]+ )+ def test_listing_actions_ordering_is_whitelisted(+ self, _name: str, ordering: str, expected_names: list[str]+ ) -> None:+ base = datetime(2021, 1, 1, tzinfo=UTC)+ for index, name in enumerate(["gamma", "alpha", "beta"]):+ Action.objects.create(team=self.team, name=name, last_calculated_at=base - timedelta(minutes=index))++ response = self.client.get(f"/api/projects/{self.team.id}/actions/?ordering={ordering}")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([a["name"] for a in response.json()["results"]], expected_names)+def test_get_tags_returns_list(self):action = Action.objects.create(team=self.team, name="bla")tag = Tag.objects.create(name="random", team_id=self.team.id)diff --git a/products/actions/frontend/components/ActionsTable.tsx b/products/actions/frontend/components/ActionsTable.tsxindex 6448d334ccb4..3c98365671eb 100644--- a/products/actions/frontend/components/ActionsTable.tsx+++ b/products/actions/frontend/components/ActionsTable.tsx@@ -1,11 +1,13 @@import { useActions, useValues } from 'kea'import { IconPin, IconPinFilled } from '@posthog/icons'-import { LemonInput, LemonSegmentedButton } from '@posthog/lemon-ui'+import { LemonInput } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'+import { MemberSelectMultiplePopover } from 'lib/components/MemberSelectMultiplePopover'import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'+import { TagSelect } from 'lib/components/TagSelect'import ViewRecordingsPlaylistButton from 'lib/components/ViewRecordingButton/ViewRecordingsPlaylistButton'import { FEATURE_FLAGS } from 'lib/constants'import { LemonButton } from 'lib/lemon-ui/LemonButton'@@ -15,6 +17,7 @@ import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { LemonTable } from 'lib/lemon-ui/LemonTable'import { createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'+import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'import { LemonTableColumn, LemonTableColumns } from 'lib/lemon-ui/LemonTable/types'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { stripHTTP } from 'lib/utils/url'@@ -22,7 +25,6 @@ import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'-import { actionsModel } from '~/models/actionsModel'import { InsightVizNode, NodeKind, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import {AccessControlLevel,@@ -32,22 +34,24 @@ import {FilterLogicalOperator,} from '~/types'-import { actionsLogic } from '../logics/actionsLogic'+import { ACTIONS_PER_PAGE, actionsLogic } from '../logics/actionsLogic'import { deleteActionWithWarning } from '../utils/deleteAction'import { SCREEN_NAME_MATCHING_LABEL, type ScreenNameMatching, isScreenNameFilter } from '../utils/screenName'import { NewActionButton } from './NewActionButton'export function ActionsTable(): JSX.Element {- // actionsModel is a singleton; params are set on first mount by actionsLogic's connect- const { actionsLoading } = useValues(actionsModel)- const { loadActions, pinAction, unpinAction } = useActions(actionsModel)+ const { actionsList, actionCount, actionsResponseLoading, page, filters, searchTerm, shouldShowEmptyState } =+ useValues(actionsLogic)+ const { setSearchTerm, setFilters, setPage, pinAction, unpinAction, loadActions } = useActions(actionsLogic)const { addProductIntentForCrossSell } = useActions(teamLogic)- const { filterType, searchTerm, actionsFiltered, shouldShowEmptyState } = useValues(actionsLogic)- const { setFilterType, setSearchTerm } = useActions(actionsLogic)const { updateHasSeenProductIntroFor } = useActions(userLogic)const { featureFlags } = useValues(featureFlagLogic)const referenceCountEnabled = !!featureFlags[FEATURE_FLAGS.ACTION_REFERENCE_COUNT]+ const sorting: Sorting | null = filters.ordering+ ? { columnKey: filters.ordering.replace(/^-/, ''), order: filters.ordering.startsWith('-') ? -1 : 1 }+ : null+const tryInInsightsUrl = (action: ActionType): string => {const query: InsightVizNode = {kind: NodeKind.InsightVizNode,@@ -72,9 +76,7 @@ export function ActionsTable(): JSX.Element {width: 0,title: 'Pinned',dataIndex: 'pinned_at',- sorter: (a: ActionType, b: ActionType) =>- (b.pinned_at ? new Date(b.pinned_at).getTime() : 0) -- (a.pinned_at ? new Date(a.pinned_at).getTime() : 0),+ sorter: true,render: function Render(pinned, action) {return (<LemonButton@@ -90,7 +92,7 @@ export function ActionsTable(): JSX.Element {title: 'Name',dataIndex: 'name',width: '25%',- sorter: (a: ActionType, b: ActionType) => (a.name || '').localeCompare(b.name || ''),+ sorter: true,render: function RenderName(_, action: ActionType, index: number): JSX.Element {return (<LemonTableLink@@ -189,11 +191,10 @@ export function ActionsTable(): JSX.Element {{title: 'Used by',dataIndex: 'reference_count',- sorter: (a: ActionType, b: ActionType) => (a.reference_count ?? 0) - (b.reference_count ?? 0),render: function RenderReferenceCount(_, action: ActionType) {const count = action.reference_countif (count === undefined) {- return actionsLoading ? (+ return actionsResponseLoading ? (<LemonSkeleton className="w-12 h-4" />) : (<span className="text-secondary">—</span>@@ -208,8 +209,8 @@ export function ActionsTable(): JSX.Element {} as LemonTableColumn<ActionType, keyof ActionType | undefined>,]: []),- createdByColumn() as LemonTableColumn<ActionType, keyof ActionType | undefined>,- createdAtColumn() as LemonTableColumn<ActionType, keyof ActionType | undefined>,+ { ...createdByColumn(), sorter: true } as LemonTableColumn<ActionType, keyof ActionType | undefined>,+ { ...createdAtColumn(), sorter: true } as LemonTableColumn<ActionType, keyof ActionType | undefined>,{width: 0,render: function RenderActions(_, action) {@@ -299,36 +300,49 @@ export function ActionsTable(): JSX.Element {}mcpSurfaceKey="actions.create"/>- {(shouldShowEmptyState && filterType === 'me') || !shouldShowEmptyState ? (- <div className="flex items-center justify-between gap-2 mb-4">- <LemonInput- type="search"- placeholder="Search for actions"- onChange={setSearchTerm}- value={searchTerm}- />- <LemonSegmentedButton- value={filterType}- onChange={setFilterType}- options={[- { value: 'all', label: 'All actions' },- { value: 'me', label: 'My actions' },- ]}- />- </div>- ) : null}- {(!shouldShowEmptyState || filterType === 'me') && (+ {!shouldShowEmptyState && (<>+ <div className="flex items-center justify-between gap-2 flex-wrap mb-4">+ <LemonInput+ type="search"+ placeholder="Search for actions"+ onChange={setSearchTerm}+ value={searchTerm}+ />+ <div className="flex items-center gap-2 flex-wrap">+ <span>Filter to:</span>+ <TagSelect+ defaultLabel="Any tags"+ value={filters.tags}+ onChange={(tags) => setFilters({ tags })}+ />+ <MemberSelectMultiplePopover+ value={filters.createdBy}+ onChange={(ids) => setFilters({ createdBy: ids })}+ />+ </div>+ </div><LemonTablecolumns={columns}- loading={actionsLoading}+ loading={actionsResponseLoading}rowKey="id"- pagination={{ pageSize: 100 }}data-attr="actions-table"- dataSource={actionsFiltered}- defaultSorting={{- columnKey: 'created_by',- order: -1,+ dataSource={actionsList}+ sorting={sorting}+ onSort={(newSorting) =>+ setFilters({+ ordering: newSorting+ ? `${newSorting.order === -1 ? '-' : ''}${newSorting.columnKey}`+ : '-created_by',+ })+ }+ pagination={{+ controlled: true,+ currentPage: page,+ entryCount: actionCount,+ pageSize: ACTIONS_PER_PAGE,+ onForward: page * ACTIONS_PER_PAGE < actionCount ? () => setPage(page + 1) : undefined,+ onBackward: page > 1 ? () => setPage(page - 1) : undefined,}}emptyState="No results. Create a new action?"/>diff --git a/products/actions/frontend/generated/api.schemas.ts b/products/actions/frontend/generated/api.schemas.tsindex 6083e10502aa..543df5ded03b 100644--- a/products/actions/frontend/generated/api.schemas.ts+++ b/products/actions/frontend/generated/api.schemas.ts@@ -687,6 +687,10 @@ export interface BulkUpdateTagsResponseApi {}export type ActionsListParams = {+ /**+ * Comma-separated list of creator user ids. Returns only actions created by these users.+ */+ created_by?: stringformat?: ActionsListFormat/*** Maximum number of actions to return. Omit to return all.@@ -696,10 +700,18 @@ export type ActionsListParams = {* Number of actions to skip before returning results.*/offset?: number+ /**+ * Field to order by (name, created_at, pinned_at, created_by). Prefix with '-' for descending.+ */+ ordering?: string/*** Case-insensitive substring match on the action name.*/search?: string+ /**+ * JSON-encoded array of tag names, e.g. ["billing","beta"]. Returns actions having any of these tags.+ */+ tags?: string}export type ActionsListFormat = (typeof ActionsListFormat)[keyof typeof ActionsListFormat]diff --git a/products/actions/frontend/logics/actionsLogic.test.ts b/products/actions/frontend/logics/actionsLogic.test.tsindex 98ce50d9af8a..baa68393da1a 100644--- a/products/actions/frontend/logics/actionsLogic.test.ts+++ b/products/actions/frontend/logics/actionsLogic.test.ts@@ -1,94 +1,55 @@import { MOCK_DEFAULT_USER } from 'lib/api.mock'-import { expectLogic } from 'kea-test-utils'-import { useMocks } from '~/mocks/jest'-import { actionsModel } from '~/models/actionsModel'import { initKeaTests } from '~/test/init'-import { ActionType, AppContext, UserBasicType } from '~/types'+import { AppContext } from '~/types'import { actionsLogic } from './actionsLogic'-let actionId = 1-const makeAction = (name: string, overrides: Partial<ActionType> = {}): ActionType => {- actionId += 1- return {- id: actionId,- name,- description: '',- tags: [],- steps: [],- created_by: { uuid: 'USER_UUID' } as UserBasicType,- ...overrides,- } as ActionType-}+const parseParams = (query: string): URLSearchParams => new URLSearchParams(query)describe('actionsLogic', () => {let logic: ReturnType<typeof actionsLogic.build>- // Seed containing one action that matches "mcp" exactly and several whose names have- // m/c/p characters spread across them — close enough to fuzzy-match when Fuse's- // effective edit budget grows. With threshold 0.3, a 3-char query allows 0 errors,- // but a trailing space makes the pattern 4 chars long and allows 1 error, which is- // enough to let names like "Map clicked" or "SMTP delivered" leak in.- const actionsSeed: ActionType[] = [- makeAction('MCP server'),- makeAction('Signed up'),- makeAction('Page viewed'),- makeAction('Checkout completed'),- makeAction('Camp fire started'),- makeAction('Map clicked'),- makeAction('Payment tapped'),- makeAction('SMTP delivered'),- makeAction('NPM published'),- makeAction('Stripe captured'),- makeAction('Upload complete'),- makeAction('Compose message'),- makeAction('Mask applied'),- makeAction('Compute provisioned'),- makeAction('CMP accepted'),- makeAction('Shop checkout'),- makeAction('Signup complete'),- makeAction('Login succeeded'),- makeAction('Logout clicked'),- makeAction('Comment posted'),- ]-- beforeEach(async () => {+ beforeEach(() => {window.POSTHOG_APP_CONTEXT = { current_user: MOCK_DEFAULT_USER } as unknown as AppContextuseMocks({get: {- '/api/projects/:team/actions/': {- count: actionsSeed.length,- next: null,- previous: null,- results: actionsSeed,- },+ '/api/projects/:team/actions/': { count: 0, results: [] },},})initKeaTests()-- actionsModel({ params: 'include_count=1' }).mount()- await expectLogic(actionsModel).toDispatchActions(['loadActionsSuccess'])-logic = actionsLogic()logic.mount()})- it('shows all actions when no search term', () => {- expect(logic.values.actionsFiltered).toHaveLength(actionsSeed.length)+ // apiParams is the contract with the backend list endpoint, so lock the mapping from+ // filter state to query string: wrong tag/creator encoding or offset math breaks filtering.+ it.each([+ ['default page and ordering', () => {}, { limit: '50', offset: '0', ordering: '-created_by' }],+ [+ 'tags as a JSON-encoded array',+ (l: typeof logic) => l.actions.setFilters({ tags: ['billing', 'beta'] }),+ { tags: JSON.stringify(['billing', 'beta']) },+ ],+ [+ 'creator ids as a comma-separated list',+ (l: typeof logic) => l.actions.setFilters({ createdBy: [3, 7] }),+ { created_by: '3,7' },+ ],+ ['page navigation as an offset', (l: typeof logic) => l.actions.setPage(3), { offset: '100' }],+ ])('sends %s', (_name, setup, expected) => {+ setup(logic)+ const params = Object.fromEntries(parseParams(logic.values.apiParams))+ expect(params).toMatchObject(expected)})- it.each([['mcp'], ['mcp '], [' mcp'], [' mcp '], ['mcp\t']])(- 'returns only MCP server when searching for "%s"',- async (term) => {- await expectLogic(logic, () => {- logic.actions.setSearchTerm(term)- }).toMatchValues({- actionsFiltered: [expect.objectContaining({ name: 'MCP server' })],- })- }- )+ it('resets to the first page when a filter changes, so no page shows a stale offset', () => {+ logic.actions.setPage(3)+ logic.actions.setFilters({ tags: ['billing'] })+ expect(logic.values.page).toEqual(1)+ expect(parseParams(logic.values.apiParams).get('offset')).toEqual('0')+ })})diff --git a/products/actions/frontend/logics/actionsLogic.ts b/products/actions/frontend/logics/actionsLogic.tsindex 2182efbde4cc..f92a8acb12c9 100644--- a/products/actions/frontend/logics/actionsLogic.ts+++ b/products/actions/frontend/logics/actionsLogic.ts@@ -1,104 +1,150 @@-import { actions, connect, kea, path, reducers, selectors } from 'kea'-import { subscriptions } from 'kea-subscriptions'+import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { actionToUrl, urlToAction } from 'kea-router'+import api, { CountedPaginatedResponse } from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { createFuse } from 'lib/utils/fuseSearch'+import { objectsEqual } from 'lib/utils/objects'+import { toParams } from 'lib/utils/url'import { DataManagementTab } from 'scenes/data-management/DataManagementScene'import { urls } from 'scenes/urls'-import { userLogic } from 'scenes/userLogic'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'-import { actionsModel } from '~/models/actionsModel'import { ActionType, ActivityScope, Breadcrumb } from '~/types'import type { actionsLogicType } from './actionsLogicType'-export type ActionsFilterType = 'all' | 'me'+export const ACTIONS_PER_PAGE = 50-export const actionsFuse = createFuse<ActionType>([], {- keys: [{ name: 'name', weight: 2 }, 'description', 'tags'],- threshold: 0.3,- ignoreLocation: true,- includeMatches: true,-})+export type ActionsResponse = CountedPaginatedResponse<ActionType>-// Called from actionsLogic's connect() — before dependencies are mounted. We read the flag via-// findMounted() because featureFlagLogic is mounted at app bootstrap, long before the actions scene.-// If it's somehow not mounted yet, we safely fall back to the non-reference-count path.-export const getActionsModelParams = (): string => {- const referenceCountEnabled =- !!featureFlagLogic.findMounted()?.values.featureFlags?.[FEATURE_FLAGS.ACTION_REFERENCE_COUNT]- return referenceCountEnabled ? 'include_count=1&include_reference_count=1' : 'include_count=1'+export interface ActionsFilters {+ createdBy: number[]+ tags: string[]+ ordering: string+}++const DEFAULT_FILTERS: ActionsFilters = {+ createdBy: [],+ tags: [],+ ordering: '-created_by',}export const actionsLogic = kea<actionsLogicType>([path(['products', 'actions', 'actionsLogic']),connect(() => ({- values: [- actionsModel({ params: getActionsModelParams() }),- ['actions', 'actionsLoading'],- userLogic,- ['user'],- featureFlagLogic,- ['featureFlags'],- ],+ values: [featureFlagLogic, ['featureFlags']],})),actions({- setFilterType: (filterType: ActionsFilterType) => ({ filterType }),setSearchTerm: (searchTerm: string) => ({ searchTerm }),+ setFilters: (filters: Partial<ActionsFilters>) => ({ filters }),+ setPage: (page: number) => ({ page }),}),reducers({- filterType: [- 'all' as ActionsFilterType,- { persist: true },- {- setFilterType: (_, { filterType }) => filterType,- },- ],searchTerm: ['',{setSearchTerm: (_, { searchTerm }) => searchTerm,},],+ filters: [+ DEFAULT_FILTERS,+ {+ setFilters: (state, { filters }) => ({ ...state, ...filters }),+ },+ ],+ page: [+ 1,+ {+ setPage: (_, { page }) => page,+ setFilters: () => 1,+ setSearchTerm: () => 1,+ },+ ],}),+ loaders(({ values, actions }) => ({+ actionsResponse: [+ { count: 0, results: [] } as ActionsResponse,+ {+ loadActions: async () => {+ const response = await api.actions.list(values.apiParams)+ return { count: response.count ?? 0, results: response.results ?? [] }+ },+ pinAction: async (action: ActionType) => {+ const updated = await api.actions.update(action.id, {+ name: action.name,+ pinned_at: new Date().toISOString(),+ })+ // Patch the row for instant icon feedback, then reload so server-side+ // ordering (e.g. by pinned_at) reflects the change.+ actions.loadActions()+ return {+ ...values.actionsResponse,+ results: values.actionsResponse.results.map((a) => (a.id === updated.id ? updated : a)),+ }+ },+ unpinAction: async (action: ActionType) => {+ const updated = await api.actions.update(action.id, {+ name: action.name,+ pinned_at: null,+ })+ actions.loadActions()+ return {+ ...values.actionsResponse,+ results: values.actionsResponse.results.map((a) => (a.id === updated.id ? updated : a)),+ }+ },+ },+ ],+ })),selectors({- actionsFiltered: [- (s) => [s.actions, s.filterType, s.searchTerm, s.user],- (actions, filterType, searchTerm, user) => {- let data: ActionType[] = actions- // Trim before handing the query to Fuse: a trailing space inflates the pattern- // length, which raises the effective edit budget (threshold × length) and lets- // unrelated items leak in (e.g. searching "mcp " matches "Map clicked").- const trimmedSearchTerm = searchTerm.trim()- if (trimmedSearchTerm) {- data = actionsFuse.search(trimmedSearchTerm).map((result) => result.item)+ actionsList: [(s) => [s.actionsResponse], (response): ActionType[] => response.results],+ actionCount: [(s) => [s.actionsResponse], (response): number => response.count],+ apiParams: [+ (s) => [s.searchTerm, s.filters, s.page, s.featureFlags],+ (searchTerm, filters, page, featureFlags): string => {+ const params: Record<string, any> = {+ limit: ACTIONS_PER_PAGE,+ offset: (page - 1) * ACTIONS_PER_PAGE,+ ordering: filters.ordering,+ include_count: 1,+ }+ if (searchTerm.trim()) {+ params.search = searchTerm.trim()+ }+ if (filters.createdBy.length > 0) {+ params.created_by = filters.createdBy.join(',')}- if (filterType === 'me') {- data = data.filter((item) => item.created_by?.uuid === user?.uuid)+ if (filters.tags.length > 0) {+ params.tags = JSON.stringify(filters.tags)}- return data+ if (featureFlags[FEATURE_FLAGS.ACTION_REFERENCE_COUNT]) {+ params.include_reference_count = 1+ }+ return toParams(params)},],+ hasActiveFilters: [+ (s) => [s.searchTerm, s.filters],+ (searchTerm, filters): boolean =>+ !!searchTerm.trim() || filters.createdBy.length > 0 || filters.tags.length > 0,+ ],shouldShowEmptyState: [- (s) => [s.actionsFiltered, s.actionsLoading, s.searchTerm],- (actionsFiltered: ActionType[], actionsLoading: boolean, searchTerm: string): boolean => {- return actionsFiltered.length == 0 && !actionsLoading && !searchTerm.length- },+ (s) => [s.actionCount, s.actionsResponseLoading, s.hasActiveFilters],+ (actionCount: number, actionsResponseLoading: boolean, hasActiveFilters: boolean): boolean =>+ actionCount === 0 && !actionsResponseLoading && !hasActiveFilters,],breadcrumbs: [() => [],- (): Breadcrumb[] => {- return [- {- key: DataManagementTab.Actions,- name: 'Actions',- path: urls.actions(),- iconType: 'action',- },- ]- },+ (): Breadcrumb[] => [+ {+ key: DataManagementTab.Actions,+ name: 'Actions',+ path: urls.actions(),+ iconType: 'action',+ },+ ],],[SIDE_PANEL_CONTEXT_KEY]: [() => [],@@ -107,9 +153,41 @@ export const actionsLogic = kea<actionsLogicType>([}),],}),- subscriptions({- actions: (actions) => {- actionsFuse.setCollection(actions)+ listeners(({ actions }) => ({+ setFilters: () => actions.loadActions(),+ setPage: () => actions.loadActions(),+ setSearchTerm: async (_, breakpoint) => {+ await breakpoint(300)+ actions.loadActions()+ },+ })),+ urlToAction(({ actions, values }) => ({+ [urls.actions()]: (_, searchParams) => {+ const urlFilters: ActionsFilters = {+ ...DEFAULT_FILTERS,+ ...(searchParams.ordering !== undefined && { ordering: searchParams.ordering }),+ ...(Array.isArray(searchParams.tags) && { tags: searchParams.tags }),+ ...(Array.isArray(searchParams.created_by) && { createdBy: searchParams.created_by.map(Number) }),+ }+ if (!objectsEqual(values.filters, urlFilters)) {+ actions.setFilters(urlFilters)+ } else if (!values.actionsResponse.results.length && !values.actionsResponseLoading) {+ actions.loadActions()+ }},+ })),+ // Search term and page are intentionally not URL-synced; only the shareable filters are.+ actionToUrl(({ values }) => {+ const buildUrl = (): [string, Record<string, any>] => [+ urls.actions(),+ {+ ...(values.filters.ordering !== DEFAULT_FILTERS.ordering && { ordering: values.filters.ordering }),+ ...(values.filters.tags.length > 0 && { tags: values.filters.tags }),+ ...(values.filters.createdBy.length > 0 && { created_by: values.filters.createdBy }),+ },+ ]+ return {+ setFilters: buildUrl,+ }}),])diff --git a/products/actions/mcp/tools.yaml b/products/actions/mcp/tools.yamlindex 71564bef00f8..299a1dc16a0d 100644--- a/products/actions/mcp/tools.yaml+++ b/products/actions/mcp/tools.yaml@@ -111,9 +111,10 @@ tools:description: >Get actions in the project. Actions are reusable event definitions that can combine multiple triggerconditions (page views, clicks, form submissions) into a single trackable event for use in insights and- funnels. Supports pagination with `limit` and `offset`, and case-insensitive name filtering with `search`.- Projects can have thousands of actions, so pass `limit` (and `search` when looking for a specific action by- name) rather than fetching every action at once.+ funnels. Supports pagination with `limit` and `offset`, case-insensitive name filtering with `search`,+ filtering by creator with `created_by` (comma-separated user ids), filtering by tag with `tags` (a+ JSON-encoded array of tag names), and sorting with `ordering`. Projects can have thousands of actions, so+ pass `limit` plus the relevant filters rather than fetching every action at once.ui_app: action-listactions-references-list:operation: actions_references_listdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 491795ca2e6a..dbf99136325f 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -221,7 +221,7 @@}},"actions-get-all": {- "description": "Get actions in the project. Actions are reusable event definitions that can combine multiple trigger conditions (page views, clicks, form submissions) into a single trackable event for use in insights and funnels. Supports pagination with `limit` and `offset`, and case-insensitive name filtering with `search`. Projects can have thousands of actions, so pass `limit` (and `search` when looking for a specific action by name) rather than fetching every action at once.",+ "description": "Get actions in the project. Actions are reusable event definitions that can combine multiple trigger conditions (page views, clicks, form submissions) into a single trackable event for use in insights and funnels. Supports pagination with `limit` and `offset`, case-insensitive name filtering with `search`, filtering by creator with `created_by` (comma-separated user ids), filtering by tag with `tags` (a JSON-encoded array of tag names), and sorting with `ordering`. Projects can have thousands of actions, so pass `limit` plus the relevant filters rather than fetching every action at once.","category": "Actions","feature": "actions","summary": "Get all actions",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 360a175f05e4..a55ff5866f8f 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -221,7 +221,7 @@}},"actions-get-all": {- "description": "Get actions in the project. Actions are reusable event definitions that can combine multiple trigger conditions (page views, clicks, form submissions) into a single trackable event for use in insights and funnels. Supports pagination with `limit` and `offset`, and case-insensitive name filtering with `search`. Projects can have thousands of actions, so pass `limit` (and `search` when looking for a specific action by name) rather than fetching every action at once.",+ "description": "Get actions in the project. Actions are reusable event definitions that can combine multiple trigger conditions (page views, clicks, form submissions) into a single trackable event for use in insights and funnels. Supports pagination with `limit` and `offset`, case-insensitive name filtering with `search`, filtering by creator with `created_by` (comma-separated user ids), filtering by tag with `tags` (a JSON-encoded array of tag names), and sorting with `ordering`. Projects can have thousands of actions, so pass `limit` plus the relevant filters rather than fetching every action at once.","category": "Actions","feature": "actions","summary": "Get all actions",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex be430f5afbec..832019e1a772 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -62136,6 +62136,10 @@ export namespace Schemas {};export type ActionsListParams = {+ /**+ * Comma-separated list of creator user ids. Returns only actions created by these users.+ */+ created_by?: string;format?: ActionsListFormat;/*** Maximum number of actions to return. Omit to return all.@@ -62145,10 +62149,18 @@ export namespace Schemas {* Number of actions to skip before returning results.*/offset?: number;+ /**+ * Field to order by (name, created_at, pinned_at, created_by). Prefix with '-' for descending.+ */+ ordering?: string;/*** Case-insensitive substring match on the action name.*/search?: string;+ /**+ * JSON-encoded array of tag names, e.g. ["billing","beta"]. Returns actions having any of these tags.+ */+ tags?: string;};export type ActionsListFormat = typeof ActionsListFormat[keyof typeof ActionsListFormat];diff --git a/services/mcp/src/generated/actions/api.ts b/services/mcp/src/generated/actions/api.tsindex 55342ff845a6..d85c299c54eb 100644--- a/services/mcp/src/generated/actions/api.ts+++ b/services/mcp/src/generated/actions/api.ts@@ -17,10 +17,24 @@ export const ActionsListParams = /* @__PURE__ */ zod.object({})export const ActionsListQueryParams = /* @__PURE__ */ zod.object({+ created_by: zod+ .string()+ .optional()+ .describe('Comma-separated list of creator user ids. Returns only actions created by these users.'),format: zod.enum(['csv', 'json']).optional(),limit: zod.number().optional().describe('Maximum number of actions to return. Omit to return all.'),offset: zod.number().optional().describe('Number of actions to skip before returning results.'),+ ordering: zod+ .string()+ .optional()+ .describe("Field to order by (name, created_at, pinned_at, created_by). Prefix with '-' for descending."),search: zod.string().optional().describe('Case-insensitive substring match on the action name.'),+ tags: zod+ .string()+ .optional()+ .describe(+ 'JSON-encoded array of tag names, e.g. ["billing","beta"]. Returns actions having any of these tags.'+ ),})export const ActionsCreateParams = /* @__PURE__ */ zod.object({diff --git a/services/mcp/src/tools/generated/actions.ts b/services/mcp/src/tools/generated/actions.tsindex 7f567ac82eca..eb6cca916925 100644--- a/services/mcp/src/tools/generated/actions.ts+++ b/services/mcp/src/tools/generated/actions.ts@@ -143,9 +143,12 @@ const actionsGetAll = (): ToolBase<typeof ActionsGetAllSchema, WithPostHogUrl<Scmethod: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/actions/`,query: {+ created_by: params.created_by,limit: params.limit,offset: params.offset,+ ordering: params.ordering,search: params.search,+ tags: params.tags,},})return await withPostHogUrl(diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/actions-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/actions-get-all.jsonindex cd0e9e22a7fa..a6cee16f6cf0 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/actions-get-all.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/actions-get-all.json@@ -1,6 +1,10 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "created_by": {+ "description": "Comma-separated list of creator user ids. Returns only actions created by these users.",+ "type": "string"+ },"limit": {"description": "Maximum number of actions to return. Omit to return all.","type": "number"@@ -9,9 +13,17 @@"description": "Number of actions to skip before returning results.","type": "number"},+ "ordering": {+ "description": "Field to order by (name, created_at, pinned_at, created_by). Prefix with '-' for descending.",+ "type": "string"+ },"search": {"description": "Case-insensitive substring match on the action name.","type": "string"+ },+ "tags": {+ "description": "JSON-encoded array of tag names, e.g. [\"billing\",\"beta\"]. Returns actions having any of these tags.",+ "type": "string"}},"type": "object"