4.8.5 test (#1819)

This commit is contained in:
Archer
2024-06-21 18:32:05 +08:00
committed by GitHub
parent 5cc01b8509
commit 24596a6e21
40 changed files with 908 additions and 1058 deletions

View File

@@ -1,18 +1,9 @@
import React, { useCallback, useEffect, useRef } from 'react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import NextHead from '@/components/common/NextHead';
import { getTeamChatInfo } from '@/web/core/chat/api';
import { delChatRecordById, getChatHistories, getTeamChatInfo } from '@/web/core/chat/api';
import { useRouter } from 'next/router';
import {
Box,
Flex,
useDisclosure,
Drawer,
DrawerOverlay,
DrawerContent,
useTheme
} from '@chakra-ui/react';
import { Box, Flex, Drawer, DrawerOverlay, DrawerContent, useTheme } from '@chakra-ui/react';
import { useToast } from '@fastgpt/web/hooks/useToast';
import { useQuery } from '@tanstack/react-query';
import { useSystemStore } from '@/web/common/system/useSystemStore';
import SideBar from '@/components/SideBar';
import PageContainer from '@/components/PageContainer';
@@ -22,21 +13,26 @@ import ChatHeader from './components/ChatHeader';
import { serviceSideProps } from '@/web/common/utils/i18n';
import { useTranslation } from 'next-i18next';
import { checkChatSupportSelectFileByChatModels } from '@/web/core/chat/utils';
import { useChatStore } from '@/web/core/chat/storeChat';
import { customAlphabet } from 'nanoid';
const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyz1234567890', 12);
import ChatBox from '@/components/ChatBox';
import type { ComponentRef, StartChatFnProps } from '@/components/ChatBox/type.d';
import { streamFetch } from '@/web/common/api/fetch';
import type { ChatHistoryItemType } from '@fastgpt/global/core/chat/type.d';
import { getChatTitleFromChatMessage } from '@fastgpt/global/core/chat/utils';
import { ChatStatusEnum } from '@fastgpt/global/core/chat/constants';
import { getErrText } from '@fastgpt/global/common/error/utils';
import MyBox from '@fastgpt/web/components/common/MyBox';
import SliderApps from './components/SliderApps';
import { GPTMessages2Chats } from '@fastgpt/global/core/chat/adapt';
import { useRequest2 } from '@fastgpt/web/hooks/useRequest';
import ChatContextProvider, { ChatContext } from '@/web/core/chat/context/chatContext';
import { AppListItemType } from '@fastgpt/global/core/app/type';
import { useContextSelector } from 'use-context-selector';
import { InitChatResponse } from '@/global/core/chat/api';
import { defaultChatData } from '@/global/core/chat/constants';
const OutLink = () => {
type Props = { appId: string; chatId: string; teamId: string; teamToken: string };
const Chat = ({ myApps }: { myApps: AppListItemType[] }) => {
const { t } = useTranslation();
const router = useRouter();
const {
@@ -45,11 +41,7 @@ const OutLink = () => {
chatId = '',
teamToken,
...customVariables
} = router.query as {
teamId: string;
appId: string;
chatId: string;
teamToken: string;
} = router.query as Props & {
[key: string]: string;
};
@@ -57,22 +49,20 @@ const OutLink = () => {
const theme = useTheme();
const { isPc } = useSystemStore();
const ChatBoxRef = useRef<ComponentRef>(null);
const forbidRefresh = useRef(false);
const { isOpen: isOpenSlider, onClose: onCloseSlider, onOpen: onOpenSlider } = useDisclosure();
const [chatData, setChatData] = useState<InitChatResponse>(defaultChatData);
const {
chatData,
setChatData,
histories,
loadHistories,
lastChatAppId,
lastChatId,
pushHistory,
updateHistory,
delOneHistory,
delOneHistoryItem,
clearHistories
} = useChatStore();
onUpdateHistory,
onClearHistories,
onDelHistory,
isOpenSlider,
onCloseSlider,
forbidLoadChat,
onChangeChatId,
onChangeAppId
} = useContextSelector(ChatContext, (v) => v);
const startChat = useCallback(
async ({ messages, controller, generatingMessage, variables }: StartChatFnProps) => {
@@ -99,34 +89,16 @@ const OutLink = () => {
// new chat
if (completionChatId !== chatId) {
const newHistory: ChatHistoryItemType = {
chatId: completionChatId,
updateTime: new Date(),
title: newTitle,
appId,
top: false
};
pushHistory(newHistory);
if (controller.signal.reason !== 'leave') {
forbidRefresh.current = true;
router.replace({
query: {
...router.query,
chatId: completionChatId
}
});
}
onChangeChatId(completionChatId, true);
loadHistories();
} else {
// update chat
const currentChat = histories.find((item) => item.chatId === chatId);
currentChat &&
updateHistory({
...currentChat,
updateTime: new Date(),
title: newTitle,
teamId,
teamToken
});
onUpdateHistory({
appId: chatData.appId,
chatId: completionChatId,
title: newTitle,
teamId,
teamToken
});
}
// update chat window
setChatData((state) => ({
@@ -135,7 +107,7 @@ const OutLink = () => {
history: ChatBoxRef.current?.getChatHistories() || state.history
}));
return { responseText, responseData, isNewChat: forbidRefresh.current };
return { responseText, responseData, isNewChat: forbidLoadChat.current };
},
[
chatId,
@@ -143,132 +115,63 @@ const OutLink = () => {
appId,
teamId,
teamToken,
setChatData,
pushHistory,
router,
histories,
updateHistory
forbidLoadChat,
onChangeChatId,
loadHistories,
onUpdateHistory,
chatData.appId
]
);
/* replace router query to last chat */
useEffect(() => {
if ((!chatId || !appId) && (lastChatId || lastChatAppId)) {
router.replace({
query: {
...router.query,
chatId: chatId || lastChatId,
appId: appId || lastChatAppId
}
});
}
}, []);
// get chat app list
const loadApps = useCallback(async () => {
try {
const apps = await getMyTokensApps({ teamId, teamToken });
if (apps.length <= 0) {
toast({
status: 'error',
title: t('core.chat.You need to a chat app')
});
return [];
}
// if app id not exist, redirect to first app
if (!appId || !apps.find((item) => item._id === appId)) {
router.replace({
query: {
...router.query,
appId: apps[0]?._id
}
});
}
return apps;
} catch (error: any) {
toast({
status: 'warning',
title: getErrText(error)
});
}
return [];
}, [appId, teamToken, router, teamId, t, toast]);
const { data: myApps = [], isLoading: isLoadingApps } = useQuery(['initApps', teamId], () => {
if (!teamId) {
toast({
status: 'error',
title: t('support.user.team.tag.Have not opened')
});
return;
}
return loadApps();
});
// load histories
useQuery(['loadHistories', appId], () => {
if (teamId && appId) {
return loadHistories({ teamId, appId, teamToken: teamToken });
}
return;
});
// get chat app info
const loadChatInfo = useCallback(async () => {
try {
const res = await getTeamChatInfo({ teamId, appId, chatId, teamToken: teamToken });
const { loading } = useRequest2(
async () => {
if (!appId || forbidLoadChat.current) return;
const res = await getTeamChatInfo({ teamId, appId, chatId, teamToken });
const history = res.history.map((item) => ({
...item,
dataId: item.dataId || nanoid(),
status: ChatStatusEnum.finish
}));
setChatData({
const result: InitChatResponse = {
...res,
history
});
};
// have records.
ChatBoxRef.current?.resetHistory(history);
ChatBoxRef.current?.resetVariables(res.variables);
if (res.history.length > 0) {
setTimeout(() => {
ChatBoxRef.current?.scrollToBottom('auto');
}, 500);
}
} catch (e: any) {
toast({
title: t('core.chat.Failed to initialize chat'),
status: 'error'
});
if (chatId) {
router.replace({
query: {
...router.query,
chatId: ''
}
setChatData(result);
},
{
manual: false,
refreshDeps: [teamId, teamToken, appId, chatId],
onError(e: any) {
toast({
title: getErrText(e, t('core.chat.Failed to initialize chat')),
status: 'error'
});
if (chatId) {
onChangeChatId('');
}
},
onFinally() {
forbidLoadChat.current = false;
}
}
return null;
}, [teamId, appId, chatId, teamToken, setChatData, toast, t, router]);
const { isFetching } = useQuery(['init', teamId, appId, chatId], () => {
if (forbidRefresh.current) {
forbidRefresh.current = false;
return null;
}
if (teamId && appId) {
return loadChatInfo();
}
return null;
});
);
return (
<MyBox display={'flex'} h={'100%'} isLoading={isLoadingApps || isFetching}>
<NextHead title={chatData.app.name}></NextHead>
<Flex h={'100%'}>
<NextHead title={chatData.app.name} icon={chatData.app.avatar}></NextHead>
{/* pc show myself apps */}
{isPc && (
<Box borderRight={theme.borders.base} w={'220px'} flexShrink={0}>
@@ -276,7 +179,7 @@ const OutLink = () => {
</Box>
)}
<PageContainer flex={'1 0 0'} w={0} p={[0, '16px']} position={'relative'}>
<PageContainer isLoading={loading} flex={'1 0 0'} w={0} p={[0, '16px']} position={'relative'}>
<Flex h={'100%'} flexDirection={['column', 'row']} bg={'white'}>
{((children: React.ReactNode) => {
return isPc || !appId ? (
@@ -299,44 +202,18 @@ const OutLink = () => {
apps={myApps}
appName={chatData.app.name}
appAvatar={chatData.app.avatar}
activeChatId={chatId}
confirmClearText={t('core.chat.Confirm to clear history')}
onClose={onCloseSlider}
history={histories.map((item, i) => ({
id: item.chatId,
title: item.title,
customTitle: item.customTitle,
top: item.top
}))}
onChangeChat={(chatId) => {
router.replace({
query: {
...router.query,
chatId: chatId || ''
}
});
if (!isPc) {
onCloseSlider();
}
}}
onDelHistory={(e) => delOneHistory({ ...e, appId, teamId, teamToken })}
onDelHistory={(e) => onDelHistory({ ...e, appId, teamId, teamToken })}
onClearHistory={() => {
clearHistories({ appId, teamId, teamToken });
router.replace({
query: {
...router.query,
chatId: ''
}
});
onClearHistories({ appId, teamId, teamToken });
}}
onSetHistoryTop={(e) => {
updateHistory({ ...e, teamId, teamToken, appId });
onUpdateHistory({ ...e, teamId, teamToken, appId });
}}
onSetCustomTitle={async (e) => {
updateHistory({
onUpdateHistory({
appId,
chatId: e.chatId,
title: e.title,
customTitle: e.title,
teamId,
teamToken
@@ -357,13 +234,11 @@ const OutLink = () => {
appAvatar={chatData.app.avatar}
appName={chatData.app.name}
history={chatData.history}
onOpenSlider={onOpenSlider}
showHistory
/>
{/* chat box */}
<Box flex={1}>
<ChatBox
active={!!chatData.app.name}
ref={ChatBoxRef}
appAvatar={chatData.app.avatar}
userAvatar={chatData.userAvatar}
@@ -372,8 +247,8 @@ const OutLink = () => {
feedbackType={'user'}
onUpdateVariable={(e) => {}}
onStartChat={startChat}
onDelMessage={(e) =>
delOneHistoryItem({ ...e, appId: chatData.appId, chatId, teamId, teamToken })
onDelMessage={({ contentId }) =>
delChatRecordById({ contentId, appId: chatData.appId, chatId, teamId, teamToken })
}
appId={chatData.appId}
chatId={chatId}
@@ -384,16 +259,73 @@ const OutLink = () => {
</Flex>
</Flex>
</PageContainer>
</MyBox>
</Flex>
);
};
const Render = (props: Props) => {
const { teamId, appId, teamToken } = props;
const { t } = useTranslation();
const { toast } = useToast();
const router = useRouter();
const { data: myApps = [], runAsync: loadMyApps } = useRequest2(
async () => {
if (teamId && teamToken) {
return getMyTokensApps({ teamId, teamToken });
}
return [];
},
{
manual: false
}
);
const { data: histories = [], runAsync: loadHistories } = useRequest2(
async () => {
if (teamId && appId && teamToken) {
return getChatHistories({ teamId, appId, teamToken: teamToken });
}
return [];
},
{
manual: false,
refreshDeps: [appId, teamId, teamToken]
}
);
// 初始化聊天框
useEffect(() => {
(async () => {
if (appId || myApps.length === 0) return;
router.replace({
query: {
...router.query,
appId: myApps[0]._id,
chatId: ''
}
});
})();
}, [appId, loadMyApps, myApps, router, t, toast]);
return (
<ChatContextProvider histories={histories} loadHistories={loadHistories}>
<Chat {...props} myApps={myApps} />
</ChatContextProvider>
);
};
export async function getServerSideProps(context: any) {
return {
props: {
appId: context?.query?.appId || '',
chatId: context?.query?.chatId || '',
teamId: context?.query?.teamId || '',
teamToken: context?.query?.teamToken || '',
...(await serviceSideProps(context, ['file']))
}
};
}
export default OutLink;
export default Render;