Skip to content

The open alternative to Salesforce, designed for AI.

Replace AGENT_CHAT_UNKNOWN_THREAD_ID with null for thread state (#19552)

Félix Malfait8c4a6cd66328
diff --git a/packages/twenty-front/src/modules/ai/components/AIChatTab.tsx b/packages/twenty-front/src/modules/ai/components/AIChatTab.tsx
index 5bddc205af1..16fb6f559de 100644
--- a/packages/twenty-front/src/modules/ai/components/AIChatTab.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AIChatTab.tsx
@@ -29,7 +29,7 @@ export const AIChatTab = () => {
const threadIdCreatedFromDraft = useAtomStateValue(
threadIdCreatedFromDraftState,
);
- const draftKey = currentAIChatThread;
+ const draftKey = currentAIChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
const editorSectionKey =
draftKey !== AGENT_CHAT_NEW_THREAD_DRAFT_KEY &&
draftKey === threadIdCreatedFromDraft
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatMessagesFetchEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatMessagesFetchEffect.tsx
index 7afb462fb97..31005802633 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatMessagesFetchEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatMessagesFetchEffect.tsx
@@ -4,7 +4,6 @@ import { type AgentChatSubscriptionEvent } from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
import { AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME } from '@/ai/constants/AgentChatRefetchMessagesEventName';
-import { AGENT_CHAT_UNKNOWN_THREAD_ID } from '@/ai/constants/AgentChatUnknownThreadId';
import { agentChatFirstLiveSeqState } from '@/ai/states/agentChatFirstLiveSeqState';
import { agentChatHandleEventCallbackState } from '@/ai/states/agentChatHandleEventCallbackState';
import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
@@ -30,8 +29,8 @@ export const AgentChatMessagesFetchEffect = () => {
const isNewThread = useMemo(
() =>
- currentAIChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY ||
- currentAIChatThread === AGENT_CHAT_UNKNOWN_THREAD_ID,
+ currentAIChatThread === null ||
+ currentAIChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
[currentAIChatThread],
);
@@ -111,7 +110,7 @@ export const AgentChatMessagesFetchEffect = () => {
const { refetch: refetchAgentChatMessages } = useQueryWithCallbacks(
GetChatMessagesDocument,
{
- variables: { threadId: currentAIChatThread },
+ variables: { threadId: currentAIChatThread ?? '' },
skip: !isDefined(currentAIChatThread) || isNewThread,
onFirstLoad: handleFirstLoad,
onDataLoaded: handleDataLoaded,
@@ -120,8 +119,12 @@ export const AgentChatMessagesFetchEffect = () => {
);
const handleRefetchMessages = useCallback(() => {
+ if (isNewThread) {
+ return;
+ }
+
refetchAgentChatMessages();
- }, [refetchAgentChatMessages]);
+ }, [refetchAgentChatMessages, isNewThread]);
useListenToBrowserEvent({
eventName: AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME,
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx
index 6564f2ea0b1..6a3b8f1c7c9 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx
@@ -88,7 +88,10 @@ export const AgentChatThreadInitializationEffect = () => {
}, [storeEntry.status, hasAiSettingsPermission, setAgentChatThreadsLoading]);
useEffect(() => {
- if (hasInitializedAgentChatThreads || isValidUuid(currentAIChatThread)) {
+ if (
+ hasInitializedAgentChatThreads ||
+ (currentAIChatThread !== null && isValidUuid(currentAIChatThread))
+ ) {
return;
}
diff --git a/packages/twenty-front/src/modules/ai/constants/AgentChatUnknownThreadId.ts b/packages/twenty-front/src/modules/ai/constants/AgentChatUnknownThreadId.ts
deleted file mode 100644
index 929f87b1f10..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/AgentChatUnknownThreadId.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const AGENT_CHAT_UNKNOWN_THREAD_ID = 'unknown-thread';
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAIChatEditor.ts b/packages/twenty-front/src/modules/ai/hooks/useAIChatEditor.ts
index 6612d7dedbe..3ea2213f162 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAIChatEditor.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAIChatEditor.ts
@@ -49,7 +49,7 @@ export const useAIChatEditor = () => {
const { removeFocusItemFromFocusStackById } =
useRemoveFocusItemFromFocusStackById();
- const draftKey = currentAIChatThread;
+ const draftKey = currentAIChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
const initialDraft = agentChatDraftsByThreadId[draftKey] ?? '';
const initialContent = textToTiptapContent(initialDraft);
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAIChatThreadClick.ts b/packages/twenty-front/src/modules/ai/hooks/useAIChatThreadClick.ts
index 7640bc39b83..a654d65b79a 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAIChatThreadClick.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAIChatThreadClick.ts
@@ -38,13 +38,14 @@ export const useAIChatThreadClick = (
const handleThreadClick = (thread: AgentChatThread) => {
setThreadIdCreatedFromDraft(null);
- const previousDraftKey = currentAIChatThread;
const isSameThread = thread.id === currentAIChatThread;
- setAgentChatDraftsByThreadId((prev) => ({
- ...prev,
- [previousDraftKey]: store.get(agentChatInputState.atom),
- }));
+ if (currentAIChatThread !== null) {
+ setAgentChatDraftsByThreadId((prev) => ({
+ ...prev,
+ [currentAIChatThread]: store.get(agentChatInputState.atom),
+ }));
+ }
setCurrentAIChatThread(thread.id);
if (!isSameThread) {
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts
index 1e31b737543..13dcca6acb7 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect } from 'react';
+import { useEffect } from 'react';
import { readUIMessageStream, type UIMessageChunk } from 'ai';
import { print, type ExecutionResult } from 'graphql';
@@ -18,8 +18,6 @@ import { agentChatFirstLiveSeqState } from '@/ai/states/agentChatFirstLiveSeqSta
import { agentChatHandleEventCallbackState } from '@/ai/states/agentChatHandleEventCallbackState';
import { agentChatIsStreamingState } from '@/ai/states/agentChatIsStreamingState';
import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
-import { agentChatStreamWriterState } from '@/ai/states/agentChatStreamWriterState';
-import { agentChatSubscriptionDisposeState } from '@/ai/states/agentChatSubscriptionDisposeState';
import { agentChatUsageState } from '@/ai/states/agentChatUsageState';
import { currentAIChatThreadTitleState } from '@/ai/states/currentAIChatThreadTitleState';
import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEvent';
@@ -98,47 +96,38 @@ export const useAgentChatSubscription = (threadId: string | null) => {
const store = useStore();
const sseClient = useAtomStateValue(sseClientState);
- const cleanup = useCallback(() => {
- const writer = store.get(agentChatStreamWriterState.atom);
-
- if (isDefined(writer)) {
- writer.close().catch(() => {});
- store.set(agentChatStreamWriterState.atom, null);
- }
-
- const dispose = store.get(agentChatSubscriptionDisposeState.atom);
-
- if (isDefined(dispose)) {
- dispose();
- store.set(agentChatSubscriptionDisposeState.atom, null);
- }
-
- if (store.get(agentChatIsStreamingState.atom)) {
- store.set(agentChatIsStreamingState.atom, false);
- }
- }, [store]);
-
useEffect(() => {
- if (!isDefined(threadId)) {
- cleanup();
-
- return;
- }
-
- if (!isDefined(sseClient)) {
+ if (!isDefined(threadId) || !isDefined(sseClient)) {
return;
}
let bridge: TransformStream<UIMessageChunk> | null = null;
let throttleTimer: ReturnType<typeof setTimeout> | null = null;
let latestMessage: ExtendedUIMessage | null = null;
+ let writer: WritableStreamDefaultWriter<UIMessageChunk> | null = null;
+ let disposed = false;
store.set(agentChatFirstLiveSeqState.atom, null);
+ const closeWriter = () => {
+ if (isDefined(writer)) {
+ writer.close().catch(() => {});
+ writer = null;
+ }
+ };
+
+ const cleanupStream = () => {
+ closeWriter();
+
+ if (store.get(agentChatIsStreamingState.atom)) {
+ store.set(agentChatIsStreamingState.atom, false);
+ }
+ };
+
const flushToAtom = () => {
const messageToFlush = latestMessage;
- if (!isDefined(messageToFlush) || !isDefined(threadId)) {
+ if (!isDefined(messageToFlush)) {
return;
}
@@ -244,7 +233,9 @@ export const useAgentChatSubscription = (threadId: string | null) => {
}
flushToAtom();
- store.set(agentChatIsStreamingState.atom, false);
+ if (!disposed) {
+ store.set(agentChatIsStreamingState.atom, false);
+ }
};
const handleEvent = (event: AgentChatSubscriptionEvent) => {
@@ -261,22 +252,19 @@ export const useAgentChatSubscription = (threadId: string | null) => {
store.set(agentChatIsStreamingState.atom, true);
bridge = new TransformStream<UIMessageChunk>();
- store.set(
- agentChatStreamWriterState.atom,
- bridge.writable.getWriter(),
- );
+ writer = bridge.writable.getWriter();
const adaptedReadable = bridge.readable.pipeThrough(
createMidStreamAdapter(),
);
startReadLoop(adaptedReadable).catch(() => {
- store.set(agentChatIsStreamingState.atom, false);
+ if (!disposed) {
+ store.set(agentChatIsStreamingState.atom, false);
+ }
});
}
- const writer = store.get(agentChatStreamWriterState.atom);
-
if (isDefined(writer)) {
writer.write(event.chunk as UIMessageChunk).catch(() => {});
}
@@ -284,13 +272,7 @@ export const useAgentChatSubscription = (threadId: string | null) => {
}
case 'message-persisted': {
- const writer = store.get(agentChatStreamWriterState.atom);
-
- if (isDefined(writer)) {
- writer.close().catch(() => {});
- store.set(agentChatStreamWriterState.atom, null);
- }
-
+ closeWriter();
dispatchBrowserEvent(AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME);
break;
}
@@ -308,13 +290,7 @@ export const useAgentChatSubscription = (threadId: string | null) => {
streamError.code = event.code;
store.set(agentChatErrorState.atom, streamError);
- const writer = store.get(agentChatStreamWriterState.atom);
-
- if (isDefined(writer)) {
- writer.close().catch(() => {});
- store.set(agentChatStreamWriterState.atom, null);
- }
-
+ closeWriter();
store.set(agentChatIsStreamingState.atom, false);
break;
}
@@ -340,19 +316,21 @@ export const useAgentChatSubscription = (threadId: string | null) => {
// graphql-sse handles reconnection automatically
},
complete: () => {
- cleanup();
+ if (!disposed) {
+ cleanupStream();
+ }
},
},
);
- store.set(agentChatSubscriptionDisposeState.atom, () => dispose);
-
return () => {
+ disposed = true;
store.set(agentChatHandleEventCallbackState.atom, null);
if (isDefined(throttleTimer)) {
clearTimeout(throttleTimer);
}
- cleanup();
+ cleanupStream();
+ dispose();
};
- }, [threadId, sseClient, store, cleanup]);
+ }, [threadId, sseClient, store]);
};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadIdForSend.ts b/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadIdForSend.ts
index 23af83b7831..4e41cc703dd 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadIdForSend.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadIdForSend.ts
@@ -20,7 +20,10 @@ export const useEnsureAgentChatThreadIdForSend = (
> => {
const currentThreadId = store.get(currentAIChatThreadState.atom);
- if (currentThreadId !== AGENT_CHAT_NEW_THREAD_DRAFT_KEY) {
+ if (
+ currentThreadId !== null &&
+ currentThreadId !== AGENT_CHAT_NEW_THREAD_DRAFT_KEY
+ ) {
return currentThreadId;
}
diff --git a/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAIChat.ts b/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAIChat.ts
index 7e04751c38b..5cf182f475b 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAIChat.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAIChat.ts
@@ -35,15 +35,16 @@ export const useSwitchToNewAIChat = () => {
const switchToNewChat = () => {
setThreadIdCreatedFromDraft(null);
- const previousDraftKey = currentAIChatThread;
const newChatDraft =
store.get(agentChatDraftsByThreadIdState.atom)[
AGENT_CHAT_NEW_THREAD_DRAFT_KEY
] ?? '';
- setAgentChatDraftsByThreadId((prev) => ({
- ...prev,
- [previousDraftKey]: store.get(agentChatInputState.atom),
- }));
+ if (currentAIChatThread !== null) {
+ setAgentChatDraftsByThreadId((prev) => ({
+ ...prev,
+ [currentAIChatThread]: store.get(agentChatInputState.atom),
+ }));
+ }
store.set(hasTriggeredCreateForDraftState.atom, false);
setCurrentAIChatThread(AGENT_CHAT_NEW_THREAD_DRAFT_KEY);
setAgentChatInput(newChatDraft);
diff --git a/packages/twenty-front/src/modules/ai/states/agentChatDisplayedThreadState.ts b/packages/twenty-front/src/modules/ai/states/agentChatDisplayedThreadState.ts
index 782a3ca9390..f72f1fe4223 100644
--- a/packages/twenty-front/src/modules/ai/states/agentChatDisplayedThreadState.ts
+++ b/packages/twenty-front/src/modules/ai/states/agentChatDisplayedThreadState.ts
@@ -1,6 +1,6 @@
import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-export const agentChatDisplayedThreadState = createAtomState<string>({
+export const agentChatDisplayedThreadState = createAtomState<string | null>({
key: 'ai/agentChatDisplayedThreadState',
- defaultValue: '',
+ defaultValue: null,
});
diff --git a/packages/twenty-front/src/modules/ai/states/agentChatFetchedMessagesComponentFamilyState.ts b/packages/twenty-front/src/modules/ai/states/agentChatFetchedMessagesComponentFamilyState.ts
index 9c439698ec8..8937193b67f 100644
--- a/packages/twenty-front/src/modules/ai/states/agentChatFetchedMessagesComponentFamilyState.ts
+++ b/packages/twenty-front/src/modules/ai/states/agentChatFetchedMessagesComponentFamilyState.ts
@@ -3,7 +3,10 @@ import { createAtomComponentFamilyState } from '@/ui/utilities/state/jotai/utils
import { type ExtendedUIMessage } from 'twenty-shared/ai';
export const agentChatFetchedMessagesComponentFamilyState =
- createAtomComponentFamilyState<ExtendedUIMessage[], { threadId: string }>({
+ createAtomComponentFamilyState<
+ ExtendedUIMessage[],
+ { threadId: string | null }
+ >({
key: 'agentChatFetchedMessagesComponentFamilyState',
defaultValue: [],
componentInstanceContext: AgentChatComponentInstanceContext,
diff --git a/packages/twenty-front/src/modules/ai/states/agentChatLastDiffSyncedThreadState.ts b/packages/twenty-front/src/modules/ai/states/agentChatLastDiffSyncedThreadState.ts
index f6db87d4d6d..54d23c8ae71 100644
--- a/packages/twenty-front/src/modules/ai/states/agentChatLastDiffSyncedThreadState.ts
+++ b/packages/twenty-front/src/modules/ai/states/agentChatLastDiffSyncedThreadState.ts
@@ -1,6 +1,8 @@
import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-export const agentChatLastDiffSyncedThreadState = createAtomState<string>({
+export const agentChatLastDiffSyncedThreadState = createAtomState<
+ string | null
+>({
key: 'ai/agentChatLastDiffSyncedThreadState',
- defaultValue: '',
+ defaultValue: null,
});
diff --git a/packages/twenty-front/src/modules/ai/states/agentChatMessagesComponentFamilyState.ts b/packages/twenty-front/src/modules/ai/states/agentChatMessagesComponentFamilyState.ts
index fcf2944f4ba..160249be56c 100644
--- a/packages/twenty-front/src/modules/ai/states/agentChatMessagesComponentFamilyState.ts
+++ b/packages/twenty-front/src/modules/ai/states/agentChatMessagesComponentFamilyState.ts
@@ -3,7 +3,10 @@ import { createAtomComponentFamilyState } from '@/ui/utilities/state/jotai/utils
import { type ExtendedUIMessage } from 'twenty-shared/ai';
export const agentChatMessagesComponentFamilyState =
- createAtomComponentFamilyState<ExtendedUIMessage[], { threadId: string }>({
+ createAtomComponentFamilyState<
+ ExtendedUIMessage[],
+ { threadId: string | null }
+ >({
key: 'agentChatMessagesComponentFamilyState',
defaultValue: [],
componentInstanceContext: AgentChatComponentInstanceContext,
diff --git a/packages/twenty-front/src/modules/ai/states/agentChatQueuedMessagesComponentFamilyState.ts b/packages/twenty-front/src/modules/ai/states/agentChatQueuedMessagesComponentFamilyState.ts
index 3b338e1e9e1..bd497e56888 100644
--- a/packages/twenty-front/src/modules/ai/states/agentChatQueuedMessagesComponentFamilyState.ts
+++ b/packages/twenty-front/src/modules/ai/states/agentChatQueuedMessagesComponentFamilyState.ts
@@ -3,7 +3,10 @@ import { createAtomComponentFamilyState } from '@/ui/utilities/state/jotai/utils
import { type ExtendedUIMessage } from 'twenty-shared/ai';
export const agentChatQueuedMessagesComponentFamilyState =
- createAtomComponentFamilyState<ExtendedUIMessage[], { threadId: string }>({
+ createAtomComponentFamilyState<
+ ExtendedUIMessage[],
+ { threadId: string | null }
+ >({
key: 'agentChatQueuedMessagesComponentFamilyState',
defaultValue: [],
componentInstanceContext: AgentChatComponentInstanceContext,
diff --git a/packages/twenty-front/src/modules/ai/states/agentChatStreamWriterState.ts b/packages/twenty-front/src/modules/ai/states/agentChatStreamWriterState.ts
deleted file mode 100644
index 04023b019bb..00000000000
--- a/packages/twenty-front/src/modules/ai/states/agentChatStreamWriterState.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { type UIMessageChunk } from 'ai';
-
-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-
-export const agentChatStreamWriterState =
- createAtomState<WritableStreamDefaultWriter<UIMessageChunk> | null>({
- key: 'agentChatStreamWriterState',
- defaultValue: null,
- });
diff --git a/packages/twenty-front/src/modules/ai/states/agentChatSubscriptionDisposeState.ts b/packages/twenty-front/src/modules/ai/states/agentChatSubscriptionDisposeState.ts
deleted file mode 100644
index 659f1bec60d..00000000000
--- a/packages/twenty-front/src/modules/ai/states/agentChatSubscriptionDisposeState.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-
-export const agentChatSubscriptionDisposeState = createAtomState<
- (() => void) | null
->({
- key: 'agentChatSubscriptionDisposeState',
- defaultValue: null,
-});
diff --git a/packages/twenty-front/src/modules/ai/states/currentAIChatThreadState.ts b/packages/twenty-front/src/modules/ai/states/currentAIChatThreadState.ts
index 5b326f5ca21..20b27940c70 100644
--- a/packages/twenty-front/src/modules/ai/states/currentAIChatThreadState.ts
+++ b/packages/twenty-front/src/modules/ai/states/currentAIChatThreadState.ts
@@ -1,7 +1,6 @@
-import { AGENT_CHAT_UNKNOWN_THREAD_ID } from '@/ai/constants/AgentChatUnknownThreadId';
import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-export const currentAIChatThreadState = createAtomState<string>({
+export const currentAIChatThreadState = createAtomState<string | null>({
key: 'ai/currentAIChatThreadState',
- defaultValue: AGENT_CHAT_UNKNOWN_THREAD_ID,
+ defaultValue: null,
});