Skip to content

The open alternative to Salesforce, designed for AI.

Fix the chat focus crash and give the preprompt effect the suggested prompts (#25017)

Félix Malfaitdf2631e713a7
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatPrepromptEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatPrepromptEffect.tsx
index 640b7474f29..2fdd688feb2 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatPrepromptEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatPrepromptEffect.tsx
@@ -4,14 +4,17 @@ import { isDefined } from 'twenty-shared/utils';
import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';
import { AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME } from '@/ai/constants/AgentChatRestoreEditorContentEventName';
import { agentChatPrepromptState } from '@/ai/states/agentChatPrepromptState';
+import { shouldFocusChatEditorState } from '@/ai/states/shouldFocusChatEditorState';
import { dispatchAgentChatSendMessageEvent } from '@/ai/utils/dispatchAgentChatSendMessageEvent';
import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEvent';
import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
+import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
export const AgentChatPrepromptEffect = () => {
const [agentChatPreprompt, setAgentChatPreprompt] = useAtomState(
agentChatPrepromptState,
);
+ const setShouldFocusChatEditor = useSetAtomState(shouldFocusChatEditorState);
useEffect(() => {
if (!isDefined(agentChatPreprompt)) {
@@ -30,13 +33,14 @@ export const AgentChatPrepromptEffect = () => {
dispatchBrowserEvent(AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME, {
content: serializePlainTextAsAdvancedTextEditorDocument(text),
});
+ setShouldFocusChatEditor(true);
}
setAgentChatPreprompt(null);
}, 0);
return () => clearTimeout(timeoutId);
- }, [agentChatPreprompt, setAgentChatPreprompt]);
+ }, [agentChatPreprompt, setAgentChatPreprompt, setShouldFocusChatEditor]);
return null;
};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
index 0ffba71abde..0f447bb1ab8 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
@@ -171,7 +171,7 @@ export const AiChatEditorSection = () => {
return (
<>
<AiChatEditorFocusEffect editor={editor} />
- <AiChatEmptyState editor={editor} isCentered={isComposerCentered} />
+ <AiChatEmptyState isCentered={isComposerCentered} />
<AiChatStandaloneError />
<AiChatSkeletonLoader />
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx
index 3ed1682796f..1d4461f50ff 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx
@@ -1,5 +1,4 @@
import { styled } from '@linaria/react';
-import { type Editor } from '@tiptap/react';
import { AiChatSuggestedPrompts } from '@/ai/components/suggested-prompts/AiChatSuggestedPrompts';
import { useShouldShowAiChatEmptyState } from '@/ai/hooks/useShouldShowAiChatEmptyState';
@@ -12,12 +11,10 @@ const StyledEmptyState = styled.div`
`;
type AiChatEmptyStateProps = {
- editor: Editor | null;
isCentered?: boolean;
};
export const AiChatEmptyState = ({
- editor,
isCentered = false,
}: AiChatEmptyStateProps) => {
const shouldShowAiChatEmptyState = useShouldShowAiChatEmptyState();
@@ -28,7 +25,7 @@ export const AiChatEmptyState = ({
return (
<StyledEmptyState>
- <AiChatSuggestedPrompts editor={editor} isCentered={isCentered} />
+ <AiChatSuggestedPrompts isCentered={isCentered} />
</StyledEmptyState>
);
};
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatPrepromptEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatPrepromptEffect.test.tsx
new file mode 100644
index 00000000000..d218e04ad50
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatPrepromptEffect.test.tsx
@@ -0,0 +1,80 @@
+import { act, render } from '@testing-library/react';
+import { Provider as JotaiProvider } from 'jotai';
+import { type ReactNode } from 'react';
+
+import { AgentChatPrepromptEffect } from '@/ai/components/AgentChatPrepromptEffect';
+import { AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME } from '@/ai/constants/AgentChatRestoreEditorContentEventName';
+import { AGENT_CHAT_SEND_MESSAGE_EVENT_NAME } from '@/ai/constants/AgentChatSendMessageEventName';
+import { agentChatPrepromptState } from '@/ai/states/agentChatPrepromptState';
+import { shouldFocusChatEditorState } from '@/ai/states/shouldFocusChatEditorState';
+import {
+ jotaiStore,
+ resetJotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
+
+const Wrapper = ({ children }: { children: ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>
+);
+
+const listenToEvent = (eventName: string) => {
+ const listener = jest.fn();
+ window.addEventListener(eventName, listener);
+
+ return listener;
+};
+
+describe('AgentChatPrepromptEffect', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ jest.useFakeTimers();
+ resetJotaiStore();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('should send the preprompt and clear the composer in SEND mode', () => {
+ const sendListener = listenToEvent(AGENT_CHAT_SEND_MESSAGE_EVENT_NAME);
+ const restoreListener = listenToEvent(
+ AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME,
+ );
+ jotaiStore.set(agentChatPrepromptState.atom, {
+ text: 'What can you do?',
+ mode: 'SEND',
+ });
+
+ render(<AgentChatPrepromptEffect />, { wrapper: Wrapper });
+ act(() => {
+ jest.runAllTimers();
+ });
+
+ expect(sendListener).toHaveBeenCalled();
+ expect(restoreListener.mock.calls[0][0].detail).toEqual({ content: '' });
+ expect(jotaiStore.get(shouldFocusChatEditorState.atom)).toBe(false);
+ expect(jotaiStore.get(agentChatPrepromptState.atom)).toBeNull();
+ });
+
+ it('should fill the composer and ask for focus in PREFILL mode', () => {
+ const sendListener = listenToEvent(AGENT_CHAT_SEND_MESSAGE_EVENT_NAME);
+ const restoreListener = listenToEvent(
+ AGENT_CHAT_RESTORE_EDITOR_CONTENT_EVENT_NAME,
+ );
+ jotaiStore.set(agentChatPrepromptState.atom, {
+ text: 'Create a workflow that ',
+ mode: 'PREFILL',
+ });
+
+ render(<AgentChatPrepromptEffect />, { wrapper: Wrapper });
+ act(() => {
+ jest.runAllTimers();
+ });
+
+ expect(sendListener).not.toHaveBeenCalled();
+ expect(restoreListener.mock.calls[0][0].detail.content).toContain(
+ 'Create a workflow that ',
+ );
+ expect(jotaiStore.get(shouldFocusChatEditorState.atom)).toBe(true);
+ expect(jotaiStore.get(agentChatPrepromptState.atom)).toBeNull();
+ });
+});
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 111af04fbca..981b26c462e 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
@@ -39,7 +39,7 @@ describe('AiChatEmptyState', () => {
});
it('should render the suggested prompts when there is no message, no error and nothing loading', () => {
- const { getByTestId } = render(<AiChatEmptyState editor={null} />, {
+ const { getByTestId } = render(<AiChatEmptyState />, {
wrapper: Wrapper,
});
@@ -55,7 +55,7 @@ describe('AiChatEmptyState', () => {
true,
);
- const { container } = render(<AiChatEmptyState editor={null} />, {
+ const { container } = render(<AiChatEmptyState />, {
wrapper: Wrapper,
});
@@ -71,7 +71,7 @@ describe('AiChatEmptyState', () => {
true,
);
- const { container } = render(<AiChatEmptyState editor={null} />, {
+ const { container } = render(<AiChatEmptyState />, {
wrapper: Wrapper,
});
diff --git a/packages/twenty-front/src/modules/ai/components/internal/AiChatEditorFocusEffect.tsx b/packages/twenty-front/src/modules/ai/components/internal/AiChatEditorFocusEffect.tsx
index aa65b180495..6c0823994cd 100644
--- a/packages/twenty-front/src/modules/ai/components/internal/AiChatEditorFocusEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/internal/AiChatEditorFocusEffect.tsx
@@ -1,5 +1,6 @@
import { type Editor } from '@tiptap/react';
import { useLayoutEffect } from 'react';
+import { isDefined } from 'twenty-shared/utils';
import { shouldFocusChatEditorState } from '@/ai/states/shouldFocusChatEditorState';
import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
@@ -16,7 +17,10 @@ export const AiChatEditorFocusEffect = ({
);
useLayoutEffect(() => {
- if (!shouldFocusChatEditor || !editor) {
+ // An editor destroyed while its replacement mounts is still defined here,
+ // and reading its commands throws. Leaving the request set hands the focus
+ // to the live editor instead.
+ if (!shouldFocusChatEditor || !isDefined(editor) || editor.isDestroyed) {
return;
}
diff --git a/packages/twenty-front/src/modules/ai/components/internal/__tests__/AiChatEditorFocusEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/internal/__tests__/AiChatEditorFocusEffect.test.tsx
new file mode 100644
index 00000000000..049eee4c3e2
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/internal/__tests__/AiChatEditorFocusEffect.test.tsx
@@ -0,0 +1,62 @@
+import { render } from '@testing-library/react';
+import { Editor } from '@tiptap/core';
+import { Document } from '@tiptap/extension-document';
+import { Paragraph } from '@tiptap/extension-paragraph';
+import { Text } from '@tiptap/extension-text';
+import { Provider as JotaiProvider } from 'jotai';
+import { type ReactNode } from 'react';
+
+import { AiChatEditorFocusEffect } from '@/ai/components/internal/AiChatEditorFocusEffect';
+import { shouldFocusChatEditorState } from '@/ai/states/shouldFocusChatEditorState';
+import {
+ jotaiStore,
+ resetJotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
+
+const Wrapper = ({ children }: { children: ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>
+);
+
+// Whether the caret lands is tiptap's business and jsdom does not carry it, so
+// these assert what the effect owns: which editor gets to consume the request.
+describe('AiChatEditorFocusEffect', () => {
+ let editor: Editor;
+
+ beforeEach(() => {
+ resetJotaiStore();
+ jotaiStore.set(shouldFocusChatEditorState.atom, true);
+ editor = new Editor({ extensions: [Document, Paragraph, Text] });
+ });
+
+ afterEach(() => {
+ if (!editor.isDestroyed) {
+ editor.destroy();
+ }
+ });
+
+ it('should consume the request on a live editor', () => {
+ render(<AiChatEditorFocusEffect editor={editor} />, { wrapper: Wrapper });
+
+ expect(jotaiStore.get(shouldFocusChatEditorState.atom)).toBe(false);
+ });
+
+ it('should leave the request for the next editor when the current one is destroyed', () => {
+ editor.destroy();
+
+ // The crash this guards against: tiptap throws from the commands getter
+ // once the view is gone, so a destroyed editor cannot simply be focused.
+ expect(() => editor.commands).toThrow();
+
+ expect(() =>
+ render(<AiChatEditorFocusEffect editor={editor} />, { wrapper: Wrapper }),
+ ).not.toThrow();
+
+ expect(jotaiStore.get(shouldFocusChatEditorState.atom)).toBe(true);
+ });
+
+ it('should keep the request while no editor is mounted', () => {
+ render(<AiChatEditorFocusEffect editor={null} />, { wrapper: Wrapper });
+
+ expect(jotaiStore.get(shouldFocusChatEditorState.atom)).toBe(true);
+ });
+});
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 4bd478d8a59..2f9e39005fd 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
@@ -1,23 +1,16 @@
import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
import { useLingui } from '@lingui/react/macro';
-import { type Editor } from '@tiptap/react';
import { Button, LightButton } from 'twenty-ui/input';
import { themeCssVariables } from 'twenty-ui/theme-constants';
-import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';
import { getAiChatSuggestedPrompts } from '@/ai/components/suggested-prompts/getAiChatSuggestedPrompts';
import { useAiChatSuggestedPromptsContext } from '@/ai/hooks/useAiChatSuggestedPromptsContext';
-import {
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- agentChatDraftsByThreadIdState,
-} from '@/ai/states/agentChatDraftsByThreadIdState';
-import { agentChatInputState } from '@/ai/states/agentChatInputState';
+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 { dispatchAgentChatSendMessageEvent } from '@/ai/utils/dispatchAgentChatSendMessageEvent';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
const StyledContainer = styled.div<{ isCentered: boolean }>`
align-items: ${({ isCentered }) => (isCentered ? 'center' : 'stretch')};
@@ -59,19 +52,14 @@ const pickRandom = <T,>(items: T[]): T =>
items[Math.floor(Math.random() * items.length)];
type AiChatSuggestedPromptsProps = {
- editor: Editor | null;
isCentered?: boolean;
};
export const AiChatSuggestedPrompts = ({
- editor,
isCentered = false,
}: AiChatSuggestedPromptsProps) => {
const { t: resolveMessage } = useLingui();
- const setAgentChatInput = useSetAtomState(agentChatInputState);
- const setAgentChatDraftsByThreadId = useSetAtomState(
- agentChatDraftsByThreadIdState,
- );
+ const { stageAiChatPreprompt } = useStageAiChatPreprompt();
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
const aiChatSuggestedPromptsContext = useAiChatSuggestedPromptsContext();
@@ -80,28 +68,11 @@ export const AiChatSuggestedPrompts = ({
);
const handleClick = (suggestedPrompt: SuggestedPrompt) => {
- const text = resolveMessage(pickRandom(suggestedPrompt.prompts));
-
- if (suggestedPrompt.mode === 'SEND') {
- // Sending reads the draft rather than the editor, so it has to be written
- // before the event is dispatched.
- setAgentChatDraftsByThreadId((previousDrafts) => ({
- ...previousDrafts,
- [currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY]:
- serializePlainTextAsAdvancedTextEditorDocument(text),
- }));
- dispatchAgentChatSendMessageEvent();
- editor?.commands.clearContent();
-
- return;
- }
-
- setAgentChatInput(text);
- editor?.commands.setContent({
- type: 'doc',
- content: [{ type: 'paragraph', content: [{ type: 'text', text }] }],
+ stageAiChatPreprompt({
+ text: resolveMessage(pickRandom(suggestedPrompt.prompts)),
+ mode: suggestedPrompt.mode ?? 'PREFILL',
+ draftKey: currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
});
- editor?.commands.focus('end');
};
return (
diff --git a/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts b/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts
index 628b69c2c8f..879025d012d 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts
@@ -1,15 +1,9 @@
import { isDefined } from 'twenty-shared/utils';
+import { useStageAiChatPreprompt } from '@/ai/hooks/useStageAiChatPreprompt';
import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';
-import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';
-import {
- AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
- agentChatDraftsByThreadIdState,
-} from '@/ai/states/agentChatDraftsByThreadIdState';
-import {
- type AgentChatPrepromptMode,
- agentChatPrepromptState,
-} from '@/ai/states/agentChatPrepromptState';
+import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
+import { type AgentChatPrepromptMode } from '@/ai/states/agentChatPrepromptState';
import { agentChatUserSelectedModelState } from '@/ai/states/agentChatUserSelectedModelState';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
@@ -19,11 +13,8 @@ export type AgentChatModelPreselection = 'FAST' | 'SMART';
export const useOpenAskAiPageWithPreprompt = () => {
const { switchToNewChat } = useSwitchToNewAiChat();
+ const { stageAiChatPreprompt } = useStageAiChatPreprompt();
const currentWorkspace = useAtomStateValue(currentWorkspaceState);
- const setAgentChatDraftsByThreadId = useSetAtomState(
- agentChatDraftsByThreadIdState,
- );
- const setAgentChatPreprompt = useSetAtomState(agentChatPrepromptState);
const setAgentChatUserSelectedModel = useSetAtomState(
agentChatUserSelectedModelState,
);
@@ -47,12 +38,11 @@ export const useOpenAskAiPageWithPreprompt = () => {
);
}
- setAgentChatDraftsByThreadId((prev) => ({
- ...prev,
- [AGENT_CHAT_NEW_THREAD_DRAFT_KEY]:
- serializePlainTextAsAdvancedTextEditorDocument(text),
- }));
- setAgentChatPreprompt({ text, mode });
+ stageAiChatPreprompt({
+ text,
+ mode,
+ draftKey: AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
+ });
};
return { openAskAiPageWithPreprompt };
diff --git a/packages/twenty-front/src/modules/ai/hooks/useStageAiChatPreprompt.ts b/packages/twenty-front/src/modules/ai/hooks/useStageAiChatPreprompt.ts
new file mode 100644
index 00000000000..183f5d46751
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/hooks/useStageAiChatPreprompt.ts
@@ -0,0 +1,35 @@
+import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';
+import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';
+import {
+ type AgentChatPrepromptMode,
+ agentChatPrepromptState,
+} from '@/ai/states/agentChatPrepromptState';
+import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
+
+// Staging a preprompt is always these two steps: sending reads the draft rather
+// than the editor, so the draft has to be written before AgentChatPrepromptEffect
+// picks the preprompt up.
+export const useStageAiChatPreprompt = () => {
+ const setAgentChatDraftsByThreadId = useSetAtomState(
+ agentChatDraftsByThreadIdState,
+ );
+ const setAgentChatPreprompt = useSetAtomState(agentChatPrepromptState);
+
+ const stageAiChatPreprompt = ({
+ text,
+ mode,
+ draftKey,
+ }: {
+ text: string;
+ mode: AgentChatPrepromptMode;
+ draftKey: string;
+ }) => {
+ setAgentChatDraftsByThreadId((previousDrafts) => ({
+ ...previousDrafts,
+ [draftKey]: serializePlainTextAsAdvancedTextEditorDocument(text),
+ }));
+ setAgentChatPreprompt({ text, mode });
+ };
+
+ return { stageAiChatPreprompt };
+};