The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(ai-chat): cancel removed AI chat uploads and keep the message when send is refused (#28081)
Etiennef9b7b2075bd2
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatPrepromptEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatPrepromptEffect.tsxindex 5ca1e4c6e6b..a0b0334bcaa 100644--- a/packages/twenty-front/src/modules/ai/components/AgentChatPrepromptEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AgentChatPrepromptEffect.tsx@@ -23,15 +23,13 @@ export const AgentChatPrepromptEffect = () => {const { serializedDocument, mode } = agentChatPreprompt;const timeoutId = setTimeout(() => {+ dispatchBrowserEvent(AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME, {+ content: serializedDocument,+ });+if (mode === 'SEND') {dispatchBrowserEvent(AGENT_CHAT_SEND_MESSAGE_EVENT_NAME);- dispatchBrowserEvent(AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME, {- content: '',- });} else {- dispatchBrowserEvent(AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME, {- content: serializedDocument,- });setShouldFocusChatEditor(true);}diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsxindex 3a4838b00c6..85d254fa3ea 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx@@ -142,7 +142,7 @@ const EditableAiChatEditorSection = () => {const aiModels = useAtomStateValue(aiModelsState);const hasNoEnabledModels = aiModels.length === 0;- const { editor, handleSendAndClear } = useAiChatEditor();+ const { editor } = useAiChatEditor();const insertDictatedText = useInsertDictatedText(editor);const [dictationInterimText, setDictationInterimText] = useState('');@@ -161,12 +161,7 @@ const EditableAiChatEditorSection = () => {</>}modelTierDropdownId="ai-chat-model-tier-dropdown"- sendButton={- <SendMessageButton- onSend={handleSendAndClear}- isDisabled={hasNoEnabledModels}- />- }+ sendButton={<SendMessageButton isDisabled={hasNoEnabledModels} />}/></StyledInputBox>);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.tsxindex bdddb2ca8d1..85c1ca33eae 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@@ -56,7 +56,7 @@ describe('AiChatEditorSection', () => {beforeEach(() => {editor = new Editor({ extensions: [Document, Paragraph, Text] });- useAiChatEditor.mockReturnValue({ editor, handleSendAndClear: jest.fn() });+ useAiChatEditor.mockReturnValue({ editor });});afterEach(() => {diff --git a/packages/twenty-front/src/modules/ai/components/internal/SendMessageButton.tsx b/packages/twenty-front/src/modules/ai/components/internal/SendMessageButton.tsxindex 98872eaab42..069511d6fd5 100644--- a/packages/twenty-front/src/modules/ai/components/internal/SendMessageButton.tsx+++ b/packages/twenty-front/src/modules/ai/components/internal/SendMessageButton.tsx@@ -1,3 +1,4 @@+import { AGENT_CHAT_SEND_MESSAGE_EVENT_NAME } from '@/ai/constants/AgentChatSendMessageEventName';import { AGENT_CHAT_STOP_EVENT_NAME } from '@/ai/constants/AgentChatStopEventName';import { agentChatIsAwaitingFirstChunkFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkFamilyState';import { agentChatIsLoadingSelector } from '@/ai/states/selectors/agentChatIsLoadingSelector';@@ -12,12 +13,10 @@ import { IconArrowUp, IconPlayerStop } from 'twenty-ui/icon';import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyStateValue';type SendMessageButtonProps = {- onSend: () => void;isDisabled?: boolean;};export const SendMessageButton = ({- onSend,isDisabled = false,}: SendMessageButtonProps) => {const agentChatInputIsEmpty = useAtomStateValue(@@ -36,6 +35,10 @@ export const SendMessageButton = ({{ threadId: currentAiChatThread },);+ const handleSendClick = () => {+ dispatchBrowserEvent(AGENT_CHAT_SEND_MESSAGE_EVENT_NAME);+ };+const handleStopClick = () => {dispatchBrowserEvent(AGENT_CHAT_STOP_EVENT_NAME);};@@ -62,7 +65,7 @@ export const SendMessageButton = ({shape="round"aria-label={t`Send message`}size="sm"- onClick={onSend}+ onClick={handleSendClick}disabled={isDisabled || agentChatInputIsEmpty || agentChatIsLoading}><IconArrowUp />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.tsxindex 91a8057ee27..6aab2f2159c 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@@ -6,13 +6,16 @@ import { type ReactNode } from 'react';import { MemoryRouter } from 'react-router-dom';import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';+import { AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME } from '@/ai/constants/AgentChatRestoreEditorContentEventName';import { useAgentChat } from '@/ai/hooks/useAgentChat';import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';+import { agentChatSelectedFilesState } from '@/ai/states/agentChatSelectedFilesState';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';+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';import { SendChatMessageDocument } from '~/generated-metadata/graphql';import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';@@ -187,6 +190,41 @@ describe('useAgentChat', () => {expect(attachChatThreadToRecord).not.toHaveBeenCalled();});+ it('keeps the composer while attachments upload and clears it on send', async () => {+ const result = renderAgentChat({+ persistedDrafts: {+ [THREAD_ID]: serializePlainTextAsAdvancedTextEditorDocument('Hello'),+ },+ sendChatMessageOutcomes: ['sent'],+ });+ const restoreEditorContent = jest.fn();++ window.addEventListener(+ AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME,+ restoreEditorContent,+ );+ jotaiStore.set(agentChatSelectedFilesState.atom, [+ new File(['brief'], 'brief.pdf'),+ ]);++ await send(result);++ expect(restoreEditorContent).not.toHaveBeenCalled();++ jotaiStore.set(agentChatSelectedFilesState.atom, []);++ await send(result);++ expect(restoreEditorContent).toHaveBeenCalledWith(+ expect.objectContaining({ detail: { content: '' } }),+ );++ window.removeEventListener(+ AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME,+ restoreEditorContent,+ );+ });+it('does not file a chat that mentions no record', async () => {const result = renderAgentChat({persistedDrafts: {diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiChatFileUpload.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiChatFileUpload.test.tsxnew file mode 100644index 00000000000..5cbf884762c--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiChatFileUpload.test.tsx@@ -0,0 +1,73 @@+import { type MockedResponse } from '@apollo/client/testing';+import { i18n } from '@lingui/core';+import { I18nProvider } from '@lingui/react';+import { act, renderHook, screen, waitFor } from '@testing-library/react';+import { type ReactNode } from 'react';++import { useAiChatFileUpload } from '@/ai/hooks/useAiChatFileUpload';+import { agentChatSelectedFilesState } from '@/ai/states/agentChatSelectedFilesState';+import { AppToaster } from '@/ui/feedback/toast/components/AppToaster';+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';+import { CreateFileUploadDocument } from '~/generated-metadata/graphql';+import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';++const createFileUploadMock: MockedResponse = {+ request: { query: CreateFileUploadDocument, variables: () => true },+ result: {+ data: {+ createFileUpload: {+ fileId: '20202020-0000-4000-8000-0000000000f1',+ uploadUrl: 'https://storage.twenty.com/upload',+ contentType: 'application/pdf',+ expiresAt: '2026-10-14T00:15:00.000Z',+ },+ },+ },+};++const putFile = jest.fn(+ (_input: RequestInfo | URL, init?: RequestInit) =>+ new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener('abort', reject);+ }),+);++global.fetch = putFile;++const MetadataAndApolloMocksWrapper = getJestMetadataAndApolloMocksWrapper({+ apolloMocks: [createFileUploadMock],+});++const Wrapper = ({ children }: { children: ReactNode }) => (+ <MetadataAndApolloMocksWrapper>+ <I18nProvider i18n={i18n}>+ {children}+ <AppToaster />+ </I18nProvider>+ </MetadataAndApolloMocksWrapper>+);++describe('useAiChatFileUpload', () => {+ it('aborts the upload of a file removed from the selection', async () => {+ const { result } = renderHook(() => useAiChatFileUpload(), {+ wrapper: Wrapper,+ });+ const file = new File(['brief'], 'brief.pdf');++ let upload: Promise<void> = Promise.resolve();++ act(() => {+ upload = result.current.uploadFiles([file]);+ });++ await waitFor(() => expect(putFile).toHaveBeenCalled());++ await act(async () => {+ jotaiStore.set(agentChatSelectedFilesState.atom, []);+ await upload;+ });++ expect(putFile.mock.calls[0][1]?.signal?.aborted).toBe(true);+ expect(screen.queryByRole('status')).not.toBeInTheDocument();+ });+});diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.tsindex 77fb952de7d..d3740f3d007 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts@@ -100,6 +100,11 @@ export const useAgentChat = () => {const agentChatSelectedFiles = store.get(agentChatSelectedFilesState.atom);if (agentChatSelectedFiles.length > 0) {+ enqueueToast({+ status: 'error',+ children: t`Wait for the attachments to finish uploading.`,+ });+return;}@@ -113,6 +118,10 @@ export const useAgentChat = () => {[threadId]: '',}));+ dispatchBrowserEvent(AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME, {+ content: '',+ });+const browsingContext = getBrowsingContext();const lastSentBrowsingContextAtom =agentChatLastSentBrowsingContextFamilyState.atomFamily(threadId);diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.tsindex 1fd8226ba5b..aee8b3638db 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts@@ -69,9 +69,6 @@ export const useAiChatEditor = () => {event.preventDefault();dispatchBrowserEvent(AGENT_CHAT_SEND_MESSAGE_EVENT_NAME);-- const { state } = view;- view.dispatch(state.tr.delete(0, state.doc.content.size));return true;}return false;@@ -164,10 +161,5 @@ export const useAiChatEditor = () => {onBrowserEvent: handleRestoreEditorContent,});- const handleSendAndClear = () => {- dispatchBrowserEvent(AGENT_CHAT_SEND_MESSAGE_EVENT_NAME);- editor?.commands.clearContent();- };-- return { editor, handleSendAndClear };+ return { editor };};diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatFileUpload.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatFileUpload.tsindex 5064226e678..9565ea4d76c 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatFileUpload.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatFileUpload.ts@@ -23,9 +23,20 @@ export const useAiChatFileUpload = () => {const store = useStore();const sendFile = async (file: File): Promise<AgentChatFileUIPart | null> => {+ const abortController = new AbortController();+ const unsubscribeFromSelectedFiles = store.sub(+ agentChatSelectedFilesState.atom,+ () => {+ if (!store.get(agentChatSelectedFilesState.atom).includes(file)) {+ abortController.abort();+ }+ },+ );+try {const uploadedFile = await directUploadFile(file, {fileFolder: FileFolder.AgentChat,+ signal: abortController.signal,});if (!store.get(agentChatSelectedFilesState.atom).includes(file)) {@@ -41,12 +52,17 @@ export const useAiChatFileUpload = () => {};} catch {const fileName = file.name;- enqueueToast({- status: 'error',- children: t`Failed to upload file: ${fileName}`,- });++ if (!abortController.signal.aborted) {+ enqueueToast({+ status: 'error',+ children: t`Failed to upload file: ${fileName}`,+ });+ }+return null;} finally {+ unsubscribeFromSelectedFiles();setAgentChatSelectedFiles((previousSelectedFiles) =>previousSelectedFiles.filter((selectedFile) => selectedFile !== file),);