index.tsx 18 KB

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