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

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