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): open each source on its own page (#102244)

Alex V3ca848d10772
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5e67d459b30c..dac9451fa6d5 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7025,17 +7025,17 @@ snapshots:
scenes-app-batchexports--runs-with-data--light:
hash: v1.k794b7964.4c1646577dc53efffd814b1a2e723f9da6b10d3641e979f48c5d0447859e2348.fkHuUw1l_9c3rJKSi467jx-6Nv81nNp-PjeRmsgU7l0
scenes-app-businessknowledge-knowledgesourcenamecell--learned-from-ticket--dark:
- hash: v1.k794b7964.b85ff3c1336311296a1d94a7784c30be0d6b69412adc433a9e4a65a88c07c51f.ihKyy57z21faDj1Sanj1miO6VVX-2No3bMntC3FYpUg
+ hash: v1.k794b7964.a46d4d71b7c29d97eb5e21a51ea6f3e094057423f4ba8d4056478f8dee07511d.Mz_2JgSjfjfty0b5EX1bU9eBPi9g1Ijhfs0Sl6L9MLM
scenes-app-businessknowledge-knowledgesourcenamecell--learned-from-ticket--light:
- hash: v1.k794b7964.79323f662ac797dc4025d4886d2f57a87e5673311280be0025fc276f0d15e24d.jCm7pNsUVBuuV45MaHMzl15aW9D0wIh2Ss-oAqE6rKM
+ hash: v1.k794b7964.2d167186b0b227d35f024e909a392bd9604579f2fd017aa4d6ac47ddee2ac1c1.lh9z25M6g1N5ZONp3-yYwpYE9GHJlLb2t5UQsdVFWSI
scenes-app-businessknowledge-knowledgesourcenamecell--learned-long-name--dark:
- hash: v1.k794b7964.7e7cf31370739d0225e424bef6b4568c3bc2ccc7e6d6c1621c133f200cc0a87b.iji1MmJcav9RJL5pcr8Gbci7RDR0JLg-6GEaLJ8TcEQ
+ hash: v1.k794b7964.d95b45472ddb1a932c7b5d87a4127f408c86401438829b68b3c6063b5d8b2832.vFiIcE0mSgmaEOrgc4j-Aw8xdpgRlYhWh4U5LKqc0_g
scenes-app-businessknowledge-knowledgesourcenamecell--learned-long-name--light:
- hash: v1.k794b7964.3c08bb4f1ab96a8adc4cf8705872b9f642af32fc3b922d525be0a4840a8c3d0f.jS5-LXszZhbx3kF69qb4WNpylwlAEOItpmu5s9QAUIM
+ hash: v1.k794b7964.845c73bb0fe4bd1e712c664bcf164f25154607bdaaf7fcb8dfdc2308ed435524.RPh8nm51fU44Ej4Zhjq2OAc04T6P5k3bjvkzugMYm3I
scenes-app-businessknowledge-knowledgesourcenamecell--user-text--dark:
- hash: v1.k794b7964.449cae34f94a0ff5bf52c776b98164dfdbf451483e123b55c047780094867aac.AuvKJ3voVpJKimIOyDDvbgkjkVPVEmiCvbLOTicmM2M
+ hash: v1.k794b7964.6dfdfa963cd528d998f0fec6cad0e97b3d999d584c03513cb02aaebfac0df7b1.p1pRi00v4RXJ6t8fXTtzfgLTTMnU0-efeu_N-yFdeL8
scenes-app-businessknowledge-knowledgesourcenamecell--user-text--light:
- hash: v1.k794b7964.b0fb25c4d63d668d6b84ddb054bf9fe5f853554513c5b1a0b03774fd54b2a47f.Y0HQ6UiYK71WFDcXIGDDQN4h4hothCtCQZIXKrdVirw
+ hash: v1.k794b7964.fba04716b8f344e21fa3bb2ec69e627bd9836ff2161986538ac2b562973b0edc.Xl-YJ8Poqz1nofU4nIyAfnM4GbZZ1YYtbM37mIzZ4w4
scenes-app-customer-analytics-account-detail--default--dark:
hash: v1.k794b7964.32d5329bf4ce6055010743914ec226973cc4d455a70581692f97d8cae13c04f1.4Zd5MpCXYXWDIegWaghLkfmgRx11JTVSpbyCab_3_YU
scenes-app-customer-analytics-account-detail--default--light:
diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsx
index 6d5966c16f41..320940b386a5 100644
--- a/frontend/src/productScenes.tsx
+++ b/frontend/src/productScenes.tsx
@@ -41,6 +41,7 @@ export const productScenes: Record<string, () => Promise<any>> = {
BusinessKnowledge: () => import('../../products/business_knowledge/frontend/scenes/BusinessKnowledgeScene'),
BusinessKnowledgeSettings: () =>
import('../../products/business_knowledge/frontend/scenes/BusinessKnowledgeSettingsScene'),
+ BusinessKnowledgeSource: () => import('../../products/business_knowledge/frontend/scenes/KnowledgeSourceScene'),
Transformations: () => import('../../frontend/src/scenes/data-pipelines/TransformationsScene'),
EventFiltering: () => import('../../frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene'),
CohortsStaffTools: () => import('../../products/cohorts/frontend/staff/CohortsStaffToolsScene'),
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index a107b5139147..12ae6a0c979e 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -99,6 +99,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/data-management/annotations/:id': ['Annotations', 'annotation'],
'/business-knowledge': ['BusinessKnowledge', 'businessKnowledge'],
'/business-knowledge/settings': ['BusinessKnowledgeSettings', 'businessKnowledgeSettings'],
+ '/business-knowledge/:id': ['BusinessKnowledgeSource', 'businessKnowledgeSource'],
'/transformations': ['Transformations', 'transformations'],
'/event-filtering': ['EventFiltering', 'eventFiltering'],
'/feature_flags/staff/cohorts': ['CohortsStaffTools', 'cohortsStaffTools'],
@@ -587,6 +588,12 @@ export const productConfiguration: Record<string, any> = {
'Upload text, public URLs, or files so PostHog AI can understand your business context, vision, and policies.',
},
BusinessKnowledgeSettings: { name: 'Business knowledge settings', projectBased: true, iconType: 'conversations' },
+ BusinessKnowledgeSource: {
+ name: 'Knowledge source',
+ projectBased: true,
+ activityScope: 'KnowledgeSource',
+ iconType: 'conversations',
+ },
Transformations: {
projectBased: true,
name: 'Transformations',
@@ -1154,6 +1161,7 @@ export const productUrls = {
annotation: (id: AnnotationType['id'] | ':id'): string => `/data-management/annotations/${id}`,
businessKnowledge: (): string => '/business-knowledge',
businessKnowledgeSettings: (): string => '/business-knowledge/settings',
+ businessKnowledgeSource: (id: string): string => `/business-knowledge/${id}`,
transformations: (): string => '/transformations',
eventFiltering: (): string => '/event-filtering',
cohort: (id: string | number): string => `/cohorts/${id}`,
@@ -2038,7 +2046,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
iconColor: ['var(--color-product-support-light)'] as FileSystemIconColor,
flag: FEATURE_FLAGS.PRODUCT_BUSINESS_KNOWLEDGE,
sceneKey: 'BusinessKnowledge',
- sceneKeys: ['BusinessKnowledge', 'BusinessKnowledgeSettings'],
+ sceneKeys: ['BusinessKnowledge', 'BusinessKnowledgeSettings', 'BusinessKnowledgeSource'],
},
{
path: 'Clusters',
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index 5a98a1bcd642..992c638b9f6a 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -95,6 +95,7 @@ export enum Scene {
InviteSignup = 'InviteSignup',
BusinessKnowledge = 'BusinessKnowledge',
BusinessKnowledgeSettings = 'BusinessKnowledgeSettings',
+ BusinessKnowledgeSource = 'BusinessKnowledgeSource',
LegacyPlugin = 'LegacyPlugin',
LegalDocuments = 'LegalDocuments',
LegalDocumentNew = 'LegalDocumentNew',
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index e5aaad594c46..9f01adfc09cf 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -537,7 +537,7 @@ def get_for_team(source_id: UUID, team_id: int) -> KnowledgeSource | None:
@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 edit modal."""
+ """Return concatenated document text for the source editor."""
try:
source = KnowledgeSource.objects.only("is_generated", "source_type").get(id=source_id, team_id=team_id)
diff --git a/products/business_knowledge/frontend/api.ts b/products/business_knowledge/frontend/api.ts
index b63049838ad8..4ebfa32a4287 100644
--- a/products/business_knowledge/frontend/api.ts
+++ b/products/business_knowledge/frontend/api.ts
@@ -7,6 +7,7 @@ import {
businessKnowledgeSourcesList,
businessKnowledgeSourcesPartialUpdate,
businessKnowledgeSourcesRefreshCreate,
+ businessKnowledgeSourcesRetrieve,
businessKnowledgeSourcesTextRetrieve,
} from './generated/api'
import type {
@@ -63,6 +64,10 @@ export async function listSources(params?: { search?: string; sourceType?: strin
return response.results
}
+export async function getSource(id: string): Promise<KnowledgeSourceApi> {
+ return await businessKnowledgeSourcesRetrieve(String(getCurrentTeamId()), id)
+}
+
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/components/EditKnowledgeSourceModal.tsx b/products/business_knowledge/frontend/components/EditKnowledgeSourceModal.tsx
deleted file mode 100644
index 30a0ff35bffc..000000000000
--- a/products/business_knowledge/frontend/components/EditKnowledgeSourceModal.tsx
+++ /dev/null
@@ -1,112 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { Form } from 'kea-forms'
-
-import { LemonButton, LemonModal, LemonSelect } from '@posthog/lemon-ui'
-
-import { LemonField } from 'lib/lemon-ui/LemonField'
-import { LemonInput } from 'lib/lemon-ui/LemonInput'
-import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
-import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
-
-import type { RefreshIntervalOption } from '../api'
-import { businessKnowledgeLogic } from '../scenes/businessKnowledgeLogic'
-import { AlwaysIncludeField } from './AlwaysIncludeField'
-import { CrawlConfigFields } from './CrawlConfigFields'
-
-export function EditKnowledgeSourceModal({
- refreshIntervalOptions,
-}: {
- refreshIntervalOptions: RefreshIntervalOption[]
-}): JSX.Element {
- const {
- isEditModalOpen,
- editingSource,
- editingSourceTextLoading,
- isEditSourceSubmitting,
- isEditUrlSourceSubmitting,
- editUrlSource,
- } = useValues(businessKnowledgeLogic)
- const { closeEditModal, submitEditSource, submitEditUrlSource } = useActions(businessKnowledgeLogic)
-
- return (
- <LemonModal
- isOpen={isEditModalOpen}
- onClose={closeEditModal}
- title={editingSource ? `Edit "${editingSource.name}"` : 'Edit knowledge source'}
- footer={
- <>
- <LemonButton onClick={closeEditModal}>Cancel</LemonButton>
- <LemonButton
- type="primary"
- loading={
- editingSource?.source_type === 'url' ? isEditUrlSourceSubmitting : isEditSourceSubmitting
- }
- disabled={editingSource?.source_type === 'text' && editingSourceTextLoading}
- onClick={editingSource?.source_type === 'url' ? submitEditUrlSource : submitEditSource}
- >
- Save
- </LemonButton>
- </>
- }
- >
- {editingSource?.source_type === 'url' ? (
- <Form logic={businessKnowledgeLogic} formKey="editUrlSource" className="flex flex-col gap-2">
- <LemonField name="name" label="Name">
- <LemonInput />
- </LemonField>
- <LemonField name="url" label="URL">
- <LemonInput placeholder="https://docs.example.com" />
- </LemonField>
- <LemonField name="crawl_mode" label="Crawl mode">
- <LemonSelect
- options={[
- { value: 'single', label: 'Single page' },
- { value: 'sitemap', label: 'Sitemap' },
- { value: 'same_origin', label: 'Crawl same origin' },
- ]}
- />
- </LemonField>
- <CrawlConfigFields crawlMode={editUrlSource.crawl_mode} url={editUrlSource.url} />
- <LemonField
- name="refresh_interval"
- label="Auto-refresh"
- info="How often PostHog re-fetches this source in the background. Changing it alone does not trigger an immediate re-crawl."
- >
- <LemonSelect options={refreshIntervalOptions} />
- </LemonField>
- <AlwaysIncludeField />
- <p className="text-xs text-muted">Changing the URL or crawl settings will trigger a re-crawl.</p>
- </Form>
- ) : editingSource?.source_type === 'text' && editingSourceTextLoading ? (
- <div className="flex flex-col gap-2">
- <LemonSkeleton className="h-10" />
- <LemonSkeleton className="h-60" />
- </div>
- ) : (
- <Form logic={businessKnowledgeLogic} formKey="editSource" className="flex flex-col gap-2">
- <LemonField name="name" label="Name">
- <LemonInput />
- </LemonField>
- {editingSource?.source_type === 'text' && (
- <LemonField name="text" label="Content">
- <LemonTextArea minRows={12} />
- </LemonField>
- )}
- {editingSource?.source_type === 'file' && editingSource.original_filename && (
- <p className="text-xs text-muted">
- Uploaded file: {editingSource.original_filename}. To replace the content, delete this source
- and upload a new file.
- </p>
- )}
- {editingSource?.source_type === 'text' && (
- <p className="text-xs text-muted">
- Saving rewrites the chunks for this source. Agents won't see the change mid-conversation
- until they refresh their prompt.
- </p>
- )}
- <AlwaysIncludeField />
- </Form>
- )}
- </LemonModal>
- )
-}
diff --git a/products/business_knowledge/frontend/components/KnowledgeSourceForm.tsx b/products/business_knowledge/frontend/components/KnowledgeSourceForm.tsx
new file mode 100644
index 000000000000..203dc7ad7409
--- /dev/null
+++ b/products/business_knowledge/frontend/components/KnowledgeSourceForm.tsx
@@ -0,0 +1,95 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { LemonBanner, LemonSelect } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
+
+import type { RefreshIntervalOption } from '../api'
+import { knowledgeSourceLogic } from '../scenes/knowledgeSourceLogic'
+import { AlwaysIncludeField } from './AlwaysIncludeField'
+import { CrawlConfigFields } from './CrawlConfigFields'
+
+export function KnowledgeSourceForm({
+ refreshIntervalOptions,
+}: {
+ refreshIntervalOptions: RefreshIntervalOption[]
+}): JSX.Element {
+ const { source, isSourceTextReady, sourceTextFailed, editUrlSource } = useValues(knowledgeSourceLogic)
+ const { loadSourceText } = useActions(knowledgeSourceLogic)
+
+ if (source?.source_type === 'url') {
+ return (
+ <Form logic={knowledgeSourceLogic} formKey="editUrlSource" className="flex flex-col gap-2 max-w-2xl">
+ <LemonField name="name" label="Name">
+ <LemonInput />
+ </LemonField>
+ <LemonField name="url" label="URL">
+ <LemonInput placeholder="https://docs.example.com" />
+ </LemonField>
+ <LemonField name="crawl_mode" label="Crawl mode">
+ <LemonSelect
+ options={[
+ { value: 'single', label: 'Single page' },
+ { value: 'sitemap', label: 'Sitemap' },
+ { value: 'same_origin', label: 'Crawl same origin' },
+ ]}
+ />
+ </LemonField>
+ <CrawlConfigFields crawlMode={editUrlSource.crawl_mode} url={editUrlSource.url} />
+ <LemonField
+ name="refresh_interval"
+ label="Auto-refresh"
+ info="How often PostHog re-fetches this source in the background. Changing it alone does not trigger an immediate re-crawl."
+ >
+ <LemonSelect options={refreshIntervalOptions} />
+ </LemonField>
+ <AlwaysIncludeField />
+ <p className="text-xs text-muted">Changing the URL or crawl settings will trigger a re-crawl.</p>
+ </Form>
+ )
+ }
+
+ if (source?.source_type === 'text' && !isSourceTextReady) {
+ return (
+ <div className="flex flex-col gap-2 max-w-2xl">
+ <LemonSkeleton className="h-10" />
+ <LemonSkeleton className="h-60" />
+ </div>
+ )
+ }
+
+ return (
+ <Form logic={knowledgeSourceLogic} formKey="editSource" className="flex flex-col gap-2 max-w-2xl">
+ {sourceTextFailed && (
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadSourceText }}>
+ Couldn't load this source's content. You can still save the name.
+ </LemonBanner>
+ )}
+ <LemonField name="name" label="Name">
+ <LemonInput />
+ </LemonField>
+ {source?.source_type === 'text' && !sourceTextFailed && (
+ <LemonField name="text" label="Content">
+ <LemonTextArea minRows={12} />
+ </LemonField>
+ )}
+ {source?.source_type === 'file' && source.original_filename && (
+ <p className="text-xs text-muted">
+ Uploaded file: {source.original_filename}. To replace the content, delete this source and upload a
+ new file.
+ </p>
+ )}
+ {source?.source_type === 'text' && !sourceTextFailed && (
+ <p className="text-xs text-muted">
+ Saving rewrites the chunks for this source. Agents won't see the change mid-conversation until they
+ refresh their prompt.
+ </p>
+ )}
+ <AlwaysIncludeField />
+ </Form>
+ )
+}
diff --git a/products/business_knowledge/frontend/components/KnowledgeSourceNameCell.tsx b/products/business_knowledge/frontend/components/KnowledgeSourceNameCell.tsx
index c30ffc91c3d3..715ed9707094 100644
--- a/products/business_knowledge/frontend/components/KnowledgeSourceNameCell.tsx
+++ b/products/business_knowledge/frontend/components/KnowledgeSourceNameCell.tsx
@@ -1,5 +1,7 @@
import { LemonTag, Link } from '@posthog/lemon-ui'
+import { urls } from 'scenes/urls'
+
import { KnowledgeSource } from '../scenes/businessKnowledgeLogic'
function inAppPath(url: string): string {
@@ -17,7 +19,13 @@ export function KnowledgeSourceNameCell({ source }: { source: KnowledgeSource })
return (
<div className="flex flex-col min-w-0 max-w-full">
<span className="flex items-center gap-1 min-w-0">
- <strong className="truncate">{source.name}</strong>
+ <Link
+ to={urls.businessKnowledgeSource(source.id)}
+ className="font-semibold truncate"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {source.name}
+ </Link>
{source.is_generated ? (
<LemonTag
type="highlight"
diff --git a/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.test.tsx b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.test.tsx
index b97542996c3f..4328454e9ef9 100644
--- a/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.test.tsx
+++ b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { cleanup, render, screen } from '@testing-library/react'
import { useActions, useValues } from 'kea'
import { type ReactNode } from 'react'
@@ -13,6 +13,14 @@ jest.mock('kea', () => ({
useActions: jest.fn(),
}))
+jest.mock('kea-router', () => ({
+ ...jest.requireActual('kea-router'),
+ router: {
+ actions: { push: jest.fn() },
+ values: { location: { pathname: '/business-knowledge' }, searchParams: {}, hashParams: {} },
+ },
+}))
+
jest.mock('lib/hooks/useFeatureFlag', () => ({
useFeatureFlag: (): boolean => true,
}))
@@ -33,12 +41,17 @@ jest.mock('../components/CreateKnowledgeSourceModal', () => ({
CreateKnowledgeSourceModal: (): null => null,
}))
-jest.mock('../components/EditKnowledgeSourceModal', () => ({
- EditKnowledgeSourceModal: (): null => null,
-}))
-
jest.mock('./businessKnowledgeLogic', () => ({
businessKnowledgeLogic: {},
+ REFRESH_INTERVAL_OPTIONS: [],
+}))
+
+jest.mock('scenes/urls', () => ({
+ urls: {
+ businessKnowledge: (): string => '/business-knowledge',
+ businessKnowledgeSource: (id: string): string => `/business-knowledge/${id}`,
+ businessKnowledgeSettings: (): string => '/business-knowledge/settings',
+ },
}))
function makeSource(overrides: Partial<KnowledgeSource> = {}): KnowledgeSource {
@@ -75,15 +88,15 @@ function makeSource(overrides: Partial<KnowledgeSource> = {}): KnowledgeSource {
}
describe('BusinessKnowledgeScene', () => {
- const openEditModal = jest.fn()
-
beforeEach(() => {
jest.clearAllMocks()
;(useActions as jest.Mock).mockReturnValue({
openCreateModal: jest.fn(),
- openEditModal,
deleteSource: jest.fn(),
refreshSource: jest.fn(),
+ setSearchTerm: jest.fn(),
+ setSourceTypeFilter: jest.fn(),
+ push: jest.fn(),
})
;(useValues as jest.Mock).mockReturnValue({
sources: [makeSource()],
@@ -91,6 +104,8 @@ describe('BusinessKnowledgeScene', () => {
readyCount: 1,
totalChunks: 3,
refreshingIds: [],
+ searchTerm: '',
+ sourceTypeFilter: 'all',
})
})
@@ -98,20 +113,21 @@ describe('BusinessKnowledgeScene', () => {
cleanup()
})
- it('lets you open the editor for a learned source', () => {
+ it('links the source name to its detail page and keeps the learned ticket link', () => {
render(<BusinessKnowledgeScene />)
+ const source = makeSource()
+ expect(screen.getByText('Refund policy').closest('a')).toHaveAttribute(
+ 'href',
+ `/business-knowledge/${source.id}`
+ )
expect(screen.getByText('Learned from ticket #42')).toBeInTheDocument()
expect(screen.getByText('Learned from ticket #42').closest('a')).toHaveAttribute(
'href',
'/project/1/support/tickets/42'
)
expect(screen.getByText('Learned')).toBeInTheDocument()
- expect(screen.getByLabelText('Edit')).toBeInTheDocument()
+ expect(screen.queryByLabelText('Edit')).not.toBeInTheDocument()
expect(screen.getByLabelText('Delete')).toBeInTheDocument()
-
- fireEvent.click(screen.getByText('Refund policy'))
-
- expect(openEditModal).toHaveBeenCalledWith(expect.objectContaining({ id: makeSource().id }))
})
})
diff --git a/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx
index 93d00952bf28..260cde7a0da0 100644
--- a/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx
+++ b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx
@@ -1,12 +1,15 @@
import { useActions, useValues } from 'kea'
+import { router } from 'kea-router'
-import { IconBook, IconPencil, IconPlusSmall, IconRefresh, IconTrash } from '@posthog/icons'
+import { IconBook, IconPlusSmall, IconRefresh, IconTrash } from '@posthog/icons'
import { LemonButton, LemonDialog, LemonInput, LemonSelect, LemonTable, LemonTag } from '@posthog/lemon-ui'
import { NotFound } from 'lib/components/NotFound'
import { TZLabel } from 'lib/components/TZLabel'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { newInternalTab } from 'lib/utils/newInternalTab'
import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
@@ -14,7 +17,6 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { BusinessKnowledgeTabs } from '../components/BusinessKnowledgeTabs'
import { CreateKnowledgeSourceModal } from '../components/CreateKnowledgeSourceModal'
-import { EditKnowledgeSourceModal } from '../components/EditKnowledgeSourceModal'
import { KnowledgeSourceNameCell } from '../components/KnowledgeSourceNameCell'
import { RefreshStatusCell } from '../components/RefreshStatusCell'
import { StatusTag } from '../components/StatusTag'
@@ -32,8 +34,9 @@ export function BusinessKnowledgeScene(): JSX.Element {
const isEnabled = useFeatureFlag('PRODUCT_BUSINESS_KNOWLEDGE')
const { sources, sourcesLoading, readyCount, totalChunks, refreshingIds, searchTerm, sourceTypeFilter } =
useValues(businessKnowledgeLogic)
- const { openCreateModal, openEditModal, deleteSource, refreshSource, setSearchTerm, setSourceTypeFilter } =
+ const { openCreateModal, deleteSource, refreshSource, setSearchTerm, setSourceTypeFilter } =
useActions(businessKnowledgeLogic)
+ const { push } = useActions(router)
if (!isEnabled) {
return <NotFound object="Business knowledge" caption="This feature is not enabled for your project." />
@@ -84,10 +87,28 @@ export function BusinessKnowledgeScene(): JSX.Element {
loading={sourcesLoading}
pagination={{ pageSize: 20 }}
rowKey={(row) => row.id}
- onRow={(row) => ({
- onClick: () => openEditModal(row),
- style: { cursor: 'pointer' },
- })}
+ onRow={(row) => {
+ const sourceUrl = urls.businessKnowledgeSource(row.id)
+ return {
+ style: { cursor: 'pointer' },
+ onClick: (e: React.MouseEvent) => {
+ if (e.metaKey || e.ctrlKey) {
+ e.preventDefault()
+ e.stopPropagation()
+ newInternalTab(sourceUrl)
+ } else {
+ push(sourceUrl)
+ }
+ },
+ onAuxClick: (e: React.MouseEvent) => {
+ if (e.button === 1) {
+ e.preventDefault()
+ e.stopPropagation()
+ newInternalTab(sourceUrl)
+ }
+ },
+ }
+ }}
columns={[
{
title: 'Name',
@@ -130,7 +151,7 @@ export function BusinessKnowledgeScene(): JSX.Element {
width: 0,
render: (_, row) => (
<div className="flex gap-1 justify-end">
- {row.source_type === 'url' && (
+ {row.source_type === 'url' && !row.is_generated && (
<LemonButton
icon={<IconRefresh />}
size="small"
@@ -142,15 +163,6 @@ export function BusinessKnowledgeScene(): JSX.Element {
}}
/>
)}
- <LemonButton
- icon={<IconPencil />}
- size="small"
- tooltip="Edit"
- onClick={(e) => {
- e.stopPropagation()
- openEditModal(row)
- }}
- />
<LemonButton
icon={<IconTrash />}
status="danger"
@@ -182,7 +194,6 @@ export function BusinessKnowledgeScene(): JSX.Element {
/>
<CreateKnowledgeSourceModal refreshIntervalOptions={REFRESH_INTERVAL_OPTIONS} />
- <EditKnowledgeSourceModal refreshIntervalOptions={REFRESH_INTERVAL_OPTIONS} />
</SceneContent>
)
}
diff --git a/products/business_knowledge/frontend/scenes/KnowledgeSourceScene.tsx b/products/business_knowledge/frontend/scenes/KnowledgeSourceScene.tsx
new file mode 100644
index 000000000000..a2e4e6431c12
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/KnowledgeSourceScene.tsx
@@ -0,0 +1,134 @@
+import { useActions, useValues } from 'kea'
+
+import { IconBook, IconRefresh, IconTrash } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonDialog, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'
+
+import { NotFound } from 'lib/components/NotFound'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { SceneExport } from 'scenes/sceneTypes'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { ProductKey } from '~/queries/schema/schema-general'
+
+import { KnowledgeSourceForm } from '../components/KnowledgeSourceForm'
+import { StatusTag } from '../components/StatusTag'
+import { REFRESH_INTERVAL_OPTIONS } from './businessKnowledgeLogic'
+import { KnowledgeSourceLogicProps, knowledgeSourceLogic } from './knowledgeSourceLogic'
+
+export const scene: SceneExport<KnowledgeSourceLogicProps> = {
+ component: KnowledgeSourceScene,
+ logic: knowledgeSourceLogic,
+ productKey: ProductKey.BUSINESS_KNOWLEDGE,
+ paramsToProps: ({ params: { id } }) => ({ id }),
+}
+
+export function KnowledgeSourceScene(): JSX.Element {
+ const isEnabled = useFeatureFlag('PRODUCT_BUSINESS_KNOWLEDGE')
+ const {
+ source,
+ sourceLoading,
+ sourceNotFound,
+ isSourceTextReady,
+ isEditSourceSubmitting,
+ isEditUrlSourceSubmitting,
+ isRefreshing,
+ isDeleting,
+ } = useValues(knowledgeSourceLogic)
+ const { loadSource, submitEditSource, submitEditUrlSource, refreshSource, deleteSource } =
+ useActions(knowledgeSourceLogic)
+
+ if (!isEnabled) {
+ return <NotFound object="Business knowledge" caption="This feature is not enabled for your project." />
+ }
+
+ if (sourceLoading && !source) {
+ return (
+ <SceneContent>
+ <LemonSkeleton className="h-10 w-80 mb-4" />
+ <LemonSkeleton className="h-60 max-w-2xl" />
+ </SceneContent>
+ )
+ }
+
+ if (sourceNotFound) {
+ return <NotFound object="knowledge source" />
+ }
+
+ if (!source) {
+ return (
+ <SceneContent>
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadSource }}>
+ Couldn't load this knowledge source. Try again.
+ </LemonBanner>
+ </SceneContent>
+ )
+ }
+
+ const isUrl = source.source_type === 'url'
+ const isSubmitting = isUrl ? isEditUrlSourceSubmitting : isEditSourceSubmitting
+ const canRefresh = isUrl && !source.is_generated
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name={source.name}
+ resourceType={{ type: 'default_icon_type', forceIcon: <IconBook /> }}
+ nameSuffix={
+ <span className="flex items-center gap-1">
+ <LemonTag>{source.source_type}</LemonTag>
+ <StatusTag source={source} />
+ </span>
+ }
+ actions={
+ <div className="flex gap-2 flex-wrap">
+ <LemonButton
+ type="primary"
+ loading={isSubmitting}
+ disabledReason={!isSourceTextReady ? 'Loading source content' : undefined}
+ onClick={isUrl ? submitEditUrlSource : submitEditSource}
+ // pinned: autocapture / Playwright key. Do not rename.
+ data-attr="business-knowledge-source-save"
+ >
+ Save
+ </LemonButton>
+ {canRefresh && (
+ <LemonButton
+ icon={<IconRefresh />}
+ loading={isRefreshing}
+ disabledReason={isDeleting ? 'Deleting this source' : undefined}
+ onClick={() => refreshSource()}
+ // pinned: autocapture / Playwright key. Do not rename.
+ data-attr="business-knowledge-source-refresh"
+ >
+ Refresh
+ </LemonButton>
+ )}
+ <LemonButton
+ icon={<IconTrash />}
+ status="danger"
+ loading={isDeleting}
+ onClick={() => {
+ LemonDialog.open({
+ title: `Delete "${source.name}"?`,
+ description: 'Chunks will be removed.',
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => deleteSource(),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }}
+ // pinned: autocapture / Playwright key. Do not rename.
+ data-attr="business-knowledge-source-delete"
+ >
+ Delete
+ </LemonButton>
+ </div>
+ }
+ />
+ <KnowledgeSourceForm refreshIntervalOptions={REFRESH_INTERVAL_OPTIONS} />
+ </SceneContent>
+ )
+}
diff --git a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts
index 203308990fa1..553159312d13 100644
--- a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts
+++ b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts
@@ -2,47 +2,28 @@ import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, sel
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { urls } from 'scenes/urls'
-import {
- createFileSource,
- createTextSource,
- createUrlSource,
- deleteSource,
- getSourceText,
- listSources,
- refreshSource,
- updateSource,
-} from '../api'
-import type { CreateUrlSourcePayload, RefreshIntervalOption, RefreshIntervalValue, UpdateSourcePayload } from '../api'
+import { createFileSource, createTextSource, createUrlSource, deleteSource, listSources, refreshSource } from '../api'
+import type { CreateUrlSourcePayload, RefreshIntervalOption } from '../api'
import type { KnowledgeSourceApi } from '../generated/api.schemas'
+import {
+ DEFAULT_URL_SOURCE_FORM,
+ type CrawlMode,
+ type KnowledgeSource,
+ type TextSourceFormValues,
+ type UrlSourceFormValues,
+ splitGlobs,
+ validateText,
+ validateUrl,
+} from './sourceFormUtils'
-export type KnowledgeSource = KnowledgeSourceApi
-export type CrawlMode = 'single' | 'sitemap' | 'same_origin' | 'github_repo'
+export type { KnowledgeSource, CrawlMode, TextSourceFormValues, UrlSourceFormValues }
export type SourceTypeFilter = 'all' | 'text' | 'url' | 'file'
-export interface TextSourceFormValues {
- name: string
- text: string
- always_include: boolean
-}
-
-export interface UrlSourceFormValues {
- name: string
- url: string
- crawl_mode: CrawlMode
- // Comma/newline-separated globs — split server-side. Keeping the form
- // state as a plain string is much easier than a list-of-inputs widget.
- include_globs: string
- exclude_globs: string
- max_pages: number
- max_depth: number
- // Background auto-refresh cadence, sent on both create and edit.
- refresh_interval: RefreshIntervalValue
- always_include: boolean
-}
-
export interface FileSourceFormValues {
name: string
file: File | null
@@ -59,101 +40,9 @@ export const REFRESH_INTERVAL_OPTIONS: RefreshIntervalOption[] = [
{ value: '7d', label: 'Every week' },
]
-const MAX_TEXT_BYTES = 1_000_000
-
-function validateText({ name, text }: TextSourceFormValues): {
- name: string | undefined
- text: string | undefined
-} {
- return {
- name: !name.trim() ? 'Give the source a short name' : undefined,
- text: !text.trim()
- ? 'Paste some content'
- : new Blob([text]).size > MAX_TEXT_BYTES
- ? 'Text exceeds the 1 MB cap — split it into smaller sources'
- : undefined,
- }
-}
-
-function validateUrl({ name, url, max_pages }: UrlSourceFormValues): {
- name: string | undefined
- url: string | undefined
- max_pages: string | undefined
-} {
- let urlError: string | undefined
- if (!url.trim()) {
- urlError = 'Paste a public HTTPS URL'
- } else {
- try {
- const parsed = new URL(url)
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
- urlError = 'Only http(s) URLs are allowed'
- }
- } catch {
- urlError = 'Not a valid URL'
- }
- }
- return {
- name: !name.trim() ? 'Give the source a short name' : undefined,
- url: urlError,
- max_pages: max_pages < 1 || max_pages > 500 ? 'max_pages must be between 1 and 500' : undefined,
- }
-}
-
-function splitGlobs(raw: string): string[] {
- return raw
- .split(/[\n,]/)
- .map((s) => s.trim())
- .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
- editSource: TextSourceFormValues
- editSourceAllErrors: Record<string, any>
- editSourceChanged: boolean
- editSourceErrors: DeepPartialMap<TextSourceFormValues, ValidationErrorType>
- editSourceHasErrors: boolean
- editSourceManualErrors: Record<string, any>
- editSourceTouched: boolean
- editSourceTouches: Record<string, boolean>
- editSourceValidationErrors: DeepPartialMap<TextSourceFormValues, ValidationErrorType>
- editUrlSource: UrlSourceFormValues
- editUrlSourceAllErrors: Record<string, any>
- editUrlSourceChanged: boolean
- editUrlSourceErrors: DeepPartialMap<UrlSourceFormValues, ValidationErrorType>
- editUrlSourceHasErrors: boolean
- editUrlSourceManualErrors: Record<string, any>
- editUrlSourceTouched: boolean
- editUrlSourceTouches: Record<string, boolean>
- editUrlSourceValidationErrors: DeepPartialMap<UrlSourceFormValues, ValidationErrorType>
- editingSource: KnowledgeSource | null
- editingSourceText: {
- id: string
- text: string
- }
- editingSourceTextLoading: boolean
fileSource: FileSourceFormValues
fileSourceAllErrors: Record<string, any>
fileSourceChanged: boolean
@@ -164,11 +53,6 @@ export interface businessKnowledgeLogicValues {
fileSourceTouches: Record<string, boolean>
fileSourceValidationErrors: DeepPartialMap<FileSourceFormValues, ValidationErrorType>
isCreateModalOpen: boolean
- isEditModalOpen: boolean
- isEditSourceSubmitting: boolean
- isEditSourceValid: boolean
- isEditUrlSourceSubmitting: boolean
- isEditUrlSourceValid: boolean
isFileSourceSubmitting: boolean
isFileSourceValid: boolean
isTextSourceSubmitting: boolean
@@ -178,8 +62,6 @@ export interface businessKnowledgeLogicValues {
readyCount: number
refreshingIds: string[]
searchTerm: string
- showEditSourceErrors: boolean
- showEditUrlSourceErrors: boolean
showFileSourceErrors: boolean
showTextSourceErrors: boolean
showUrlSourceErrors: boolean
@@ -212,39 +94,9 @@ export interface businessKnowledgeLogicActions {
closeCreateModal: () => {
value: true
}
- closeEditModal: () => {
- value: true
- }
deleteSource: (id: string) => {
id: string
}
- loadEditingSourceText: ({ id }: { id: string }) => {
- id: string
- }
- loadEditingSourceTextFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadEditingSourceTextSuccess: (
- editingSourceText: {
- id: string
- text: string
- },
- payload?: {
- id: string
- }
- ) => {
- editingSourceText: {
- id: string
- text: string
- }
- payload?: {
- id: string
- }
- }
loadSources: (_: void) => void
loadSourcesFailure: (
error: string,
@@ -263,9 +115,6 @@ export interface businessKnowledgeLogicActions {
openCreateModal: () => {
value: true
}
- openEditModal: (source: KnowledgeSource) => {
- source: KnowledgeSourceApi
- }
refreshSource: (id: string) => {
id: string
}
@@ -314,33 +163,6 @@ export interface businessKnowledgeLogicActions {
source: KnowledgeSource
}
}
- resetEditSource: (values?: TextSourceFormValues) => {
- values?: TextSourceFormValues
- }
- resetEditUrlSource: (values?: UrlSourceFormValues) => {
- values?: UrlSourceFormValues
- }
- resetEditingSourceText: () => any
- resetEditingSourceTextFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- resetEditingSourceTextSuccess: (
- editingSourceText: {
- id: string
- text: string
- },
- payload?: any
- ) => {
- editingSourceText: {
- id: string
- text: string
- }
- payload?: any
- }
resetFileSource: (values?: FileSourceFormValues) => {
values?: FileSourceFormValues
}
@@ -353,32 +175,6 @@ export interface businessKnowledgeLogicActions {
setCreateTab: (tab: CreateTab) => {
tab: CreateTab
}
- setEditSourceManualErrors: (errors: Record<string, any>) => {
- errors: Record<string, any>
- }
- setEditSourceValue: (
- key: FieldName,
- value: any
- ) => {
- name: FieldName
- value: any
- }
- setEditSourceValues: (values: DeepPartial<TextSourceFormValues>) => {
- values: DeepPartial<TextSourceFormValues>
- }
- setEditUrlSourceManualErrors: (errors: Record<string, any>) => {
- errors: Record<string, any>
- }
- setEditUrlSourceValue: (
- key: FieldName,
- value: any
- ) => {
- name: FieldName
- value: any
- }
- setEditUrlSourceValues: (values: DeepPartial<UrlSourceFormValues>) => {
- values: DeepPartial<UrlSourceFormValues>
- }
setFileSourceManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
@@ -424,38 +220,6 @@ export interface businessKnowledgeLogicActions {
setUrlSourceValues: (values: DeepPartial<UrlSourceFormValues>) => {
values: DeepPartial<UrlSourceFormValues>
}
- submitEditSource: () => {
- value: boolean
- }
- submitEditSourceFailure: (
- error: Error,
- errors: Record<string, any>
- ) => {
- error: Error
- errors: Record<string, any>
- }
- submitEditSourceRequest: (editSource: TextSourceFormValues) => {
- editSource: TextSourceFormValues
- }
- submitEditSourceSuccess: (editSource: TextSourceFormValues) => {
- editSource: TextSourceFormValues
- }
- submitEditUrlSource: () => {
- value: boolean
- }
- submitEditUrlSourceFailure: (
- error: Error,
- errors: Record<string, any>
- ) => {
- error: Error
- errors: Record<string, any>
- }
- submitEditUrlSourceRequest: (editUrlSource: UrlSourceFormValues) => {
- editUrlSource: UrlSourceFormValues
- }
- submitEditUrlSourceSuccess: (editUrlSource: UrlSourceFormValues) => {
- editUrlSource: UrlSourceFormValues
- }
submitFileSource: () => {
value: boolean
}
@@ -504,12 +268,6 @@ export interface businessKnowledgeLogicActions {
submitUrlSourceSuccess: (urlSource: UrlSourceFormValues) => {
urlSource: UrlSourceFormValues
}
- touchEditSourceField: (key: string) => {
- key: string
- }
- touchEditUrlSourceField: (key: string) => {
- key: string
- }
touchFileSourceField: (key: string) => {
key: string
}
@@ -526,7 +284,6 @@ export interface businessKnowledgeLogicMeta {
__keaTypeGenInternalSelectorTypes: {
readyCount: (sources: KnowledgeSourceApi[]) => number
totalChunks: (sources: KnowledgeSourceApi[]) => number
- isEditModalOpen: (editingSource: KnowledgeSourceApi | null) => boolean
}
}
@@ -545,8 +302,6 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
setCreateTab: (tab: CreateTab) => ({ tab }),
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
setSourceTypeFilter: (sourceTypeFilter: SourceTypeFilter) => ({ sourceTypeFilter }),
- openEditModal: (source: KnowledgeSource) => ({ source }),
- closeEditModal: true,
deleteSource: (id: string) => ({ id }),
refreshSource: (id: string) => ({ id }),
refreshSourceDone: (id: string) => ({ id }),
@@ -566,13 +321,6 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
closeCreateModal: () => 'text',
},
],
- editingSource: [
- null as KnowledgeSource | null,
- {
- openEditModal: (_, { source }) => source,
- closeEditModal: () => null,
- },
- ],
refreshingIds: [
[] as string[],
{
@@ -612,17 +360,8 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
values.sources.map((s) => (s.id === source.id ? source : s)),
},
],
- editingSourceText: [
- { id: '', text: '' } as { id: string; text: string },
- {
- loadEditingSourceText: async ({ id }: { id: string }) => {
- return await getSourceText(id)
- },
- resetEditingSourceText: () => ({ id: '', text: '' }),
- },
- ],
})),
- forms(({ actions, values }) => ({
+ forms(({ actions }) => ({
textSource: {
defaults: { name: '', text: '', always_include: false } as TextSourceFormValues,
errors: validateText,
@@ -632,7 +371,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
lemonToast.success(`"${created.name}" indexed into ${created.chunk_count} chunks`)
actions.closeCreateModal()
actions.resetTextSource()
- actions.loadSources()
+ router.actions.push(urls.businessKnowledgeSource(created.id))
} catch (error: any) {
lemonToast.error(
error?.detail ||
@@ -644,17 +383,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
},
},
urlSource: {
- defaults: {
- name: '',
- url: '',
- crawl_mode: 'single',
- include_globs: '',
- exclude_globs: '',
- max_pages: 50,
- max_depth: 2,
- refresh_interval: 'manual',
- always_include: false,
- } as UrlSourceFormValues,
+ defaults: DEFAULT_URL_SOURCE_FORM,
errors: validateUrl,
submit: async (formValues: UrlSourceFormValues) => {
const includeGlobs = splitGlobs(formValues.include_globs)
@@ -677,11 +406,11 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
try {
const created = await createUrlSource(payload)
// Ingestion runs in the background; the source starts PROCESSING
- // and the list polls until it flips to ready.
+ // and the detail page polls until it flips to ready.
lemonToast.success(`"${created.name}" added — fetching and indexing in the background`)
actions.closeCreateModal()
actions.resetUrlSource()
- actions.loadSources()
+ router.actions.push(urls.businessKnowledgeSource(created.id))
} catch (error: any) {
lemonToast.error(
error?.detail ||
@@ -717,7 +446,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
lemonToast.success(`"${created.name}" indexed into ${created.chunk_count} chunks`)
actions.closeCreateModal()
actions.resetFileSource()
- actions.loadSources()
+ router.actions.push(urls.businessKnowledgeSource(created.id))
} catch (error: any) {
lemonToast.error(
error?.detail ||
@@ -729,109 +458,8 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
}
},
},
- editSource: {
- defaults: { name: '', text: '', always_include: false } as TextSourceFormValues,
- errors: ({ name, text }: TextSourceFormValues) => {
- const isText = values.editingSource?.source_type === 'text'
- return {
- name: !name.trim() ? 'Give the source a short name' : undefined,
- text: isText
- ? !text.trim()
- ? 'Paste some content'
- : new Blob([text]).size > MAX_TEXT_BYTES
- ? 'Text exceeds the 1 MB cap — split it into smaller sources'
- : undefined
- : undefined,
- }
- },
- submit: async ({ name, text, always_include }: TextSourceFormValues) => {
- const current = values.editingSource
- if (!current) {
- return
- }
- const isText = current.source_type === 'text'
- const payload: UpdateSourcePayload = { name, always_include, ...(isText && { text }) }
- try {
- const updated = await updateSource(current.id, payload)
- const msg = isText
- ? `"${updated.name}" re-indexed into ${updated.chunk_count} chunks`
- : `"${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()
- } catch (error: any) {
- lemonToast.error(
- error?.detail ||
- error?.data?.detail ||
- 'Could not save the changes. Check the error and try again.'
- )
- throw error
- }
- },
- },
- editUrlSource: {
- defaults: {
- name: '',
- url: '',
- crawl_mode: 'single' as CrawlMode,
- include_globs: '',
- exclude_globs: '',
- max_pages: 50,
- max_depth: 2,
- refresh_interval: 'manual',
- always_include: false,
- } as UrlSourceFormValues,
- errors: validateUrl,
- submit: async (vals: UrlSourceFormValues) => {
- const current = values.editingSource
- if (!current) {
- return
- }
- const editIncludeGlobs = splitGlobs(vals.include_globs)
- const payload: UpdateSourcePayload = {
- name: vals.name,
- url: vals.url,
- crawl_mode: vals.crawl_mode,
- refresh_interval: vals.refresh_interval,
- always_include: vals.always_include,
- ...(vals.crawl_mode !== 'single' && {
- ...(editIncludeGlobs.length > 0 && { include_globs: editIncludeGlobs }),
- exclude_globs: splitGlobs(vals.exclude_globs),
- max_pages: vals.max_pages,
- max_depth: vals.max_depth,
- }),
- }
- try {
- 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) {
- lemonToast.error(
- error?.detail ||
- error?.data?.url?.[0] ||
- error?.data?.detail ||
- 'Could not save the changes. Check the error and try again.'
- )
- throw error
- }
- },
- },
})),
- listeners(({ actions, values, cache }) => ({
+ listeners(({ actions, cache }) => ({
setSearchTerm: async (_, breakpoint) => {
await breakpoint(300)
actions.loadSources()
@@ -881,30 +509,6 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
actions.refreshSourceDone(id)
}
},
- openEditModal: ({ source }) => {
- if (source.source_type === 'url') {
- 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 }) => {
- if (values.editingSource && values.editingSource.id === editingSourceText.id) {
- actions.setEditSourceValue('text', editingSourceText.text)
- }
- },
- closeEditModal: () => {
- actions.resetEditSource()
- actions.resetEditUrlSource()
- actions.resetEditingSourceText()
- },
})),
selectors({
readyCount: [
@@ -915,7 +519,6 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
(s) => [s.sources],
(sources: KnowledgeSource[]) => sources.reduce((sum, s) => sum + (s.chunk_count || 0), 0),
],
- isEditModalOpen: [(s) => [s.editingSource], (editingSource: KnowledgeSource | null) => editingSource !== null],
}),
afterMount(({ actions }) => {
actions.loadSources()
diff --git a/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.test.ts b/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.test.ts
new file mode 100644
index 000000000000..a53039afd4de
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.test.ts
@@ -0,0 +1,186 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import * as api from '../api'
+import type { KnowledgeSourceApi } from '../generated/api.schemas'
+import { knowledgeSourceLogic } from './knowledgeSourceLogic'
+
+jest.mock('../api', () => ({
+ getSource: jest.fn(),
+ getSourceText: jest.fn(),
+ updateSource: jest.fn(),
+ deleteSource: jest.fn(),
+ refreshSource: jest.fn(),
+}))
+
+jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
+ lemonToast: {
+ success: jest.fn(),
+ error: jest.fn(),
+ info: jest.fn(),
+ },
+}))
+
+const SOURCE_ID = '11111111-1111-1111-1111-111111111111'
+
+const MOCK_SOURCE: KnowledgeSourceApi = {
+ id: SOURCE_ID,
+ team_id: 1,
+ name: 'Refund policy',
+ source_type: 'text',
+ is_generated: false,
+ status: 'ready',
+ error_message: '',
+ document_count: 1,
+ chunk_count: 3,
+ created_at: '2026-09-01T12:00:00Z',
+ updated_at: '2026-09-01T12:00:00Z',
+ source_url: '',
+ last_refresh_at: null,
+ last_refresh_status: 'success',
+ last_refresh_error: '',
+ refresh_interval: 'manual',
+ next_refresh_at: null,
+ has_unsafe_documents: false,
+ embedding_status: 'completed',
+ learned_from_ticket_number: null,
+ learned_from_ticket_url: null,
+ crawl_mode: 'single',
+ crawl_config: {},
+ original_filename: '',
+ file_content_type: '',
+ file_size_bytes: null,
+ always_include: false,
+}
+
+const mockedApi = api as jest.Mocked<typeof api>
+
+describe('knowledgeSourceLogic', () => {
+ let logic: ReturnType<typeof knowledgeSourceLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.clearAllMocks()
+ mockedApi.getSource.mockResolvedValue(MOCK_SOURCE)
+ mockedApi.getSourceText.mockResolvedValue({ id: SOURCE_ID, text: 'Refund within 30 days.' })
+ mockedApi.updateSource.mockResolvedValue({ ...MOCK_SOURCE, name: 'Updated policy', chunk_count: 4 })
+ mockedApi.deleteSource.mockResolvedValue(undefined)
+ logic = knowledgeSourceLogic({ id: SOURCE_ID })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it('marks the source not found on a 404 without throwing', async () => {
+ logic.unmount()
+ mockedApi.getSource.mockRejectedValue({ status: 404, detail: 'Not found.' })
+ logic = knowledgeSourceLogic({ id: SOURCE_ID })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({
+ source: null,
+ sourceNotFound: true,
+ sourceLoading: false,
+ })
+ })
+
+ it('stays on the page after a successful save', async () => {
+ const pushSpy = jest.spyOn(router.actions, 'push')
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setEditSourceValues({
+ name: 'Updated policy',
+ text: 'Refund within 60 days.',
+ always_include: false,
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.submitEditSource()
+ }).toFinishAllListeners()
+
+ expect(mockedApi.updateSource).toHaveBeenCalledWith(
+ SOURCE_ID,
+ expect.objectContaining({ name: 'Updated policy', text: 'Refund within 60 days.' })
+ )
+ expect(logic.values.editSource.text).toBe('Refund within 60 days.')
+ expect(pushSpy).not.toHaveBeenCalled()
+ expect(mockedApi.getSource).toHaveBeenCalled()
+ pushSpy.mockRestore()
+ })
+
+ it('does not treat a server error as not found', async () => {
+ logic.unmount()
+ mockedApi.getSource.mockRejectedValue({ status: 500, detail: 'boom' })
+ logic = knowledgeSourceLogic({ id: SOURCE_ID })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({
+ source: null,
+ sourceNotFound: false,
+ sourceLoading: false,
+ })
+ })
+
+ it('does not reset in-progress edits when the source is polled', async () => {
+ logic.unmount()
+ mockedApi.getSource.mockResolvedValue({
+ ...MOCK_SOURCE,
+ source_type: 'url',
+ status: 'processing',
+ source_url: 'https://docs.example.com',
+ })
+ logic = knowledgeSourceLogic({ id: SOURCE_ID })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setEditUrlSourceValue('name', 'Draft name')
+
+ await expectLogic(logic, () => {
+ logic.actions.loadSource()
+ }).toFinishAllListeners()
+
+ expect(logic.values.editUrlSource.name).toBe('Draft name')
+ })
+
+ it('still opens the text form if content fails to load', async () => {
+ logic.unmount()
+ mockedApi.getSourceText.mockRejectedValue({ status: 500, detail: 'boom' })
+ mockedApi.updateSource.mockResolvedValue({ ...MOCK_SOURCE, name: 'Renamed policy', always_include: true })
+ logic = knowledgeSourceLogic({ id: SOURCE_ID })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({
+ sourceTextFailed: true,
+ isSourceTextReady: true,
+ })
+
+ logic.actions.setEditSourceValues({ name: 'Renamed policy', always_include: true })
+
+ await expectLogic(logic, () => {
+ logic.actions.submitEditSource()
+ }).toFinishAllListeners()
+
+ expect(mockedApi.updateSource).toHaveBeenCalledWith(SOURCE_ID, {
+ name: 'Renamed policy',
+ always_include: true,
+ })
+ })
+
+ it('navigates to the list after delete', async () => {
+ const pushSpy = jest.spyOn(router.actions, 'push')
+
+ await expectLogic(logic, () => {
+ logic.actions.deleteSource()
+ }).toFinishAllListeners()
+
+ expect(mockedApi.deleteSource).toHaveBeenCalledWith(SOURCE_ID)
+ expect(pushSpy).toHaveBeenCalledWith('/business-knowledge')
+ pushSpy.mockRestore()
+ })
+})
diff --git a/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.ts b/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.ts
new file mode 100644
index 000000000000..70b4ae8bab8e
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/knowledgeSourceLogic.ts
@@ -0,0 +1,491 @@
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+ type LogicWrapper,
+} from 'kea'
+import { forms } from 'kea-forms'
+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
+import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { Scene } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import type { Breadcrumb } from '~/types'
+
+import { deleteSource, getSource, getSourceText, refreshSource, updateSource } from '../api'
+import type { UpdateSourcePayload } from '../api'
+import type { KnowledgeSourceApi } from '../generated/api.schemas'
+import {
+ DEFAULT_URL_SOURCE_FORM,
+ type CrawlMode,
+ type KnowledgeSource,
+ type TextSourceFormValues,
+ type UrlSourceFormValues,
+ editUrlSourceValuesFromSource,
+ splitGlobs,
+ validateText,
+ validateUrl,
+} from './sourceFormUtils'
+
+const PROCESSING_POLL_MS = 3000
+const EMBEDDING_POLL_MS = 60_000
+
+export type { KnowledgeSource, CrawlMode, TextSourceFormValues, UrlSourceFormValues }
+
+function hasLoadedSourceText(source: KnowledgeSource | null, sourceText: { id: string }): boolean {
+ return source?.source_type !== 'text' || sourceText.id === source.id
+}
+
+function sourcePollDelayMs(source: KnowledgeSource): number | null {
+ if (source.status === 'processing') {
+ return PROCESSING_POLL_MS
+ }
+ if (source.status === 'ready' && source.embedding_status === 'pending') {
+ return EMBEDDING_POLL_MS
+ }
+ return null
+}
+
+export interface KnowledgeSourceLogicProps {
+ id: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface knowledgeSourceLogicValues {
+ breadcrumbs: Breadcrumb[]
+ editSource: TextSourceFormValues
+ editSourceAllErrors: Record<string, any>
+ editSourceChanged: boolean
+ editSourceErrors: DeepPartialMap<TextSourceFormValues, ValidationErrorType>
+ editSourceHasErrors: boolean
+ editSourceManualErrors: Record<string, any>
+ editSourceTouched: boolean
+ editSourceTouches: Record<string, boolean>
+ editSourceValidationErrors: DeepPartialMap<TextSourceFormValues, ValidationErrorType>
+ editUrlSource: UrlSourceFormValues
+ editUrlSourceAllErrors: Record<string, any>
+ editUrlSourceChanged: boolean
+ editUrlSourceErrors: DeepPartialMap<UrlSourceFormValues, ValidationErrorType>
+ editUrlSourceHasErrors: boolean
+ editUrlSourceManualErrors: Record<string, any>
+ editUrlSourceTouched: boolean
+ editUrlSourceTouches: Record<string, boolean>
+ editUrlSourceValidationErrors: DeepPartialMap<UrlSourceFormValues, ValidationErrorType>
+ isDeleting: boolean
+ isEditSourceSubmitting: boolean
+ isEditSourceValid: boolean
+ isEditUrlSourceSubmitting: boolean
+ isEditUrlSourceValid: boolean
+ isRefreshing: boolean
+ isSourceTextReady: boolean
+ showEditSourceErrors: boolean
+ showEditUrlSourceErrors: boolean
+ source: KnowledgeSource | null
+ sourceLoading: boolean
+ sourceNotFound: boolean
+ sourceText: {
+ id: string
+ text: string
+ }
+ sourceTextFailed: boolean
+ sourceTextLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface knowledgeSourceLogicActions {
+ deleteSource: () => {
+ value: true
+ }
+ deleteSourceDone: () => {
+ value: true
+ }
+ loadSource: () => any
+ loadSourceFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSourceSuccess: (
+ source: KnowledgeSourceApi | null,
+ payload?: any
+ ) => {
+ source: KnowledgeSourceApi | null
+ payload?: any
+ }
+ loadSourceText: () => any
+ loadSourceTextFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSourceTextSuccess: (
+ sourceText: {
+ id: string
+ text: string
+ },
+ payload?: any
+ ) => {
+ sourceText: {
+ id: string
+ text: string
+ }
+ payload?: any
+ }
+ markSourceNotFound: () => {
+ value: true
+ }
+ refreshSource: () => {
+ value: true
+ }
+ refreshSourceDone: () => {
+ value: true
+ }
+ resetEditSource: (values?: TextSourceFormValues) => {
+ values?: TextSourceFormValues
+ }
+ resetEditUrlSource: (values?: UrlSourceFormValues) => {
+ values?: UrlSourceFormValues
+ }
+ setEditSourceManualErrors: (errors: Record<string, any>) => {
+ errors: Record<string, any>
+ }
+ setEditSourceValue: (
+ key: FieldName,
+ value: any
+ ) => {
+ name: FieldName
+ value: any
+ }
+ setEditSourceValues: (values: DeepPartial<TextSourceFormValues>) => {
+ values: DeepPartial<TextSourceFormValues>
+ }
+ setEditUrlSourceManualErrors: (errors: Record<string, any>) => {
+ errors: Record<string, any>
+ }
+ setEditUrlSourceValue: (
+ key: FieldName,
+ value: any
+ ) => {
+ name: FieldName
+ value: any
+ }
+ setEditUrlSourceValues: (values: DeepPartial<UrlSourceFormValues>) => {
+ values: DeepPartial<UrlSourceFormValues>
+ }
+ submitEditSource: () => {
+ value: boolean
+ }
+ submitEditSourceFailure: (
+ error: Error,
+ errors: Record<string, any>
+ ) => {
+ error: Error
+ errors: Record<string, any>
+ }
+ submitEditSourceRequest: (editSource: TextSourceFormValues) => {
+ editSource: TextSourceFormValues
+ }
+ submitEditSourceSuccess: (editSource: TextSourceFormValues) => {
+ editSource: TextSourceFormValues
+ }
+ submitEditUrlSource: () => {
+ value: boolean
+ }
+ submitEditUrlSourceFailure: (
+ error: Error,
+ errors: Record<string, any>
+ ) => {
+ error: Error
+ errors: Record<string, any>
+ }
+ submitEditUrlSourceRequest: (editUrlSource: UrlSourceFormValues) => {
+ editUrlSource: UrlSourceFormValues
+ }
+ submitEditUrlSourceSuccess: (editUrlSource: UrlSourceFormValues) => {
+ editUrlSource: UrlSourceFormValues
+ }
+ touchEditSourceField: (key: string) => {
+ key: string
+ }
+ touchEditUrlSourceField: (key: string) => {
+ key: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface knowledgeSourceLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ breadcrumbs: (source: KnowledgeSourceApi | null) => Breadcrumb[]
+ isSourceTextReady: (
+ source: KnowledgeSourceApi | null,
+ sourceText: {
+ id: string
+ text: string
+ },
+ sourceTextFailed: boolean
+ ) => boolean
+ }
+}
+
+export type knowledgeSourceLogicType = MakeLogicType<
+ knowledgeSourceLogicValues,
+ knowledgeSourceLogicActions,
+ KnowledgeSourceLogicProps,
+ knowledgeSourceLogicMeta
+>
+
+export const knowledgeSourceLogic: LogicWrapper<knowledgeSourceLogicType> = kea<knowledgeSourceLogicType>([
+ props({} as KnowledgeSourceLogicProps),
+ key((props) => props.id),
+ path((key) => ['products', 'business_knowledge', 'knowledgeSourceLogic', key]),
+ actions({
+ markSourceNotFound: true,
+ deleteSource: true,
+ deleteSourceDone: true,
+ refreshSource: true,
+ refreshSourceDone: true,
+ }),
+ reducers({
+ sourceNotFound: [
+ false,
+ {
+ loadSource: () => false,
+ markSourceNotFound: () => true,
+ },
+ ],
+ isDeleting: [
+ false,
+ {
+ deleteSource: () => true,
+ deleteSourceDone: () => false,
+ },
+ ],
+ isRefreshing: [
+ false,
+ {
+ refreshSource: () => true,
+ refreshSourceDone: () => false,
+ },
+ ],
+ sourceTextFailed: [
+ false,
+ {
+ loadSourceText: () => false,
+ loadSourceTextSuccess: () => false,
+ loadSourceTextFailure: () => true,
+ },
+ ],
+ }),
+ loaders(({ actions, props }) => ({
+ source: [
+ null as KnowledgeSource | null,
+ {
+ loadSource: async () => {
+ try {
+ return await getSource(props.id)
+ } catch (error: unknown) {
+ // Catch 404 here so initKea does not toast. The scene renders NotFound.
+ if ((error as { status?: number } | null)?.status === 404) {
+ actions.markSourceNotFound()
+ return null
+ }
+ throw error
+ }
+ },
+ },
+ ],
+ sourceText: [
+ { id: '', text: '' } as { id: string; text: string },
+ {
+ loadSourceText: async () => {
+ return await getSourceText(props.id)
+ },
+ },
+ ],
+ })),
+ forms(({ actions, values, props }) => ({
+ editSource: {
+ defaults: { name: '', text: '', always_include: false } as TextSourceFormValues,
+ errors: (vals: TextSourceFormValues) => {
+ if (values.source?.source_type === 'text' && hasLoadedSourceText(values.source, values.sourceText)) {
+ return validateText(vals)
+ }
+ return {
+ name: !vals.name.trim() ? 'Give the source a short name' : undefined,
+ }
+ },
+ submit: async ({ name, text, always_include }: TextSourceFormValues) => {
+ const current = values.source
+ if (!current) {
+ return
+ }
+ const includeText = current.source_type === 'text' && hasLoadedSourceText(current, values.sourceText)
+ const payload: UpdateSourcePayload = { name, always_include, ...(includeText && { text }) }
+ try {
+ const updated = await updateSource(props.id, payload)
+ const msg = includeText
+ ? `"${updated.name}" re-indexed into ${updated.chunk_count} chunks`
+ : `"${updated.name}" renamed`
+ lemonToast.success(msg)
+ actions.loadSource()
+ } catch (error: any) {
+ lemonToast.error(
+ error?.detail ||
+ error?.data?.detail ||
+ 'Could not save the changes. Check the error and try again.'
+ )
+ throw error
+ }
+ },
+ },
+ editUrlSource: {
+ defaults: DEFAULT_URL_SOURCE_FORM,
+ errors: validateUrl,
+ submit: async (vals: UrlSourceFormValues) => {
+ const current = values.source
+ if (!current) {
+ return
+ }
+ const editIncludeGlobs = splitGlobs(vals.include_globs)
+ const payload: UpdateSourcePayload = {
+ name: vals.name,
+ url: vals.url,
+ crawl_mode: vals.crawl_mode,
+ refresh_interval: vals.refresh_interval,
+ always_include: vals.always_include,
+ ...(vals.crawl_mode !== 'single' && {
+ ...(editIncludeGlobs.length > 0 && { include_globs: editIncludeGlobs }),
+ exclude_globs: splitGlobs(vals.exclude_globs),
+ max_pages: vals.max_pages,
+ max_depth: vals.max_depth,
+ }),
+ }
+ try {
+ const updated = await updateSource(props.id, payload)
+ lemonToast.success(`"${updated.name}" updated`)
+ actions.loadSource()
+ } catch (error: any) {
+ lemonToast.error(
+ error?.detail ||
+ error?.data?.url?.[0] ||
+ error?.data?.detail ||
+ 'Could not save the changes. Check the error and try again.'
+ )
+ throw error
+ }
+ },
+ },
+ })),
+ listeners(({ actions, values, props, cache }) => ({
+ loadSourceSuccess: ({ source }) => {
+ if (!source) {
+ cache.disposables.dispose('pollProcessing')
+ return
+ }
+ // Hydrate once. Later polls must not wipe in-progress edits, and a text
+ // save must not restore the stale sourceText loader value.
+ if (!cache.formHydrated) {
+ if (source.source_type === 'url') {
+ actions.setEditUrlSourceValues(editUrlSourceValuesFromSource(source))
+ } else {
+ const textReady = hasLoadedSourceText(source, values.sourceText)
+ actions.setEditSourceValues({
+ name: source.name,
+ text: textReady ? values.sourceText.text : '',
+ always_include: source.always_include ?? false,
+ })
+ if (!textReady) {
+ actions.loadSourceText()
+ }
+ }
+ cache.formHydrated = true
+ }
+ const delayMs = sourcePollDelayMs(source)
+ if (delayMs === null) {
+ cache.disposables.dispose('pollProcessing')
+ } else {
+ cache.disposables.add(() => {
+ const id = setTimeout(() => actions.loadSource(), delayMs)
+ return () => clearTimeout(id)
+ }, 'pollProcessing')
+ }
+ },
+ loadSourceTextSuccess: ({ sourceText }) => {
+ if (values.source && values.source.id === sourceText.id) {
+ actions.setEditSourceValue('text', sourceText.text)
+ }
+ },
+ deleteSource: async () => {
+ try {
+ await deleteSource(props.id)
+ lemonToast.success('Knowledge source deleted')
+ router.actions.push(urls.businessKnowledge())
+ } catch (error: any) {
+ lemonToast.error(error?.detail || 'Could not delete the source.')
+ } finally {
+ actions.deleteSourceDone()
+ }
+ },
+ refreshSource: async () => {
+ try {
+ const updated = await refreshSource(props.id)
+ if (updated.last_refresh_status === 'not_modified') {
+ lemonToast.info(`"${updated.name}" is already up to date`)
+ } else {
+ lemonToast.success(`"${updated.name}" refreshed`)
+ }
+ actions.loadSource()
+ } catch (error: any) {
+ lemonToast.error(
+ error?.detail || error?.data?.detail || error?.data?.url?.[0] || 'Could not refresh the source.'
+ )
+ } finally {
+ actions.refreshSourceDone()
+ }
+ },
+ })),
+ selectors({
+ breadcrumbs: [
+ (s) => [s.source],
+ (source: KnowledgeSource | null): Breadcrumb[] => [
+ {
+ key: Scene.BusinessKnowledge,
+ name: 'Business knowledge',
+ path: urls.businessKnowledge(),
+ iconType: 'conversations',
+ },
+ {
+ key: Scene.BusinessKnowledgeSource,
+ name: source?.name ?? 'Knowledge source',
+ iconType: 'conversations',
+ },
+ ],
+ ],
+ isSourceTextReady: [
+ (s) => [s.source, s.sourceText, s.sourceTextFailed],
+ (
+ source: KnowledgeSource | null,
+ sourceText: { id: string; text: string },
+ sourceTextFailed: boolean
+ ): boolean => hasLoadedSourceText(source, sourceText) || sourceTextFailed,
+ ],
+ }),
+ afterMount(({ actions }) => {
+ actions.loadSource()
+ }),
+])
diff --git a/products/business_knowledge/frontend/scenes/sourceFormUtils.ts b/products/business_knowledge/frontend/scenes/sourceFormUtils.ts
new file mode 100644
index 000000000000..b82dbd8ec6af
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/sourceFormUtils.ts
@@ -0,0 +1,106 @@
+import type { RefreshIntervalValue } from '../api'
+import type { KnowledgeSourceApi } from '../generated/api.schemas'
+
+export type KnowledgeSource = KnowledgeSourceApi
+export type CrawlMode = 'single' | 'sitemap' | 'same_origin' | 'github_repo'
+
+export interface TextSourceFormValues {
+ name: string
+ text: string
+ always_include: boolean
+}
+
+export interface UrlSourceFormValues {
+ name: string
+ url: string
+ crawl_mode: CrawlMode
+ // Comma/newline-separated globs — split server-side. Keeping the form
+ // state as a plain string is much easier than a list-of-inputs widget.
+ include_globs: string
+ exclude_globs: string
+ max_pages: number
+ max_depth: number
+ // Background auto-refresh cadence, sent on both create and edit.
+ refresh_interval: RefreshIntervalValue
+ always_include: boolean
+}
+
+export const MAX_TEXT_BYTES = 1_000_000
+
+export const DEFAULT_URL_SOURCE_FORM: UrlSourceFormValues = {
+ name: '',
+ url: '',
+ crawl_mode: 'single',
+ include_globs: '',
+ exclude_globs: '',
+ max_pages: 50,
+ max_depth: 2,
+ refresh_interval: 'manual',
+ always_include: false,
+}
+
+export function validateText({ name, text }: TextSourceFormValues): {
+ name: string | undefined
+ text: string | undefined
+} {
+ return {
+ name: !name.trim() ? 'Give the source a short name' : undefined,
+ text: !text.trim()
+ ? 'Paste some content'
+ : new Blob([text]).size > MAX_TEXT_BYTES
+ ? 'Text exceeds the 1 MB cap. Split it into smaller sources'
+ : undefined,
+ }
+}
+
+export function validateUrl({ name, url, max_pages }: UrlSourceFormValues): {
+ name: string | undefined
+ url: string | undefined
+ max_pages: string | undefined
+} {
+ let urlError: string | undefined
+ if (!url.trim()) {
+ urlError = 'Paste a public HTTPS URL'
+ } else {
+ try {
+ const parsed = new URL(url)
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ urlError = 'Only http(s) URLs are allowed'
+ }
+ } catch {
+ urlError = 'Not a valid URL'
+ }
+ }
+ return {
+ name: !name.trim() ? 'Give the source a short name' : undefined,
+ url: urlError,
+ max_pages: max_pages < 1 || max_pages > 500 ? 'max_pages must be between 1 and 500' : undefined,
+ }
+}
+
+export function splitGlobs(raw: string): string[] {
+ return raw
+ .split(/[\n,]/)
+ .map((s) => s.trim())
+ .filter(Boolean)
+}
+
+export 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,
+ }
+}
diff --git a/products/business_knowledge/manifest.tsx b/products/business_knowledge/manifest.tsx
index fc602e0f726a..eeda35be1f1a 100644
--- a/products/business_knowledge/manifest.tsx
+++ b/products/business_knowledge/manifest.tsx
@@ -28,15 +28,25 @@ export const manifest: ProductManifest = {
projectBased: true,
iconType: 'conversations',
},
+ BusinessKnowledgeSource: {
+ name: 'Knowledge source',
+ import: () => import('./frontend/scenes/KnowledgeSourceScene'),
+ projectBased: true,
+ activityScope: 'KnowledgeSource',
+ iconType: 'conversations',
+ },
},
routes: {
'/business-knowledge': ['BusinessKnowledge', 'businessKnowledge'],
+ // Static sibling must stay above :id so kea-router does not treat "settings" as an id.
'/business-knowledge/settings': ['BusinessKnowledgeSettings', 'businessKnowledgeSettings'],
+ '/business-knowledge/:id': ['BusinessKnowledgeSource', 'businessKnowledgeSource'],
},
redirects: {},
urls: {
businessKnowledge: (): string => '/business-knowledge',
businessKnowledgeSettings: (): string => '/business-knowledge/settings',
+ businessKnowledgeSource: (id: string): string => `/business-knowledge/${id}`,
},
fileSystemTypes: {},
treeItemsNew: [],
diff --git a/products/business_knowledge/mcp/tools.yaml b/products/business_knowledge/mcp/tools.yaml
index 453ab793c85d..971ff97ce588 100644
--- a/products/business_knowledge/mcp/tools.yaml
+++ b/products/business_knowledge/mcp/tools.yaml
@@ -72,6 +72,7 @@ tools:
readOnly: true
destructive: false
idempotent: true
+ enrich_url: '{id}'
list: true
title: List business knowledge sources
description: >
@@ -122,6 +123,7 @@ tools:
readOnly: true
destructive: false
idempotent: true
+ enrich_url: '{id}'
title: Get business knowledge source
description: >
Get a single business knowledge source by ID, including processing status, document/chunk counts, and
diff --git a/services/mcp/src/tools/generated/business_knowledge.ts b/services/mcp/src/tools/generated/business_knowledge.ts
index 458501a14caf..09b082b0a0c5 100644
--- a/services/mcp/src/tools/generated/business_knowledge.ts
+++ b/services/mcp/src/tools/generated/business_knowledge.ts
@@ -110,7 +110,18 @@ const businessKnowledgeSourcesList = (): ToolBase<
])
),
} as typeof result
- return await withPostHogUrl(context, filtered, '/business-knowledge')
+ return await withPostHogUrl(
+ context,
+ {
+ ...filtered,
+ results: await Promise.all(
+ (filtered.results ?? []).map((item) =>
+ withPostHogUrl(context, item, `/business-knowledge/${item.id}`)
+ )
+ ),
+ },
+ '/business-knowledge'
+ )
},
})
@@ -159,7 +170,7 @@ const BusinessKnowledgeSourcesRetrieveSchema = () => {
const businessKnowledgeSourcesRetrieve = (): ToolBase<
ReturnType<typeof BusinessKnowledgeSourcesRetrieveSchema>,
- Schemas.KnowledgeSource
+ WithPostHogUrl<Schemas.KnowledgeSource>
> => ({
name: 'business-knowledge-sources-retrieve',
schema: BusinessKnowledgeSourcesRetrieveSchema(),
@@ -169,7 +180,7 @@ const businessKnowledgeSourcesRetrieve = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/business_knowledge/sources/${encodeURIComponent(String(params.id))}/`,
})
- return result
+ return await withPostHogUrl(context, result, `/business-knowledge/${result.id}`)
},
})
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index 66a530c18edd..60b8ef53566b 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -264,6 +264,11 @@
"params": [],
"scope": "project"
},
+ "businessKnowledgeSource": {
+ "template": "/business-knowledge/{id}",
+ "params": ["id"],
+ "scope": "project"
+ },
"canvas": {
"template": "/canvas",
"params": [],
diff --git a/services/mcp/tests/tools/businessKnowledge.integration.test.ts b/services/mcp/tests/tools/businessKnowledge.integration.test.ts
index 38c08b89c87d..99e30bb50c08 100644
--- a/services/mcp/tests/tools/businessKnowledge.integration.test.ts
+++ b/services/mcp/tests/tools/businessKnowledge.integration.test.ts
@@ -83,7 +83,7 @@ describe('Business knowledge sources', { concurrent: false }, () => {
expect(retrieved.id).toBe(source.id)
expect(retrieved.name).toBe(name)
expect(retrieved.source_type).toBe('text')
- expect(retrieved).not.toHaveProperty('_posthogUrl')
+ expect(retrieved._posthogUrl).toContain(`/business-knowledge/${source.id}`)
})
})
@@ -134,6 +134,7 @@ describe('Business knowledge sources', { concurrent: false }, () => {
expect(source).toHaveProperty('name')
expect(source).toHaveProperty('source_type')
expect(source).toHaveProperty('status')
+ expect(source._posthogUrl).toContain(`/business-knowledge/${source.id}`)
const unexpectedFields = ['documents', 'source_text', 'team']
for (const field of unexpectedFields) {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
index 4c9281ae96a7..f734f25a2582 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -13,7 +13,7 @@
"type": "object"
},
"url": {
- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/business-knowledge/settings\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
"type": "string"
}
},