Skip to content

Commit

Permalink
feat(Assistant): Ignore instant messages if not for the actual conver…
Browse files Browse the repository at this point in the history
…sation
  • Loading branch information
JF-Cozy committed Oct 22, 2024
1 parent 4cad078 commit d32a2f0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
34 changes: 32 additions & 2 deletions src/assistant/AssistantProvider.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import React, { useMemo, useContext, useState, useCallback } from 'react'

import { useClient } from 'cozy-client'
import useRealtime from 'cozy-ui/transpiled/react/hooks/useRealtime'
import useRealtime from 'cozy-realtime/dist/useRealtime'

import { CHAT_EVENTS_DOCTYPE, CHAT_CONVERSATIONS_DOCTYPE } from './queries'

export const AssistantContext = React.createContext()

Expand All @@ -14,17 +16,44 @@ export const useAssistant = () => {
return context
}

const pushMessagesIdInState = (res, setState) => {
const messagesId = res.messages.map(message => message.id)
setState(v => ({
...v,
messagesId
}))
}

const isMessageForThisConversation = (res, messagesId) =>
messagesId.includes(res._id)

const AssistantProvider = ({ children }) => {
const client = useClient()
const [assistantState, setAssistantState] = useState({
message: '',
status: 'idle',
messagesId: [],
conversationId: undefined
})

useRealtime(client, {
'io.cozy.ai.chat.events': {
[CHAT_CONVERSATIONS_DOCTYPE]: {
created: res => {
pushMessagesIdInState(res, setAssistantState)
},
updated: res => {
pushMessagesIdInState(res, setAssistantState)
}
}
})

useRealtime(client, {
[CHAT_EVENTS_DOCTYPE]: {
created: res => {
if (!isMessageForThisConversation(res, assistantState.messagesId)) {
return
}

if (res.object === 'done') {
if (assistantState.status !== 'idle') {
// to be sure the last response is inside io.cozy.ai.chat.conversations
Expand Down Expand Up @@ -86,6 +115,7 @@ const AssistantProvider = ({ children }) => {
setAssistantState({
message: '',
status: 'idle',
messagesId: [],
conversationId: undefined
}),
[]
Expand Down
3 changes: 2 additions & 1 deletion src/assistant/queries.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Q, fetchPolicies } from 'cozy-client'

const CONTACTS_DOCTYPE = 'io.cozy.contacts'
const CHAT_CONVERSATIONS_DOCTYPE = 'io.cozy.ai.chat.conversations'
export const CHAT_CONVERSATIONS_DOCTYPE = 'io.cozy.ai.chat.conversations'
export const CHAT_EVENTS_DOCTYPE = 'io.cozy.ai.chat.events'

const defaultFetchPolicy = fetchPolicies.olderThan(86_400_000) // 24 hours

Expand Down

0 comments on commit d32a2f0

Please sign in to comment.