Skip to content

Commit

Permalink
fix: auto send prompt runtime (#3295)
Browse files Browse the repository at this point in the history
  • Loading branch information
c121914yu authored Dec 2, 2024
1 parent c506442 commit f28b7e4
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 76 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ type useChatStoreType = ChatProviderProps & {
ttsConfig: AppTTSConfigType;
whisperConfig: AppWhisperConfigType;
autoTTSResponse: boolean;
autoExecute: AppAutoExecuteConfigType;
startSegmentedAudio: () => Promise<any>;
splitText2Audio: (text: string, done?: boolean | undefined) => void;
finishSegmentedAudio: () => void;
Expand Down Expand Up @@ -136,24 +135,38 @@ const Provider = ({
}: ChatProviderProps & {
children: React.ReactNode;
}) => {
const chatConfig = useContextSelector(
const welcomeText = useContextSelector(
ChatItemContext,
(v) => v.chatBoxData?.app?.chatConfig || {}
(v) => v.chatBoxData?.app?.chatConfig?.welcomeText ?? ''
);
const variables = useContextSelector(
ChatItemContext,
(v) => v.chatBoxData?.app?.chatConfig?.variables ?? []
);
const questionGuide = useContextSelector(
ChatItemContext,
(v) => v.chatBoxData?.app?.chatConfig?.questionGuide ?? false
);
const ttsConfig = useContextSelector(
ChatItemContext,
(v) => v.chatBoxData?.app?.chatConfig?.ttsConfig ?? defaultTTSConfig
);
const whisperConfig = useContextSelector(
ChatItemContext,
(v) => v.chatBoxData?.app?.chatConfig?.whisperConfig ?? defaultWhisperConfig
);
const chatInputGuide = useContextSelector(
ChatItemContext,
(v) => v.chatBoxData?.app?.chatConfig?.chatInputGuide ?? defaultChatInputGuideConfig
);
const fileSelectConfig = useContextSelector(
ChatItemContext,
(v) => v.chatBoxData?.app?.chatConfig?.fileSelectConfig ?? defaultAppSelectFileConfig
);

const chatRecords = useContextSelector(ChatRecordContext, (v) => v.chatRecords);
const setChatRecords = useContextSelector(ChatRecordContext, (v) => v.setChatRecords);

const {
welcomeText = '',
variables = [],
questionGuide = false,
ttsConfig = defaultTTSConfig,
whisperConfig = defaultWhisperConfig,
chatInputGuide = defaultChatInputGuideConfig,
fileSelectConfig = defaultAppSelectFileConfig,
autoExecute = defaultAutoExecuteConfig
} = useMemo(() => chatConfig, [chatConfig]);

// segment audio
const [audioPlayingChatId, setAudioPlayingChatId] = useState<string>();
const {
Expand Down Expand Up @@ -202,7 +215,6 @@ const Provider = ({
const value: useChatStoreType = {
...props,
welcomeText,
autoExecute,
variableList: variables.filter((item) => item.type !== VariableInputEnum.custom),
allVariableList: variables,
questionGuide,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ enum FeedbackTypeEnum {

type Props = OutLinkChatAuthProps &
ChatProviderProps & {
isReady?: boolean;
feedbackType?: `${FeedbackTypeEnum}`;
showMarkIcon?: boolean; // admin mark dataset
showVoiceIcon?: boolean;
Expand All @@ -98,7 +97,6 @@ type Props = OutLinkChatAuthProps &
};

const ChatBox = ({
isReady = true,
feedbackType = FeedbackTypeEnum.hidden,
showMarkIcon = false,
showVoiceIcon = true,
Expand Down Expand Up @@ -132,6 +130,7 @@ const ChatBox = ({

const appAvatar = useContextSelector(ChatItemContext, (v) => v.chatBoxData?.app?.avatar);
const userAvatar = useContextSelector(ChatItemContext, (v) => v.chatBoxData?.userAvatar);
const chatBoxData = useContextSelector(ChatItemContext, (v) => v.chatBoxData);
const ChatBoxRef = useContextSelector(ChatItemContext, (v) => v.ChatBoxRef);
const variablesForm = useContextSelector(ChatItemContext, (v) => v.variablesForm);
const chatRecords = useContextSelector(ChatRecordContext, (v) => v.chatRecords);
Expand All @@ -146,7 +145,6 @@ const ChatBox = ({
const variableList = useContextSelector(ChatBoxContext, (v) => v.variableList);
const allVariableList = useContextSelector(ChatBoxContext, (v) => v.allVariableList);
const questionGuide = useContextSelector(ChatBoxContext, (v) => v.questionGuide);
const autoExecute = useContextSelector(ChatBoxContext, (v) => v.autoExecute);
const startSegmentedAudio = useContextSelector(ChatBoxContext, (v) => v.startSegmentedAudio);
const finishSegmentedAudio = useContextSelector(ChatBoxContext, (v) => v.finishSegmentedAudio);
const setAudioPlayingChatId = useContextSelector(ChatBoxContext, (v) => v.setAudioPlayingChatId);
Expand All @@ -166,7 +164,9 @@ const ChatBox = ({
});
const { setValue, watch } = chatForm;
const chatStartedWatch = watch('chatStarted');
const chatStarted = chatStartedWatch || chatRecords.length > 0 || variableList.length === 0;
const chatStarted =
chatBoxData?.appId === appId &&
(chatStartedWatch || chatRecords.length > 0 || variableList.length === 0);

// 滚动到底部
const scrollToBottom = useMemoizedFn((behavior: 'smooth' | 'auto' = 'smooth', delay = 0) => {
Expand Down Expand Up @@ -802,9 +802,9 @@ const ChatBox = ({
setQuestionGuide([]);
setValue('chatStarted', false);
abortRequest('leave');
}, [router.query, setValue, chatId]);
}, [abortRequest, setValue]);

// add listener
// Add listener
useEffect(() => {
const windowMessage = ({ data }: MessageEvent<{ type: 'sendPrompt'; text: string }>) => {
if (data?.type === 'sendPrompt' && data?.text) {
Expand All @@ -829,30 +829,27 @@ const ChatBox = ({
eventBus.off(EventNameEnum.sendQuestion);
eventBus.off(EventNameEnum.editQuestion);
};
}, [isReady, resetInputVal, sendPrompt]);
}, [chatBoxData, resetInputVal, sendPrompt]);

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

// output data
Expand Down
10 changes: 5 additions & 5 deletions projects/app/src/pages/chat/components/ChatHeader.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useState, useCallback } from 'react';
import { Flex, useTheme, Box, useDisclosure } from '@chakra-ui/react';
import { Flex, Box, useDisclosure } from '@chakra-ui/react';
import MyIcon from '@fastgpt/web/components/common/Icon';
import Avatar from '@fastgpt/web/components/common/Avatar';
import ToolMenu from './ToolMenu';
Expand All @@ -10,7 +10,6 @@ import MyTag from '@fastgpt/web/components/common/Tag/index';
import { useContextSelector } from 'use-context-selector';
import { ChatContext } from '@/web/core/chat/context/chatContext';
import MyTooltip from '@fastgpt/web/components/common/MyTooltip';
import { InitChatResponse } from '@/global/core/chat/api';
import { AppFolderTypeList, AppTypeEnum } from '@fastgpt/global/core/app/constants';
import { useSystem } from '@fastgpt/web/hooks/useSystem';
import LightRowTabs from '@fastgpt/web/components/common/Tabs/LightRowTabs';
Expand All @@ -22,9 +21,9 @@ import {
} from '@fastgpt/global/common/parentFolder/type';
import { getMyApps } from '@/web/core/app/api';
import SelectOneResource from '@/components/common/folder/SelectOneResource';
import { ChatItemContext } from '@/web/core/chat/context/chatItemContext';

const ChatHeader = ({
chatData,
history,
showHistory,
apps,
Expand All @@ -33,15 +32,16 @@ const ChatHeader = ({
}: {
history: ChatItemType[];
showHistory?: boolean;
chatData: InitChatResponse;
apps?: AppListItemType[];
onRouteToAppDetail?: () => void;
totalRecordsCount: number;
}) => {
const { t } = useTranslation();
const isPlugin = chatData.app.type === AppTypeEnum.plugin;
const { isPc } = useSystem();

const chatData = useContextSelector(ChatItemContext, (v) => v.chatBoxData);
const isPlugin = chatData.app.type === AppTypeEnum.plugin;

return isPc && isPlugin ? null : (
<Flex
alignItems={'center'}
Expand Down
21 changes: 7 additions & 14 deletions projects/app/src/pages/chat/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import React, { useCallback, useEffect, useMemo } from 'react';
import NextHead from '@/components/common/NextHead';
import { useRouter } from 'next/router';
import { getInitChatInfo } from '@/web/core/chat/api';
Expand All @@ -24,7 +24,7 @@ import { useRequest2 } from '@fastgpt/web/hooks/useRequest';
import { useMount } from 'ahooks';
import { getNanoid } from '@fastgpt/global/common/string/tools';

import { defaultChatData, GetChatTypeEnum } from '@/global/core/chat/constants';
import { GetChatTypeEnum } from '@/global/core/chat/constants';
import ChatContextProvider, { ChatContext } from '@/web/core/chat/context/chatContext';
import { AppListItemType } from '@fastgpt/global/core/app/type';
import { useContextSelector } from 'use-context-selector';
Expand All @@ -36,7 +36,6 @@ import ChatItemContextProvider, { ChatItemContext } from '@/web/core/chat/contex
import ChatRecordContextProvider, {
ChatRecordContext
} from '@/web/core/chat/context/chatRecordContext';
import { InitChatResponse } from '@/global/core/chat/api';

const CustomPluginRunBox = dynamic(() => import('./components/CustomPluginRunBox'));

Expand All @@ -56,13 +55,13 @@ const Chat = ({ myApps }: { myApps: AppListItemType[] }) => {

const resetVariables = useContextSelector(ChatItemContext, (v) => v.resetVariables);
const isPlugin = useContextSelector(ChatItemContext, (v) => v.isPlugin);
const chatBoxData = useContextSelector(ChatItemContext, (v) => v.chatBoxData);
const setChatBoxData = useContextSelector(ChatItemContext, (v) => v.setChatBoxData);

const chatRecords = useContextSelector(ChatRecordContext, (v) => v.chatRecords);
const totalRecordsCount = useContextSelector(ChatRecordContext, (v) => v.totalRecordsCount);

// Load chat init data
const [chatData, setChatData] = useState<InitChatResponse>(defaultChatData);
const { loading } = useRequest2(
async () => {
if (!appId || forbidLoadChat.current) return;
Expand All @@ -71,11 +70,7 @@ const Chat = ({ myApps }: { myApps: AppListItemType[] }) => {
res.userAvatar = userInfo?.avatar;

// Wait for state update to complete
await new Promise((resolve) => {
setChatData(res);
setChatBoxData(res);
setTimeout(resolve, 0);
});
setChatBoxData(res);

// reset chat variables
resetVariables({
Expand Down Expand Up @@ -132,14 +127,14 @@ const Chat = ({ myApps }: { myApps: AppListItemType[] }) => {
// new chat
onUpdateHistoryTitle({ chatId, newTitle });
// update chat window
setChatData((state) => ({
setChatBoxData((state) => ({
...state,
title: newTitle
}));

return { responseText, responseData, isNewChat: forbidLoadChat.current };
},
[chatId, appId, onUpdateHistoryTitle, forbidLoadChat]
[appId, chatId, onUpdateHistoryTitle, setChatBoxData, forbidLoadChat]
);
const RenderHistorySlider = useMemo(() => {
const Children = (
Expand All @@ -164,7 +159,7 @@ const Chat = ({ myApps }: { myApps: AppListItemType[] }) => {

return (
<Flex h={'100%'}>
<NextHead title={chatData.app.name} icon={chatData.app.avatar}></NextHead>
<NextHead title={chatBoxData.app.name} icon={chatBoxData.app.avatar}></NextHead>
{/* pc show myself apps */}
{isPc && (
<Box borderRight={theme.borders.base} w={'220px'} flexShrink={0}>
Expand All @@ -188,7 +183,6 @@ const Chat = ({ myApps }: { myApps: AppListItemType[] }) => {
<ChatHeader
totalRecordsCount={totalRecordsCount}
apps={myApps}
chatData={chatData}
history={chatRecords}
showHistory
onRouteToAppDetail={() => router.push(`/app/detail?appId=${appId}`)}
Expand All @@ -213,7 +207,6 @@ const Chat = ({ myApps }: { myApps: AppListItemType[] }) => {
feedbackType={'user'}
onStartChat={onStartChat}
chatType={'chat'}
isReady={!loading}
showRawSource
showNodeStatus
/>
Expand Down
21 changes: 11 additions & 10 deletions projects/app/src/pages/chat/share.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ const OutLink = (props: Props) => {
const isChatRecordsLoaded = useContextSelector(ChatRecordContext, (v) => v.isChatRecordsLoaded);

const initSign = useRef(false);
const [chatData, setChatData] = useState<InitChatResponse>(defaultChatData);
const { data, loading } = useRequest2(
async () => {
const shareId = outLinkAuthData.shareId;
Expand All @@ -100,11 +99,7 @@ const OutLink = (props: Props) => {
outLinkUid
});

await new Promise((resolve) => {
setChatData(res);
setChatBoxData(res);
setTimeout(resolve, 0);
});
setChatBoxData(res);

resetVariables({
variables: res.variables
Expand Down Expand Up @@ -180,7 +175,7 @@ const OutLink = (props: Props) => {
onUpdateHistoryTitle({ chatId: completionChatId, newTitle });

// update chat window
setChatData((state) => ({
setChatBoxData((state) => ({
...state,
title: newTitle
}));
Expand All @@ -199,7 +194,15 @@ const OutLink = (props: Props) => {

return { responseText, responseData, isNewChat: forbidLoadChat.current };
},
[chatId, customVariables, outLinkAuthData, onUpdateHistoryTitle, forbidLoadChat, onChangeChatId]
[
chatId,
customVariables,
outLinkAuthData,
onUpdateHistoryTitle,
setChatBoxData,
forbidLoadChat,
onChangeChatId
]
);

// window init
Expand Down Expand Up @@ -258,7 +261,6 @@ const OutLink = (props: Props) => {
{/* header */}
{showHead === '1' ? (
<ChatHeader
chatData={chatData}
history={chatRecords}
totalRecordsCount={totalRecordsCount}
showHistory={showHistory === '1'}
Expand All @@ -282,7 +284,6 @@ const OutLink = (props: Props) => {
feedbackType={'user'}
onStartChat={startChat}
chatType="share"
isReady={!loading}
showRawSource={showRawSource}
showNodeStatus={showNodeStatus}
/>
Expand Down
Loading

0 comments on commit f28b7e4

Please sign in to comment.