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

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