: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(business knowledge): search pagination filters (#100822)
Alex V06e90ce88bb6
diff --git a/products/business_knowledge/backend/api/views.py b/products/business_knowledge/backend/api/views.pyindex 2af1245b87b6..242b60402278 100644--- a/products/business_knowledge/backend/api/views.py+++ b/products/business_knowledge/backend/api/views.py@@ -81,9 +81,35 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:return queryset.filter(team_id=self.team_id)- @extend_schema(responses={200: KnowledgeSourceSerializer(many=True)})+ @extend_schema(+ parameters=[+ OpenApiParameter(+ "search",+ OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Case-insensitive substring match against the source name and URL.",+ ),+ OpenApiParameter(+ "source_type",+ OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ enum=[choice.value for choice in SourceType],+ description="Filter to a single source type (text, url, or file).",+ ),+ ],+ responses={200: KnowledgeSourceSerializer(many=True)},+ )def list(self, request: Request, **kwargs) -> Response:- sources = logic.list_for_team(self.team_id)+ source_type = request.query_params.get("source_type") or None+ if source_type is not None and source_type not in SourceType.values:+ raise exceptions.ValidationError({"source_type": "Must be one of: text, url, file."})+ sources = logic.list_for_team(+ self.team_id,+ search=request.query_params.get("search") or None,+ source_type=source_type,+ )page = self.paginate_queryset(sources)if page is not None:return self.get_paginated_response(KnowledgeSourceSerializer(instance=page, many=True).data)diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.pyindex 573d98748b08..e5aaad594c46 100644--- a/products/business_knowledge/backend/logic.py+++ b/products/business_knowledge/backend/logic.py@@ -510,11 +510,21 @@ def _source_list_annotations() -> dict[str, object]:@with_team_scope(canonical=True)-def list_for_team(team_id: int) -> list[KnowledgeSource]:+def list_for_team(+ team_id: int,+ *,+ search: str | None = None,+ source_type: str | None = None,+) -> list[KnowledgeSource]:# Annotate counts in one round-trip so the serializer doesn't N+1.- return list(- KnowledgeSource.objects.filter(team_id=team_id).annotate(**_source_list_annotations()).order_by("-created_at")- )+ queryset = KnowledgeSource.objects.filter(team_id=team_id)+ if source_type:+ queryset = queryset.filter(source_type=source_type)+ if search:+ term = search.strip()+ if term:+ queryset = queryset.filter(Q(name__icontains=term) | Q(source_url__icontains=term))+ return list(queryset.annotate(**_source_list_annotations()).order_by("-created_at"))@with_team_scope(canonical=True)diff --git a/products/business_knowledge/backend/tests/test_api.py b/products/business_knowledge/backend/tests/test_api.pyindex 6a21ecbee079..d5f79b13fae9 100644--- a/products/business_knowledge/backend/tests/test_api.py+++ b/products/business_knowledge/backend/tests/test_api.py@@ -74,6 +74,47 @@ class TestKnowledgeSourceAPI(APIBaseTest):names = [row["name"] for row in response.json()["results"]]assert names == ["Mine"]+ def test_list_applies_search_and_type_filters(self, _ff) -> None:+ from posthog.models.team import Team++ KnowledgeSource.objects.unscoped().create(team=self.team, name="Alpha docs", source_type="text", status="ready")+ KnowledgeSource.objects.unscoped().create(+ team=self.team,+ name="Beta guide",+ source_type="url",+ status="ready",+ source_url="https://example.com/beta-handbook",+ )+ KnowledgeSource.objects.unscoped().create(+ team=self.team, name="Gamma report", source_type="file", status="ready"+ )+ other_team = Team.objects.create_with_data(+ organization=self.organization, initiating_user=self.user, name="Other"+ )+ KnowledgeSource.objects.unscoped().create(+ team=other_team, name="Alpha secrets", source_type="text", status="ready"+ )++ def names(query: str) -> list[str]:+ resp = self.client.get(f"{self.url}?{query}")+ assert resp.status_code == status.HTTP_200_OK, resp.content+ return sorted(row["name"] for row in resp.json()["results"])++ # Search matches the name case-insensitively and never leaks another team's row.+ assert names("search=alpha") == ["Alpha docs"]+ assert names("search=ALPHA") == ["Alpha docs"]+ # Search also matches source_url, not just the name.+ assert names("search=beta-handbook") == ["Beta guide"]+ # Type filter narrows to a single source_type.+ assert names("source_type=url") == ["Beta guide"]+ # Search and type combine as AND.+ assert names("source_type=file&search=gamma") == ["Gamma report"]+ assert names("source_type=text&search=beta") == []++ def test_list_rejects_unknown_source_type(self, _ff) -> None:+ response = self.client.get(f"{self.url}?source_type=bogus")+ assert response.status_code == status.HTTP_400_BAD_REQUEST+def test_cannot_read_other_team_source_via_id(self, _ff) -> None:from posthog.models.team import Teamdiff --git a/products/business_knowledge/frontend/api.ts b/products/business_knowledge/frontend/api.tsindex bfb4c8227b65..b63049838ad8 100644--- a/products/business_knowledge/frontend/api.ts+++ b/products/business_knowledge/frontend/api.ts@@ -9,7 +9,12 @@ import {businessKnowledgeSourcesRefreshCreate,businessKnowledgeSourcesTextRetrieve,} from './generated/api'-import type { CrawlModeEnumApi, KnowledgeSourceApi } from './generated/api.schemas'+import type {+ BusinessKnowledgeSourcesListParams,+ BusinessKnowledgeSourcesListSourceType,+ CrawlModeEnumApi,+ KnowledgeSourceApi,+} from './generated/api.schemas'export type { KnowledgeSourceApi as KnowledgeSourceDTOApi }@@ -43,8 +48,18 @@ export interface UpdateSourcePayload {always_include?: boolean}-export async function listSources(): Promise<KnowledgeSourceApi[]> {- const response = await businessKnowledgeSourcesList(String(getCurrentTeamId()), { limit: 1000 })+export async function listSources(params?: { search?: string; sourceType?: string }): Promise<KnowledgeSourceApi[]> {+ const search = params?.search?.trim()+ const sourceType =+ params?.sourceType && params.sourceType !== 'all'+ ? (params.sourceType as BusinessKnowledgeSourcesListSourceType)+ : undefined+ const query: BusinessKnowledgeSourcesListParams = {+ limit: 1000,+ ...(search ? { search } : {}),+ ...(sourceType ? { source_type: sourceType } : {}),+ }+ const response = await businessKnowledgeSourcesList(String(getCurrentTeamId()), query)return response.results}diff --git a/products/business_knowledge/frontend/generated/api.schemas.ts b/products/business_knowledge/frontend/generated/api.schemas.tsindex ee04f6672b4f..b69640adc130 100644--- a/products/business_knowledge/frontend/generated/api.schemas.ts+++ b/products/business_knowledge/frontend/generated/api.schemas.ts@@ -344,8 +344,25 @@ export type BusinessKnowledgeSourcesListParams = {* The initial index from which to return the results.*/offset?: number+ /**+ * Case-insensitive substring match against the source name and URL.+ */+ search?: string+ /**+ * Filter to a single source type (text, url, or file).+ */+ source_type?: BusinessKnowledgeSourcesListSourceType}+export type BusinessKnowledgeSourcesListSourceType =+ (typeof BusinessKnowledgeSourcesListSourceType)[keyof typeof BusinessKnowledgeSourcesListSourceType]++export const BusinessKnowledgeSourcesListSourceType = {+ File: 'file',+ Text: 'text',+ Url: 'url',+} as const+export type BusinessKnowledgeSourcesTextRetrieve200 = {text?: string}diff --git a/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsxindex 5df0082a5102..93d00952bf28 100644--- a/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx+++ b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { IconBook, IconPencil, IconPlusSmall, IconRefresh, IconTrash } from '@posthog/icons'-import { LemonButton, LemonDialog, LemonTable, LemonTag } from '@posthog/lemon-ui'+import { LemonButton, LemonDialog, LemonInput, LemonSelect, LemonTable, LemonTag } from '@posthog/lemon-ui'import { NotFound } from 'lib/components/NotFound'import { TZLabel } from 'lib/components/TZLabel'@@ -30,8 +30,10 @@ export const scene: SceneExport = {export function BusinessKnowledgeScene(): JSX.Element {const isEnabled = useFeatureFlag('PRODUCT_BUSINESS_KNOWLEDGE')- const { sources, sourcesLoading, readyCount, totalChunks, refreshingIds } = useValues(businessKnowledgeLogic)- const { openCreateModal, openEditModal, deleteSource, refreshSource } = useActions(businessKnowledgeLogic)+ const { sources, sourcesLoading, readyCount, totalChunks, refreshingIds, searchTerm, sourceTypeFilter } =+ useValues(businessKnowledgeLogic)+ const { openCreateModal, openEditModal, deleteSource, refreshSource, setSearchTerm, setSourceTypeFilter } =+ useActions(businessKnowledgeLogic)if (!isEnabled) {return <NotFound object="Business knowledge" caption="This feature is not enabled for your project." />@@ -57,9 +59,30 @@ export function BusinessKnowledgeScene(): JSX.Element {<span>{totalChunks.toLocaleString()} chunks indexed</span></div>+ <div className="flex gap-2 items-center mb-2">+ <LemonInput+ type="search"+ placeholder="Search by name or URL"+ value={searchTerm}+ onChange={setSearchTerm}+ className="max-w-80"+ />+ <LemonSelect+ value={sourceTypeFilter}+ onChange={setSourceTypeFilter}+ options={[+ { value: 'all', label: 'All types' },+ { value: 'text', label: 'Text' },+ { value: 'url', label: 'URL' },+ { value: 'file', label: 'File' },+ ]}+ />+ </div>+<LemonTable<KnowledgeSource>dataSource={sources}loading={sourcesLoading}+ pagination={{ pageSize: 20 }}rowKey={(row) => row.id}onRow={(row) => ({onClick: () => openEditModal(row),@@ -151,7 +174,11 @@ export function BusinessKnowledgeScene(): JSX.Element {),},]}- emptyState="No knowledge sources yet. Click 'Add source' to index your first."+ emptyState={+ searchTerm || sourceTypeFilter !== 'all'+ ? 'No sources match your search or filter.'+ : "No knowledge sources yet. Click 'Add source' to index your first."+ }/><CreateKnowledgeSourceModal refreshIntervalOptions={REFRESH_INTERVAL_OPTIONS} />diff --git a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.tsindex d29d6e1fab95..203308990fa1 100644--- a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts+++ b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts@@ -20,6 +20,7 @@ import type { KnowledgeSourceApi } from '../generated/api.schemas'export type KnowledgeSource = KnowledgeSourceApiexport type CrawlMode = 'single' | 'sitemap' | 'same_origin' | 'github_repo'+export type SourceTypeFilter = 'all' | 'text' | 'url' | 'file'export interface TextSourceFormValues {name: string@@ -106,6 +107,26 @@ function splitGlobs(raw: string): string[] {.filter(Boolean)}+function editUrlSourceValuesFromSource(source: KnowledgeSource): UrlSourceFormValues {+ const cfg = (source.crawl_config || {}) as {+ include_globs?: string[]+ exclude_globs?: string[]+ max_pages?: number+ max_depth?: number+ }+ return {+ name: source.name,+ url: source.source_url,+ crawl_mode: (source.crawl_mode || 'single') as CrawlMode,+ include_globs: (cfg.include_globs || []).join('\n'),+ exclude_globs: (cfg.exclude_globs || []).join('\n'),+ max_pages: cfg.max_pages ?? 50,+ max_depth: cfg.max_depth ?? 2,+ refresh_interval: (source.refresh_interval || 'manual') as RefreshIntervalValue,+ always_include: source.always_include ?? false,+ }+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface businessKnowledgeLogicValues {createTab: CreateTab@@ -156,11 +177,13 @@ export interface businessKnowledgeLogicValues {isUrlSourceValid: booleanreadyCount: numberrefreshingIds: string[]+ searchTerm: stringshowEditSourceErrors: booleanshowEditUrlSourceErrors: booleanshowFileSourceErrors: booleanshowTextSourceErrors: booleanshowUrlSourceErrors: boolean+ sourceTypeFilter: SourceTypeFiltersources: KnowledgeSource[]sourcesLoading: booleantextSource: TextSourceFormValues@@ -222,7 +245,7 @@ export interface businessKnowledgeLogicActions {id: string}}- loadSources: () => any+ loadSources: (_: void) => voidloadSourcesFailure: (error: string,errorObject?: any@@ -232,10 +255,10 @@ export interface businessKnowledgeLogicActions {}loadSourcesSuccess: (sources: KnowledgeSourceApi[],- payload?: any+ payload?: void) => {sources: KnowledgeSourceApi[]- payload?: any+ payload?: void}openCreateModal: () => {value: true@@ -369,6 +392,12 @@ export interface businessKnowledgeLogicActions {setFileSourceValues: (values: DeepPartial<FileSourceFormValues>) => {values: DeepPartial<FileSourceFormValues>}+ setSearchTerm: (searchTerm: string) => {+ searchTerm: string+ }+ setSourceTypeFilter: (sourceTypeFilter: SourceTypeFilter) => {+ sourceTypeFilter: SourceTypeFilter+ }setTextSourceManualErrors: (errors: Record<string, any>) => {errors: Record<string, any>}@@ -514,6 +543,8 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([openCreateModal: true,closeCreateModal: true,setCreateTab: (tab: CreateTab) => ({ tab }),+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),+ setSourceTypeFilter: (sourceTypeFilter: SourceTypeFilter) => ({ sourceTypeFilter }),openEditModal: (source: KnowledgeSource) => ({ source }),closeEditModal: true,deleteSource: (id: string) => ({ id }),@@ -549,13 +580,32 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([refreshSourceDone: (state, { id }) => state.filter((x) => x !== id),},],+ searchTerm: [+ '',+ {+ setSearchTerm: (_, { searchTerm }) => searchTerm,+ },+ ],+ sourceTypeFilter: [+ 'all' as SourceTypeFilter,+ {+ setSourceTypeFilter: (_, { sourceTypeFilter }) => sourceTypeFilter,+ },+ ],}),loaders(({ values }) => ({sources: [[] as KnowledgeSource[],{- loadSources: async () => {- return await listSources()+ loadSources: async (_: void, breakpoint) => {+ const sources = await listSources({+ search: values.searchTerm,+ sourceType: values.sourceTypeFilter,+ })+ // Drop a response a newer request has already superseded, so a+ // slow-then-fast search/filter can't land out of order.+ breakpoint()+ return sources},removeSourceFromList: ({ id }: { id: string }) => values.sources.filter((s) => s.id !== id),replaceSourceInList: ({ source }: { source: KnowledgeSource }) =>@@ -708,6 +758,11 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([: `"${updated.name}" renamed`lemonToast.success(msg)actions.replaceSourceInList({ source: updated })+ // A rename can push the row out of (or into) the active+ // server-side filter, so re-fetch to reapply it.+ if (values.searchTerm || values.sourceTypeFilter !== 'all') {+ actions.loadSources()+ }actions.closeEditModal()actions.resetEditSource()actions.resetEditingSourceText()@@ -757,6 +812,11 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([const updated = await updateSource(current.id, payload)lemonToast.success(`"${updated.name}" updated`)actions.replaceSourceInList({ source: updated })+ // A rename or URL change can push the row out of (or into)+ // the active server-side filter, so re-fetch to reapply it.+ if (values.searchTerm || values.sourceTypeFilter !== 'all') {+ actions.loadSources()+ }actions.closeEditModal()actions.resetEditUrlSource()} catch (error: any) {@@ -772,6 +832,13 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([},})),listeners(({ actions, values, cache }) => ({+ setSearchTerm: async (_, breakpoint) => {+ await breakpoint(300)+ actions.loadSources()+ },+ setSourceTypeFilter: () => {+ actions.loadSources()+ },loadSourcesSuccess: ({ sources }) => {// URL ingestion runs in the background — poll while anything is still// processing so the row flips to ready (or error) without a manual reload.@@ -816,32 +883,16 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([},openEditModal: ({ source }) => {if (source.source_type === 'url') {- const cfg = (source.crawl_config || {}) as {- include_globs?: string[]- exclude_globs?: string[]- max_pages?: number- max_depth?: number- }- actions.setEditUrlSourceValues({- name: source.name,- url: source.source_url,- crawl_mode: (source.crawl_mode || 'single') as CrawlMode,- include_globs: (cfg.include_globs || []).join('\n'),- exclude_globs: (cfg.exclude_globs || []).join('\n'),- max_pages: cfg.max_pages ?? 50,- max_depth: cfg.max_depth ?? 2,- refresh_interval: (source.refresh_interval || 'manual') as RefreshIntervalValue,- always_include: source.always_include ?? false,- })- } else {- actions.setEditSourceValues({- name: source.name,- text: '',- always_include: source.always_include ?? false,- })- if (source.source_type === 'text') {- actions.loadEditingSourceText({ id: source.id })- }+ actions.setEditUrlSourceValues(editUrlSourceValuesFromSource(source))+ return+ }+ actions.setEditSourceValues({+ name: source.name,+ text: '',+ always_include: source.always_include ?? false,+ })+ if (source.source_type === 'text') {+ actions.loadEditingSourceText({ id: source.id })}},loadEditingSourceTextSuccess: ({ editingSourceText }) => {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6226f53622dd..c89fdee76eff 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -96222,8 +96222,25 @@ export namespace Schemas {* The initial index from which to return the results.*/offset?: number;+ /**+ * Case-insensitive substring match against the source name and URL.+ */+ search?: string;+ /**+ * Filter to a single source type (text, url, or file).+ */+ source_type?: BusinessKnowledgeSourcesListSourceType;};+ export type BusinessKnowledgeSourcesListSourceType = typeof BusinessKnowledgeSourcesListSourceType[keyof typeof BusinessKnowledgeSourcesListSourceType];+++ export const BusinessKnowledgeSourcesListSourceType = {+ File: 'file',+ Text: 'text',+ Url: 'url',+ } as const;+export type BusinessKnowledgeSourcesTextRetrieve200 = {text?: string;};diff --git a/services/mcp/src/generated/business_knowledge/api.ts b/services/mcp/src/generated/business_knowledge/api.tsindex 767a6ecd4809..c2dc8f31bd4f 100644--- a/services/mcp/src/generated/business_knowledge/api.ts+++ b/services/mcp/src/generated/business_knowledge/api.ts@@ -69,6 +69,11 @@ export const BusinessKnowledgeSourcesListParams = () => zod.object({export const BusinessKnowledgeSourcesListQueryParams = () => zod.object({limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),+ search: zod.string().optional().describe('Case-insensitive substring match against the source name and URL.'),+ source_type: zod+ .enum(['file', 'text', 'url'])+ .optional()+ .describe('Filter to a single source type (text, url, or file).'),})export const BusinessKnowledgeSourcesCreateParams = () => zod.object({diff --git a/services/mcp/src/tools/generated/business_knowledge.ts b/services/mcp/src/tools/generated/business_knowledge.tsindex 72d25fb0817e..458501a14caf 100644--- a/services/mcp/src/tools/generated/business_knowledge.ts+++ b/services/mcp/src/tools/generated/business_knowledge.ts@@ -85,6 +85,8 @@ const businessKnowledgeSourcesList = (): ToolBase<query: {limit: params.limit,offset: params.offset,+ search: params.search,+ source_type: params.source_type,},})const filtered = {