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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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, getRawUserVariablesFromUrlParams } 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-config/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(
  152. appId ? ['appConversationData', isInstalledApp, appId, true] : null,
  153. () => fetchConversations(isInstalledApp, appId, undefined, true, 100),
  154. { revalidateOnFocus: false, revalidateOnReconnect: false },
  155. )
  156. const { data: appConversationData, isLoading: appConversationDataLoading, mutate: mutateAppConversationData } = useSWR(
  157. appId ? ['appConversationData', isInstalledApp, appId, false] : null,
  158. () => fetchConversations(isInstalledApp, appId, undefined, false, 100),
  159. { revalidateOnFocus: false, revalidateOnReconnect: false },
  160. )
  161. const { data: appChatListData, isLoading: appChatListDataLoading } = useSWR(
  162. chatShouldReloadKey ? ['appChatList', chatShouldReloadKey, isInstalledApp, appId] : null,
  163. () => fetchChatList(chatShouldReloadKey, isInstalledApp, appId),
  164. { revalidateOnFocus: false, revalidateOnReconnect: false },
  165. )
  166. const [clearChatList, setClearChatList] = useState(false)
  167. const [isResponding, setIsResponding] = useState(false)
  168. const appPrevChatTree = useMemo(
  169. () => (currentConversationId && appChatListData?.data.length)
  170. ? buildChatItemTree(getFormattedChatList(appChatListData.data))
  171. : [],
  172. [appChatListData, currentConversationId],
  173. )
  174. const [showNewConversationItemInList, setShowNewConversationItemInList] = useState(false)
  175. const pinnedConversationList = useMemo(() => {
  176. return appPinnedConversationData?.data || []
  177. }, [appPinnedConversationData])
  178. const { t } = useTranslation()
  179. const newConversationInputsRef = useRef<Record<string, any>>({})
  180. const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any>>({})
  181. const [initInputs, setInitInputs] = useState<Record<string, any>>({})
  182. const [initUserVariables, setInitUserVariables] = useState<Record<string, any>>({})
  183. const handleNewConversationInputsChange = useCallback((newInputs: Record<string, any>) => {
  184. newConversationInputsRef.current = newInputs
  185. setNewConversationInputs(newInputs)
  186. }, [])
  187. const inputsForms = useMemo(() => {
  188. return (appParams?.user_input_form || []).filter((item: any) => !item.external_data_tool).map((item: any) => {
  189. if (item.paragraph) {
  190. let value = initInputs[item.paragraph.variable]
  191. if (value && item.paragraph.max_length && value.length > item.paragraph.max_length)
  192. value = value.slice(0, item.paragraph.max_length)
  193. return {
  194. ...item.paragraph,
  195. default: value || item.default,
  196. type: 'paragraph',
  197. }
  198. }
  199. if (item.number) {
  200. const convertedNumber = Number(initInputs[item.number.variable]) ?? undefined
  201. return {
  202. ...item.number,
  203. default: convertedNumber || item.default,
  204. type: 'number',
  205. }
  206. }
  207. if (item.select) {
  208. const isInputInOptions = item.select.options.includes(initInputs[item.select.variable])
  209. return {
  210. ...item.select,
  211. default: (isInputInOptions ? initInputs[item.select.variable] : undefined) || item.select.default,
  212. type: 'select',
  213. }
  214. }
  215. if (item['file-list']) {
  216. return {
  217. ...item['file-list'],
  218. type: 'file-list',
  219. }
  220. }
  221. if (item.file) {
  222. return {
  223. ...item.file,
  224. type: 'file',
  225. }
  226. }
  227. let value = initInputs[item['text-input'].variable]
  228. if (value && item['text-input'].max_length && value.length > item['text-input'].max_length)
  229. value = value.slice(0, item['text-input'].max_length)
  230. return {
  231. ...item['text-input'],
  232. default: value || item.default,
  233. type: 'text-input',
  234. }
  235. })
  236. }, [initInputs, appParams])
  237. const allInputsHidden = useMemo(() => {
  238. return inputsForms.length > 0 && inputsForms.every(item => item.hide === true)
  239. }, [inputsForms])
  240. useEffect(() => {
  241. // init inputs from url params
  242. (async () => {
  243. const inputs = await getRawInputsFromUrlParams()
  244. const userVariables = await getRawUserVariablesFromUrlParams()
  245. setInitInputs(inputs)
  246. setInitUserVariables(userVariables)
  247. })()
  248. }, [])
  249. useEffect(() => {
  250. const conversationInputs: Record<string, any> = {}
  251. inputsForms.forEach((item: any) => {
  252. conversationInputs[item.variable] = item.default || null
  253. })
  254. handleNewConversationInputsChange(conversationInputs)
  255. }, [handleNewConversationInputsChange, inputsForms])
  256. const { data: newConversation } = useSWR(newConversationId ? [isInstalledApp, appId, newConversationId] : null, () => generationConversationName(isInstalledApp, appId, newConversationId), { revalidateOnFocus: false })
  257. const [originConversationList, setOriginConversationList] = useState<ConversationItem[]>([])
  258. useEffect(() => {
  259. if (appConversationData?.data && !appConversationDataLoading)
  260. setOriginConversationList(appConversationData?.data)
  261. }, [appConversationData, appConversationDataLoading])
  262. const conversationList = useMemo(() => {
  263. const data = originConversationList.slice()
  264. if (showNewConversationItemInList && data[0]?.id !== '') {
  265. data.unshift({
  266. id: '',
  267. name: t('share.chat.newChatDefaultName'),
  268. inputs: {},
  269. introduction: '',
  270. })
  271. }
  272. return data
  273. }, [originConversationList, showNewConversationItemInList, t])
  274. useEffect(() => {
  275. if (newConversation) {
  276. setOriginConversationList(produce((draft) => {
  277. const index = draft.findIndex(item => item.id === newConversation.id)
  278. if (index > -1)
  279. draft[index] = newConversation
  280. else
  281. draft.unshift(newConversation)
  282. }))
  283. }
  284. }, [newConversation])
  285. const currentConversationItem = useMemo(() => {
  286. let conversationItem = conversationList.find(item => item.id === currentConversationId)
  287. if (!conversationItem && pinnedConversationList.length)
  288. conversationItem = pinnedConversationList.find(item => item.id === currentConversationId)
  289. return conversationItem
  290. }, [conversationList, currentConversationId, pinnedConversationList])
  291. const currentConversationLatestInputs = useMemo(() => {
  292. if (!currentConversationId || !appChatListData?.data.length)
  293. return newConversationInputsRef.current || {}
  294. return appChatListData.data.slice().pop().inputs || {}
  295. }, [appChatListData, currentConversationId])
  296. const [currentConversationInputs, setCurrentConversationInputs] = useState<Record<string, any>>(currentConversationLatestInputs || {})
  297. useEffect(() => {
  298. if (currentConversationItem)
  299. setCurrentConversationInputs(currentConversationLatestInputs || {})
  300. }, [currentConversationItem, currentConversationLatestInputs])
  301. const { notify } = useToastContext()
  302. const checkInputsRequired = useCallback((silent?: boolean) => {
  303. if (allInputsHidden)
  304. return true
  305. let hasEmptyInput = ''
  306. let fileIsUploading = false
  307. const requiredVars = inputsForms.filter(({ required }) => required)
  308. if (requiredVars.length) {
  309. requiredVars.forEach(({ variable, label, type }) => {
  310. if (hasEmptyInput)
  311. return
  312. if (fileIsUploading)
  313. return
  314. if (!newConversationInputsRef.current[variable] && !silent)
  315. hasEmptyInput = label as string
  316. if ((type === InputVarType.singleFile || type === InputVarType.multiFiles) && newConversationInputsRef.current[variable] && !silent) {
  317. const files = newConversationInputsRef.current[variable]
  318. if (Array.isArray(files))
  319. fileIsUploading = files.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)
  320. else
  321. fileIsUploading = files.transferMethod === TransferMethod.local_file && !files.uploadedId
  322. }
  323. })
  324. }
  325. if (hasEmptyInput) {
  326. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }) })
  327. return false
  328. }
  329. if (fileIsUploading) {
  330. notify({ type: 'info', message: t('appDebug.errorMessage.waitForFileUpload') })
  331. return
  332. }
  333. return true
  334. }, [inputsForms, notify, t, allInputsHidden])
  335. const handleStartChat = useCallback((callback: any) => {
  336. if (checkInputsRequired()) {
  337. setShowNewConversationItemInList(true)
  338. callback?.()
  339. }
  340. }, [setShowNewConversationItemInList, checkInputsRequired])
  341. const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ handleStop: noop })
  342. const handleChangeConversation = useCallback((conversationId: string) => {
  343. currentChatInstanceRef.current.handleStop()
  344. setNewConversationId('')
  345. handleConversationIdInfoChange(conversationId)
  346. if (conversationId)
  347. setClearChatList(false)
  348. }, [handleConversationIdInfoChange, setClearChatList])
  349. const handleNewConversation = useCallback(async () => {
  350. currentChatInstanceRef.current.handleStop()
  351. setShowNewConversationItemInList(true)
  352. handleChangeConversation('')
  353. handleNewConversationInputsChange(await getRawInputsFromUrlParams())
  354. setClearChatList(true)
  355. }, [handleChangeConversation, setShowNewConversationItemInList, handleNewConversationInputsChange, setClearChatList])
  356. const handleUpdateConversationList = useCallback(() => {
  357. mutateAppConversationData()
  358. mutateAppPinnedConversationData()
  359. }, [mutateAppConversationData, mutateAppPinnedConversationData])
  360. const handlePinConversation = useCallback(async (conversationId: string) => {
  361. await pinConversation(isInstalledApp, appId, conversationId)
  362. notify({ type: 'success', message: t('common.api.success') })
  363. handleUpdateConversationList()
  364. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList])
  365. const handleUnpinConversation = useCallback(async (conversationId: string) => {
  366. await unpinConversation(isInstalledApp, appId, conversationId)
  367. notify({ type: 'success', message: t('common.api.success') })
  368. handleUpdateConversationList()
  369. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList])
  370. const [conversationDeleting, setConversationDeleting] = useState(false)
  371. const handleDeleteConversation = useCallback(async (
  372. conversationId: string,
  373. {
  374. onSuccess,
  375. }: Callback,
  376. ) => {
  377. if (conversationDeleting)
  378. return
  379. try {
  380. setConversationDeleting(true)
  381. await delConversation(isInstalledApp, appId, conversationId)
  382. notify({ type: 'success', message: t('common.api.success') })
  383. onSuccess()
  384. }
  385. finally {
  386. setConversationDeleting(false)
  387. }
  388. if (conversationId === currentConversationId)
  389. handleNewConversation()
  390. handleUpdateConversationList()
  391. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList, handleNewConversation, currentConversationId, conversationDeleting])
  392. const [conversationRenaming, setConversationRenaming] = useState(false)
  393. const handleRenameConversation = useCallback(async (
  394. conversationId: string,
  395. newName: string,
  396. {
  397. onSuccess,
  398. }: Callback,
  399. ) => {
  400. if (conversationRenaming)
  401. return
  402. if (!newName.trim()) {
  403. notify({
  404. type: 'error',
  405. message: t('common.chat.conversationNameCanNotEmpty'),
  406. })
  407. return
  408. }
  409. setConversationRenaming(true)
  410. try {
  411. await renameConversation(isInstalledApp, appId, conversationId, newName)
  412. notify({
  413. type: 'success',
  414. message: t('common.actionMsg.modifiedSuccessfully'),
  415. })
  416. setOriginConversationList(produce((draft) => {
  417. const index = originConversationList.findIndex(item => item.id === conversationId)
  418. const item = draft[index]
  419. draft[index] = {
  420. ...item,
  421. name: newName,
  422. }
  423. }))
  424. onSuccess()
  425. }
  426. finally {
  427. setConversationRenaming(false)
  428. }
  429. }, [isInstalledApp, appId, notify, t, conversationRenaming, originConversationList])
  430. const handleNewConversationCompleted = useCallback((newConversationId: string) => {
  431. setNewConversationId(newConversationId)
  432. handleConversationIdInfoChange(newConversationId)
  433. setShowNewConversationItemInList(false)
  434. mutateAppConversationData()
  435. }, [mutateAppConversationData, handleConversationIdInfoChange])
  436. const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {
  437. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, appId)
  438. notify({ type: 'success', message: t('common.api.success') })
  439. }, [isInstalledApp, appId, t, notify])
  440. return {
  441. isInstalledApp,
  442. appId,
  443. currentConversationId,
  444. currentConversationItem,
  445. handleConversationIdInfoChange,
  446. appData,
  447. appParams: appParams || {} as ChatConfig,
  448. appMeta,
  449. appPinnedConversationData,
  450. appConversationData,
  451. appConversationDataLoading,
  452. appChatListData,
  453. appChatListDataLoading,
  454. appPrevChatTree,
  455. pinnedConversationList,
  456. conversationList,
  457. setShowNewConversationItemInList,
  458. newConversationInputs,
  459. newConversationInputsRef,
  460. handleNewConversationInputsChange,
  461. inputsForms,
  462. handleNewConversation,
  463. handleStartChat,
  464. handleChangeConversation,
  465. handlePinConversation,
  466. handleUnpinConversation,
  467. conversationDeleting,
  468. handleDeleteConversation,
  469. conversationRenaming,
  470. handleRenameConversation,
  471. handleNewConversationCompleted,
  472. newConversationId,
  473. chatShouldReloadKey,
  474. handleFeedback,
  475. currentChatInstanceRef,
  476. sidebarCollapseState,
  477. handleSidebarCollapse,
  478. clearChatList,
  479. setClearChatList,
  480. isResponding,
  481. setIsResponding,
  482. currentConversationInputs,
  483. setCurrentConversationInputs,
  484. allInputsHidden,
  485. initUserVariables,
  486. }
  487. }