index.tsx 23 KB

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