您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import {
  2. useCallback,
  3. useEffect,
  4. useMemo,
  5. useRef,
  6. useState,
  7. } from 'react'
  8. import { useTranslation } from 'react-i18next'
  9. import useSWR from 'swr'
  10. import { useLocalStorageState } from 'ahooks'
  11. import produce from 'immer'
  12. import type {
  13. Callback,
  14. ChatConfig,
  15. ChatItem,
  16. Feedback,
  17. } from '../types'
  18. import { CONVERSATION_ID_INFO } from '../constants'
  19. import { buildChatItemTree } from '../utils'
  20. import { addFileInfos, sortAgentSorts } from '../../../tools/utils'
  21. import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
  22. import {
  23. delConversation,
  24. fetchAppInfo,
  25. fetchAppMeta,
  26. fetchAppParams,
  27. fetchChatList,
  28. fetchConversations,
  29. generationConversationName,
  30. pinConversation,
  31. renameConversation,
  32. unpinConversation,
  33. updateFeedback,
  34. } from '@/service/share'
  35. import type { InstalledApp } from '@/models/explore'
  36. import type {
  37. AppData,
  38. ConversationItem,
  39. } from '@/models/share'
  40. import { useToastContext } from '@/app/components/base/toast'
  41. import { changeLanguage } from '@/i18n/i18next-config'
  42. import { useAppFavicon } from '@/hooks/use-app-favicon'
  43. import { InputVarType } from '@/app/components/workflow/types'
  44. import { TransferMethod } from '@/types/app'
  45. function getFormattedChatList(messages: any[]) {
  46. const newChatList: ChatItem[] = []
  47. messages.forEach((item) => {
  48. const questionFiles = item.message_files?.filter((file: any) => file.belongs_to === 'user') || []
  49. newChatList.push({
  50. id: `question-${item.id}`,
  51. content: item.query,
  52. isAnswer: false,
  53. message_files: getProcessedFilesFromResponse(questionFiles.map((item: any) => ({ ...item, related_id: item.id }))),
  54. parentMessageId: item.parent_message_id || undefined,
  55. })
  56. const answerFiles = item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || []
  57. newChatList.push({
  58. id: item.id,
  59. content: item.answer,
  60. agent_thoughts: addFileInfos(item.agent_thoughts ? sortAgentSorts(item.agent_thoughts) : item.agent_thoughts, item.message_files),
  61. feedback: item.feedback,
  62. isAnswer: true,
  63. citation: item.retriever_resources,
  64. message_files: getProcessedFilesFromResponse(answerFiles.map((item: any) => ({ ...item, related_id: item.id }))),
  65. parentMessageId: `question-${item.id}`,
  66. })
  67. })
  68. return newChatList
  69. }
  70. export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {
  71. const isInstalledApp = useMemo(() => !!installedAppInfo, [installedAppInfo])
  72. const { data: appInfo, isLoading: appInfoLoading, error: appInfoError } = useSWR(installedAppInfo ? null : 'appInfo', fetchAppInfo)
  73. useAppFavicon({
  74. enable: !installedAppInfo,
  75. icon_type: appInfo?.site.icon_type,
  76. icon: appInfo?.site.icon,
  77. icon_background: appInfo?.site.icon_background,
  78. icon_url: appInfo?.site.icon_url,
  79. })
  80. const appData = useMemo(() => {
  81. if (isInstalledApp) {
  82. const { id, app } = installedAppInfo!
  83. return {
  84. app_id: id,
  85. site: {
  86. title: app.name,
  87. icon_type: app.icon_type,
  88. icon: app.icon,
  89. icon_background: app.icon_background,
  90. icon_url: app.icon_url,
  91. prompt_public: false,
  92. copyright: '',
  93. show_workflow_steps: true,
  94. use_icon_as_answer_icon: app.use_icon_as_answer_icon,
  95. },
  96. plan: 'basic',
  97. } as AppData
  98. }
  99. return appInfo
  100. }, [isInstalledApp, installedAppInfo, appInfo])
  101. const appId = useMemo(() => appData?.app_id, [appData])
  102. useEffect(() => {
  103. if (appData?.site.default_language)
  104. changeLanguage(appData.site.default_language)
  105. }, [appData])
  106. const [sidebarCollapseState, setSidebarCollapseState] = useState<boolean>(false)
  107. const handleSidebarCollapse = useCallback((state: boolean) => {
  108. if (appId) {
  109. setSidebarCollapseState(state)
  110. localStorage.setItem('webappSidebarCollapse', state ? 'collapsed' : 'expanded')
  111. }
  112. }, [appId, setSidebarCollapseState])
  113. useEffect(() => {
  114. if (appId) {
  115. const localState = localStorage.getItem('webappSidebarCollapse')
  116. setSidebarCollapseState(localState === 'collapsed')
  117. }
  118. }, [appId])
  119. const [conversationIdInfo, setConversationIdInfo] = useLocalStorageState<Record<string, string>>(CONVERSATION_ID_INFO, {
  120. defaultValue: {},
  121. })
  122. const currentConversationId = useMemo(() => conversationIdInfo?.[appId || ''] || '', [appId, conversationIdInfo])
  123. const handleConversationIdInfoChange = useCallback((changeConversationId: string) => {
  124. if (appId) {
  125. setConversationIdInfo({
  126. ...conversationIdInfo,
  127. [appId || '']: changeConversationId,
  128. })
  129. }
  130. }, [appId, conversationIdInfo, setConversationIdInfo])
  131. const [newConversationId, setNewConversationId] = useState('')
  132. const chatShouldReloadKey = useMemo(() => {
  133. if (currentConversationId === newConversationId)
  134. return ''
  135. return currentConversationId
  136. }, [currentConversationId, newConversationId])
  137. const { data: appParams } = useSWR(['appParams', isInstalledApp, appId], () => fetchAppParams(isInstalledApp, appId))
  138. const { data: appMeta } = useSWR(['appMeta', isInstalledApp, appId], () => fetchAppMeta(isInstalledApp, appId))
  139. const { data: appPinnedConversationData, mutate: mutateAppPinnedConversationData } = useSWR(['appConversationData', isInstalledApp, appId, true], () => fetchConversations(isInstalledApp, appId, undefined, true, 100))
  140. const { data: appConversationData, isLoading: appConversationDataLoading, mutate: mutateAppConversationData } = useSWR(['appConversationData', isInstalledApp, appId, false], () => fetchConversations(isInstalledApp, appId, undefined, false, 100))
  141. const { data: appChatListData, isLoading: appChatListDataLoading } = useSWR(chatShouldReloadKey ? ['appChatList', chatShouldReloadKey, isInstalledApp, appId] : null, () => fetchChatList(chatShouldReloadKey, isInstalledApp, appId))
  142. const [clearChatList, setClearChatList] = useState(false)
  143. const [isResponding, setIsResponding] = useState(false)
  144. const appPrevChatTree = useMemo(
  145. () => (currentConversationId && appChatListData?.data.length)
  146. ? buildChatItemTree(getFormattedChatList(appChatListData.data))
  147. : [],
  148. [appChatListData, currentConversationId],
  149. )
  150. const [showNewConversationItemInList, setShowNewConversationItemInList] = useState(false)
  151. const pinnedConversationList = useMemo(() => {
  152. return appPinnedConversationData?.data || []
  153. }, [appPinnedConversationData])
  154. const { t } = useTranslation()
  155. const newConversationInputsRef = useRef<Record<string, any>>({})
  156. const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any>>({})
  157. const handleNewConversationInputsChange = useCallback((newInputs: Record<string, any>) => {
  158. newConversationInputsRef.current = newInputs
  159. setNewConversationInputs(newInputs)
  160. }, [])
  161. const inputsForms = useMemo(() => {
  162. return (appParams?.user_input_form || []).filter((item: any) => !item.external_data_tool).map((item: any) => {
  163. if (item.paragraph) {
  164. return {
  165. ...item.paragraph,
  166. type: 'paragraph',
  167. }
  168. }
  169. if (item.number) {
  170. return {
  171. ...item.number,
  172. type: 'number',
  173. }
  174. }
  175. if (item.select) {
  176. return {
  177. ...item.select,
  178. type: 'select',
  179. }
  180. }
  181. if (item['file-list']) {
  182. return {
  183. ...item['file-list'],
  184. type: 'file-list',
  185. }
  186. }
  187. if (item.file) {
  188. return {
  189. ...item.file,
  190. type: 'file',
  191. }
  192. }
  193. return {
  194. ...item['text-input'],
  195. type: 'text-input',
  196. }
  197. })
  198. }, [appParams])
  199. useEffect(() => {
  200. const conversationInputs: Record<string, any> = {}
  201. inputsForms.forEach((item: any) => {
  202. conversationInputs[item.variable] = item.default || null
  203. })
  204. handleNewConversationInputsChange(conversationInputs)
  205. }, [handleNewConversationInputsChange, inputsForms])
  206. const { data: newConversation } = useSWR(newConversationId ? [isInstalledApp, appId, newConversationId] : null, () => generationConversationName(isInstalledApp, appId, newConversationId), { revalidateOnFocus: false })
  207. const [originConversationList, setOriginConversationList] = useState<ConversationItem[]>([])
  208. useEffect(() => {
  209. if (appConversationData?.data && !appConversationDataLoading)
  210. setOriginConversationList(appConversationData?.data)
  211. }, [appConversationData, appConversationDataLoading])
  212. const conversationList = useMemo(() => {
  213. const data = originConversationList.slice()
  214. if (showNewConversationItemInList && data[0]?.id !== '') {
  215. data.unshift({
  216. id: '',
  217. name: t('share.chat.newChatDefaultName'),
  218. inputs: {},
  219. introduction: '',
  220. })
  221. }
  222. return data
  223. }, [originConversationList, showNewConversationItemInList, t])
  224. useEffect(() => {
  225. if (newConversation) {
  226. setOriginConversationList(produce((draft) => {
  227. const index = draft.findIndex(item => item.id === newConversation.id)
  228. if (index > -1)
  229. draft[index] = newConversation
  230. else
  231. draft.unshift(newConversation)
  232. }))
  233. }
  234. }, [newConversation])
  235. const currentConversationItem = useMemo(() => {
  236. let conversationItem = conversationList.find(item => item.id === currentConversationId)
  237. if (!conversationItem && pinnedConversationList.length)
  238. conversationItem = pinnedConversationList.find(item => item.id === currentConversationId)
  239. return conversationItem
  240. }, [conversationList, currentConversationId, pinnedConversationList])
  241. const currentConversationLatestInputs = useMemo(() => {
  242. if (!currentConversationId || !appChatListData?.data.length)
  243. return {}
  244. return appChatListData.data.slice().pop().inputs || {}
  245. }, [appChatListData, currentConversationId])
  246. const [currentConversationInputs, setCurrentConversationInputs] = useState<Record<string, any>>(currentConversationLatestInputs || {})
  247. useEffect(() => {
  248. if (currentConversationItem)
  249. setCurrentConversationInputs(currentConversationLatestInputs || {})
  250. }, [currentConversationItem, currentConversationLatestInputs])
  251. const { notify } = useToastContext()
  252. const checkInputsRequired = useCallback((silent?: boolean) => {
  253. let hasEmptyInput = ''
  254. let fileIsUploading = false
  255. const requiredVars = inputsForms.filter(({ required }) => required)
  256. if (requiredVars.length) {
  257. requiredVars.forEach(({ variable, label, type }) => {
  258. if (hasEmptyInput)
  259. return
  260. if (fileIsUploading)
  261. return
  262. if (!newConversationInputsRef.current[variable] && !silent)
  263. hasEmptyInput = label as string
  264. if ((type === InputVarType.singleFile || type === InputVarType.multiFiles) && newConversationInputsRef.current[variable] && !silent) {
  265. const files = newConversationInputsRef.current[variable]
  266. if (Array.isArray(files))
  267. fileIsUploading = files.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)
  268. else
  269. fileIsUploading = files.transferMethod === TransferMethod.local_file && !files.uploadedId
  270. }
  271. })
  272. }
  273. if (hasEmptyInput) {
  274. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }) })
  275. return false
  276. }
  277. if (fileIsUploading) {
  278. notify({ type: 'info', message: t('appDebug.errorMessage.waitForFileUpload') })
  279. return
  280. }
  281. return true
  282. }, [inputsForms, notify, t])
  283. const handleStartChat = useCallback((callback: any) => {
  284. if (checkInputsRequired()) {
  285. setShowNewConversationItemInList(true)
  286. callback?.()
  287. }
  288. }, [setShowNewConversationItemInList, checkInputsRequired])
  289. const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ handleStop: () => { } })
  290. const handleChangeConversation = useCallback((conversationId: string) => {
  291. currentChatInstanceRef.current.handleStop()
  292. setNewConversationId('')
  293. handleConversationIdInfoChange(conversationId)
  294. if (conversationId)
  295. setClearChatList(false)
  296. }, [handleConversationIdInfoChange, setClearChatList])
  297. const handleNewConversation = useCallback(() => {
  298. currentChatInstanceRef.current.handleStop()
  299. setShowNewConversationItemInList(true)
  300. handleChangeConversation('')
  301. handleNewConversationInputsChange({})
  302. setClearChatList(true)
  303. }, [handleChangeConversation, setShowNewConversationItemInList, handleNewConversationInputsChange, setClearChatList])
  304. const handleUpdateConversationList = useCallback(() => {
  305. mutateAppConversationData()
  306. mutateAppPinnedConversationData()
  307. }, [mutateAppConversationData, mutateAppPinnedConversationData])
  308. const handlePinConversation = useCallback(async (conversationId: string) => {
  309. await pinConversation(isInstalledApp, appId, conversationId)
  310. notify({ type: 'success', message: t('common.api.success') })
  311. handleUpdateConversationList()
  312. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList])
  313. const handleUnpinConversation = useCallback(async (conversationId: string) => {
  314. await unpinConversation(isInstalledApp, appId, conversationId)
  315. notify({ type: 'success', message: t('common.api.success') })
  316. handleUpdateConversationList()
  317. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList])
  318. const [conversationDeleting, setConversationDeleting] = useState(false)
  319. const handleDeleteConversation = useCallback(async (
  320. conversationId: string,
  321. {
  322. onSuccess,
  323. }: Callback,
  324. ) => {
  325. if (conversationDeleting)
  326. return
  327. try {
  328. setConversationDeleting(true)
  329. await delConversation(isInstalledApp, appId, conversationId)
  330. notify({ type: 'success', message: t('common.api.success') })
  331. onSuccess()
  332. }
  333. finally {
  334. setConversationDeleting(false)
  335. }
  336. if (conversationId === currentConversationId)
  337. handleNewConversation()
  338. handleUpdateConversationList()
  339. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList, handleNewConversation, currentConversationId, conversationDeleting])
  340. const [conversationRenaming, setConversationRenaming] = useState(false)
  341. const handleRenameConversation = useCallback(async (
  342. conversationId: string,
  343. newName: string,
  344. {
  345. onSuccess,
  346. }: Callback,
  347. ) => {
  348. if (conversationRenaming)
  349. return
  350. if (!newName.trim()) {
  351. notify({
  352. type: 'error',
  353. message: t('common.chat.conversationNameCanNotEmpty'),
  354. })
  355. return
  356. }
  357. setConversationRenaming(true)
  358. try {
  359. await renameConversation(isInstalledApp, appId, conversationId, newName)
  360. notify({
  361. type: 'success',
  362. message: t('common.actionMsg.modifiedSuccessfully'),
  363. })
  364. setOriginConversationList(produce((draft) => {
  365. const index = originConversationList.findIndex(item => item.id === conversationId)
  366. const item = draft[index]
  367. draft[index] = {
  368. ...item,
  369. name: newName,
  370. }
  371. }))
  372. onSuccess()
  373. }
  374. finally {
  375. setConversationRenaming(false)
  376. }
  377. }, [isInstalledApp, appId, notify, t, conversationRenaming, originConversationList])
  378. const handleNewConversationCompleted = useCallback((newConversationId: string) => {
  379. setNewConversationId(newConversationId)
  380. handleConversationIdInfoChange(newConversationId)
  381. setShowNewConversationItemInList(false)
  382. mutateAppConversationData()
  383. }, [mutateAppConversationData, handleConversationIdInfoChange])
  384. const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {
  385. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, appId)
  386. notify({ type: 'success', message: t('common.api.success') })
  387. }, [isInstalledApp, appId, t, notify])
  388. return {
  389. appInfoError,
  390. appInfoLoading,
  391. isInstalledApp,
  392. appId,
  393. currentConversationId,
  394. currentConversationItem,
  395. handleConversationIdInfoChange,
  396. appData,
  397. appParams: appParams || {} as ChatConfig,
  398. appMeta,
  399. appPinnedConversationData,
  400. appConversationData,
  401. appConversationDataLoading,
  402. appChatListData,
  403. appChatListDataLoading,
  404. appPrevChatTree,
  405. pinnedConversationList,
  406. conversationList,
  407. setShowNewConversationItemInList,
  408. newConversationInputs,
  409. newConversationInputsRef,
  410. handleNewConversationInputsChange,
  411. inputsForms,
  412. handleNewConversation,
  413. handleStartChat,
  414. handleChangeConversation,
  415. handlePinConversation,
  416. handleUnpinConversation,
  417. conversationDeleting,
  418. handleDeleteConversation,
  419. conversationRenaming,
  420. handleRenameConversation,
  421. handleNewConversationCompleted,
  422. newConversationId,
  423. chatShouldReloadKey,
  424. handleFeedback,
  425. currentChatInstanceRef,
  426. sidebarCollapseState,
  427. handleSidebarCollapse,
  428. clearChatList,
  429. setClearChatList,
  430. isResponding,
  431. setIsResponding,
  432. currentConversationInputs,
  433. setCurrentConversationInputs,
  434. }
  435. }