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): frontend part (#58332)

Alex V5e31ac548a51
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 4e86067aedbc..067bb57d84b0 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -51,6 +51,7 @@ export const productScenes: Record<string, () => Promise<any>> = {
Actions: () => import('../../products/actions/frontend/pages/Actions'),
Action: () => import('../../products/actions/frontend/pages/Action'),
NewAction: () => import('../../products/actions/frontend/pages/Action'),
+ BusinessKnowledge: () => import('../../products/business_knowledge/frontend/scenes/BusinessKnowledgeScene'),
Transformations: () => import('../../frontend/src/scenes/data-pipelines/TransformationsScene'),
SupportTickets: () => import('../../products/conversations/frontend/scenes/tickets/SupportTicketsScene'),
SupportTicketDetail: () => import('../../products/conversations/frontend/scenes/ticket/SupportTicketScene'),
@@ -142,6 +143,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/data-management/actions/new': ['NewAction', 'actionNew'],
'/data-management/actions/:id': ['Action', 'action'],
'/data-management/actions/new/': ['NewAction', 'actionNew'],
+ '/business-knowledge': ['BusinessKnowledge', 'businessKnowledge'],
'/transformations': ['Transformations', 'transformations'],
'/support/tickets': ['SupportTickets', 'supportTickets'],
'/support/tickets/:ticketId': ['SupportTicketDetail', 'supportTicketDetail'],
@@ -308,6 +310,13 @@ export const productConfiguration: Record<string, any> = {
},
Action: { name: 'Action', projectBased: true, activityScope: 'Action', iconType: 'action' },
NewAction: { name: 'New Action', projectBased: true, activityScope: 'Action', iconType: 'action' },
+ BusinessKnowledge: {
+ name: 'Business knowledge',
+ projectBased: true,
+ activityScope: 'KnowledgeSource',
+ description:
+ 'Upload text, public URLs, or files your AI support agent can cite when answering customer tickets.',
+ },
Transformations: {
projectBased: true,
name: 'Transformations',
@@ -619,6 +628,7 @@ export const productUrls = {
},
action: (id: string | number): string => `/data-management/actions/${id}`,
actions: (): string => '/data-management/actions',
+ businessKnowledge: (): string => '/business-knowledge',
transformations: (): string => '/transformations',
cohort: (id: string | number): string => `/cohorts/${id}`,
cohorts: (): string => '/cohorts',
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index 42644f8d62e6..0c836d64fecc 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -82,6 +82,7 @@ export enum Scene {
StripeConfirmInstall = 'StripeConfirmInstall',
IngestionWarnings = 'IngestionWarnings',
InviteSignup = 'InviteSignup',
+ BusinessKnowledge = 'BusinessKnowledge',
LegacyPlugin = 'LegacyPlugin',
LegalDocuments = 'LegalDocuments',
LegalDocumentNew = 'LegalDocumentNew',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 522432d7411a..80933b937a21 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -275,7 +275,7 @@ importers:
version: 3.12.1
jest:
specifier: 'catalog:'
oxfmt:
specifier: 'catalog:'
version: 0.35.0
@@ -445,10 +445,10 @@ importers:
'@storybook/react-webpack5':
specifier: ^7.6.4
'@storybook/test-runner':
specifier: ^0.16.0
+ version: 0.16.0(@types/[email protected])([email protected])
'@storybook/theming':
specifier: ^7.6.4
@@ -499,7 +499,7 @@ importers:
version: 2.0.0([email protected])
webpack:
specifier: ^5.88.2
+ version: 5.88.2(@swc/[email protected])([email protected])
webpack-cli:
specifier: ^5.1.4
version: 5.1.4([email protected])
@@ -1297,7 +1297,7 @@ importers:
version: 29.7.0
jest-image-snapshot:
specifier: ^6.1.0
+ version: 6.4.0([email protected](@types/[email protected]))
kea-typegen:
specifier: 3.6.2-leakfix.5
version: 3.6.2-leakfix.5([email protected])
@@ -1792,7 +1792,7 @@ importers:
'@storybook/test-runner':
specifier: ^0.16.0
+ version: 0.16.0(@types/[email protected])([email protected])
'@storybook/theming':
specifier: ^7.6.20
@@ -1813,7 +1813,7 @@ importers:
jest-image-snapshot:
specifier: ^6.4.0
+ version: 6.4.0([email protected](@types/[email protected]))
storybook:
specifier: ^7.6.4
version: 7.6.4([email protected])
@@ -2068,7 +2068,35 @@ importers:
products/batch_exports: {}
- products/business_knowledge: {}
+ products/business_knowledge:
+ dependencies:
+ '@posthog/icons':
+ specifier: '*'
+ '@posthog/lemon-ui':
+ specifier: '*'
+ '@types/react':
+ specifier: 18.3.27
+ version: 18.3.27
+ kea:
+ specifier: 'catalog:'
+ version: 4.0.0-pre.5([email protected])
+ kea-forms:
+ specifier: 'catalog:'
+ kea-loaders:
+ specifier: 'catalog:'
+ kea-router:
+ specifier: 'catalog:'
+ posthog-js:
+ specifier: 'catalog:'
+ version: 1.373.2
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
products/cdp: {}
@@ -29347,41 +29375,6 @@ snapshots:
- ts-node
- utf-8-validate
- dependencies:
- '@jest/console': 29.7.0
- '@jest/reporters': 29.7.0
- '@jest/test-result': 29.7.0
- '@jest/transform': 29.7.0
- '@jest/types': 29.6.3
- '@types/node': 22.18.8
- ansi-escapes: 4.3.2
- chalk: 4.1.2
- ci-info: 3.8.0
- exit: 0.1.2
- graceful-fs: 4.2.11
- jest-changed-files: 29.7.0
- jest-haste-map: 29.7.0
- jest-message-util: 29.7.0
- jest-regex-util: 29.6.3
- jest-resolve: 29.7.0
- jest-resolve-dependencies: 29.7.0
- jest-runner: 29.7.0
- jest-runtime: 29.7.0
- jest-snapshot: 29.7.0
- jest-util: 29.7.0
- jest-validate: 29.7.0
- jest-watcher: 29.7.0
- micromatch: 4.0.8
- pretty-format: 29.7.0
- slash: 3.0.0
- strip-ansi: 6.0.1
- transitivePeerDependencies:
- - babel-plugin-macros
- - supports-color
- - ts-node
-
dependencies:
'@jest/console': 29.7.0
@@ -32054,7 +32047,7 @@ snapshots:
react-refresh: 0.14.0
schema-utils: 3.3.0
source-map: 0.7.6
+ webpack: 5.88.2(@swc/[email protected])([email protected])
optionalDependencies:
type-fest: 4.41.0
webpack-hot-middleware: 2.25.4
@@ -34089,7 +34082,7 @@ snapshots:
- encoding
- supports-color
dependencies:
'@babel/core': 7.29.0
'@storybook/channels': 7.6.4
@@ -34119,12 +34112,12 @@ snapshots:
semver: 7.7.4
style-loader: 3.3.3([email protected])
swc-loader: 0.2.3(@swc/[email protected])([email protected])
- terser-webpack-plugin: 5.3.9(@swc/[email protected])([email protected])([email protected])
+ terser-webpack-plugin: 5.3.9(@swc/[email protected])([email protected])
ts-dedent: 2.2.0
url: 0.11.1
util: 0.12.5
util-deprecate: 1.0.2
+ webpack: 5.88.2(@swc/[email protected])([email protected])
webpack-dev-middleware: 6.1.1([email protected])
webpack-hot-middleware: 2.25.4
webpack-virtual-modules: 0.5.0
@@ -34195,7 +34188,7 @@ snapshots:
get-port: 5.1.1
giget: 1.1.2
globby: 11.1.0
- jscodeshift: 0.15.1(@babel/[email protected](@babel/[email protected]))
+ jscodeshift: 0.15.1(@babel/[email protected](@babel/[email protected]))
leven: 3.1.0
ora: 5.4.1
prettier: 2.8.8
@@ -34238,7 +34231,7 @@ snapshots:
'@types/cross-spawn': 6.0.2
cross-spawn: 7.0.6
globby: 11.1.0
- jscodeshift: 0.15.1(@babel/[email protected](@babel/[email protected]))
+ jscodeshift: 0.15.1(@babel/[email protected](@babel/[email protected]))
lodash: 4.18.1
prettier: 2.8.8
recast: 0.23.11
@@ -34530,7 +34523,7 @@ snapshots:
'@storybook/[email protected]': {}
dependencies:
'@babel/preset-flow': 7.23.3(@babel/[email protected])
'@babel/preset-react': 7.23.3(@babel/[email protected])
@@ -34550,7 +34543,7 @@ snapshots:
react-dom: 18.3.1([email protected])
react-refresh: 0.14.0
semver: 7.7.4
+ webpack: 5.88.2(@swc/[email protected])([email protected])
optionalDependencies:
'@babel/core': 7.26.0
typescript: 5.9.3
@@ -34633,7 +34626,7 @@ snapshots:
react-docgen-typescript: 2.2.2([email protected])
tslib: 2.8.1
typescript: 5.9.3
+ webpack: 5.88.2(@swc/[email protected])([email protected])
transitivePeerDependencies:
- supports-color
@@ -34667,10 +34660,10 @@ snapshots:
- typescript
- vite-plugin-glimmerx
dependencies:
+ '@storybook/builder-webpack5': 7.6.4([email protected])([email protected])([email protected])
'@types/node': 18.19.130
react: 18.3.1
@@ -34789,7 +34782,7 @@ snapshots:
- encoding
- supports-color
dependencies:
'@babel/core': 7.29.0
'@babel/generator': 7.29.1
@@ -34810,10 +34803,10 @@ snapshots:
jest-circus: 29.7.0
jest-environment-node: 29.7.0
jest-junit: 16.0.0
jest-runner: 29.7.0
jest-serializer-html: 7.1.0
+ jest-watch-typeahead: 2.2.2([email protected])
node-fetch: 2.7.0([email protected])
playwright: 1.45.0
read-pkg-up: 7.0.1
@@ -37072,17 +37065,17 @@ snapshots:
dependencies:
+ webpack: 5.88.2(@swc/[email protected])([email protected])
webpack-cli: 5.1.4([email protected])
dependencies:
+ webpack: 5.88.2(@swc/[email protected])([email protected])
webpack-cli: 5.1.4([email protected])
dependencies:
+ webpack: 5.88.2(@swc/[email protected])([email protected])
webpack-cli: 5.1.4([email protected])
'@xmldom/[email protected]': {}
@@ -37689,14 +37682,14 @@ snapshots:
loader-utils: 2.0.4
make-dir: 3.1.0
schema-utils: 2.7.1
+ webpack: 5.88.2(@swc/[email protected])([email protected])
dependencies:
'@babel/core': 7.29.0
find-cache-dir: 4.0.0
schema-utils: 4.2.0
+ webpack: 5.88.2(@swc/[email protected])([email protected])
@@ -38766,21 +38759,6 @@ snapshots:
safe-buffer: 5.2.1
sha.js: 2.4.12
- dependencies:
- '@jest/types': 29.6.3
- chalk: 4.1.2
- exit: 0.1.2
- graceful-fs: 4.2.11
- jest-util: 29.7.0
- prompts: 2.4.2
- transitivePeerDependencies:
- - '@types/node'
- - babel-plugin-macros
- - supports-color
- - ts-node
-
dependencies:
'@jest/types': 29.6.3
@@ -38893,7 +38871,7 @@ snapshots:
postcss-value-parser: 4.2.0
schema-utils: 2.7.1
semver: 6.3.1
+ webpack: 5.88.2(@swc/[email protected])([email protected])
dependencies:
@@ -38905,7 +38883,7 @@ snapshots:
postcss-modules-values: 4.0.0([email protected])
postcss-value-parser: 4.2.0
semver: 7.7.4
+ webpack: 5.88.2(@swc/[email protected])([email protected])
dependencies:
@@ -40671,7 +40649,7 @@ snapshots:
dependencies:
loader-utils: 2.0.4
schema-utils: 3.3.0
+ webpack: 5.88.2(@swc/[email protected])([email protected])
dependencies:
@@ -40815,7 +40793,7 @@ snapshots:
semver: 7.7.4
tapable: 2.3.0
typescript: 5.9.3
+ webpack: 5.88.2(@swc/[email protected])([email protected])
dependencies:
@@ -41494,7 +41472,7 @@ snapshots:
dependencies:
html-webpack-plugin: 5.5.3([email protected])
+ webpack: 5.88.2(@swc/[email protected])([email protected])
dependencies:
@@ -41503,7 +41481,7 @@ snapshots:
lodash: 4.17.21
pretty-error: 4.0.0
tapable: 2.2.1
+ webpack: 5.88.2(@swc/[email protected])([email protected])
dependencies:
@@ -42274,25 +42252,6 @@ snapshots:
- ts-node
- utf-8-validate
- dependencies:
- '@jest/test-result': 29.7.0
- '@jest/types': 29.6.3
- chalk: 4.1.2
- exit: 0.1.2
- import-local: 3.2.0
- jest-util: 29.7.0
- jest-validate: 29.7.0
- yargs: 17.7.2
- transitivePeerDependencies:
- - '@types/node'
- - babel-plugin-macros
- - supports-color
- - ts-node
-
dependencies:
@@ -42365,37 +42324,6 @@ snapshots:
- supports-color
- utf-8-validate
- dependencies:
- '@babel/core': 7.29.0
- '@jest/test-sequencer': 29.7.0
- '@jest/types': 29.6.3
- babel-jest: 29.7.0(@babel/[email protected])
- chalk: 4.1.2
- ci-info: 3.8.0
- deepmerge: 4.3.1
- glob: 7.2.3
- graceful-fs: 4.2.11
- jest-circus: 29.7.0
- jest-environment-node: 29.7.0
- jest-get-type: 29.6.3
- jest-regex-util: 29.6.3
- jest-resolve: 29.7.0
- jest-runner: 29.7.0
- jest-util: 29.7.0
- jest-validate: 29.7.0
- micromatch: 4.0.8
- parse-json: 5.2.0
- pretty-format: 29.7.0
- slash: 3.0.0
- strip-json-comments: 3.1.1
- optionalDependencies:
- '@types/node': 22.18.8
- transitivePeerDependencies:
- - babel-plugin-macros
- - supports-color
-
dependencies:
'@babel/core': 7.29.0
@@ -42646,7 +42574,7 @@ snapshots:
optionalDependencies:
fsevents: 2.3.3
dependencies:
chalk: 4.1.2
get-stdin: 5.0.1
@@ -42803,7 +42731,7 @@ snapshots:
'@types/node': 22.18.8
jest-util: 30.0.5
dependencies:
expect-playwright: 0.8.0
@@ -43226,7 +43154,7 @@ snapshots:
leven: 3.1.0
pretty-format: 30.0.5
dependencies:
ansi-escapes: 6.0.0
chalk: 5.6.2
@@ -43302,18 +43230,6 @@ snapshots:
- ts-node
- utf-8-validate
- dependencies:
- '@jest/types': 29.6.3
- import-local: 3.2.0
- transitivePeerDependencies:
- - '@types/node'
- - babel-plugin-macros
- - supports-color
- - ts-node
-
dependencies:
@@ -43384,7 +43300,7 @@ snapshots:
dependencies:
'@babel/core': 7.29.0
'@babel/parser': 7.29.2
@@ -43407,7 +43323,7 @@ snapshots:
temp: 0.8.4
write-file-atomic: 2.4.3
optionalDependencies:
- '@babel/preset-env': 7.23.5(@babel/[email protected])
+ '@babel/preset-env': 7.23.5(@babel/[email protected])
transitivePeerDependencies:
- supports-color
@@ -43681,7 +43597,7 @@ snapshots:
less: 4.2.2
loader-utils: 2.0.4
schema-utils: 3.3.0
+ webpack: 5.88.2(@swc/[email protected])([email protected])
dependencies:
@@ -46177,7 +46093,7 @@ snapshots:
postcss: 8.5.6
schema-utils: 3.3.0
semver: 7.7.0
+ webpack: 5.88.2(@swc/[email protected])([email protected])
dependencies:
@@ -47167,7 +47083,7 @@ snapshots:
dependencies:
loader-utils: 2.0.4
schema-utils: 3.3.0
+ webpack: 5.88.2(@swc/[email protected])([email protected])
dependencies:
@@ -48304,7 +48220,7 @@ snapshots:
neo-async: 2.6.2
schema-utils: 3.3.0
semver: 7.7.0
+ webpack: 5.88.2(@swc/[email protected])([email protected])
optionalDependencies:
sass: 1.56.0
@@ -49012,11 +48928,11 @@ snapshots:
dependencies:
loader-utils: 2.0.4
schema-utils: 3.3.0
+ webpack: 5.88.2(@swc/[email protected])([email protected])
dependencies:
+ webpack: 5.88.2(@swc/[email protected])([email protected])
@@ -49220,7 +49136,7 @@ snapshots:
dependencies:
'@swc/core': 1.15.18
+ webpack: 5.88.2(@swc/[email protected])([email protected])
@@ -49414,17 +49330,16 @@ snapshots:
'@swc/core': 1.15.18
esbuild: 0.27.7
dependencies:
'@jridgewell/trace-mapping': 0.3.29
jest-worker: 27.5.1
schema-utils: 3.3.0
serialize-javascript: 6.0.1
terser: 5.19.1
+ webpack: 5.88.2(@swc/[email protected])([email protected])
optionalDependencies:
'@swc/core': 1.15.18
- esbuild: 0.18.20
dependencies:
@@ -49664,27 +49579,6 @@ snapshots:
tslib: 2.8.1
typescript: 5.9.3
- dependencies:
- '@cspotcode/source-map-support': 0.8.1
- '@tsconfig/node10': 1.0.9
- '@tsconfig/node12': 1.0.11
- '@tsconfig/node14': 1.0.3
- '@tsconfig/node16': 1.0.3
- '@types/node': 22.18.8
- acorn: 8.15.0
- acorn-walk: 8.3.2
- arg: 4.1.3
- create-require: 1.1.1
- diff: 4.0.2
- make-error: 1.3.6
- typescript: 5.9.3
- v8-compile-cache-lib: 3.0.1
- yn: 3.1.1
- optionalDependencies:
- '@swc/core': 1.11.4
- optional: true
-
dependencies:
'@cspotcode/source-map-support': 0.8.1
@@ -50620,7 +50514,7 @@ snapshots:
import-local: 3.1.0
interpret: 3.1.1
rechoir: 0.8.0
+ webpack: 5.88.2(@swc/[email protected])([email protected])
webpack-merge: 5.8.0
@@ -50631,7 +50525,7 @@ snapshots:
range-parser: 1.2.1
schema-utils: 4.2.0
optionalDependencies:
+ webpack: 5.88.2(@swc/[email protected])([email protected])
dependencies:
@@ -50682,7 +50576,7 @@ snapshots:
- esbuild
- uglify-js
dependencies:
'@types/eslint-scope': 3.7.4
'@types/estree': 1.0.1
@@ -50705,7 +50599,7 @@ snapshots:
neo-async: 2.6.2
schema-utils: 3.3.0
tapable: 2.2.1
- terser-webpack-plugin: 5.3.9(@swc/[email protected])([email protected])([email protected])
+ terser-webpack-plugin: 5.3.9(@swc/[email protected])([email protected])
watchpack: 2.4.0
webpack-sources: 3.2.3
optionalDependencies:
diff --git a/products/business_knowledge/frontend/api.ts b/products/business_knowledge/frontend/api.ts
new file mode 100644
index 000000000000..c40ef6b2ecd1
--- /dev/null
+++ b/products/business_knowledge/frontend/api.ts
@@ -0,0 +1,81 @@
+import { getCurrentTeamId } from 'lib/utils/getAppContext'
+
+import { apiMutator } from '../../../frontend/src/lib/api-orval-mutator'
+import {
+ businessKnowledgeSourcesCreate,
+ businessKnowledgeSourcesDestroy,
+ businessKnowledgeSourcesList,
+ businessKnowledgeSourcesPartialUpdate,
+ businessKnowledgeSourcesRefreshCreate,
+ businessKnowledgeSourcesTextRetrieve,
+} from './generated/api'
+import type { CrawlModeEnumApi, KnowledgeSourceApi } from './generated/api.schemas'
+
+export type { KnowledgeSourceApi as KnowledgeSourceDTOApi }
+
+// TODO: replace with generated types once the backend exposes URL source serializers
+export interface CreateUrlSourcePayload {
+ name: string
+ url: string
+ source_type: 'url'
+ crawl_mode: CrawlModeEnumApi
+ include_globs?: string[]
+ exclude_globs?: string[]
+ max_pages?: number
+ max_depth?: number
+}
+
+export interface UpdateSourcePayload {
+ name?: string
+ text?: string
+ url?: string
+ crawl_mode?: CrawlModeEnumApi
+ include_globs?: string[]
+ exclude_globs?: string[]
+ max_pages?: number
+ max_depth?: number
+}
+
+export async function listSources(): Promise<KnowledgeSourceApi[]> {
+ const response = await businessKnowledgeSourcesList(String(getCurrentTeamId()), { limit: 1000 })
+ return response.results
+}
+
+export async function getSourceText(id: string): Promise<{ id: string; text: string }> {
+ const response = await businessKnowledgeSourcesTextRetrieve(String(getCurrentTeamId()), id)
+ return { id, text: response.text ?? '' }
+}
+
+export async function createTextSource(name: string, text: string): Promise<KnowledgeSourceApi> {
+ return await businessKnowledgeSourcesCreate(String(getCurrentTeamId()), { name, text })
+}
+
+export async function createUrlSource(payload: CreateUrlSourcePayload): Promise<KnowledgeSourceApi> {
+ return await businessKnowledgeSourcesCreate(
+ String(getCurrentTeamId()),
+ payload as unknown as Parameters<typeof businessKnowledgeSourcesCreate>[1]
+ )
+}
+
+export async function createFileSource(formData: FormData): Promise<KnowledgeSourceApi> {
+ return await apiMutator<KnowledgeSourceApi>(`/api/projects/${getCurrentTeamId()}/business_knowledge/sources/`, {
+ method: 'POST',
+ body: formData,
+ })
+}
+
+export async function updateSource(id: string, payload: UpdateSourcePayload): Promise<KnowledgeSourceApi> {
+ return await businessKnowledgeSourcesPartialUpdate(
+ String(getCurrentTeamId()),
+ id,
+ payload as Parameters<typeof businessKnowledgeSourcesPartialUpdate>[2]
+ )
+}
+
+export async function deleteSource(id: string): Promise<void> {
+ await businessKnowledgeSourcesDestroy(String(getCurrentTeamId()), id)
+}
+
+export async function refreshSource(id: string): Promise<KnowledgeSourceApi> {
+ return await businessKnowledgeSourcesRefreshCreate(String(getCurrentTeamId()), id)
+}
diff --git a/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx
new file mode 100644
index 000000000000..5a8ac8b2f61c
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/BusinessKnowledgeScene.tsx
@@ -0,0 +1,494 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { IconBook, IconPencil, IconPlusSmall, IconRefresh, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonModal, LemonSelect, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'
+
+import { NotFound } from 'lib/components/NotFound'
+import { TZLabel } from 'lib/components/TZLabel'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
+import { SceneExport } from 'scenes/sceneTypes'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+
+import { CreateTab, KnowledgeSource, businessKnowledgeLogic } from './businessKnowledgeLogic'
+
+export const scene: SceneExport = {
+ component: BusinessKnowledgeScene,
+ logic: businessKnowledgeLogic,
+}
+
+function StatusTag({ status }: { status: KnowledgeSource['status'] }): JSX.Element {
+ const variant =
+ status === 'ready' ? 'success' : status === 'error' ? 'danger' : status === 'processing' ? 'warning' : 'muted'
+ return <LemonTag type={variant}>{status}</LemonTag>
+}
+
+function CrawlModeHelp(): JSX.Element {
+ const { urlSource } = useValues(businessKnowledgeLogic)
+ if (urlSource.crawl_mode === 'single') {
+ return (
+ <p className="text-xs text-muted">
+ Fetch this URL once and index its main text. Use the refresh button on the row to re-fetch.
+ </p>
+ )
+ }
+ if (urlSource.crawl_mode === 'sitemap') {
+ return (
+ <p className="text-xs text-muted">
+ Read sitemap.xml at this URL (or <code>/sitemap.xml</code> at its origin) and index each listed page.
+ Scheduled refresh is Stage 5.
+ </p>
+ )
+ }
+ return (
+ <p className="text-xs text-muted">
+ BFS-crawl from this URL staying on the same scheme + host + port. Honors robots.txt.
+ </p>
+ )
+}
+
+function CrawlConfigFields({ crawlMode }: { crawlMode: string }): JSX.Element | null {
+ if (crawlMode === 'single') {
+ return null
+ }
+ return (
+ <>
+ <LemonField
+ name="include_globs"
+ label="Include globs"
+ info="URL path patterns to include. One per line or comma-separated. Empty = include everything."
+ >
+ <LemonTextArea minRows={2} placeholder={'/docs/*\n/handbook/*'} />
+ </LemonField>
+ <LemonField
+ name="exclude_globs"
+ label="Exclude globs"
+ info="URL path patterns to exclude. Applied after include."
+ >
+ <LemonTextArea minRows={2} placeholder="/docs/private/*" />
+ </LemonField>
+ <div className="flex gap-2">
+ <LemonField name="max_pages" label="Max pages" className="flex-1">
+ <LemonInput type="number" min={1} max={500} />
+ </LemonField>
+ {crawlMode === 'same_origin' && (
+ <LemonField name="max_depth" label="Max depth" className="flex-1">
+ <LemonInput type="number" min={0} max={5} />
+ </LemonField>
+ )}
+ </div>
+ </>
+ )
+}
+
+function RefreshStatusCell({ source }: { source: KnowledgeSource }): JSX.Element | null {
+ if (source.source_type !== 'url') {
+ return null
+ }
+ if (!source.last_refresh_at) {
+ return <span className="text-muted">—</span>
+ }
+ return (
+ <div>
+ <TZLabel time={source.last_refresh_at} />
+ {source.last_refresh_status === 'error' ? (
+ <LemonTag type="danger" title={source.last_refresh_error || undefined}>
+ refresh failed
+ </LemonTag>
+ ) : null}
+ </div>
+ )
+}
+
+export function BusinessKnowledgeScene(): JSX.Element {
+ const isEnabled = useFeatureFlag('PRODUCT_BUSINESS_KNOWLEDGE')
+ const {
+ sources,
+ sourcesLoading,
+ isCreateModalOpen,
+ isEditModalOpen,
+ createTab,
+ editingSource,
+ editingSourceTextLoading,
+ readyCount,
+ totalChunks,
+ isTextSourceSubmitting,
+ isUrlSourceSubmitting,
+ isFileSourceSubmitting,
+ isEditSourceSubmitting,
+ isEditUrlSourceSubmitting,
+ urlSource,
+ editUrlSource,
+ refreshingIds,
+ } = useValues(businessKnowledgeLogic)
+ const {
+ openCreateModal,
+ closeCreateModal,
+ setCreateTab,
+ openEditModal,
+ closeEditModal,
+ deleteSource,
+ refreshSource,
+ submitTextSource,
+ submitUrlSource,
+ submitFileSource,
+ setFileSourceValue,
+ submitEditSource,
+ submitEditUrlSource,
+ } = useActions(businessKnowledgeLogic)
+
+ if (!isEnabled) {
+ return <NotFound object="Business knowledge" caption="This feature is not enabled for your project." />
+ }
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name="Business knowledge"
+ description="Upload text, public URLs, or files your AI support agent can cite when answering customer tickets."
+ resourceType={{ type: 'default_icon_type', forceIcon: <IconBook /> }}
+ actions={
+ <LemonButton type="primary" icon={<IconPlusSmall />} onClick={openCreateModal}>
+ Add source
+ </LemonButton>
+ }
+ />
+
+ <div className="flex gap-4 text-sm text-muted mb-2">
+ <span>{readyCount} ready</span>
+ <span>•</span>
+ <span>{totalChunks.toLocaleString()} chunks indexed</span>
+ </div>
+
+ <LemonTable<KnowledgeSource>
+ dataSource={sources}
+ loading={sourcesLoading}
+ rowKey={(row) => row.id}
+ onRow={(row) => ({
+ onClick: () => openEditModal(row),
+ style: { cursor: 'pointer' },
+ })}
+ columns={[
+ {
+ title: 'Name',
+ key: 'name',
+ render: (_, row) => (
+ <div className="flex flex-col">
+ <strong>{row.name}</strong>
+ {row.source_type === 'url' && row.source_url ? (
+ <Link
+ to={row.source_url}
+ target="_blank"
+ className="text-xs text-muted truncate"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {row.source_url}
+ </Link>
+ ) : row.source_type === 'file' && row.original_filename ? (
+ <span className="text-xs text-muted truncate">{row.original_filename}</span>
+ ) : null}
+ </div>
+ ),
+ },
+ {
+ title: 'Type',
+ key: 'source_type',
+ render: (_, row) => <LemonTag>{row.source_type}</LemonTag>,
+ },
+ {
+ title: 'Status',
+ key: 'status',
+ render: (_, row) => <StatusTag status={row.status} />,
+ },
+ {
+ title: 'Pages / chunks',
+ key: 'chunk_count',
+ render: (_, row) => {
+ const pages = row.document_count
+ return row.source_type === 'url' && row.crawl_mode && row.crawl_mode !== 'single'
+ ? `${pages.toLocaleString()} / ${row.chunk_count.toLocaleString()}`
+ : row.chunk_count.toLocaleString()
+ },
+ },
+ {
+ title: 'Added',
+ key: 'created_at',
+ render: (_, row) => <TZLabel time={row.created_at} />,
+ },
+ {
+ title: 'Last refresh',
+ key: 'last_refresh_at',
+ render: (_, row) => <RefreshStatusCell source={row} />,
+ },
+ {
+ title: '',
+ key: 'actions',
+ width: 0,
+ render: (_, row) => (
+ <div className="flex gap-1 justify-end">
+ {row.source_type === 'url' && (
+ <LemonButton
+ icon={<IconRefresh />}
+ size="small"
+ tooltip="Re-fetch and re-index this URL"
+ loading={refreshingIds.includes(row.id)}
+ onClick={(e) => {
+ e.stopPropagation()
+ refreshSource(row.id)
+ }}
+ />
+ )}
+ <LemonButton
+ icon={<IconPencil />}
+ size="small"
+ tooltip="Edit"
+ onClick={(e) => {
+ e.stopPropagation()
+ openEditModal(row)
+ }}
+ />
+ <LemonButton
+ icon={<IconTrash />}
+ status="danger"
+ size="small"
+ tooltip="Delete"
+ onClick={(e) => {
+ e.stopPropagation()
+ LemonDialog.open({
+ title: `Delete "${row.name}"?`,
+ description: 'Chunks will be removed.',
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => deleteSource(row.id),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }}
+ />
+ </div>
+ ),
+ },
+ ]}
+ emptyState="No knowledge sources yet. Click 'Add source' to index your first."
+ />
+
+ <LemonModal
+ isOpen={isCreateModalOpen}
+ onClose={closeCreateModal}
+ width={800}
+ title="Add to business knowledge"
+ footer={
+ <>
+ <LemonButton onClick={closeCreateModal}>Cancel</LemonButton>
+ {createTab === 'text' ? (
+ <LemonButton type="primary" loading={isTextSourceSubmitting} onClick={submitTextSource}>
+ Add
+ </LemonButton>
+ ) : createTab === 'url' ? (
+ <LemonButton type="primary" loading={isUrlSourceSubmitting} onClick={submitUrlSource}>
+ Fetch and index
+ </LemonButton>
+ ) : (
+ <LemonButton type="primary" loading={isFileSourceSubmitting} onClick={submitFileSource}>
+ Upload and index
+ </LemonButton>
+ )}
+ </>
+ }
+ >
+ <LemonTabs
+ activeKey={createTab}
+ onChange={(key) => setCreateTab(key as CreateTab)}
+ tabs={[
+ {
+ key: 'text',
+ label: 'Text',
+ content: (
+ <Form
+ logic={businessKnowledgeLogic}
+ formKey="textSource"
+ className="flex flex-col gap-2"
+ >
+ <LemonField name="name" label="Name">
+ <LemonInput placeholder="e.g. Refund policy" />
+ </LemonField>
+ <LemonField name="text" label="Content">
+ <LemonTextArea
+ placeholder="Paste FAQ, macros, or any text the support agent should be able to cite."
+ minRows={12}
+ />
+ </LemonField>
+ <p className="text-xs text-muted">
+ Text is chunked paragraph-by-paragraph and stored in Postgres. The support agent
+ can find it via SQL — no embeddings or vector DB in this stage.
+ </p>
+ </Form>
+ ),
+ },
+ {
+ key: 'url',
+ label: 'URL',
+ content: (
+ <Form
+ logic={businessKnowledgeLogic}
+ formKey="urlSource"
+ className="flex flex-col gap-2"
+ >
+ <LemonField name="name" label="Name">
+ <LemonInput placeholder="e.g. Product docs – Billing" />
+ </LemonField>
+ <LemonField name="url" label="Entry URL">
+ <LemonInput
+ type="url"
+ inputMode="url"
+ placeholder="https://docs.example.com/billing or https://example.com/sitemap.xml"
+ />
+ </LemonField>
+ <LemonField name="crawl_mode" label="Mode">
+ <LemonSelect
+ options={[
+ {
+ value: 'single',
+ label: 'Single page',
+ },
+ {
+ value: 'sitemap',
+ label: 'Sitemap.xml',
+ },
+ {
+ value: 'same_origin',
+ label: 'Same-origin crawl',
+ },
+ ]}
+ />
+ </LemonField>
+ <CrawlModeHelp />
+ <CrawlConfigFields crawlMode={urlSource.crawl_mode} />
+ </Form>
+ ),
+ },
+ {
+ key: 'file',
+ label: 'File',
+ content: (
+ <Form
+ logic={businessKnowledgeLogic}
+ formKey="fileSource"
+ className="flex flex-col gap-2"
+ >
+ <LemonField name="file" label="File">
+ <LemonFileInput
+ accept=".pdf,.docx,.md,.markdown,.txt,.csv"
+ multiple={false}
+ callToAction="Drop a file here or click to browse"
+ showUploadedFiles
+ onChange={(files) => {
+ const file = files[0] ?? null
+ setFileSourceValue('file', file)
+ if (file) {
+ const nameWithoutExt = file.name.replace(/\.[^.]+$/, '')
+ setFileSourceValue('name', nameWithoutExt)
+ }
+ }}
+ />
+ </LemonField>
+ <LemonField name="name" label="Name">
+ <LemonInput placeholder="Auto-filled from filename" />
+ </LemonField>
+ <p className="text-xs text-muted">
+ PDF, DOCX, Markdown, CSV, or plain text. Max 50 MB. The file is parsed into text
+ and chunked — the original file is not stored.
+ </p>
+ </Form>
+ ),
+ },
+ ]}
+ />
+ </LemonModal>
+
+ <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} />
+ <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>
+ )}
+ </Form>
+ )}
+ </LemonModal>
+ </SceneContent>
+ )
+}
diff --git a/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts
new file mode 100644
index 000000000000..1053d243833a
--- /dev/null
+++ b/products/business_knowledge/frontend/scenes/businessKnowledgeLogic.ts
@@ -0,0 +1,424 @@
+import { actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
+import { forms } from 'kea-forms'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import {
+ createFileSource,
+ createTextSource,
+ createUrlSource,
+ deleteSource,
+ getSourceText,
+ listSources,
+ refreshSource,
+ updateSource,
+} from '../api'
+import type { CreateUrlSourcePayload, UpdateSourcePayload } from '../api'
+import type { KnowledgeSourceApi } from '../generated/api.schemas'
+import type { businessKnowledgeLogicType } from './businessKnowledgeLogicType'
+
+export type KnowledgeSource = KnowledgeSourceApi
+export type CrawlMode = 'single' | 'sitemap' | 'same_origin' | 'github_repo'
+
+export interface TextSourceFormValues {
+ name: string
+ text: string
+}
+
+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
+}
+
+export interface FileSourceFormValues {
+ name: string
+ file: File | null
+}
+
+export type CreateTab = 'text' | 'url' | 'file'
+
+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)
+}
+
+export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([
+ path(['products', 'business_knowledge', 'businessKnowledgeLogic']),
+ actions({
+ openCreateModal: true,
+ closeCreateModal: true,
+ setCreateTab: (tab: CreateTab) => ({ tab }),
+ openEditModal: (source: KnowledgeSource) => ({ source }),
+ closeEditModal: true,
+ deleteSource: (id: string) => ({ id }),
+ refreshSource: (id: string) => ({ id }),
+ refreshSourceDone: (id: string) => ({ id }),
+ }),
+ reducers({
+ isCreateModalOpen: [
+ false,
+ {
+ openCreateModal: () => true,
+ closeCreateModal: () => false,
+ },
+ ],
+ createTab: [
+ 'text' as CreateTab,
+ {
+ setCreateTab: (_, { tab }) => tab,
+ closeCreateModal: () => 'text',
+ },
+ ],
+ editingSource: [
+ null as KnowledgeSource | null,
+ {
+ openEditModal: (_, { source }) => source,
+ closeEditModal: () => null,
+ },
+ ],
+ refreshingIds: [
+ [] as string[],
+ {
+ refreshSource: (state, { id }) => (state.includes(id) ? state : [...state, id]),
+ refreshSourceDone: (state, { id }) => state.filter((x) => x !== id),
+ },
+ ],
+ }),
+ loaders(({ values }) => ({
+ sources: [
+ [] as KnowledgeSource[],
+ {
+ loadSources: async () => {
+ return await listSources()
+ },
+ removeSourceFromList: ({ id }: { id: string }) => values.sources.filter((s) => s.id !== id),
+ replaceSourceInList: ({ source }: { source: KnowledgeSource }) =>
+ 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 }) => ({
+ textSource: {
+ defaults: { name: '', text: '' } as TextSourceFormValues,
+ errors: validateText,
+ submit: async ({ name, text }: TextSourceFormValues) => {
+ try {
+ const created = await createTextSource(name, text)
+ lemonToast.success(`"${created.name}" indexed into ${created.chunk_count} chunks`)
+ actions.closeCreateModal()
+ actions.resetTextSource()
+ actions.loadSources()
+ } catch (error: any) {
+ lemonToast.error(
+ error?.detail ||
+ error?.data?.detail ||
+ 'Could not save the source. Check the error and try again.'
+ )
+ throw error
+ }
+ },
+ },
+ urlSource: {
+ defaults: {
+ name: '',
+ url: '',
+ crawl_mode: 'single',
+ include_globs: '',
+ exclude_globs: '',
+ max_pages: 50,
+ max_depth: 2,
+ } as UrlSourceFormValues,
+ errors: validateUrl,
+ submit: async (values: UrlSourceFormValues) => {
+ const payload: CreateUrlSourcePayload = {
+ name: values.name,
+ url: values.url,
+ source_type: 'url',
+ crawl_mode: values.crawl_mode,
+ ...(values.crawl_mode !== 'single' && {
+ include_globs: splitGlobs(values.include_globs),
+ exclude_globs: splitGlobs(values.exclude_globs),
+ max_pages: values.max_pages,
+ max_depth: values.max_depth,
+ }),
+ }
+ try {
+ const created = await createUrlSource(payload)
+ const pageLabel =
+ created.crawl_mode && created.crawl_mode !== 'single'
+ ? ` (${created.document_count} pages)`
+ : ''
+ lemonToast.success(`"${created.name}" indexed into ${created.chunk_count} chunks${pageLabel}`)
+ actions.closeCreateModal()
+ actions.resetUrlSource()
+ actions.loadSources()
+ } catch (error: any) {
+ lemonToast.error(
+ error?.detail ||
+ error?.data?.url?.[0] ||
+ error?.data?.detail ||
+ 'Could not fetch the URL. Make sure it is publicly accessible.'
+ )
+ throw error
+ }
+ },
+ },
+ fileSource: {
+ defaults: { name: '', file: null } as FileSourceFormValues,
+ errors: ({ name, file }: FileSourceFormValues) => ({
+ name: !name.trim() ? 'Give the source a short name' : undefined,
+ file: !file
+ ? 'Select a file to upload'
+ : file.size > 50 * 1024 * 1024
+ ? 'File exceeds the 50 MB cap'
+ : undefined,
+ }),
+ submit: async ({ name, file }: FileSourceFormValues) => {
+ if (!file) {
+ return
+ }
+ const formData = new FormData()
+ formData.append('name', name)
+ formData.append('file', file)
+ formData.append('source_type', 'file')
+ try {
+ const created = await createFileSource(formData)
+ lemonToast.success(`"${created.name}" indexed into ${created.chunk_count} chunks`)
+ actions.closeCreateModal()
+ actions.resetFileSource()
+ actions.loadSources()
+ } catch (error: any) {
+ lemonToast.error(
+ error?.detail ||
+ error?.data?.file?.[0] ||
+ error?.data?.detail ||
+ 'Could not parse the file. Check format and try again.'
+ )
+ throw error
+ }
+ },
+ },
+ editSource: {
+ defaults: { name: '', text: '' } 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 }: TextSourceFormValues) => {
+ const current = values.editingSource
+ if (!current) {
+ return
+ }
+ const isText = current.source_type === 'text'
+ const payload: UpdateSourcePayload = { name, ...(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 })
+ 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,
+ } as UrlSourceFormValues,
+ errors: validateUrl,
+ submit: async (vals: UrlSourceFormValues) => {
+ const current = values.editingSource
+ if (!current) {
+ return
+ }
+ const payload: UpdateSourcePayload = {
+ name: vals.name,
+ url: vals.url,
+ crawl_mode: vals.crawl_mode,
+ ...(vals.crawl_mode !== 'single' && {
+ include_globs: splitGlobs(vals.include_globs),
+ 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 })
+ 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 }) => ({
+ deleteSource: async ({ id }) => {
+ try {
+ await deleteSource(id)
+ actions.removeSourceFromList({ id })
+ lemonToast.success('Knowledge source deleted')
+ } catch (error: any) {
+ lemonToast.error(error?.detail || 'Could not delete the source.')
+ }
+ },
+ refreshSource: async ({ id }) => {
+ try {
+ const updated = await refreshSource(id)
+ actions.replaceSourceInList({ source: updated })
+ if (updated.last_refresh_status === 'not_modified') {
+ lemonToast.info(`"${updated.name}" is already up to date`)
+ } else {
+ lemonToast.success(`"${updated.name}" refreshed`)
+ }
+ } catch (error: any) {
+ lemonToast.error(
+ error?.detail || error?.data?.detail || error?.data?.url?.[0] || 'Could not refresh the source.'
+ )
+ } finally {
+ actions.refreshSourceDone(id)
+ }
+ },
+ openEditModal: ({ source }) => {
+ if (source.source_type === 'url') {
+ const cfg = (source.crawl_config || {}) as {
+ include_globs?: string[]
+ exclude_globs?: string[]
+ max_pages?: number
+ max_depth?: number
+ }
+ actions.setEditUrlSourceValues({
+ name: source.name,
+ url: source.source_url,
+ crawl_mode: (source.crawl_mode || 'single') as CrawlMode,
+ include_globs: (cfg.include_globs || []).join('\n'),
+ exclude_globs: (cfg.exclude_globs || []).join('\n'),
+ max_pages: cfg.max_pages ?? 50,
+ max_depth: cfg.max_depth ?? 2,
+ })
+ } else {
+ actions.setEditSourceValues({ name: source.name, text: '' })
+ 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: [
+ (s) => [s.sources],
+ (sources: KnowledgeSource[]) => sources.filter((s) => s.status === 'ready').length,
+ ],
+ totalChunks: [
+ (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/manifest.tsx b/products/business_knowledge/manifest.tsx
index 3487e35e752e..1ff06ad014e4 100644
--- a/products/business_knowledge/manifest.tsx
+++ b/products/business_knowledge/manifest.tsx
@@ -8,14 +8,21 @@ import { ProductManifest } from '../../frontend/src/types'
export const manifest: ProductManifest = {
name: 'BusinessKnowledge',
scenes: {
- // Define scenes here
+ BusinessKnowledge: {
+ name: 'Business knowledge',
+ import: () => import('./frontend/scenes/BusinessKnowledgeScene'),
+ projectBased: true,
+ activityScope: 'KnowledgeSource',
+ description:
+ 'Upload text, public URLs, or files your AI support agent can cite when answering customer tickets.',
+ },
},
routes: {
- // Define routes here
+ '/business-knowledge': ['BusinessKnowledge', 'businessKnowledge'],
},
redirects: {},
urls: {
- // Define URL helpers here
+ businessKnowledge: (): string => '/business-knowledge',
},
fileSystemTypes: {},
treeItemsNew: [],
diff --git a/products/business_knowledge/package.json b/products/business_knowledge/package.json
index f7ae423bfbe1..6d158993644e 100644
--- a/products/business_knowledge/package.json
+++ b/products/business_knowledge/package.json
@@ -2,5 +2,18 @@
"name": "@posthog/products-business-knowledge",
"scripts": {
"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short --override-ini='addopts=' || test $? -eq 5"
+ },
+ "dependencies": {
+ "kea": "catalog:",
+ "kea-forms": "catalog:",
+ "kea-loaders": "catalog:",
+ "kea-router": "catalog:",
+ "posthog-js": "catalog:"
+ },
+ "peerDependencies": {
+ "@posthog/icons": "*",
+ "@posthog/lemon-ui": "*",
+ "@types/react": "*",
+ "react": "*"
}
}