You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

преди 2 месеца
преди 2 месеца
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import { useEffect, useRef, useState } from 'react'
  2. import { useDebounceFn } from 'ahooks'
  3. import Textarea from '@/app/components/base/textarea'
  4. import SchemaEditor from '@/app/components/workflow/nodes/llm/components/json-schema-config-modal/schema-editor'
  5. import { FileUploaderInAttachmentWrapper } from '@/app/components/base/file-uploader'
  6. import ErrorMessage from '@/app/components/workflow/nodes/llm/components/json-schema-config-modal/error-message'
  7. import {
  8. checkJsonSchemaDepth,
  9. getValidationErrorMessage,
  10. validateSchemaAgainstDraft7,
  11. } from '@/app/components/workflow/nodes/llm/utils'
  12. import {
  13. validateJSONSchema,
  14. } from '@/app/components/workflow/variable-inspect/utils'
  15. import { useFeatures } from '@/app/components/base/features/hooks'
  16. import { getProcessedFiles, getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
  17. import { JSON_SCHEMA_MAX_DEPTH } from '@/config'
  18. import { TransferMethod } from '@/types/app'
  19. import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
  20. import { SupportUploadFileTypes } from '@/app/components/workflow/types'
  21. import type { VarInInspect } from '@/types/workflow'
  22. import { VarInInspectType } from '@/types/workflow'
  23. import cn from '@/utils/classnames'
  24. import BoolValue from '../panel/chat-variable-panel/components/bool-value'
  25. type Props = {
  26. currentVar: VarInInspect
  27. handleValueChange: (varId: string, value: any) => void
  28. }
  29. const ValueContent = ({
  30. currentVar,
  31. handleValueChange,
  32. }: Props) => {
  33. const contentContainerRef = useRef<HTMLDivElement>(null)
  34. const errorMessageRef = useRef<HTMLDivElement>(null)
  35. const [editorHeight, setEditorHeight] = useState(0)
  36. const showTextEditor = currentVar.value_type === 'secret' || currentVar.value_type === 'string' || currentVar.value_type === 'number'
  37. const showBoolEditor = typeof currentVar.value === 'boolean'
  38. const showBoolArrayEditor = Array.isArray(currentVar.value) && currentVar.value.every(v => typeof v === 'boolean')
  39. const isSysFiles = currentVar.type === VarInInspectType.system && currentVar.name === 'files'
  40. const showJSONEditor = !isSysFiles && (currentVar.value_type === 'object' || currentVar.value_type === 'array[string]' || currentVar.value_type === 'array[number]' || currentVar.value_type === 'array[object]' || currentVar.value_type === 'array[any]')
  41. const showFileEditor = isSysFiles || currentVar.value_type === 'file' || currentVar.value_type === 'array[file]'
  42. const textEditorDisabled = currentVar.type === VarInInspectType.environment || (currentVar.type === VarInInspectType.system && currentVar.name !== 'query' && currentVar.name !== 'files')
  43. const JSONEditorDisabled = currentVar.value_type === 'array[any]'
  44. const formatFileValue = (value: VarInInspect) => {
  45. if (value.value_type === 'file')
  46. return value.value ? getProcessedFilesFromResponse([value.value]) : []
  47. if (value.value_type === 'array[file]' || (value.type === VarInInspectType.system && currentVar.name === 'files'))
  48. return value.value && value.value.length > 0 ? getProcessedFilesFromResponse(value.value) : []
  49. return []
  50. }
  51. const [value, setValue] = useState<any>()
  52. const [json, setJson] = useState('')
  53. const [parseError, setParseError] = useState<Error | null>(null)
  54. const [validationError, setValidationError] = useState<string>('')
  55. const fileFeature = useFeatures(s => s.features.file)
  56. const [fileValue, setFileValue] = useState<any>(formatFileValue(currentVar))
  57. const { run: debounceValueChange } = useDebounceFn(handleValueChange, { wait: 500 })
  58. if (showTextEditor) {
  59. if (currentVar.value_type === 'number')
  60. setValue(JSON.stringify(currentVar.value))
  61. if (!currentVar.value)
  62. setValue('')
  63. setValue(currentVar.value)
  64. }
  65. if (showJSONEditor)
  66. setJson(currentVar.value ? JSON.stringify(currentVar.value, null, 2) : '')
  67. if (showFileEditor)
  68. setFileValue(formatFileValue(currentVar))
  69. const handleTextChange = (value: string) => {
  70. if (currentVar.value_type === 'string')
  71. setValue(value)
  72. if (currentVar.value_type === 'number') {
  73. if (/^-?\d+(\.)?(\d+)?$/.test(value))
  74. setValue(Number.parseFloat(value))
  75. }
  76. const newValue = currentVar.value_type === 'number' ? Number.parseFloat(value) : value
  77. debounceValueChange(currentVar.id, newValue)
  78. }
  79. const jsonValueValidate = (value: string, type: string) => {
  80. try {
  81. const newJSONSchema = JSON.parse(value)
  82. setParseError(null)
  83. const result = validateJSONSchema(newJSONSchema, type)
  84. if (!result.success) {
  85. setValidationError(result.error.message)
  86. return false
  87. }
  88. if (type === 'object' || type === 'array[object]') {
  89. const schemaDepth = checkJsonSchemaDepth(newJSONSchema)
  90. if (schemaDepth > JSON_SCHEMA_MAX_DEPTH) {
  91. setValidationError(`Schema exceeds maximum depth of ${JSON_SCHEMA_MAX_DEPTH}.`)
  92. return false
  93. }
  94. const validationErrors = validateSchemaAgainstDraft7(newJSONSchema)
  95. if (validationErrors.length > 0) {
  96. setValidationError(getValidationErrorMessage(validationErrors))
  97. return false
  98. }
  99. }
  100. setValidationError('')
  101. return true
  102. }
  103. catch (error) {
  104. setValidationError('')
  105. if (error instanceof Error) {
  106. setParseError(error)
  107. return false
  108. }
  109. else {
  110. setParseError(new Error('Invalid JSON'))
  111. return false
  112. }
  113. }
  114. }
  115. const handleEditorChange = (value: string) => {
  116. setJson(value)
  117. if (jsonValueValidate(value, currentVar.value_type)) {
  118. const parsed = JSON.parse(value)
  119. debounceValueChange(currentVar.id, parsed)
  120. }
  121. }
  122. const fileValueValidate = (fileList: any[]) => fileList.every(file => file.upload_file_id)
  123. const handleFileChange = (value: any[]) => {
  124. setFileValue(value)
  125. // check every file upload progress
  126. // invoke update api after every file uploaded
  127. if (!fileValueValidate(value))
  128. return
  129. if (currentVar.value_type === 'file')
  130. debounceValueChange(currentVar.id, value[0])
  131. if (currentVar.value_type === 'array[file]' || isSysFiles)
  132. debounceValueChange(currentVar.id, value)
  133. }
  134. // get editor height
  135. useEffect(() => {
  136. if (contentContainerRef.current && errorMessageRef.current) {
  137. const errorMessageObserver = new ResizeObserver((entries) => {
  138. for (const entry of entries) {
  139. const { inlineSize } = entry.borderBoxSize[0]
  140. const height = (contentContainerRef.current as any).clientHeight - inlineSize
  141. setEditorHeight(height)
  142. }
  143. })
  144. errorMessageObserver.observe(errorMessageRef.current)
  145. return () => {
  146. errorMessageObserver.disconnect()
  147. }
  148. }
  149. }, [setEditorHeight])
  150. return (
  151. <div
  152. ref={contentContainerRef}
  153. className='flex h-full flex-col'
  154. >
  155. <div className={cn('grow')} style={{ height: `${editorHeight}px` }}>
  156. {showTextEditor && (
  157. <Textarea
  158. readOnly={textEditorDisabled}
  159. disabled={textEditorDisabled}
  160. className='h-full'
  161. value={value as any}
  162. onChange={e => handleTextChange(e.target.value)}
  163. />
  164. )}
  165. {showBoolEditor && (
  166. <div className='w-[295px]'>
  167. <BoolValue
  168. value={currentVar.value as boolean}
  169. onChange={(newValue) => {
  170. setValue(newValue)
  171. debounceValueChange(currentVar.id, newValue)
  172. }}
  173. />
  174. </div>
  175. )}
  176. {
  177. showBoolArrayEditor && (
  178. <div className='w-[295px] space-y-1'>
  179. {currentVar.value.map((v: boolean, i: number) => (
  180. <BoolValue
  181. key={i}
  182. value={v}
  183. onChange={(newValue) => {
  184. const newArray = [...(currentVar.value as boolean[])]
  185. newArray[i] = newValue
  186. setValue(newArray)
  187. debounceValueChange(currentVar.id, newArray)
  188. }}
  189. />
  190. ))}
  191. </div>
  192. )
  193. }
  194. {showJSONEditor && (
  195. <SchemaEditor
  196. readonly={JSONEditorDisabled}
  197. className='overflow-y-auto'
  198. hideTopMenu
  199. schema={json}
  200. onUpdate={handleEditorChange}
  201. />
  202. )}
  203. {showFileEditor && (
  204. <div className='max-w-[460px]'>
  205. <FileUploaderInAttachmentWrapper
  206. value={fileValue}
  207. onChange={files => handleFileChange(getProcessedFiles(files))}
  208. fileConfig={{
  209. allowed_file_types: [
  210. SupportUploadFileTypes.image,
  211. SupportUploadFileTypes.document,
  212. SupportUploadFileTypes.audio,
  213. SupportUploadFileTypes.video,
  214. ],
  215. allowed_file_extensions: [
  216. ...FILE_EXTS[SupportUploadFileTypes.image],
  217. ...FILE_EXTS[SupportUploadFileTypes.document],
  218. ...FILE_EXTS[SupportUploadFileTypes.audio],
  219. ...FILE_EXTS[SupportUploadFileTypes.video],
  220. ],
  221. allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
  222. number_limits: currentVar.value_type === 'file' ? 1 : (fileFeature as any).fileUploadConfig?.workflow_file_upload_limit || 5,
  223. fileUploadConfig: (fileFeature as any).fileUploadConfig,
  224. }}
  225. isDisabled={textEditorDisabled}
  226. />
  227. </div>
  228. )}
  229. </div>
  230. <div ref={errorMessageRef} className='shrink-0'>
  231. {parseError && <ErrorMessage className='mt-1' message={parseError.message} />}
  232. {validationError && <ErrorMessage className='mt-1' message={validationError} />}
  233. </div>
  234. </div>
  235. )
  236. }
  237. export default ValueContent