index.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  91. showResSidebar()
  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. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  208. showResSidebar()
  209. }
  210. const handleCompleted = (taskId?: number, isSuccess?: boolean) => {
  211. // console.log(taskId, isSuccess)
  212. const allTasklistLatest = getLatestTaskList()
  213. const pendingTaskList = allTasklistLatest.filter(task => task.status === TaskStatus.pending)
  214. const nextPendingTaskId = pendingTaskList[0]?.id
  215. // console.log(`start: ${allTasklistLatest.map(item => item.status).join(',')}`)
  216. const newAllTaskList = allTasklistLatest.map((item) => {
  217. if (item.id === taskId) {
  218. return {
  219. ...item,
  220. status: TaskStatus.completed,
  221. }
  222. }
  223. if (item.id === nextPendingTaskId) {
  224. return {
  225. ...item,
  226. status: TaskStatus.running,
  227. }
  228. }
  229. return item
  230. })
  231. // console.log(`end: ${newAllTaskList.map(item => item.status).join(',')}`)
  232. setAllTaskList(newAllTaskList)
  233. }
  234. const fetchInitData = async () => {
  235. if (!isInstalledApp)
  236. await checkOrSetAccessToken()
  237. return Promise.all([isInstalledApp
  238. ? {
  239. app_id: installedAppInfo?.id,
  240. site: {
  241. title: installedAppInfo?.app.name,
  242. prompt_public: false,
  243. copyright: '',
  244. },
  245. plan: 'basic',
  246. }
  247. : fetchAppInfo(), fetchAppParams(isInstalledApp, installedAppInfo?.id), fetchSavedMessage()])
  248. }
  249. useEffect(() => {
  250. (async () => {
  251. const [appData, appParams]: any = await fetchInitData()
  252. const { app_id: appId, site: siteInfo } = appData
  253. setAppId(appId)
  254. setSiteInfo(siteInfo as SiteInfo)
  255. changeLanguage(siteInfo.default_language)
  256. const { user_input_form, more_like_this }: any = appParams
  257. const prompt_variables = userInputsFormToPromptVariables(user_input_form)
  258. setPromptConfig({
  259. prompt_template: '', // placeholder for feture
  260. prompt_variables,
  261. } as PromptConfig)
  262. setMoreLikeThisConfig(more_like_this)
  263. })()
  264. }, [])
  265. // Can Use metadata(https://beta.nextjs.org/docs/api-reference/metadata) to set title. But it only works in server side client.
  266. useEffect(() => {
  267. if (siteInfo?.title)
  268. document.title = `${siteInfo.title} - Powered by Dify`
  269. }, [siteInfo?.title])
  270. const [isShowResSidebar, { setTrue: showResSidebar, setFalse: hideResSidebar }] = useBoolean(false)
  271. const resRef = useRef<HTMLDivElement>(null)
  272. useClickAway(() => {
  273. hideResSidebar()
  274. }, resRef)
  275. const renderRes = (task?: Task) => (<Res
  276. key={task?.id}
  277. isCallBatchAPI={isCallBatchAPI}
  278. isPC={isPC}
  279. isMobile={isMobile}
  280. isInstalledApp={!!isInstalledApp}
  281. installedAppInfo={installedAppInfo}
  282. promptConfig={promptConfig}
  283. moreLikeThisEnabled={!!moreLikeThisConfig?.enabled}
  284. inputs={isCallBatchAPI ? (task as Task).params.inputs : inputs}
  285. query={isCallBatchAPI ? (task as Task).params.query : query}
  286. controlSend={controlSend}
  287. controlStopResponding={controlStopResponding}
  288. onShowRes={showResSidebar}
  289. handleSaveMessage={handleSaveMessage}
  290. taskId={task?.id}
  291. onCompleted={handleCompleted}
  292. />)
  293. const renderBatchRes = () => {
  294. return (showTaskList.map(task => renderRes(task)))
  295. }
  296. const renderResWrap = (
  297. <div
  298. ref={resRef}
  299. className={
  300. cn(
  301. 'flex flex-col h-full shrink-0',
  302. isPC ? 'px-10 py-8' : 'bg-gray-50',
  303. isTablet && 'p-6', isMobile && 'p-4')
  304. }
  305. >
  306. <>
  307. <div className='shrink-0 flex items-center justify-between'>
  308. <div className='flex items-center space-x-3'>
  309. <div className={s.starIcon}></div>
  310. <div className='text-lg text-gray-800 font-semibold'>{t('share.generation.title')}</div>
  311. </div>
  312. {!isPC && (
  313. <div
  314. className='flex items-center justify-center cursor-pointer'
  315. onClick={hideResSidebar}
  316. >
  317. <XMarkIcon className='w-4 h-4 text-gray-800' />
  318. </div>
  319. )}
  320. </div>
  321. <div className='grow overflow-y-auto'>
  322. {!isCallBatchAPI ? renderRes() : renderBatchRes()}
  323. {!noPendingTask && (
  324. <div className='mt-4'>
  325. <Loading type='area' />
  326. </div>
  327. )}
  328. </div>
  329. </>
  330. </div>
  331. )
  332. if (!appId || !siteInfo || !promptConfig)
  333. return <Loading type='app' />
  334. return (
  335. <>
  336. <div className={cn(
  337. isPC && 'flex',
  338. isInstalledApp ? s.installedApp : 'h-screen',
  339. 'bg-gray-50',
  340. )}>
  341. {/* Left */}
  342. <div className={cn(
  343. isPC ? 'w-[600px] max-w-[50%] p-8' : 'p-4',
  344. isInstalledApp && 'rounded-l-2xl',
  345. 'shrink-0 relative flex flex-col pb-10 h-full border-r border-gray-100 bg-white',
  346. )}>
  347. <div className='mb-6'>
  348. <div className='flex justify-between items-center'>
  349. <div className='flex items-center space-x-3'>
  350. <AppIcon size="small" icon={siteInfo.icon} background={siteInfo.icon_background || appDefaultIconBackground} />
  351. <div className='text-lg text-gray-800 font-semibold'>{siteInfo.title}</div>
  352. </div>
  353. {!isPC && (
  354. <Button
  355. className='shrink-0 !h-8 !px-3 ml-2'
  356. onClick={showResSidebar}
  357. >
  358. <div className='flex items-center space-x-2 text-primary-600 text-[13px] font-medium'>
  359. <div className={s.starIcon}></div>
  360. <span>{t('share.generation.title')}</span>
  361. </div>
  362. </Button>
  363. )}
  364. </div>
  365. {siteInfo.description && (
  366. <div className='mt-2 text-xs text-gray-500'>{siteInfo.description}</div>
  367. )}
  368. </div>
  369. <TabHeader
  370. items={[
  371. { id: 'create', name: t('share.generation.tabs.create') },
  372. { id: 'batch', name: t('share.generation.tabs.batch') },
  373. {
  374. id: 'saved',
  375. name: t('share.generation.tabs.saved'),
  376. isRight: true,
  377. extra: savedMessages.length > 0
  378. ? (
  379. <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'>
  380. {savedMessages.length}
  381. </div>
  382. )
  383. : null,
  384. },
  385. ]}
  386. value={currTab}
  387. onChange={setCurrTab}
  388. />
  389. <div className='grow h-20 overflow-y-auto'>
  390. <div className={cn(currTab === 'create' ? 'block' : 'hidden')}>
  391. <RunOnce
  392. siteInfo={siteInfo}
  393. inputs={inputs}
  394. onInputsChange={setInputs}
  395. promptConfig={promptConfig}
  396. query={query}
  397. onQueryChange={setQuery}
  398. onSend={handleSend}
  399. />
  400. </div>
  401. <div className={cn(isInBatchTab ? 'block' : 'hidden')}>
  402. <RunBatch
  403. vars={promptConfig.prompt_variables}
  404. onSend={handleRunBatch}
  405. />
  406. </div>
  407. {currTab === 'saved' && (
  408. <SavedItems
  409. className='mt-4'
  410. list={savedMessages}
  411. onRemove={handleRemoveSavedMessage}
  412. onStartCreateContent={() => setCurrTab('create')}
  413. />
  414. )}
  415. </div>
  416. {/* copyright */}
  417. <div className={cn(
  418. isInstalledApp ? 'left-[248px]' : 'left-8',
  419. 'fixed bottom-4 flex space-x-2 text-gray-400 font-normal text-xs',
  420. )}>
  421. <div className="">© {siteInfo.copyright || siteInfo.title} {(new Date()).getFullYear()}</div>
  422. {siteInfo.privacy_policy && (
  423. <>
  424. <div>·</div>
  425. <div>{t('share.chat.privacyPolicyLeft')}
  426. <a
  427. className='text-gray-500'
  428. href={siteInfo.privacy_policy}
  429. target='_blank'>{t('share.chat.privacyPolicyMiddle')}</a>
  430. {t('share.chat.privacyPolicyRight')}
  431. </div>
  432. </>
  433. )}
  434. </div>
  435. </div>
  436. {/* Result */}
  437. {isPC && (
  438. <div className='grow h-full'>
  439. {renderResWrap}
  440. </div>
  441. )}
  442. {(!isPC && isShowResSidebar) && (
  443. <div
  444. className={cn('fixed z-50 inset-0', isTablet ? 'pl-[128px]' : 'pl-6')}
  445. style={{
  446. background: 'rgba(35, 56, 118, 0.2)',
  447. }}
  448. >
  449. {renderResWrap}
  450. </div>
  451. )}
  452. </div>
  453. </>
  454. )
  455. }
  456. export default TextGeneration