Skip to content

Commit

Permalink
feat(Assistant): Show instant message sorted by position
Browse files Browse the repository at this point in the history
  • Loading branch information
JF-Cozy committed Oct 31, 2024
1 parent 3e34c40 commit a909d1b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
15 changes: 12 additions & 3 deletions src/assistant/AssistantProvider.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useMemo, useContext, useState, useCallback } from 'react'
import set from 'lodash/set'

import { useClient } from 'cozy-client'
import useRealtime from 'cozy-realtime/dist/useRealtime'
Expand All @@ -7,6 +8,12 @@ import { CHAT_EVENTS_DOCTYPE, CHAT_CONVERSATIONS_DOCTYPE } from './queries'

export const AssistantContext = React.createContext()

export const getInstantMessage = assistantState =>
Object.keys(assistantState.message)
.sort((a, b) => a - b)
.map(key => assistantState.message[key])
.join('')

export const makeConversationId = () =>
`${Date.now()}-${Math.floor(Math.random() * 90000) + 10000}`

Expand All @@ -33,7 +40,7 @@ const isMessageForThisConversation = (res, messagesId) =>
const AssistantProvider = ({ children }) => {
const client = useClient()
const [assistantState, setAssistantState] = useState({
message: '',
message: {},
status: 'idle',
messagesId: []
})
Expand Down Expand Up @@ -70,9 +77,11 @@ const AssistantProvider = ({ children }) => {
}

if (res.object === 'delta') {
const message = set(assistantState.message, res.position, res.content)

setAssistantState(v => ({
...v,
message: v.message + res.content,
message,
status: 'writing'
}))
}
Expand All @@ -83,7 +92,7 @@ const AssistantProvider = ({ children }) => {
const clearAssistant = useCallback(
() =>
setAssistantState({
message: '',
message: {},
status: 'idle',
messagesId: []
}),
Expand Down
4 changes: 2 additions & 2 deletions src/assistant/Conversations/ChatConversation.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import React, { useRef, useEffect } from 'react'
import { useQuery, isQueryLoading } from 'cozy-client'

import { buildChatConversationQueryById } from '../queries'
import { useAssistant } from '../AssistantProvider'
import { useAssistant, getInstantMessage } from '../AssistantProvider'
import ChatUserItem from './ChatUserItem'
import ChatAssistantItem from './ChatAssistantItem'
import ChatRealtimeAnswer from './ChatRealtimeAnswer'
Expand Down Expand Up @@ -67,7 +67,7 @@ const ChatConversation = ({ conversation, myself }) => {
{showLastConv && (
<ChatRealtimeAnswer
isLoading={assistantState.status === 'pending'}
label={assistantState.message}
label={getInstantMessage(assistantState)}
/>
)}
</div>
Expand Down

0 comments on commit a909d1b

Please sign in to comment.