2026-03-21 12:52:21 +00:00
|
|
|
import { useProcessStreamingMessageUpdate } from '@/ai/hooks/useProcessStreamingMessageUpdate';
|
2026-03-05 10:39:31 +00:00
|
|
|
import { agentChatMessageComponentFamilyState } from '@/ai/states/agentChatMessageComponentFamilyState';
|
|
|
|
|
import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';
|
|
|
|
|
import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';
|
|
|
|
|
import { useCallback } from 'react';
|
|
|
|
|
import { type ExtendedUIMessage } from 'twenty-shared/ai';
|
|
|
|
|
import { isDefined } from 'twenty-shared/utils';
|
|
|
|
|
import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
|
|
|
|
|
|
2026-03-21 12:52:21 +00:00
|
|
|
export const useUpdateStreamingPartsWithDiff = () => {
|
2026-03-05 10:39:31 +00:00
|
|
|
const agentChatMessageFamilyCallbackState =
|
|
|
|
|
useAtomComponentFamilyStateCallbackState(
|
|
|
|
|
agentChatMessageComponentFamilyState,
|
|
|
|
|
);
|
|
|
|
|
|
2026-03-21 12:52:21 +00:00
|
|
|
const { processStreamingMessageUpdate } = useProcessStreamingMessageUpdate();
|
2026-03-05 10:39:31 +00:00
|
|
|
|
2026-03-21 12:52:21 +00:00
|
|
|
const updateStreamingPartsWithDiff = useCallback(
|
|
|
|
|
(incomingMessages: ExtendedUIMessage[]) => {
|
|
|
|
|
for (const incomingMessage of incomingMessages) {
|
2026-03-05 10:39:31 +00:00
|
|
|
const alreadyExistingMessage = jotaiStore.get(
|
2026-03-21 12:52:21 +00:00
|
|
|
agentChatMessageFamilyCallbackState(incomingMessage.id),
|
2026-03-05 10:39:31 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const messageContentHasChanged = !isDeeplyEqual(
|
|
|
|
|
alreadyExistingMessage,
|
2026-03-21 12:52:21 +00:00
|
|
|
incomingMessage,
|
2026-03-05 10:39:31 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const messageAlreadyExists = isDefined(alreadyExistingMessage);
|
|
|
|
|
|
|
|
|
|
const shouldProcessMessage =
|
|
|
|
|
!messageAlreadyExists || messageContentHasChanged;
|
|
|
|
|
|
|
|
|
|
if (!shouldProcessMessage) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-21 12:52:21 +00:00
|
|
|
const clonedMessage = structuredClone(incomingMessage);
|
2026-03-05 10:39:31 +00:00
|
|
|
|
|
|
|
|
jotaiStore.set(
|
2026-03-21 12:52:21 +00:00
|
|
|
agentChatMessageFamilyCallbackState(incomingMessage.id),
|
2026-03-05 10:39:31 +00:00
|
|
|
clonedMessage,
|
|
|
|
|
);
|
|
|
|
|
|
2026-03-21 12:52:21 +00:00
|
|
|
processStreamingMessageUpdate(incomingMessage);
|
2026-03-05 10:39:31 +00:00
|
|
|
}
|
|
|
|
|
},
|
2026-03-21 12:52:21 +00:00
|
|
|
[agentChatMessageFamilyCallbackState, processStreamingMessageUpdate],
|
2026-03-05 10:39:31 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return {
|
2026-03-21 12:52:21 +00:00
|
|
|
updateStreamingPartsWithDiff,
|
2026-03-05 10:39:31 +00:00
|
|
|
};
|
|
|
|
|
};
|