Skip to content

Commit

Permalink
fix: Fixed an issue where the first message would be displayed when s…
Browse files Browse the repository at this point in the history
…ending the second message #2625 (#2626)

### What problem does this PR solve?

fix: Fixed an issue where the first message would be displayed when
sending the second message #2625

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):
  • Loading branch information
cike8899 authored Sep 27, 2024
1 parent 34abcf7 commit ca2de89
Show file tree
Hide file tree
Showing 15 changed files with 267 additions and 213 deletions.
6 changes: 4 additions & 2 deletions api/apps/conversation_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@
def set_conversation():
req = request.json
conv_id = req.get("conversation_id")
if conv_id:
is_new = req.get("is_new")
del req["is_new"]
if not is_new:
del req["conversation_id"]
try:
if not ConversationService.update_by_id(conv_id, req):
Expand All @@ -56,7 +58,7 @@ def set_conversation():
if not e:
return get_data_error_result(retmsg="Dialog not found")
conv = {
"id": get_uuid(),
"id": conv_id,
"dialog_id": req["dialog_id"],
"name": req.get("name", "New conversation"),
"message": [{"role": "assistant", "content": dia.prompt_config["prologue"]}]
Expand Down
2 changes: 1 addition & 1 deletion web/.umirc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export default defineConfig({
copy: ['src/conf.json'],
proxy: {
'/v1': {
target: 'http://127.0.0.1:9456/',
target: 'http://127.0.0.1:9380/',
changeOrigin: true,
ws: true,
logger: console,
Expand Down
10 changes: 8 additions & 2 deletions web/src/components/message-input/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ const MessageInput = ({
file,
}) => {
let nextConversationId: string = conversationId;
if (createConversationBeforeUploadDocument && !conversationId) {
if (createConversationBeforeUploadDocument) {
const creatingRet = await createConversationBeforeUploadDocument(
file.name,
);
Expand Down Expand Up @@ -234,8 +234,14 @@ const MessageInput = ({
>
<Button
type={'text'}
disabled={disabled}
icon={
<SvgIcon name="paper-clip" width={18} height={22}></SvgIcon>
<SvgIcon
name="paper-clip"
width={18}
height={22}
disabled={disabled}
></SvgIcon>
}
></Button>
</Upload>
Expand Down
14 changes: 7 additions & 7 deletions web/src/components/message-item/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ import { useDeleteMessage, useFeedback } from '@/hooks/chat-hooks';
import { useSetModalState } from '@/hooks/common-hooks';
import { IRemoveMessageById, useSpeechWithSse } from '@/hooks/logic-hooks';
import { IFeedbackRequestBody } from '@/interfaces/request/chat';
import { ConversationContext } from '@/pages/chat/context';
import { getMessagePureId } from '@/utils/chat';
import { hexStringToUint8Array } from '@/utils/common-util';
import { SpeechPlayer } from 'openai-speech-stream-player';
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';

export const useSendFeedback = (messageId: string) => {
const { visible, hideModal, showModal } = useSetModalState();
Expand Down Expand Up @@ -59,24 +58,21 @@ export const useSpeech = (content: string, audioBinary?: string) => {
const { read } = useSpeechWithSse();
const player = useRef<SpeechPlayer>();
const [isPlaying, setIsPlaying] = useState<boolean>(false);
const callback = useContext(ConversationContext);

const initialize = useCallback(async () => {
player.current = new SpeechPlayer({
audio: ref.current!,
onPlaying: () => {
setIsPlaying(true);
callback?.(true);
},
onPause: () => {
setIsPlaying(false);
callback?.(false);
},
onChunkEnd: () => {},
mimeType: 'audio/mpeg',
});
await player.current.init();
}, [callback]);
}, []);

const pause = useCallback(() => {
player.current?.pause();
Expand All @@ -103,7 +99,11 @@ export const useSpeech = (content: string, audioBinary?: string) => {
if (audioBinary) {
const units = hexStringToUint8Array(audioBinary);
if (units) {
player.current?.feed(units);
try {
player.current?.feed(units);
} catch (error) {
console.warn(error);
}
}
}
}, [audioBinary]);
Expand Down
1 change: 1 addition & 0 deletions web/src/constants/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export enum SharedFrom {
export enum ChatSearchParams {
DialogId = 'dialogId',
ConversationId = 'conversationId',
isNew = 'isNew',
}

export const EmptyConversationId = 'empty';
76 changes: 57 additions & 19 deletions web/src/hooks/chat-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,22 @@ import {
import i18n from '@/locales/config';
import { IClientConversation } from '@/pages/chat/interface';
import chatService from '@/services/chat-service';
import { buildMessageListWithUuid, isConversationIdExist } from '@/utils/chat';
import {
buildMessageListWithUuid,
getConversationId,
isConversationIdExist,
} from '@/utils/chat';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { message } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import { has, set } from 'lodash';
import { useCallback, useMemo, useState } from 'react';
import { useSearchParams } from 'umi';
import { history, useSearchParams } from 'umi';

//#region logic

export const useClickDialogCard = () => {
const [, setSearchParams] = useSearchParams();
const [_, setSearchParams] = useSearchParams();

const newQueryParameters: URLSearchParams = useMemo(() => {
return new URLSearchParams();
Expand All @@ -44,13 +48,33 @@ export const useClickDialogCard = () => {
return { handleClickDialog };
};

export const useClickConversationCard = () => {
const [currentQueryParameters, setSearchParams] = useSearchParams();
const newQueryParameters: URLSearchParams = useMemo(
() => new URLSearchParams(currentQueryParameters.toString()),
[currentQueryParameters],
);

const handleClickConversation = useCallback(
(conversationId: string, isNew: string) => {
newQueryParameters.set(ChatSearchParams.ConversationId, conversationId);
newQueryParameters.set(ChatSearchParams.isNew, isNew);
setSearchParams(newQueryParameters);
},
[setSearchParams, newQueryParameters],
);

return { handleClickConversation };
};

export const useGetChatSearchParams = () => {
const [currentQueryParameters] = useSearchParams();

return {
dialogId: currentQueryParameters.get(ChatSearchParams.DialogId) || '',
conversationId:
currentQueryParameters.get(ChatSearchParams.ConversationId) || '',
isNew: currentQueryParameters.get(ChatSearchParams.isNew) || '',
};
};

Expand All @@ -60,6 +84,7 @@ export const useGetChatSearchParams = () => {

export const useFetchNextDialogList = () => {
const { handleClickDialog } = useClickDialogCard();
const { dialogId } = useGetChatSearchParams();

const {
data,
Expand All @@ -70,11 +95,20 @@ export const useFetchNextDialogList = () => {
initialData: [],
gcTime: 0,
refetchOnWindowFocus: false,
queryFn: async () => {
refetchOnMount: false,
queryFn: async (...params) => {
console.log('🚀 ~ queryFn: ~ params:', params);
const { data } = await chatService.listDialog();

if (data.retcode === 0 && data.data.length > 0) {
handleClickDialog(data.data[0].id);
if (data.retcode === 0) {
const list: IDialog[] = data.data;
if (list.length > 0) {
if (list.every((x) => x.id !== dialogId)) {
handleClickDialog(data.data[0].id);
}
} else {
history.push('/chat');
}
}

return data?.data ?? [];
Expand All @@ -86,6 +120,7 @@ export const useFetchNextDialogList = () => {

export const useSetNextDialog = () => {
const queryClient = useQueryClient();

const {
data,
isPending: loading,
Expand All @@ -96,8 +131,10 @@ export const useSetNextDialog = () => {
const { data } = await chatService.setDialog(params);
if (data.retcode === 0) {
queryClient.invalidateQueries({
exact: false,
queryKey: ['fetchDialogList'],
});

queryClient.invalidateQueries({
queryKey: ['fetchDialog'],
});
Expand Down Expand Up @@ -166,6 +203,7 @@ export const useRemoveNextDialog = () => {
const { data } = await chatService.removeDialog({ dialogIds });
if (data.retcode === 0) {
queryClient.invalidateQueries({ queryKey: ['fetchDialogList'] });

message.success(i18n.t('message.deleted'));
}
return data.retcode;
Expand All @@ -181,6 +219,7 @@ export const useRemoveNextDialog = () => {

export const useFetchNextConversationList = () => {
const { dialogId } = useGetChatSearchParams();
const { handleClickConversation } = useClickConversationCard();
const {
data,
isFetching: loading,
Expand All @@ -193,7 +232,9 @@ export const useFetchNextConversationList = () => {
enabled: !!dialogId,
queryFn: async () => {
const { data } = await chatService.listConversation({ dialogId });

if (data.retcode === 0 && data.data.length > 0) {
handleClickConversation(data.data[0].id, '');
}
return data?.data;
},
});
Expand All @@ -202,7 +243,7 @@ export const useFetchNextConversationList = () => {
};

export const useFetchNextConversation = () => {
const { conversationId } = useGetChatSearchParams();
const { isNew, conversationId } = useGetChatSearchParams();
const {
data,
isFetching: loading,
Expand All @@ -214,17 +255,9 @@ export const useFetchNextConversation = () => {
gcTime: 0,
refetchOnWindowFocus: false,
queryFn: async () => {
if (isConversationIdExist(conversationId)) {
if (isNew !== 'true' && isConversationIdExist(conversationId)) {
const { data } = await chatService.getConversation({ conversationId });
// if (data.retcode === 0 && needToBeSaved) {
// yield put({
// type: 'kFModel/fetch_document_thumbnails',
// payload: {
// doc_ids: getDocumentIdsFromConversionReference(data.data),
// },
// });
// yield put({ type: 'setCurrentConversation', payload: data.data });
// }

const conversation = data?.data ?? {};

const messageList = buildMessageListWithUuid(conversation?.message);
Expand Down Expand Up @@ -265,7 +298,12 @@ export const useUpdateNextConversation = () => {
} = useMutation({
mutationKey: ['updateConversation'],
mutationFn: async (params: Record<string, any>) => {
const { data } = await chatService.setConversation(params);
const { data } = await chatService.setConversation({
...params,
conversation_id: params.conversation_id
? params.conversation_id
: getConversationId(),
});
if (data.retcode === 0) {
queryClient.invalidateQueries({ queryKey: ['fetchConversationList'] });
}
Expand Down
6 changes: 6 additions & 0 deletions web/src/hooks/logic-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ export const useSendMessageWithSse = (
const send = useCallback(
async (
body: any,
controller?: AbortController,
): Promise<{ response: Response; data: ResponseType } | undefined> => {
try {
setDone(false);
Expand All @@ -234,6 +235,7 @@ export const useSendMessageWithSse = (
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
signal: controller?.signal,
});

const res = response.clone().json();
Expand All @@ -249,6 +251,7 @@ export const useSendMessageWithSse = (
const { done, value } = x;
if (done) {
console.info('done');
setAnswer({} as IAnswer);
break;
}
try {
Expand All @@ -268,9 +271,12 @@ export const useSendMessageWithSse = (
}
console.info('done?');
setDone(true);
setAnswer({} as IAnswer);
return { data: await res, response };
} catch (e) {
setDone(true);
setAnswer({} as IAnswer);

console.warn(e);
}
},
Expand Down
1 change: 1 addition & 0 deletions web/src/interfaces/database/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export interface IConversation {
name: string;
update_date: string;
update_time: number;
is_new: true;
}

export interface Message {
Expand Down
2 changes: 1 addition & 1 deletion web/src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -580,7 +580,7 @@ The above is the content you need to summarize.`,
addGoogleRegion: 'Google Cloud Region',
GoogleRegionMessage: 'Please input Google Cloud Region',
modelProvidersWarn:
'Please add both embedding model and LLM in <b>Settings > Model</b> providers firstly.',
'Please add both embedding model and LLM in <b>Settings > Model providers</b> firstly.',
},
message: {
registered: 'Registered!',
Expand Down
Loading

0 comments on commit ca2de89

Please sign in to comment.