The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Polish AI chat mode design and actions (#25542)
Thomas des Francs729e7d82b8bc
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatPinScrollToBottomOnMountLayoutEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatPinScrollToBottomOnMountLayoutEffect.tsxdeleted file mode 100644index 1937666f576..00000000000--- a/packages/twenty-front/src/modules/ai/components/AgentChatPinScrollToBottomOnMountLayoutEffect.tsx+++ /dev/null@@ -1,32 +0,0 @@-import { useLayoutEffect } from 'react';-import { isDefined } from 'twenty-shared/utils';--import { pinAiChatScrollToBottom } from '@/ai/utils/pinAiChatScrollToBottom';-import { useScrollWrapperHTMLElement } from '@/ui/utilities/scroll/hooks/useScrollWrapperHTMLElement';-import { scrollWrapperScrollBottomComponentState } from '@/ui/utilities/scroll/states/scrollWrapperScrollBottomComponentState';-import { getScrollBottomInPx } from '@/ui/utilities/scroll/utils/getScrollBottomInPx';-import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';--export const AgentChatPinScrollToBottomOnMountLayoutEffect = () => {- const { getScrollWrapperElement } = useScrollWrapperHTMLElement();-- const setScrollWrapperScrollBottom = useSetAtomComponentState(- scrollWrapperScrollBottomComponentState,- );-- useLayoutEffect(() => {- const { scrollWrapperElement } = getScrollWrapperElement();-- if (!isDefined(scrollWrapperElement)) {- return;- }-- return pinAiChatScrollToBottom({- scrollWrapperElement,- onPinningStopped: () =>- setScrollWrapperScrollBottom(getScrollBottomInPx(scrollWrapperElement)),- });- }, [getScrollWrapperElement, setScrollWrapperScrollBottom]);-- return null;-};diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect.tsxindex 8a4eb49d3bd..ea29c626d56 100644--- a/packages/twenty-front/src/modules/ai/components/AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect.tsx@@ -1,16 +1,13 @@-import { useStore } from 'jotai';-import { useEffect } from 'react';+import { useLayoutEffect } from 'react';import { isDefined } from 'twenty-shared/utils';import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';-import { agentChatIsInitialScrollPendingOnThreadChangeState } from '@/ai/states/agentChatIsInitialScrollPendingOnThreadChangeState';import { pinAiChatScrollToBottom } from '@/ai/utils/pinAiChatScrollToBottom';import { useScrollWrapperHTMLElement } from '@/ui/utilities/scroll/hooks/useScrollWrapperHTMLElement';import { scrollWrapperScrollBottomComponentState } from '@/ui/utilities/scroll/states/scrollWrapperScrollBottomComponentState';import { getScrollBottomInPx } from '@/ui/utilities/scroll/utils/getScrollBottomInPx';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';-import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';export const AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect =() => {@@ -18,34 +15,21 @@ export const AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect =agentChatDisplayedThreadState,);- const setAgentChatIsInitialScrollPendingOnThreadChange = useSetAtomState(- agentChatIsInitialScrollPendingOnThreadChangeState,- );-- const store = useStore();-const { getScrollWrapperElement } = useScrollWrapperHTMLElement();const setScrollWrapperScrollBottom = useSetAtomComponentState(scrollWrapperScrollBottomComponentState,);- useEffect(() => {- if (!store.get(agentChatIsInitialScrollPendingOnThreadChangeState.atom)) {- return;- }-+ useLayoutEffect(() => {const { scrollWrapperElement } = getScrollWrapperElement();if (!isDefined(scrollWrapperElement)) {- setAgentChatIsInitialScrollPendingOnThreadChange(false);return;}return pinAiChatScrollToBottom({scrollWrapperElement,- onContentSettled: () =>- setAgentChatIsInitialScrollPendingOnThreadChange(false),onPinningStopped: () =>setScrollWrapperScrollBottom(getScrollBottomInPx(scrollWrapperElement),@@ -53,8 +37,6 @@ export const AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect =});}, [agentChatDisplayedThread,- store,- setAgentChatIsInitialScrollPendingOnThreadChange,getScrollWrapperElement,setScrollWrapperScrollBottom,]);diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatStreamSubscriptionEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatStreamSubscriptionEffect.tsxindex ebdd0f5b9a2..df08b1d3e69 100644--- a/packages/twenty-front/src/modules/ai/components/AgentChatStreamSubscriptionEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AgentChatStreamSubscriptionEffect.tsx@@ -11,7 +11,6 @@ import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThrimport { agentChatFetchedMessagesComponentFamilyState } from '@/ai/states/agentChatFetchedMessagesComponentFamilyState';import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkComponentFamilyState';import { agentChatIsAwaitingPersistedRefetchComponentFamilyState } from '@/ai/states/agentChatIsAwaitingPersistedRefetchComponentFamilyState';-import { agentChatIsInitialScrollPendingOnThreadChangeState } from '@/ai/states/agentChatIsInitialScrollPendingOnThreadChangeState';import { agentChatIsLoadingState } from '@/ai/states/agentChatIsLoadingState';import { agentChatIsStreamingComponentFamilyState } from '@/ai/states/agentChatIsStreamingComponentFamilyState';import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';@@ -82,10 +81,6 @@ export const AgentChatStreamSubscriptionEffect = () => {agentChatDisplayedThreadState,);- const setAgentChatIsInitialScrollPendingOnThreadChange = useSetAtomState(- agentChatIsInitialScrollPendingOnThreadChangeState,- );-useEffect(() => {if (agentChatIsStreaming) {return;@@ -101,9 +96,6 @@ export const AgentChatStreamSubscriptionEffect = () => {}if (isThreadSwitch && agentChatIsAwaitingFirstChunk) {- if (agentChatFetchedMessages.length > 0) {- setAgentChatIsInitialScrollPendingOnThreadChange(true);- }setAgentChatDisplayedThread(currentAiChatThread);return;@@ -112,9 +104,6 @@ export const AgentChatStreamSubscriptionEffect = () => {setAgentChatMessages(agentChatFetchedMessages);if (isThreadSwitch) {- if (agentChatFetchedMessages.length > 0) {- setAgentChatIsInitialScrollPendingOnThreadChange(true);- }setAgentChatDisplayedThread(currentAiChatThread);}}, [@@ -126,7 +115,6 @@ export const AgentChatStreamSubscriptionEffect = () => {currentAiChatThread,agentChatDisplayedThread,setAgentChatDisplayedThread,- setAgentChatIsInitialScrollPendingOnThreadChange,]);const setAgentChatIsLoading = useSetAtomState(agentChatIsLoadingState);diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsxindex d2be244cd9a..78a2849f9dd 100644--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx@@ -6,6 +6,7 @@ import {tipTapDocumentToMarkdown,} from 'twenty-shared/utils';+import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';import {AGENT_CHAT_NEW_THREAD_DRAFT_KEY,agentChatDraftsByThreadIdState,@@ -19,22 +20,18 @@ import { currentAiChatThreadTitleComponentFamilyState } from '@/ai/states/currenimport { hasInitializedAgentChatThreadsState } from '@/ai/states/hasInitializedAgentChatThreadsState';import { hasTriggeredCreateForDraftState } from '@/ai/states/hasTriggeredCreateForDraftState';import { sortChatThreadsByLastActivityDesc } from '@/ai/utils/sortChatThreadsByLastActivityDesc';-import { useUpdateMetadataStoreDraft } from '@/metadata-store/hooks/useUpdateMetadataStoreDraft';import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';import { useHasPermissionFlag } from '@/settings/roles/hooks/useHasPermissionFlag';import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';-import { useApolloClient } from '@apollo/client/react';-import {- GetChatThreadsDocument,- PermissionFlagType,-} from '~/generated-metadata/graphql';+import { PermissionFlagType } from '~/generated-metadata/graphql';++const AGENT_CHAT_THREADS_REFRESH_RETRY_DELAY_MS = 3000;export const AgentChatThreadInitializationEffect = () => {- const client = useApolloClient();- const { replaceDraft, applyChanges } = useUpdateMetadataStoreDraft();+ const { refreshAgentChatThreads } = useRefreshAgentChatThreads();const hasAiPermission = useHasPermissionFlag(PermissionFlagType.AI);const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);@@ -64,20 +61,32 @@ export const AgentChatThreadInitializationEffect = () => {return;}- client- .query({- query: GetChatThreadsDocument,- fetchPolicy: 'network-only',- })- .then((result) => {- if (!isDefined(result.data?.chatThreads)) {- return;- }-- replaceDraft('agentChatThreads', result.data.chatThreads);- applyChanges();- });- }, [storeEntry.status, hasAiPermission, client, replaceDraft, applyChanges]);+ let isActive = true;+ let retryTimeoutId: number | undefined;++ const refreshUntilLoaded = async () => {+ const agentChatThreads = await refreshAgentChatThreads();++ if (!isActive || isDefined(agentChatThreads)) {+ return;+ }++ retryTimeoutId = window.setTimeout(+ () => void refreshUntilLoaded(),+ AGENT_CHAT_THREADS_REFRESH_RETRY_DELAY_MS,+ );+ };++ void refreshUntilLoaded();++ return () => {+ isActive = false;++ if (isDefined(retryTimeoutId)) {+ window.clearTimeout(retryTimeoutId);+ }+ };+ }, [storeEntry.status, hasAiPermission, refreshAgentChatThreads]);useEffect(() => {setAgentChatThreadsLoading(diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsxindex 7a6059307ff..abb201f7e14 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx@@ -5,7 +5,7 @@ import { RoutingStatusDisplay } from '@/ai/components/RoutingStatusDisplay';import { ThinkingStepsDisplay } from '@/ai/components/ThinkingStepsDisplay';import { AiChatQuestionStatusRenderer } from '@/ai/components/AiChatQuestionStatusRenderer';-import { LazyMarkdownRenderer } from '@/ai/components/LazyMarkdownRenderer';+import { LazyMarkdownContent } from '@/ai/components/LazyMarkdownRenderer';import { ToolStepRenderer } from '@/ai/components/ToolStepRenderer';import { groupContiguousThinkingStepParts } from '@/ai/utils/groupContiguousThinkingStepParts';import { isCodeInterpreterToolPart } from '@/ai/utils/isCodeInterpreterToolPart';@@ -34,7 +34,7 @@ const MessagePartRenderer = ({}) => {switch (part.type) {case 'text':- return <LazyMarkdownRenderer text={part.text} />;+ return <LazyMarkdownContent text={part.text} />;case 'data-routing-status':return <RoutingStatusDisplay data={part.data} />;case 'data-compaction':diff --git a/packages/twenty-front/src/modules/ai/components/AiChatCollapseButton.tsx b/packages/twenty-front/src/modules/ai/components/AiChatCollapseButton.tsxdeleted file mode 100644index eef75b040f8..00000000000--- a/packages/twenty-front/src/modules/ai/components/AiChatCollapseButton.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { useLingui } from '@lingui/react/macro';-import { IconLayoutSidebarRightCollapse } from 'twenty-ui/icon';-import { IconButton } from 'twenty-ui/input';--import { useReturnFromExpandedAiChat } from '@/ai/hooks/useReturnFromExpandedAiChat';-import { isWelcomeAnimationVisibleState } from '@/onboarding/states/isWelcomeAnimationVisibleState';-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';--export const AiChatCollapseButton = () => {- const { t } = useLingui();- const returnFromExpandedAiChat = useReturnFromExpandedAiChat({- reopenSidePanel: true,- });- const isWelcomeAnimationVisible = useAtomStateValue(- isWelcomeAnimationVisibleState,- );-- return (- <IconButton- Icon={IconLayoutSidebarRightCollapse}- size="small"- variant="tertiary"- disabled={isWelcomeAnimationVisible}- onClick={returnFromExpandedAiChat}- ariaLabel={t`Collapse to side panel`}- />- );-};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsxindex 40592b4cc24..c2d25d96fac 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx@@ -1,3 +1,4 @@+import { StyledAiChatContentContainer } from '@/ai/components/StyledAiChatContentContainer';import { useState } from 'react';import { styled } from '@linaria/react';@@ -20,7 +21,6 @@ import { AiChatDictationEffect } from '@/ai/dictation/components/AiChatDictationimport { AiChatDictationHint } from '@/ai/dictation/components/AiChatDictationHint';import { AiChatContextUsageButton } from '@/ai/components/internal/AiChatContextUsageButton';import { AiChatEditorFocusEffect } from '@/ai/components/internal/AiChatEditorFocusEffect';-import { AiChatSkeletonLoader } from '@/ai/components/internal/AiChatSkeletonLoader';import { SendMessageButton } from '@/ai/components/internal/SendMessageButton';import { useAgentChatModelId } from '@/ai/hooks/useAgentChatModelId';import { useAiChatEditor } from '@/ai/hooks/useAiChatEditor';@@ -41,7 +41,9 @@ import { PermissionFlagType } from '~/generated-metadata/graphql';import { useNavigateSettings } from '~/hooks/useNavigateSettings';import { SETTINGS_AI_TABS } from '~/pages/settings/ai/constants/SettingsAiTabs';-const StyledInputArea = styled.div<{ isMobile: boolean }>`+const StyledInputArea = styled(StyledAiChatContentContainer)<{+ isMobile: boolean;+}>`align-items: flex-end;background: ${themeCssVariables.background.primary};display: flex;@@ -57,7 +59,9 @@ const StyledInputArea = styled.div<{ isMobile: boolean }>`const StyledInputBox = styled.div<{ isMobile: boolean }>`background-color: ${themeCssVariables.background.transparent.lighter};border: 1px solid ${themeCssVariables.border.color.medium};- border-radius: ${themeCssVariables.border.radius.sm};+ border-radius: calc(+ ${themeCssVariables.border.radius.md} + ${themeCssVariables.spacing[1]}+ );box-sizing: border-box;display: flex;flex-direction: column;@@ -195,7 +199,6 @@ export const AiChatEditorSection = () => {/><AiChatEmptyState isCentered={isComposerCentered} /><AiChatStandaloneError />- <AiChatSkeletonLoader /><StyledInputArea isMobile={isMobile}><AgentChatContextPreview />diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsxindex 1d4461f50ff..c0ed67b4d97 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx@@ -1,9 +1,10 @@+import { StyledAiChatContentContainer } from '@/ai/components/StyledAiChatContentContainer';import { styled } from '@linaria/react';import { AiChatSuggestedPrompts } from '@/ai/components/suggested-prompts/AiChatSuggestedPrompts';import { useShouldShowAiChatEmptyState } from '@/ai/hooks/useShouldShowAiChatEmptyState';-const StyledEmptyState = styled.div`+const StyledEmptyState = styled(StyledAiChatContentContainer)`display: flex;flex: 1;flex-direction: column;diff --git a/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx b/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsxindex 1ed32779823..2dece0d3d3f 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx@@ -34,11 +34,8 @@ const StyledMessageText = styled.div<{ isUser?: boolean }>`background: ${({ isUser }) =>isUser ? themeCssVariables.background.tertiary : 'transparent'};border-radius: ${({ isUser }) =>- isUser ? themeCssVariables.border.radius.sm : '0'};- color: ${({ isUser }) =>- isUser- ? themeCssVariables.font.color.secondary- : themeCssVariables.font.color.primary};+ isUser ? themeCssVariables.border.radius.lg : '0'};+ color: ${themeCssVariables.font.color.primary};font-weight: ${({ isUser }) => (isUser ? 500 : 400)};line-height: 1.4em;max-width: 100%;diff --git a/packages/twenty-front/src/modules/ai/components/AiChatNonLastMessageIdsList.tsx b/packages/twenty-front/src/modules/ai/components/AiChatNonLastMessageIdsList.tsxindex ea78826e09c..0bd93b5b429 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatNonLastMessageIdsList.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatNonLastMessageIdsList.tsx@@ -1,18 +1,6 @@import { AiChatMessage } from '@/ai/components/AiChatMessage';import { agentChatNonLastMessageIdsComponentSelector } from '@/ai/states/selectors/agentChatNonLastMessageIdsComponentSelector';import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';-import { styled } from '@linaria/react';--// Settled messages never change, so let the browser skip layout and paint for-// the ones scrolled out of view. `auto` in contain-intrinsic-size keeps the-// last rendered height once a message has been painted; the estimate only-// applies to never-painted messages, where scroll anchoring absorbs the-// correction. 160px approximates a typical assistant message so the scrollbar-// stays close to truth on long resumed threads.-const StyledSettledMessage = styled.div`- contain-intrinsic-size: auto 160px;- content-visibility: auto;-`;export const AiChatNonLastMessageIdsList = () => {const agentChatNonLastMessageIds = useAtomComponentSelectorValue(@@ -20,8 +8,6 @@ export const AiChatNonLastMessageIdsList = () => {);return agentChatNonLastMessageIds.map((messageId) => (- <StyledSettledMessage key={messageId}>- <AiChatMessage messageId={messageId} />- </StyledSettledMessage>+ <AiChatMessage key={messageId} messageId={messageId} />));};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsxindex e2ba9159bec..ab38f9ef106 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsx@@ -1,17 +1,20 @@import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';-import { useContext } from 'react';-import { IconEdit, IconSparkles } from 'twenty-ui/icon';-import { IconButton } from 'twenty-ui/input';-import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';+import { isDefined } from 'twenty-shared/utils';+import { themeCssVariables } from 'twenty-ui/theme-constants';import { useIsMobile } from 'twenty-ui/utilities';import { AiChatCloseButton } from '@/ai/components/AiChatCloseButton';-import { AiChatCollapseButton } from '@/ai/components/AiChatCollapseButton';-import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';+import { AiChatPageThreadHeader } from '@/ai/components/AiChatPageThreadHeader';+import { AiChatThreadDeleteConfirmationModal } from '@/ai/components/AiChatThreadDeleteConfirmationModal';+import { AI_CHAT_THREAD_ACTIONS_SURFACE } from '@/ai/constants/AiChatThreadActionsSurface';+import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { currentAiChatThreadDataSelector } from '@/ai/states/selectors/currentAiChatThreadDataSelector';import { useNavigationDrawerExpanded } from '@/navigation/hooks/useNavigationDrawerExpanded';import { SIDE_PANEL_TOP_BAR_HEIGHT } from '@/side-panel/constants/SidePanelTopBarHeight';import { NavigationDrawerCollapseButton } from '@/ui/navigation/navigation-drawer/components/NavigationDrawerCollapseButton';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';const StyledHeader = styled.header`align-items: center;@@ -20,9 +23,9 @@ const StyledHeader = styled.header`box-sizing: border-box;display: flex;flex-shrink: 0;- gap: ${themeCssVariables.spacing['0.5']};+ gap: ${themeCssVariables.spacing[2]};height: ${SIDE_PANEL_TOP_BAR_HEIGHT}px;- padding: 0 ${themeCssVariables.spacing[2]};+ padding: 0 ${themeCssVariables.spacing[3]};`;const StyledHeaderTitle = styled.div`@@ -31,7 +34,7 @@ const StyledHeaderTitle = styled.div`display: flex;flex: 1;font-size: ${themeCssVariables.font.size.md};- font-weight: ${themeCssVariables.font.weight.semiBold};+ font-weight: ${themeCssVariables.font.weight.medium};gap: ${themeCssVariables.spacing[1]};min-width: 0;overflow: hidden;@@ -46,42 +49,39 @@ type AiChatPageHeaderProps = {export const AiChatPageHeader = ({ isOnboarding }: AiChatPageHeaderProps) => {const { t } = useLingui();- const { theme } = useContext(ThemeContext);const isMobile = useIsMobile();const isNavigationDrawerExpanded = useNavigationDrawerExpanded();- const { switchToNewChat } = useSwitchToNewAiChat();+ const currentAiChatThreadData = useAtomStateValue(+ currentAiChatThreadDataSelector,+ );+ const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);+ const isNewChat =+ !isDefined(currentAiChatThread) ||+ currentAiChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY;return (<StyledHeader>{!isNavigationDrawerExpanded && !isMobile && (<NavigationDrawerCollapseButton direction="right" />)}- <StyledHeaderTitle>- <IconSparkles size={theme.icon.size.md} />- {isOnboarding ? t`Onboarding` : t`Ask AI`}- </StyledHeaderTitle>- {/* The onboarding conversation is single-threaded: switching or- starting threads would abandon the workspace setup. */}- {!isOnboarding && (- <IconButton- Icon={IconEdit}- size="small"- variant="tertiary"- onClick={() => switchToNewChat()}- ariaLabel={t`New conversation`}+ {isDefined(currentAiChatThreadData) && !isOnboarding ? (+ <AiChatPageThreadHeader+ key={currentAiChatThreadData.id}+ thread={currentAiChatThreadData}/>+ ) : (+ <StyledHeaderTitle>+ {isOnboarding ? t`Onboarding` : isNewChat ? t`New chat` : null}+ </StyledHeaderTitle>)}- {/* Collapsing back into the side panel is a desktop notion; on mobile- the page is left outright, so it closes the way the side panel does,- down to the same button. */}{isMobile ? (<AiChatCloseButton variant="primary" />) : (- <>- <AiChatCollapseButton />- {isOnboarding && <AiChatCloseButton />}- </>+ isOnboarding && <AiChatCloseButton />)}+ <AiChatThreadDeleteConfirmationModal+ surface={AI_CHAT_THREAD_ACTIONS_SURFACE.PAGE_HEADER}+ /></StyledHeader>);};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPageThreadHeader.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPageThreadHeader.tsxnew file mode 100644index 00000000000..7c4199e528f--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatPageThreadHeader.tsx@@ -0,0 +1,131 @@+import { styled } from '@linaria/react';+import { useLingui } from '@lingui/react/macro';+import { Key } from 'ts-key-enum';+import { isDefined } from 'twenty-shared/utils';+import { IconDotsVertical, IconPlus } from 'twenty-ui/icon';+import { Button, IconButton } from 'twenty-ui/input';+import { OverflowingTextWithTooltip } from 'twenty-ui/surfaces';+import { themeCssVariables } from 'twenty-ui/theme-constants';++import { AiChatThreadItemMenu } from '@/ai/components/AiChatThreadItemMenu';+import { AI_CHAT_THREAD_ACTIONS_SURFACE } from '@/ai/constants/AiChatThreadActionsSurface';+import { useAiChatThreadRename } from '@/ai/hooks/useAiChatThreadRename';+import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';+import { currentAiChatThreadTitleComponentFamilyState } from '@/ai/states/currentAiChatThreadTitleComponentFamilyState';+import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';+import { TextInput } from '@/ui/input/components/TextInput';+import { useAtomComponentFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateValue';+import { type AgentChatThread } from '~/generated-metadata/graphql';++const StyledTitle = styled.div`+ color: ${themeCssVariables.font.color.primary};+ flex-shrink: 1;+ font-size: ${themeCssVariables.font.size.md};+ font-weight: ${themeCssVariables.font.weight.medium};+ max-width: 100%;+ min-width: 0;+ padding: 0 ${themeCssVariables.spacing[1]};+ width: fit-content;+`;++const StyledActions = styled.div`+ align-items: center;+ display: flex;+ flex-shrink: 0;+ gap: ${themeCssVariables.spacing[2]};+ margin-left: auto;+`;++type AiChatPageThreadHeaderProps = {+ thread: AgentChatThread;+};++export const AiChatPageThreadHeader = ({+ thread,+}: AiChatPageThreadHeaderProps) => {+ const { t } = useLingui();+ const { switchToNewChat } = useSwitchToNewAiChat();+ const currentAiChatThreadTitle = useAtomComponentFamilyStateValue(+ currentAiChatThreadTitleComponentFamilyState,+ { threadId: thread.id },+ );+ const title = thread.title ?? currentAiChatThreadTitle;+ const {+ isRenaming,+ draftTitle,+ setDraftTitle,+ startRename,+ cancelRename,+ commitRename,+ } = useAiChatThreadRename({ ...thread, title });+ const displayTitle = title || t`New chat`;+ const agentChatMessages = useAtomComponentFamilyStateValue(+ agentChatMessagesComponentFamilyState,+ { threadId: thread.id },+ );+ const hasConversation =+ agentChatMessages.length > 0 || isDefined(thread.lastMessageAt);++ return (+ <>+ <StyledTitle>+ {isRenaming ? (+ <TextInput+ value={draftTitle}+ onChange={setDraftTitle}+ onFocus={(event) => event.target.select()}+ onBlur={() => commitRename(draftTitle)}+ onKeyDown={(event) => {+ if (event.nativeEvent.isComposing || event.keyCode === 229) {+ return;+ }+ if (event.key === Key.Enter) {+ event.preventDefault();+ event.stopPropagation();+ event.currentTarget.blur();+ } else if (event.key === Key.Escape) {+ event.preventDefault();+ event.stopPropagation();+ cancelRename();+ }+ }}+ placeholder={t`Chat name`}+ sizeVariant="sm"+ autoGrow+ inheritFontStyles+ autoFocus+ />+ ) : (+ <OverflowingTextWithTooltip text={displayTitle} />+ )}+ </StyledTitle>+ <StyledActions>+ {hasConversation && (+ <Button+ Icon={IconPlus}+ title={t`New chat`}+ size="small"+ variant="primary"+ accent="blue"+ onClick={() => switchToNewChat()}+ />+ )}+ <AiChatThreadItemMenu+ threadId={thread.id}+ threadTitle={displayTitle}+ isArchived={Boolean(thread.deletedAt)}+ surface={AI_CHAT_THREAD_ACTIONS_SURFACE.PAGE_HEADER}+ onRenameRequested={startRename}+ clickableComponent={+ <IconButton+ Icon={IconDotsVertical}+ size="small"+ variant="secondary"+ ariaLabel={t`Chat actions`}+ />+ }+ />+ </StyledActions>+ </>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsxindex 356b740c9e7..fd1bbfa6806 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsx@@ -1,27 +1,73 @@-import { useEffect } from 'react';+import { useLayoutEffect } from 'react';import { useParams } from 'react-router-dom';import { isDefined, isValidUuid } from 'twenty-shared/utils';+import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';import { useSwitchAgentChatThreadWithDraft } from '@/ai/hooks/useSwitchAgentChatThreadWithDraft';+import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { currentAiChatThreadDataSelector } from '@/ai/states/selectors/currentAiChatThreadDataSelector';+import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';+import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyStateValue';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';export const AiChatPageThreadUrlSyncEffect = () => {const { threadId } = useParams();const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);+ const currentAiChatThreadData = useAtomStateValue(+ currentAiChatThreadDataSelector,+ );+ const metadataStoreAgentChatThreads = useAtomFamilyStateValue(+ metadataStoreState,+ 'agentChatThreads',+ );const { switchThreadWithDraft } = useSwitchAgentChatThreadWithDraft();+ const { refreshAgentChatThreads } = useRefreshAgentChatThreads();+ const { switchToNewChat } = useSwitchToNewAiChat({+ shouldOpenInFullPage: true,+ });- useEffect(() => {+ useLayoutEffect(() => {if (!isDefined(threadId) || !isValidUuid(threadId)) {return;}- if (threadId === currentAiChatThread) {+ if (threadId !== currentAiChatThread) {+ switchThreadWithDraft(threadId);return;}- switchThreadWithDraft(threadId);- }, [threadId, currentAiChatThread, switchThreadWithDraft]);+ if (+ metadataStoreAgentChatThreads.status === 'up-to-date' &&+ !isDefined(currentAiChatThreadData)+ ) {+ let isCurrentThread = true;++ void refreshAgentChatThreads().then((chatThreads) => {+ if (+ !isCurrentThread ||+ !isDefined(chatThreads) ||+ chatThreads.some((chatThread) => chatThread.id === threadId)+ ) {+ return;+ }++ switchToNewChat();+ });++ return () => {+ isCurrentThread = false;+ };+ }+ }, [+ threadId,+ currentAiChatThread,+ currentAiChatThreadData,+ metadataStoreAgentChatThreads.status,+ refreshAgentChatThreads,+ switchThreadWithDraft,+ switchToNewChat,+ ]);return null;};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatQueuedMessages.tsx b/packages/twenty-front/src/modules/ai/components/AiChatQueuedMessages.tsxindex 168177a8c9a..906b725f943 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatQueuedMessages.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatQueuedMessages.tsx@@ -1,3 +1,4 @@+import { StyledAiChatContentContainer } from '@/ai/components/StyledAiChatContentContainer';import { styled } from '@linaria/react';import { agentChatQueuedMessagesComponentFamilyState } from '@/ai/states/agentChatQueuedMessagesComponentFamilyState';@@ -10,7 +11,7 @@ import { IconX } from 'twenty-ui/icon';import { LightIconButton } from 'twenty-ui/input';import { themeCssVariables } from 'twenty-ui/theme-constants';-const StyledQueueContainer = styled.div`+const StyledQueueContainer = styled(StyledAiChatContentContainer)`display: flex;flex-direction: column;gap: ${themeCssVariables.spacing[1]};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatStandaloneError.tsx b/packages/twenty-front/src/modules/ai/components/AiChatStandaloneError.tsxindex 2f0265e1810..e62eee8eb4a 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatStandaloneError.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatStandaloneError.tsx@@ -1,3 +1,4 @@+import { StyledAiChatContentContainer } from '@/ai/components/StyledAiChatContentContainer';import { styled } from '@linaria/react';import { themeCssVariables } from 'twenty-ui/theme-constants';@@ -12,13 +13,11 @@ import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { isDefined } from 'twenty-shared/utils';-const StyledErrorContainer = styled.div`- box-sizing: border-box;+const StyledErrorContainer = styled(StyledAiChatContentContainer)`display: flex;flex: 1;flex-direction: column;padding: ${themeCssVariables.spacing[3]};- width: 100%;`;export const AiChatStandaloneError = () => {diff --git a/packages/twenty-front/src/modules/ai/components/AiChatTabMessageList.tsx b/packages/twenty-front/src/modules/ai/components/AiChatTabMessageList.tsxindex fbf053ac65e..1a169c127f9 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatTabMessageList.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatTabMessageList.tsx@@ -1,22 +1,21 @@+import { MarkdownLoadingSkeleton } from '@/ai/components/LazyMarkdownRenderer';+import { StyledAiChatContentContainer } from '@/ai/components/StyledAiChatContentContainer';import { AiChatErrorUnderMessageList } from '@/ai/components/AiChatErrorUnderMessageList';import { AiChatLastMessageWithStreamingState } from '@/ai/components/AiChatLastMessageWithStreamingState';import { AiChatNonLastMessageIdsList } from '@/ai/components/AiChatNonLastMessageIdsList';import { AiChatPendingResponseIndicator } from '@/ai/components/AiChatPendingResponseIndicator';import { AiChatScrollToBottomButton } from '@/ai/components/AiChatScrollToBottomButton';import { AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect } from '@/ai/components/AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect';-import { AgentChatPinScrollToBottomOnMountLayoutEffect } from '@/ai/components/AgentChatPinScrollToBottomOnMountLayoutEffect';import { AgentChatStreamingAutoScrollEffect } from '@/ai/components/AgentChatStreamingAutoScrollEffect';import { agentChatHasMessageComponentSelector } from '@/ai/states/selectors/agentChatHasMessageComponentSelector';-import { agentChatIsInitialScrollPendingOnThreadChangeState } from '@/ai/states/agentChatIsInitialScrollPendingOnThreadChangeState';import { AiChatMessageListPreambleContext } from '@/ai/contexts/AiChatMessageListPreambleContext';import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';import { getAiChatScrollWrapperInstanceId } from '@/ai/utils/getAiChatScrollWrapperInstanceId';import { ScrollWrapper } from '@/ui/utilities/scroll/components/ScrollWrapper';import { ScrollWrapperComponentInstanceContext } from '@/ui/utilities/scroll/states/contexts/ScrollWrapperComponentInstanceContext';import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { styled } from '@linaria/react';-import { useContext } from 'react';+import { Suspense, useContext } from 'react';import { isDefined } from 'twenty-shared/utils';import { themeCssVariables } from 'twenty-ui/theme-constants';@@ -29,15 +28,16 @@ const StyledScrollWrapperContainer = styled.div`width: 100%;`;-const StyledPreambleOutsideScrollContainer = styled.div`+const StyledPreambleOutsideScrollContainer = styled(+ StyledAiChatContentContainer,+)`display: flex;flex-direction: column;flex-shrink: 0;padding: ${themeCssVariables.spacing[4]};- width: 100%;`;-const StyledMessageListContent = styled.div`+const StyledMessageListContent = styled(StyledAiChatContentContainer)`display: flex;flex-direction: column;gap: ${themeCssVariables.spacing[2]};@@ -54,10 +54,6 @@ export const AiChatTabMessageList = () => {const scrollWrapperInstanceId =getAiChatScrollWrapperInstanceId(aiChatSurface);- const agentChatIsInitialScrollPendingOnThreadChange = useAtomStateValue(- agentChatIsInitialScrollPendingOnThreadChangeState,- );-if (!agentChatHasMessage) {if (!isDefined(messageListPreamble)) {return null;@@ -74,27 +70,28 @@ export const AiChatTabMessageList = () => {<ScrollWrapperComponentInstanceContext.Providervalue={{ instanceId: scrollWrapperInstanceId }}>- <StyledScrollWrapperContainer- style={{- visibility: agentChatIsInitialScrollPendingOnThreadChange- ? 'hidden'- : 'visible',- }}- >- <ScrollWrapper componentInstanceId={scrollWrapperInstanceId}>+ <Suspense+ fallback={<StyledMessageListContent>- {messageListPreamble}- <AiChatNonLastMessageIdsList />- <AiChatLastMessageWithStreamingState />- <AiChatPendingResponseIndicator />- <AiChatErrorUnderMessageList />+ <MarkdownLoadingSkeleton /></StyledMessageListContent>- <AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect />- <AgentChatPinScrollToBottomOnMountLayoutEffect />- <AgentChatStreamingAutoScrollEffect />- </ScrollWrapper>- <AiChatScrollToBottomButton />- </StyledScrollWrapperContainer>+ }+ >+ <StyledScrollWrapperContainer>+ <ScrollWrapper componentInstanceId={scrollWrapperInstanceId}>+ <StyledMessageListContent>+ {messageListPreamble}+ <AiChatNonLastMessageIdsList />+ <AiChatLastMessageWithStreamingState />+ <AiChatPendingResponseIndicator />+ <AiChatErrorUnderMessageList />+ </StyledMessageListContent>+ <AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect />+ <AgentChatStreamingAutoScrollEffect />+ </ScrollWrapper>+ <AiChatScrollToBottomButton />+ </StyledScrollWrapperContainer>+ </Suspense></ScrollWrapperComponentInstanceContext.Provider>);};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadItemMenu.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadItemMenu.tsxindex 57deabb66e6..0c099b9b90f 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadItemMenu.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadItemMenu.tsx@@ -1,4 +1,5 @@import { useLingui } from '@lingui/react/macro';+import { type ReactNode } from 'react';import {IconArchive,IconArchiveOff,@@ -27,6 +28,7 @@ type AiChatThreadItemMenuProps = {isArchived: boolean;surface: AiChatThreadActionsSurface;onRenameRequested: () => void;+ clickableComponent?: ReactNode;};export const AiChatThreadItemMenu = ({@@ -35,6 +37,7 @@ export const AiChatThreadItemMenu = ({isArchived,surface,onRenameRequested,+ clickableComponent,}: AiChatThreadItemMenuProps) => {const { t } = useLingui();const dropdownId = getAiChatThreadItemMenuDropdownId(threadId, surface);@@ -75,11 +78,13 @@ export const AiChatThreadItemMenu = ({dropdownId={dropdownId}dropdownPlacement="bottom-end"clickableComponent={- <LightIconButton- aria-label={t`Chat actions`}- Icon={IconDotsVertical}- accent="tertiary"- />+ clickableComponent ?? (+ <LightIconButton+ aria-label={t`Chat actions`}+ Icon={IconDotsVertical}+ accent="tertiary"+ />+ )}dropdownComponents={<DropdownContent>diff --git a/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx b/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsxindex 25509886798..c98688e9e2e 100644--- a/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx+++ b/packages/twenty-front/src/modules/ai/components/LazyMarkdownRenderer.tsx@@ -121,7 +121,7 @@ const MarkdownRenderer = lazy(async () => {};});-const LoadingSkeleton = () => {+export const MarkdownLoadingSkeleton = () => {const { theme } = useContext(ThemeContext);return (<SkeletonTheme@@ -131,23 +131,7 @@ const LoadingSkeleton = () => {><StyledSkeletonContainer><Skeleton- width="70%"- height={SKELETON_LOADER_HEIGHT_SIZES.standard.m}- />-- <Skeleton height={SKELETON_LOADER_HEIGHT_SIZES.standard.s} />- <Skeleton height={SKELETON_LOADER_HEIGHT_SIZES.standard.s} />- <Skeleton- width="90%"- height={SKELETON_LOADER_HEIGHT_SIZES.standard.s}- />-- <Skeleton- width="85%"- height={SKELETON_LOADER_HEIGHT_SIZES.standard.s}- />- <Skeleton- width="80%"+ width={200}height={SKELETON_LOADER_HEIGHT_SIZES.standard.s}/></StyledSkeletonContainer>@@ -157,16 +141,13 @@ const LoadingSkeleton = () => {// Protecting per block behind the memo means only the streaming tail blocks// pay the reference-parsing cost on each flush; settled blocks never re-run it.-const MemoizedMarkdownBlock = memo(- ({ blockText }: { blockText: string }) => (- <MarkdownRenderer>- {protectChatReferencesForMarkdown(blockText)}- </MarkdownRenderer>- ),- (previousProps, nextProps) => previousProps.blockText === nextProps.blockText,-);+const MemoizedMarkdownBlock = memo(({ blockText }: { blockText: string }) => (+ <MarkdownRenderer>+ {protectChatReferencesForMarkdown(blockText)}+ </MarkdownRenderer>+));-export const LazyMarkdownRenderer = ({ text }: { text: string }) => {+export const LazyMarkdownContent = ({ text }: { text: string }) => {// Not state: the blocks are a pure function of `text`, the ref only caches// the previous split so streaming appends skip re-tokenizing settled blocks.// oxlint-disable-next-line twenty/no-state-useref@@ -184,11 +165,15 @@ export const LazyMarkdownRenderer = ({ text }: { text: string }) => {className="markdown-section"data-replay-ignore-mutations="true">- <Suspense fallback={<LoadingSkeleton />}>- {markdownBlocks.map((blockText, blockIndex) => (- <MemoizedMarkdownBlock key={blockIndex} blockText={blockText} />- ))}- </Suspense>+ {markdownBlocks.map((blockText, blockIndex) => (+ <MemoizedMarkdownBlock key={blockIndex} blockText={blockText} />+ ))}</StyledMarkdownContainer>);};++export const LazyMarkdownRenderer = ({ text }: { text: string }) => (+ <Suspense fallback={<MarkdownLoadingSkeleton />}>+ <LazyMarkdownContent text={text} />+ </Suspense>+);diff --git a/packages/twenty-front/src/modules/ai/components/LazyMarkdownRendererStyledComponents.tsx b/packages/twenty-front/src/modules/ai/components/LazyMarkdownRendererStyledComponents.tsxindex ee9f2b4a0e0..e6968817bb5 100644--- a/packages/twenty-front/src/modules/ai/components/LazyMarkdownRendererStyledComponents.tsx+++ b/packages/twenty-front/src/modules/ai/components/LazyMarkdownRendererStyledComponents.tsx@@ -162,10 +162,11 @@ export const StyledParagraph = styled.div``;export const StyledSkeletonContainer = styled.div`- display: flex;- flex-direction: column;- gap: ${themeCssVariables.spacing[2]};- width: 100%;+ max-width: 100%;++ .react-loading-skeleton {+ max-width: 100%;+ }`;export const StyledTableScrollContainer = styled.div`diff --git a/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatThreadItem.tsx b/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatThreadItem.tsxindex 7e0b23a5fce..d4eed6f873c 100644--- a/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatThreadItem.tsx+++ b/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatThreadItem.tsx@@ -1,7 +1,4 @@-import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';-import { IconArchive, IconComment } from 'twenty-ui/icon';-import { themeCssVariables } from 'twenty-ui/theme-constants';import { AiChatThreadItemMenu } from '@/ai/components/AiChatThreadItemMenu';import { AI_CHAT_THREAD_ACTIONS_SURFACE } from '@/ai/constants/AiChatThreadActionsSurface';@@ -12,43 +9,6 @@ import { NavigationDrawerInput } from '@/ui/navigation/navigation-drawer/componeimport { NavigationDrawerItem } from '@/ui/navigation/navigation-drawer/components/NavigationDrawerItem';import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';import { type AgentChatThread } from '~/generated-metadata/graphql';-import { beautifyPastDateRelativeToNowShort } from '~/utils/date-utils';--const StyledRightOptions = styled.div`- align-items: center;- display: flex;- height: ${themeCssVariables.spacing[6]};- justify-content: flex-end;- min-width: ${themeCssVariables.spacing[6]};- position: relative;-`;--const StyledTimestamp = styled.span<{ $isDropdownOpen: boolean }>`- color: ${themeCssVariables.font.color.light};- font-size: ${themeCssVariables.font.size.xs};- font-weight: ${themeCssVariables.font.weight.regular};- opacity: ${({ $isDropdownOpen }) => ($isDropdownOpen ? 0 : 1)};- transition: opacity 150ms;-- .navigation-drawer-item:hover & {- opacity: 0;- }-`;--const StyledMenuTrigger = styled.div<{ $isDropdownOpen: boolean }>`- opacity: ${({ $isDropdownOpen }) => ($isDropdownOpen ? 1 : 0)};- pointer-events: ${({ $isDropdownOpen }) =>- $isDropdownOpen ? 'auto' : 'none'};- position: absolute;- right: 0;- top: 0;- transition: opacity 150ms;-- .navigation-drawer-item:hover & {- opacity: 1;- pointer-events: auto;- }-`;type NavigationDrawerAiChatThreadItemProps = {thread: AgentChatThread;@@ -72,11 +32,7 @@ export const NavigationDrawerAiChatThreadItem = ({} = useAiChatThreadRename(thread);const isArchived = Boolean(thread.deletedAt);- const ThreadIcon = isArchived ? IconArchive : IconComment;const displayLabel = thread.title || t`New chat`;- const timestamp = beautifyPastDateRelativeToNowShort(- thread.lastMessageAt ?? thread.updatedAt ?? thread.createdAt,- );const itemMenuDropdownId = getAiChatThreadItemMenuDropdownId(thread.id,AI_CHAT_THREAD_ACTIONS_SURFACE.NAV_DRAWER,@@ -89,7 +45,6 @@ export const NavigationDrawerAiChatThreadItem = ({if (isRenaming) {return (<NavigationDrawerInput- Icon={ThreadIcon}value={draftTitle}onChange={setDraftTitle}onSubmit={commitRename}@@ -103,26 +58,18 @@ export const NavigationDrawerAiChatThreadItem = ({return (<NavigationDrawerItemlabel={displayLabel}- Icon={ThreadIcon}active={isActive}onClick={() => onClick(thread)}variant={isArchived ? 'tertiary' : 'default'}- alwaysShowRightOptions+ isRightOptionsDropdownOpen={isDropdownOpen}rightOptions={- <StyledRightOptions>- <StyledTimestamp $isDropdownOpen={isDropdownOpen}>- {timestamp}- </StyledTimestamp>- <StyledMenuTrigger $isDropdownOpen={isDropdownOpen}>- <AiChatThreadItemMenu- threadId={thread.id}- threadTitle={displayLabel}- isArchived={isArchived}- surface={AI_CHAT_THREAD_ACTIONS_SURFACE.NAV_DRAWER}- onRenameRequested={startRename}- />- </StyledMenuTrigger>- </StyledRightOptions>+ <AiChatThreadItemMenu+ threadId={thread.id}+ threadTitle={displayLabel}+ isArchived={isArchived}+ surface={AI_CHAT_THREAD_ACTIONS_SURFACE.NAV_DRAWER}+ onRenameRequested={startRename}+ />}/>);diff --git a/packages/twenty-front/src/modules/ai/components/StyledAiChatContentContainer.tsx b/packages/twenty-front/src/modules/ai/components/StyledAiChatContentContainer.tsxnew file mode 100644index 00000000000..1acbe451132--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/StyledAiChatContentContainer.tsx@@ -0,0 +1,8 @@+import { styled } from '@linaria/react';++export const StyledAiChatContentContainer = styled.div`+ box-sizing: border-box;+ margin-inline: auto;+ max-width: var(--ai-chat-content-max-width, none);+ width: 100%;+`;diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatMessage.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatMessage.stories.tsxindex f965c35b47d..9eae38d1bd9 100644--- a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatMessage.stories.tsx+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatMessage.stories.tsx@@ -3,12 +3,13 @@ import {type Meta,type StoryObj,} from '@storybook/react-vite';-import { useEffect } from 'react';+import { Suspense, useEffect } from 'react';import { userEvent, within } from 'storybook/test';import { type ExtendedUIMessage } from 'twenty-shared/ai';import { ComponentDecorator } from 'twenty-ui/testing';import { AiChatMessage } from '@/ai/components/AiChatMessage';+import { MarkdownLoadingSkeleton } from '@/ai/components/LazyMarkdownRenderer';import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';@@ -288,7 +289,9 @@ const AgentChatInstanceDecorator: Decorator = (Story) => (value={{ instanceId: INSTANCE_ID }}><AgentChatMessagesSetterEffect messages={allMockMessages} />- <Story />+ <Suspense fallback={<MarkdownLoadingSkeleton />}>+ <Story />+ </Suspense></AgentChatComponentInstanceContext.Provider>);diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadInitializationEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadInitializationEffect.test.tsxnew file mode 100644index 00000000000..168eed9c390--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadInitializationEffect.test.tsx@@ -0,0 +1,57 @@+import { act, render } from '@testing-library/react';+import { createStore, Provider as JotaiProvider } from 'jotai';++import { AgentChatThreadInitializationEffect } from '@/ai/components/AgentChatThreadInitializationEffect';+import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';++const refreshAgentChatThreadsMock = jest.fn();++jest.mock('@/ai/hooks/useRefreshAgentChatThreads', () => ({+ useRefreshAgentChatThreads: () => ({+ refreshAgentChatThreads: refreshAgentChatThreadsMock,+ }),+}));++jest.mock('@/settings/roles/hooks/useHasPermissionFlag', () => ({+ useHasPermissionFlag: () => true,+}));++describe('AgentChatThreadInitializationEffect', () => {+ beforeEach(() => {+ jest.useFakeTimers();+ jest.clearAllMocks();+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ it('retries when the initial thread request fails', async () => {+ refreshAgentChatThreadsMock+ .mockResolvedValueOnce(undefined)+ .mockResolvedValueOnce([]);++ render(+ <JotaiProvider store={createStore()}>+ <AgentChatComponentInstanceContext.Provider+ value={{ instanceId: 'agent-chat-initialization-test' }}+ >+ <AgentChatThreadInitializationEffect />+ </AgentChatComponentInstanceContext.Provider>+ </JotaiProvider>,+ );++ await act(async () => {+ await Promise.resolve();+ });++ expect(refreshAgentChatThreadsMock).toHaveBeenCalledTimes(1);++ await act(async () => {+ jest.advanceTimersByTime(3000);+ await Promise.resolve();+ });++ expect(refreshAgentChatThreadsMock).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatAssistantMessageRenderer.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatAssistantMessageRenderer.test.tsxindex 0d5f77f7a8a..502b7d062d4 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatAssistantMessageRenderer.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatAssistantMessageRenderer.test.tsx@@ -27,7 +27,7 @@ jest.mock('@/ai/components/ToolStepRenderer', () => ({}));jest.mock('@/ai/components/LazyMarkdownRenderer', () => ({- LazyMarkdownRenderer: ({ text }: { text: string }) => (+ LazyMarkdownContent: ({ text }: { text: string }) => (<div data-testid="markdown-renderer">{text}</div>),}));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.tsxindex 981b26c462e..ec2445a87d2 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,3 +1,4 @@+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';@@ -18,7 +19,7 @@ jest.mock('@/ai/components/suggested-prompts/AiChatSuggestedPrompts', () => ({}));const INSTANCE_ID = 'aiChatEmptyStateTest';-const THREAD_ID = 'thread-1';+const THREAD_ID = AGENT_CHAT_NEW_THREAD_DRAFT_KEY;const Wrapper = ({ children }: { children: ReactNode }) => (<JotaiProvider store={jotaiStore}>diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageHeader.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageHeader.test.tsxnew file mode 100644index 00000000000..d78688747db--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageHeader.test.tsx@@ -0,0 +1,355 @@+import { i18n } from '@lingui/core';+import { I18nProvider } from '@lingui/react';+import { act, render, screen, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { Provider as JotaiProvider } from 'jotai';+import { type ReactNode } from 'react';+import { MemoryRouter } from 'react-router-dom';++import { AiChatPageHeader } from '@/ai/components/AiChatPageHeader';+import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';+import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';+import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';+import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { currentAiChatThreadTitleComponentFamilyState } from '@/ai/states/currentAiChatThreadTitleComponentFamilyState';+import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';+import {+ jotaiStore,+ resetJotaiStore,+} from '@/ui/utilities/state/jotai/jotaiStore';+import { type AgentChatThread } from '~/generated-metadata/graphql';++const switchToNewChat = jest.fn();+const renameChatThread = jest.fn();+const archiveChatThread = jest.fn();+const unarchiveChatThread = jest.fn();+const deleteChatThread = jest.fn();++jest.mock('@/ai/hooks/useSwitchToNewAiChat', () => ({+ useSwitchToNewAiChat: () => ({ switchToNewChat }),+}));+jest.mock('@/ai/hooks/useRenameChatThread', () => ({+ useRenameChatThread: () => ({ renameChatThread }),+}));+jest.mock('@/ai/hooks/useChatThreadArchiveActions', () => ({+ useChatThreadArchiveActions: () => ({+ archiveChatThread,+ unarchiveChatThread,+ }),+}));+jest.mock('@/ai/hooks/useDeleteChatThread', () => ({+ useDeleteChatThread: () => ({ deleteChatThread }),+}));+jest.mock('@/navigation/hooks/useNavigationDrawerExpanded', () => ({+ useNavigationDrawerExpanded: () => true,+}));+jest.mock('@/ai/components/AiChatCloseButton', () => ({+ AiChatCloseButton: () => <button>Close chat</button>,+}));++const THREAD: AgentChatThread = {+ __typename: 'AgentChatThread',+ id: 'thread-1',+ title: 'Best leads',+ createdAt: '2026-09-01T00:00:00.000Z',+ updatedAt: '2026-09-01T00:00:00.000Z',+ lastMessageAt: '2026-09-01T00:00:00.000Z',+ totalInputTokens: 0,+ totalOutputTokens: 0,+ conversationSize: 0,+ totalInputCredits: 0,+ totalOutputCredits: 0,+};++const Wrapper = ({ children }: { children: ReactNode }) => (+ <JotaiProvider store={jotaiStore}>+ <I18nProvider i18n={i18n}>+ <MemoryRouter>+ <AgentChatComponentInstanceContext.Provider+ value={{ instanceId: 'ai-chat-header-test' }}+ >+ {children}+ </AgentChatComponentInstanceContext.Provider>+ </MemoryRouter>+ </I18nProvider>+ </JotaiProvider>+);++const setThreads = (threads: AgentChatThread[]) => {+ jotaiStore.set(metadataStoreState.atomFamily('agentChatThreads'), {+ current: threads,+ draft: threads,+ status: 'up-to-date',+ });+};++describe('AiChatPageHeader', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ resetJotaiStore();+ setThreads([THREAD]);+ jotaiStore.set(currentAiChatThreadState.atom, THREAD.id);+ renameChatThread.mockResolvedValue(true);+ });++ it.each([null, AGENT_CHAT_NEW_THREAD_DRAFT_KEY])(+ 'hides conversation actions on the new-chat page (%s)',+ (threadId) => {+ jotaiStore.set(currentAiChatThreadState.atom, threadId);+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ expect(screen.getByText('New chat')).toBeVisible();+ expect(screen.queryByRole('button', { name: /^New chat/ })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Chat actions' })).toBeNull();+ },+ );++ it('starts a new chat from the current conversation', async () => {+ const user = userEvent.setup();+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ expect(screen.getByText('Best leads')).toBeVisible();+ await user.click(screen.getByRole('button', { name: /^New chat/ }));+ expect(switchToNewChat).toHaveBeenCalledTimes(1);+ expect(+ screen.queryByRole('button', { name: 'Collapse to side panel' }),+ ).toBeNull();+ });++ it('does not label an existing chat as new while its metadata loads', () => {+ setThreads([]);+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ expect(screen.queryByText('New chat')).toBeNull();+ expect(screen.queryByRole('button', { name: 'Chat actions' })).toBeNull();++ act(() => setThreads([THREAD]));++ expect(screen.getByText('Best leads')).toBeVisible();+ expect(screen.getByRole('button', { name: 'Chat actions' })).toBeVisible();+ });++ it.each([0, 100])(+ 'keeps New chat hidden without messages regardless of token usage (%s)',+ (conversationSize) => {+ setThreads([{ ...THREAD, lastMessageAt: null, conversationSize }]);+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ expect(screen.queryByRole('button', { name: /^New chat/ })).toBeNull();+ },+ );++ it('shows New chat as soon as messages load without a last-message timestamp', () => {+ setThreads([{ ...THREAD, lastMessageAt: null }]);+ jotaiStore.set(agentChatDisplayedThreadState.atom, THREAD.id);+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ expect(screen.queryByRole('button', { name: /^New chat/ })).toBeNull();++ act(() => {+ jotaiStore.set(+ agentChatMessagesComponentFamilyState.atomFamily({+ instanceId: 'ai-chat-header-test',+ familyKey: { threadId: THREAD.id },+ }),+ [{ id: 'message-1', role: 'user', parts: [] }],+ );+ });++ expect(screen.getByRole('button', { name: /^New chat/ })).toBeVisible();+ });++ it('checks the header thread for messages while a different conversation is displayed', () => {+ setThreads([{ ...THREAD, lastMessageAt: null }]);+ jotaiStore.set(agentChatDisplayedThreadState.atom, 'previous-thread');+ jotaiStore.set(+ agentChatMessagesComponentFamilyState.atomFamily({+ instanceId: 'ai-chat-header-test',+ familyKey: { threadId: 'previous-thread' },+ }),+ [{ id: 'previous-message', role: 'user', parts: [] }],+ );+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ expect(screen.queryByRole('button', { name: /^New chat/ })).toBeNull();++ act(() => {+ jotaiStore.set(+ agentChatMessagesComponentFamilyState.atomFamily({+ instanceId: 'ai-chat-header-test',+ familyKey: { threadId: THREAD.id },+ }),+ [{ id: 'current-message', role: 'user', parts: [] }],+ );+ });++ expect(screen.getByRole('button', { name: /^New chat/ })).toBeVisible();+ });++ it('keeps onboarding single-threaded', () => {+ render(<AiChatPageHeader isOnboarding />, { wrapper: Wrapper });++ expect(screen.getByText('Onboarding')).toBeVisible();+ expect(screen.queryByRole('button', { name: /^New chat/ })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Chat actions' })).toBeNull();+ expect(screen.getByRole('button', { name: 'Close chat' })).toBeVisible();+ });++ it('uses the generated title before metadata refreshes and prefers later renames', async () => {+ setThreads([{ ...THREAD, title: null }]);+ const user = userEvent.setup();+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ act(() => {+ jotaiStore.set(+ currentAiChatThreadTitleComponentFamilyState.atomFamily({+ instanceId: 'ai-chat-header-test',+ familyKey: { threadId: THREAD.id },+ }),+ 'Generated title',+ );+ });++ expect(screen.getByText('Generated title')).toBeVisible();+ await user.click(screen.getByRole('button', { name: 'Chat actions' }));+ await user.click(screen.getByText('Rename'));+ expect(screen.getByRole('textbox')).toHaveValue('Generated title');+ await user.keyboard('{Enter}');+ expect(renameChatThread).not.toHaveBeenCalled();++ await user.click(screen.getByRole('button', { name: 'Chat actions' }));+ await user.click(screen.getByText('Delete'));+ expect(+ within(screen.getByRole('dialog')).getByText('Generated title'),+ ).toBeVisible();+ await user.click(screen.getByRole('button', { name: /^Cancel/ }));++ act(() => setThreads([{ ...THREAD, title: 'Renamed title' }]));+ expect(screen.getByText('Renamed title')).toBeVisible();+ expect(screen.queryByText('Generated title')).toBeNull();+ });++ it('offers archive and unarchive even when the current chat is filtered out of the sidebar', async () => {+ const user = userEvent.setup();+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ await user.click(screen.getByRole('button', { name: 'Chat actions' }));+ await user.click(screen.getByText('Archive'));+ expect(archiveChatThread).toHaveBeenCalledWith(THREAD.id);++ act(() => setThreads([{ ...THREAD, deletedAt: '2026-09-07T00:00:00Z' }]));++ expect(screen.getByText('Best leads')).toBeVisible();+ await user.click(screen.getByRole('button', { name: 'Chat actions' }));+ await user.click(screen.getByText('Unarchive'));+ expect(unarchiveChatThread).toHaveBeenCalledWith(THREAD.id);+ });++ it('renames the current chat and discards the rename editor when switching threads', async () => {+ const user = userEvent.setup();+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ await user.click(screen.getByRole('button', { name: 'Chat actions' }));+ await user.click(screen.getByText('Rename'));+ const input = screen.getByRole('textbox');+ await user.clear(input);+ await user.type(input, 'Qualified leads{Enter}');+ expect(renameChatThread).toHaveBeenCalledWith(THREAD.id, 'Qualified leads');++ await user.click(screen.getByRole('button', { name: 'Chat actions' }));+ await user.click(screen.getByText('Rename'));+ act(() => {+ setThreads([THREAD, { ...THREAD, id: 'thread-2', title: 'Other chat' }]);+ jotaiStore.set(currentAiChatThreadState.atom, 'thread-2');+ });+ expect(screen.queryByRole('textbox')).toBeNull();+ expect(screen.getByText('Other chat')).toBeVisible();+ });++ it.each(['{Enter}', '{Tab}', '{Shift>}{Tab}{/Shift}'])(+ 'saves once and leaves the rename editor on %s',+ async (key) => {+ const user = userEvent.setup();+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ await user.click(screen.getByRole('button', { name: 'Chat actions' }));+ await user.click(screen.getByText('Rename'));+ await user.clear(screen.getByRole('textbox'));+ await user.type(screen.getByRole('textbox'), 'Qualified leads');+ await user.keyboard(key);++ expect(renameChatThread).toHaveBeenCalledTimes(1);+ expect(renameChatThread).toHaveBeenCalledWith(+ THREAD.id,+ 'Qualified leads',+ );+ expect(screen.queryByRole('textbox')).toBeNull();+ },+ );++ it('saves when clicking outside without swallowing the next action', async () => {+ const user = userEvent.setup();+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ await user.click(screen.getByRole('button', { name: 'Chat actions' }));+ await user.click(screen.getByText('Rename'));+ await user.clear(screen.getByRole('textbox'));+ await user.type(screen.getByRole('textbox'), 'Qualified leads');+ await user.click(screen.getByRole('button', { name: /^New chat/ }));++ expect(renameChatThread).toHaveBeenCalledTimes(1);+ expect(renameChatThread).toHaveBeenCalledWith(THREAD.id, 'Qualified leads');+ expect(screen.queryByRole('textbox')).toBeNull();+ expect(switchToNewChat).toHaveBeenCalledTimes(1);+ });++ it('discards the draft on Escape without saving', async () => {+ const user = userEvent.setup();+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ await user.click(screen.getByRole('button', { name: 'Chat actions' }));+ await user.click(screen.getByText('Rename'));+ await user.clear(screen.getByRole('textbox'));+ await user.type(screen.getByRole('textbox'), 'Discard this{Escape}');++ expect(renameChatThread).not.toHaveBeenCalled();+ expect(screen.queryByRole('textbox')).toBeNull();+ expect(screen.getByText('Best leads')).toBeVisible();+ });++ it('preserves the draft for retry when saving fails', async () => {+ renameChatThread.mockResolvedValueOnce(false);+ const user = userEvent.setup();+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ await user.click(screen.getByRole('button', { name: 'Chat actions' }));+ await user.click(screen.getByText('Rename'));+ await user.clear(screen.getByRole('textbox'));+ await user.type(screen.getByRole('textbox'), 'Qualified leads{Enter}');++ expect(screen.getByRole('textbox')).toHaveValue('Qualified leads');+ expect(screen.getByRole('textbox')).not.toHaveFocus();+ await user.click(screen.getByRole('textbox'));+ await user.keyboard('{Enter}');++ expect(renameChatThread).toHaveBeenCalledTimes(2);+ expect(renameChatThread).toHaveBeenLastCalledWith(+ THREAD.id,+ 'Qualified leads',+ );+ expect(screen.queryByRole('textbox')).toBeNull();+ });++ it('requires confirmation before deleting the current chat', async () => {+ const user = userEvent.setup();+ render(<AiChatPageHeader isOnboarding={false} />, { wrapper: Wrapper });++ await user.click(screen.getByRole('button', { name: 'Chat actions' }));+ await user.click(screen.getByText('Delete'));+ expect(screen.getByText('Delete chat')).toBeVisible();+ expect(deleteChatThread).not.toHaveBeenCalled();+ await user.click(screen.getByRole('button', { name: /^Delete/ }));+ expect(deleteChatThread).toHaveBeenCalledWith(THREAD.id);+ });+});diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageThreadUrlSyncEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageThreadUrlSyncEffect.test.tsxindex d5f5f22fb06..47a273c1e8d 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageThreadUrlSyncEffect.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageThreadUrlSyncEffect.test.tsx@@ -6,6 +6,7 @@ import { AppPath } from 'twenty-shared/types';import { AiChatPageThreadUrlSyncEffect } from '@/ai/components/AiChatPageThreadUrlSyncEffect';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';import {jotaiStore,resetJotaiStore,@@ -14,6 +15,18 @@ import {const switchThreadWithDraftMock = jest.fn((toThreadId: string) => {jotaiStore.set(currentAiChatThreadState.atom, toThreadId);});+const switchToNewChatMock = jest.fn();+const refreshAgentChatThreadsMock = jest.fn();++jest.mock('@/ai/hooks/useSwitchToNewAiChat', () => ({+ useSwitchToNewAiChat: () => ({ switchToNewChat: switchToNewChatMock }),+}));++jest.mock('@/ai/hooks/useRefreshAgentChatThreads', () => ({+ useRefreshAgentChatThreads: () => ({+ refreshAgentChatThreads: refreshAgentChatThreadsMock,+ }),+}));jest.mock('@/ai/hooks/useSwitchAgentChatThreadWithDraft', () => ({useSwitchAgentChatThreadWithDraft: () => ({@@ -53,6 +66,7 @@ const renderEffectAt = (initialPath: string) =>describe('AiChatPageThreadUrlSyncEffect', () => {beforeEach(() => {jest.clearAllMocks();+ refreshAgentChatThreadsMock.mockResolvedValue([]);resetJotaiStore();navigateToThread = undefined;});@@ -65,6 +79,54 @@ describe('AiChatPageThreadUrlSyncEffect', () => {expect(switchThreadWithDraftMock).toHaveBeenCalledWith(THREAD_A);});+ it('recovers a missing chat only after refreshing the loaded thread list', async () => {+ renderEffectAt(`/chat/${THREAD_A}`);++ expect(switchToNewChatMock).not.toHaveBeenCalled();+ expect(refreshAgentChatThreadsMock).not.toHaveBeenCalled();++ await act(async () => {+ jotaiStore.set(metadataStoreState.atomFamily('agentChatThreads'), {+ current: [],+ draft: [],+ status: 'up-to-date',+ });+ });++ expect(refreshAgentChatThreadsMock).toHaveBeenCalledTimes(1);+ expect(switchToNewChatMock).toHaveBeenCalledTimes(1);+ });++ it('keeps a valid chat URL found by refreshing a stale thread list', async () => {+ refreshAgentChatThreadsMock.mockResolvedValue([{ id: THREAD_A }]);+ jotaiStore.set(metadataStoreState.atomFamily('agentChatThreads'), {+ current: [{ id: THREAD_B }],+ draft: [],+ status: 'up-to-date',+ });++ await act(async () => {+ renderEffectAt(`/chat/${THREAD_A}`);+ });++ expect(refreshAgentChatThreadsMock).toHaveBeenCalledTimes(1);+ expect(switchToNewChatMock).not.toHaveBeenCalled();+ });++ it('keeps an archived chat URL when the thread exists in metadata', () => {+ jotaiStore.set(metadataStoreState.atomFamily('agentChatThreads'), {+ current: [{ id: THREAD_A, deletedAt: '2026-09-07T00:00:00Z' }],+ draft: [],+ status: 'up-to-date',+ });++ renderEffectAt(`/chat/${THREAD_A}`);++ expect(switchThreadWithDraftMock).toHaveBeenCalledWith(THREAD_A);+ expect(refreshAgentChatThreadsMock).not.toHaveBeenCalled();+ expect(switchToNewChatMock).not.toHaveBeenCalled();+ });+it('should adopt the thread the browser navigated to', () => {jotaiStore.set(currentAiChatThreadState.atom, THREAD_A);diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatTabMessageList.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatTabMessageList.test.tsxindex e4130da489c..d2118d45c15 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatTabMessageList.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatTabMessageList.test.tsx@@ -65,12 +65,6 @@ jest.mock(AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect: () => null,}),);-jest.mock(- '@/ai/components/AgentChatPinScrollToBottomOnMountLayoutEffect',- () => ({- AgentChatPinScrollToBottomOnMountLayoutEffect: () => null,- }),-);jest.mock('@/ai/components/AgentChatStreamingAutoScrollEffect', () => ({AgentChatStreamingAutoScrollEffect: () => null,}));diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatTabMessageListPreamble.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatTabMessageListPreamble.test.tsxindex f41d86b7905..f451dd72617 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatTabMessageListPreamble.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatTabMessageListPreamble.test.tsx@@ -1,6 +1,9 @@-import { render } from '@testing-library/react';+import { act, render, screen } from '@testing-library/react';import { Provider as JotaiProvider } from 'jotai';import { type ReactNode } from 'react';+import type * as React from 'react';+import { AiChatNonLastMessageIdsList } from '@/ai/components/AiChatNonLastMessageIdsList';+import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';import { AiChatTabMessageList } from '@/ai/components/AiChatTabMessageList';import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';@@ -25,7 +28,7 @@ jest.mock('@/ui/utilities/scroll/components/ScrollWrapper', () => ({}));jest.mock('@/ai/components/AiChatNonLastMessageIdsList', () => ({- AiChatNonLastMessageIdsList: () => null,+ AiChatNonLastMessageIdsList: jest.fn(() => null),}));jest.mock('@/ai/components/AiChatLastMessageWithStreamingState', () => ({AiChatLastMessageWithStreamingState: () => null,@@ -36,22 +39,28 @@ jest.mock('@/ai/components/AiChatErrorUnderMessageList', () => ({jest.mock('@/ai/components/AiChatScrollToBottomButton', () => ({AiChatScrollToBottomButton: () => null,}));+const mockPinScrollToBottom = jest.fn();+jest.mock('@/ai/components/AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect',- () => ({- AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect: () => null,- }),-);-jest.mock(- '@/ai/components/AgentChatPinScrollToBottomOnMountLayoutEffect',- () => ({- AgentChatPinScrollToBottomOnMountLayoutEffect: () => null,- }),+ () => {+ const { useLayoutEffect } = jest.requireActual<typeof React>('react');+ return {+ AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect: () => {+ useLayoutEffect(mockPinScrollToBottom, []);+ return null;+ },+ };+ },);jest.mock('@/ai/components/AgentChatStreamingAutoScrollEffect', () => ({AgentChatStreamingAutoScrollEffect: () => null,}));+jest.mock('@/ai/components/LazyMarkdownRenderer', () => ({+ MarkdownLoadingSkeleton: () => <div role="status">Loading conversation</div>,+}));+const INSTANCE_ID = 'aiChatTabMessageListPreambleTest';const THREAD_ID = 'thread-1';@@ -100,3 +109,51 @@ describe('AiChatTabMessageList preamble branch', () => {expect(queryByTestId('initial-loading-indicator')).not.toBeInTheDocument();});});++describe('AiChatTabMessageList loading', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ resetJotaiStore();+ jotaiStore.set(agentChatDisplayedThreadState.atom, THREAD_ID);+ jotaiStore.set(+ agentChatMessagesComponentFamilyState.atomFamily({+ instanceId: INSTANCE_ID,+ familyKey: { threadId: THREAD_ID },+ }),+ [{ id: 'message-1', role: 'user', parts: [] }],+ );+ });++ it('shows one placeholder and waits for message content before positioning the conversation', async () => {+ let finishLoading = () => {};+ let isLoaded = false;+ const loading = new Promise<void>((resolve) => {+ finishLoading = resolve;+ });++ jest.mocked(AiChatNonLastMessageIdsList).mockImplementation(() => {+ if (!isLoaded) {+ throw loading;+ }+ return Array.from({ length: 16 }, (_, index) => (+ <div key={index}>Message {index + 1}</div>+ ));+ });++ renderPreambleBranch();++ expect(screen.getAllByRole('status')).toHaveLength(1);+ expect(screen.queryByText('Message 1')).not.toBeInTheDocument();+ expect(mockPinScrollToBottom).not.toHaveBeenCalled();++ await act(async () => {+ isLoaded = true;+ finishLoading();+ await loading;+ });++ expect(screen.queryByRole('status')).not.toBeInTheDocument();+ expect(screen.getAllByText(/^Message /)).toHaveLength(16);+ expect(mockPinScrollToBottom).toHaveBeenCalled();+ });+});diff --git a/packages/twenty-front/src/modules/ai/components/internal/AiChatSkeletonLoader.tsx b/packages/twenty-front/src/modules/ai/components/internal/AiChatSkeletonLoader.tsxindex 6d54996062b..886bb3d2b67 100644--- a/packages/twenty-front/src/modules/ai/components/internal/AiChatSkeletonLoader.tsx+++ b/packages/twenty-front/src/modules/ai/components/internal/AiChatSkeletonLoader.tsx@@ -1,65 +1,18 @@+import { StyledAiChatContentContainer } from '@/ai/components/StyledAiChatContentContainer';import { styled } from '@linaria/react';import { useContext } from 'react';import Skeleton, { SkeletonTheme } from 'react-loading-skeleton';import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';-import { agentChatMessagesLoadingState } from '@/ai/states/agentChatMessagesLoadingState';-import { agentChatThreadsLoadingState } from '@/ai/states/agentChatThreadsLoadingState';-import { agentChatHasMessageComponentSelector } from '@/ai/states/selectors/agentChatHasMessageComponentSelector';-import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';-import { skipMessagesSkeletonUntilLoadedState } from '@/ai/states/skipMessagesSkeletonUntilLoadedState';-import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';--const StyledSkeletonContainer = styled.div`+const StyledSkeletonContainer = styled(StyledAiChatContentContainer)`display: flex;flex: 1;flex-direction: column;- gap: ${themeCssVariables.spacing[6]};padding: ${themeCssVariables.spacing[3]};`;-const StyledMessageBubble = styled.div`- align-items: center;- display: flex;- gap: ${themeCssVariables.spacing[3]};-`;--const StyledMessageSkeleton = styled.div`- width: 100%;-`;--const NUMBER_OF_SKELETONS = 6;-export const AiChatSkeletonLoader = () => {const { theme } = useContext(ThemeContext);- const agentChatThreadsLoading = useAtomStateValue(- agentChatThreadsLoadingState,- );- const agentChatMessagesLoading = useAtomStateValue(- agentChatMessagesLoadingState,- );- const skipMessagesSkeletonUntilLoaded = useAtomStateValue(- skipMessagesSkeletonUntilLoadedState,- );- const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);-- const hasMessages = useAtomComponentSelectorValue(- agentChatHasMessageComponentSelector,- );-- const isOnNewChatSlot =- currentAiChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY;- const showForMessagesLoading =- agentChatMessagesLoading && !skipMessagesSkeletonUntilLoaded;- const shouldRender =- !hasMessages &&- ((agentChatThreadsLoading && isOnNewChatSlot) || showForMessagesLoading);-- if (!shouldRender) {- return null;- }return (<SkeletonTheme@@ -68,15 +21,7 @@ export const AiChatSkeletonLoader = () => {borderRadius={4}><StyledSkeletonContainer>- {Array.from({ length: NUMBER_OF_SKELETONS }).map((_, index) => (- <StyledMessageBubble key={index}>- <Skeleton width={24} height={24} borderRadius={4} />-- <StyledMessageSkeleton>- <Skeleton height={20} borderRadius={8} />- </StyledMessageSkeleton>- </StyledMessageBubble>- ))}+ <Skeleton height={20} borderRadius={8} /></StyledSkeletonContainer></SkeletonTheme>);diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatThreadActionsSurface.ts b/packages/twenty-front/src/modules/ai/constants/AiChatThreadActionsSurface.tsindex 196f0165838..2cfc361c839 100644--- a/packages/twenty-front/src/modules/ai/constants/AiChatThreadActionsSurface.ts+++ b/packages/twenty-front/src/modules/ai/constants/AiChatThreadActionsSurface.ts@@ -1,4 +1,5 @@export const AI_CHAT_THREAD_ACTIONS_SURFACE = {SIDE_PANEL: 'side-panel',NAV_DRAWER: 'nav-drawer',+ PAGE_HEADER: 'page-header',} as const;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.tsxindex fb12f20e229..5181ae8250f 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,5 @@-import { renderHook } from '@testing-library/react';+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';@@ -9,6 +10,7 @@ import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';import { useIsAiChatComposerCentered } from '@/ai/hooks/useIsAiChatComposerCentered';import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';+import { agentChatMessagesLoadingState } from '@/ai/states/agentChatMessagesLoadingState';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';import { type AiChatSurface } from '@/ai/types/AiChatSurface';import {@@ -17,7 +19,7 @@ import {} from '@/ui/utilities/state/jotai/jotaiStore';const INSTANCE_ID = 'aiChatComposerCenteredTest';-const THREAD_ID = 'thread-1';+const THREAD_ID = AGENT_CHAT_NEW_THREAD_DRAFT_KEY;const renderForSurface = ({surface = AI_CHAT_SURFACE.PAGE,@@ -56,6 +58,31 @@ describe('useIsAiChatComposerCentered', () => {expect(result.current).toBe(true);});+ it('centers a new draft even if the previous conversation was still loading', () => {+ jotaiStore.set(agentChatMessagesLoadingState.atom, true);+ const { result } = renderForSurface();++ expect(result.current).toBe(true);+ });++ it('keeps an existing conversation bottom-aligned before, during and after fetching messages', () => {+ jotaiStore.set(currentAiChatThreadState.atom, 'existing-thread');+ jotaiStore.set(agentChatDisplayedThreadState.atom, 'existing-thread');+ const { result } = renderForSurface();++ expect(result.current).toBe(false);+ act(() => jotaiStore.set(agentChatMessagesLoadingState.atom, true));+ expect(result.current).toBe(false);+ act(() => jotaiStore.set(agentChatMessagesLoadingState.atom, false));+ 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();+ expect(result.current).toBe(false);+ });+it('should not center the composer in the side panel', () => {const { result } = renderForSurface({surface: AI_CHAT_SURFACE.SIDE_PANEL,diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsxnew file mode 100644index 00000000000..94ed1ccbcbf--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsx@@ -0,0 +1,152 @@+import { act, renderHook } from '@testing-library/react';+import { createStore, Provider as JotaiProvider } from 'jotai';+import { type ReactNode } from 'react';++import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';+import { clearMetadataStoreStorage } from '@/metadata-store/storage/metadataStoreStorage';+import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';+import { type AgentChatThread } from '~/generated-metadata/graphql';++const queryMock = jest.fn();++jest.mock('@apollo/client/react', () => ({+ ...jest.requireActual('@apollo/client/react'),+ useApolloClient: () => ({ query: queryMock }),+}));++const buildThread = (id: string, title: string): AgentChatThread => ({+ __typename: 'AgentChatThread',+ id,+ title,+ createdAt: '2026-09-07T00:00:00.000Z',+ updatedAt: '2026-09-07T00:00:00.000Z',+ lastMessageAt: '2026-09-07T00:00:00.000Z',+ totalInputTokens: 0,+ totalOutputTokens: 0,+ conversationSize: 0,+ totalInputCredits: 0,+ totalOutputCredits: 0,+});++const getWrapper = (store: ReturnType<typeof createStore>) =>+ function Wrapper({ children }: { children: ReactNode }) {+ return <JotaiProvider store={store}>{children}</JotaiProvider>;+ };++describe('useRefreshAgentChatThreads', () => {+ beforeEach(async () => {+ await clearMetadataStoreStorage();+ jest.clearAllMocks();+ });++ it('loads chat threads into an empty store', async () => {+ const store = createStore();+ const thread = buildThread('thread-1', 'Loaded thread');+ queryMock.mockResolvedValue({ data: { chatThreads: [thread] } });+ const { result } = renderHook(() => useRefreshAgentChatThreads(), {+ wrapper: getWrapper(store),+ });++ await act(async () => {+ await result.current.refreshAgentChatThreads();+ });++ expect(+ store.get(metadataStoreState.atomFamily('agentChatThreads')),+ ).toMatchObject({+ current: [thread],+ status: 'up-to-date',+ });+ });++ it('retries when the store changes during the request', async () => {+ const store = createStore();+ const newerThread = buildThread('thread-1', 'Newer title');+ const staleThread = buildThread('thread-1', 'Stale title');+ const serverOnlyThread = buildThread('thread-2', 'Server thread');+ let resolveQuery: (value: {+ data: { chatThreads: AgentChatThread[] };+ }) => void = () => undefined;++ queryMock+ .mockReturnValueOnce(+ new Promise((resolve) => {+ resolveQuery = resolve;+ }),+ )+ .mockResolvedValueOnce({+ data: { chatThreads: [newerThread, serverOnlyThread] },+ });+ const { result } = renderHook(() => useRefreshAgentChatThreads(), {+ wrapper: getWrapper(store),+ });++ const refreshPromise = result.current.refreshAgentChatThreads();++ act(() => {+ store.set(metadataStoreState.atomFamily('agentChatThreads'), {+ current: [newerThread],+ draft: [],+ status: 'up-to-date',+ });+ });++ let refreshedThreads: AgentChatThread[] | undefined;++ await act(async () => {+ resolveQuery({ data: { chatThreads: [staleThread] } });+ refreshedThreads = await refreshPromise;+ });++ expect(refreshedThreads).toEqual([newerThread, serverOnlyThread]);+ expect(queryMock).toHaveBeenCalledTimes(2);+ expect(+ store.get(metadataStoreState.atomFamily('agentChatThreads')).current,+ ).toEqual([newerThread, serverOnlyThread]);+ });++ it('applies server updates and removals when the store has not changed', async () => {+ const store = createStore();+ const staleThread = buildThread('thread-1', 'Stale title');+ const refreshedThread = buildThread('thread-1', 'Refreshed title');+ const removedThread = buildThread('thread-2', 'Removed thread');+ store.set(metadataStoreState.atomFamily('agentChatThreads'), {+ current: [staleThread, removedThread],+ draft: [],+ status: 'up-to-date',+ });+ queryMock.mockResolvedValue({+ data: { chatThreads: [refreshedThread] },+ });+ const { result } = renderHook(() => useRefreshAgentChatThreads(), {+ wrapper: getWrapper(store),+ });++ await act(async () => {+ await result.current.refreshAgentChatThreads();+ });++ expect(+ store.get(metadataStoreState.atomFamily('agentChatThreads')).current,+ ).toEqual([refreshedThread]);+ });++ it('keeps the store empty so initialization can retry a failed request', async () => {+ const store = createStore();+ queryMock.mockRejectedValue(new Error('Network error'));+ const { result } = renderHook(() => useRefreshAgentChatThreads(), {+ wrapper: getWrapper(store),+ });++ await act(async () => {+ await result.current.refreshAgentChatThreads();+ });++ expect(+ store.get(metadataStoreState.atomFamily('agentChatThreads')),+ ).toMatchObject({+ current: [],+ status: 'empty',+ });+ });+});diff --git a/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts b/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.tsnew file mode 100644index 00000000000..55a26b3fdd1--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts@@ -0,0 +1,50 @@+import { useApolloClient } from '@apollo/client/react';+import { useStore } from 'jotai';+import { useCallback } from 'react';+import { isDefined } from 'twenty-shared/utils';++import { useUpdateMetadataStoreDraft } from '@/metadata-store/hooks/useUpdateMetadataStoreDraft';+import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';+import { GetChatThreadsDocument } from '~/generated-metadata/graphql';++export const useRefreshAgentChatThreads = () => {+ const client = useApolloClient();+ const store = useStore();+ const { replaceDraft, applyChanges } = useUpdateMetadataStoreDraft();++ const refreshAgentChatThreads = useCallback(async () => {+ while (true) {+ const storeEntryBeforeRequest = store.get(+ metadataStoreState.atomFamily('agentChatThreads'),+ );+ const result = await client+ .query({+ query: GetChatThreadsDocument,+ fetchPolicy: 'network-only',+ })+ .catch(() => undefined);++ const agentChatThreads = result?.data?.chatThreads;++ if (!isDefined(agentChatThreads)) {+ return undefined;+ }++ // Retry with a fresh server snapshot when a local or subscription update+ // arrives during the request.+ if (+ store.get(metadataStoreState.atomFamily('agentChatThreads')) !==+ storeEntryBeforeRequest+ ) {+ continue;+ }++ replaceDraft('agentChatThreads', agentChatThreads);+ applyChanges();++ return agentChatThreads;+ }+ }, [client, store, replaceDraft, applyChanges]);++ return { refreshAgentChatThreads };+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useShouldShowAiChatEmptyState.ts b/packages/twenty-front/src/modules/ai/hooks/useShouldShowAiChatEmptyState.tsindex 17176c31eec..75469ced5cb 100644--- a/packages/twenty-front/src/modules/ai/hooks/useShouldShowAiChatEmptyState.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useShouldShowAiChatEmptyState.ts@@ -4,11 +4,9 @@ import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThimport { agentChatErrorComponentFamilyState } from '@/ai/states/agentChatErrorComponentFamilyState';import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkComponentFamilyState';import { agentChatIsStreamingComponentFamilyState } from '@/ai/states/agentChatIsStreamingComponentFamilyState';-import { agentChatMessagesLoadingState } from '@/ai/states/agentChatMessagesLoadingState';import { agentChatThreadsLoadingState } from '@/ai/states/agentChatThreadsLoadingState';import { agentChatHasMessageComponentSelector } from '@/ai/states/selectors/agentChatHasMessageComponentSelector';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';-import { skipMessagesSkeletonUntilLoadedState } from '@/ai/states/skipMessagesSkeletonUntilLoadedState';import { useIsMobile } from '@/ui/utilities/responsive/hooks/useIsMobile';import { useAtomComponentFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateValue';import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';@@ -31,12 +29,6 @@ export const useShouldShowAiChatEmptyState = () => {const agentChatThreadsLoading = useAtomStateValue(agentChatThreadsLoadingState,);- const agentChatMessagesLoading = useAtomStateValue(- agentChatMessagesLoadingState,- );- const skipMessagesSkeletonUntilLoaded = useAtomStateValue(- skipMessagesSkeletonUntilLoadedState,- );const hasMessages = useAtomComponentSelectorValue(agentChatHasMessageComponentSelector,@@ -46,15 +38,13 @@ export const useShouldShowAiChatEmptyState = () => {const isOnNewChatSlot =currentAiChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY;- const skeletonShowing =- (agentChatThreadsLoading && isOnNewChatSlot) ||- (agentChatMessagesLoading && !skipMessagesSkeletonUntilLoaded);return (+ isOnNewChatSlot &&!isMobile &&!hasMessages &&!isDefined(agentChatError) &&- !skeletonShowing &&+ !agentChatThreadsLoading &&!agentChatIsAwaitingFirstChunk &&!agentChatIsStreaming);diff --git a/packages/twenty-front/src/modules/ai/states/agentChatIsInitialScrollPendingOnThreadChangeState.ts b/packages/twenty-front/src/modules/ai/states/agentChatIsInitialScrollPendingOnThreadChangeState.tsdeleted file mode 100644index 04bf3291224..00000000000--- a/packages/twenty-front/src/modules/ai/states/agentChatIsInitialScrollPendingOnThreadChangeState.ts+++ /dev/null@@ -1,7 +0,0 @@-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';--export const agentChatIsInitialScrollPendingOnThreadChangeState =- createAtomState<boolean>({- key: 'ai/agentChatIsInitialScrollPendingOnThreadChangeState',- defaultValue: false,- });diff --git a/packages/twenty-front/src/modules/ai/states/selectors/currentAiChatThreadDataSelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/currentAiChatThreadDataSelector.tsnew file mode 100644index 00000000000..8195c138e5a--- /dev/null+++ b/packages/twenty-front/src/modules/ai/states/selectors/currentAiChatThreadDataSelector.ts@@ -0,0 +1,17 @@+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';+import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';+import { createAtomSelector } from '@/ui/utilities/state/jotai/utils/createAtomSelector';++export const currentAiChatThreadDataSelector = createAtomSelector<+ FlatAgentChatThread | undefined+>({+ key: 'currentAiChatThreadDataSelector',+ get: ({ get }) => {+ const currentThreadId = get(currentAiChatThreadState);+ const storeItem = get(metadataStoreState, 'agentChatThreads');+ const threads = storeItem.current as FlatAgentChatThread[];++ return threads.find((thread) => thread.id === currentThreadId);+ },+});diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/pinAiChatScrollToBottom.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/pinAiChatScrollToBottom.test.tsindex 26907f7527e..d6ce3a558e0 100644--- a/packages/twenty-front/src/modules/ai/utils/__tests__/pinAiChatScrollToBottom.test.ts+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/pinAiChatScrollToBottom.test.ts@@ -147,18 +147,15 @@ describe('pinAiChatScrollToBottom', () => {it('should stop once the content is quiet and the minimum duration has elapsed', () => {const scrollWrapperElement = buildScrollWrapperElement();- const onContentSettled = jest.fn();const onPinningStopped = jest.fn();pinAiChatScrollToBottom({scrollWrapperElement,- onContentSettled,onPinningStopped,});advanceFrames(framesToCover(AI_CHAT_SCROLL_PIN_MIN_DURATION_IN_MS));- expect(onContentSettled).toHaveBeenCalledTimes(1);expect(onPinningStopped).toHaveBeenCalledTimes(1);});@@ -196,18 +193,15 @@ describe('pinAiChatScrollToBottom', () => {it('should stop immediately when the user scrolls', () => {const scrollWrapperElement = buildScrollWrapperElement();- const onContentSettled = jest.fn();const onPinningStopped = jest.fn();pinAiChatScrollToBottom({scrollWrapperElement,- onContentSettled,onPinningStopped,});listenersByEventName.get('wheel')?.(new Event('wheel'));- expect(onContentSettled).toHaveBeenCalledTimes(1);expect(onPinningStopped).toHaveBeenCalledTimes(1);scrollWrapperElement.scrollHeight = 9000;@@ -218,29 +212,24 @@ describe('pinAiChatScrollToBottom', () => {it('should stop via the watchdog when frames never run', () => {const scrollWrapperElement = buildScrollWrapperElement();- const onContentSettled = jest.fn();const onPinningStopped = jest.fn();pinAiChatScrollToBottom({scrollWrapperElement,- onContentSettled,onPinningStopped,});jest.advanceTimersByTime(AI_CHAT_SCROLL_PIN_MAX_DURATION_IN_MS);- expect(onContentSettled).toHaveBeenCalledTimes(1);expect(onPinningStopped).toHaveBeenCalledTimes(1);});- it('should invoke each callback exactly once when stopped by the caller', () => {+ it('should invoke the stop callback exactly once when stopped by the caller', () => {const scrollWrapperElement = buildScrollWrapperElement();- const onContentSettled = jest.fn();const onPinningStopped = jest.fn();const stop = pinAiChatScrollToBottom({scrollWrapperElement,- onContentSettled,onPinningStopped,});@@ -248,7 +237,6 @@ describe('pinAiChatScrollToBottom', () => {stop();jest.advanceTimersByTime(AI_CHAT_SCROLL_PIN_MAX_DURATION_IN_MS);- expect(onContentSettled).toHaveBeenCalledTimes(1);expect(onPinningStopped).toHaveBeenCalledTimes(1);expect(listenersByEventName.size).toBe(0);});diff --git a/packages/twenty-front/src/modules/ai/utils/pinAiChatScrollToBottom.ts b/packages/twenty-front/src/modules/ai/utils/pinAiChatScrollToBottom.tsindex 8ba68eba295..443a15ebc5e 100644--- a/packages/twenty-front/src/modules/ai/utils/pinAiChatScrollToBottom.ts+++ b/packages/twenty-front/src/modules/ai/utils/pinAiChatScrollToBottom.ts@@ -8,13 +8,11 @@ import { scrollAiChatToBottom } from '@/ai/utils/scrollAiChatToBottom';type PinAiChatScrollToBottomParams = {scrollWrapperElement: HTMLElement;- onContentSettled?: () => void;onPinningStopped?: () => void;};export const pinAiChatScrollToBottom = ({scrollWrapperElement,- onContentSettled,onPinningStopped,}: PinAiChatScrollToBottomParams) => {const startedAtInMs = performance.now();@@ -24,18 +22,8 @@ export const pinAiChatScrollToBottom = ({let lastClientWidthInPx = -1;let lastChangeAtInMs = startedAtInMs;let animationFrameId: number | undefined;- let hasSettled = false;let hasStopped = false;- const settle = () => {- if (hasSettled) {- return;- }-- hasSettled = true;- onContentSettled?.();- };-const stop = () => {if (hasStopped) {return;@@ -53,7 +41,6 @@ export const pinAiChatScrollToBottom = ({scrollWrapperElement.removeEventListener(eventName, stop),);- settle();onPinningStopped?.();};@@ -79,10 +66,6 @@ export const pinAiChatScrollToBottom = ({const isQuiet =nowInMs - lastChangeAtInMs >= AI_CHAT_SCROLL_PIN_QUIET_DURATION_IN_MS;- if (isQuiet) {- settle();- }-if (isQuiet &&nowInMs - startedAtInMs >= AI_CHAT_SCROLL_PIN_MIN_DURATION_IN_MSdiff --git a/packages/twenty-front/src/modules/side-panel/components/SidePanelAskAiHandoffEffect.tsx b/packages/twenty-front/src/modules/side-panel/components/SidePanelAskAiHandoffEffect.tsxindex c33460130fd..7a496f2c08c 100644--- a/packages/twenty-front/src/modules/side-panel/components/SidePanelAskAiHandoffEffect.tsx+++ b/packages/twenty-front/src/modules/side-panel/components/SidePanelAskAiHandoffEffect.tsx@@ -6,6 +6,7 @@ import { shouldContinueAiChatInSidePanelState } from '@/ai/states/shouldContinueimport { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';import { useOpenAskAiPageInSidePanel } from '@/side-panel/hooks/useOpenAskAiPageInSidePanel';import { isAiChatPath } from '~/utils/isAiChatPath';+import { isSettingsPath } from '~/utils/isSettingsPath';type SidePanelAskAiHandoffEffectProps = {onContinueChatFromFullWidth: () => void;@@ -30,6 +31,10 @@ export const SidePanelAskAiHandoffEffect = ({store.set(shouldContinueAiChatInSidePanelState.atom, false);store.set(shouldOpenAiChatAfterOnboardingState.atom, false);+ if (isSettingsPath(pathname)) {+ return;+ }+onContinueChatFromFullWidth();openAskAiPage({ resetNavigationStack: true });}, [pathname, store, openAskAiPage, onContinueChatFromFullWidth]);diff --git a/packages/twenty-front/src/modules/side-panel/components/__tests__/SidePanelAskAiHandoffEffect.test.tsx b/packages/twenty-front/src/modules/side-panel/components/__tests__/SidePanelAskAiHandoffEffect.test.tsxindex dcab40bad89..19e69a64d49 100644--- a/packages/twenty-front/src/modules/side-panel/components/__tests__/SidePanelAskAiHandoffEffect.test.tsx+++ b/packages/twenty-front/src/modules/side-panel/components/__tests__/SidePanelAskAiHandoffEffect.test.tsx@@ -19,12 +19,13 @@ jest.mock('@/side-panel/hooks/useOpenAskAiPageInSidePanel', () => ({const onContinueChatFromFullWidthMock = jest.fn();-let navigateAwayFromChatPage: (() => void) | undefined;+let navigateAwayFromChatPage: ((pathname?: string) => void) | undefined;const ChatPageRoute = () => {const navigate = useNavigate();- navigateAwayFromChatPage = () => navigate('/objects/companies');+ navigateAwayFromChatPage = (pathname = '/objects/companies') =>+ navigate(pathname);return <AiChatPageContinueInSidePanelEffect />;};@@ -39,6 +40,7 @@ const RouterUnderTest = ({ initialPath }: { initialPath: string }) => (<Routes><Route path="/chat/:threadId?" element={<ChatPageRoute />} /><Route path="/objects/companies" element={<div />} />+ <Route path="/settings/*" element={<div />} /></Routes></MemoryRouter></JotaiProvider>@@ -90,6 +92,31 @@ describe('SidePanelAskAiHandoffEffect', () => {expect(onContinueChatFromFullWidthMock).not.toHaveBeenCalled();});+ it.each(['/chat', '/chat/existing-thread'])(+ 'does not move the chat from %s into the side panel when opening settings or leaving them',+ (initialPath) => {+ jotaiStore.set(shouldOpenAiChatAfterOnboardingState.atom, true);++ render(<RouterUnderTest initialPath={initialPath} />);++ act(() => navigateAwayFromChatPage?.('/settings/profile'));++ expect(openAskAiPageMock).not.toHaveBeenCalled();+ expect(onContinueChatFromFullWidthMock).not.toHaveBeenCalled();+ expect(jotaiStore.get(shouldContinueAiChatInSidePanelState.atom)).toBe(+ false,+ );+ expect(jotaiStore.get(shouldOpenAiChatAfterOnboardingState.atom)).toBe(+ false,+ );++ act(() => navigateAwayFromChatPage?.());++ expect(openAskAiPageMock).not.toHaveBeenCalled();+ expect(onContinueChatFromFullWidthMock).not.toHaveBeenCalled();+ },+ );+it('should do nothing away from the chat page when the marker is not set', () => {render(<RouterUnderTest initialPath="/objects/companies" />);diff --git a/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/NavigationDrawerItem.tsx b/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/NavigationDrawerItem.tsxindex 4154357b7aa..1f61eddedc8 100644--- a/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/NavigationDrawerItem.tsx+++ b/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/NavigationDrawerItem.tsx@@ -235,7 +235,8 @@ const StyledRightOptionsVisbility = styled.div`width: 1px;&[data-visible='true'],- .navigation-drawer-item:hover & {+ .navigation-drawer-item:hover &,+ .navigation-drawer-item:focus-within & {clip-path: unset;display: flex;height: unset;diff --git a/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsxindex 6c03bd3cefa..6fcc8f7d263 100644--- a/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx+++ b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx@@ -28,12 +28,12 @@ const StyledPanel = styled.div`overflow: hidden;`;-const StyledCenteredChatContainer = styled.div`+const StyledChatContainer = styled.div`+ --ai-chat-content-max-width: 768px;+display: flex;flex: 1;flex-direction: column;- margin: 0 auto;- max-width: 768px;min-height: 0;width: 100%;`;@@ -50,7 +50,7 @@ export const AiChatPage = () => {<AiChatPageContinueInSidePanelEffect />{shouldOpenAiChatAfterOnboarding && <WorkspaceSetupChatKickoffEffect />}<AiChatPageHeader isOnboarding={shouldOpenAiChatAfterOnboarding} />- <StyledCenteredChatContainer>+ <StyledChatContainer><AiChatMessageListPreambleContext.Providervalue={shouldOpenAiChatAfterOnboarding ? (@@ -62,7 +62,7 @@ export const AiChatPage = () => {<AiChatTab /></AiChatSurfaceContext.Provider></AiChatMessageListPreambleContext.Provider>- </StyledCenteredChatContainer>+ </StyledChatContainer></StyledPanel>);};diff --git a/packages/twenty-front/src/pages/settings/ai/SettingsAgentTurnDetail.tsx b/packages/twenty-front/src/pages/settings/ai/SettingsAgentTurnDetail.tsxindex 3ae231e3e0e..cd3ce23d224 100644--- a/packages/twenty-front/src/pages/settings/ai/SettingsAgentTurnDetail.tsx+++ b/packages/twenty-front/src/pages/settings/ai/SettingsAgentTurnDetail.tsx@@ -10,6 +10,7 @@ import { useQuery } from '@apollo/client/react';import { styled } from '@linaria/react';import { t } from '@lingui/core/macro';import Skeleton from 'react-loading-skeleton';+import { Suspense } from 'react';import { useParams } from 'react-router-dom';import { SettingsPath } from 'twenty-shared/types';import { getSettingsPath } from 'twenty-shared/utils';@@ -149,38 +150,41 @@ export const SettingsAgentTurnDetail = () => {})}/>{turn.messages.length > 0 ? (- <StyledMessagesContainer>- {mapDBMessagesToUIMessages(- ([...turn.messages] as AgentMessage[])- .filter((msg) => msg.parts.length > 0)- .sort((a, b) => {- if (a.role === 'user' && b.role === 'assistant') return -1;- if (a.role === 'assistant' && b.role === 'user') return 1;- return (- new Date(a.createdAt).getTime() -- new Date(b.createdAt).getTime()- );- }),- ).map((message) => {- const roleLabel =- message.role === 'user'- ? t`User`- : message.role === 'system'- ? t`System`- : t`Assistant`;- return (- <StyledMessageBubble key={message.id}>- <StyledMessageRole>{roleLabel}</StyledMessageRole>- <StyledMessageContent>- <AiChatAssistantMessageRenderer- messageParts={message.parts}- isLastMessageStreaming={false}- />- </StyledMessageContent>- </StyledMessageBubble>- );- })}- </StyledMessagesContainer>+ <Suspense fallback={<Skeleton height={16} width={200} />}>+ <StyledMessagesContainer>+ {mapDBMessagesToUIMessages(+ ([...turn.messages] as AgentMessage[])+ .filter((msg) => msg.parts.length > 0)+ .sort((a, b) => {+ if (a.role === 'user' && b.role === 'assistant')+ return -1;+ if (a.role === 'assistant' && b.role === 'user') return 1;+ return (+ new Date(a.createdAt).getTime() -+ new Date(b.createdAt).getTime()+ );+ }),+ ).map((message) => {+ const roleLabel =+ message.role === 'user'+ ? t`User`+ : message.role === 'system'+ ? t`System`+ : t`Assistant`;+ return (+ <StyledMessageBubble key={message.id}>+ <StyledMessageRole>{roleLabel}</StyledMessageRole>+ <StyledMessageContent>+ <AiChatAssistantMessageRenderer+ messageParts={message.parts}+ isLastMessageStreaming={false}+ />+ </StyledMessageContent>+ </StyledMessageBubble>+ );+ })}+ </StyledMessagesContainer>+ </Suspense>) : (<div>{t`No messages found for this turn`}</div>)}diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant.tsnew file mode 100644index 00000000000..066ce9ec9f0--- /dev/null+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant.ts@@ -0,0 +1,65 @@+export const AGENT_CHAT_THREAD_DATA_SEED_IDS = {+ APPLE_DEFAULT_THREAD: '20202020-0000-4000-8000-000000000011',+ APPLE_IMPORT_THREAD: '20202020-0000-4000-8000-000000000013',+ APPLE_FOLLOW_UP_THREAD: '20202020-0000-4000-8000-000000000014',+ YCOMBINATOR_DEFAULT_THREAD: '20202020-0000-4000-8000-000000000012',+};++type AgentChatConversationSeed = {+ threadId: string;+ exchanges: [string, string][];+};++export const APPLE_AGENT_CHAT_CONVERSATION_SEEDS: AgentChatConversationSeed[] =+ [+ {+ threadId: AGENT_CHAT_THREAD_DATA_SEED_IDS.APPLE_IMPORT_THREAD,+ exchanges: [+ [+ 'Help me prepare a company import.',+ 'Let’s review the file before importing. We’ll check the columns, clean up duplicates, and confirm the field mapping. No records have been changed.',+ ],+ [+ 'Which columns should I include?',+ '## Recommended columns\n\n| Source column | Twenty field | Example |\n| --- | --- | --- |\n| Company | Name | Acme Studio |\n| Website | Domain name | acme.example |\n| City | Address city | Paris |\n| Country | Address country | France |\n| Employees | Employees | 50 |\n| Annual revenue | Annual revenue | 1200000 |\n\nKeep one company per row and put contact details in a separate sheet.',+ ],+ [+ 'How should I clean the domains?',+ '## Normalize company websites\n\n1. Remove leading and trailing spaces.\n2. Use the same format for every website.\n3. Check for spelling mistakes.\n4. Separate multiple websites into distinct columns.\n5. Leave unknown websites empty.\n\nFor example, `https://acme.example/about` and `acme.example` refer to the same company domain. Review duplicates before choosing which record to keep.',+ ],+ [+ 'What about duplicate companies?',+ '## Review duplicates\n\nGroup rows by domain first, then review matching company names.\n\n- Keep the most complete address.\n- Prefer the most recently verified employee count.\n- Preserve useful notes from both rows.\n- Check subsidiaries before merging similar names.\n- Ask the record owner when details conflict.\n\nDo not merge companies based only on a similar name. Two separate businesses can share a name.',+ ],+ [+ 'Can you give me a mapping checklist?',+ '## Confirm the mapping\n\n| Check | Expected result |\n| --- | --- |\n| Company name | Required on every row |\n| Domain | One normalized domain |\n| Employee count | Whole number |\n| Revenue | Number without currency symbols |\n| Currency | A consistent currency code |\n| Country | Consistent country names |\n| Owner | An existing workspace member |\n| Notes | Plain text or supported formatting |\n\nReview a small sample before importing the entire file.',+ ],+ [+ 'How do we handle missing values?',+ '## Missing information\n\nLeave unknown values blank instead of entering placeholders such as “N/A” or “unknown”.\n\n1. Require a company name.\n2. Flag rows without a domain for manual review.\n3. Keep missing revenue empty rather than entering zero.\n4. Assign an owner only when the match is clear.\n5. Keep a separate list of rows that need follow-up.\n\nA zero is a real value; it should not mean that information is missing.',+ ],+ [+ 'What should I review after a small test import?',+ '## Validate the sample\n\n- Open several imported company records.\n- Check that names and websites are in the right fields.\n- Confirm currencies and numeric formatting.\n- Check that owners resolved correctly.\n- Look for unintended duplicates.\n- Compare the imported row count with the source file.\n\nIf anything looks wrong, correct the mapping before continuing. Keep the original file so you can compare the results.',+ ],+ [+ 'Summarize the next steps.',+ '## Ready for review\n\n1. Clean and normalize the source file.\n2. Review potential duplicates.\n3. Confirm field mapping and required values.\n4. Import a small sample.\n5. Review the resulting records.\n6. Import the remaining rows once the sample is correct.\n\nThis conversation is a preparation checklist. No import has been performed.',+ ],+ ],+ },+ {+ threadId: AGENT_CHAT_THREAD_DATA_SEED_IDS.APPLE_FOLLOW_UP_THREAD,+ exchanges: [+ [+ 'Help me plan customer follow-ups for this week.',+ 'Start with customers waiting for a reply, then review upcoming renewals and recent meetings.\n\n- Monday: review open questions.\n- Wednesday: follow up after demos.\n- Friday: confirm next steps and owners.',+ ],+ [+ 'Draft a short follow-up I can personalize.',+ 'Hi [Name],\n\nThanks for our conversation. I’m following up on [topic] and would love to hear your thoughts. Would [day] work for a quick check-in?\n\nBest,\nTim\n\nThis is a draft for review; no message has been sent.',+ ],+ ],+ },+ ];diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/__tests__/seed-agents.util.spec.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/__tests__/seed-agents.util.spec.tsnew file mode 100644index 00000000000..14b8cf51136--- /dev/null+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/__tests__/seed-agents.util.spec.ts@@ -0,0 +1,105 @@+import { type QueryRunner } from 'typeorm';++import {+ SEED_APPLE_WORKSPACE_ID,+ SEED_YCOMBINATOR_WORKSPACE_ID,+} from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';+import { seedAgents } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-agents.util';++type SeedRow = {+ id: string;+ workspaceId: string;+ threadId?: string;+ turnId?: string;+ messageId?: string;+ createdAt: Date;+};++describe('seedAgents', () => {+ it.each([+ [SEED_APPLE_WORKSPACE_ID, 3, 22, 11],+ [SEED_YCOMBINATOR_WORKSPACE_ID, 1, 4, 2],+ ])(+ 'keeps messages, turns, and parts in their owning conversation for %s',+ async (workspaceId, threadCount, messageCount, turnCount) => {+ const tables = new Map<string, SeedRow[]>();+ let tableName: string;+ const queryBuilder = {+ insert: jest.fn().mockReturnThis(),+ update: jest.fn().mockReturnThis(),+ set: jest.fn().mockReturnThis(),+ where: jest.fn().mockReturnThis(),+ andWhere: jest.fn().mockReturnThis(),+ into: jest.fn().mockReturnThis(),+ orIgnore: jest.fn().mockReturnThis(),+ values: jest.fn().mockReturnThis(),+ execute: jest.fn().mockResolvedValue({}),+ };+ queryBuilder.into.mockImplementation((name: string) => {+ tableName = name;++ return queryBuilder;+ });+ queryBuilder.values.mockImplementation((rows: SeedRow[]) => {+ tables.set(tableName, [...(tables.get(tableName) ?? []), ...rows]);++ return queryBuilder;+ });+ const queryRunner = {+ manager: { createQueryBuilder: () => queryBuilder },+ } as unknown as QueryRunner;++ await seedAgents({+ queryRunner,+ schemaName: 'core',+ workspaceId,+ chatReferenceIds: {+ applicationId: 'application-id',+ objectMetadataId: 'object-id',+ roleId: 'role-id',+ viewId: 'view-id',+ },+ });++ const threads = tables.get('core.agentChatThread') ?? [];+ const turns = tables.get('core.agentTurn') ?? [];+ const messages = tables.get('core.agentMessage') ?? [];+ const parts = tables.get('core.agentMessagePart') ?? [];++ expect(threads).toHaveLength(threadCount);+ expect(messages).toHaveLength(messageCount);+ expect(parts).toHaveLength(messageCount);+ expect(turns).toHaveLength(turnCount);+ expect(queryBuilder.where).toHaveBeenCalledWith(+ 'id = :threadId AND "workspaceId" = :workspaceId',+ { threadId: threads[0].id, workspaceId },+ );+ expect(queryBuilder.andWhere).toHaveBeenCalledWith('title IS NULL');+ expect(new Set(turns.map((turn) => turn.id)).size).toBe(turns.length);+ for (const message of messages) {+ expect(threads).toContainEqual(+ expect.objectContaining({ id: message.threadId, workspaceId }),+ );+ expect(turns).toContainEqual(+ expect.objectContaining({+ id: message.turnId,+ threadId: message.threadId,+ workspaceId,+ }),+ );+ }+ for (const turn of turns) {+ const firstMessage = messages.find(+ (message) => message.turnId === turn.id,+ );++ expect(turn.createdAt).toEqual(firstMessage?.createdAt);+ }+ for (const part of parts) {+ expect(messages).toContainEqual(+ expect.objectContaining({ id: part.messageId, workspaceId }),+ );+ }+ },+ );+});diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-agents.util.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-agents.util.tsindex 3982a0eed4b..b94ab68ab75 100644--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-agents.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-agents.util.ts@@ -1,6 +1,11 @@+import uniqBy from 'lodash.uniqby';import { type QueryRunner } from 'typeorm';import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';+import {+ AGENT_CHAT_THREAD_DATA_SEED_IDS,+ APPLE_AGENT_CHAT_CONVERSATION_SEEDS,+} from 'src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant';import {SEED_APPLE_WORKSPACE_ID,SEED_YCOMBINATOR_WORKSPACE_ID,@@ -18,11 +23,6 @@ export const AGENT_DATA_SEED_IDS = {YCOMBINATOR_DEFAULT_AGENT: '20202020-0000-4000-8000-000000000002',};-export const AGENT_CHAT_THREAD_DATA_SEED_IDS = {- APPLE_DEFAULT_THREAD: '20202020-0000-4000-8000-000000000011',- YCOMBINATOR_DEFAULT_THREAD: '20202020-0000-4000-8000-000000000012',-};-export const AGENT_CHAT_MESSAGE_DATA_SEED_IDS = {APPLE_MESSAGE_1: '20202020-0000-4000-8000-000000000021',APPLE_MESSAGE_2: '20202020-0000-4000-8000-000000000022',@@ -68,6 +68,10 @@ const seedChatThreads = async ({}const now = new Date();+ const title =+ workspaceId === SEED_APPLE_WORKSPACE_ID+ ? 'Explore your workspace'+ : 'Portfolio performance';await queryRunner.manager.createQueryBuilder()@@ -76,6 +80,7 @@ const seedChatThreads = async ({'id','workspaceId','userWorkspaceId',+ 'title','createdAt','updatedAt',])@@ -85,12 +90,51 @@ const seedChatThreads = async ({id: threadId,workspaceId,userWorkspaceId,+ title,createdAt: now,updatedAt: now,},]).execute();+ await queryRunner.manager+ .createQueryBuilder()+ .update(`${schemaName}.${agentChatThreadTableName}`)+ .set({ title })+ .where('id = :threadId AND "workspaceId" = :workspaceId', {+ threadId,+ workspaceId,+ })+ .andWhere('title IS NULL')+ .execute();++ if (workspaceId === SEED_APPLE_WORKSPACE_ID) {+ await queryRunner.manager+ .createQueryBuilder()+ .insert()+ .into(`${schemaName}.${agentChatThreadTableName}`)+ .orIgnore()+ .values(+ [+ {+ id: AGENT_CHAT_THREAD_DATA_SEED_IDS.APPLE_IMPORT_THREAD,+ title: 'Prepare a company import',+ },+ {+ id: AGENT_CHAT_THREAD_DATA_SEED_IDS.APPLE_FOLLOW_UP_THREAD,+ title: 'Plan customer follow-ups',+ },+ ].map((thread) => ({+ ...thread,+ workspaceId,+ userWorkspaceId,+ createdAt: now,+ updatedAt: now,+ })),+ )+ .execute();+ }+return threadId;};@@ -118,7 +162,6 @@ const seedChatMessages = async ({}: SeedChatMessagesArgs) => {let messageIds: string[];let partIds: string[];- let turnIds: string[];let messages: Array<{id: string;workspaceId: string;@@ -149,7 +192,7 @@ const seedChatMessages = async ({AGENT_CHAT_MESSAGE_PART_DATA_SEED_IDS.APPLE_MESSAGE_1_PART_1,AGENT_CHAT_MESSAGE_PART_DATA_SEED_IDS.APPLE_MESSAGE_2_PART_1,];- turnIds = ['20202020-0000-4000-8000-000000000061'];+ const turnIds = ['20202020-0000-4000-8000-000000000061'];messages = [{id: messageIds[0],@@ -202,7 +245,7 @@ const seedChatMessages = async ({AGENT_CHAT_MESSAGE_PART_DATA_SEED_IDS.YCOMBINATOR_MESSAGE_3_PART_1,AGENT_CHAT_MESSAGE_PART_DATA_SEED_IDS.YCOMBINATOR_MESSAGE_4_PART_1,];- turnIds = [+ const turnIds = ['20202020-0000-4000-8000-000000000071','20202020-0000-4000-8000-000000000072',];@@ -288,11 +331,46 @@ const seedChatMessages = async ({);}- const turns = turnIds.map((id, index) => ({- id,+ if (workspaceId === SEED_APPLE_WORKSPACE_ID) {+ let seedId = 100;++ for (const conversation of APPLE_AGENT_CHAT_CONVERSATION_SEEDS) {+ for (const exchange of conversation.exchanges) {+ const turnId = `20202020-0000-4000-8000-${String(seedId++).padStart(12, '0')}`;++ for (const [index, textContent] of exchange.entries()) {+ const messageId = `20202020-0000-4000-8000-${String(seedId++).padStart(12, '0')}`;+ const partId = `20202020-0000-4000-8000-${String(seedId++).padStart(12, '0')}`;+ const createdAt = new Date(baseTime.getTime() + seedId * 60 * 1000);++ messages.push({+ id: messageId,+ workspaceId,+ threadId: conversation.threadId,+ turnId,+ role:+ index === 0 ? AgentMessageRole.USER : AgentMessageRole.ASSISTANT,+ createdAt,+ });+ messageParts.push({+ id: partId,+ workspaceId,+ messageId,+ orderIndex: 0,+ type: 'text',+ textContent,+ createdAt,+ });+ }+ }+ }+ }++ const turns = uniqBy(messages, 'turnId').map((message) => ({+ id: message.turnId,workspaceId,- threadId,- createdAt: messages[index * 2].createdAt,+ threadId: message.threadId,+ createdAt: message.createdAt,}));await queryRunner.manager