1
1
import { addNewMessageAtom , updateMessageAtom } from './atoms/ChatMessage.atom'
2
2
import { toChatMessage } from '@models/ChatMessage'
3
- import { events , EventName , NewMessageResponse } from '@janhq/core'
3
+ import { events , EventName , NewMessageResponse , DataService } from '@janhq/core'
4
4
import { useSetAtom } from 'jotai'
5
5
import { ReactNode , useEffect } from 'react'
6
6
import useGetBots from '@hooks/useGetBots'
7
7
import useGetUserConversations from '@hooks/useGetUserConversations'
8
+ import { updateConversationAtom } from './atoms/Conversation.atom'
9
+ import { executeSerial } from '../../electron/core/plugin-manager/execution/extension-manager'
10
+ import { debounce } from 'lodash'
11
+
12
+ let currentConversation : Conversation | undefined = undefined
13
+
14
+ const debouncedUpdateConversation = debounce (
15
+ async ( updatedConv : Conversation ) => {
16
+ await executeSerial ( DataService . UpdateConversation , updatedConv )
17
+ } ,
18
+ 1000
19
+ )
8
20
9
21
export default function EventHandler ( { children } : { children : ReactNode } ) {
10
22
const addNewMessage = useSetAtom ( addNewMessageAtom )
11
23
const updateMessage = useSetAtom ( updateMessageAtom )
24
+ const updateConversation = useSetAtom ( updateConversationAtom )
12
25
const { getBotById } = useGetBots ( )
13
26
const { getConversationById } = useGetUserConversations ( )
14
27
@@ -34,12 +47,32 @@ export default function EventHandler({ children }: { children: ReactNode }) {
34
47
messageResponse . conversationId &&
35
48
messageResponse . _id &&
36
49
messageResponse . message
37
- )
50
+ ) {
38
51
updateMessage (
39
52
messageResponse . _id ,
40
53
messageResponse . conversationId ,
41
54
messageResponse . message
42
55
)
56
+ }
57
+
58
+ if ( messageResponse . conversationId ) {
59
+ if (
60
+ ! currentConversation ||
61
+ currentConversation . _id !== messageResponse . conversationId
62
+ ) {
63
+ currentConversation = await getConversationById (
64
+ messageResponse . conversationId
65
+ )
66
+ }
67
+
68
+ const updatedConv : Conversation = {
69
+ ...currentConversation ,
70
+ lastMessage : messageResponse . message ,
71
+ }
72
+
73
+ updateConversation ( updatedConv )
74
+ debouncedUpdateConversation ( updatedConv )
75
+ }
43
76
}
44
77
45
78
useEffect ( ( ) => {
@@ -57,3 +90,6 @@ export default function EventHandler({ children }: { children: ReactNode }) {
57
90
} , [ ] )
58
91
return < > { children } </ >
59
92
}
93
+ function useDebouncedCallback ( arg0 : ( ) => void , arg1 : number ) {
94
+ throw new Error ( 'Function not implemented.' )
95
+ }
0 commit comments