Skip to content

Commit

Permalink
perf: chat store reset storage (#3186)
Browse files Browse the repository at this point in the history
* perf: chat store reset storage

* perf: auto exec code
  • Loading branch information
c121914yu committed Nov 25, 2024
1 parent 2072c22 commit c8f2689
Show file tree
Hide file tree
Showing 35 changed files with 315 additions and 209 deletions.
14 changes: 9 additions & 5 deletions packages/web/hooks/useScrollPagination.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -188,14 +188,16 @@ export function useScrollPagination<

pageSize = 10,
params = {},
EmptyTip
EmptyTip,
showErrorToast = true
}: {
refreshDeps?: any[];
scrollLoadType?: 'top' | 'bottom';

pageSize?: number;
params?: Record<string, any>;
EmptyTip?: React.JSX.Element;
showErrorToast?: boolean;
}
) {
const { t } = useTranslation();
Expand Down Expand Up @@ -249,10 +251,12 @@ export function useScrollPagination<
setData((prevData) => (offset === 0 ? res.list : [...prevData, ...res.list]));
}
} catch (error: any) {
toast({
title: getErrText(error, t('common:core.chat.error.data_error')),
status: 'error'
});
if (showErrorToast) {
toast({
title: getErrText(error, t('common:core.chat.error.data_error')),
status: 'error'
});
}
console.log(error);
}

Expand Down
3 changes: 3 additions & 0 deletions packages/web/i18n/en/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"app.version_past": "Previously Published",
"app.version_publish_tips": "This version will be saved to the team cloud, synchronized with the entire team, and update the app version on all release channels.",
"app_detail": "Application Details",
"auto_execute": "Automatic execution",
"auto_execute_default_prompt_placeholder": "Default questions sent when executing automatically",
"chat_debug": "Chat Preview",
"chat_logs": "Conversation Logs",
"chat_logs_tips": "Logs will record the online, shared, and API (requires chatId) conversation records of this app.",
Expand Down Expand Up @@ -77,6 +79,7 @@
"move.hint": "After moving, the selected application/folder will inherit the permission settings of the new folder, and the original permission settings will become invalid.",
"move_app": "Move Application",
"not_json_file": "Please select a JSON file",
"open_auto_execute": "Enable automatic execution",
"open_vision_function_tip": "Models with icon switches have image recognition capabilities. \nAfter being turned on, the model will parse the pictures in the file link and automatically parse the pictures in the user's question (user question ≤ 500 words).",
"or_drag_JSON": "or drag in JSON file",
"paste_config": "Paste Configuration",
Expand Down
3 changes: 3 additions & 0 deletions packages/web/i18n/zh/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"app.version_past": "发布过",
"app.version_publish_tips": "该版本将被保存至团队云端,同步给整个团队,同时更新所有发布渠道的应用版本",
"app_detail": "应用详情",
"auto_execute": "自动执行",
"auto_execute_default_prompt_placeholder": "自动执行时,发送的默认问题",
"auto_execute_tip": "开启后,用户进入对话界面将自动触发工作流。执行顺序:1、对话开场白;2、全局变量;3、自动执行。",
"chat_debug": "调试预览",
"chat_logs": "对话日志",
Expand Down Expand Up @@ -78,6 +80,7 @@
"move.hint": "移动后,所选应用/文件夹将继承新文件夹的权限设置,原先的权限设置失效。",
"move_app": "移动应用",
"not_json_file": "请选择JSON文件",
"open_auto_execute": "启用自动执行",
"open_vision_function_tip": "有图示开关的模型即拥有图片识别能力。若开启,模型会解析文件链接里的图片,并自动解析用户问题中的图片(用户问题≤500字时生效)。",
"or_drag_JSON": "或拖入JSON文件",
"paste_config": "粘贴配置",
Expand Down
2 changes: 1 addition & 1 deletion projects/app/src/components/Layout/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { useMemo } from 'react';
import { Box, BoxProps, Flex, Link, LinkProps } from '@chakra-ui/react';
import { useRouter } from 'next/router';
import { useUserStore } from '@/web/support/user/useUserStore';
import { useChatStore } from '@/web/core/chat/context/storeChat';
import { useChatStore } from '@/web/core/chat/context/useChatStore';
import { HUMAN_ICON } from '@fastgpt/global/common/system/constants';
import NextLink from 'next/link';
import Badge from '../Badge';
Expand Down
2 changes: 1 addition & 1 deletion projects/app/src/components/Layout/navbarPhone.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useMemo } from 'react';
import { useRouter } from 'next/router';
import { Flex, Box } from '@chakra-ui/react';
import { useChatStore } from '@/web/core/chat/context/storeChat';
import { useChatStore } from '@/web/core/chat/context/useChatStore';
import { useTranslation } from 'next-i18next';
import Badge from '../Badge';
import MyIcon from '@fastgpt/web/components/common/Icon';
Expand Down
6 changes: 3 additions & 3 deletions projects/app/src/components/core/app/AutoExecConfig.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const AutoExecConfig = ({
return (
<Flex alignItems={'center'}>
<MyIcon name={'core/app/simpleMode/autoExec'} mr={2} w={'20px'} />
<FormLabel color={'myGray.600'}>{t('common:core.app.Auto execute')}</FormLabel>
<FormLabel color={'myGray.600'}>{t('app:auto_execute')}</FormLabel>
<ChatFunctionTip type={'autoExec'} />
<Box flex={1} />
<MyTooltip label={t('common:core.app.Config_auto_execute')}>
Expand All @@ -50,7 +50,7 @@ const AutoExecConfig = ({
>
<ModalBody>
<Flex justifyContent={'space-between'} alignItems={'center'}>
<FormLabel flex={'0 0 80px'}>{t('common:core.app.Auto execute')}</FormLabel>
<FormLabel flex={'0 0 100px'}>{t('app:open_auto_execute')}</FormLabel>
<Switch
isChecked={isOpenAutoExec}
onChange={(e) => {
Expand All @@ -68,7 +68,7 @@ const AutoExecConfig = ({
value={defaultPrompt}
rows={8}
bg={'myGray.50'}
placeholder={t('common:core.app.schedule.Default prompt placeholder')}
placeholder={t('app:auto_execute_default_prompt_placeholder')}
onChange={(e) => {
onChange({
...value,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import FilePreview from '../../components/FilePreview';
import { useFileUpload } from '../hooks/useFileUpload';
import ComplianceTip from '@/components/common/ComplianceTip/index';
import { useToast } from '@fastgpt/web/hooks/useToast';
import { useChatStore } from '@/web/core/chat/context/storeChat';

const InputGuideBox = dynamic(() => import('./InputGuideBox'));

Expand All @@ -34,33 +33,29 @@ const ChatInput = ({
onStop,
TextareaDom,
resetInputVal,
chatForm,
appId
chatForm
}: {
onSendMessage: SendPromptFnType;
onStop: () => void;
TextareaDom: React.MutableRefObject<HTMLTextAreaElement | null>;
resetInputVal: (val: ChatBoxInputType) => void;
chatForm: UseFormReturn<ChatBoxInputFormType>;
appId: string;
}) => {
const { t } = useTranslation();
const { toast } = useToast();
const { isPc } = useSystem();

const { chatId } = useChatStore();

const { setValue, watch, control } = chatForm;
const inputValue = watch('input');

const {
isChatting,
whisperConfig,
autoTTSResponse,
chatInputGuide,
outLinkAuthData,
fileSelectConfig
} = useContextSelector(ChatBoxContext, (v) => v);
const outLinkAuthData = useContextSelector(ChatBoxContext, (v) => v.outLinkAuthData);
const appId = useContextSelector(ChatBoxContext, (v) => v.appId);
const chatId = useContextSelector(ChatBoxContext, (v) => v.chatId);
const isChatting = useContextSelector(ChatBoxContext, (v) => v.isChatting);
const whisperConfig = useContextSelector(ChatBoxContext, (v) => v.whisperConfig);
const autoTTSResponse = useContextSelector(ChatBoxContext, (v) => v.autoTTSResponse);
const chatInputGuide = useContextSelector(ChatBoxContext, (v) => v.chatInputGuide);
const fileSelectConfig = useContextSelector(ChatBoxContext, (v) => v.fileSelectConfig);

const fileCtrl = useFieldArray({
control,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ import { createContext, useContextSelector } from 'use-context-selector';
import { VariableInputEnum } from '@fastgpt/global/core/workflow/constants';
import { getChatResData } from '@/web/core/chat/api';
import { ChatItemContext } from '@/web/core/chat/context/chatItemContext';
import { useChatStore } from '@/web/core/chat/context/storeChat';
import { ChatRecordContext } from '@/web/core/chat/context/chatRecordContext';

export type ChatProviderProps = {
// not chat test params
appId: string;
chatId: string;
outLinkAuthData?: OutLinkChatAuthProps;

chatType: 'log' | 'chat' | 'share' | 'team';
showRawSource: boolean;
showNodeStatus: boolean;
Expand Down Expand Up @@ -60,9 +62,12 @@ type useChatStoreType = ChatProviderProps & {
setAudioPlayingChatId: React.Dispatch<React.SetStateAction<string | undefined>>;
isChatting: boolean;
chatInputGuide: ChatInputGuideConfigType;
outLinkAuthData: OutLinkChatAuthProps;
getHistoryResponseData: ({ dataId }: { dataId: string }) => Promise<ChatHistoryItemResType[]>;
fileSelectConfig: AppFileSelectConfigType;

appId: string;
chatId: string;
outLinkAuthData: OutLinkChatAuthProps;
};

export const ChatBoxContext = createContext<useChatStoreType>({
Expand Down Expand Up @@ -120,6 +125,9 @@ export const ChatBoxContext = createContext<useChatStoreType>({
});

const Provider = ({
appId,
chatId,
outLinkAuthData = {},
chatType = 'chat',
showRawSource,
showNodeStatus,
Expand All @@ -128,7 +136,6 @@ const Provider = ({
}: ChatProviderProps & {
children: React.ReactNode;
}) => {
const { chatId, appId, outLinkAuthData } = useChatStore();
const chatConfig = useContextSelector(
ChatItemContext,
(v) => v.chatBoxData?.app?.chatConfig || {}
Expand Down Expand Up @@ -215,6 +222,8 @@ const Provider = ({
setAudioPlayingChatId,
isChatting,
chatInputGuide,
appId,
chatId,
outLinkAuthData,
getHistoryResponseData,
chatType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,24 @@ import { ChatBoxInputFormType, UserInputFileItemType } from '../type';
import { AppFileSelectConfigType } from '@fastgpt/global/core/app/type';
import { documentFileType } from '@fastgpt/global/common/file/constants';
import { useSystemStore } from '@/web/common/system/useSystemStore';
import { useChatStore } from '@/web/core/chat/context/storeChat';
import { useContextSelector } from 'use-context-selector';
import { ChatBoxContext } from '../Provider';

type UseFileUploadOptions = {
fileSelectConfig: AppFileSelectConfigType;
fileCtrl: UseFieldArrayReturn<ChatBoxInputFormType, 'files', 'id'>;
};

export const useFileUpload = (props: UseFileUploadOptions) => {
const { outLinkAuthData, appId, chatId } = useChatStore();
const { fileSelectConfig, fileCtrl } = props;
const { toast } = useToast();
const { t } = useTranslation();
const { feConfigs } = useSystemStore();

const outLinkAuthData = useContextSelector(ChatBoxContext, (v) => v.outLinkAuthData);
const appId = useContextSelector(ChatBoxContext, (v) => v.appId);
const chatId = useContextSelector(ChatBoxContext, (v) => v.chatId);

const {
update: updateFiles,
remove: removeFiles,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ import { mergeChatResponseData } from '@fastgpt/global/core/chat/utils';
import { getWebReqUrl } from '@fastgpt/web/common/system/utils';
import { ChatRecordContext } from '@/web/core/chat/context/chatRecordContext';
import { ChatItemContext } from '@/web/core/chat/context/chatItemContext';
import { useChatStore } from '@/web/core/chat/context/storeChat';
import TimeBox from './components/TimeBox';
import MyBox from '@fastgpt/web/components/common/MyBox';

Expand Down Expand Up @@ -130,8 +129,6 @@ const ChatBox = ({
const [adminMarkData, setAdminMarkData] = useState<AdminMarkType & { dataId: string }>();
const [questionGuides, setQuestionGuide] = useState<string[]>([]);

const { appId, chatId, outLinkAuthData } = useChatStore();

const appAvatar = useContextSelector(ChatItemContext, (v) => v.chatBoxData?.app?.avatar);
const userAvatar = useContextSelector(ChatItemContext, (v) => v.chatBoxData?.userAvatar);
const ChatBoxRef = useContextSelector(ChatItemContext, (v) => v.ChatBoxRef);
Expand All @@ -145,6 +142,9 @@ const ChatBox = ({
);
const ScrollData = useContextSelector(ChatRecordContext, (v) => v.ScrollData);

const appId = useContextSelector(ChatBoxContext, (v) => v.appId);
const chatId = useContextSelector(ChatBoxContext, (v) => v.chatId);
const outLinkAuthData = useContextSelector(ChatBoxContext, (v) => v.outLinkAuthData);
const welcomeText = useContextSelector(ChatBoxContext, (v) => v.welcomeText);
const variableList = useContextSelector(ChatBoxContext, (v) => v.variableList);
const allVariableList = useContextSelector(ChatBoxContext, (v) => v.allVariableList);
Expand Down Expand Up @@ -854,15 +854,25 @@ const ChatBox = ({
restartChat() {
abortRequest();

setIsChatRecordsLoaded(false);
setChatRecords([]);
setIsChatRecordsLoaded(false);
setValue('chatStarted', false);
},
scrollToBottom(behavior = 'auto') {
scrollToBottom(behavior, 500);
}
}));

// Auto send prompt
useEffect(() => {
if (autoExecute.open && chatStarted && chatRecords.length === 0 && isChatRecordsLoaded) {
sendPrompt({
text: autoExecute.defaultPrompt || 'AUTO_EXECUTE',
hideInUI: true
});
}
}, [sendPrompt, chatStarted, autoExecute, chatRecords, isChatRecordsLoaded]);

const RenderRecords = useMemo(() => {
return (
<ScrollData
Expand Down Expand Up @@ -1006,15 +1016,6 @@ const ChatBox = ({
welcomeText
]);

useEffect(() => {
if (autoExecute.open && chatStarted && chatRecords.length === 0 && isChatRecordsLoaded) {
sendPrompt({
text: autoExecute.defaultPrompt || 'AUTO_EXECUTE',
hideInUI: true
});
}
}, [sendPrompt, chatStarted, autoExecute, chatRecords, isChatRecordsLoaded]);

return (
<MyBox
isLoading={isLoading}
Expand All @@ -1027,18 +1028,17 @@ const ChatBox = ({
{/* chat box container */}
{RenderRecords}
{/* message input */}
{onStartChat && chatStarted && active && appId && !isInteractive && (
{onStartChat && chatStarted && active && !isInteractive && (
<ChatInput
onSendMessage={sendPrompt}
onStop={() => chatController.current?.abort('stop')}
TextareaDom={TextareaDom}
resetInputVal={resetInputVal}
chatForm={chatForm}
appId={appId}
/>
)}
{/* user feedback modal */}
{!!feedbackId && chatId && appId && (
{!!feedbackId && chatId && (
<FeedbackModal
appId={appId}
teamId={teamId}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,9 @@ import { ChatBoxInputFormType } from '../../ChatBox/type';
import { FlowNodeInputItemType } from '@fastgpt/global/core/workflow/type/io';
import { ChatItemContext } from '@/web/core/chat/context/chatItemContext';
import { ChatRecordContext } from '@/web/core/chat/context/chatRecordContext';
import { useChatStore } from '@/web/core/chat/context/storeChat';

const RenderInput = () => {
const { t } = useTranslation();
const { chatId, outLinkAuthData } = useChatStore();

const pluginInputs = useContextSelector(ChatItemContext, (v) => v.chatBoxData?.app?.pluginInputs);
const variablesForm = useContextSelector(ChatItemContext, (v) => v.variablesForm);
Expand All @@ -35,6 +33,8 @@ const RenderInput = () => {
const isChatting = useContextSelector(PluginRunContext, (v) => v.isChatting);
const fileSelectConfig = useContextSelector(PluginRunContext, (v) => v.fileSelectConfig);
const instruction = useContextSelector(PluginRunContext, (v) => v.instruction);
const chatId = useContextSelector(PluginRunContext, (v) => v.chatId);
const outLinkAuthData = useContextSelector(PluginRunContext, (v) => v.outLinkAuthData);

const {
control,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import MyNumberInput from '@fastgpt/web/components/common/Input/NumberInput';
import { isEqual } from 'lodash';
import { ChatItemContext } from '@/web/core/chat/context/chatItemContext';
import { ChatRecordContext } from '@/web/core/chat/context/chatRecordContext';
import { useChatStore } from '@/web/core/chat/context/storeChat';

const JsonEditor = dynamic(() => import('@fastgpt/web/components/common/Textarea/JsonEditor'));

Expand All @@ -35,7 +34,6 @@ const FileSelector = ({
value: any;
}) => {
const { t } = useTranslation();
const { outLinkAuthData } = useChatStore();

const variablesForm = useContextSelector(ChatItemContext, (v) => v.variablesForm);
const histories = useContextSelector(ChatRecordContext, (v) => v.chatRecords);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import { getPluginRunUserQuery } from '@fastgpt/global/core/workflow/utils';
import { cloneDeep } from 'lodash';
import { ChatItemContext } from '@/web/core/chat/context/chatItemContext';
import { ChatRecordContext } from '@/web/core/chat/context/chatRecordContext';
import { useChatStore } from '@/web/core/chat/context/storeChat';
import { AppFileSelectConfigType } from '@fastgpt/global/core/app/type';
import { defaultAppSelectFileConfig } from '@fastgpt/global/core/app/constants';

Expand All @@ -33,7 +32,10 @@ export const PluginRunContext = createContext<PluginRunContextType>({
throw new Error('Function not implemented.');
},
instruction: '',
fileSelectConfig: defaultAppSelectFileConfig
fileSelectConfig: defaultAppSelectFileConfig,
appId: '',
chatId: '',
outLinkAuthData: {}
});

const PluginRunContextProvider = ({
Expand Down
Loading

0 comments on commit c8f2689

Please sign in to comment.