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

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