index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. 'use client'
  2. import type { FC } from 'react'
  3. import {
  4. memo,
  5. useCallback,
  6. useEffect,
  7. useMemo,
  8. useRef,
  9. useState,
  10. } from 'react'
  11. import useSWR from 'swr'
  12. import { setAutoFreeze } from 'immer'
  13. import {
  14. useEventListener,
  15. } from 'ahooks'
  16. import ReactFlow, {
  17. Background,
  18. ReactFlowProvider,
  19. SelectionMode,
  20. useEdgesState,
  21. useNodesState,
  22. useOnViewportChange,
  23. useReactFlow,
  24. useStoreApi,
  25. } from 'reactflow'
  26. import type {
  27. Viewport,
  28. } from 'reactflow'
  29. import 'reactflow/dist/style.css'
  30. import './style.css'
  31. import type {
  32. Edge,
  33. EnvironmentVariable,
  34. Node,
  35. } from './types'
  36. import {
  37. ControlMode,
  38. SupportUploadFileTypes,
  39. } from './types'
  40. import { WorkflowContextProvider } from './context'
  41. import {
  42. useDSL,
  43. useEdgesInteractions,
  44. useNodesInteractions,
  45. useNodesReadOnly,
  46. useNodesSyncDraft,
  47. usePanelInteractions,
  48. useSelectionInteractions,
  49. useShortcuts,
  50. useWorkflow,
  51. useWorkflowInit,
  52. useWorkflowReadOnly,
  53. useWorkflowUpdate,
  54. } from './hooks'
  55. import Header from './header'
  56. import CustomNode from './nodes'
  57. import CustomNoteNode from './note-node'
  58. import { CUSTOM_NOTE_NODE } from './note-node/constants'
  59. import CustomIterationStartNode from './nodes/iteration-start'
  60. import { CUSTOM_ITERATION_START_NODE } from './nodes/iteration-start/constants'
  61. import Operator from './operator'
  62. import CustomEdge from './custom-edge'
  63. import CustomConnectionLine from './custom-connection-line'
  64. import Panel from './panel'
  65. import Features from './features'
  66. import HelpLine from './help-line'
  67. import CandidateNode from './candidate-node'
  68. import PanelContextmenu from './panel-contextmenu'
  69. import NodeContextmenu from './node-contextmenu'
  70. import SyncingDataModal from './syncing-data-modal'
  71. import UpdateDSLModal from './update-dsl-modal'
  72. import DSLExportConfirmModal from './dsl-export-confirm-modal'
  73. import LimitTips from './limit-tips'
  74. import {
  75. useStore,
  76. useWorkflowStore,
  77. } from './store'
  78. import {
  79. initialEdges,
  80. initialNodes,
  81. } from './utils'
  82. import {
  83. CUSTOM_NODE,
  84. DSL_EXPORT_CHECK,
  85. ITERATION_CHILDREN_Z_INDEX,
  86. WORKFLOW_DATA_UPDATE,
  87. } from './constants'
  88. import { WorkflowHistoryProvider } from './workflow-history-store'
  89. import Loading from '@/app/components/base/loading'
  90. import { FeaturesProvider } from '@/app/components/base/features'
  91. import type { Features as FeaturesData } from '@/app/components/base/features/types'
  92. import { useFeaturesStore } from '@/app/components/base/features/hooks'
  93. import { useEventEmitterContextContext } from '@/context/event-emitter'
  94. import Confirm from '@/app/components/base/confirm'
  95. import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
  96. import { fetchFileUploadConfig } from '@/service/common'
  97. const nodeTypes = {
  98. [CUSTOM_NODE]: CustomNode,
  99. [CUSTOM_NOTE_NODE]: CustomNoteNode,
  100. [CUSTOM_ITERATION_START_NODE]: CustomIterationStartNode,
  101. }
  102. const edgeTypes = {
  103. [CUSTOM_NODE]: CustomEdge,
  104. }
  105. type WorkflowProps = {
  106. nodes: Node[]
  107. edges: Edge[]
  108. viewport?: Viewport
  109. }
  110. const Workflow: FC<WorkflowProps> = memo(({
  111. nodes: originalNodes,
  112. edges: originalEdges,
  113. viewport,
  114. }) => {
  115. const workflowContainerRef = useRef<HTMLDivElement>(null)
  116. const workflowStore = useWorkflowStore()
  117. const reactflow = useReactFlow()
  118. const featuresStore = useFeaturesStore()
  119. const [nodes, setNodes] = useNodesState(originalNodes)
  120. const [edges, setEdges] = useEdgesState(originalEdges)
  121. const showFeaturesPanel = useStore(state => state.showFeaturesPanel)
  122. const controlMode = useStore(s => s.controlMode)
  123. const nodeAnimation = useStore(s => s.nodeAnimation)
  124. const showConfirm = useStore(s => s.showConfirm)
  125. const showImportDSLModal = useStore(s => s.showImportDSLModal)
  126. const {
  127. setShowConfirm,
  128. setControlPromptEditorRerenderKey,
  129. setShowImportDSLModal,
  130. setSyncWorkflowDraftHash,
  131. } = workflowStore.getState()
  132. const {
  133. handleSyncWorkflowDraft,
  134. syncWorkflowDraftWhenPageClose,
  135. } = useNodesSyncDraft()
  136. const { workflowReadOnly } = useWorkflowReadOnly()
  137. const { nodesReadOnly } = useNodesReadOnly()
  138. const [secretEnvList, setSecretEnvList] = useState<EnvironmentVariable[]>([])
  139. const { eventEmitter } = useEventEmitterContextContext()
  140. eventEmitter?.useSubscription((v: any) => {
  141. if (v.type === WORKFLOW_DATA_UPDATE) {
  142. setNodes(v.payload.nodes)
  143. setEdges(v.payload.edges)
  144. if (v.payload.viewport)
  145. reactflow.setViewport(v.payload.viewport)
  146. if (v.payload.features && featuresStore) {
  147. const { setFeatures } = featuresStore.getState()
  148. setFeatures(v.payload.features)
  149. }
  150. if (v.payload.hash)
  151. setSyncWorkflowDraftHash(v.payload.hash)
  152. setTimeout(() => setControlPromptEditorRerenderKey(Date.now()))
  153. }
  154. if (v.type === DSL_EXPORT_CHECK)
  155. setSecretEnvList(v.payload.data as EnvironmentVariable[])
  156. })
  157. useEffect(() => {
  158. setAutoFreeze(false)
  159. return () => {
  160. setAutoFreeze(true)
  161. }
  162. }, [])
  163. useEffect(() => {
  164. return () => {
  165. handleSyncWorkflowDraft(true, true)
  166. }
  167. // eslint-disable-next-line react-hooks/exhaustive-deps
  168. }, [])
  169. const { handleRefreshWorkflowDraft } = useWorkflowUpdate()
  170. const handleSyncWorkflowDraftWhenPageClose = useCallback(() => {
  171. if (document.visibilityState === 'hidden')
  172. syncWorkflowDraftWhenPageClose()
  173. else if (document.visibilityState === 'visible')
  174. setTimeout(() => handleRefreshWorkflowDraft(), 500)
  175. }, [syncWorkflowDraftWhenPageClose, handleRefreshWorkflowDraft])
  176. useEffect(() => {
  177. document.addEventListener('visibilitychange', handleSyncWorkflowDraftWhenPageClose)
  178. return () => {
  179. document.removeEventListener('visibilitychange', handleSyncWorkflowDraftWhenPageClose)
  180. }
  181. }, [handleSyncWorkflowDraftWhenPageClose])
  182. useEventListener('keydown', (e) => {
  183. if ((e.key === 'd' || e.key === 'D') && (e.ctrlKey || e.metaKey))
  184. e.preventDefault()
  185. if ((e.key === 'z' || e.key === 'Z') && (e.ctrlKey || e.metaKey))
  186. e.preventDefault()
  187. if ((e.key === 'y' || e.key === 'Y') && (e.ctrlKey || e.metaKey))
  188. e.preventDefault()
  189. if ((e.key === 's' || e.key === 'S') && (e.ctrlKey || e.metaKey))
  190. e.preventDefault()
  191. })
  192. useEventListener('mousemove', (e) => {
  193. const containerClientRect = workflowContainerRef.current?.getBoundingClientRect()
  194. if (containerClientRect) {
  195. workflowStore.setState({
  196. mousePosition: {
  197. pageX: e.clientX,
  198. pageY: e.clientY,
  199. elementX: e.clientX - containerClientRect.left,
  200. elementY: e.clientY - containerClientRect.top,
  201. },
  202. })
  203. }
  204. })
  205. const {
  206. handleNodeDragStart,
  207. handleNodeDrag,
  208. handleNodeDragStop,
  209. handleNodeEnter,
  210. handleNodeLeave,
  211. handleNodeClick,
  212. handleNodeConnect,
  213. handleNodeConnectStart,
  214. handleNodeConnectEnd,
  215. handleNodeContextMenu,
  216. handleHistoryBack,
  217. handleHistoryForward,
  218. } = useNodesInteractions()
  219. const {
  220. handleEdgeEnter,
  221. handleEdgeLeave,
  222. handleEdgesChange,
  223. } = useEdgesInteractions()
  224. const {
  225. handleSelectionStart,
  226. handleSelectionChange,
  227. handleSelectionDrag,
  228. } = useSelectionInteractions()
  229. const {
  230. handlePaneContextMenu,
  231. handlePaneContextmenuCancel,
  232. } = usePanelInteractions()
  233. const {
  234. isValidConnection,
  235. } = useWorkflow()
  236. const {
  237. exportCheck,
  238. handleExportDSL,
  239. } = useDSL()
  240. useOnViewportChange({
  241. onEnd: () => {
  242. handleSyncWorkflowDraft()
  243. },
  244. })
  245. useShortcuts()
  246. const store = useStoreApi()
  247. if (process.env.NODE_ENV === 'development') {
  248. store.getState().onError = (code, message) => {
  249. if (code === '002')
  250. return
  251. console.warn(message)
  252. }
  253. }
  254. return (
  255. <div
  256. id='workflow-container'
  257. className={`
  258. relative w-full min-w-[960px] h-full bg-[#F0F2F7]
  259. ${workflowReadOnly && 'workflow-panel-animation'}
  260. ${nodeAnimation && 'workflow-node-animation'}
  261. `}
  262. ref={workflowContainerRef}
  263. >
  264. <SyncingDataModal />
  265. <CandidateNode />
  266. <Header />
  267. <Panel />
  268. <Operator handleRedo={handleHistoryForward} handleUndo={handleHistoryBack} />
  269. {
  270. showFeaturesPanel && <Features />
  271. }
  272. <PanelContextmenu />
  273. <NodeContextmenu />
  274. <HelpLine />
  275. {
  276. !!showConfirm && (
  277. <Confirm
  278. isShow
  279. onCancel={() => setShowConfirm(undefined)}
  280. onConfirm={showConfirm.onConfirm}
  281. title={showConfirm.title}
  282. content={showConfirm.desc}
  283. />
  284. )
  285. }
  286. {
  287. showImportDSLModal && (
  288. <UpdateDSLModal
  289. onCancel={() => setShowImportDSLModal(false)}
  290. onBackup={exportCheck}
  291. onImport={handlePaneContextmenuCancel}
  292. />
  293. )
  294. }
  295. {
  296. secretEnvList.length > 0 && (
  297. <DSLExportConfirmModal
  298. envList={secretEnvList}
  299. onConfirm={handleExportDSL}
  300. onClose={() => setSecretEnvList([])}
  301. />
  302. )
  303. }
  304. <LimitTips />
  305. <ReactFlow
  306. nodeTypes={nodeTypes}
  307. edgeTypes={edgeTypes}
  308. nodes={nodes}
  309. edges={edges}
  310. onNodeDragStart={handleNodeDragStart}
  311. onNodeDrag={handleNodeDrag}
  312. onNodeDragStop={handleNodeDragStop}
  313. onNodeMouseEnter={handleNodeEnter}
  314. onNodeMouseLeave={handleNodeLeave}
  315. onNodeClick={handleNodeClick}
  316. onNodeContextMenu={handleNodeContextMenu}
  317. onConnect={handleNodeConnect}
  318. onConnectStart={handleNodeConnectStart}
  319. onConnectEnd={handleNodeConnectEnd}
  320. onEdgeMouseEnter={handleEdgeEnter}
  321. onEdgeMouseLeave={handleEdgeLeave}
  322. onEdgesChange={handleEdgesChange}
  323. onSelectionStart={handleSelectionStart}
  324. onSelectionChange={handleSelectionChange}
  325. onSelectionDrag={handleSelectionDrag}
  326. onPaneContextMenu={handlePaneContextMenu}
  327. connectionLineComponent={CustomConnectionLine}
  328. connectionLineContainerStyle={{ zIndex: ITERATION_CHILDREN_Z_INDEX }}
  329. defaultViewport={viewport}
  330. multiSelectionKeyCode={null}
  331. deleteKeyCode={null}
  332. nodesDraggable={!nodesReadOnly}
  333. nodesConnectable={!nodesReadOnly}
  334. nodesFocusable={!nodesReadOnly}
  335. edgesFocusable={!nodesReadOnly}
  336. panOnDrag={controlMode === ControlMode.Hand && !workflowReadOnly}
  337. zoomOnPinch={!workflowReadOnly}
  338. zoomOnScroll={!workflowReadOnly}
  339. zoomOnDoubleClick={!workflowReadOnly}
  340. isValidConnection={isValidConnection}
  341. selectionKeyCode={null}
  342. selectionMode={SelectionMode.Partial}
  343. selectionOnDrag={controlMode === ControlMode.Pointer && !workflowReadOnly}
  344. minZoom={0.25}
  345. >
  346. <Background
  347. gap={[14, 14]}
  348. size={2}
  349. color='#E4E5E7'
  350. />
  351. </ReactFlow>
  352. </div>
  353. )
  354. })
  355. Workflow.displayName = 'Workflow'
  356. const WorkflowWrap = memo(() => {
  357. const {
  358. data,
  359. isLoading,
  360. } = useWorkflowInit()
  361. const { data: fileUploadConfigResponse } = useSWR({ url: '/files/upload' }, fetchFileUploadConfig)
  362. const nodesData = useMemo(() => {
  363. if (data)
  364. return initialNodes(data.graph.nodes, data.graph.edges)
  365. return []
  366. }, [data])
  367. const edgesData = useMemo(() => {
  368. if (data)
  369. return initialEdges(data.graph.edges, data.graph.nodes)
  370. return []
  371. }, [data])
  372. if (!data || isLoading) {
  373. return (
  374. <div className='flex justify-center items-center relative w-full h-full bg-[#F0F2F7]'>
  375. <Loading />
  376. </div>
  377. )
  378. }
  379. const features = data.features || {}
  380. const initialFeatures: FeaturesData = {
  381. file: {
  382. image: {
  383. enabled: !!features.file_upload?.image?.enabled,
  384. number_limits: features.file_upload?.image?.number_limits || 3,
  385. transfer_methods: features.file_upload?.image?.transfer_methods || ['local_file', 'remote_url'],
  386. },
  387. enabled: !!(features.file_upload?.enabled || features.file_upload?.image?.enabled),
  388. allowed_file_types: features.file_upload?.allowed_file_types || [SupportUploadFileTypes.image],
  389. allowed_file_extensions: features.file_upload?.allowed_file_extensions || FILE_EXTS[SupportUploadFileTypes.image].map(ext => `.${ext}`),
  390. allowed_file_upload_methods: features.file_upload?.allowed_file_upload_methods || features.file_upload?.image?.transfer_methods || ['local_file', 'remote_url'],
  391. number_limits: features.file_upload?.number_limits || features.file_upload?.image?.number_limits || 3,
  392. fileUploadConfig: fileUploadConfigResponse,
  393. },
  394. opening: {
  395. enabled: !!features.opening_statement,
  396. opening_statement: features.opening_statement,
  397. suggested_questions: features.suggested_questions,
  398. },
  399. suggested: features.suggested_questions_after_answer || { enabled: false },
  400. speech2text: features.speech_to_text || { enabled: false },
  401. text2speech: features.text_to_speech || { enabled: false },
  402. citation: features.retriever_resource || { enabled: false },
  403. moderation: features.sensitive_word_avoidance || { enabled: false },
  404. }
  405. return (
  406. <ReactFlowProvider>
  407. <WorkflowHistoryProvider
  408. nodes={nodesData}
  409. edges={edgesData} >
  410. <FeaturesProvider features={initialFeatures}>
  411. <Workflow
  412. nodes={nodesData}
  413. edges={edgesData}
  414. viewport={data?.graph.viewport}
  415. />
  416. </FeaturesProvider>
  417. </WorkflowHistoryProvider>
  418. </ReactFlowProvider>
  419. )
  420. })
  421. WorkflowWrap.displayName = 'WorkflowWrap'
  422. const WorkflowContainer = () => {
  423. return (
  424. <WorkflowContextProvider>
  425. <WorkflowWrap />
  426. </WorkflowContextProvider>
  427. )
  428. }
  429. export default memo(WorkflowContainer)