index.tsx 18 KB

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