update-dsl-modal.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. 'use client'
  2. import type { MouseEventHandler } from 'react'
  3. import {
  4. memo,
  5. useCallback,
  6. useRef,
  7. useState,
  8. } from 'react'
  9. import { useContext } from 'use-context-selector'
  10. import { useTranslation } from 'react-i18next'
  11. import {
  12. RiAlertFill,
  13. RiCloseLine,
  14. RiFileDownloadLine,
  15. } from '@remixicon/react'
  16. import { WORKFLOW_DATA_UPDATE } from './constants'
  17. import {
  18. SupportUploadFileTypes,
  19. } from './types'
  20. import {
  21. initialEdges,
  22. initialNodes,
  23. } from './utils'
  24. import {
  25. importDSL,
  26. importDSLConfirm,
  27. } from '@/service/apps'
  28. import { fetchWorkflowDraft } from '@/service/workflow'
  29. import {
  30. DSLImportMode,
  31. DSLImportStatus,
  32. } from '@/models/app'
  33. import Uploader from '@/app/components/app/create-from-dsl-modal/uploader'
  34. import Button from '@/app/components/base/button'
  35. import Modal from '@/app/components/base/modal'
  36. import { ToastContext } from '@/app/components/base/toast'
  37. import { useEventEmitterContextContext } from '@/context/event-emitter'
  38. import { useStore as useAppStore } from '@/app/components/app/store'
  39. import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
  40. type UpdateDSLModalProps = {
  41. onCancel: () => void
  42. onBackup: () => void
  43. onImport?: () => void
  44. }
  45. const UpdateDSLModal = ({
  46. onCancel,
  47. onBackup,
  48. onImport,
  49. }: UpdateDSLModalProps) => {
  50. const { t } = useTranslation()
  51. const { notify } = useContext(ToastContext)
  52. const appDetail = useAppStore(s => s.appDetail)
  53. const [currentFile, setDSLFile] = useState<File>()
  54. const [fileContent, setFileContent] = useState<string>()
  55. const [loading, setLoading] = useState(false)
  56. const { eventEmitter } = useEventEmitterContextContext()
  57. const [show, setShow] = useState(true)
  58. const [showErrorModal, setShowErrorModal] = useState(false)
  59. const [versions, setVersions] = useState<{ importedVersion: string; systemVersion: string }>()
  60. const [importId, setImportId] = useState<string>()
  61. const readFile = (file: File) => {
  62. const reader = new FileReader()
  63. reader.onload = function (event) {
  64. const content = event.target?.result
  65. setFileContent(content as string)
  66. }
  67. reader.readAsText(file)
  68. }
  69. const handleFile = (file?: File) => {
  70. setDSLFile(file)
  71. if (file)
  72. readFile(file)
  73. if (!file)
  74. setFileContent('')
  75. }
  76. const handleWorkflowUpdate = async (app_id: string) => {
  77. const {
  78. graph,
  79. features,
  80. hash,
  81. } = await fetchWorkflowDraft(`/apps/${app_id}/workflows/draft`)
  82. const { nodes, edges, viewport } = graph
  83. const newFeatures = {
  84. file: {
  85. image: {
  86. enabled: !!features.file_upload?.image?.enabled,
  87. number_limits: features.file_upload?.image?.number_limits || 3,
  88. transfer_methods: features.file_upload?.image?.transfer_methods || ['local_file', 'remote_url'],
  89. },
  90. enabled: !!(features.file_upload?.enabled || features.file_upload?.image?.enabled),
  91. allowed_file_types: features.file_upload?.allowed_file_types || [SupportUploadFileTypes.image],
  92. allowed_file_extensions: features.file_upload?.allowed_file_extensions || FILE_EXTS[SupportUploadFileTypes.image].map(ext => `.${ext}`),
  93. allowed_file_upload_methods: features.file_upload?.allowed_file_upload_methods || features.file_upload?.image?.transfer_methods || ['local_file', 'remote_url'],
  94. number_limits: features.file_upload?.number_limits || features.file_upload?.image?.number_limits || 3,
  95. },
  96. opening: {
  97. enabled: !!features.opening_statement,
  98. opening_statement: features.opening_statement,
  99. suggested_questions: features.suggested_questions,
  100. },
  101. suggested: features.suggested_questions_after_answer || { enabled: false },
  102. speech2text: features.speech_to_text || { enabled: false },
  103. text2speech: features.text_to_speech || { enabled: false },
  104. citation: features.retriever_resource || { enabled: false },
  105. moderation: features.sensitive_word_avoidance || { enabled: false },
  106. }
  107. eventEmitter?.emit({
  108. type: WORKFLOW_DATA_UPDATE,
  109. payload: {
  110. nodes: initialNodes(nodes, edges),
  111. edges: initialEdges(edges, nodes),
  112. viewport,
  113. features: newFeatures,
  114. hash,
  115. },
  116. } as any)
  117. }
  118. const isCreatingRef = useRef(false)
  119. const handleImport: MouseEventHandler = useCallback(async () => {
  120. if (isCreatingRef.current)
  121. return
  122. isCreatingRef.current = true
  123. if (!currentFile)
  124. return
  125. try {
  126. if (appDetail && fileContent) {
  127. setLoading(true)
  128. const response = await importDSL({ mode: DSLImportMode.YAML_CONTENT, yaml_content: fileContent, app_id: appDetail.id })
  129. const { id, status, app_id, imported_dsl_version, current_dsl_version } = response
  130. if (status === DSLImportStatus.COMPLETED || status === DSLImportStatus.COMPLETED_WITH_WARNINGS) {
  131. if (!app_id) {
  132. notify({ type: 'error', message: t('workflow.common.importFailure') })
  133. return
  134. }
  135. handleWorkflowUpdate(app_id)
  136. if (onImport)
  137. onImport()
  138. notify({
  139. type: status === DSLImportStatus.COMPLETED ? 'success' : 'warning',
  140. message: t(status === DSLImportStatus.COMPLETED ? 'workflow.common.importSuccess' : 'workflow.common.importWarning'),
  141. children: status === DSLImportStatus.COMPLETED_WITH_WARNINGS && t('workflow.common.importWarningDetails'),
  142. })
  143. setLoading(false)
  144. onCancel()
  145. }
  146. else if (status === DSLImportStatus.PENDING) {
  147. setShow(false)
  148. setTimeout(() => {
  149. setShowErrorModal(true)
  150. }, 300)
  151. setVersions({
  152. importedVersion: imported_dsl_version ?? '',
  153. systemVersion: current_dsl_version ?? '',
  154. })
  155. setImportId(id)
  156. }
  157. else {
  158. setLoading(false)
  159. notify({ type: 'error', message: t('workflow.common.importFailure') })
  160. }
  161. }
  162. }
  163. catch (e) {
  164. setLoading(false)
  165. notify({ type: 'error', message: t('workflow.common.importFailure') })
  166. }
  167. isCreatingRef.current = false
  168. }, [currentFile, fileContent, onCancel, notify, t, eventEmitter, appDetail, onImport])
  169. const onUpdateDSLConfirm: MouseEventHandler = async () => {
  170. try {
  171. if (!importId)
  172. return
  173. const response = await importDSLConfirm({
  174. import_id: importId,
  175. })
  176. const { status, app_id } = response
  177. if (status === DSLImportStatus.COMPLETED) {
  178. if (!app_id) {
  179. notify({ type: 'error', message: t('workflow.common.importFailure') })
  180. return
  181. }
  182. handleWorkflowUpdate(app_id)
  183. if (onImport)
  184. onImport()
  185. notify({ type: 'success', message: t('workflow.common.importSuccess') })
  186. setLoading(false)
  187. onCancel()
  188. }
  189. else if (status === DSLImportStatus.FAILED) {
  190. setLoading(false)
  191. notify({ type: 'error', message: t('workflow.common.importFailure') })
  192. }
  193. }
  194. catch (e) {
  195. setLoading(false)
  196. notify({ type: 'error', message: t('workflow.common.importFailure') })
  197. }
  198. }
  199. return (
  200. <>
  201. <Modal
  202. className='p-6 w-[520px] rounded-2xl'
  203. isShow={show}
  204. onClose={onCancel}
  205. >
  206. <div className='flex items-center justify-between mb-3'>
  207. <div className='title-2xl-semi-bold text-text-primary'>{t('workflow.common.importDSL')}</div>
  208. <div className='flex items-center justify-center w-[22px] h-[22px] cursor-pointer' onClick={onCancel}>
  209. <RiCloseLine className='w-[18px] h-[18px] text-text-tertiary' />
  210. </div>
  211. </div>
  212. <div className='flex relative p-2 mb-2 gap-0.5 flex-grow rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-xs overflow-hidden'>
  213. <div className='absolute top-0 left-0 w-full h-full opacity-40 bg-[linear-gradient(92deg,rgba(247,144,9,0.25)_0%,rgba(255,255,255,0.00)_100%)]' />
  214. <div className='flex p-1 justify-center items-start'>
  215. <RiAlertFill className='w-4 h-4 flex-shrink-0 text-text-warning-secondary' />
  216. </div>
  217. <div className='flex py-1 flex-col items-start gap-0.5 flex-grow'>
  218. <div className='text-text-primary system-xs-medium whitespace-pre-line'>{t('workflow.common.importDSLTip')}</div>
  219. <div className='flex pt-1 pb-0.5 items-start gap-1 self-stretch'>
  220. <Button
  221. size='small'
  222. variant='secondary'
  223. className='z-[1000]'
  224. onClick={onBackup}
  225. >
  226. <RiFileDownloadLine className='w-3.5 h-3.5 text-components-button-secondary-text' />
  227. <div className='flex px-[3px] justify-center items-center gap-1'>
  228. {t('workflow.common.backupCurrentDraft')}
  229. </div>
  230. </Button>
  231. </div>
  232. </div>
  233. </div>
  234. <div>
  235. <div className='pt-2 text-text-primary system-md-semibold'>
  236. {t('workflow.common.chooseDSL')}
  237. </div>
  238. <div className='flex w-full py-4 flex-col justify-center items-start gap-4 self-stretch'>
  239. <Uploader
  240. file={currentFile}
  241. updateFile={handleFile}
  242. className='!mt-0 w-full'
  243. />
  244. </div>
  245. </div>
  246. <div className='flex pt-5 gap-2 items-center justify-end self-stretch'>
  247. <Button onClick={onCancel}>{t('app.newApp.Cancel')}</Button>
  248. <Button
  249. disabled={!currentFile || loading}
  250. variant='warning'
  251. onClick={handleImport}
  252. loading={loading}
  253. >
  254. {t('workflow.common.overwriteAndImport')}
  255. </Button>
  256. </div>
  257. </Modal>
  258. <Modal
  259. isShow={showErrorModal}
  260. onClose={() => setShowErrorModal(false)}
  261. className='w-[480px]'
  262. >
  263. <div className='flex pb-4 flex-col items-start gap-2 self-stretch'>
  264. <div className='text-text-primary title-2xl-semi-bold'>{t('app.newApp.appCreateDSLErrorTitle')}</div>
  265. <div className='flex flex-grow flex-col text-text-secondary system-md-regular'>
  266. <div>{t('app.newApp.appCreateDSLErrorPart1')}</div>
  267. <div>{t('app.newApp.appCreateDSLErrorPart2')}</div>
  268. <br />
  269. <div>{t('app.newApp.appCreateDSLErrorPart3')}<span className='system-md-medium'>{versions?.importedVersion}</span></div>
  270. <div>{t('app.newApp.appCreateDSLErrorPart4')}<span className='system-md-medium'>{versions?.systemVersion}</span></div>
  271. </div>
  272. </div>
  273. <div className='flex pt-6 justify-end items-start gap-2 self-stretch'>
  274. <Button variant='secondary' onClick={() => setShowErrorModal(false)}>{t('app.newApp.Cancel')}</Button>
  275. <Button variant='primary' destructive onClick={onUpdateDSLConfirm}>{t('app.newApp.Confirm')}</Button>
  276. </div>
  277. </Modal>
  278. </>
  279. )
  280. }
  281. export default memo(UpdateDSLModal)