index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. if (!isInstalledApp)
  232. await checkOrSetAccessToken()
  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), fetchSavedMessage()])
  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