index.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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 {
  6. RiErrorWarningFill,
  7. } from '@remixicon/react'
  8. import { useBoolean, useClickAway } from 'ahooks'
  9. import { XMarkIcon } from '@heroicons/react/24/outline'
  10. import { usePathname, useRouter, useSearchParams } from 'next/navigation'
  11. import TabHeader from '../../base/tab-header'
  12. import Button from '../../base/button'
  13. import { checkOrSetAccessToken } from '../utils'
  14. import s from './style.module.css'
  15. import RunBatch from './run-batch'
  16. import ResDownload from './run-batch/res-download'
  17. import cn from '@/utils/classnames'
  18. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  19. import RunOnce from '@/app/components/share/text-generation/run-once'
  20. import { fetchSavedMessage as doFetchSavedMessage, fetchAppInfo, fetchAppParams, removeMessage, saveMessage } from '@/service/share'
  21. import type { SiteInfo } from '@/models/share'
  22. import type {
  23. MoreLikeThisConfig,
  24. PromptConfig,
  25. SavedMessage,
  26. TextToSpeechConfig,
  27. } from '@/models/debug'
  28. import AppIcon from '@/app/components/base/app-icon'
  29. import { changeLanguage } from '@/i18n/i18next-config'
  30. import Loading from '@/app/components/base/loading'
  31. import { userInputsFormToPromptVariables } from '@/utils/model-config'
  32. import Res from '@/app/components/share/text-generation/result'
  33. import SavedItems from '@/app/components/app/text-generate/saved-items'
  34. import type { InstalledApp } from '@/models/explore'
  35. import { DEFAULT_VALUE_MAX_LEN, appDefaultIconBackground } from '@/config'
  36. import Toast from '@/app/components/base/toast'
  37. import type { VisionFile, VisionSettings } from '@/types/app'
  38. import { Resolution, TransferMethod } from '@/types/app'
  39. import { useAppFavicon } from '@/hooks/use-app-favicon'
  40. const GROUP_SIZE = 5 // to avoid RPM(Request per minute) limit. The group task finished then the next group.
  41. enum TaskStatus {
  42. pending = 'pending',
  43. running = 'running',
  44. completed = 'completed',
  45. failed = 'failed',
  46. }
  47. type TaskParam = {
  48. inputs: Record<string, any>
  49. }
  50. type Task = {
  51. id: number
  52. status: TaskStatus
  53. params: TaskParam
  54. }
  55. export type IMainProps = {
  56. isInstalledApp?: boolean
  57. installedAppInfo?: InstalledApp
  58. isWorkflow?: boolean
  59. }
  60. const TextGeneration: FC<IMainProps> = ({
  61. isInstalledApp = false,
  62. installedAppInfo,
  63. isWorkflow = false,
  64. }) => {
  65. const { notify } = Toast
  66. const { t } = useTranslation()
  67. const media = useBreakpoints()
  68. const isPC = media === MediaType.pc
  69. const isTablet = media === MediaType.tablet
  70. const isMobile = media === MediaType.mobile
  71. const searchParams = useSearchParams()
  72. const mode = searchParams.get('mode') || 'create'
  73. const [currentTab, setCurrentTab] = useState<string>(['create', 'batch'].includes(mode) ? mode : 'create')
  74. const router = useRouter()
  75. const pathname = usePathname()
  76. useEffect(() => {
  77. const params = new URLSearchParams(searchParams)
  78. if (params.has('mode')) {
  79. params.delete('mode')
  80. router.replace(`${pathname}?${params.toString()}`)
  81. }
  82. // eslint-disable-next-line react-hooks/exhaustive-deps
  83. }, [])
  84. // Notice this situation isCallBatchAPI but not in batch tab
  85. const [isCallBatchAPI, setIsCallBatchAPI] = useState(false)
  86. const isInBatchTab = currentTab === 'batch'
  87. const [inputs, setInputs] = useState<Record<string, any>>({})
  88. const [appId, setAppId] = useState<string>('')
  89. const [siteInfo, setSiteInfo] = useState<SiteInfo | null>(null)
  90. const [canReplaceLogo, setCanReplaceLogo] = useState<boolean>(false)
  91. const [promptConfig, setPromptConfig] = useState<PromptConfig | null>(null)
  92. const [moreLikeThisConfig, setMoreLikeThisConfig] = useState<MoreLikeThisConfig | null>(null)
  93. const [textToSpeechConfig, setTextToSpeechConfig] = useState<TextToSpeechConfig | null>(null)
  94. // save message
  95. const [savedMessages, setSavedMessages] = useState<SavedMessage[]>([])
  96. const fetchSavedMessage = async () => {
  97. const res: any = await doFetchSavedMessage(isInstalledApp, installedAppInfo?.id)
  98. setSavedMessages(res.data)
  99. }
  100. const handleSaveMessage = async (messageId: string) => {
  101. await saveMessage(messageId, isInstalledApp, installedAppInfo?.id)
  102. notify({ type: 'success', message: t('common.api.saved') })
  103. fetchSavedMessage()
  104. }
  105. const handleRemoveSavedMessage = async (messageId: string) => {
  106. await removeMessage(messageId, isInstalledApp, installedAppInfo?.id)
  107. notify({ type: 'success', message: t('common.api.remove') })
  108. fetchSavedMessage()
  109. }
  110. // send message task
  111. const [controlSend, setControlSend] = useState(0)
  112. const [controlStopResponding, setControlStopResponding] = useState(0)
  113. const [visionConfig, setVisionConfig] = useState<VisionSettings>({
  114. enabled: false,
  115. number_limits: 2,
  116. detail: Resolution.low,
  117. transfer_methods: [TransferMethod.local_file],
  118. })
  119. const [completionFiles, setCompletionFiles] = useState<VisionFile[]>([])
  120. const handleSend = () => {
  121. setIsCallBatchAPI(false)
  122. setControlSend(Date.now())
  123. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  124. setAllTaskList([]) // clear batch task running status
  125. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  126. showResSidebar()
  127. }
  128. const [controlRetry, setControlRetry] = useState(0)
  129. const handleRetryAllFailedTask = () => {
  130. setControlRetry(Date.now())
  131. }
  132. const [allTaskList, doSetAllTaskList] = useState<Task[]>([])
  133. const allTaskListRef = useRef<Task[]>([])
  134. const getLatestTaskList = () => allTaskListRef.current
  135. const setAllTaskList = (taskList: Task[]) => {
  136. doSetAllTaskList(taskList)
  137. allTaskListRef.current = taskList
  138. }
  139. const pendingTaskList = allTaskList.filter(task => task.status === TaskStatus.pending)
  140. const noPendingTask = pendingTaskList.length === 0
  141. const showTaskList = allTaskList.filter(task => task.status !== TaskStatus.pending)
  142. const [currGroupNum, doSetCurrGroupNum] = useState(0)
  143. const currGroupNumRef = useRef(0)
  144. const setCurrGroupNum = (num: number) => {
  145. doSetCurrGroupNum(num)
  146. currGroupNumRef.current = num
  147. }
  148. const getCurrGroupNum = () => {
  149. return currGroupNumRef.current
  150. }
  151. const allSuccessTaskList = allTaskList.filter(task => task.status === TaskStatus.completed)
  152. const allFailedTaskList = allTaskList.filter(task => task.status === TaskStatus.failed)
  153. const allTasksFinished = allTaskList.every(task => task.status === TaskStatus.completed)
  154. const allTasksRun = allTaskList.every(task => [TaskStatus.completed, TaskStatus.failed].includes(task.status))
  155. const [batchCompletionRes, doSetBatchCompletionRes] = useState<Record<string, string>>({})
  156. const batchCompletionResRef = useRef<Record<string, string>>({})
  157. const setBatchCompletionRes = (res: Record<string, string>) => {
  158. doSetBatchCompletionRes(res)
  159. batchCompletionResRef.current = res
  160. }
  161. const getBatchCompletionRes = () => batchCompletionResRef.current
  162. const exportRes = allTaskList.map((task) => {
  163. const batchCompletionResLatest = getBatchCompletionRes()
  164. const res: Record<string, string> = {}
  165. const { inputs } = task.params
  166. promptConfig?.prompt_variables.forEach((v) => {
  167. res[v.name] = inputs[v.key]
  168. })
  169. let result = batchCompletionResLatest[task.id]
  170. // task might return multiple fields, should marshal object to string
  171. if (typeof batchCompletionResLatest[task.id] === 'object')
  172. result = JSON.stringify(result)
  173. res[t('share.generation.completionResult')] = result
  174. return res
  175. })
  176. const checkBatchInputs = (data: string[][]) => {
  177. if (!data || data.length === 0) {
  178. notify({ type: 'error', message: t('share.generation.errorMsg.empty') })
  179. return false
  180. }
  181. const headerData = data[0]
  182. let isMapVarName = true
  183. promptConfig?.prompt_variables.forEach((item, index) => {
  184. if (!isMapVarName)
  185. return
  186. if (item.name !== headerData[index])
  187. isMapVarName = false
  188. })
  189. if (!isMapVarName) {
  190. notify({ type: 'error', message: t('share.generation.errorMsg.fileStructNotMatch') })
  191. return false
  192. }
  193. let payloadData = data.slice(1)
  194. if (payloadData.length === 0) {
  195. notify({ type: 'error', message: t('share.generation.errorMsg.atLeastOne') })
  196. return false
  197. }
  198. // check middle empty line
  199. const allEmptyLineIndexes = payloadData.filter(item => item.every(i => i === '')).map(item => payloadData.indexOf(item))
  200. if (allEmptyLineIndexes.length > 0) {
  201. let hasMiddleEmptyLine = false
  202. let startIndex = allEmptyLineIndexes[0] - 1
  203. allEmptyLineIndexes.forEach((index) => {
  204. if (hasMiddleEmptyLine)
  205. return
  206. if (startIndex + 1 !== index) {
  207. hasMiddleEmptyLine = true
  208. return
  209. }
  210. startIndex++
  211. })
  212. if (hasMiddleEmptyLine) {
  213. notify({ type: 'error', message: t('share.generation.errorMsg.emptyLine', { rowIndex: startIndex + 2 }) })
  214. return false
  215. }
  216. }
  217. // check row format
  218. payloadData = payloadData.filter(item => !item.every(i => i === ''))
  219. // after remove empty rows in the end, checked again
  220. if (payloadData.length === 0) {
  221. notify({ type: 'error', message: t('share.generation.errorMsg.atLeastOne') })
  222. return false
  223. }
  224. let errorRowIndex = 0
  225. let requiredVarName = ''
  226. let moreThanMaxLengthVarName = ''
  227. let maxLength = 0
  228. payloadData.forEach((item, index) => {
  229. if (errorRowIndex !== 0)
  230. return
  231. promptConfig?.prompt_variables.forEach((varItem, varIndex) => {
  232. if (errorRowIndex !== 0)
  233. return
  234. if (varItem.type === 'string') {
  235. const maxLen = varItem.max_length || DEFAULT_VALUE_MAX_LEN
  236. if (item[varIndex].length > maxLen) {
  237. moreThanMaxLengthVarName = varItem.name
  238. maxLength = maxLen
  239. errorRowIndex = index + 1
  240. return
  241. }
  242. }
  243. if (!varItem.required)
  244. return
  245. if (item[varIndex].trim() === '') {
  246. requiredVarName = varItem.name
  247. errorRowIndex = index + 1
  248. }
  249. })
  250. })
  251. if (errorRowIndex !== 0) {
  252. if (requiredVarName)
  253. notify({ type: 'error', message: t('share.generation.errorMsg.invalidLine', { rowIndex: errorRowIndex + 1, varName: requiredVarName }) })
  254. if (moreThanMaxLengthVarName)
  255. notify({ type: 'error', message: t('share.generation.errorMsg.moreThanMaxLengthLine', { rowIndex: errorRowIndex + 1, varName: moreThanMaxLengthVarName, maxLength }) })
  256. return false
  257. }
  258. return true
  259. }
  260. const handleRunBatch = (data: string[][]) => {
  261. if (!checkBatchInputs(data))
  262. return
  263. if (!allTasksFinished) {
  264. notify({ type: 'info', message: t('appDebug.errorMessage.waitForBatchResponse') })
  265. return
  266. }
  267. const payloadData = data.filter(item => !item.every(i => i === '')).slice(1)
  268. const varLen = promptConfig?.prompt_variables.length || 0
  269. setIsCallBatchAPI(true)
  270. const allTaskList: Task[] = payloadData.map((item, i) => {
  271. const inputs: Record<string, string> = {}
  272. if (varLen > 0) {
  273. item.slice(0, varLen).forEach((input, index) => {
  274. inputs[promptConfig?.prompt_variables[index].key as string] = input
  275. })
  276. }
  277. return {
  278. id: i + 1,
  279. status: i < GROUP_SIZE ? TaskStatus.running : TaskStatus.pending,
  280. params: {
  281. inputs,
  282. },
  283. }
  284. })
  285. setAllTaskList(allTaskList)
  286. setCurrGroupNum(0)
  287. setControlSend(Date.now())
  288. // clear run once task status
  289. setControlStopResponding(Date.now())
  290. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  291. showResSidebar()
  292. }
  293. const handleCompleted = (completionRes: string, taskId?: number, isSuccess?: boolean) => {
  294. const allTaskListLatest = getLatestTaskList()
  295. const batchCompletionResLatest = getBatchCompletionRes()
  296. const pendingTaskList = allTaskListLatest.filter(task => task.status === TaskStatus.pending)
  297. const runTasksCount = 1 + allTaskListLatest.filter(task => [TaskStatus.completed, TaskStatus.failed].includes(task.status)).length
  298. const needToAddNextGroupTask = (getCurrGroupNum() !== runTasksCount) && pendingTaskList.length > 0 && (runTasksCount % GROUP_SIZE === 0 || (allTaskListLatest.length - runTasksCount < GROUP_SIZE))
  299. // avoid add many task at the same time
  300. if (needToAddNextGroupTask)
  301. setCurrGroupNum(runTasksCount)
  302. const nextPendingTaskIds = needToAddNextGroupTask ? pendingTaskList.slice(0, GROUP_SIZE).map(item => item.id) : []
  303. const newAllTaskList = allTaskListLatest.map((item) => {
  304. if (item.id === taskId) {
  305. return {
  306. ...item,
  307. status: isSuccess ? TaskStatus.completed : TaskStatus.failed,
  308. }
  309. }
  310. if (needToAddNextGroupTask && nextPendingTaskIds.includes(item.id)) {
  311. return {
  312. ...item,
  313. status: TaskStatus.running,
  314. }
  315. }
  316. return item
  317. })
  318. setAllTaskList(newAllTaskList)
  319. if (taskId) {
  320. setBatchCompletionRes({
  321. ...batchCompletionResLatest,
  322. [`${taskId}`]: completionRes,
  323. })
  324. }
  325. }
  326. const fetchInitData = async () => {
  327. if (!isInstalledApp)
  328. await checkOrSetAccessToken()
  329. return Promise.all([
  330. isInstalledApp
  331. ? {
  332. app_id: installedAppInfo?.id,
  333. site: {
  334. title: installedAppInfo?.app.name,
  335. prompt_public: false,
  336. copyright: '',
  337. icon: installedAppInfo?.app.icon,
  338. icon_background: installedAppInfo?.app.icon_background,
  339. },
  340. plan: 'basic',
  341. }
  342. : fetchAppInfo(),
  343. fetchAppParams(isInstalledApp, installedAppInfo?.id),
  344. !isWorkflow
  345. ? fetchSavedMessage()
  346. : {},
  347. ])
  348. }
  349. useEffect(() => {
  350. (async () => {
  351. const [appData, appParams]: any = await fetchInitData()
  352. const { app_id: appId, site: siteInfo, can_replace_logo } = appData
  353. setAppId(appId)
  354. setSiteInfo(siteInfo as SiteInfo)
  355. setCanReplaceLogo(can_replace_logo)
  356. changeLanguage(siteInfo.default_language)
  357. const { user_input_form, more_like_this, file_upload, text_to_speech }: any = appParams
  358. setVisionConfig({
  359. ...file_upload.image,
  360. image_file_size_limit: appParams?.system_parameters?.image_file_size_limit,
  361. fileUploadConfig: appParams?.system_parameters,
  362. })
  363. const prompt_variables = userInputsFormToPromptVariables(user_input_form)
  364. setPromptConfig({
  365. prompt_template: '', // placeholder for future
  366. prompt_variables,
  367. } as PromptConfig)
  368. setMoreLikeThisConfig(more_like_this)
  369. setTextToSpeechConfig(text_to_speech)
  370. })()
  371. }, [])
  372. // Can Use metadata(https://beta.nextjs.org/docs/api-reference/metadata) to set title. But it only works in server side client.
  373. useEffect(() => {
  374. if (siteInfo?.title) {
  375. if (canReplaceLogo)
  376. document.title = `${siteInfo.title}`
  377. else
  378. document.title = `${siteInfo.title} - Powered by Dify`
  379. }
  380. }, [siteInfo?.title, canReplaceLogo])
  381. useAppFavicon({
  382. enable: !isInstalledApp,
  383. icon_type: siteInfo?.icon_type,
  384. icon: siteInfo?.icon,
  385. icon_background: siteInfo?.icon_background,
  386. icon_url: siteInfo?.icon_url,
  387. })
  388. const [isShowResSidebar, { setTrue: doShowResSidebar, setFalse: hideResSidebar }] = useBoolean(false)
  389. const showResSidebar = () => {
  390. // fix: useClickAway hideResSidebar will close sidebar
  391. setTimeout(() => {
  392. doShowResSidebar()
  393. }, 0)
  394. }
  395. const resRef = useRef<HTMLDivElement>(null)
  396. useClickAway(() => {
  397. hideResSidebar()
  398. }, resRef)
  399. const renderRes = (task?: Task) => (<Res
  400. key={task?.id}
  401. isWorkflow={isWorkflow}
  402. isCallBatchAPI={isCallBatchAPI}
  403. isPC={isPC}
  404. isMobile={isMobile}
  405. isInstalledApp={isInstalledApp}
  406. installedAppInfo={installedAppInfo}
  407. isError={task?.status === TaskStatus.failed}
  408. promptConfig={promptConfig}
  409. moreLikeThisEnabled={!!moreLikeThisConfig?.enabled}
  410. inputs={isCallBatchAPI ? (task as Task).params.inputs : inputs}
  411. controlSend={controlSend}
  412. controlRetry={task?.status === TaskStatus.failed ? controlRetry : 0}
  413. controlStopResponding={controlStopResponding}
  414. onShowRes={showResSidebar}
  415. handleSaveMessage={handleSaveMessage}
  416. taskId={task?.id}
  417. onCompleted={handleCompleted}
  418. visionConfig={visionConfig}
  419. completionFiles={completionFiles}
  420. isShowTextToSpeech={!!textToSpeechConfig?.enabled}
  421. siteInfo={siteInfo}
  422. />)
  423. const renderBatchRes = () => {
  424. return (showTaskList.map(task => renderRes(task)))
  425. }
  426. const resWrapClassNames = (() => {
  427. if (isPC)
  428. return 'grow h-full'
  429. if (!isShowResSidebar)
  430. return 'none'
  431. return cn('fixed z-50 inset-0', isTablet ? 'pl-[128px]' : 'pl-6')
  432. })()
  433. const renderResWrap = (
  434. <div
  435. ref={resRef}
  436. className={
  437. cn(
  438. 'flex flex-col h-full shrink-0',
  439. isPC ? 'px-10 py-8' : 'bg-gray-50',
  440. isTablet && 'p-6', isMobile && 'p-4')
  441. }
  442. >
  443. <>
  444. <div className='flex items-center justify-between shrink-0'>
  445. <div className='flex items-center space-x-3'>
  446. <div className={s.starIcon}></div>
  447. <div className='text-lg font-semibold text-gray-800'>{t('share.generation.title')}</div>
  448. </div>
  449. <div className='flex items-center space-x-2'>
  450. {allFailedTaskList.length > 0 && (
  451. <div className='flex items-center'>
  452. <RiErrorWarningFill className='w-4 h-4 text-[#D92D20]' />
  453. <div className='ml-1 text-[#D92D20]'>{t('share.generation.batchFailed.info', { num: allFailedTaskList.length })}</div>
  454. <Button
  455. variant='primary'
  456. className='ml-2'
  457. onClick={handleRetryAllFailedTask}
  458. >{t('share.generation.batchFailed.retry')}</Button>
  459. <div className='mx-3 w-[1px] h-3.5 bg-gray-200'></div>
  460. </div>
  461. )}
  462. {allSuccessTaskList.length > 0 && (
  463. <ResDownload
  464. isMobile={isMobile}
  465. values={exportRes}
  466. />
  467. )}
  468. {!isPC && (
  469. <div
  470. className='flex items-center justify-center cursor-pointer'
  471. onClick={hideResSidebar}
  472. >
  473. <XMarkIcon className='w-4 h-4 text-gray-800' />
  474. </div>
  475. )}
  476. </div>
  477. </div>
  478. <div className='overflow-y-auto grow'>
  479. {!isCallBatchAPI ? renderRes() : renderBatchRes()}
  480. {!noPendingTask && (
  481. <div className='mt-4'>
  482. <Loading type='area' />
  483. </div>
  484. )}
  485. </div>
  486. </>
  487. </div>
  488. )
  489. if (!appId || !siteInfo || !promptConfig) {
  490. return (
  491. <div className='flex items-center h-screen'>
  492. <Loading type='app' />
  493. </div>)
  494. }
  495. return (
  496. <>
  497. <div className={cn(
  498. isPC && 'flex',
  499. isInstalledApp ? s.installedApp : 'h-screen',
  500. 'bg-gray-50',
  501. )}>
  502. {/* Left */}
  503. <div className={cn(
  504. isPC ? 'w-[600px] max-w-[50%] p-8' : 'p-4',
  505. isInstalledApp && 'rounded-l-2xl',
  506. 'shrink-0 relative flex flex-col pb-10 h-full border-r border-gray-100 bg-white',
  507. )}>
  508. <div className='mb-6'>
  509. <div className='flex items-center justify-between'>
  510. <div className='flex items-center space-x-3'>
  511. <AppIcon
  512. size="small"
  513. iconType={siteInfo.icon_type}
  514. icon={siteInfo.icon}
  515. background={siteInfo.icon_background || appDefaultIconBackground}
  516. imageUrl={siteInfo.icon_url}
  517. />
  518. <div className='text-lg font-semibold text-gray-800'>{siteInfo.title}</div>
  519. </div>
  520. {!isPC && (
  521. <Button
  522. className='shrink-0 ml-2'
  523. onClick={showResSidebar}
  524. >
  525. <div className='flex items-center space-x-2 text-primary-600 text-[13px] font-medium'>
  526. <div className={s.starIcon}></div>
  527. <span>{t('share.generation.title')}</span>
  528. </div>
  529. </Button>
  530. )}
  531. </div>
  532. {siteInfo.description && (
  533. <div className='mt-2 text-xs text-gray-500'>{siteInfo.description}</div>
  534. )}
  535. </div>
  536. <TabHeader
  537. items={[
  538. { id: 'create', name: t('share.generation.tabs.create') },
  539. { id: 'batch', name: t('share.generation.tabs.batch') },
  540. ...(!isWorkflow
  541. ? [{
  542. id: 'saved',
  543. name: t('share.generation.tabs.saved'),
  544. isRight: true,
  545. extra: savedMessages.length > 0
  546. ? (
  547. <div className='ml-1 flex items-center h-5 px-1.5 rounded-md border border-gray-200 text-gray-500 text-xs font-medium'>
  548. {savedMessages.length}
  549. </div>
  550. )
  551. : null,
  552. }]
  553. : []),
  554. ]}
  555. value={currentTab}
  556. onChange={setCurrentTab}
  557. />
  558. <div className='h-20 overflow-y-auto grow'>
  559. <div className={cn(currentTab === 'create' ? 'block' : 'hidden')}>
  560. <RunOnce
  561. siteInfo={siteInfo}
  562. inputs={inputs}
  563. onInputsChange={setInputs}
  564. promptConfig={promptConfig}
  565. onSend={handleSend}
  566. visionConfig={visionConfig}
  567. onVisionFilesChange={setCompletionFiles}
  568. />
  569. </div>
  570. <div className={cn(isInBatchTab ? 'block' : 'hidden')}>
  571. <RunBatch
  572. vars={promptConfig.prompt_variables}
  573. onSend={handleRunBatch}
  574. isAllFinished={allTasksRun}
  575. />
  576. </div>
  577. {currentTab === 'saved' && (
  578. <SavedItems
  579. className='mt-4'
  580. isShowTextToSpeech={textToSpeechConfig?.enabled}
  581. list={savedMessages}
  582. onRemove={handleRemoveSavedMessage}
  583. onStartCreateContent={() => setCurrentTab('create')}
  584. />
  585. )}
  586. </div>
  587. {/* copyright */}
  588. <div className={cn(
  589. isInstalledApp ? 'left-[248px]' : 'left-8',
  590. 'fixed bottom-4 flex space-x-2 text-gray-400 font-normal text-xs',
  591. )}>
  592. <div className="">© {siteInfo.copyright || siteInfo.title} {(new Date()).getFullYear()}</div>
  593. {siteInfo.privacy_policy && (
  594. <>
  595. <div>·</div>
  596. <div>{t('share.chat.privacyPolicyLeft')}
  597. <a
  598. className='text-gray-500 px-1'
  599. href={siteInfo.privacy_policy}
  600. target='_blank' rel='noopener noreferrer'>{t('share.chat.privacyPolicyMiddle')}</a>
  601. {t('share.chat.privacyPolicyRight')}
  602. </div>
  603. </>
  604. )}
  605. </div>
  606. </div>
  607. {/* Result */}
  608. <div
  609. className={resWrapClassNames}
  610. style={{
  611. background: (!isPC && isShowResSidebar) ? 'rgba(35, 56, 118, 0.2)' : 'none',
  612. }}
  613. >
  614. {renderResWrap}
  615. </div>
  616. </div>
  617. </>
  618. )
  619. }
  620. export default TextGeneration