chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,55 @@
import { describe, expect, it } from 'vite-plus/test'
import escape from '../escape'
describe('escape', () => {
// Basic special character escaping
it('should escape null character', () => {
expect(escape('\0')).toBe('\\0')
})
it('should escape backspace', () => {
expect(escape('\b')).toBe('\\b')
})
it('should escape form feed', () => {
expect(escape('\f')).toBe('\\f')
})
it('should escape newline', () => {
expect(escape('\n')).toBe('\\n')
})
it('should escape carriage return', () => {
expect(escape('\r')).toBe('\\r')
})
it('should escape tab', () => {
expect(escape('\t')).toBe('\\t')
})
it('should escape vertical tab', () => {
expect(escape('\v')).toBe('\\v')
})
it('should escape single quote', () => {
expect(escape("'")).toBe("\\'")
})
// Multiple special characters in one string
it('should escape multiple special characters', () => {
expect(escape('line1\nline2\ttab')).toBe('line1\\nline2\\ttab')
})
it('should return empty string for empty string input', () => {
expect(escape('')).toBe('')
})
// Pass-through for normal strings
it('should leave normal text unchanged', () => {
expect(escape('hello world')).toBe('hello world')
})
it('should leave special regex characters unchanged', () => {
expect(escape('a.b*c+d')).toBe('a.b*c+d')
})
})
@@ -0,0 +1,88 @@
import { describe, expect, it } from 'vite-plus/test'
import unescape from '../unescape'
describe('unescape', () => {
// Basic escape sequences
it('should unescape \\n to newline', () => {
expect(unescape('\\n')).toBe('\n')
})
it('should unescape \\t to tab', () => {
expect(unescape('\\t')).toBe('\t')
})
it('should unescape \\r to carriage return', () => {
expect(unescape('\\r')).toBe('\r')
})
it('should unescape \\b to backspace', () => {
expect(unescape('\\b')).toBe('\b')
})
it('should unescape \\f to form feed', () => {
expect(unescape('\\f')).toBe('\f')
})
it('should unescape \\v to vertical tab', () => {
expect(unescape('\\v')).toBe('\v')
})
it('should unescape \\0 to null character', () => {
expect(unescape('\\0')).toBe('\0')
})
it('should unescape \\\\ to backslash', () => {
expect(unescape('\\\\')).toBe('\\')
})
it("should unescape \\' to single quote", () => {
expect(unescape("\\'")).toBe("'")
})
it('should unescape \\" to double quote', () => {
expect(unescape('\\"')).toBe('"')
})
// Hex escape sequences (\\xNN)
it('should unescape 2-digit hex sequences', () => {
expect(unescape('\\x41')).toBe('A')
expect(unescape('\\x61')).toBe('a')
})
// Unicode escape sequences (\\uNNNN)
it('should unescape 4-digit unicode sequences', () => {
expect(unescape('\\u0041')).toBe('A')
expect(unescape('\\u4e2d')).toBe('中')
})
// Variable-length unicode (\\u{NNNN})
it('should unescape variable-length unicode sequences', () => {
expect(unescape('\\u{41}')).toBe('A')
expect(unescape('\\u{1F600}')).toBe('😀')
})
// Octal escape sequences
it('should unescape octal sequences', () => {
expect(unescape('\\101')).toBe('A') // 0o101 = 65 = 'A'
expect(unescape('\\12')).toBe('\n') // 0o12 = 10 = '\n'
})
// Python-style 8-digit unicode (\\UNNNNNNNN)
it('should unescape Python-style 8-digit unicode', () => {
expect(unescape('\\U0001F3B5')).toBe('🎵')
})
// Multiple escape sequences
it('should unescape multiple sequences in one string', () => {
expect(unescape('line1\\nline2\\ttab')).toBe('line1\nline2\ttab')
})
// Mixed content
it('should leave non-escape content unchanged', () => {
expect(unescape('hello world')).toBe('hello world')
})
it('should handle empty string', () => {
expect(unescape('')).toBe('')
})
})
@@ -0,0 +1,17 @@
function escape(input: string): string {
if (!input || typeof input !== 'string') return ''
const res = input
// .replaceAll('\\', '\\\\') // This would add too many backslashes
.replaceAll('\0', '\\0')
.replaceAll('\b', '\\b')
.replaceAll('\f', '\\f')
.replaceAll('\n', '\\n')
.replaceAll('\r', '\\r')
.replaceAll('\t', '\\t')
.replaceAll('\v', '\\v')
.replaceAll("'", "\\'")
return res
}
export default escape
@@ -0,0 +1,10 @@
export { useDocumentCreation } from './use-document-creation'
export { IndexingType, useIndexingConfig } from './use-indexing-config'
export { useIndexingEstimate } from './use-indexing-estimate'
export { usePreviewState } from './use-preview-state'
export { MAXIMUM_CHUNK_TOKEN_LENGTH, useSegmentationState } from './use-segmentation-state'
export type { ParentChildConfig } from './use-segmentation-state'
@@ -0,0 +1,52 @@
// https://github.com/iamakulov/unescape-js/blob/master/src/index.js
/**
* \\ - matches the backslash which indicates the beginning of an escape sequence
* (
* u\{([0-9A-Fa-f]+)\} - first alternative; matches the variable-length hexadecimal escape sequence (\u{ABCD0})
* |
* u([0-9A-Fa-f]{4}) - second alternative; matches the 4-digit hexadecimal escape sequence (\uABCD)
* |
* x([0-9A-Fa-f]{2}) - third alternative; matches the 2-digit hexadecimal escape sequence (\xA5)
* |
* ([1-7][0-7]{0,2}|[0-7]{2,3}) - fourth alternative; matches the up-to-3-digit octal escape sequence (\5 or \512)
* |
* (['"tbrnfv0\\]) - fifth alternative; matches the special escape characters (\t, \n and so on)
* |
* \U([0-9A-Fa-f]+) - sixth alternative; matches the 8-digit hexadecimal escape sequence used by python (\U0001F3B5)
* )
*/
const jsEscapeRegex =
/\\(u\{([0-9A-Fa-f]+)\}|u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([1-7][0-7]{0,2}|[0-7]{2,3})|(['"tbrnfv0\\]))|\\U([0-9A-Fa-f]{8})/g
const usualEscapeSequences: Record<string, string> = {
'0': '\0',
b: '\b',
f: '\f',
n: '\n',
r: '\r',
t: '\t',
v: '\v',
"'": "'",
'"': '"',
'\\': '\\',
}
const fromHex = (str: string) => String.fromCodePoint(Number.parseInt(str, 16))
const fromOct = (str: string) => String.fromCodePoint(Number.parseInt(str, 8))
const unescape = (str: string) => {
return str.replace(
jsEscapeRegex,
(_, __, varHex, longHex, shortHex, octal, specialCharacter, python) => {
if (varHex !== undefined) return fromHex(varHex)
else if (longHex !== undefined) return fromHex(longHex)
else if (shortHex !== undefined) return fromHex(shortHex)
else if (octal !== undefined) return fromOct(octal)
else if (python !== undefined) return fromHex(python)
else return usualEscapeSequences[specialCharacter]!
},
)
}
export default unescape
@@ -0,0 +1,297 @@
import type {
DatasetAndDocumentResponse,
DocumentDetailResponse,
} from '@dify/contracts/api/console/datasets/types.gen'
import type { ProviderWithModelsResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import type { StepTwoFile, StepTwoNotionPage } from '../types'
import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type {
ChunkingMode,
CrawlOptions,
CrawlResultItem,
CreateDocumentReq,
ProcessRule,
SummaryIndexSetting as SummaryIndexSettingType,
} from '@/models/datasets'
import type { RetrievalConfig, RETRIEVE_METHOD } from '@/types/app'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { trackEvent } from '@/app/components/base/amplitude'
import { isReRankModelSelected } from '@/app/components/datasets/common/check-rerank-model'
import { toast } from '@/app/notifications'
import { DataSourceProvider } from '@/models/common'
import { DataSourceType, ProcessMode } from '@/models/datasets'
import { consoleQuery } from '@/service/console'
import { getNotionInfo, getWebsiteInfo } from '../creation-params'
import { IndexingType } from './use-indexing-config'
import { MAXIMUM_CHUNK_TOKEN_LENGTH } from './use-segmentation-state'
type UseDocumentCreationOptions = {
datasetId?: string
isSetting?: boolean
documentDetail?: DocumentDetailResponse
dataSourceType: DataSourceType
files: StepTwoFile[]
notionPages: StepTwoNotionPage[]
notionCredentialId: string
websitePages: CrawlResultItem[]
crawlOptions?: CrawlOptions
websiteCrawlProvider?: DataSourceProvider
websiteCrawlJobId?: string
canCreateDocument?: boolean
// Callbacks
onStepChange?: (delta: number) => void
updateIndexingTypeCache?: (type: string) => void
updateResultCache?: (res: DatasetAndDocumentResponse) => void
updateRetrievalMethodCache?: (method: RETRIEVE_METHOD | '') => void
onSave?: () => void
mutateDatasetRes?: () => void
}
type ValidationParams = {
segmentationType: ProcessMode
maxChunkLength: number
limitMaxChunkLength: number
overlap: number
indexType: IndexingType
embeddingModel: DefaultModel
rerankModelList: ProviderWithModelsResponse[]
retrievalConfig: RetrievalConfig
}
export const useDocumentCreation = (options: UseDocumentCreationOptions) => {
const { t } = useTranslation(['appDebug', 'datasetCreation'])
const {
datasetId,
isSetting,
documentDetail,
dataSourceType,
files,
notionPages,
notionCredentialId,
websitePages,
crawlOptions,
websiteCrawlProvider = DataSourceProvider.jinaReader,
websiteCrawlJobId = '',
canCreateDocument = true,
onStepChange,
updateIndexingTypeCache,
updateResultCache,
updateRetrievalMethodCache,
onSave,
mutateDatasetRes,
} = options
const { mutateAsync: createFirstDocument, isPending: isCreatingFirstDocument } = useMutation(
consoleQuery.datasets.init.post.mutationOptions(),
)
const { mutateAsync: createDocument, isPending: isCreatingDocument } = useMutation(
consoleQuery.datasets.byDatasetId.documents.post.mutationOptions(),
)
const queryClient = useQueryClient()
const invalidDatasetList = useCallback(() => {
queryClient.invalidateQueries({ queryKey: consoleQuery.datasets.get.key() })
}, [queryClient])
const isCreating = isCreatingFirstDocument || isCreatingDocument
// Validate creation params
const validateParams = useCallback(
(params: ValidationParams): boolean => {
const {
segmentationType,
maxChunkLength,
limitMaxChunkLength,
overlap,
indexType,
embeddingModel,
rerankModelList,
retrievalConfig,
} = params
if (segmentationType === ProcessMode.general && overlap > maxChunkLength) {
toast.error(t(($) => $['stepTwo.overlapCheck'], { ns: 'datasetCreation' }))
return false
}
if (segmentationType === ProcessMode.general && maxChunkLength > limitMaxChunkLength) {
toast.error(
t(($) => $['stepTwo.maxLengthCheck'], {
ns: 'datasetCreation',
limit: limitMaxChunkLength,
}),
)
return false
}
if (!isSetting) {
if (
indexType === IndexingType.QUALIFIED &&
(!embeddingModel.model || !embeddingModel.provider)
) {
toast.error(t(($) => $['datasetConfig.embeddingModelRequired'], { ns: 'appDebug' }))
return false
}
if (
!isReRankModelSelected({
rerankModelList,
retrievalConfig,
indexMethod: indexType,
})
) {
toast.error(t(($) => $['datasetConfig.rerankModelRequired'], { ns: 'appDebug' }))
return false
}
}
return true
},
[t, isSetting],
)
// Build creation params
const buildCreationParams = useCallback(
(
currentDocForm: ChunkingMode,
docLanguage: string,
processRule: ProcessRule,
retrievalConfig: RetrievalConfig,
embeddingModel: DefaultModel,
indexingTechnique: string,
summaryIndexSetting?: SummaryIndexSettingType,
): CreateDocumentReq | null => {
if (isSetting) {
return {
original_document_id: documentDetail?.id,
doc_form: currentDocForm,
doc_language: docLanguage,
process_rule: processRule,
summary_index_setting: summaryIndexSetting,
retrieval_model: retrievalConfig,
embedding_model: embeddingModel.model,
embedding_model_provider: embeddingModel.provider,
indexing_technique: indexingTechnique,
} as CreateDocumentReq
}
const params: CreateDocumentReq = {
data_source: {
type: dataSourceType,
info_list: {
data_source_type: dataSourceType,
},
},
indexing_technique: indexingTechnique,
process_rule: processRule,
summary_index_setting: summaryIndexSetting,
doc_form: currentDocForm,
doc_language: docLanguage,
retrieval_model: retrievalConfig,
embedding_model: embeddingModel.model,
embedding_model_provider: embeddingModel.provider,
} as CreateDocumentReq
// Add data source specific info
if (dataSourceType === DataSourceType.FILE) {
params.data_source!.info_list.file_info_list = {
file_ids: files.map((file) => file.id || '').filter(Boolean),
}
}
if (dataSourceType === DataSourceType.NOTION)
params.data_source!.info_list.notion_info_list = getNotionInfo(
notionPages,
notionCredentialId,
)
if (dataSourceType === DataSourceType.WEB) {
params.data_source!.info_list.website_info_list = getWebsiteInfo({
websiteCrawlProvider,
websiteCrawlJobId,
websitePages,
crawlOptions,
})
}
return params
},
[
isSetting,
documentDetail,
dataSourceType,
files,
notionPages,
notionCredentialId,
websitePages,
websiteCrawlProvider,
websiteCrawlJobId,
crawlOptions,
],
)
// Execute creation
const executeCreation = useCallback(
async (
params: CreateDocumentReq,
indexType: IndexingType,
retrievalConfig: RetrievalConfig,
) => {
if (datasetId && !isSetting && !canCreateDocument) return
if (!datasetId) {
await createFirstDocument(
{ body: params },
{
onSuccess(data) {
updateIndexingTypeCache?.(indexType)
updateResultCache?.(data)
updateRetrievalMethodCache?.(retrievalConfig.search_method as RETRIEVE_METHOD)
},
},
)
} else {
await createDocument(
{ params: { dataset_id: datasetId }, body: params },
{
onSuccess(data) {
updateIndexingTypeCache?.(indexType)
updateResultCache?.(data)
updateRetrievalMethodCache?.(retrievalConfig.search_method as RETRIEVE_METHOD)
},
},
)
}
mutateDatasetRes?.()
invalidDatasetList()
trackEvent('create_datasets', {
data_source_type: dataSourceType,
indexing_technique: indexType,
})
onStepChange?.(+1)
if (isSetting) onSave?.()
},
[
datasetId,
createFirstDocument,
createDocument,
updateIndexingTypeCache,
updateResultCache,
updateRetrievalMethodCache,
mutateDatasetRes,
invalidDatasetList,
dataSourceType,
onStepChange,
isSetting,
canCreateDocument,
onSave,
],
)
// Validate preview params
const validatePreviewParams = useCallback(
(maxChunkLength: number): boolean => {
if (maxChunkLength > MAXIMUM_CHUNK_TOKEN_LENGTH) {
toast.error(
t(($) => $['stepTwo.maxLengthCheck'], {
ns: 'datasetCreation',
limit: MAXIMUM_CHUNK_TOKEN_LENGTH,
}),
)
return false
}
return true
},
[t],
)
return {
isCreating,
validateParams,
buildCreationParams,
executeCreation,
validatePreviewParams,
}
}
@@ -0,0 +1,151 @@
import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { RetrievalConfig } from '@/types/app'
import { useQuery } from '@tanstack/react-query'
import { useEffect, useMemo, useState } from 'react'
import { checkShowMultiModalTip } from '@/app/components/datasets/settings/utils'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import {
useDefaultModel,
useModelListAndDefaultModelAndCurrentProviderAndModel,
} from '@/app/components/header/account-setting/model-provider-page/hooks'
import { consoleQuery } from '@/service/console'
import { RETRIEVE_METHOD } from '@/types/app'
export const IndexingType = {
QUALIFIED: 'high_quality',
ECONOMICAL: 'economy',
} as const
export type IndexingType = (typeof IndexingType)[keyof typeof IndexingType]
const DEFAULT_RETRIEVAL_CONFIG: RetrievalConfig = {
search_method: RETRIEVE_METHOD.semantic,
reranking_enable: false,
reranking_model: {
reranking_provider_name: '',
reranking_model_name: '',
},
top_k: 3,
score_threshold_enabled: false,
score_threshold: 0.5,
}
type UseIndexingConfigOptions = {
initialIndexType?: IndexingType
initialEmbeddingModel?: DefaultModel
initialRetrievalConfig?: RetrievalConfig
isAPIKeySet: boolean
hasSetIndexType: boolean
}
export const useIndexingConfig = (options: UseIndexingConfigOptions) => {
const {
initialIndexType,
initialEmbeddingModel,
initialRetrievalConfig,
isAPIKeySet,
hasSetIndexType,
} = options
// Rerank model
const {
modelList: rerankModelList,
defaultModel: rerankDefaultModel,
currentModel: isRerankDefaultModelValid,
} = useModelListAndDefaultModelAndCurrentProviderAndModel(ModelTypeEnum.rerank)
// Embedding model list
const { data: embeddingModelList = [] } = useQuery(
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
input: { params: { model_type: ModelTypeEnum.textEmbedding } },
select: (response) => response.data,
}),
)
const { data: defaultEmbeddingModel } = useDefaultModel(ModelTypeEnum.textEmbedding)
// Index type state
const [indexType, setIndexType] = useState<IndexingType>(() => {
if (initialIndexType) return initialIndexType
return isAPIKeySet ? IndexingType.QUALIFIED : IndexingType.ECONOMICAL
})
// Embedding model state
const [embeddingModel, setEmbeddingModel] = useState<DefaultModel>(
initialEmbeddingModel ?? {
provider: defaultEmbeddingModel?.provider.provider || '',
model: defaultEmbeddingModel?.model || '',
},
)
// Retrieval config state
const [retrievalConfig, setRetrievalConfig] = useState<RetrievalConfig>(
initialRetrievalConfig ?? DEFAULT_RETRIEVAL_CONFIG,
)
// Sync retrieval config with rerank model when available
useEffect(() => {
if (initialRetrievalConfig) return
setRetrievalConfig({
search_method: RETRIEVE_METHOD.semantic,
reranking_enable: !!isRerankDefaultModelValid,
reranking_model: {
reranking_provider_name: isRerankDefaultModelValid
? (rerankDefaultModel?.provider.provider ?? '')
: '',
reranking_model_name: isRerankDefaultModelValid ? (rerankDefaultModel?.model ?? '') : '',
},
top_k: 3,
score_threshold_enabled: false,
score_threshold: 0.5,
})
}, [rerankDefaultModel, isRerankDefaultModelValid, initialRetrievalConfig])
// Sync index type with props
useEffect(() => {
if (initialIndexType) setIndexType(initialIndexType)
else setIndexType(isAPIKeySet ? IndexingType.QUALIFIED : IndexingType.ECONOMICAL)
}, [isAPIKeySet, initialIndexType])
// Show multimodal tip
const showMultiModalTip = useMemo(() => {
return checkShowMultiModalTip({
embeddingModel,
rerankingEnable: retrievalConfig.reranking_enable,
rerankModel: {
rerankingProviderName: retrievalConfig.reranking_model.reranking_provider_name,
rerankingModelName: retrievalConfig.reranking_model.reranking_model_name,
},
indexMethod: indexType,
embeddingModelList,
rerankModelList,
})
}, [embeddingModel, retrievalConfig, indexType, embeddingModelList, rerankModelList])
// Get effective indexing technique
const getIndexingTechnique = () => initialIndexType || indexType
return {
// Index type
indexType,
setIndexType,
hasSetIndexType,
getIndexingTechnique,
// Embedding model
embeddingModel,
setEmbeddingModel,
embeddingModelList,
defaultEmbeddingModel,
// Retrieval config
retrievalConfig,
setRetrievalConfig,
rerankModelList,
rerankDefaultModel,
isRerankDefaultModelValid,
// Computed
showMultiModalTip,
}
}
@@ -0,0 +1,131 @@
import type { StepTwoFile, StepTwoNotionPage } from '../types'
import type { IndexingType } from './use-indexing-config'
import type { ChunkingMode, CrawlOptions, CrawlResultItem, ProcessRule } from '@/models/datasets'
import { useMutation } from '@tanstack/react-query'
import { useCallback } from 'react'
import { DataSourceProvider } from '@/models/common'
import { DataSourceType } from '@/models/datasets'
import { consoleQuery } from '@/service/console'
import {
getFileIndexingEstimateParamsForFile,
getFileIndexingEstimateParamsForNotion,
getFileIndexingEstimateParamsForWeb,
} from '../creation-params'
type UseIndexingEstimateOptions = {
dataSourceType: DataSourceType
datasetId?: string
// Document settings
currentDocForm: ChunkingMode
docLanguage: string
// File data source
files: StepTwoFile[]
previewItemId?: string
// Notion data source
notionPages: StepTwoNotionPage[]
notionCredentialId: string
// Website data source
websitePages: CrawlResultItem[]
crawlOptions?: CrawlOptions
websiteCrawlProvider?: DataSourceProvider
websiteCrawlJobId?: string
// Processing
indexingTechnique: IndexingType
processRule: ProcessRule
}
export const useIndexingEstimate = (options: UseIndexingEstimateOptions) => {
const {
dataSourceType,
datasetId,
currentDocForm,
docLanguage,
files,
previewItemId,
notionPages,
notionCredentialId,
websitePages,
crawlOptions,
websiteCrawlProvider,
websiteCrawlJobId,
indexingTechnique,
processRule,
} = options
// Step two keeps one data source, so one estimate request serves it.
const estimateMutation = useMutation(
consoleQuery.datasets.indexingEstimate.post.mutationOptions(),
)
const getEstimateParams = useCallback(
(selectedId?: string) => {
if (dataSourceType === DataSourceType.FILE) {
return getFileIndexingEstimateParamsForFile({
docForm: currentDocForm,
docLanguage,
dataSourceType: DataSourceType.FILE,
files: selectedId ? files.filter((file) => file.id === selectedId) : files,
indexingTechnique,
processRule,
dataset_id: datasetId!,
})
}
if (dataSourceType === DataSourceType.NOTION) {
return getFileIndexingEstimateParamsForNotion({
docForm: currentDocForm,
docLanguage,
dataSourceType: DataSourceType.NOTION,
notionPages: notionPages.filter((page) => page.page_id === selectedId),
indexingTechnique,
processRule,
dataset_id: datasetId || '',
credential_id: notionCredentialId,
})
}
return getFileIndexingEstimateParamsForWeb({
docForm: currentDocForm,
docLanguage,
dataSourceType: DataSourceType.WEB,
websitePages: websitePages.filter((page) => page.source_url === selectedId),
crawlOptions,
websiteCrawlProvider: websiteCrawlProvider ?? DataSourceProvider.jinaReader,
websiteCrawlJobId: websiteCrawlJobId ?? '',
indexingTechnique,
processRule,
dataset_id: datasetId || '',
})
},
[
dataSourceType,
currentDocForm,
docLanguage,
files,
notionPages,
notionCredentialId,
websitePages,
crawlOptions,
websiteCrawlProvider,
websiteCrawlJobId,
indexingTechnique,
processRule,
datasetId,
],
)
const { mutate } = estimateMutation
const fetchEstimate = useCallback(
(selectedId = previewItemId) => {
mutate({ body: getEstimateParams(selectedId) })
},
[mutate, getEstimateParams, previewItemId],
)
return {
currentMutation: estimateMutation,
estimate: estimateMutation.data,
isIdle: estimateMutation.isIdle,
isPending: estimateMutation.isPending,
fetchEstimate,
reset: estimateMutation.reset,
}
}
@@ -0,0 +1,124 @@
import type { DocumentDetailResponse } from '@dify/contracts/api/console/datasets/types.gen'
import type { StepTwoFile, StepTwoNotionPage } from '../types'
import type { CrawlResultItem, DocumentItem } from '@/models/datasets'
import { useCallback, useState } from 'react'
import { DataSourceType } from '@/models/datasets'
type UsePreviewStateOptions = {
dataSourceType: DataSourceType
files: StepTwoFile[]
notionPages: StepTwoNotionPage[]
websitePages: CrawlResultItem[]
documentDetail?: DocumentDetailResponse
datasetId?: string
}
export const usePreviewState = (options: UsePreviewStateOptions) => {
const { dataSourceType, files, notionPages, websitePages, documentDetail, datasetId } = options
// File preview state
// Editing an existing document has no preview item until one is picked.
const isEditing = !!datasetId && !!documentDetail
const [previewFile, setPreviewFile] = useState<StepTwoFile | DocumentItem | undefined>(
isEditing ? undefined : files[0],
)
// Notion page preview state
const [previewNotionPage, setPreviewNotionPage] = useState<StepTwoNotionPage | undefined>(
isEditing ? undefined : notionPages[0],
)
// Website page preview state
const [previewWebsitePage, setPreviewWebsitePage] = useState<CrawlResultItem | undefined>(
isEditing ? undefined : websitePages[0],
)
// Get preview items for document picker based on data source type
const getPreviewPickerItems = useCallback(() => {
if (dataSourceType === DataSourceType.FILE) {
return files.map((file) => ({
id: file.id ?? '',
name: file.name,
extension: file.extension ?? '',
}))
}
if (dataSourceType === DataSourceType.NOTION) {
return notionPages.map((page) => ({
id: page.page_id,
name: page.page_name,
extension: 'md',
}))
}
if (dataSourceType === DataSourceType.WEB) {
return websitePages.map((page) => ({
id: page.source_url,
name: page.title,
extension: 'md',
}))
}
return []
}, [dataSourceType, files, notionPages, websitePages])
// Get current preview value for picker
const getPreviewPickerValue = useCallback(() => {
if (dataSourceType === DataSourceType.FILE) {
return (
previewFile && {
id: previewFile.id ?? '',
name: previewFile.name,
extension: previewFile.extension ?? '',
}
)
}
if (dataSourceType === DataSourceType.NOTION) {
return {
id: previewNotionPage?.page_id || '',
name: previewNotionPage?.page_name || '',
extension: 'md',
}
}
if (dataSourceType === DataSourceType.WEB) {
return {
id: previewWebsitePage?.source_url || '',
name: previewWebsitePage?.title || '',
extension: 'md',
}
}
return { id: '', name: '', extension: '' }
}, [dataSourceType, previewFile, previewNotionPage, previewWebsitePage])
// Handle preview change
const handlePreviewChange = useCallback(
(selected: { id: string; name: string }) => {
if (dataSourceType === DataSourceType.FILE) {
setPreviewFile(files.find((file) => file.id === selected.id))
} else if (dataSourceType === DataSourceType.NOTION) {
const selectedPage = notionPages.find((page) => page.page_id === selected.id)
if (selectedPage) setPreviewNotionPage(selectedPage)
} else if (dataSourceType === DataSourceType.WEB) {
const selectedPage = websitePages.find((page) => page.source_url === selected.id)
if (selectedPage) setPreviewWebsitePage(selectedPage)
}
},
[dataSourceType, files, notionPages, websitePages],
)
return {
// File preview
previewFile,
setPreviewFile,
// Notion preview
previewNotionPage,
setPreviewNotionPage,
// Website preview
previewWebsitePage,
setPreviewWebsitePage,
// Picker helpers
getPreviewPickerItems,
getPreviewPickerValue,
handlePreviewChange,
}
}
@@ -0,0 +1,250 @@
import type { PreProcessingRule } from '@dify/contracts/api/console/datasets/types.gen'
import type {
ParentMode,
ProcessRule,
Rules,
SummaryIndexSetting as SummaryIndexSettingType,
} from '@/models/datasets'
import { useCallback, useRef, useState } from 'react'
import { env } from '@/env'
import { ChunkingMode, ProcessMode } from '@/models/datasets'
import escape from './escape'
import unescape from './unescape'
// Constants
const DEFAULT_SEGMENT_IDENTIFIER = '\\n\\n'
const DEFAULT_MAXIMUM_CHUNK_LENGTH = 1024
const DEFAULT_OVERLAP = 50
export const MAXIMUM_CHUNK_TOKEN_LENGTH = env.NEXT_PUBLIC_INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH
export type ParentChildConfig = {
chunkForContext: ParentMode
parent: {
delimiter: string
maxLength: number
}
child: {
delimiter: string
maxLength: number
}
}
const defaultParentChildConfig: ParentChildConfig = {
chunkForContext: 'paragraph',
parent: {
delimiter: '\\n\\n',
maxLength: 1024,
},
child: {
delimiter: '\\n',
maxLength: 512,
},
}
type UseSegmentationStateOptions = {
initialSegmentationType?: ProcessMode
initialSummaryIndexSetting?: SummaryIndexSettingType
}
export const useSegmentationState = (options: UseSegmentationStateOptions = {}) => {
const { initialSegmentationType, initialSummaryIndexSetting } = options
// Segmentation type (general or parent-child)
const [segmentationType, setSegmentationType] = useState<ProcessMode>(
initialSegmentationType ?? ProcessMode.general,
)
// General chunking settings
const [segmentIdentifier, doSetSegmentIdentifier] = useState(DEFAULT_SEGMENT_IDENTIFIER)
const [maxChunkLength, setMaxChunkLength] = useState(DEFAULT_MAXIMUM_CHUNK_LENGTH)
const [limitMaxChunkLength, setLimitMaxChunkLength] = useState(MAXIMUM_CHUNK_TOKEN_LENGTH)
const [overlap, setOverlap] = useState(DEFAULT_OVERLAP)
// Pre-processing rules
const [rules, setRules] = useState<PreProcessingRule[]>([])
const [defaultConfig, setDefaultConfig] = useState<Rules>()
const [summaryIndexSetting, setSummaryIndexSetting] = useState<
SummaryIndexSettingType | undefined
>(initialSummaryIndexSetting)
const summaryIndexSettingRef = useRef<SummaryIndexSettingType | undefined>(
initialSummaryIndexSetting,
)
const handleSummaryIndexSettingChange = useCallback((payload: SummaryIndexSettingType) => {
setSummaryIndexSetting((prev) => {
const newSetting = { ...prev, ...payload }
summaryIndexSettingRef.current = newSetting
return newSetting
})
}, [])
// Parent-child config
const [parentChildConfig, setParentChildConfig] =
useState<ParentChildConfig>(defaultParentChildConfig)
// Escaped segment identifier setter
const setSegmentIdentifier = useCallback((value: string, canEmpty?: boolean) => {
if (value) {
doSetSegmentIdentifier(escape(value))
} else {
doSetSegmentIdentifier(canEmpty ? '' : DEFAULT_SEGMENT_IDENTIFIER)
}
}, [])
// Rule toggle handler
const toggleRule = useCallback((id: string) => {
setRules((prev) =>
prev.map((rule) => (rule.id === id ? { ...rule, enabled: !rule.enabled } : rule)),
)
}, [])
// Reset to defaults
const resetToDefaults = useCallback(() => {
if (defaultConfig) {
setSegmentIdentifier(defaultConfig.segmentation.separator)
setMaxChunkLength(defaultConfig.segmentation.max_tokens)
setOverlap(defaultConfig.segmentation.chunk_overlap!)
setRules(defaultConfig.pre_processing_rules)
}
setParentChildConfig(defaultParentChildConfig)
}, [defaultConfig, setSegmentIdentifier])
// Apply config from document detail
const applyConfigFromRules = useCallback(
(rulesConfig: Rules, isHierarchical: boolean) => {
const separator = rulesConfig.segmentation.separator
const max = rulesConfig.segmentation.max_tokens
const chunkOverlap = rulesConfig.segmentation.chunk_overlap
setSegmentIdentifier(separator)
setMaxChunkLength(max)
setOverlap(chunkOverlap!)
setRules(rulesConfig.pre_processing_rules)
setDefaultConfig(rulesConfig)
if (isHierarchical) {
setParentChildConfig({
chunkForContext: rulesConfig.parent_mode || 'paragraph',
parent: {
delimiter: escape(rulesConfig.segmentation.separator),
maxLength: rulesConfig.segmentation.max_tokens,
},
child: {
delimiter: escape(rulesConfig.subchunk_segmentation!.separator),
maxLength: rulesConfig.subchunk_segmentation!.max_tokens,
},
})
}
},
[setSegmentIdentifier],
)
// Get process rule for API
const getProcessRule = useCallback(
(docForm: ChunkingMode): ProcessRule => {
if (docForm === ChunkingMode.parentChild) {
return {
rules: {
pre_processing_rules: rules,
segmentation: {
separator: unescape(parentChildConfig.parent.delimiter),
max_tokens: parentChildConfig.parent.maxLength,
},
parent_mode: parentChildConfig.chunkForContext,
subchunk_segmentation: {
separator: unescape(parentChildConfig.child.delimiter),
max_tokens: parentChildConfig.child.maxLength,
},
},
mode: 'hierarchical',
summary_index_setting: summaryIndexSettingRef.current,
} as ProcessRule
}
return {
rules: {
pre_processing_rules: rules,
segmentation: {
separator: unescape(segmentIdentifier),
max_tokens: maxChunkLength,
chunk_overlap: overlap,
},
},
mode: segmentationType,
summary_index_setting: summaryIndexSettingRef.current,
} as ProcessRule
},
[rules, parentChildConfig, segmentIdentifier, maxChunkLength, overlap, segmentationType],
)
// Update parent config field
const updateParentConfig = useCallback(
(field: 'delimiter' | 'maxLength', value: string | number) => {
setParentChildConfig((prev) => {
let newValue: string | number
if (field === 'delimiter') newValue = value ? escape(value as string) : ''
else newValue = value
return {
...prev,
parent: { ...prev.parent, [field]: newValue },
}
})
},
[],
)
// Update child config field
const updateChildConfig = useCallback(
(field: 'delimiter' | 'maxLength', value: string | number) => {
setParentChildConfig((prev) => {
let newValue: string | number
if (field === 'delimiter') newValue = value ? escape(value as string) : ''
else newValue = value
return {
...prev,
child: { ...prev.child, [field]: newValue },
}
})
},
[],
)
// Set chunk for context mode
const setChunkForContext = useCallback((mode: ParentMode) => {
setParentChildConfig((prev) => ({ ...prev, chunkForContext: mode }))
}, [])
return {
// General chunking state
segmentationType,
setSegmentationType,
segmentIdentifier,
setSegmentIdentifier,
maxChunkLength,
setMaxChunkLength,
limitMaxChunkLength,
setLimitMaxChunkLength,
overlap,
setOverlap,
// Rules
rules,
setRules,
defaultConfig,
setDefaultConfig,
toggleRule,
summaryIndexSetting,
handleSummaryIndexSettingChange,
// Parent-child config
parentChildConfig,
setParentChildConfig,
updateParentConfig,
updateChildConfig,
setChunkForContext,
// Actions
resetToDefaults,
applyConfigFromRules,
getProcessRule,
}
}