index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useEffect, useRef, useState } from 'react'
  4. import { useTranslation } from 'react-i18next'
  5. import cn from 'classnames'
  6. import { useBoolean, useClickAway, useGetState } from 'ahooks'
  7. import { XMarkIcon } from '@heroicons/react/24/outline'
  8. import TabHeader from '../../base/tab-header'
  9. import Button from '../../base/button'
  10. import s from './style.module.css'
  11. import RunBatch from './run-batch'
  12. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  13. import RunOnce from '@/app/components/share/text-generation/run-once'
  14. import { fetchSavedMessage as doFetchSavedMessage, fetchAppInfo, fetchAppParams, removeMessage, saveMessage } from '@/service/share'
  15. import type { SiteInfo } from '@/models/share'
  16. import type { MoreLikeThisConfig, PromptConfig, SavedMessage } from '@/models/debug'
  17. import AppIcon from '@/app/components/base/app-icon'
  18. import { changeLanguage } from '@/i18n/i18next-config'
  19. import Loading from '@/app/components/base/loading'
  20. import { userInputsFormToPromptVariables } from '@/utils/model-config'
  21. import Res from '@/app/components/share/text-generation/result'
  22. import SavedItems from '@/app/components/app/text-generate/saved-items'
  23. import type { InstalledApp } from '@/models/explore'
  24. import { appDefaultIconBackground } from '@/config'
  25. import Toast from '@/app/components/base/toast'
  26. const PARALLEL_LIMIT = 5
  27. enum TaskStatus {
  28. pending = 'pending',
  29. running = 'running',
  30. completed = 'completed',
  31. }
  32. type TaskParam = {
  33. inputs: Record<string, any>
  34. query: string
  35. }
  36. type Task = {
  37. id: number
  38. status: TaskStatus
  39. params: TaskParam
  40. }
  41. export type IMainProps = {
  42. isInstalledApp?: boolean
  43. installedAppInfo?: InstalledApp
  44. }
  45. const TextGeneration: FC<IMainProps> = ({
  46. isInstalledApp = false,
  47. installedAppInfo,
  48. }) => {
  49. const { notify } = Toast
  50. const { t } = useTranslation()
  51. const media = useBreakpoints()
  52. const isPC = media === MediaType.pc
  53. const isTablet = media === MediaType.tablet
  54. const isMobile = media === MediaType.mobile
  55. const [currTab, setCurrTab] = useState<string>('create')
  56. // Notice this situation isCallBatchAPI but not in batch tab
  57. const [isCallBatchAPI, setIsCallBatchAPI] = useState(false)
  58. const isInBatchTab = currTab === 'batch'
  59. const [inputs, setInputs] = useState<Record<string, any>>({})
  60. const [query, setQuery] = useState('') // run once query content
  61. const [appId, setAppId] = useState<string>('')
  62. const [siteInfo, setSiteInfo] = useState<SiteInfo | null>(null)
  63. const [promptConfig, setPromptConfig] = useState<PromptConfig | null>(null)
  64. const [moreLikeThisConfig, setMoreLikeThisConfig] = useState<MoreLikeThisConfig | null>(null)
  65. // save message
  66. const [savedMessages, setSavedMessages] = useState<SavedMessage[]>([])
  67. const fetchSavedMessage = async () => {
  68. const res: any = await doFetchSavedMessage(isInstalledApp, installedAppInfo?.id)
  69. setSavedMessages(res.data)
  70. }
  71. useEffect(() => {
  72. fetchSavedMessage()
  73. }, [])
  74. const handleSaveMessage = async (messageId: string) => {
  75. await saveMessage(messageId, isInstalledApp, installedAppInfo?.id)
  76. notify({ type: 'success', message: t('common.api.saved') })
  77. fetchSavedMessage()
  78. }
  79. const handleRemoveSavedMessage = async (messageId: string) => {
  80. await removeMessage(messageId, isInstalledApp, installedAppInfo?.id)
  81. notify({ type: 'success', message: t('common.api.remove') })
  82. fetchSavedMessage()
  83. }
  84. // send message task
  85. const [controlSend, setControlSend] = useState(0)
  86. const [controlStopResponding, setControlStopResponding] = useState(0)
  87. const handleSend = () => {
  88. setIsCallBatchAPI(false)
  89. setControlSend(Date.now())
  90. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  91. setAllTaskList([]) // clear batch task running status
  92. }
  93. const [allTaskList, setAllTaskList, getLatestTaskList] = useGetState<Task[]>([])
  94. const pendingTaskList = allTaskList.filter(task => task.status === TaskStatus.pending)
  95. const noPendingTask = pendingTaskList.length === 0
  96. const showTaskList = allTaskList.filter(task => task.status !== TaskStatus.pending)
  97. const allTaskFinished = allTaskList.every(task => task.status === TaskStatus.completed)
  98. const checkBatchInputs = (data: string[][]) => {
  99. if (!data || data.length === 0) {
  100. notify({ type: 'error', message: t('share.generation.errorMsg.empty') })
  101. return false
  102. }
  103. const headerData = data[0]
  104. const varLen = promptConfig?.prompt_variables.length || 0
  105. let isMapVarName = true
  106. promptConfig?.prompt_variables.forEach((item, index) => {
  107. if (!isMapVarName)
  108. return
  109. if (item.name !== headerData[index])
  110. isMapVarName = false
  111. })
  112. if (headerData[varLen] !== t('share.generation.queryTitle'))
  113. isMapVarName = false
  114. if (!isMapVarName) {
  115. notify({ type: 'error', message: t('share.generation.errorMsg.fileStructNotMatch') })
  116. return false
  117. }
  118. let payloadData = data.slice(1)
  119. if (payloadData.length === 0) {
  120. notify({ type: 'error', message: t('share.generation.errorMsg.atLeastOne') })
  121. return false
  122. }
  123. // check middle empty line
  124. const allEmptyLineIndexes = payloadData.filter(item => item.every(i => i === '')).map(item => payloadData.indexOf(item))
  125. if (allEmptyLineIndexes.length > 0) {
  126. let hasMiddleEmptyLine = false
  127. let startIndex = allEmptyLineIndexes[0] - 1
  128. allEmptyLineIndexes.forEach((index) => {
  129. if (hasMiddleEmptyLine)
  130. return
  131. if (startIndex + 1 !== index) {
  132. hasMiddleEmptyLine = true
  133. return
  134. }
  135. startIndex++
  136. })
  137. if (hasMiddleEmptyLine) {
  138. notify({ type: 'error', message: t('share.generation.errorMsg.emptyLine', { rowIndex: startIndex + 2 }) })
  139. return false
  140. }
  141. }
  142. // check row format
  143. payloadData = payloadData.filter(item => !item.every(i => i === ''))
  144. // after remove empty rows in the end, checked again
  145. if (payloadData.length === 0) {
  146. notify({ type: 'error', message: t('share.generation.errorMsg.atLeastOne') })
  147. return false
  148. }
  149. let errorRowIndex = 0
  150. let requiredVarName = ''
  151. payloadData.forEach((item, index) => {
  152. if (errorRowIndex !== 0)
  153. return
  154. promptConfig?.prompt_variables.forEach((varItem, varIndex) => {
  155. if (errorRowIndex !== 0)
  156. return
  157. if (varItem.required === false)
  158. return
  159. if (item[varIndex].trim() === '') {
  160. requiredVarName = varItem.name
  161. errorRowIndex = index + 1
  162. }
  163. })
  164. if (errorRowIndex !== 0)
  165. return
  166. if (item[varLen] === '') {
  167. requiredVarName = t('share.generation.queryTitle')
  168. errorRowIndex = index + 1
  169. }
  170. })
  171. if (errorRowIndex !== 0) {
  172. notify({ type: 'error', message: t('share.generation.errorMsg.invalidLine', { rowIndex: errorRowIndex + 1, varName: requiredVarName }) })
  173. return false
  174. }
  175. return true
  176. }
  177. const handleRunBatch = (data: string[][]) => {
  178. if (!checkBatchInputs(data))
  179. return
  180. if (!allTaskFinished) {
  181. notify({ type: 'info', message: t('appDebug.errorMessage.waitForBatchResponse') })
  182. return
  183. }
  184. const payloadData = data.filter(item => !item.every(i => i === '')).slice(1)
  185. const varLen = promptConfig?.prompt_variables.length || 0
  186. setIsCallBatchAPI(true)
  187. const allTaskList: Task[] = payloadData.map((item, i) => {
  188. const inputs: Record<string, string> = {}
  189. if (varLen > 0) {
  190. item.slice(0, varLen).forEach((input, index) => {
  191. inputs[promptConfig?.prompt_variables[index].key as string] = input
  192. })
  193. }
  194. return {
  195. id: i + 1,
  196. status: i < PARALLEL_LIMIT ? TaskStatus.running : TaskStatus.pending,
  197. params: {
  198. inputs,
  199. query: item[varLen],
  200. },
  201. }
  202. })
  203. setAllTaskList(allTaskList)
  204. setControlSend(Date.now())
  205. // clear run once task status
  206. setControlStopResponding(Date.now())
  207. }
  208. const handleCompleted = (taskId?: number, isSuccess?: boolean) => {
  209. // console.log(taskId, isSuccess)
  210. const allTasklistLatest = getLatestTaskList()
  211. const pendingTaskList = allTasklistLatest.filter(task => task.status === TaskStatus.pending)
  212. const nextPendingTaskId = pendingTaskList[0]?.id
  213. // console.log(`start: ${allTasklistLatest.map(item => item.status).join(',')}`)
  214. const newAllTaskList = allTasklistLatest.map((item) => {
  215. if (item.id === taskId) {
  216. return {
  217. ...item,
  218. status: TaskStatus.completed,
  219. }
  220. }
  221. if (item.id === nextPendingTaskId) {
  222. return {
  223. ...item,
  224. status: TaskStatus.running,
  225. }
  226. }
  227. return item
  228. })
  229. // console.log(`end: ${newAllTaskList.map(item => item.status).join(',')}`)
  230. setAllTaskList(newAllTaskList)
  231. }
  232. const fetchInitData = () => {
  233. return Promise.all([isInstalledApp
  234. ? {
  235. app_id: installedAppInfo?.id,
  236. site: {
  237. title: installedAppInfo?.app.name,
  238. prompt_public: false,
  239. copyright: '',
  240. },
  241. plan: 'basic',
  242. }
  243. : fetchAppInfo(), fetchAppParams(isInstalledApp, installedAppInfo?.id)])
  244. }
  245. useEffect(() => {
  246. (async () => {
  247. const [appData, appParams]: any = await fetchInitData()
  248. const { app_id: appId, site: siteInfo } = appData
  249. setAppId(appId)
  250. setSiteInfo(siteInfo as SiteInfo)
  251. changeLanguage(siteInfo.default_language)
  252. const { user_input_form, more_like_this }: any = appParams
  253. const prompt_variables = userInputsFormToPromptVariables(user_input_form)
  254. setPromptConfig({
  255. prompt_template: '', // placeholder for feture
  256. prompt_variables,
  257. } as PromptConfig)
  258. setMoreLikeThisConfig(more_like_this)
  259. })()
  260. }, [])
  261. // Can Use metadata(https://beta.nextjs.org/docs/api-reference/metadata) to set title. But it only works in server side client.
  262. useEffect(() => {
  263. if (siteInfo?.title)
  264. document.title = `${siteInfo.title} - Powered by Dify`
  265. }, [siteInfo?.title])
  266. const [isShowResSidebar, { setTrue: showResSidebar, setFalse: hideResSidebar }] = useBoolean(false)
  267. const resRef = useRef<HTMLDivElement>(null)
  268. useClickAway(() => {
  269. hideResSidebar()
  270. }, resRef)
  271. const renderRes = (task?: Task) => (<Res
  272. key={task?.id}
  273. isCallBatchAPI={isCallBatchAPI}
  274. isPC={isPC}
  275. isMobile={isMobile}
  276. isInstalledApp={!!isInstalledApp}
  277. installedAppInfo={installedAppInfo}
  278. promptConfig={promptConfig}
  279. moreLikeThisEnabled={!!moreLikeThisConfig?.enabled}
  280. inputs={isCallBatchAPI ? (task as Task).params.inputs : inputs}
  281. query={isCallBatchAPI ? (task as Task).params.query : query}
  282. controlSend={controlSend}
  283. controlStopResponding={controlStopResponding}
  284. onShowRes={showResSidebar}
  285. handleSaveMessage={handleSaveMessage}
  286. taskId={task?.id}
  287. onCompleted={handleCompleted}
  288. />)
  289. const renderBatchRes = () => {
  290. return (showTaskList.map(task => renderRes(task)))
  291. }
  292. const renderResWrap = (
  293. <div
  294. ref={resRef}
  295. className={
  296. cn(
  297. 'flex flex-col h-full shrink-0',
  298. isPC ? 'px-10 py-8' : 'bg-gray-50',
  299. isTablet && 'p-6', isMobile && 'p-4')
  300. }
  301. >
  302. <>
  303. <div className='shrink-0 flex items-center justify-between'>
  304. <div className='flex items-center space-x-3'>
  305. <div className={s.starIcon}></div>
  306. <div className='text-lg text-gray-800 font-semibold'>{t('share.generation.title')}</div>
  307. </div>
  308. {!isPC && (
  309. <div
  310. className='flex items-center justify-center cursor-pointer'
  311. onClick={hideResSidebar}
  312. >
  313. <XMarkIcon className='w-4 h-4 text-gray-800' />
  314. </div>
  315. )}
  316. </div>
  317. <div className='grow overflow-y-auto'>
  318. {!isCallBatchAPI ? renderRes() : renderBatchRes()}
  319. {!noPendingTask && (
  320. <div className='mt-4'>
  321. <Loading type='area' />
  322. </div>
  323. )}
  324. </div>
  325. </>
  326. </div>
  327. )
  328. if (!appId || !siteInfo || !promptConfig)
  329. return <Loading type='app' />
  330. return (
  331. <>
  332. <div className={cn(
  333. isPC && 'flex',
  334. isInstalledApp ? s.installedApp : 'h-screen',
  335. 'bg-gray-50',
  336. )}>
  337. {/* Left */}
  338. <div className={cn(
  339. isPC ? 'w-[600px] max-w-[50%] p-8' : 'p-4',
  340. isInstalledApp && 'rounded-l-2xl',
  341. 'shrink-0 relative flex flex-col pb-10 h-full border-r border-gray-100 bg-white',
  342. )}>
  343. <div className='mb-6'>
  344. <div className='flex justify-between items-center'>
  345. <div className='flex items-center space-x-3'>
  346. <AppIcon size="small" icon={siteInfo.icon} background={siteInfo.icon_background || appDefaultIconBackground} />
  347. <div className='text-lg text-gray-800 font-semibold'>{siteInfo.title}</div>
  348. </div>
  349. {!isPC && (
  350. <Button
  351. className='shrink-0 !h-8 !px-3 ml-2'
  352. onClick={showResSidebar}
  353. >
  354. <div className='flex items-center space-x-2 text-primary-600 text-[13px] font-medium'>
  355. <div className={s.starIcon}></div>
  356. <span>{t('share.generation.title')}</span>
  357. </div>
  358. </Button>
  359. )}
  360. </div>
  361. {siteInfo.description && (
  362. <div className='mt-2 text-xs text-gray-500'>{siteInfo.description}</div>
  363. )}
  364. </div>
  365. <TabHeader
  366. items={[
  367. { id: 'create', name: t('share.generation.tabs.create') },
  368. { id: 'batch', name: t('share.generation.tabs.batch') },
  369. {
  370. id: 'saved',
  371. name: t('share.generation.tabs.saved'),
  372. isRight: true,
  373. extra: savedMessages.length > 0
  374. ? (
  375. <div className='ml-1 flext items-center h-5 px-1.5 rounded-md border border-gray-200 text-gray-500 text-xs font-medium'>
  376. {savedMessages.length}
  377. </div>
  378. )
  379. : null,
  380. },
  381. ]}
  382. value={currTab}
  383. onChange={setCurrTab}
  384. />
  385. <div className='grow h-20 overflow-y-auto'>
  386. <div className={cn(currTab === 'create' ? 'block' : 'hidden')}>
  387. <RunOnce
  388. siteInfo={siteInfo}
  389. inputs={inputs}
  390. onInputsChange={setInputs}
  391. promptConfig={promptConfig}
  392. query={query}
  393. onQueryChange={setQuery}
  394. onSend={handleSend}
  395. />
  396. </div>
  397. <div className={cn(isInBatchTab ? 'block' : 'hidden')}>
  398. <RunBatch
  399. vars={promptConfig.prompt_variables}
  400. onSend={handleRunBatch}
  401. />
  402. </div>
  403. {currTab === 'saved' && (
  404. <SavedItems
  405. className='mt-4'
  406. list={savedMessages}
  407. onRemove={handleRemoveSavedMessage}
  408. onStartCreateContent={() => setCurrTab('create')}
  409. />
  410. )}
  411. </div>
  412. {/* copyright */}
  413. <div className={cn(
  414. isInstalledApp ? 'left-[248px]' : 'left-8',
  415. 'fixed bottom-4 flex space-x-2 text-gray-400 font-normal text-xs',
  416. )}>
  417. <div className="">© {siteInfo.copyright || siteInfo.title} {(new Date()).getFullYear()}</div>
  418. {siteInfo.privacy_policy && (
  419. <>
  420. <div>·</div>
  421. <div>{t('share.chat.privacyPolicyLeft')}
  422. <a
  423. className='text-gray-500'
  424. href={siteInfo.privacy_policy}
  425. target='_blank'>{t('share.chat.privacyPolicyMiddle')}</a>
  426. {t('share.chat.privacyPolicyRight')}
  427. </div>
  428. </>
  429. )}
  430. </div>
  431. </div>
  432. {/* Result */}
  433. {isPC && (
  434. <div className='grow h-full'>
  435. {renderResWrap}
  436. </div>
  437. )}
  438. {(!isPC && isShowResSidebar) && (
  439. <div
  440. className={cn('fixed z-50 inset-0', isTablet ? 'pl-[128px]' : 'pl-6')}
  441. style={{
  442. background: 'rgba(35, 56, 118, 0.2)',
  443. }}
  444. >
  445. {renderResWrap}
  446. </div>
  447. )}
  448. </div>
  449. </>
  450. )
  451. }
  452. export default TextGeneration