You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hooks.tsx 19KB

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