Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(business-knowledge): show indexed pages on a url source (#105072)

Alex Vc88535a9b305
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index ea985a3aa3dd..e7d8418694dc 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -72,6 +72,7 @@ const ERROR_FILTER_ALLOW_LIST = [
'updateCoreMemory', // maxSettingsLogic's updateCoreMemoryFailure listener shows its own save-failure toast
'loadSessionEventDeltas', // The experiment watch shelf renders the refusal, or the failure with a retry
'loadLineage', // MetricLineagePanel renders every failure class itself, including the not-ready 404
+ 'loadSourceDocuments', // The knowledge source page renders its own retry banner for the indexed page list
]
/*
diff --git a/products/business_knowledge/backend/api/serializers.py b/products/business_knowledge/backend/api/serializers.py
index cd9ca7382b92..c1cc80fb87cf 100644
--- a/products/business_knowledge/backend/api/serializers.py
+++ b/products/business_knowledge/backend/api/serializers.py
@@ -26,6 +26,7 @@ from ..models import (
EmbeddingStatus,
KnowledgeSource,
RefreshInterval,
+ SafetyVerdict,
SourceType,
)
@@ -447,6 +448,25 @@ class CreateCrawlSourceSerializer(_NameValidationMixin, _UrlValidationMixin, ser
return attrs
+class KnowledgeSourceDocumentSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="Document id.")
+ url = serializers.URLField(
+ read_only=True,
+ allow_blank=True,
+ help_text="Fetched page URL after redirects. Empty for text and file documents.",
+ )
+ title = serializers.CharField(
+ read_only=True,
+ allow_blank=True,
+ help_text="Page title extracted while indexing. Falls back to empty when the page had none.",
+ )
+ safety_verdict = serializers.ChoiceField(
+ choices=SafetyVerdict.choices,
+ read_only=True,
+ help_text="Content-safety verdict. Only `safe` documents are included in search. `unknown` is still waiting on classification.",
+ )
+
+
class KnowledgeDocumentWindowSerializer(serializers.Serializer):
"""
One chunk in a drill-down window over a single knowledge document.
diff --git a/products/business_knowledge/backend/api/views.py b/products/business_knowledge/backend/api/views.py
index 8dd7d8efcfe7..faaa6c29e0b0 100644
--- a/products/business_knowledge/backend/api/views.py
+++ b/products/business_knowledge/backend/api/views.py
@@ -47,6 +47,7 @@ from .serializers import (
KnowledgeDocumentWindowSerializer,
KnowledgeGapSuggestionSerializer,
KnowledgeSearchResultSerializer,
+ KnowledgeSourceDocumentSerializer,
KnowledgeSourceSerializer,
UpdateTextSourceSerializer,
UpdateUrlSourceSerializer,
@@ -372,6 +373,30 @@ class KnowledgeSourceViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
raise exceptions.NotFound()
return Response(KnowledgeSourceSerializer(instance=updated).data)
+ @extend_schema(responses={200: KnowledgeSourceDocumentSerializer(many=True)})
+ @action(
+ detail=True,
+ methods=["get"],
+ url_path="documents",
+ required_scopes=["business_knowledge:read"],
+ )
+ def documents(self, request: Request, pk: str, **kwargs) -> Response:
+ try:
+ source_id = UUID(pk)
+ except (ValueError, DjangoValidationError):
+ raise exceptions.NotFound()
+ documents = logic.list_live_documents_for_source(source_id, self.team_id)
+ if documents is None:
+ raise exceptions.NotFound()
+ page = self.paginate_queryset(documents)
+ serializer = KnowledgeSourceDocumentSerializer(
+ instance=page if page is not None else documents,
+ many=True,
+ )
+ if page is not None:
+ return self.get_paginated_response(serializer.data)
+ return Response(serializer.data)
+
@extend_schema(responses={200: {"type": "object", "properties": {"text": {"type": "string"}}}})
@action(detail=True, methods=["get"], url_path="text")
def text(self, request: Request, pk: str, **kwargs) -> Response:
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index caafd171cb3a..3908ad896e8e 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -580,6 +580,21 @@ def get_for_team(source_id: UUID, team_id: int) -> KnowledgeSource | None:
return None
+@with_team_scope(canonical=True)
+def list_live_documents_for_source(source_id: UUID, team_id: int) -> list[KnowledgeDocument] | None:
+ if not KnowledgeSource.objects.filter(id=source_id, team_id=team_id).exists():
+ return None
+ return list(
+ KnowledgeDocument.objects.filter(
+ team_id=team_id,
+ source_id=source_id,
+ tombstoned_at__isnull=True,
+ )
+ .only("id", "url", "title", "safety_verdict")
+ .order_by("url", "id")
+ )
+
+
@with_team_scope(canonical=True)
def get_source_text_for_team(source_id: UUID, team_id: int) -> str | None:
"""Return concatenated document text for the source editor."""
diff --git a/products/business_knowledge/backend/tests/test_api.py b/products/business_knowledge/backend/tests/test_api.py
index 56a84b181dc3..6d72619755f4 100644
--- a/products/business_knowledge/backend/tests/test_api.py
+++ b/products/business_knowledge/backend/tests/test_api.py
@@ -359,6 +359,76 @@ class TestKnowledgeSourceAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
+ def test_lists_live_indexed_urls(self, _ff) -> None:
+ from posthog.models.team import Team
+
+ source = KnowledgeSource.objects.unscoped().create(
+ team=self.team,
+ name="Docs",
+ source_type="url",
+ status="ready",
+ source_url="https://docs.example.com",
+ )
+ KnowledgeDocument.objects.unscoped().create(
+ team=self.team,
+ source=source,
+ stable_id="https://docs.example.com/b",
+ title="Beta",
+ content="secret page body",
+ url="https://docs.example.com/b",
+ safety_verdict=SafetyVerdict.SAFE,
+ )
+ KnowledgeDocument.objects.unscoped().create(
+ team=self.team,
+ source=source,
+ stable_id="https://docs.example.com/a",
+ title="Alpha",
+ content="another secret body",
+ url="https://docs.example.com/a",
+ safety_verdict=SafetyVerdict.UNKNOWN,
+ )
+ KnowledgeDocument.objects.unscoped().create(
+ team=self.team,
+ source=source,
+ stable_id="https://docs.example.com/gone",
+ title="Gone",
+ content="removed page",
+ url="https://docs.example.com/gone",
+ safety_verdict=SafetyVerdict.SAFE,
+ tombstoned_at=timezone.now(),
+ )
+ other_team = Team.objects.create_with_data(
+ organization=self.organization, initiating_user=self.user, name="Other"
+ )
+ other_source = KnowledgeSource.objects.unscoped().create(
+ team=other_team,
+ name="Theirs",
+ source_type="url",
+ status="ready",
+ source_url="https://other.example.com",
+ )
+ KnowledgeDocument.objects.unscoped().create(
+ team=other_team,
+ source=other_source,
+ stable_id="https://other.example.com/secret",
+ title="Secret",
+ content="other team",
+ url="https://other.example.com/secret",
+ )
+
+ response = self.client.get(f"{self.url}{source.id}/documents/?limit=500")
+ assert response.status_code == status.HTTP_200_OK, response.content
+ rows = response.json()["results"]
+ assert [row["url"] for row in rows] == [
+ "https://docs.example.com/a",
+ "https://docs.example.com/b",
+ ]
+ assert rows[0]["title"] == "Alpha"
+ assert rows[0]["safety_verdict"] == "unknown"
+ assert "content" not in rows[0]
+ assert self.client.get(f"{self.url}{other_source.id}/documents/").status_code == status.HTTP_404_NOT_FOUND
+ assert self.client.get(f"{self.url}not-a-uuid/documents/").status_code == status.HTTP_404_NOT_FOUND
+
@patch("posthoganalytics.feature_enabled", return_value=True)
class TestEmbeddingStatusAPI(APIBaseTest):
diff --git a/products/business_knowledge/frontend/api.ts b/products/business_knowledge/frontend/api.ts
index 3c19cf91462a..11f149c2f62d 100644
--- a/products/business_knowledge/frontend/api.ts
+++ b/products/business_knowledge/frontend/api.ts
@@ -4,6 +4,7 @@ import { apiMutator } from '../../../frontend/src/lib/api-orval-mutator'
import {
businessKnowledgeSourcesCreate,
businessKnowledgeSourcesDestroy,
+ businessKnowledgeSourcesDocumentsList,
businessKnowledgeSourcesList,
businessKnowledgeSourcesPartialUpdate,
businessKnowledgeSourcesRefreshCreate,
@@ -16,6 +17,7 @@ import type {
BusinessKnowledgeSourcesListSourceType,
CrawlModeEnumApi,
KnowledgeSourceApi,
+ KnowledgeSourceDocumentApi,
} from './generated/api.schemas'
export type { KnowledgeSourceApi as KnowledgeSourceDTOApi }
@@ -78,6 +80,12 @@ export async function getSource(id: string): Promise<KnowledgeSourceApi> {
return await businessKnowledgeSourcesRetrieve(String(getCurrentTeamId()), id)
}
+export async function getSourceDocuments(id: string): Promise<KnowledgeSourceDocumentApi[]> {
+ // 500 matches the crawl cap (MAX_URLS_PER_SOURCE), so one page is the full set.
+ const response = await businessKnowledgeSourcesDocumentsList(String(getCurrentTeamId()), id, { limit: 500 })
+ return response.results
+}
+
export async function getSourceText(id: string): Promise<{ id: string; text: string }> {
const response = await businessKnowledgeSourcesTextRetrieve(String(getCurrentTeamId()), id)
return { id, text: response.text ?? '' }
diff --git a/products/business_knowledge/frontend/generated/api.schemas.ts b/products/business_knowledge/frontend/generated/api.schemas.ts
index ee9a963406f8..cf6de5315491 100644
--- a/products/business_knowledge/frontend/generated/api.schemas.ts
+++ b/products/business_knowledge/frontend/generated/api.schemas.ts
@@ -296,6 +296,43 @@ export interface PatchedUpdateTextSourceApi {
always_include?: boolean
}
+/**
+ * * `unknown` - Unknown
+ * * `safe` - Safe
+ * * `unsafe` - Unsafe
+ */
+export type SafetyVerdictEnumApi = (typeof SafetyVerdictEnumApi)[keyof typeof SafetyVerdictEnumApi]
+
+export const SafetyVerdictEnumApi = {
+ Unknown: 'unknown',
+ Safe: 'safe',
+ Unsafe: 'unsafe',
+} as const
+
+export interface KnowledgeSourceDocumentApi {
+ /** Document id. */
+ readonly id: string
+ /** Fetched page URL after redirects. Empty for text and file documents. */
+ readonly url: string
+ /** Page title extracted while indexing. Falls back to empty when the page had none. */
+ readonly title: string
+ /** Content-safety verdict. Only `safe` documents are included in search. `unknown` is still waiting on classification.
+ *
+ * * `unknown` - Unknown
+ * * `safe` - Safe
+ * * `unsafe` - Unsafe */
+ readonly safety_verdict: SafetyVerdictEnumApi
+}
+
+export interface PaginatedKnowledgeSourceDocumentListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: KnowledgeSourceDocumentApi[]
+}
+
export type BusinessKnowledgeDocumentsWindowListParams = {
/**
* Zero-based chunk ordinal to center the window on (from a search result).
@@ -377,6 +414,17 @@ export const BusinessKnowledgeSourcesListSourceType = {
Url: 'url',
} as const
+export type BusinessKnowledgeSourcesDocumentsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type BusinessKnowledgeSourcesTextRetrieve200 = {
text?: string
}
diff --git a/products/business_knowledge/frontend/generated/api.ts b/products/business_knowledge/frontend/generated/api.ts
index 70a15ff0205b..303e74b4eaa1 100644
--- a/products/business_knowledge/frontend/generated/api.ts
+++ b/products/business_knowledge/frontend/generated/api.ts
@@ -13,6 +13,7 @@ import type {
BusinessKnowledgeDocumentsWindowListParams,
BusinessKnowledgeGapSuggestionsListParams,
BusinessKnowledgeSettingsApi,
+ BusinessKnowledgeSourcesDocumentsListParams,
BusinessKnowledgeSourcesListParams,
BusinessKnowledgeSourcesTextRetrieve200,
CreateTextSourceApi,
@@ -24,6 +25,7 @@ import type {
KnowledgeSearchResultApi,
KnowledgeSourceApi,
PaginatedKnowledgeGapSuggestionListApi,
+ PaginatedKnowledgeSourceDocumentListApi,
PaginatedKnowledgeSourceListApi,
PatchedBusinessKnowledgeSettingsUpdateApi,
PatchedUpdateTextSourceApi,
@@ -379,6 +381,41 @@ export const businessKnowledgeSourcesDestroy = async (
})
}
+export const getBusinessKnowledgeSourcesDocumentsListUrl = (
+ projectId: string,
+ id: string,
+ params?: BusinessKnowledgeSourcesDocumentsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/business_knowledge/sources/${id}/documents/?${stringifiedParams}`
+ : `/api/projects/${projectId}/business_knowledge/sources/${id}/documents/`
+}
+
+export const businessKnowledgeSourcesDocumentsList = async (
+ projectId: string,
+ id: string,
+ params?: BusinessKnowledgeSourcesDocumentsListParams,
+ options?: RequestInit
+): Promise<PaginatedKnowledgeSourceDocumentListApi> => {
+ return apiMutator<PaginatedKnowledgeSourceDocumentListApi>(
+ getBusinessKnowledgeSourcesDocumentsListUrl(projectId, id, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
export const getBusinessKnowledgeSourcesRefreshCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/business_knowledge/sources/${id}/refresh/`
}
diff --git a/products/business_knowledge/frontend/scenes/KnowledgeSourceScene.tsx b/products/business_knowledge/frontend/scenes/KnowledgeSourceScene.tsx
index a2e4e6431c12..e85f3dab7383 100644
--- a/products/business_knowledge/frontend/scenes/KnowledgeSourceScene.tsx
+++ b/products/business_knowledge/frontend/scenes/KnowledgeSourceScene.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { IconBook, IconRefresh, IconTrash } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonDialog, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonDialog, LemonSkeleton, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'
import { NotFound } from 'lib/components/NotFound'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
@@ -13,6 +13,7 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { KnowledgeSourceForm } from '../components/KnowledgeSourceForm'
import { StatusTag } from '../components/StatusTag'
+import type { KnowledgeSourceDocumentApi, SafetyVerdictEnumApi } from '../generated/api.schemas'
import { REFRESH_INTERVAL_OPTIONS } from './businessKnowledgeLogic'
import { KnowledgeSourceLogicProps, knowledgeSourceLogic } from './knowledgeSourceLogic'
@@ -23,6 +24,24 @@ export const scene: SceneExport<KnowledgeSourceLogicProps> = {
paramsToProps: ({ params: { id } }) => ({ id }),
}
+function safetyTag(verdict: SafetyVerdictEnumApi): JSX.Element {
+ if (verdict === 'safe') {
+ return <LemonTag type="success">safe</LemonTag>
+ }
+ if (verdict === 'unsafe') {
+ return (
+ <LemonTag type="danger" title="Excluded from search.">
+ unsafe
+ </LemonTag>
+ )
+ }
+ return (
+ <LemonTag type="warning" title="Waiting for the content check. Search skips this page until then.">
+ pending
+ </LemonTag>
+ )
+}
+
export function KnowledgeSourceScene(): JSX.Element {
const isEnabled = useFeatureFlag('PRODUCT_BUSINESS_KNOWLEDGE')
const {
@@ -34,8 +53,11 @@ export function KnowledgeSourceScene(): JSX.Element {
isEditUrlSourceSubmitting,
isRefreshing,
isDeleting,
+ sourceDocuments,
+ sourceDocumentsLoaded,
+ sourceDocumentsFailed,
} = useValues(knowledgeSourceLogic)
- const { loadSource, submitEditSource, submitEditUrlSource, refreshSource, deleteSource } =
+ const { loadSource, loadSourceDocuments, submitEditSource, submitEditUrlSource, refreshSource, deleteSource } =
useActions(knowledgeSourceLogic)
if (!isEnabled) {
@@ -129,6 +151,70 @@ export function KnowledgeSourceScene(): JSX.Element {
}
/>
<KnowledgeSourceForm refreshIntervalOptions={REFRESH_INTERVAL_OPTIONS} />
+ {isUrl && (
+ <div className="max-w-3xl min-w-0 flex flex-col gap-2">
+ <h3 className="text-sm font-semibold m-0">Indexed pages</h3>
+ {sourceDocumentsFailed && (
+ <LemonBanner
+ type="error"
+ action={{ children: 'Try again', onClick: () => loadSourceDocuments() }}
+ >
+ Couldn't load indexed pages.
+ </LemonBanner>
+ )}
+ {!(sourceDocumentsFailed && sourceDocuments.length === 0) && (
+ <LemonTable<KnowledgeSourceDocumentApi>
+ dataSource={sourceDocuments}
+ loading={!sourceDocumentsLoaded}
+ rowKey={(row) => row.id}
+ tableLayout="fixed"
+ nouns={['page', 'pages']}
+ pagination={{ pageSize: 20 }}
+ emptyState={
+ source.status === 'processing'
+ ? 'Pages show up here after indexing finishes.'
+ : 'No pages indexed.'
+ }
+ columns={[
+ {
+ title: 'URL',
+ key: 'url',
+ width: '55%',
+ render: (_, row) =>
+ row.url ? (
+ <Link
+ to={row.url}
+ target="_blank"
+ title={row.url}
+ className="block max-w-full truncate"
+ >
+ {row.url}
+ </Link>
+ ) : (
+ <span className="text-muted">No URL</span>
+ ),
+ },
+ {
+ title: 'Title',
+ key: 'title',
+ width: '30%',
+ render: (_, row) => (
+ <span className="block max-w-full truncate" title={row.title || undefined}>
+ {row.title}
+ </span>
+ ),
+ },
+ {
+ title: 'Content check',
+ key: 'safety_verdict',
+ width: '15%',
+ render: (_, row) => safetyTag(row.safety_verdict),
+ },
+ ]}
+ />
+ )}
+ </div>
+ )}
</SceneContent>
)
}
diff --git a/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.test.ts b/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.test.ts
index a53039afd4de..3d476497ec3f 100644
--- a/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.test.ts
+++ b/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.test.ts
@@ -10,6 +10,7 @@ import { knowledgeSourceLogic } from './knowledgeSourceLogic'
jest.mock('../api', () => ({
getSource: jest.fn(),
getSourceText: jest.fn(),
+ getSourceDocuments: jest.fn(),
updateSource: jest.fn(),
deleteSource: jest.fn(),
refreshSource: jest.fn(),
@@ -65,6 +66,7 @@ describe('knowledgeSourceLogic', () => {
jest.clearAllMocks()
mockedApi.getSource.mockResolvedValue(MOCK_SOURCE)
mockedApi.getSourceText.mockResolvedValue({ id: SOURCE_ID, text: 'Refund within 30 days.' })
+ mockedApi.getSourceDocuments.mockResolvedValue([])
mockedApi.updateSource.mockResolvedValue({ ...MOCK_SOURCE, name: 'Updated policy', chunk_count: 4 })
mockedApi.deleteSource.mockResolvedValue(undefined)
logic = knowledgeSourceLogic({ id: SOURCE_ID })
@@ -110,6 +112,7 @@ describe('knowledgeSourceLogic', () => {
expect(logic.values.editSource.text).toBe('Refund within 60 days.')
expect(pushSpy).not.toHaveBeenCalled()
expect(mockedApi.getSource).toHaveBeenCalled()
+ expect(mockedApi.getSourceDocuments).not.toHaveBeenCalled()
pushSpy.mockRestore()
})
@@ -146,6 +149,29 @@ describe('knowledgeSourceLogic', () => {
}).toFinishAllListeners()
expect(logic.values.editUrlSource.name).toBe('Draft name')
+ expect(mockedApi.getSourceDocuments).toHaveBeenCalledWith(SOURCE_ID)
+ expect(logic.values.sourceDocumentsLoaded).toBe(true)
+ })
+
+ it('keeps the source when the indexed page list fails', async () => {
+ logic.unmount()
+ mockedApi.getSource.mockResolvedValue({
+ ...MOCK_SOURCE,
+ source_type: 'url',
+ status: 'ready',
+ source_url: 'https://docs.example.com',
+ })
+ mockedApi.getSourceDocuments.mockRejectedValue({ status: 500, detail: 'boom' })
+ logic = knowledgeSourceLogic({ id: SOURCE_ID })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({
+ sourceNotFound: false,
+ sourceDocumentsFailed: true,
+ sourceDocumentsLoaded: false,
+ sourceDocuments: [],
+ })
+ expect(logic.values.source?.id).toBe(SOURCE_ID)
})
it('still opens the text form if content fails to load', async () => {
diff --git a/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.ts b/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.ts
index 70b4ae8bab8e..b40ac7d04c82 100644
--- a/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.ts
+++ b/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.ts
@@ -22,9 +22,9 @@ import { urls } from 'scenes/urls'
import type { Breadcrumb } from '~/types'
-import { deleteSource, getSource, getSourceText, refreshSource, updateSource } from '../api'
+import { deleteSource, getSource, getSourceDocuments, getSourceText, refreshSource, updateSource } from '../api'
import type { UpdateSourcePayload } from '../api'
-import type { KnowledgeSourceApi } from '../generated/api.schemas'
+import type { KnowledgeSourceApi, KnowledgeSourceDocumentApi } from '../generated/api.schemas'
import {
DEFAULT_URL_SOURCE_FORM,
type CrawlMode,
@@ -91,6 +91,10 @@ export interface knowledgeSourceLogicValues {
showEditSourceErrors: boolean
showEditUrlSourceErrors: boolean
source: KnowledgeSource | null
+ sourceDocuments: KnowledgeSourceDocumentApi[]
+ sourceDocumentsFailed: boolean
+ sourceDocumentsLoaded: boolean
+ sourceDocumentsLoading: boolean
sourceLoading: boolean
sourceNotFound: boolean
sourceText: {
@@ -110,6 +114,21 @@ export interface knowledgeSourceLogicActions {
value: true
}
loadSource: () => any
+ loadSourceDocuments: (_: void) => void
+ loadSourceDocumentsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSourceDocumentsSuccess: (
+ sourceDocuments: KnowledgeSourceDocumentApi[],
+ payload?: void
+ ) => {
+ sourceDocuments: KnowledgeSourceDocumentApi[]
+ payload?: void
+ }
loadSourceFailure: (
error: string,
errorObject?: any
@@ -290,6 +309,22 @@ export const knowledgeSourceLogic: LogicWrapper<knowledgeSourceLogicType> = kea<
loadSourceTextFailure: () => true,
},
],
+ sourceDocumentsFailed: [
+ false,
+ {
+ loadSourceDocuments: () => false,
+ loadSourceDocumentsSuccess: () => false,
+ loadSourceDocumentsFailure: () => true,
+ },
+ ],
+ // Stays false until the first successful response, so the table does not
+ // render its empty state in the gap before the loader starts.
+ sourceDocumentsLoaded: [
+ false,
+ {
+ loadSourceDocumentsSuccess: () => true,
+ },
+ ],
}),
loaders(({ actions, props }) => ({
source: [
@@ -317,6 +352,17 @@ export const knowledgeSourceLogic: LogicWrapper<knowledgeSourceLogicType> = kea<
},
},
],
+ sourceDocuments: [
+ [] as KnowledgeSourceDocumentApi[],
+ {
+ loadSourceDocuments: async (_: void, breakpoint) => {
+ const documents = await getSourceDocuments(props.id)
+ // A poll can start a second fetch before the first returns.
+ breakpoint()
+ return documents
+ },
+ },
+ ],
})),
forms(({ actions, values, props }) => ({
editSource: {
@@ -415,6 +461,9 @@ export const knowledgeSourceLogic: LogicWrapper<knowledgeSourceLogicType> = kea<
}
cache.formHydrated = true
}
+ if (source.source_type === 'url') {
+ actions.loadSourceDocuments()
+ }
const delayMs = sourcePollDelayMs(source)
if (delayMs === null) {
cache.disposables.dispose('pollProcessing')
diff --git a/products/business_knowledge/mcp/tools.yaml b/products/business_knowledge/mcp/tools.yaml
index 971ff97ce588..96b405980135 100644
--- a/products/business_knowledge/mcp/tools.yaml
+++ b/products/business_knowledge/mcp/tools.yaml
@@ -63,6 +63,9 @@ tools:
business-knowledge-sources-destroy:
operation: business_knowledge_sources_destroy
enabled: false
+ business-knowledge-sources-documents-list:
+ operation: business_knowledge_sources_documents_list
+ enabled: false
business-knowledge-sources-list:
operation: business_knowledge_sources_list
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 399a6b1343b2..6337a5711915 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -53705,6 +53705,35 @@ export namespace Schemas {
readonly always_include: boolean;
}
+ /**
+ * * `unknown` - Unknown
+ * * `safe` - Safe
+ * * `unsafe` - Unsafe
+ */
+ export type SafetyVerdictEnum = typeof SafetyVerdictEnum[keyof typeof SafetyVerdictEnum];
+
+
+ export const SafetyVerdictEnum = {
+ Unknown: 'unknown',
+ Safe: 'safe',
+ Unsafe: 'unsafe',
+ } as const;
+
+ export interface KnowledgeSourceDocument {
+ /** Document id. */
+ readonly id: string;
+ /** Fetched page URL after redirects. Empty for text and file documents. */
+ readonly url: string;
+ /** Page title extracted while indexing. Falls back to empty when the page had none. */
+ readonly title: string;
+ /** Content-safety verdict. Only `safe` documents are included in search. `unknown` is still waiting on classification.
+ *
+ * * `unknown` - Unknown
+ * * `safe` - Safe
+ * * `unsafe` - Unsafe */
+ readonly safety_verdict: SafetyVerdictEnum;
+ }
+
export interface KustomerConversationSignalExtra {
status: string | null;
priority: string | null;
@@ -62550,6 +62579,15 @@ export namespace Schemas {
results: KnowledgeGapSuggestion[];
}
+ export interface PaginatedKnowledgeSourceDocumentList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: KnowledgeSourceDocument[];
+ }
+
export interface PaginatedKnowledgeSourceList {
count: number;
/** @nullable */
@@ -104653,6 +104691,17 @@ export namespace Schemas {
Url: 'url',
} as const;
+ export type BusinessKnowledgeSourcesDocumentsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type BusinessKnowledgeSourcesTextRetrieve200 = {
text?: string;
};