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