Skip to content

The open alternative to Salesforce, designed for AI.

AI chat: a new chat has its thread id from the start (#27617)

Félix Malfait6dcd85e3fe22
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index dc2b940813a..0dafd60ee29 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -8155,11 +8155,6 @@ export type AssignRoleToAgentMutationVariables = Exact<{
export type AssignRoleToAgentMutation = { __typename?: 'Mutation', assignRoleToAgent: boolean };
-export type CreateChatThreadMutationVariables = Exact<{ [key: string]: never; }>;
-
-
-export type CreateChatThreadMutation = { __typename?: 'Mutation', createChatThread: { __typename?: 'AgentChatThread', id: string, title?: string | null, createdAt: string, updatedAt: string } };
-
export type CreateOneAgentMutationVariables = Exact<{
input: CreateAgentInput;
}>;
@@ -10811,7 +10806,6 @@ export const FindManyTimelineActivityTypesDocument = {"kind":"Document","definit
export const ActivateSkillDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ActivateSkill"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"activateSkill"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SkillFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SkillFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Skill"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<ActivateSkillMutation, ActivateSkillMutationVariables>;
export const AssignAgentChatThreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AssignAgentChatThread"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"assigneeWorkspaceMemberId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"assignAgentChatThread"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}},{"kind":"Argument","name":{"kind":"Name","value":"assigneeWorkspaceMemberId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"assigneeWorkspaceMemberId"}}}]}]}}]} as unknown as DocumentNode<AssignAgentChatThreadMutation, AssignAgentChatThreadMutationVariables>;
export const AssignRoleToAgentDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AssignRoleToAgent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"roleId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"assignRoleToAgent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"agentId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}}},{"kind":"Argument","name":{"kind":"Name","value":"roleId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"roleId"}}}]}]}}]} as unknown as DocumentNode<AssignRoleToAgentMutation, AssignRoleToAgentMutationVariables>;
-export const CreateChatThreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateChatThread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createChatThread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<CreateChatThreadMutation, CreateChatThreadMutationVariables>;
export const CreateOneAgentDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateOneAgent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateAgentInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createOneAgent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Agent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"prompt"}},{"kind":"Field","name":{"kind":"Name","value":"modelId"}},{"kind":"Field","name":{"kind":"Name","value":"responseFormat"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"modelConfiguration"}},{"kind":"Field","name":{"kind":"Name","value":"triggers"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<CreateOneAgentMutation, CreateOneAgentMutationVariables>;
export const CreateSkillDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateSkill"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateSkillInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createSkill"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SkillFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SkillFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Skill"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<CreateSkillMutation, CreateSkillMutationVariables>;
export const DeactivateSkillDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeactivateSkill"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deactivateSkill"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SkillFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SkillFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Skill"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<DeactivateSkillMutation, DeactivateSkillMutationVariables>;
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatMessagesFetchEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatMessagesFetchEffect.tsx
index 7bb097ca9be..aa9db0cf73f 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatMessagesFetchEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatMessagesFetchEffect.tsx
@@ -1,11 +1,11 @@
import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
import { useStore } from 'jotai';
-import { useCallback, useMemo } from 'react';
+import { useCallback } from 'react';
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_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
+import { useIsOnNewAiChatSlot } from '@/ai/hooks/useIsOnNewAiChatSlot';
import { agentChatErrorFamilyState } from '@/ai/states/agentChatErrorFamilyState';
import { agentChatFetchedMessagesFamilyState } from '@/ai/states/agentChatFetchedMessagesFamilyState';
import { agentChatFirstLiveSeqFamilyState } from '@/ai/states/agentChatFirstLiveSeqFamilyState';
@@ -31,12 +31,7 @@ export const AgentChatMessagesFetchEffect = () => {
const store = useStore();
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
- const isNewThread = useMemo(
- () =>
- currentAiChatThread === null ||
- currentAiChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- [currentAiChatThread],
- );
+ const isNewThread = useIsOnNewAiChatSlot() || currentAiChatThread === null;
const setAgentChatMessagesLoading = useSetAtomState(
agentChatMessagesLoadingState,
@@ -152,7 +147,7 @@ export const AgentChatMessagesFetchEffect = () => {
{
variables: { threadId: currentAiChatThread ?? '' },
fetchPolicy: 'network-only',
- skip: !isDefined(currentAiChatThread) || isNewThread,
+ skip: isNewThread,
onFirstLoad: handleFirstLoad,
onDataLoaded: handleDataLoaded,
onLoadingChange: handleLoadingChange,
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatStreamSubscriptionEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatStreamSubscriptionEffect.tsx
index 739e091eaee..f2bb6f030c8 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatStreamSubscriptionEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatStreamSubscriptionEffect.tsx
@@ -1,11 +1,8 @@
import { useEffect } from 'react';
-import { isValidUuid } from 'twenty-shared/utils';
-import { AGENT_CHAT_ENSURE_THREAD_FOR_DRAFT_EVENT_NAME } from '@/ai/constants/AgentChatEnsureThreadForDraftEventName';
import { useAgentChat } from '@/ai/hooks/useAgentChat';
import { useAgentChatSubscription } from '@/ai/hooks/useAgentChatSubscription';
-import { useEnsureAgentChatThreadExistsForDraft } from '@/ai/hooks/useEnsureAgentChatThreadExistsForDraft';
-import { useEnsureAgentChatThreadIdForSend } from '@/ai/hooks/useEnsureAgentChatThreadIdForSend';
+import { useIsOnNewAiChatSlot } from '@/ai/hooks/useIsOnNewAiChatSlot';
import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
import { agentChatFetchedMessagesFamilyState } from '@/ai/states/agentChatFetchedMessagesFamilyState';
import { agentChatIsAwaitingFirstChunkFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkFamilyState';
@@ -13,7 +10,6 @@ import { agentChatIsAwaitingPersistedRefetchFamilyState } from '@/ai/states/agen
import { agentChatIsStreamingFamilyState } from '@/ai/states/agentChatIsStreamingFamilyState';
import { agentChatMessagesFamilyState } from '@/ai/states/agentChatMessagesFamilyState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
-import { useListenToBrowserEvent } from '@/browser-event/hooks/useListenToBrowserEvent';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
import { useSetAtomFamilyState } from '@/ui/utilities/state/jotai/hooks/useSetAtomFamilyState';
@@ -21,24 +17,11 @@ import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAto
export const AgentChatStreamSubscriptionEffect = () => {
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
+ const isOnNewAiChatSlot = useIsOnNewAiChatSlot();
- const { ensureThreadExistsForDraft } =
- useEnsureAgentChatThreadExistsForDraft();
- const { ensureThreadIdForSend } = useEnsureAgentChatThreadIdForSend();
+ useAgentChat();
- useListenToBrowserEvent({
- eventName: AGENT_CHAT_ENSURE_THREAD_FOR_DRAFT_EVENT_NAME,
- onBrowserEvent: ensureThreadExistsForDraft,
- });
-
- useAgentChat(ensureThreadIdForSend);
-
- const subscriptionThreadId =
- currentAiChatThread !== null && isValidUuid(currentAiChatThread)
- ? currentAiChatThread
- : null;
-
- useAgentChatSubscription(subscriptionThreadId);
+ useAgentChatSubscription(isOnNewAiChatSlot ? null : currentAiChatThread);
const agentChatFetchedMessages = useAtomFamilyStateValue(
agentChatFetchedMessagesFamilyState,
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx
index b778a0dc35b..a17b6629a51 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx
@@ -1,17 +1,16 @@
import { useStore } from 'jotai';
import { useEffect } from 'react';
-import { isDefined, isValidUuid } from 'twenty-shared/utils';
+import { isDefined } from 'twenty-shared/utils';
import { getAgentChatUsageFromThread } from '@/ai/utils/getAgentChatUsageFromThread';
import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { agentChatUsageFamilyState } from '@/ai/states/agentChatUsageFamilyState';
import { agentChatThreadsLoadingSelector } from '@/ai/states/selectors/agentChatThreadsLoadingSelector';
import { agentChatThreadRecordFamilySelector } from '@/ai/states/selectors/agentChatThreadRecordFamilySelector';
import { agentChatVisibleThreadsSelector } from '@/ai/states/selectors/agentChatVisibleThreadsSelector';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { hasInitializedAgentChatThreadsState } from '@/ai/states/hasInitializedAgentChatThreadsState';
-import { hasTriggeredCreateForDraftState } from '@/ai/states/hasTriggeredCreateForDraftState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { sortChatThreadsByLastActivityDesc } from '@/ai/utils/sortChatThreadsByLastActivityDesc';
import { metadataStoreStatusFamilySelector } from '@/metadata-store/states/metadataStoreStatusFamilySelector';
import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
@@ -84,7 +83,7 @@ export const AgentChatThreadInitializationEffect = () => {
return;
}
- if (isDefined(currentAiChatThread) && isValidUuid(currentAiChatThread)) {
+ if (isDefined(currentAiChatThread)) {
const selectedThread = store.get(
agentChatThreadRecordFamilySelector.selectorFamily(currentAiChatThread),
);
@@ -114,8 +113,7 @@ export const AgentChatThreadInitializationEffect = () => {
getAgentChatUsageFromThread(firstThread),
);
} else {
- store.set(hasTriggeredCreateForDraftState.atom, false);
- setCurrentAiChatThread(AGENT_CHAT_NEW_THREAD_DRAFT_KEY);
+ setCurrentAiChatThread(store.get(newAiChatThreadIdState.atom));
}
}, [
agentChatVisibleThreads,
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatTab.tsx b/packages/twenty-front/src/modules/ai/components/AiChatTab.tsx
index 322190e539b..8350b892fa0 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatTab.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatTab.tsx
@@ -10,8 +10,6 @@ import { AgentChatThreadMarkAsReadEffect } from '@/ai/components/AgentChatThread
import { AgentChatStreamingPartsDiffSyncEffect } from '@/ai/components/AgentChatStreamingPartsDiffSyncEffect';
import { AiChatEditorSection } from '@/ai/components/AiChatEditorSection';
import { useAiChatFileUpload } from '@/ai/hooks/useAiChatFileUpload';
-import { useIsOnNewAiChatSlot } from '@/ai/hooks/useIsOnNewAiChatSlot';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
@@ -32,10 +30,6 @@ export const AiChatTab = () => {
const isWorkspaceSetupChat = useIsWorkspaceSetupChat();
const [isDraggingFile, setIsDraggingFile] = useState(false);
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
- const isOnNewAiChatSlot = useIsOnNewAiChatSlot();
- const editorSectionKey = isOnNewAiChatSlot
- ? AGENT_CHAT_NEW_THREAD_DRAFT_KEY
- : (currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY);
const { uploadFiles } = useAiChatFileUpload();
@@ -77,7 +71,7 @@ export const AiChatTab = () => {
<>
<AiChatTabMessageList />
<AiChatQueuedMessages />
- <AiChatEditorSection key={editorSectionKey} />
+ <AiChatEditorSection key={currentAiChatThread} />
</>
)}
</StyledContainer>
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.test.tsx
index ba193d84fe3..bdddb2ca8d1 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.test.tsx
@@ -1,6 +1,6 @@
import { i18n } from '@lingui/core';
import { I18nProvider } from '@lingui/react';
-import { act, render, screen } from '@testing-library/react';
+import { render, screen } from '@testing-library/react';
import { Document } from '@tiptap/extension-document';
import { Paragraph } from '@tiptap/extension-paragraph';
import { Text } from '@tiptap/extension-text';
@@ -9,14 +9,12 @@ import { type ReactNode } from 'react';
import { AiChatEditorSection } from '@/ai/components/AiChatEditorSection';
import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
-import { threadIdCreatedFromDraftState } from '@/ai/states/threadIdCreatedFromDraftState';
-import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
import { getTestEnrichedObjectMetadataItemsMock } from '~/testing/utils/getTestEnrichedObjectMetadataItemsMock';
-const CREATED_THREAD_ID = '20202020-7c1e-4a0f-9d2b-3f4e5a6b7c8d';
+const NEW_CHAT_THREAD_ID = '20202020-7c1e-4a0f-9d2b-3f4e5a6b7c8d';
const useAiChatEditor = jest.fn();
jest.mock('@/ai/hooks/useAiChatEditor', () => ({
@@ -34,15 +32,13 @@ jest.mock('@/ai/components/AiChatPendingAskGate', () => ({
const objectMetadataItems = getTestEnrichedObjectMetadataItemsMock();
-const renderEditorSectionOnNewChat = () => {
+const renderEditorSection = (currentAiChatThread: string) => {
const MetadataAndApolloWrapper = getJestMetadataAndApolloMocksWrapper({
objectMetadataItems,
onInitializeJotaiStore: (store) => {
- store.set(currentAiChatThreadState.atom, AGENT_CHAT_NEW_THREAD_DRAFT_KEY);
- store.set(
- agentChatDisplayedThreadState.atom,
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- );
+ store.set(newAiChatThreadIdState.atom, NEW_CHAT_THREAD_ID);
+ store.set(currentAiChatThreadState.atom, currentAiChatThread);
+ store.set(agentChatDisplayedThreadState.atom, currentAiChatThread);
},
});
@@ -67,16 +63,17 @@ describe('AiChatEditorSection', () => {
editor.destroy();
});
- it('keeps the composer mounted when typing the first message creates the thread', () => {
- renderEditorSectionOnNewChat();
- const sendButton = screen.getByRole('button', { name: /send/i });
+ it('shows the composer on a new chat, which has no thread to load permissions for', () => {
+ renderEditorSection(NEW_CHAT_THREAD_ID);
- act(() => {
- jotaiStore.set(threadIdCreatedFromDraftState.atom, CREATED_THREAD_ID);
- jotaiStore.set(currentAiChatThreadState.atom, CREATED_THREAD_ID);
- jotaiStore.set(agentChatDisplayedThreadState.atom, CREATED_THREAD_ID);
- });
+ expect(screen.getByRole('button', { name: /send/i })).toBeInTheDocument();
+ });
+
+ it('waits for the permissions of an existing chat', () => {
+ renderEditorSection('20202020-7c1e-4a0f-9d2b-3f4e5a6b7c8e');
- expect(sendButton).toBeInTheDocument();
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Loading conversation…',
+ );
});
});
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmptyState.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmptyState.test.tsx
index 0197413d470..25d5cde7bb2 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmptyState.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmptyState.test.tsx
@@ -1,4 +1,3 @@
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { render } from '@testing-library/react';
import { Provider as JotaiProvider } from 'jotai';
import { type ReactNode } from 'react';
@@ -8,6 +7,7 @@ import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThr
import { agentChatIsAwaitingFirstChunkFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkFamilyState';
import { agentChatIsStreamingFamilyState } from '@/ai/states/agentChatIsStreamingFamilyState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import {
jotaiStore,
resetJotaiStore,
@@ -17,7 +17,7 @@ jest.mock('@/ai/components/suggested-prompts/AiChatSuggestedPrompts', () => ({
AiChatSuggestedPrompts: () => <div data-testid="suggested-prompts" />,
}));
-const THREAD_ID = AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
+const THREAD_ID = '20202020-0000-4000-8000-0000000000aa';
const Wrapper = ({ children }: { children: ReactNode }) => (
<JotaiProvider store={jotaiStore}>{children}</JotaiProvider>
@@ -27,6 +27,7 @@ describe('AiChatEmptyState', () => {
beforeEach(() => {
jest.clearAllMocks();
resetJotaiStore();
+ jotaiStore.set(newAiChatThreadIdState.atom, THREAD_ID);
jotaiStore.set(currentAiChatThreadState.atom, THREAD_ID);
jotaiStore.set(agentChatDisplayedThreadState.atom, THREAD_ID);
});
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatParticipantMentionBar.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatParticipantMentionBar.test.tsx
index 8f26ccebefb..371505bf495 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatParticipantMentionBar.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatParticipantMentionBar.test.tsx
@@ -11,10 +11,7 @@ import { CoreObjectNameSingular } from 'twenty-shared/types';
import { serializeAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializeAdvancedTextEditorDocument';
import { AiChatParticipantMentionBar } from '@/ai/components/AiChatParticipantMentionBar';
-import {
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- agentChatDraftsByThreadIdState,
-} from '@/ai/states/agentChatDraftsByThreadIdState';
+import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { MentionTag } from '@/mention/extensions/MentionTag';
import { getMentionTagContent } from '@/mention/utils/getMentionTagContent';
@@ -27,11 +24,12 @@ jest.mock('@tiptap/react', () => ({
}));
const GRACE_ID = '20202020-0000-4000-8000-000000000021';
+const THREAD_ID = '20202020-0000-4000-8000-0000000000aa';
const renderBar = (editor: Editor) => {
const Wrapper = getJestMetadataAndApolloMocksWrapper({
onInitializeJotaiStore: (store) => {
- store.set(currentAiChatThreadState.atom, AGENT_CHAT_NEW_THREAD_DRAFT_KEY);
+ store.set(currentAiChatThreadState.atom, THREAD_ID);
},
});
@@ -52,8 +50,7 @@ describe('AiChatParticipantMentionBar', () => {
extensions: [Document, Paragraph, Text, MentionTag],
onUpdate: ({ editor: updatedEditor }) => {
jotaiStore.set(agentChatDraftsByThreadIdState.atom, {
- [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]:
- serializeAdvancedTextEditorDocument(updatedEditor),
+ [THREAD_ID]: serializeAdvancedTextEditorDocument(updatedEditor),
});
},
});
diff --git a/packages/twenty-front/src/modules/ai/components/suggested-prompts/AiChatSuggestedPrompts.tsx b/packages/twenty-front/src/modules/ai/components/suggested-prompts/AiChatSuggestedPrompts.tsx
index 473b4913774..e4526b4c554 100644
--- a/packages/twenty-front/src/modules/ai/components/suggested-prompts/AiChatSuggestedPrompts.tsx
+++ b/packages/twenty-front/src/modules/ai/components/suggested-prompts/AiChatSuggestedPrompts.tsx
@@ -10,10 +10,7 @@ import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-
import { getAiChatSuggestedPrompts } from '@/ai/components/suggested-prompts/getAiChatSuggestedPrompts';
import { useAiChatSuggestedPromptsContext } from '@/ai/hooks/useAiChatSuggestedPromptsContext';
import { useStageAiChatPreprompt } from '@/ai/hooks/useStageAiChatPreprompt';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
-import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { type SuggestedPrompt } from '@/ai/types/SuggestedPrompt';
-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
const StyledContainer = styled.div<{ isCentered: boolean }>`
align-items: ${({ isCentered }) => (isCentered ? 'center' : 'stretch')};
@@ -63,7 +60,6 @@ export const AiChatSuggestedPrompts = ({
}: AiChatSuggestedPromptsProps) => {
const { t: resolveMessage } = useLingui();
const { stageAiChatPreprompt } = useStageAiChatPreprompt();
- const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
const aiChatSuggestedPromptsContext = useAiChatSuggestedPromptsContext();
const suggestedPrompts = getAiChatSuggestedPrompts(
@@ -76,7 +72,6 @@ export const AiChatSuggestedPrompts = ({
resolveMessage(pickRandom(suggestedPrompt.prompts)),
),
mode: suggestedPrompt.mode ?? 'PREFILL',
- draftKey: currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
});
};
diff --git a/packages/twenty-front/src/modules/ai/constants/AgentChatEnsureThreadForDraftEventName.ts b/packages/twenty-front/src/modules/ai/constants/AgentChatEnsureThreadForDraftEventName.ts
deleted file mode 100644
index 18a3c15572f..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/AgentChatEnsureThreadForDraftEventName.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export const AGENT_CHAT_ENSURE_THREAD_FOR_DRAFT_EVENT_NAME =
- 'agent-chat-ensure-thread-for-draft' as const;
diff --git a/packages/twenty-front/src/modules/ai/graphql/mutations/createChatThread.ts b/packages/twenty-front/src/modules/ai/graphql/mutations/createChatThread.ts
deleted file mode 100644
index a89162a2b39..00000000000
--- a/packages/twenty-front/src/modules/ai/graphql/mutations/createChatThread.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { gql } from '@apollo/client';
-
-export const CREATE_CHAT_THREAD = gql`
- mutation CreateChatThread {
- createChatThread {
- id
-
- title
- createdAt
- updatedAt
- }
- }
-`;
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChat.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChat.test.tsx
index 8f927b0bde8..91a8057ee27 100644
--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChat.test.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChat.test.tsx
@@ -7,10 +7,9 @@ import { MemoryRouter } from 'react-router-dom';
import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';
import { useAgentChat } from '@/ai/hooks/useAgentChat';
-import {
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- agentChatDraftsByThreadIdState,
-} from '@/ai/states/agentChatDraftsByThreadIdState';
+import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';
+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { aiModelsState } from '@/client-config/states/aiModelsState';
import { serializeMentionTagAsAdvancedTextEditorDocument } from '@/mention/utils/serializeMentionTagAsAdvancedTextEditorDocument';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
@@ -70,11 +69,11 @@ const renderAgentChat = ({
persistedDrafts: Record<string, string>;
sendChatMessageOutcomes: ('sent' | 'failed')[];
}) => {
- const ensureThreadIdForSend = jest.fn(() => Promise.resolve(THREAD_ID));
const MetadataAndApolloMocksWrapper = getJestMetadataAndApolloMocksWrapper({
apolloMocks: sendChatMessageOutcomes.map(buildSendChatMessageMock),
onInitializeJotaiStore: (store) => {
store.set(aiModelsState.atom, [{ modelId: 'model', label: 'Model' }]);
+ store.set(newAiChatThreadIdState.atom, THREAD_ID);
},
});
@@ -92,13 +91,19 @@ const renderAgentChat = ({
() => {
useAtomStateValue(agentChatDraftsByThreadIdState);
- return useAgentChat(ensureThreadIdForSend);
+ return {
+ ...useAgentChat(),
+ currentAiChatThread: useAtomStateValue(currentAiChatThreadState),
+ newAiChatThreadId: useAtomStateValue(newAiChatThreadIdState),
+ };
},
{ wrapper: Wrapper },
).result;
};
-const send = async (result: { current: ReturnType<typeof useAgentChat> }) => {
+const send = async (result: {
+ current: Pick<ReturnType<typeof useAgentChat>, 'handleSendMessage'>;
+}) => {
await act(async () => {
await result.current.handleSendMessage();
});
@@ -112,7 +117,7 @@ describe('useAgentChat', () => {
it('files a chat started from a record under it once its message is sent', async () => {
const result = renderAgentChat({
persistedDrafts: {
- [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]: DRAFT_STARTED_FROM_COMPANY,
+ [THREAD_ID]: DRAFT_STARTED_FROM_COMPANY,
},
sendChatMessageOutcomes: ['sent'],
});
@@ -124,15 +129,32 @@ describe('useAgentChat', () => {
threadId: THREAD_ID,
...COMPANY_TARGET,
});
- expect(readPersistedDrafts()).toEqual({
- [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]: '',
+ expect(readPersistedDrafts()).toEqual({ [THREAD_ID]: '' });
+ });
+
+ it('keeps the new chat until its first message is sent', async () => {
+ const result = renderAgentChat({
+ persistedDrafts: {
+ [THREAD_ID]: serializePlainTextAsAdvancedTextEditorDocument('Hello'),
+ },
+ sendChatMessageOutcomes: ['failed', 'sent'],
});
+
+ await send(result);
+
+ expect(result.current.currentAiChatThread).toBe(THREAD_ID);
+ expect(result.current.newAiChatThreadId).toBe(THREAD_ID);
+
+ await send(result);
+
+ expect(result.current.currentAiChatThread).toBe(THREAD_ID);
+ expect(result.current.newAiChatThreadId).not.toBe(THREAD_ID);
});
it('files the chat when the retry of a failed first send goes through', async () => {
const result = renderAgentChat({
persistedDrafts: {
- [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]: DRAFT_STARTED_FROM_COMPANY,
+ [THREAD_ID]: DRAFT_STARTED_FROM_COMPANY,
},
sendChatMessageOutcomes: ['failed', 'sent'],
});
@@ -155,7 +177,7 @@ describe('useAgentChat', () => {
it('does not file a chat under a record it only mentions', async () => {
const result = renderAgentChat({
persistedDrafts: {
- [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]: DRAFT_MENTIONING_COMPANY,
+ [THREAD_ID]: DRAFT_MENTIONING_COMPANY,
},
sendChatMessageOutcomes: ['sent'],
});
@@ -168,8 +190,7 @@ describe('useAgentChat', () => {
it('does not file a chat that mentions no record', async () => {
const result = renderAgentChat({
persistedDrafts: {
- [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]:
- serializePlainTextAsAdvancedTextEditorDocument('Hello'),
+ [THREAD_ID]: serializePlainTextAsAdvancedTextEditorDocument('Hello'),
},
sendChatMessageOutcomes: ['sent'],
});
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useIsAiChatComposerCentered.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useIsAiChatComposerCentered.test.tsx
index b56944d2270..21ffddcb33f 100644
--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useIsAiChatComposerCentered.test.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useIsAiChatComposerCentered.test.tsx
@@ -1,4 +1,3 @@
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { act, renderHook } from '@testing-library/react';
import { Provider as JotaiProvider } from 'jotai';
import { type ReactNode } from 'react';
@@ -10,7 +9,7 @@ import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThr
import { agentChatMessagesFamilyState } from '@/ai/states/agentChatMessagesFamilyState';
import { agentChatMessagesLoadingState } from '@/ai/states/agentChatMessagesLoadingState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
-import { threadIdCreatedFromDraftState } from '@/ai/states/threadIdCreatedFromDraftState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';
import { type AiChatSurface } from '@/ai/types/AiChatSurface';
import {
@@ -18,7 +17,7 @@ import {
resetJotaiStore,
} from '@/ui/utilities/state/jotai/jotaiStore';
-const THREAD_ID = AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
+const THREAD_ID = '20202020-0000-4000-8000-0000000000aa';
const renderForSurface = ({
surface = AI_CHAT_SURFACE.PAGE,
@@ -39,6 +38,7 @@ const renderForSurface = ({
describe('useIsAiChatComposerCentered', () => {
beforeEach(() => {
resetJotaiStore();
+ jotaiStore.set(newAiChatThreadIdState.atom, THREAD_ID);
jotaiStore.set(currentAiChatThreadState.atom, THREAD_ID);
jotaiStore.set(agentChatDisplayedThreadState.atom, THREAD_ID);
});
@@ -68,17 +68,14 @@ describe('useIsAiChatComposerCentered', () => {
expect(result.current).toBe(false);
});
- it('keeps the composer centered on the thread its draft created until the first message', () => {
- jotaiStore.set(currentAiChatThreadState.atom, 'draft-thread');
- jotaiStore.set(agentChatDisplayedThreadState.atom, 'draft-thread');
- jotaiStore.set(threadIdCreatedFromDraftState.atom, 'draft-thread');
+ it('keeps the composer centered on the new chat until its first message', () => {
const { result } = renderForSurface();
expect(result.current).toBe(true);
act(() =>
jotaiStore.set(
- agentChatMessagesFamilyState.atomFamily({ threadId: 'draft-thread' }),
+ agentChatMessagesFamilyState.atomFamily({ threadId: THREAD_ID }),
[{ id: 'message-1', role: 'user', parts: [] }],
),
);
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useLeaveRemovedAiChatThread.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useLeaveRemovedAiChatThread.test.tsx
index 8903178652f..f567f4fe325 100644
--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useLeaveRemovedAiChatThread.test.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useLeaveRemovedAiChatThread.test.tsx
@@ -3,12 +3,10 @@ import { Provider as JotaiProvider } from 'jotai';
import { type ReactNode } from 'react';
import { useLeaveRemovedAiChatThread } from '@/ai/hooks/useLeaveRemovedAiChatThread';
-import {
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- agentChatDraftsByThreadIdState,
-} from '@/ai/states/agentChatDraftsByThreadIdState';
+import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';
import { agentChatInputIsEmptySelector } from '@/ai/states/selectors/agentChatInputIsEmptySelector';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { setAgentChatThreadList } from '@/ai/testing/setAgentChatThreadList';
import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';
import {
@@ -30,6 +28,7 @@ jest.mock('@/ai/hooks/useRefreshAgentChatThreads', () => ({
const REMOVED_CHAT_ID = '20202020-0000-4000-8000-0000000000aa';
const OLDER_CHAT_ID = '20202020-0000-4000-8000-0000000000bb';
const RECENT_CHAT_ID = '20202020-0000-4000-8000-0000000000cc';
+const NEW_CHAT_ID = '20202020-0000-4000-8000-0000000000dd';
const buildChat = (id: string, updatedAt: string): AgentChatThreadRecord => ({
__typename: 'AgentChatThread',
@@ -57,6 +56,7 @@ describe('useLeaveRemovedAiChatThread', () => {
jest.clearAllMocks();
resetJotaiStore();
loadAgentChatThread.mockResolvedValue(null);
+ jotaiStore.set(newAiChatThreadIdState.atom, NEW_CHAT_ID);
jotaiStore.set(currentAiChatThreadState.atom, REMOVED_CHAT_ID);
});
@@ -81,9 +81,17 @@ describe('useLeaveRemovedAiChatThread', () => {
await leave();
- expect(jotaiStore.get(currentAiChatThreadState.atom)).toBe(
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- );
+ expect(jotaiStore.get(currentAiChatThreadState.atom)).toBe(NEW_CHAT_ID);
+ });
+
+ it('stays on the new chat, which has no thread until its first message', async () => {
+ setAgentChatThreadList(jotaiStore, []);
+ jotaiStore.set(currentAiChatThreadState.atom, NEW_CHAT_ID);
+
+ await leave();
+
+ expect(jotaiStore.get(currentAiChatThreadState.atom)).toBe(NEW_CHAT_ID);
+ expect(loadAgentChatThread).not.toHaveBeenCalled();
});
it('stays on a chat that is still listed', async () => {
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useProjectAiChatThreadToUrl.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useProjectAiChatThreadToUrl.test.tsx
index bdfbad9452c..aac01584c31 100644
--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useProjectAiChatThreadToUrl.test.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useProjectAiChatThreadToUrl.test.tsx
@@ -1,8 +1,9 @@
import { act, renderHook } from '@testing-library/react';
+import { getDefaultStore } from 'jotai';
import { AppPath } from 'twenty-shared/types';
import { useProjectAiChatThreadToUrl } from '@/ai/hooks/useProjectAiChatThreadToUrl';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
const navigateAppMock = jest.fn();
@@ -35,13 +36,15 @@ describe('useProjectAiChatThreadToUrl', () => {
);
});
- it('should clear the url param for a draft thread', () => {
+ it('should clear the url param for the new chat', () => {
window.history.pushState(null, '', `/chat/${THREAD_A}`);
const { result } = renderHook(() => useProjectAiChatThreadToUrl());
act(() => {
- result.current.projectAiChatThreadToUrl(AGENT_CHAT_NEW_THREAD_DRAFT_KEY);
+ result.current.projectAiChatThreadToUrl(
+ getDefaultStore().get(newAiChatThreadIdState.atom),
+ );
});
expect(navigateAppMock).toHaveBeenCalledWith(
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useSelectAiChatThread.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useSelectAiChatThread.test.tsx
index f91b3dafeaf..ea99779112a 100644
--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useSelectAiChatThread.test.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useSelectAiChatThread.test.tsx
@@ -6,7 +6,6 @@ import { Provider as JotaiProvider } from 'jotai';
import { type ReactNode } from 'react';
import { useSelectAiChatThread } from '@/ai/hooks/useSelectAiChatThread';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';
import {
@@ -27,7 +26,7 @@ describe('useSelectAiChatThread', () => {
resetJotaiStore();
});
- it.each([AGENT_CHAT_NEW_THREAD_DRAFT_KEY, 'other-thread'])(
+ it.each(['new-chat-thread', 'other-thread'])(
'leaves onboarding when selecting %s',
(threadId) => {
jotaiStore.set(shouldOpenAiChatAfterOnboardingState.atom, true);
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
index fccfa2ccd3a..925b45ee4c1 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
@@ -5,11 +5,7 @@ import { t } from '@lingui/core/macro';
import { useStore } from 'jotai';
import { useCallback } from 'react';
import { type ExtendedUIMessage } from 'twenty-shared/ai';
-import {
- isDefined,
- isValidUuid,
- tipTapDocumentToMarkdown,
-} from 'twenty-shared/utils';
+import { isDefined, tipTapDocumentToMarkdown } from 'twenty-shared/utils';
import { useToast } from 'twenty-ui/components/feedback';
import { v4 } from 'uuid';
@@ -22,11 +18,9 @@ import { useAttachChatThreadToRecord } from '@/ai/hooks/useAttachChatThreadToRec
import { useGetBrowsingContext } from '@/ai/hooks/useGetBrowsingContext';
import { useOptimisticallyRestoreOnSend } from '@/ai/hooks/useOptimisticallyRestoreOnSend';
import { useProjectAiChatThreadToUrl } from '@/ai/hooks/useProjectAiChatThreadToUrl';
+import { useRefreshAgentChatThreadPermissions } from '@/ai/hooks/useRefreshAgentChatThreadPermissions';
import { useWarnAboutParticipantMentionsNotAdded } from '@/ai/hooks/useWarnAboutParticipantMentionsNotAdded';
-import {
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- agentChatDraftsByThreadIdState,
-} from '@/ai/states/agentChatDraftsByThreadIdState';
+import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';
import { agentChatLastSentBrowsingContextFamilyState } from '@/ai/states/agentChatLastSentBrowsingContextFamilyState';
import { agentChatSelectedFilesState } from '@/ai/states/agentChatSelectedFilesState';
import { agentChatSentMessageHandOffState } from '@/ai/states/agentChatSentMessageHandOffState';
@@ -35,6 +29,7 @@ import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { agentChatErrorFamilyState } from '@/ai/states/agentChatErrorFamilyState';
import { agentChatIsAwaitingFirstChunkFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkFamilyState';
import { agentChatMessagesFamilyState } from '@/ai/states/agentChatMessagesFamilyState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { getConversationTargetsFromSerializedDocument } from '@/ai/utils/getConversationTargetsFromSerializedDocument';
import { getParticipantMentionsFromSerializedDocument } from '@/ai/utils/getParticipantMentionsFromSerializedDocument';
import { isAiChatCreditsExhaustedError } from '@/ai/utils/isAiChatCreditsExhaustedError';
@@ -54,9 +49,7 @@ import {
StopAgentChatStreamDocument,
} from '~/generated-metadata/graphql';
-export const useAgentChat = (
- ensureThreadIdForSend: () => Promise<string | null>,
-) => {
+export const useAgentChat = () => {
const { modelIdForRequest } = useAgentChatModelId();
const aiModels = useAtomStateValue(aiModelsState);
const { getBrowsingContext } = useGetBrowsingContext();
@@ -68,6 +61,8 @@ export const useAgentChat = (
const { enqueueToast } = useToast();
const setCurrentAiChatThread = useSetAtomState(currentAiChatThreadState);
const { projectAiChatThreadToUrl } = useProjectAiChatThreadToUrl();
+ const { refreshAgentChatThreadPermissions } =
+ useRefreshAgentChatThreadPermissions();
const store = useStore();
const setAgentChatUploadedFiles = useSetAtomState(
@@ -79,11 +74,12 @@ export const useAgentChat = (
);
const handleSendMessage = useCallback(async () => {
- const draftKey =
- store.get(currentAiChatThreadState.atom) ??
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
+ const newAiChatThreadId = store.get(newAiChatThreadIdState.atom);
+ const threadId =
+ store.get(currentAiChatThreadState.atom) ?? newAiChatThreadId;
+ const isNewChat = threadId === newAiChatThreadId;
const serializedContentToSend =
- store.get(agentChatDraftsByThreadIdState.atom)[draftKey] ?? '';
+ store.get(agentChatDraftsByThreadIdState.atom)[threadId] ?? '';
const contentToSend = tipTapDocumentToMarkdown(
serializedContentToSend,
).trim();
@@ -109,20 +105,12 @@ export const useAgentChat = (
const agentChatUploadedFiles = store.get(agentChatUploadedFilesState.atom);
- const threadId = await ensureThreadIdForSend();
-
- if (!isDefined(threadId)) {
- return;
- }
-
- if (draftKey === AGENT_CHAT_NEW_THREAD_DRAFT_KEY) {
- setCurrentAiChatThread(threadId);
- projectAiChatThreadToUrl(threadId);
- }
+ // Selects the new chat when the composer wrote to it before the chat list loaded
+ setCurrentAiChatThread(threadId);
setAgentChatDraftsByThreadId((prev) => ({
...prev,
- [draftKey]: '',
+ [threadId]: '',
}));
const browsingContext = getBrowsingContext();
@@ -242,19 +230,24 @@ export const useAgentChat = (
removeOptimisticUserMessage();
}
+ // The send created the thread. Its permissions load before it stops
+ // being the new chat, so its composer never shows as loading.
+ if (isNewChat) {
+ await refreshAgentChatThreadPermissions([threadId]);
+ store.set(newAiChatThreadIdState.atom, v4());
+
+ if (store.get(currentAiChatThreadState.atom) === threadId) {
+ projectAiChatThreadToUrl(threadId);
+ }
+ }
+
dispatchBrowserEvent(AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME);
} catch (error) {
- const restoredDraftKey =
- draftKey === AGENT_CHAT_NEW_THREAD_DRAFT_KEY ? threadId : draftKey;
-
rollbackOptimisticRestore();
setAgentChatDraftsByThreadId((prev) => ({
...prev,
- [restoredDraftKey]: serializedContentToSend,
- ...(draftKey === AGENT_CHAT_NEW_THREAD_DRAFT_KEY
- ? { [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]: '' }
- : {}),
+ [threadId]: serializedContentToSend,
}));
setAgentChatUploadedFiles((currentUploadedFiles) => [
...agentChatUploadedFiles,
@@ -274,7 +267,6 @@ export const useAgentChat = (
}
}, [
store,
- ensureThreadIdForSend,
getBrowsingContext,
setAgentChatUploadedFiles,
setAgentChatDraftsByThreadId,
@@ -283,6 +275,7 @@ export const useAgentChat = (
enqueueToast,
setCurrentAiChatThread,
projectAiChatThreadToUrl,
+ refreshAgentChatThreadPermissions,
apolloClient,
applyOptimisticRestore,
attachChatThreadToRecord,
@@ -297,7 +290,7 @@ export const useAgentChat = (
const handleStop = useCallback(async () => {
const threadId = store.get(currentAiChatThreadState.atom);
- if (!isDefined(threadId) || !isValidUuid(threadId)) {
+ if (!isDefined(threadId)) {
return;
}
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts
index 701a5a400b6..1fd8226ba5b 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts
@@ -9,12 +9,9 @@ import { AI_CHAT_EDITOR_PROFILE } from '@/ai/constants/AiChatEditorProfile';
import { AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME } from '@/ai/constants/AgentChatRestoreEditorContentEventName';
import { AI_CHAT_INPUT_ID } from '@/ai/constants/AiChatInputId';
import { useAiChatFileUpload } from '@/ai/hooks/useAiChatFileUpload';
-import {
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- agentChatDraftsByThreadIdState,
-} from '@/ai/states/agentChatDraftsByThreadIdState';
+import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
-import { AGENT_CHAT_ENSURE_THREAD_FOR_DRAFT_EVENT_NAME } from '@/ai/constants/AgentChatEnsureThreadForDraftEventName';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { AGENT_CHAT_SEND_MESSAGE_EVENT_NAME } from '@/ai/constants/AgentChatSendMessageEventName';
import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEvent';
import { MENTION_SUGGESTION_PLUGIN_KEY } from '@/mention/constants/MentionSuggestionPluginKey';
@@ -34,6 +31,7 @@ import { turnIntoEmptyStringIfWhitespacesOnly } from '~/utils/string/turnIntoEmp
export const useAiChatEditor = () => {
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
+ const newAiChatThreadId = useAtomStateValue(newAiChatThreadIdState);
const [agentChatDraftsByThreadId, setAgentChatDraftsByThreadId] =
useAtomState(agentChatDraftsByThreadIdState);
const { searchMentionRecords } = useMentionSearch();
@@ -47,7 +45,7 @@ export const useAiChatEditor = () => {
const { removeFocusItemFromFocusStackById } =
useRemoveFocusItemFromFocusStackById();
- const draftKey = currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
+ const draftKey = currentAiChatThread ?? newAiChatThreadId;
const initialDraft = agentChatDraftsByThreadId[draftKey] ?? '';
const editor = useAdvancedTextEditor({
profile: AI_CHAT_EDITOR_PROFILE,
@@ -109,9 +107,6 @@ export const useAiChatEditor = () => {
...prev,
[draftKey]: serializedDraft,
}));
- if (draftKey === AGENT_CHAT_NEW_THREAD_DRAFT_KEY && text.trim() !== '') {
- dispatchBrowserEvent(AGENT_CHAT_ENSURE_THREAD_FOR_DRAFT_EVENT_NAME);
- }
},
onFocus: () => {
pushFocusItemToFocusStack({
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatPendingParticipantMentions.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatPendingParticipantMentions.ts
index baddb64210f..6cd793ac8fd 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatPendingParticipantMentions.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatPendingParticipantMentions.ts
@@ -1,10 +1,8 @@
import { useMemo } from 'react';
-import {
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- agentChatDraftsByThreadIdState,
-} from '@/ai/states/agentChatDraftsByThreadIdState';
+import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { agentChatThreadRecordFamilySelector } from '@/ai/states/selectors/agentChatThreadRecordFamilySelector';
import { filterNewParticipantMentions } from '@/ai/utils/filterNewParticipantMentions';
import { getParticipantMentionsFromSerializedDocument } from '@/ai/utils/getParticipantMentionsFromSerializedDocument';
@@ -14,7 +12,8 @@ import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomState
export const useAiChatPendingParticipantMentions = () => {
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
- const draftKey = currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
+ const newAiChatThreadId = useAtomStateValue(newAiChatThreadIdState);
+ const draftKey = currentAiChatThread ?? newAiChatThreadId;
const serializedDraft =
useAtomStateValue(agentChatDraftsByThreadIdState)[draftKey] ?? '';
const thread = useAtomFamilySelectorValue(
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts
index e4b01287879..9c25123a667 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts
@@ -1,8 +1,6 @@
-import { threadIdCreatedFromDraftState } from '@/ai/states/threadIdCreatedFromDraftState';
import { useSelectAiChatThread } from '@/ai/hooks/useSelectAiChatThread';
import { useNavigateToAiChatPage } from '@/ai/hooks/useNavigateToAiChatPage';
import { useOpenAskAiPageInSidePanel } from '@/side-panel/hooks/useOpenAskAiPageInSidePanel';
-import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';
import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';
@@ -16,16 +14,11 @@ export const useAiChatThreadClick = (
) => {
const { resetNavigationStack = false, shouldOpenInFullPage = false } =
options;
- const setThreadIdCreatedFromDraft = useSetAtomState(
- threadIdCreatedFromDraftState,
- );
const { selectAiChatThread } = useSelectAiChatThread();
const { openAskAiPage } = useOpenAskAiPageInSidePanel();
const { navigateToAiChatPage } = useNavigateToAiChatPage();
const handleThreadClick = (thread: Pick<AgentChatThreadRecord, 'id'>) => {
- setThreadIdCreatedFromDraft(null);
-
selectAiChatThread(thread.id);
if (isCurrentPathAiChatPage()) {
diff --git a/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts b/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts
deleted file mode 100644
index 7780598aaa7..00000000000
--- a/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { useApplyAgentChatThreadUpdate } from '@/ai/hooks/useApplyAgentChatThreadUpdate';
-import { useRefreshAgentChatThreadPermissions } from '@/ai/hooks/useRefreshAgentChatThreadPermissions';
-import { useStore } from 'jotai';
-import { useCallback } from 'react';
-import { isDefined } from 'twenty-shared/utils';
-
-import { useProjectAiChatThreadToUrl } from '@/ai/hooks/useProjectAiChatThreadToUrl';
-import {
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- agentChatDraftsByThreadIdState,
-} from '@/ai/states/agentChatDraftsByThreadIdState';
-import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
-import { hasTriggeredCreateForDraftState } from '@/ai/states/hasTriggeredCreateForDraftState';
-import { isCreatingForFirstSendState } from '@/ai/states/isCreatingForFirstSendState';
-import { pendingAgentChatThreadCreationState } from '@/ai/states/pendingAgentChatThreadCreationState';
-import { shouldFocusChatEditorState } from '@/ai/states/shouldFocusChatEditorState';
-import { skipMessagesSkeletonUntilLoadedState } from '@/ai/states/skipMessagesSkeletonUntilLoadedState';
-import { threadIdCreatedFromDraftState } from '@/ai/states/threadIdCreatedFromDraftState';
-import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
-
-import { useMutation } from '@apollo/client/react';
-import { CreateChatThreadDocument } from '~/generated-metadata/graphql';
-
-export const useCreateAgentChatThread = () => {
- const setCurrentAiChatThread = useSetAtomState(currentAiChatThreadState);
- const setAgentChatDraftsByThreadId = useSetAtomState(
- agentChatDraftsByThreadIdState,
- );
- const { projectAiChatThreadToUrl } = useProjectAiChatThreadToUrl();
- const store = useStore();
- const { refreshAgentChatThreadPermissions } =
- useRefreshAgentChatThreadPermissions();
- const { addAgentChatThread } = useApplyAgentChatThreadUpdate();
-
- const [createChatThreadMutation] = useMutation(CreateChatThreadDocument, {
- onCompleted: (data) => {
- const newThread = {
- id: data.createChatThread.id,
- title: data.createChatThread.title ?? null,
- createdAt: data.createChatThread.createdAt,
- updatedAt: data.createChatThread.updatedAt,
- deletedAt: null,
- };
-
- addAgentChatThread(newThread);
- void refreshAgentChatThreadPermissions([newThread.id]);
-
- if (store.get(isCreatingForFirstSendState.atom)) {
- store.set(isCreatingForFirstSendState.atom, false);
- store.set(threadIdCreatedFromDraftState.atom, newThread.id);
- return;
- }
-
- const newThreadId = data.createChatThread.id;
- const previousDraftKey =
- store.get(currentAiChatThreadState.atom) ??
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
- const draftsSnapshot = store.get(agentChatDraftsByThreadIdState.atom);
- const newDraft = draftsSnapshot[AGENT_CHAT_NEW_THREAD_DRAFT_KEY] ?? '';
-
- if (previousDraftKey === AGENT_CHAT_NEW_THREAD_DRAFT_KEY) {
- store.set(hasTriggeredCreateForDraftState.atom, true);
- setAgentChatDraftsByThreadId((previousDrafts) => ({
- ...previousDrafts,
- [newThreadId]: newDraft,
- [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]: '',
- }));
- store.set(shouldFocusChatEditorState.atom, true);
- store.set(skipMessagesSkeletonUntilLoadedState.atom, true);
- store.set(threadIdCreatedFromDraftState.atom, newThreadId);
- }
-
- setCurrentAiChatThread(newThreadId);
- projectAiChatThreadToUrl(newThreadId);
- },
- onError: () => {
- store.set(isCreatingForFirstSendState.atom, false);
- store.set(hasTriggeredCreateForDraftState.atom, false);
- },
- });
-
- // Every caller shares the in-flight creation so a draft never gets two threads
- const createChatThread = useCallback((): Promise<string | null> => {
- const pendingCreation = store.get(pendingAgentChatThreadCreationState.atom);
-
- if (isDefined(pendingCreation)) {
- return pendingCreation;
- }
-
- const creation = createChatThreadMutation()
- .then(
- ({ data }) => data?.createChatThread.id ?? null,
- () => null,
- )
- .finally(() => {
- store.set(pendingAgentChatThreadCreationState.atom, null);
- });
-
- store.set(pendingAgentChatThreadCreationState.atom, creation);
-
- return creation;
- }, [createChatThreadMutation, store]);
-
- return { createChatThread };
-};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useCurrentAiChatThreadAccess.ts b/packages/twenty-front/src/modules/ai/hooks/useCurrentAiChatThreadAccess.ts
index 3d41b68085b..062e869f5e8 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useCurrentAiChatThreadAccess.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useCurrentAiChatThreadAccess.ts
@@ -1,5 +1,4 @@
import { useIsOnNewAiChatSlot } from '@/ai/hooks/useIsOnNewAiChatSlot';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { agentChatThreadPermissionsFamilySelector } from '@/ai/states/selectors/agentChatThreadPermissionsFamilySelector';
import { getAiChatThreadAccess } from '@/ai/utils/getAiChatThreadAccess';
@@ -11,12 +10,12 @@ export const useCurrentAiChatThreadAccess = () => {
const isOnNewAiChatSlot = useIsOnNewAiChatSlot();
const permissions = useAtomFamilySelectorValue(
agentChatThreadPermissionsFamilySelector,
- currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
+ currentAiChatThread ?? '',
);
+ // Before the chat list picks a chat, the composer writes to the new one
return getAiChatThreadAccess({
- currentAiChatThread,
- isOnNewAiChatSlot,
+ isOnNewAiChatSlot: isOnNewAiChatSlot || currentAiChatThread === null,
permissions,
});
};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadExistsForDraft.ts b/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadExistsForDraft.ts
deleted file mode 100644
index 090557f5553..00000000000
--- a/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadExistsForDraft.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { useStore } from 'jotai';
-import { useCallback } from 'react';
-
-import { useCreateAgentChatThread } from '@/ai/hooks/useCreateAgentChatThread';
-import {
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- agentChatDraftsByThreadIdState,
-} from '@/ai/states/agentChatDraftsByThreadIdState';
-import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
-import { hasTriggeredCreateForDraftState } from '@/ai/states/hasTriggeredCreateForDraftState';
-import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';
-
-export const useEnsureAgentChatThreadExistsForDraft = () => {
- const { createChatThread } = useCreateAgentChatThread();
- const store = useStore();
-
- const ensureThreadExistsForDraft = useCallback(() => {
- const currentThreadId = store.get(currentAiChatThreadState.atom);
-
- if (currentThreadId !== AGENT_CHAT_NEW_THREAD_DRAFT_KEY) {
- return;
- }
-
- const draft =
- store.get(agentChatDraftsByThreadIdState.atom)[
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY
- ] ?? '';
-
- if (
- tipTapDocumentToMarkdown(draft).trim() === '' ||
- store.get(hasTriggeredCreateForDraftState.atom)
- ) {
- return;
- }
-
- void createChatThread();
- }, [createChatThread, store]);
-
- return { ensureThreadExistsForDraft };
-};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadIdForSend.ts b/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadIdForSend.ts
deleted file mode 100644
index 2db271c9200..00000000000
--- a/packages/twenty-front/src/modules/ai/hooks/useEnsureAgentChatThreadIdForSend.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { useStore } from 'jotai';
-import { useCallback } from 'react';
-import { isDefined } from 'twenty-shared/utils';
-
-import { useCreateAgentChatThread } from '@/ai/hooks/useCreateAgentChatThread';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
-import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
-import { isCreatingForFirstSendState } from '@/ai/states/isCreatingForFirstSendState';
-import { pendingAgentChatThreadCreationState } from '@/ai/states/pendingAgentChatThreadCreationState';
-
-export const useEnsureAgentChatThreadIdForSend = () => {
- const { createChatThread } = useCreateAgentChatThread();
- const store = useStore();
-
- const ensureThreadIdForSend = useCallback(async (): Promise<
- string | null
- > => {
- const currentThreadId = store.get(currentAiChatThreadState.atom);
-
- if (
- currentThreadId !== null &&
- currentThreadId !== AGENT_CHAT_NEW_THREAD_DRAFT_KEY
- ) {
- return currentThreadId;
- }
-
- const pendingCreation = store.get(pendingAgentChatThreadCreationState.atom);
-
- if (isDefined(pendingCreation)) {
- return pendingCreation;
- }
-
- store.set(isCreatingForFirstSendState.atom, true);
-
- return createChatThread();
- }, [createChatThread, store]);
-
- return { ensureThreadIdForSend };
-};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useIsOnNewAiChatSlot.ts b/packages/twenty-front/src/modules/ai/hooks/useIsOnNewAiChatSlot.ts
index 697e7f7fa35..9507728aff8 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useIsOnNewAiChatSlot.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useIsOnNewAiChatSlot.ts
@@ -1,19 +1,10 @@
-import { isDefined } from 'twenty-shared/utils';
-
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
-import { threadIdCreatedFromDraftState } from '@/ai/states/threadIdCreatedFromDraftState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
export const useIsOnNewAiChatSlot = () => {
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
- const threadIdCreatedFromDraft = useAtomStateValue(
- threadIdCreatedFromDraftState,
- );
+ const newAiChatThreadId = useAtomStateValue(newAiChatThreadIdState);
- return (
- currentAiChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY ||
- (isDefined(threadIdCreatedFromDraft) &&
- currentAiChatThread === threadIdCreatedFromDraft)
- );
+ return currentAiChatThread === newAiChatThreadId;
};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useLeaveRemovedAiChatThread.ts b/packages/twenty-front/src/modules/ai/hooks/useLeaveRemovedAiChatThread.ts
index aea0a2bb574..a3d39a3e6b4 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useLeaveRemovedAiChatThread.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useLeaveRemovedAiChatThread.ts
@@ -1,11 +1,11 @@
import { useStore } from 'jotai';
import { useCallback } from 'react';
-import { isDefined, isValidUuid } from 'twenty-shared/utils';
+import { isDefined } from 'twenty-shared/utils';
import { useProjectAiChatThreadToUrl } from '@/ai/hooks/useProjectAiChatThreadToUrl';
import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { agentChatThreadsSelector } from '@/ai/states/selectors/agentChatThreadsSelector';
import { agentChatVisibleThreadsSelector } from '@/ai/states/selectors/agentChatVisibleThreadsSelector';
import { sortChatThreadsByLastActivityDesc } from '@/ai/utils/sortChatThreadsByLastActivityDesc';
@@ -18,11 +18,12 @@ export const useLeaveRemovedAiChatThread = () => {
const leaveRemovedAiChatThread = useCallback(async () => {
const currentThreadId = store.get(currentAiChatThreadState.atom);
+ const newAiChatThreadId = store.get(newAiChatThreadIdState.atom);
const threads = store.get(agentChatThreadsSelector.atom);
if (
!isDefined(currentThreadId) ||
- !isValidUuid(currentThreadId) ||
+ currentThreadId === newAiChatThreadId ||
threads.some(({ id }) => id === currentThreadId)
) {
return;
@@ -41,7 +42,7 @@ export const useLeaveRemovedAiChatThread = () => {
const nextThreadId =
sortChatThreadsByLastActivityDesc(
store.get(agentChatVisibleThreadsSelector.atom),
- )[0]?.id ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
+ )[0]?.id ?? newAiChatThreadId;
store.set(currentAiChatThreadState.atom, nextThreadId);
projectAiChatThreadToUrl(nextThreadId);
}, [store, projectAiChatThreadToUrl, loadAgentChatThread]);
diff --git a/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts b/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts
index a25b22c3159..30a8c2ff7c9 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts
@@ -3,7 +3,6 @@ import { isDefined } from 'twenty-shared/utils';
import { useStageAiChatPreprompt } from '@/ai/hooks/useStageAiChatPreprompt';
import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { type AgentChatPrepromptMode } from '@/ai/states/agentChatPrepromptState';
import { useWorkspaceAiModelTiers } from '@/ai/hooks/useWorkspaceAiModelTiers';
import { agentChatUserSelectedModelTierState } from '@/ai/states/agentChatUserSelectedModelTierState';
@@ -43,11 +42,7 @@ export const useOpenAskAiPageWithPreprompt = () => {
setAgentChatUserSelectedModelTier(tier === chatTier ? null : tier);
}
- stageAiChatPreprompt({
- serializedDocument,
- mode,
- draftKey: AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- });
+ stageAiChatPreprompt({ serializedDocument, mode });
};
return { openAskAiPageWithPreprompt };
diff --git a/packages/twenty-front/src/modules/ai/hooks/useProjectAiChatThreadToUrl.ts b/packages/twenty-front/src/modules/ai/hooks/useProjectAiChatThreadToUrl.ts
index e8432bab70b..778e8913e43 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useProjectAiChatThreadToUrl.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useProjectAiChatThreadToUrl.ts
@@ -1,13 +1,15 @@
+import { useStore } from 'jotai';
import { useCallback } from 'react';
import { AppPath } from 'twenty-shared/types';
-import { isValidUuid } from 'twenty-shared/utils';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { useNavigateApp } from '~/hooks/useNavigateApp';
import { getCurrentHistoryEntryState } from '~/utils/getCurrentHistoryEntryState';
import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';
export const useProjectAiChatThreadToUrl = () => {
const navigateApp = useNavigateApp();
+ const store = useStore();
const projectAiChatThreadToUrl = useCallback(
(threadId: string) => {
@@ -15,14 +17,17 @@ export const useProjectAiChatThreadToUrl = () => {
return;
}
+ // The new chat has no thread to open yet, so its URL carries no id
+ const isNewChat = threadId === store.get(newAiChatThreadIdState.atom);
+
navigateApp(
AppPath.AiChat,
- { threadId: isValidUuid(threadId) ? threadId : null },
+ { threadId: isNewChat ? null : threadId },
undefined,
{ replace: true, state: getCurrentHistoryEntryState() },
);
},
- [navigateApp],
+ [navigateApp, store],
);
return { projectAiChatThreadToUrl };
diff --git a/packages/twenty-front/src/modules/ai/hooks/useStageAiChatPreprompt.ts b/packages/twenty-front/src/modules/ai/hooks/useStageAiChatPreprompt.ts
index 1b3be55c2c9..6e6764f39e4 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useStageAiChatPreprompt.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useStageAiChatPreprompt.ts
@@ -1,12 +1,17 @@
+import { useStore } from 'jotai';
+
import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';
import {
type AgentChatPrepromptMode,
agentChatPrepromptState,
} from '@/ai/states/agentChatPrepromptState';
+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
// Sending reads the draft, not the editor, so it's written before AgentChatPrepromptEffect picks it up.
export const useStageAiChatPreprompt = () => {
+ const store = useStore();
const setAgentChatDraftsByThreadId = useSetAtomState(
agentChatDraftsByThreadIdState,
);
@@ -15,15 +20,17 @@ export const useStageAiChatPreprompt = () => {
const stageAiChatPreprompt = ({
serializedDocument,
mode,
- draftKey,
}: {
serializedDocument: string;
mode: AgentChatPrepromptMode;
- draftKey: string;
}) => {
+ const threadId =
+ store.get(currentAiChatThreadState.atom) ??
+ store.get(newAiChatThreadIdState.atom);
+
setAgentChatDraftsByThreadId((previousDrafts) => ({
...previousDrafts,
- [draftKey]: serializedDocument,
+ [threadId]: serializedDocument,
}));
setAgentChatPreprompt({ serializedDocument, mode });
};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAiChat.ts b/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAiChat.ts
index 11a099b58b5..240d84e41e7 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAiChat.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAiChat.ts
@@ -2,12 +2,9 @@ import { useStore } from 'jotai';
import { useNavigateToAiChatPage } from '@/ai/hooks/useNavigateToAiChatPage';
import { useSelectAiChatThread } from '@/ai/hooks/useSelectAiChatThread';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { shouldFocusChatEditorState } from '@/ai/states/shouldFocusChatEditorState';
-import { hasTriggeredCreateForDraftState } from '@/ai/states/hasTriggeredCreateForDraftState';
-import { threadIdCreatedFromDraftState } from '@/ai/states/threadIdCreatedFromDraftState';
import { useOpenAskAiPageInSidePanel } from '@/side-panel/hooks/useOpenAskAiPageInSidePanel';
-import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
type UseSwitchToNewAiChatParams = {
shouldOpenInFullPage?: boolean;
@@ -16,18 +13,13 @@ type UseSwitchToNewAiChatParams = {
export const useSwitchToNewAiChat = ({
shouldOpenInFullPage = false,
}: UseSwitchToNewAiChatParams = {}) => {
- const setThreadIdCreatedFromDraft = useSetAtomState(
- threadIdCreatedFromDraftState,
- );
const { selectAiChatThread } = useSelectAiChatThread();
const store = useStore();
const { openAskAiPage } = useOpenAskAiPageInSidePanel();
const { navigateToAiChatPage } = useNavigateToAiChatPage();
const switchToNewChat = () => {
- setThreadIdCreatedFromDraft(null);
- store.set(hasTriggeredCreateForDraftState.atom, false);
- selectAiChatThread(AGENT_CHAT_NEW_THREAD_DRAFT_KEY);
+ selectAiChatThread(store.get(newAiChatThreadIdState.atom));
if (shouldOpenInFullPage) {
navigateToAiChatPage();
diff --git a/packages/twenty-front/src/modules/ai/states/agentChatDraftsByThreadIdState.ts b/packages/twenty-front/src/modules/ai/states/agentChatDraftsByThreadIdState.ts
index 12db203824e..4d9a80f9668 100644
--- a/packages/twenty-front/src/modules/ai/states/agentChatDraftsByThreadIdState.ts
+++ b/packages/twenty-front/src/modules/ai/states/agentChatDraftsByThreadIdState.ts
@@ -1,8 +1,6 @@
import { isAgentChatDraftsByThreadId } from '@/ai/utils/isAgentChatDraftsByThreadId';
import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-export const AGENT_CHAT_NEW_THREAD_DRAFT_KEY = '__new__';
-
const DRAFTS_STORAGE_KEY = 'ai/agentChatDraftsByThreadIdState';
export const agentChatDraftsByThreadIdState = createAtomState<
diff --git a/packages/twenty-front/src/modules/ai/states/hasTriggeredCreateForDraftState.ts b/packages/twenty-front/src/modules/ai/states/hasTriggeredCreateForDraftState.ts
deleted file mode 100644
index cc31b971b24..00000000000
--- a/packages/twenty-front/src/modules/ai/states/hasTriggeredCreateForDraftState.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-
-export const hasTriggeredCreateForDraftState = createAtomState<boolean>({
- key: 'ai/hasTriggeredCreateForDraftState',
- defaultValue: false,
-});
diff --git a/packages/twenty-front/src/modules/ai/states/isCreatingForFirstSendState.ts b/packages/twenty-front/src/modules/ai/states/isCreatingForFirstSendState.ts
deleted file mode 100644
index b41152c3a30..00000000000
--- a/packages/twenty-front/src/modules/ai/states/isCreatingForFirstSendState.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-
-export const isCreatingForFirstSendState = createAtomState<boolean>({
- key: 'ai/isCreatingForFirstSendState',
- defaultValue: false,
-});
diff --git a/packages/twenty-front/src/modules/ai/states/newAiChatThreadIdState.ts b/packages/twenty-front/src/modules/ai/states/newAiChatThreadIdState.ts
new file mode 100644
index 00000000000..abb110e0d6f
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/states/newAiChatThreadIdState.ts
@@ -0,0 +1,40 @@
+import { isString } from '@sniptt/guards';
+import { isValidUuid } from 'twenty-shared/utils';
+import { v4 } from 'uuid';
+
+import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
+
+const NEW_AI_CHAT_THREAD_ID_STORAGE_KEY = 'ai/newAiChatThreadIdState';
+
+// Stored per tab so two tabs never start the same chat, and stored before the
+// first keystroke so a reload finds the draft typed under it
+const readOrStoreNewAiChatThreadId = (): string => {
+ try {
+ const storedThreadId: unknown = JSON.parse(
+ sessionStorage.getItem(NEW_AI_CHAT_THREAD_ID_STORAGE_KEY) ?? 'null',
+ );
+
+ if (isString(storedThreadId) && isValidUuid(storedThreadId)) {
+ return storedThreadId;
+ }
+
+ const threadId = v4();
+
+ sessionStorage.setItem(
+ NEW_AI_CHAT_THREAD_ID_STORAGE_KEY,
+ JSON.stringify(threadId),
+ );
+
+ return threadId;
+ } catch {
+ return v4();
+ }
+};
+
+// The server creates the new chat's thread on its first message, and a fresh
+// id replaces this one once that message is sent
+export const newAiChatThreadIdState = createAtomState<string>({
+ key: NEW_AI_CHAT_THREAD_ID_STORAGE_KEY,
+ defaultValue: readOrStoreNewAiChatThreadId(),
+ useSessionStorage: true,
+});
diff --git a/packages/twenty-front/src/modules/ai/states/pendingAgentChatThreadCreationState.ts b/packages/twenty-front/src/modules/ai/states/pendingAgentChatThreadCreationState.ts
deleted file mode 100644
index f948f80d50a..00000000000
--- a/packages/twenty-front/src/modules/ai/states/pendingAgentChatThreadCreationState.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-
-export const pendingAgentChatThreadCreationState = createAtomState<Promise<
- string | null
-> | null>({
- key: 'ai/pendingAgentChatThreadCreationState',
- defaultValue: null,
-});
diff --git a/packages/twenty-front/src/modules/ai/states/selectors/agentChatInputIsEmptySelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/agentChatInputIsEmptySelector.ts
index 37e85a9b1b4..6a866529123 100644
--- a/packages/twenty-front/src/modules/ai/states/selectors/agentChatInputIsEmptySelector.ts
+++ b/packages/twenty-front/src/modules/ai/states/selectors/agentChatInputIsEmptySelector.ts
@@ -1,8 +1,6 @@
-import {
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- agentChatDraftsByThreadIdState,
-} from '@/ai/states/agentChatDraftsByThreadIdState';
+import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { createAtomSelector } from '@/ui/utilities/state/jotai/utils/createAtomSelector';
import { isNonEmptyString } from '@sniptt/guards';
@@ -11,7 +9,7 @@ export const agentChatInputIsEmptySelector = createAtomSelector<boolean>({
key: 'agentChatInputIsEmptySelector',
get: ({ get }) => {
const draftKey =
- get(currentAiChatThreadState) ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
+ get(currentAiChatThreadState) ?? get(newAiChatThreadIdState);
return !isNonEmptyString(get(agentChatDraftsByThreadIdState)[draftKey]);
},
diff --git a/packages/twenty-front/src/modules/ai/states/threadIdCreatedFromDraftState.ts b/packages/twenty-front/src/modules/ai/states/threadIdCreatedFromDraftState.ts
deleted file mode 100644
index 8c585450ac7..00000000000
--- a/packages/twenty-front/src/modules/ai/states/threadIdCreatedFromDraftState.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
-
-export const threadIdCreatedFromDraftState = createAtomState<string | null>({
- key: 'ai/threadIdCreatedFromDraftState',
- defaultValue: null,
-});
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatThreadAccess.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatThreadAccess.test.ts
index b9b1b4bc684..0029e727cea 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatThreadAccess.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatThreadAccess.test.ts
@@ -11,7 +11,7 @@ describe('getAiChatThreadAccess', () => {
it.each([
{
description:
- 'lets the author write in the thread their draft just created while its permissions load',
+ 'lets the author write in the new chat, which has no thread yet',
isOnNewAiChatSlot: true,
permissions: undefined,
expectedAccess: 'writer',
@@ -23,9 +23,8 @@ describe('getAiChatThreadAccess', () => {
expectedAccess: 'loading',
},
{
- description:
- 'follows the loaded permissions of the thread the draft created',
- isOnNewAiChatSlot: true,
+ description: 'lets a member who can only read the thread view it',
+ isOnNewAiChatSlot: false,
permissions: READ_ONLY_PERMISSIONS,
expectedAccess: 'viewer',
},
@@ -43,12 +42,8 @@ describe('getAiChatThreadAccess', () => {
expectedAccess: 'unavailable',
},
])('$description', ({ isOnNewAiChatSlot, permissions, expectedAccess }) => {
- expect(
- getAiChatThreadAccess({
- currentAiChatThread: 'thread',
- isOnNewAiChatSlot,
- permissions,
- }),
- ).toBe(expectedAccess);
+ expect(getAiChatThreadAccess({ isOnNewAiChatSlot, permissions })).toBe(
+ expectedAccess,
+ );
});
});
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getDisplayedAiChatThreadId.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getDisplayedAiChatThreadId.test.ts
index a8bb0b6b173..ccb7041f6ec 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/getDisplayedAiChatThreadId.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getDisplayedAiChatThreadId.test.ts
@@ -9,6 +9,7 @@ describe('getDisplayedAiChatThreadId', () => {
getDisplayedAiChatThreadId({
urlThreadId: URL_CHAT_ID,
currentAiChatThread: CURRENT_CHAT_ID,
+ isOnNewAiChatSlot: false,
}),
).toBe(URL_CHAT_ID);
});
@@ -18,6 +19,7 @@ describe('getDisplayedAiChatThreadId', () => {
getDisplayedAiChatThreadId({
urlThreadId: undefined,
currentAiChatThread: CURRENT_CHAT_ID,
+ isOnNewAiChatSlot: false,
}),
).toBe(CURRENT_CHAT_ID);
});
@@ -25,8 +27,9 @@ describe('getDisplayedAiChatThreadId', () => {
it('shows no record for a new chat', () => {
expect(
getDisplayedAiChatThreadId({
- urlThreadId: 'new',
- currentAiChatThread: 'new-thread-draft',
+ urlThreadId: undefined,
+ currentAiChatThread: CURRENT_CHAT_ID,
+ isOnNewAiChatSlot: true,
}),
).toBeNull();
});
diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatThreadAccess.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatThreadAccess.ts
index 14babecfd59..9a41e01810d 100644
--- a/packages/twenty-front/src/modules/ai/utils/getAiChatThreadAccess.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatThreadAccess.ts
@@ -1,27 +1,21 @@
import { isDefined } from 'twenty-shared/utils';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { type RecordPermissionsDto } from '~/generated-metadata/graphql';
type GetAiChatThreadAccessParams = {
- currentAiChatThread: string | null;
isOnNewAiChatSlot: boolean;
permissions: RecordPermissionsDto | undefined;
};
export const getAiChatThreadAccess = ({
- currentAiChatThread,
isOnNewAiChatSlot,
permissions,
}: GetAiChatThreadAccessParams) => {
- if (
- !isDefined(currentAiChatThread) ||
- currentAiChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY
- ) {
+ if (isOnNewAiChatSlot) {
return 'writer';
}
if (!isDefined(permissions?.canUpdate)) {
- return isOnNewAiChatSlot ? 'writer' : 'loading';
+ return 'loading';
}
if (!permissions.canRead) {
return 'unavailable';
diff --git a/packages/twenty-front/src/modules/ai/utils/getDisplayedAiChatThreadId.ts b/packages/twenty-front/src/modules/ai/utils/getDisplayedAiChatThreadId.ts
index b49edfa0414..27dfa87279c 100644
--- a/packages/twenty-front/src/modules/ai/utils/getDisplayedAiChatThreadId.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getDisplayedAiChatThreadId.ts
@@ -4,17 +4,15 @@ import { isDefined, isValidUuid } from 'twenty-shared/utils';
export const getDisplayedAiChatThreadId = ({
urlThreadId,
currentAiChatThread,
+ isOnNewAiChatSlot,
}: {
urlThreadId: string | undefined;
currentAiChatThread: string | null;
+ isOnNewAiChatSlot: boolean;
}): string | null => {
if (isDefined(urlThreadId) && isValidUuid(urlThreadId)) {
return urlThreadId;
}
- if (isDefined(currentAiChatThread) && isValidUuid(currentAiChatThread)) {
- return currentAiChatThread;
- }
-
- return null;
+ return isOnNewAiChatSlot ? null : currentAiChatThread;
};
diff --git a/packages/twenty-front/src/modules/command-menu-item/display/components/CommandMenuAskAiFallbackItem.tsx b/packages/twenty-front/src/modules/command-menu-item/display/components/CommandMenuAskAiFallbackItem.tsx
index e57a0041485..91e0aecb08f 100644
--- a/packages/twenty-front/src/modules/command-menu-item/display/components/CommandMenuAskAiFallbackItem.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/display/components/CommandMenuAskAiFallbackItem.tsx
@@ -4,7 +4,6 @@ import { IconMessageCirclePlus } from 'twenty-ui/icon';
import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';
import { useStageAiChatPreprompt } from '@/ai/hooks/useStageAiChatPreprompt';
import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { COMMAND_MENU_ASK_AI_FALLBACK_ITEM_ID } from '@/command-menu-item/constants/CommandMenuAskAiFallbackItemId';
import { CommandMenuItem } from '@/command-menu/components/CommandMenuItem';
import { sidePanelSearchState } from '@/side-panel/states/sidePanelSearchState';
@@ -29,7 +28,6 @@ export const CommandMenuAskAiFallbackItem = ({
serializedDocument:
serializePlainTextAsAdvancedTextEditorDocument(prompt),
mode: 'SEND',
- draftKey: AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
});
setSidePanelSearch('');
};
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/__tests__/WidgetActionChatThreadCreate.test.tsx b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/__tests__/WidgetActionChatThreadCreate.test.tsx
index a8c5bcc02c6..5c994454716 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/__tests__/WidgetActionChatThreadCreate.test.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/__tests__/WidgetActionChatThreadCreate.test.tsx
@@ -4,13 +4,14 @@ import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
import { getConversationTargetsFromSerializedDocument } from '@/ai/utils/getConversationTargetsFromSerializedDocument';
import { recordStoreFamilyState } from '@/object-record/record-store/states/recordStoreFamilyState';
import { WidgetActionChatThreadCreate } from '@/page-layout/widgets/chat-threads/components/WidgetActionChatThreadCreate';
import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
const COMPANY_ID = '20202020-0000-4000-8000-000000000002';
+const NEW_CHAT_ID = '20202020-0000-4000-8000-0000000000dd';
const switchToNewChat = jest.fn();
const mockHasPermissionFlag = jest.fn(() => true);
@@ -38,6 +39,7 @@ const renderAction = () =>
{
wrapper: getJestMetadataAndApolloMocksWrapper({
onInitializeJotaiStore: (store) => {
+ store.set(newAiChatThreadIdState.atom, NEW_CHAT_ID);
store.set(recordStoreFamilyState.atomFamily(COMPANY_ID), {
__typename: 'Company',
id: COMPANY_ID,
@@ -50,7 +52,7 @@ const renderAction = () =>
const readPersistedNewChatDraft = (): string =>
JSON.parse(localStorage.getItem('ai/agentChatDraftsByThreadIdState') ?? '{}')[
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY
+ NEW_CHAT_ID
] ?? '';
describe('WidgetActionChatThreadCreate', () => {
diff --git a/packages/twenty-front/src/modules/side-panel/components/SidePanelAskAiInfo.tsx b/packages/twenty-front/src/modules/side-panel/components/SidePanelAskAiInfo.tsx
index fadb1f30874..a0130b15cd7 100644
--- a/packages/twenty-front/src/modules/side-panel/components/SidePanelAskAiInfo.tsx
+++ b/packages/twenty-front/src/modules/side-panel/components/SidePanelAskAiInfo.tsx
@@ -1,5 +1,5 @@
import { AiChatThreadDetailsDropdown } from '@/ai/components/AiChatThreadDetailsDropdown';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
+import { useIsOnNewAiChatSlot } from '@/ai/hooks/useIsOnNewAiChatSlot';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { agentChatThreadRecordFamilySelector } from '@/ai/states/selectors/agentChatThreadRecordFamilySelector';
import { HeaderIdentifier } from '@/ui/layout/page/components/HeaderIdentifier';
@@ -19,6 +19,7 @@ const StyledContainer = styled.div`
export const SidePanelAskAiInfo = () => {
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
+ const isOnNewAiChatSlot = useIsOnNewAiChatSlot();
const currentAiChatThreadTitle = useAtomFamilySelectorValue(
agentChatThreadRecordFamilySelector,
currentAiChatThread ?? '',
@@ -27,10 +28,9 @@ export const SidePanelAskAiInfo = () => {
return (
<StyledContainer>
<HeaderIdentifier title={currentAiChatThreadTitle ?? t`Ask AI`} />
- {isDefined(currentAiChatThread) &&
- currentAiChatThread !== AGENT_CHAT_NEW_THREAD_DRAFT_KEY && (
- <AiChatThreadDetailsDropdown threadId={currentAiChatThread} />
- )}
+ {isDefined(currentAiChatThread) && !isOnNewAiChatSlot && (
+ <AiChatThreadDetailsDropdown threadId={currentAiChatThread} />
+ )}
</StyledContainer>
);
};
diff --git a/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx
index 3d8123ef69f..112eae5ef74 100644
--- a/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx
+++ b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx
@@ -8,6 +8,7 @@ import { AiChatPageHeader } from '@/ai/components/AiChatPageHeader';
import { AiChatTab } from '@/ai/components/AiChatTab';
import { AI_CHAT_SURFACE } from '@/ai/constants/AiChatSurface';
import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';
+import { useIsOnNewAiChatSlot } from '@/ai/hooks/useIsOnNewAiChatSlot';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { getDisplayedAiChatThreadId } from '@/ai/utils/getDisplayedAiChatThreadId';
import { PageCardLayout } from '@/ui/layout/page/components/PageCardLayout';
@@ -28,10 +29,12 @@ const StyledChatContainer = styled.div`
export const AiChatPage = () => {
const { threadId } = useParams();
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
+ const isOnNewAiChatSlot = useIsOnNewAiChatSlot();
const isMobile = useIsMobile();
const displayedThreadId = getDisplayedAiChatThreadId({
urlThreadId: threadId,
currentAiChatThread,
+ isOnNewAiChatSlot,
});
return (
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts
index 40329c38595..52f565dbbef 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts
@@ -8,6 +8,10 @@ import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/service
import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
import { DatabaseEventAction } from 'src/engine/api/graphql/graphql-query-runner/enums/database-event-action';
import { AgentChatTurnPreflightService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service';
+import {
+ TwentyOrmException,
+ TwentyOrmExceptionCode,
+} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
const WORKSPACE_ID = 'workspace';
const THREAD_ID = 'thread';
@@ -16,6 +20,7 @@ const workspace = { id: WORKSPACE_ID } as never;
const buildResolver = () => {
const threadRepository = {
+ existsBy: jest.fn().mockResolvedValue(true),
findOne: jest.fn().mockResolvedValue(null),
update: jest.fn().mockResolvedValue({ affected: 0 }),
delete: jest.fn(),
@@ -27,6 +32,7 @@ const buildResolver = () => {
query: jest.fn().mockResolvedValue([]),
};
const sharing = {
+ createThread: jest.fn().mockResolvedValue({ id: THREAD_ID }),
getAuthContext: jest.fn().mockResolvedValue({ userWorkspaceId: 'owner' }),
getReadableThread: jest
.fn()
@@ -64,6 +70,7 @@ const buildResolver = () => {
lastActivityAt: new Date(),
updatedAt: new Date(),
}),
+ emitParticipantCreated: jest.fn(),
} as never,
);
const chatService = new AgentChatService(
@@ -196,6 +203,55 @@ describe('Shared conversation API boundaries', () => {
expect(streaming.streamAgentChat).toHaveBeenCalled();
});
+ it('creates the thread of a new chat on its first message', async () => {
+ const { resolver, sharing, threadRepository, streaming } = buildResolver();
+ threadRepository.existsBy.mockResolvedValue(false);
+ await resolver.sendChatMessage(
+ THREAD_ID,
+ 'Hello',
+ 'message',
+ null,
+ undefined,
+ null,
+ null,
+ 'member-workspace',
+ 'owner',
+ workspace,
+ );
+ expect(sharing.createThread).toHaveBeenCalledWith({
+ id: THREAD_ID,
+ workspaceMemberId: 'owner',
+ workspaceId: WORKSPACE_ID,
+ });
+ expect(streaming.streamAgentChat).toHaveBeenCalled();
+ });
+
+ it('does not let a new chat id take over a thread created concurrently by someone else', async () => {
+ const { resolver, sharing, threadRepository, streaming } = buildResolver();
+ threadRepository.existsBy.mockResolvedValue(false);
+ sharing.createThread.mockRejectedValue(
+ new TwentyOrmException(
+ 'Duplicate',
+ TwentyOrmExceptionCode.DUPLICATE_ENTRY_DETECTED,
+ ),
+ );
+ await expect(
+ resolver.sendChatMessage(
+ THREAD_ID,
+ 'Hello',
+ 'message',
+ null,
+ undefined,
+ null,
+ null,
+ 'viewer-workspace',
+ VIEWER_ID,
+ workspace,
+ ),
+ ).rejects.toMatchObject({ code: 'THREAD_NOT_FOUND' });
+ expect(streaming.streamAgentChat).not.toHaveBeenCalled();
+ });
+
it('returns readable threads and catchup to viewers without granting ownership', async () => {
const { resolver } = buildResolver();
const thread = await resolver.chatThread(THREAD_ID, VIEWER_ID, workspace);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts
index 283f5abe8f7..ecd3b880b90 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts
@@ -178,6 +178,12 @@ export class AgentChatResolver {
@AuthWorkspaceMemberId() workspaceMemberId: string,
@AuthWorkspace() workspace: WorkspaceEntity,
): Promise<SendChatMessageResultDTO> {
+ await this.threadService.createThreadIfMissing({
+ threadId,
+ workspaceMemberId,
+ workspaceId: workspace.id,
+ });
+
const sentMessage = await this.sendChatMessageToThread({
threadId,
text,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts
index b7191c3ad17..59a62add50c 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts
@@ -12,6 +12,7 @@ import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/a
import { type AgentChatThreadAccessArgs } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-access-args.type';
import { type AgentChatThreadActivity } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-activity.type';
import { buildAgentChatThreadActivitySetClause } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-activity-set-clause.util';
+import { isUniqueViolationError } from 'src/engine/metadata-modules/ai/ai-chat/utils/is-unique-violation-error.util';
import { throwAgentChatThreadNotFound } from 'src/engine/metadata-modules/ai/ai-chat/utils/throw-agent-chat-thread-not-found.util';
import { touchAgentChatThread } from 'src/engine/metadata-modules/ai/ai-chat/utils/touch-agent-chat-thread.util';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
@@ -55,6 +56,27 @@ export class AgentChatThreadService {
return savedThread;
}
+ // The client picks a new chat's id, so its first message creates the thread.
+ // An existing thread is left for the caller to check access to.
+ async createThreadIfMissing({
+ threadId,
+ ...args
+ }: AgentChatThreadAccessArgs): Promise<void> {
+ if (
+ await this.threadRepository.existsBy(args.workspaceId, { id: threadId })
+ ) {
+ return;
+ }
+
+ try {
+ await this.createThread({ ...args, id: threadId });
+ } catch (error) {
+ if (!isUniqueViolationError(error)) {
+ throw error;
+ }
+ }
+ }
+
// owned threads are skipped so an upsert cannot reassign them
async assignCreatedThreadsToCreator({
authContext,