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

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