Skip to content

The open alternative to Salesforce, designed for AI.

Animate the first AI chat message out of the composer (#26890)

Thomas des Francs34c1db9a1dca
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
index e234464bf42..c64b0ab8eb4 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
@@ -24,6 +24,7 @@ import { AiChatDictationEffect } from '@/ai/dictation/components/AiChatDictation
import { AiChatDictationHint } from '@/ai/dictation/components/AiChatDictationHint';
import { AiChatContextUsageButton } from '@/ai/components/internal/AiChatContextUsageButton';
import { AiChatEditorFocusEffect } from '@/ai/components/internal/AiChatEditorFocusEffect';
+import { AiChatSentMessageHandOffEffect } from '@/ai/components/internal/AiChatSentMessageHandOffEffect';
import { SendMessageButton } from '@/ai/components/internal/SendMessageButton';
import { useAiChatEditor } from '@/ai/hooks/useAiChatEditor';
import { useInsertDictatedText } from '@/ai/dictation/hooks/useInsertDictatedText';
@@ -32,9 +33,11 @@ import { useHasReachedAiChatCreditsCap } from '@/ai/hooks/useHasReachedAiChatCre
import { useHasReachedAiChatUsageLimit } from '@/ai/hooks/useHasReachedAiChatUsageLimit';
import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
+import { agentChatHasMessageComponentSelector } from '@/ai/states/selectors/agentChatHasMessageComponentSelector';
import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';
import { aiModelsState } from '@/client-config/states/aiModelsState';
import { useIsMobile } from 'twenty-ui/utilities';
+import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';
import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
@@ -109,13 +112,21 @@ const StyledEditorWrapper = styled.div<{ isMobile: boolean }>`
}
`;
+const StyledMessageListPlaceholder = styled.div`
+ display: flex;
+ flex: 1;
+ flex-direction: column;
+`;
+
// Collapsing this spacer is what slides the composer from the middle of an
// empty page down to the bottom once the conversation starts.
const StyledComposerBottomSpacer = styled.div`
flex-basis: 0;
flex-grow: 0;
flex-shrink: 0;
- transition-duration: calc(${themeCssVariables.animation.duration.fast} * 1s);
+ transition-duration: calc(
+ ${themeCssVariables.animation.duration.normal} * 1s
+ );
transition-property: flex-grow;
transition-timing-function: ease-out;
@@ -175,7 +186,6 @@ const EditableAiChatEditorSection = () => {
{ objectName: CoreObjectNameSingular.InputAsk, objectNameType: 'singular' },
);
const pendingAskThreadId =
- isDefined(inputAskObjectMetadataItem) &&
isDefined(agentChatDisplayedThread) &&
agentChatDisplayedThread !== AGENT_CHAT_NEW_THREAD_DRAFT_KEY
? agentChatDisplayedThread
@@ -206,16 +216,27 @@ const EditableAiChatEditorSection = () => {
</StyledButtonsContainer>
</StyledInputBox>
);
+ const hasMessages = useAtomComponentSelectorValue(
+ agentChatHasMessageComponentSelector,
+ );
return (
<>
<AiChatEditorFocusEffect editor={editor} />
+ <AiChatSentMessageHandOffEffect
+ editor={editor}
+ isComposerCentered={isComposerCentered}
+ />
<AiChatDictationEffect
onInterimText={setDictationInterimText}
onFinalText={insertDictatedText}
/>
- <AiChatEmptyState isCentered={isComposerCentered} />
- <AiChatStandaloneError />
+ {!hasMessages && (
+ <StyledMessageListPlaceholder>
+ <AiChatEmptyState isCentered={isComposerCentered} />
+ <AiChatStandaloneError />
+ </StyledMessageListPlaceholder>
+ )}
<StyledInputArea isMobile={isMobile}>
<AgentChatContextPreview />
@@ -226,7 +247,7 @@ const EditableAiChatEditorSection = () => {
)}
{hasReachedAiChatCreditsCap && <AIChatNoMoreBillingCreditsBanner />}
{shouldShowUsageLimitBanner && <AiChatUsageLimitReachedBanner />}
- {isDefined(pendingAskThreadId) ? (
+ {isDefined(inputAskObjectMetadataItem) ? (
<AiChatPendingAskGate threadId={pendingAskThreadId}>
{composer}
</AiChatPendingAskGate>
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx
index c0ed67b4d97..8e9e89eccb2 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx
@@ -1,3 +1,4 @@
+import { MarkdownRenderer } from '@/ai/components/MarkdownRenderer';
import { StyledAiChatContentContainer } from '@/ai/components/StyledAiChatContentContainer';
import { styled } from '@linaria/react';
@@ -20,6 +21,8 @@ export const AiChatEmptyState = ({
}: AiChatEmptyStateProps) => {
const shouldShowAiChatEmptyState = useShouldShowAiChatEmptyState();
+ MarkdownRenderer.preload();
+
if (!shouldShowAiChatEmptyState) {
return null;
}
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx b/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx
index 041b39d1bea..ada593a7897 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx
@@ -1,8 +1,10 @@
import { useLingui } from '@lingui/react/macro';
import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';
import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';
+import { useAiChatSentMessageHandOff } from '@/ai/hooks/useAiChatSentMessageHandOff';
import { useIsCurrentAiChatThreadReadOnly } from '@/ai/hooks/useIsCurrentAiChatThreadReadOnly';
import { styled } from '@linaria/react';
+import { type ReactNode } from 'react';
import { AgentChatFilePreview } from '@/ai/components/internal/AgentChatFilePreview';
import { AgentMessageRole } from '@/ai/constants/AgentMessageRole';
@@ -147,6 +149,24 @@ const StyledFilesContainer = styled.div`
margin-top: ${themeCssVariables.spacing[2]};
`;
+type AiChatUserMessageTextProps = {
+ messageId: string;
+ children: ReactNode;
+};
+
+const AiChatUserMessageText = ({
+ messageId,
+ children,
+}: AiChatUserMessageTextProps) => {
+ const sentMessageHandOffRef = useAiChatSentMessageHandOff(messageId);
+
+ return (
+ <StyledMessageText isUser ref={sentMessageHandOffRef}>
+ {children}
+ </StyledMessageText>
+ );
+};
+
type AiChatMessageProps = {
messageId: string;
isLastMessageStreaming?: boolean;
@@ -194,6 +214,13 @@ export const AiChatMessage = ({
const shouldShowError = isDefined(error) && isLastAssistantMessage;
const fileParts = agentChatMessage.parts.filter(isExtendedFileUIPart);
+ const messageContent = (
+ <AiChatAssistantMessageRenderer
+ isLastMessageStreaming={isLastMessageStreaming}
+ messageParts={agentChatMessage.parts}
+ hasError={shouldShowError}
+ />
+ );
return (
<StyledMessageBubble isUser={isUser}>
@@ -201,13 +228,13 @@ export const AiChatMessage = ({
<StyledSender>{senderLabel}</StyledSender>
)}
<StyledMessageContainer isUser={isUser}>
- <StyledMessageText isUser={isUser}>
- <AiChatAssistantMessageRenderer
- isLastMessageStreaming={isLastMessageStreaming}
- messageParts={agentChatMessage.parts}
- hasError={shouldShowError}
- />
- </StyledMessageText>
+ {isUser ? (
+ <AiChatUserMessageText messageId={messageId}>
+ {messageContent}
+ </AiChatUserMessageText>
+ ) : (
+ <StyledMessageText>{messageContent}</StyledMessageText>
+ )}
{fileParts.length > 0 && (
<StyledFilesContainer>
{fileParts.map((file) => (
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx
index 07a7a2acb86..9f5582e16cf 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx
@@ -21,7 +21,7 @@ const StyledWaitingCount = styled.span`
`;
type AiChatPendingAskGateProps = {
- threadId: string;
+ threadId: string | null;
children: ReactNode;
};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatTab.tsx b/packages/twenty-front/src/modules/ai/components/AiChatTab.tsx
index 3eb0e1cc1d2..4f7899bbcb1 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatTab.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatTab.tsx
@@ -11,9 +11,9 @@ import { AgentChatHasBeenOpenedEffect } from '@/ai/components/AgentChatHasBeenOp
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 { threadIdCreatedFromDraftState } from '@/ai/states/threadIdCreatedFromDraftState';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { AiChatQueuedMessages } from '@/ai/components/AiChatQueuedMessages';
@@ -33,15 +33,10 @@ export const AiChatTab = () => {
const isWorkspaceSetupChat = useIsWorkspaceSetupChat();
const [isDraggingFile, setIsDraggingFile] = useState(false);
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
- const threadIdCreatedFromDraft = useAtomStateValue(
- threadIdCreatedFromDraftState,
- );
- const draftKey = currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
- const editorSectionKey =
- draftKey !== AGENT_CHAT_NEW_THREAD_DRAFT_KEY &&
- draftKey === threadIdCreatedFromDraft
- ? AGENT_CHAT_NEW_THREAD_DRAFT_KEY
- : draftKey;
+ const isOnNewAiChatSlot = useIsOnNewAiChatSlot();
+ const editorSectionKey = isOnNewAiChatSlot
+ ? AGENT_CHAT_NEW_THREAD_DRAFT_KEY
+ : (currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY);
const { uploadFiles } = useAiChatFileUpload();
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatTabMessageList.tsx b/packages/twenty-front/src/modules/ai/components/AiChatTabMessageList.tsx
index f3a45c4352d..83d2104bc33 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatTabMessageList.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatTabMessageList.tsx
@@ -74,9 +74,11 @@ export const AiChatTabMessageList = () => {
>
<Suspense
fallback={
- <StyledMessageListContent>
- <MarkdownLoadingSkeleton />
- </StyledMessageListContent>
+ <StyledScrollWrapperContainer>
+ <StyledMessageListContent>
+ <MarkdownLoadingSkeleton />
+ </StyledMessageListContent>
+ </StyledScrollWrapperContainer>
}
>
<StyledScrollWrapperContainer>
diff --git a/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx b/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx
index 24d0c893946..a7b3111e9eb 100644
--- a/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx
+++ b/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx
@@ -1,141 +1,16 @@
import { SKELETON_LOADER_HEIGHT_SIZES } from '@/activities/components/SkeletonLoader';
import {
StyledMarkdownContainer,
- StyledParagraph,
StyledSkeletonContainer,
- StyledTableScrollContainer,
} from '@/ai/components/LazyMarkdownRendererStyledComponents';
-import { MarkdownCodeBlock } from '@/ai/components/MarkdownCodeBlock';
-import { TextWithChatReferences } from '@/ai/components/TextWithChatReferences';
+import { MarkdownRenderer } from '@/ai/components/MarkdownRenderer';
import { EMPTY_MARKDOWN_BLOCK_SPLIT_CACHE } from '@/ai/constants/EmptyMarkdownBlockSplitCache';
import { getMarkdownBlocksIncrementally } from '@/ai/utils/getMarkdownBlocksIncrementally';
import { protectChatReferencesForMarkdown } from '@/ai/utils/protectChatReferencesForMarkdown';
-import {
- cloneElement,
- isValidElement,
- lazy,
- memo,
- Suspense,
- useRef,
-} from 'react';
+import { memo, Suspense, useRef } from 'react';
import Skeleton, { SkeletonTheme } from 'react-loading-skeleton';
-import { getSafeUrl, isDefined } from 'twenty-shared/utils';
import { useTheme } from 'twenty-ui/theme';
-const processChildrenForChatReferences = (
- children: React.ReactNode,
-): React.ReactNode => {
- if (typeof children === 'string') {
- return <TextWithChatReferences text={children} />;
- }
-
- if (Array.isArray(children)) {
- return children.map((child, index) => (
- <span key={index}>{processChildrenForChatReferences(child)}</span>
- ));
- }
-
- if (isValidElement<{ children?: React.ReactNode }>(children)) {
- const childProps = children.props;
-
- if (isDefined(childProps.children)) {
- return cloneElement(children, {
- children: processChildrenForChatReferences(childProps.children),
- });
- }
- }
-
- return children;
-};
-
-const createChatReferenceElement =
- (Element: React.ElementType) =>
- ({ children }: { children?: React.ReactNode }) => (
- <Element>{processChildrenForChatReferences(children)}</Element>
- );
-
-// react-markdown uses each entry as the JSX element type, so rebuilding this map
-// per render would remount every node on every streamed chunk.
-const MARKDOWN_COMPONENTS = {
- table: ({ children }: { children?: React.ReactNode }) => (
- <StyledTableScrollContainer>
- <table>{children}</table>
- </StyledTableScrollContainer>
- ),
- p: createChatReferenceElement(StyledParagraph),
- td: createChatReferenceElement('td'),
- th: createChatReferenceElement('th'),
- li: createChatReferenceElement('li'),
- h1: createChatReferenceElement('h1'),
- h2: createChatReferenceElement('h2'),
- h3: createChatReferenceElement('h3'),
- h4: createChatReferenceElement('h4'),
- h5: createChatReferenceElement('h5'),
- h6: createChatReferenceElement('h6'),
- a: ({
- children,
- href,
- title,
- }: {
- children?: React.ReactNode;
- href?: string;
- title?: string;
- }) => (
- <a
- className="markdown-link"
- href={getSafeUrl(href)}
- title={title}
- target="_blank"
- rel="noopener noreferrer"
- >
- {processChildrenForChatReferences(children)}
- </a>
- ),
- code: ({
- className,
- children,
- }: {
- className?: string;
- children?: React.ReactNode;
- }) => <code className={className}>{children}</code>,
- pre: ({ children }: { children?: React.ReactNode }) => (
- <MarkdownCodeBlock>{children}</MarkdownCodeBlock>
- ),
-};
-
-const MARKDOWN_COMPONENTS_WITHOUT_IMAGES = {
- ...MARKDOWN_COMPONENTS,
- img: () => null,
-};
-
-const MarkdownRenderer = lazy(async () => {
- const [{ default: Markdown }, { default: remarkGfm }] = await Promise.all([
- import('react-markdown'),
- import('remark-gfm'),
- ]);
-
- const remarkPlugins = [remarkGfm];
-
- return {
- default: ({
- children,
- noImage,
- }: {
- children: string;
- noImage?: boolean;
- }) => (
- <Markdown
- remarkPlugins={remarkPlugins}
- components={
- noImage ? MARKDOWN_COMPONENTS_WITHOUT_IMAGES : MARKDOWN_COMPONENTS
- }
- >
- {children}
- </Markdown>
- ),
- };
-});
-
export const MarkdownLoadingSkeleton = () => {
const theme = useTheme();
return (
diff --git a/packages/twenty-front/src/modules/ai/components/MarkdownRenderer.tsx b/packages/twenty-front/src/modules/ai/components/MarkdownRenderer.tsx
new file mode 100644
index 00000000000..024fbb92422
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/MarkdownRenderer.tsx
@@ -0,0 +1,124 @@
+import {
+ StyledParagraph,
+ StyledTableScrollContainer,
+} from '@/ai/components/LazyMarkdownRendererStyledComponents';
+import { MarkdownCodeBlock } from '@/ai/components/MarkdownCodeBlock';
+import { TextWithChatReferences } from '@/ai/components/TextWithChatReferences';
+import { cloneElement, isValidElement } from 'react';
+import { getSafeUrl, isDefined } from 'twenty-shared/utils';
+import { lazyWithPreload } from '~/utils/lazyWithPreload';
+
+const processChildrenForChatReferences = (
+ children: React.ReactNode,
+): React.ReactNode => {
+ if (typeof children === 'string') {
+ return <TextWithChatReferences text={children} />;
+ }
+
+ if (Array.isArray(children)) {
+ return children.map((child, index) => (
+ <span key={index}>{processChildrenForChatReferences(child)}</span>
+ ));
+ }
+
+ if (isValidElement<{ children?: React.ReactNode }>(children)) {
+ const childProps = children.props;
+
+ if (isDefined(childProps.children)) {
+ return cloneElement(children, {
+ children: processChildrenForChatReferences(childProps.children),
+ });
+ }
+ }
+
+ return children;
+};
+
+const createChatReferenceElement =
+ (Element: React.ElementType) =>
+ ({ children }: { children?: React.ReactNode }) => (
+ <Element>{processChildrenForChatReferences(children)}</Element>
+ );
+
+// react-markdown uses each entry as the JSX element type, so rebuilding this map
+// per render would remount every node on every streamed chunk.
+const MARKDOWN_COMPONENTS = {
+ table: ({ children }: { children?: React.ReactNode }) => (
+ <StyledTableScrollContainer>
+ <table>{children}</table>
+ </StyledTableScrollContainer>
+ ),
+ p: createChatReferenceElement(StyledParagraph),
+ td: createChatReferenceElement('td'),
+ th: createChatReferenceElement('th'),
+ li: createChatReferenceElement('li'),
+ h1: createChatReferenceElement('h1'),
+ h2: createChatReferenceElement('h2'),
+ h3: createChatReferenceElement('h3'),
+ h4: createChatReferenceElement('h4'),
+ h5: createChatReferenceElement('h5'),
+ h6: createChatReferenceElement('h6'),
+ a: ({
+ children,
+ href,
+ title,
+ }: {
+ children?: React.ReactNode;
+ href?: string;
+ title?: string;
+ }) => (
+ <a
+ className="markdown-link"
+ href={getSafeUrl(href)}
+ title={title}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {processChildrenForChatReferences(children)}
+ </a>
+ ),
+ code: ({
+ className,
+ children,
+ }: {
+ className?: string;
+ children?: React.ReactNode;
+ }) => <code className={className}>{children}</code>,
+ pre: ({ children }: { children?: React.ReactNode }) => (
+ <MarkdownCodeBlock>{children}</MarkdownCodeBlock>
+ ),
+};
+
+const MARKDOWN_COMPONENTS_WITHOUT_IMAGES = {
+ ...MARKDOWN_COMPONENTS,
+ img: () => null,
+};
+
+type MarkdownRendererProps = {
+ children: string;
+ noImage?: boolean;
+};
+
+export const MarkdownRenderer = lazyWithPreload<MarkdownRendererProps>(
+ async () => {
+ const [{ default: Markdown }, { default: remarkGfm }] = await Promise.all([
+ import('react-markdown'),
+ import('remark-gfm'),
+ ]);
+
+ const remarkPlugins = [remarkGfm];
+
+ return {
+ default: ({ children, noImage }: MarkdownRendererProps) => (
+ <Markdown
+ remarkPlugins={remarkPlugins}
+ components={
+ noImage ? MARKDOWN_COMPONENTS_WITHOUT_IMAGES : MARKDOWN_COMPONENTS
+ }
+ >
+ {children}
+ </Markdown>
+ ),
+ };
+ },
+);
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
new file mode 100644
index 00000000000..03aff21a5c1
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.test.tsx
@@ -0,0 +1,95 @@
+import { i18n } from '@lingui/core';
+import { I18nProvider } from '@lingui/react';
+import { act, render, screen } from '@testing-library/react';
+import { Document } from '@tiptap/extension-document';
+import { Paragraph } from '@tiptap/extension-paragraph';
+import { Text } from '@tiptap/extension-text';
+import { Editor } from '@tiptap/react';
+import { type ReactNode } from 'react';
+
+import { AiChatEditorSection } from '@/ai/components/AiChatEditorSection';
+import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';
+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 { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
+import { getTestEnrichedObjectMetadataItemsMock } from '~/testing/utils/getTestEnrichedObjectMetadataItemsMock';
+
+const CREATED_THREAD_ID = '20202020-7c1e-4a0f-9d2b-3f4e5a6b7c8d';
+
+const useAiChatEditor = jest.fn();
+jest.mock('@/ai/hooks/useAiChatEditor', () => ({
+ useAiChatEditor: () => useAiChatEditor(),
+}));
+jest.mock('@/ai/hooks/useHasReachedAiChatUsageLimit', () => ({
+ useHasReachedAiChatUsageLimit: () => false,
+}));
+jest.mock('@/ai/components/AiChatStandaloneError', () => ({
+ AiChatStandaloneError: () => null,
+}));
+jest.mock('@/ai/components/AiChatPendingAskGate', () => ({
+ AiChatPendingAskGate: ({ children }: { children: ReactNode }) => children,
+}));
+
+const objectMetadataItems = getTestEnrichedObjectMetadataItemsMock();
+
+const renderEditorSectionOnNewChat = () => {
+ const MetadataAndApolloWrapper = getJestMetadataAndApolloMocksWrapper({
+ objectMetadataItems: [
+ ...objectMetadataItems,
+ {
+ ...objectMetadataItems[0],
+ id: '20202020-1b2c-4d3e-8f4a-5b6c7d8e9f0a',
+ nameSingular: 'inputAsk',
+ namePlural: 'inputAsks',
+ },
+ ],
+ onInitializeJotaiStore: (store) => {
+ store.set(currentAiChatThreadState.atom, AGENT_CHAT_NEW_THREAD_DRAFT_KEY);
+ store.set(
+ agentChatDisplayedThreadState.atom,
+ AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
+ );
+ },
+ });
+
+ return render(
+ <MetadataAndApolloWrapper>
+ <I18nProvider i18n={i18n}>
+ <AgentChatComponentInstanceContext.Provider
+ value={{ instanceId: 'agentChatComponentInstance' }}
+ >
+ <AiChatEditorSection />
+ </AgentChatComponentInstanceContext.Provider>
+ </I18nProvider>
+ </MetadataAndApolloWrapper>,
+ );
+};
+
+describe('AiChatEditorSection', () => {
+ let editor: Editor;
+
+ beforeEach(() => {
+ editor = new Editor({ extensions: [Document, Paragraph, Text] });
+ useAiChatEditor.mockReturnValue({ editor, handleSendAndClear: jest.fn() });
+ });
+
+ afterEach(() => {
+ editor.destroy();
+ });
+
+ it('keeps the composer mounted when typing the first message creates the thread', () => {
+ renderEditorSectionOnNewChat();
+ const sendButton = screen.getByRole('button', { name: /send/i });
+
+ act(() => {
+ jotaiStore.set(threadIdCreatedFromDraftState.atom, CREATED_THREAD_ID);
+ jotaiStore.set(currentAiChatThreadState.atom, CREATED_THREAD_ID);
+ jotaiStore.set(agentChatDisplayedThreadState.atom, CREATED_THREAD_ID);
+ });
+
+ expect(sendButton).toBeInTheDocument();
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/components/internal/AiChatSentMessageHandOffEffect.tsx b/packages/twenty-front/src/modules/ai/components/internal/AiChatSentMessageHandOffEffect.tsx
new file mode 100644
index 00000000000..fde4e7814c0
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/internal/AiChatSentMessageHandOffEffect.tsx
@@ -0,0 +1,48 @@
+import { type Editor } from '@tiptap/react';
+import { isNonEmptyString } from '@sniptt/guards';
+import { useStore } from 'jotai';
+import { isDefined } from 'twenty-shared/utils';
+
+import { AGENT_CHAT_SEND_MESSAGE_EVENT_NAME } from '@/ai/constants/AgentChatSendMessageEventName';
+import { agentChatSentMessageHandOffState } from '@/ai/states/agentChatSentMessageHandOffState';
+import { getTextBoundingClientRect } from '@/ai/utils/getTextBoundingClientRect';
+import { useListenToBrowserEvent } from '@/browser-event/hooks/useListenToBrowserEvent';
+
+type AiChatSentMessageHandOffEffectProps = {
+ editor: Editor | null;
+ isComposerCentered: boolean;
+};
+
+export const AiChatSentMessageHandOffEffect = ({
+ editor,
+ isComposerCentered,
+}: AiChatSentMessageHandOffEffectProps) => {
+ const store = useStore();
+
+ const handOffSentMessage = () => {
+ if (!isComposerCentered) {
+ store.set(agentChatSentMessageHandOffState.atom, null);
+ return;
+ }
+
+ if (
+ !isDefined(editor) ||
+ editor.isDestroyed ||
+ !isNonEmptyString(editor.getText().trim())
+ ) {
+ return;
+ }
+
+ store.set(agentChatSentMessageHandOffState.atom, {
+ composerTextRect: getTextBoundingClientRect(editor.view.dom),
+ messageId: null,
+ });
+ };
+
+ useListenToBrowserEvent({
+ eventName: AGENT_CHAT_SEND_MESSAGE_EVENT_NAME,
+ onBrowserEvent: handOffSentMessage,
+ });
+
+ return null;
+};
diff --git a/packages/twenty-front/src/modules/ai/components/internal/__tests__/AiChatSentMessageHandOffEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/internal/__tests__/AiChatSentMessageHandOffEffect.test.tsx
new file mode 100644
index 00000000000..73570b59dd9
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/internal/__tests__/AiChatSentMessageHandOffEffect.test.tsx
@@ -0,0 +1,77 @@
+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 { AiChatSentMessageHandOffEffect } from '@/ai/components/internal/AiChatSentMessageHandOffEffect';
+import { agentChatSentMessageHandOffState } from '@/ai/states/agentChatSentMessageHandOffState';
+import { dispatchAgentChatSendMessageEvent } from '@/ai/utils/dispatchAgentChatSendMessageEvent';
+import {
+ jotaiStore,
+ resetJotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
+
+const PENDING_HAND_OFF = {
+ composerTextRect: { left: 1, top: 2 },
+ messageId: null,
+};
+
+const Wrapper = ({ children }: { children: ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>
+);
+
+describe('AiChatSentMessageHandOffEffect', () => {
+ let editor: Editor;
+
+ beforeEach(() => {
+ resetJotaiStore();
+ jotaiStore.set(agentChatSentMessageHandOffState.atom, PENDING_HAND_OFF);
+ editor = new Editor({
+ element: document.createElement('div'),
+ extensions: [Document, Paragraph, Text],
+ });
+ });
+
+ afterEach(() => {
+ editor.destroy();
+ });
+
+ it.each([
+ {
+ description:
+ 'keeps the pending hand-off when Enter is pressed again on the emptied composer',
+ composerText: '',
+ isComposerCentered: true,
+ expectedHandOff: PENDING_HAND_OFF,
+ },
+ {
+ description:
+ 'drops the pending hand-off when a message is sent from the bottom composer',
+ composerText: 'Show my pipeline',
+ isComposerCentered: false,
+ expectedHandOff: null,
+ },
+ ])(
+ '$description',
+ ({ composerText, isComposerCentered, expectedHandOff }) => {
+ editor.commands.setContent(composerText);
+
+ render(
+ <AiChatSentMessageHandOffEffect
+ editor={editor}
+ isComposerCentered={isComposerCentered}
+ />,
+ { wrapper: Wrapper },
+ );
+
+ dispatchAgentChatSendMessageEvent();
+
+ expect(jotaiStore.get(agentChatSentMessageHandOffState.atom)).toEqual(
+ expectedHandOff,
+ );
+ },
+ );
+});
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 5181ae8250f..9435c3fc8d8 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
@@ -12,6 +12,7 @@ import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThr
import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
import { agentChatMessagesLoadingState } from '@/ai/states/agentChatMessagesLoadingState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
+import { threadIdCreatedFromDraftState } from '@/ai/states/threadIdCreatedFromDraftState';
import { type AiChatSurface } from '@/ai/types/AiChatSurface';
import {
jotaiStore,
@@ -77,6 +78,27 @@ 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');
+ const { result } = renderForSurface();
+
+ expect(result.current).toBe(true);
+
+ act(() =>
+ jotaiStore.set(
+ agentChatMessagesComponentFamilyState.atomFamily({
+ instanceId: INSTANCE_ID,
+ familyKey: { threadId: 'draft-thread' },
+ }),
+ [{ id: 'message-1', role: 'user', parts: [] }],
+ ),
+ );
+
+ expect(result.current).toBe(false);
+ });
+
it('does not center while the initial route has not selected a thread yet', () => {
jotaiStore.set(currentAiChatThreadState.atom, null);
const { result } = renderForSurface();
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
index 8a402c5cfa7..0b1d40a45dd 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts
@@ -36,6 +36,7 @@ import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/a
import { agentChatLastSentBrowsingContextFamilyState } from '@/ai/states/agentChatLastSentBrowsingContextFamilyState';
import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
import { agentChatSelectedFilesState } from '@/ai/states/agentChatSelectedFilesState';
+import { agentChatSentMessageHandOffState } from '@/ai/states/agentChatSentMessageHandOffState';
import { agentChatUploadedFilesState } from '@/ai/states/agentChatUploadedFilesState';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { getConversationTargetsFromSerializedDocument } from '@/ai/utils/getConversationTargetsFromSerializedDocument';
@@ -173,6 +174,11 @@ export const useAgentChat = (
const currentMessages = store.get(messagesAtom);
+ store.set(agentChatSentMessageHandOffState.atom, (sentMessageHandOff) =>
+ isDefined(sentMessageHandOff)
+ ? { ...sentMessageHandOff, messageId }
+ : null,
+ );
store.set(messagesAtom, [...currentMessages, optimisticUserMessage]);
store.set(errorAtom, null);
store.set(isAwaitingFirstChunkAtom, true);
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingAsks.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingAsks.ts
index 767b9438875..bf17071bed8 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingAsks.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingAsks.ts
@@ -28,7 +28,7 @@ type PendingInputAskRecord = ObjectRecord & {
export const useAgentChatPendingAsks = ({
threadId,
}: {
- threadId: string;
+ threadId: string | null;
}): AgentChatPendingAsk[] => {
const { objectMetadataItem: inputAskObjectMetadataItem } =
useObjectMetadataItem({
@@ -37,7 +37,7 @@ export const useAgentChatPendingAsks = ({
const filter = useMemo(
() => ({
- threadId: { eq: threadId },
+ threadId: { eq: threadId ?? '' },
status: { in: ['PENDING'] },
}),
[threadId],
@@ -49,6 +49,7 @@ export const useAgentChatPendingAsks = ({
orderBy: ORDER_BY_CREATION,
recordGqlFields: { id: true, toolCallId: true, form: true },
fetchPolicy: 'network-only',
+ skip: !isDefined(threadId),
});
const refetchPendingInputAsks = useCallback(async () => {
@@ -66,12 +67,14 @@ export const useAgentChatPendingAsks = ({
useListenToEventsForQuery({
queryId: `agent-chat-pending-input-ask-${threadId}`,
operationSignature,
+ skip: !isDefined(threadId),
onSseReconnected: refetchPendingInputAsks,
});
useListenToObjectRecordOperationBrowserEvent({
onObjectRecordOperationBrowserEvent: refetchPendingInputAsks,
objectMetadataItemId: inputAskObjectMetadataItem.id,
+ enabled: isDefined(threadId),
});
return useMemo(
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatSentMessageHandOff.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatSentMessageHandOff.ts
new file mode 100644
index 00000000000..aa8f055aa05
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatSentMessageHandOff.ts
@@ -0,0 +1,59 @@
+import { useReducedMotion } from 'framer-motion';
+import { useStore } from 'jotai';
+import { useCallback } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+import { useTheme } from 'twenty-ui/theme';
+
+import { agentChatSentMessageHandOffState } from '@/ai/states/agentChatSentMessageHandOffState';
+import { getTextBoundingClientRect } from '@/ai/utils/getTextBoundingClientRect';
+
+export const useAiChatSentMessageHandOff = (messageId: string) => {
+ const store = useStore();
+ const theme = useTheme();
+ const shouldReduceMotion = useReducedMotion();
+
+ return useCallback(
+ (messageTextElement: HTMLDivElement | null) => {
+ const sentMessageHandOff = store.get(
+ agentChatSentMessageHandOffState.atom,
+ );
+
+ if (
+ !isDefined(messageTextElement) ||
+ !isDefined(sentMessageHandOff) ||
+ sentMessageHandOff.messageId !== messageId
+ ) {
+ return;
+ }
+
+ store.set(agentChatSentMessageHandOffState.atom, null);
+
+ if (shouldReduceMotion) {
+ return;
+ }
+
+ requestAnimationFrame(() => {
+ if (!messageTextElement.isConnected) {
+ return;
+ }
+
+ const origin = sentMessageHandOff.composerTextRect;
+ const destination = getTextBoundingClientRect(messageTextElement);
+
+ messageTextElement.animate(
+ [
+ {
+ transform: `translate(${origin.left - destination.left}px, ${origin.top - destination.top}px)`,
+ },
+ { transform: 'none' },
+ ],
+ {
+ duration: theme.animation.duration.normal * 1000,
+ easing: 'ease-out',
+ },
+ );
+ });
+ },
+ [messageId, store, theme, shouldReduceMotion],
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts b/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts
index 1196478a641..c3d9af107b4 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts
@@ -49,6 +49,7 @@ export const useCreateAgentChatThread = () => {
if (store.get(isCreatingForFirstSendState.atom)) {
store.set(isCreatingForFirstSendState.atom, false);
+ store.set(threadIdCreatedFromDraftState.atom, newThread.id);
setIsCreatingChatThread(false);
return;
}
diff --git a/packages/twenty-front/src/modules/ai/hooks/useCurrentAiChatThreadAccess.ts b/packages/twenty-front/src/modules/ai/hooks/useCurrentAiChatThreadAccess.ts
index 6de8a6e334e..3d41b68085b 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useCurrentAiChatThreadAccess.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useCurrentAiChatThreadAccess.ts
@@ -1,28 +1,22 @@
-import { isDefined } from 'twenty-shared/utils';
-
+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';
import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
export const useCurrentAiChatThreadAccess = () => {
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
+ const isOnNewAiChatSlot = useIsOnNewAiChatSlot();
const permissions = useAtomFamilySelectorValue(
agentChatThreadPermissionsFamilySelector,
currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY,
);
- if (
- !isDefined(currentAiChatThread) ||
- currentAiChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY
- ) {
- return 'writer';
- }
- if (!isDefined(permissions?.canUpdate)) {
- return 'loading';
- }
- if (!permissions.canRead) {
- return 'unavailable';
- }
- return permissions.canUpdate ? 'writer' : 'viewer';
+
+ return getAiChatThreadAccess({
+ currentAiChatThread,
+ isOnNewAiChatSlot,
+ permissions,
+ });
};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useIsOnNewAiChatSlot.ts b/packages/twenty-front/src/modules/ai/hooks/useIsOnNewAiChatSlot.ts
new file mode 100644
index 00000000000..697e7f7fa35
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/hooks/useIsOnNewAiChatSlot.ts
@@ -0,0 +1,19 @@
+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 { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+
+export const useIsOnNewAiChatSlot = () => {
+ const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
+ const threadIdCreatedFromDraft = useAtomStateValue(
+ threadIdCreatedFromDraftState,
+ );
+
+ return (
+ currentAiChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY ||
+ (isDefined(threadIdCreatedFromDraft) &&
+ currentAiChatThread === threadIdCreatedFromDraft)
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useShouldShowAiChatEmptyState.ts b/packages/twenty-front/src/modules/ai/hooks/useShouldShowAiChatEmptyState.ts
index a32c893a6e9..ae8540e2a25 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useShouldShowAiChatEmptyState.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useShouldShowAiChatEmptyState.ts
@@ -1,6 +1,6 @@
import { isDefined } from 'twenty-shared/utils';
-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
+import { useIsOnNewAiChatSlot } from '@/ai/hooks/useIsOnNewAiChatSlot';
import { agentChatErrorComponentFamilyState } from '@/ai/states/agentChatErrorComponentFamilyState';
import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkComponentFamilyState';
import { agentChatIsStreamingComponentFamilyState } from '@/ai/states/agentChatIsStreamingComponentFamilyState';
@@ -36,11 +36,10 @@ export const useShouldShowAiChatEmptyState = () => {
const isMobile = useIsMobile();
- const isOnNewChatSlot =
- currentAiChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY;
+ const isOnNewAiChatSlot = useIsOnNewAiChatSlot();
return (
- isOnNewChatSlot &&
+ isOnNewAiChatSlot &&
!isMobile &&
!hasMessages &&
!isDefined(agentChatError) &&
diff --git a/packages/twenty-front/src/modules/ai/states/agentChatSentMessageHandOffState.ts b/packages/twenty-front/src/modules/ai/states/agentChatSentMessageHandOffState.ts
new file mode 100644
index 00000000000..357a7ea2a7e
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/states/agentChatSentMessageHandOffState.ts
@@ -0,0 +1,9 @@
+import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';
+
+export const agentChatSentMessageHandOffState = createAtomState<{
+ composerTextRect: Pick<DOMRect, 'left' | 'top'>;
+ messageId: string | null;
+} | null>({
+ key: 'ai/agentChatSentMessageHandOffState',
+ defaultValue: null,
+});
diff --git a/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatLastMessageIdComponentSelector.test.tsx b/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatLastMessageIdComponentSelector.test.tsx
new file mode 100644
index 00000000000..8dfe9d01ee7
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatLastMessageIdComponentSelector.test.tsx
@@ -0,0 +1,85 @@
+import { renderHook } from '@testing-library/react';
+import { Provider as JotaiProvider } from 'jotai';
+import { type ReactNode } from 'react';
+
+import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';
+import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
+import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
+import { agentChatLastMessageIdComponentSelector } from '@/ai/states/selectors/agentChatLastMessageIdComponentSelector';
+import { agentChatNonLastMessageIdsComponentSelector } from '@/ai/states/selectors/agentChatNonLastMessageIdsComponentSelector';
+import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';
+import {
+ jotaiStore,
+ resetJotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
+
+const INSTANCE_ID = 'agentChatLastMessageIdTest';
+const THREAD_ID = 'thread';
+
+const USER_MESSAGE = { id: 'user-message', role: 'user' as const, parts: [] };
+const ASSISTANT_MESSAGE = {
+ id: 'assistant-message',
+ role: 'assistant' as const,
+ parts: [],
+};
+
+const Wrapper = ({ children }: { children: ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>
+ <AgentChatComponentInstanceContext.Provider
+ value={{ instanceId: INSTANCE_ID }}
+ >
+ {children}
+ </AgentChatComponentInstanceContext.Provider>
+ </JotaiProvider>
+);
+
+describe('agentChatLastMessageIdComponentSelector', () => {
+ beforeEach(() => {
+ resetJotaiStore();
+ jotaiStore.set(agentChatDisplayedThreadState.atom, THREAD_ID);
+ });
+
+ it.each([
+ {
+ description:
+ 'keeps a message the user just sent in the list so it stays mounted when the reply starts',
+ messages: [USER_MESSAGE],
+ expectedNonLastMessageIds: ['user-message'],
+ expectedLastMessageId: null,
+ },
+ {
+ description: 'gives the reply the streaming slot',
+ messages: [USER_MESSAGE, ASSISTANT_MESSAGE],
+ expectedNonLastMessageIds: ['user-message'],
+ expectedLastMessageId: 'assistant-message',
+ },
+ ])(
+ '$description',
+ ({ messages, expectedNonLastMessageIds, expectedLastMessageId }) => {
+ jotaiStore.set(
+ agentChatMessagesComponentFamilyState.atomFamily({
+ instanceId: INSTANCE_ID,
+ familyKey: { threadId: THREAD_ID },
+ }),
+ messages,
+ );
+
+ const { result } = renderHook(
+ () => ({
+ nonLastMessageIds: useAtomComponentSelectorValue(
+ agentChatNonLastMessageIdsComponentSelector,
+ ),
+ lastMessageId: useAtomComponentSelectorValue(
+ agentChatLastMessageIdComponentSelector,
+ ),
+ }),
+ { wrapper: Wrapper },
+ );
+
+ expect(result.current).toEqual({
+ nonLastMessageIds: expectedNonLastMessageIds,
+ lastMessageId: expectedLastMessageId,
+ });
+ },
+ );
+});
diff --git a/packages/twenty-front/src/modules/ai/states/selectors/agentChatLastMessageIdComponentSelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/agentChatLastMessageIdComponentSelector.ts
index 63d7deac081..d9f6bca028a 100644
--- a/packages/twenty-front/src/modules/ai/states/selectors/agentChatLastMessageIdComponentSelector.ts
+++ b/packages/twenty-front/src/modules/ai/states/selectors/agentChatLastMessageIdComponentSelector.ts
@@ -1,3 +1,4 @@
+import { AgentMessageRole } from '@/ai/constants/AgentMessageRole';
import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';
import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
@@ -17,6 +18,12 @@ export const agentChatLastMessageIdComponentSelector =
familyKey: { threadId: currentThreadId },
});
- return messages.at(-1)?.id ?? null;
+ const lastMessage = messages.at(-1);
+
+ if (lastMessage?.role === AgentMessageRole.USER) {
+ return null;
+ }
+
+ return lastMessage?.id ?? null;
},
});
diff --git a/packages/twenty-front/src/modules/ai/states/selectors/agentChatNonLastMessageIdsComponentSelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/agentChatNonLastMessageIdsComponentSelector.ts
index c236be66928..13260b73603 100644
--- a/packages/twenty-front/src/modules/ai/states/selectors/agentChatNonLastMessageIdsComponentSelector.ts
+++ b/packages/twenty-front/src/modules/ai/states/selectors/agentChatNonLastMessageIdsComponentSelector.ts
@@ -1,6 +1,7 @@
import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';
import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
+import { agentChatLastMessageIdComponentSelector } from '@/ai/states/selectors/agentChatLastMessageIdComponentSelector';
import { createAtomComponentSelector } from '@/ui/utilities/state/jotai/utils/createAtomComponentSelector';
export const agentChatNonLastMessageIdsComponentSelector =
@@ -17,7 +18,13 @@ export const agentChatNonLastMessageIdsComponentSelector =
familyKey: { threadId: currentThreadId },
});
- return messages.slice(0, -1).map((message) => message.id);
+ const lastMessageId = get(agentChatLastMessageIdComponentSelector, {
+ instanceId,
+ });
+
+ return messages
+ .filter((message) => message.id !== lastMessageId)
+ .map((message) => message.id);
},
areEqual: (previous, next) =>
previous.length === next.length &&
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
new file mode 100644
index 00000000000..b9b1b4bc684
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatThreadAccess.test.ts
@@ -0,0 +1,54 @@
+import { getAiChatThreadAccess } from '@/ai/utils/getAiChatThreadAccess';
+
+const READ_ONLY_PERMISSIONS = {
+ canRead: true,
+ canUpdate: false,
+ canDelete: false,
+ canSoftDelete: false,
+};
+
+describe('getAiChatThreadAccess', () => {
+ it.each([
+ {
+ description:
+ 'lets the author write in the thread their draft just created while its permissions load',
+ isOnNewAiChatSlot: true,
+ permissions: undefined,
+ expectedAccess: 'writer',
+ },
+ {
+ description: 'keeps any other thread loading until its permissions load',
+ isOnNewAiChatSlot: false,
+ permissions: undefined,
+ expectedAccess: 'loading',
+ },
+ {
+ description:
+ 'follows the loaded permissions of the thread the draft created',
+ isOnNewAiChatSlot: true,
+ permissions: READ_ONLY_PERMISSIONS,
+ expectedAccess: 'viewer',
+ },
+ {
+ description: 'lets a member who can update the thread write in it',
+ isOnNewAiChatSlot: false,
+ permissions: { ...READ_ONLY_PERMISSIONS, canUpdate: true },
+ expectedAccess: 'writer',
+ },
+ {
+ description:
+ 'marks a thread the member can no longer read as unavailable',
+ isOnNewAiChatSlot: false,
+ permissions: { ...READ_ONLY_PERMISSIONS, canRead: false },
+ expectedAccess: 'unavailable',
+ },
+ ])('$description', ({ isOnNewAiChatSlot, permissions, expectedAccess }) => {
+ expect(
+ getAiChatThreadAccess({
+ currentAiChatThread: 'thread',
+ isOnNewAiChatSlot,
+ permissions,
+ }),
+ ).toBe(expectedAccess);
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatThreadAccess.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatThreadAccess.ts
new file mode 100644
index 00000000000..14babecfd59
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatThreadAccess.ts
@@ -0,0 +1,30 @@
+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
+ ) {
+ return 'writer';
+ }
+ if (!isDefined(permissions?.canUpdate)) {
+ return isOnNewAiChatSlot ? 'writer' : 'loading';
+ }
+ if (!permissions.canRead) {
+ return 'unavailable';
+ }
+ return permissions.canUpdate ? 'writer' : 'viewer';
+};
diff --git a/packages/twenty-front/src/modules/ai/utils/getTextBoundingClientRect.ts b/packages/twenty-front/src/modules/ai/utils/getTextBoundingClientRect.ts
new file mode 100644
index 00000000000..f9e6e5e80dc
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/getTextBoundingClientRect.ts
@@ -0,0 +1,7 @@
+export const getTextBoundingClientRect = (element: HTMLElement) => {
+ const range = document.createRange();
+
+ range.selectNodeContents(element);
+
+ return range.getBoundingClientRect();
+};
diff --git a/packages/twenty-front/src/utils/__tests__/lazyWithPreload.test.tsx b/packages/twenty-front/src/utils/__tests__/lazyWithPreload.test.tsx
index d03c9e9e08f..53e0921dd04 100644
--- a/packages/twenty-front/src/utils/__tests__/lazyWithPreload.test.tsx
+++ b/packages/twenty-front/src/utils/__tests__/lazyWithPreload.test.tsx
@@ -47,6 +47,19 @@ describe('lazyWithPreload', () => {
consoleErrorSpy.mockRestore();
});
+ it('should render the loaded component with its props once preloaded', async () => {
+ const Greeting = ({ name }: { name: string }) => <div>Hello {name}</div>;
+ const PreloadableGreeting = lazyWithPreload(async () => ({
+ default: Greeting,
+ }));
+
+ PreloadableGreeting.preload();
+ await flushPendingPromises();
+ render(<PreloadableGreeting name="Ada" />);
+
+ expect(screen.getByText('Hello Ada')).toBeInTheDocument();
+ });
+
it('should not produce an unhandled rejection when the preload fails', async () => {
const onUnhandledRejection = jest.fn();
process.on('unhandledRejection', onUnhandledRejection);
diff --git a/packages/twenty-front/src/utils/lazyWithPreload.tsx b/packages/twenty-front/src/utils/lazyWithPreload.tsx
index f6ff66634de..c79777bbf94 100644
--- a/packages/twenty-front/src/utils/lazyWithPreload.tsx
+++ b/packages/twenty-front/src/utils/lazyWithPreload.tsx
@@ -1,19 +1,28 @@
-import { type ComponentType } from 'react';
+import { type ComponentType, createElement } from 'react';
-type LoadState =
+type LoadState<TProps extends object> =
| { status: 'idle' }
| { status: 'pending'; promise: Promise<void> }
- | { status: 'loaded'; component: ComponentType }
+ | { status: 'loaded'; component: ComponentType<TProps> }
| { status: 'failed'; error: unknown };
-type PreloadableComponent = ComponentType & {
+type PreloadableComponent<TProps extends object> = ComponentType<TProps> & {
preload: () => void;
};
-export const lazyWithPreload = (
- loader: () => Promise<{ default: ComponentType }>,
-): PreloadableComponent => {
- let loadState: LoadState = { status: 'idle' };
+type LazyWithPreload = {
+ (
+ loader: () => Promise<{ default: ComponentType }>,
+ ): PreloadableComponent<object>;
+ <TProps extends object>(
+ loader: () => Promise<{ default: ComponentType<TProps> }>,
+ ): PreloadableComponent<TProps>;
+};
+
+export const lazyWithPreload: LazyWithPreload = <TProps extends object>(
+ loader: () => Promise<{ default: ComponentType<TProps> }>,
+): PreloadableComponent<TProps> => {
+ let loadState: LoadState<TProps> = { status: 'idle' };
const startLoading = (): Promise<void> => {
if (loadState.status === 'pending') {
@@ -48,15 +57,13 @@ export const lazyWithPreload = (
startLoading();
};
- const PreloadableComponent = () => {
+ const PreloadableComponent: ComponentType<TProps> = (props) => {
if (loadState.status === 'failed') {
throw loadState.error;
}
if (loadState.status === 'loaded') {
- const Component = loadState.component;
-
- return <Component />;
+ return createElement(loadState.component, props);
}
throw startLoading();