Skip to content

The open alternative to Salesforce, designed for AI.

Redirect to companies and collapse the chat when workspace setup ends (#23904)

Raphaël Bosi8c8996a372e4
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatPinScrollToBottomOnMountLayoutEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatPinScrollToBottomOnMountLayoutEffect.tsx
new file mode 100644
index 00000000000..1937666f576
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatPinScrollToBottomOnMountLayoutEffect.tsx
@@ -0,0 +1,32 @@
+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.tsx
index 2d70d2dbb53..8a4eb49d3bd 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect.tsx
@@ -1,73 +1,62 @@
-import { AI_CHAT_SCROLL_WRAPPER_ID } from '@/ai/constants/AiChatScrollWrapperId';
+import { useStore } from 'jotai';
+import { useEffect } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+
+import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
import { agentChatIsInitialScrollPendingOnThreadChangeState } from '@/ai/states/agentChatIsInitialScrollPendingOnThreadChangeState';
-import { scrollAiChatToBottom } from '@/ai/utils/scrollAiChatToBottom';
+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';
-import { useEffect } from 'react';
-
-const SCROLL_SETTLE_DELAY_MS = 150;
export const AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect =
() => {
- const agentChatIsInitialScrollPendingOnThreadChange = useAtomStateValue(
- agentChatIsInitialScrollPendingOnThreadChangeState,
+ const agentChatDisplayedThread = useAtomStateValue(
+ agentChatDisplayedThreadState,
);
const setAgentChatIsInitialScrollPendingOnThreadChange = useSetAtomState(
agentChatIsInitialScrollPendingOnThreadChangeState,
);
+ const store = useStore();
+
+ const { getScrollWrapperElement } = useScrollWrapperHTMLElement();
+
+ const setScrollWrapperScrollBottom = useSetAtomComponentState(
+ scrollWrapperScrollBottomComponentState,
+ );
+
useEffect(() => {
- if (!agentChatIsInitialScrollPendingOnThreadChange) {
+ if (!store.get(agentChatIsInitialScrollPendingOnThreadChangeState.atom)) {
return;
}
- const scrollWrapperElement = document.getElementById(
- `scroll-wrapper-${AI_CHAT_SCROLL_WRAPPER_ID}`,
- );
+ const { scrollWrapperElement } = getScrollWrapperElement();
- if (!scrollWrapperElement) {
+ if (!isDefined(scrollWrapperElement)) {
+ setAgentChatIsInitialScrollPendingOnThreadChange(false);
return;
}
- let settleTimeoutId: ReturnType<typeof setTimeout> | null = null;
-
- const scheduleSettle = () => {
- if (settleTimeoutId !== null) {
- clearTimeout(settleTimeoutId);
- }
-
- scrollAiChatToBottom();
-
- settleTimeoutId = setTimeout(() => {
- scrollAiChatToBottom();
- setAgentChatIsInitialScrollPendingOnThreadChange(false);
- mutationObserver.disconnect();
- }, SCROLL_SETTLE_DELAY_MS);
- };
-
- const mutationObserver = new MutationObserver(() => {
- scheduleSettle();
+ return pinAiChatScrollToBottom({
+ scrollWrapperElement,
+ onContentSettled: () =>
+ setAgentChatIsInitialScrollPendingOnThreadChange(false),
+ onPinningStopped: () =>
+ setScrollWrapperScrollBottom(
+ getScrollBottomInPx(scrollWrapperElement),
+ ),
});
-
- mutationObserver.observe(scrollWrapperElement, {
- childList: true,
- subtree: true,
- attributes: true,
- attributeFilter: ['class'],
- });
-
- scheduleSettle();
-
- return () => {
- if (settleTimeoutId !== null) {
- clearTimeout(settleTimeoutId);
- }
- mutationObserver.disconnect();
- };
}, [
- agentChatIsInitialScrollPendingOnThreadChange,
+ agentChatDisplayedThread,
+ store,
setAgentChatIsInitialScrollPendingOnThreadChange,
+ getScrollWrapperElement,
+ setScrollWrapperScrollBottom,
]);
return null;
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatScrollToBottomOnMountLayoutEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatScrollToBottomOnMountLayoutEffect.tsx
deleted file mode 100644
index e44c6892025..00000000000
--- a/packages/twenty-front/src/modules/ai/components/AgentChatScrollToBottomOnMountLayoutEffect.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-import { scrollAiChatToBottom } from '@/ai/utils/scrollAiChatToBottom';
-import { useLayoutEffect } from 'react';
-
-export const AgentChatScrollToBottomOnMountLayoutEffect = () => {
- useLayoutEffect(() => {
- scrollAiChatToBottom();
- }, []);
-
- return null;
-};
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatStreamingAutoScrollEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatStreamingAutoScrollEffect.tsx
index 6182240eb0f..15d94c0ef7a 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatStreamingAutoScrollEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatStreamingAutoScrollEffect.tsx
@@ -1,10 +1,15 @@
-import { agentChatIsScrolledToBottomSelector } from '@/ai/states/selectors/agentChatIsScrolledToBottomSelector';
+import { isNonEmptyArray } from '@sniptt/guards';
+import { useEffect } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+
import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
+import { agentChatIsScrolledToBottomComponentSelector } from '@/ai/states/selectors/agentChatIsScrolledToBottomComponentSelector';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { scrollAiChatToBottom } from '@/ai/utils/scrollAiChatToBottom';
+import { useScrollWrapperHTMLElement } from '@/ui/utilities/scroll/hooks/useScrollWrapperHTMLElement';
import { useAtomComponentFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateValue';
+import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-import { useEffect } from 'react';
export const AgentChatStreamingAutoScrollEffect = () => {
const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);
@@ -14,19 +19,27 @@ export const AgentChatStreamingAutoScrollEffect = () => {
{ threadId: currentAiChatThread },
);
- const agentChatIsScrolledToBottom = useAtomStateValue(
- agentChatIsScrolledToBottomSelector,
+ const agentChatIsScrolledToBottom = useAtomComponentSelectorValue(
+ agentChatIsScrolledToBottomComponentSelector,
);
+ const { getScrollWrapperElement } = useScrollWrapperHTMLElement();
+
useEffect(() => {
- if (agentChatMessages.length === 0) {
+ if (!isNonEmptyArray(agentChatMessages)) {
return;
}
- if (agentChatIsScrolledToBottom) {
- scrollAiChatToBottom();
+ if (!agentChatIsScrolledToBottom) {
+ return;
+ }
+
+ const { scrollWrapperElement } = getScrollWrapperElement();
+
+ if (isDefined(scrollWrapperElement)) {
+ scrollAiChatToBottom(scrollWrapperElement);
}
- }, [agentChatMessages, agentChatIsScrolledToBottom]);
+ }, [agentChatMessages, agentChatIsScrolledToBottom, getScrollWrapperElement]);
return null;
};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx
index 48ee249322c..7a6059307ff 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx
@@ -9,11 +9,13 @@ import { LazyMarkdownRenderer } from '@/ai/components/LazyMarkdownRenderer';
import { ToolStepRenderer } from '@/ai/components/ToolStepRenderer';
import { groupContiguousThinkingStepParts } from '@/ai/utils/groupContiguousThinkingStepParts';
import { isCodeInterpreterToolPart } from '@/ai/utils/isCodeInterpreterToolPart';
+import { isHiddenCompleteWorkspaceSetupToolPart } from '@/ai/utils/isHiddenCompleteWorkspaceSetupToolPart';
import { styled } from '@linaria/react';
import { getToolName, isToolUIPart } from 'ai';
import {
ASK_QUESTIONS_TOOL_NAME,
type ExtendedUIMessagePart,
+ isSucceededCompleteWorkspaceSetupToolPart,
} from 'twenty-shared/ai';
import { themeCssVariables } from 'twenty-ui/theme-constants';
@@ -79,9 +81,13 @@ export const AiChatAssistantMessageRenderer = ({
const hasCodeExecutionData = messageParts.some(
(part) => part.type === 'data-code-execution',
);
+ const hasSucceededCompleteWorkspaceSetupToolPart = messageParts.some(
+ isSucceededCompleteWorkspaceSetupToolPart,
+ );
const filteredParts = messageParts.filter(
(part) =>
part.type !== 'data-thread-title' &&
+ !isHiddenCompleteWorkspaceSetupToolPart(part) &&
!(hasCodeExecutionData && isCodeInterpreterToolPart(part)),
);
const renderItems = groupContiguousThinkingStepParts(filteredParts);
@@ -89,7 +95,9 @@ export const AiChatAssistantMessageRenderer = ({
const lastRenderItemIndex = renderItems.length - 1;
if (!renderItems.length && !hasError) {
- return <AiChatInitialLoadingIndicator />;
+ return hasSucceededCompleteWorkspaceSetupToolPart ? null : (
+ <AiChatInitialLoadingIndicator />
+ );
}
return (
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatScrollToBottomButton.tsx b/packages/twenty-front/src/modules/ai/components/AiChatScrollToBottomButton.tsx
index d485a258c3f..e58b8d8296a 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatScrollToBottomButton.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatScrollToBottomButton.tsx
@@ -1,7 +1,9 @@
-import { agentChatIsScrolledToBottomSelector } from '@/ai/states/selectors/agentChatIsScrolledToBottomSelector';
+import { agentChatIsScrolledToBottomComponentSelector } from '@/ai/states/selectors/agentChatIsScrolledToBottomComponentSelector';
import { scrollAiChatToBottom } from '@/ai/utils/scrollAiChatToBottom';
-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { useScrollWrapperHTMLElement } from '@/ui/utilities/scroll/hooks/useScrollWrapperHTMLElement';
+import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';
import { styled } from '@linaria/react';
+import { isDefined } from 'twenty-shared/utils';
import { IconArrowDown } from 'twenty-ui/icon';
import { themeCssVariables } from 'twenty-ui/theme-constants';
@@ -35,14 +37,24 @@ const StyledScrollToBottomButton = styled.button<{ isVisible: boolean }>`
`;
export const AiChatScrollToBottomButton = () => {
- const agentChatIsScrolledToBottom = useAtomStateValue(
- agentChatIsScrolledToBottomSelector,
+ const agentChatIsScrolledToBottom = useAtomComponentSelectorValue(
+ agentChatIsScrolledToBottomComponentSelector,
);
+ const { getScrollWrapperElement } = useScrollWrapperHTMLElement();
+
+ const handleClick = () => {
+ const { scrollWrapperElement } = getScrollWrapperElement();
+
+ if (isDefined(scrollWrapperElement)) {
+ scrollAiChatToBottom(scrollWrapperElement);
+ }
+ };
+
return (
<StyledScrollToBottomButton
isVisible={!agentChatIsScrolledToBottom}
- onClick={scrollAiChatToBottom}
+ onClick={handleClick}
>
<IconArrowDown size={16} />
</StyledScrollToBottomButton>
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatTab.tsx b/packages/twenty-front/src/modules/ai/components/AiChatTab.tsx
index ffec3ce5b58..ed13633a4cd 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatTab.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatTab.tsx
@@ -4,7 +4,6 @@ import { themeCssVariables } from 'twenty-ui/theme-constants';
import { DropZone } from '@/activities/files/components/DropZone';
import { AgentChatHasBeenOpenedEffect } from '@/ai/components/AgentChatHasBeenOpenedEffect';
-import { AgentChatStreamingAutoScrollEffect } from '@/ai/components/AgentChatStreamingAutoScrollEffect';
import { AgentChatStreamingPartsDiffSyncEffect } from '@/ai/components/AgentChatStreamingPartsDiffSyncEffect';
import { AiChatEditorSection } from '@/ai/components/AiChatEditorSection';
import { useAiChatFileUpload } from '@/ai/hooks/useAiChatFileUpload';
@@ -49,7 +48,6 @@ export const AiChatTab = () => {
>
<AgentChatHasBeenOpenedEffect />
<AgentChatStreamingPartsDiffSyncEffect />
- <AgentChatStreamingAutoScrollEffect />
{isDraggingFile && (
<DropZone
setIsDraggingFile={setIsDraggingFile}
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatTabMessageList.tsx b/packages/twenty-front/src/modules/ai/components/AiChatTabMessageList.tsx
index f27c9621449..fbf053ac65e 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatTabMessageList.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatTabMessageList.tsx
@@ -4,12 +4,15 @@ import { AiChatNonLastMessageIdsList } from '@/ai/components/AiChatNonLastMessag
import { AiChatPendingResponseIndicator } from '@/ai/components/AiChatPendingResponseIndicator';
import { AiChatScrollToBottomButton } from '@/ai/components/AiChatScrollToBottomButton';
import { AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect } from '@/ai/components/AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect';
-import { AgentChatScrollToBottomOnMountLayoutEffect } from '@/ai/components/AgentChatScrollToBottomOnMountLayoutEffect';
-import { AI_CHAT_SCROLL_WRAPPER_ID } from '@/ai/constants/AiChatScrollWrapperId';
+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';
@@ -43,10 +46,14 @@ const StyledMessageListContent = styled.div`
export const AiChatTabMessageList = () => {
const messageListPreamble = useContext(AiChatMessageListPreambleContext);
+ const aiChatSurface = useContext(AiChatSurfaceContext);
const agentChatHasMessage = useAtomComponentSelectorValue(
agentChatHasMessageComponentSelector,
);
+ const scrollWrapperInstanceId =
+ getAiChatScrollWrapperInstanceId(aiChatSurface);
+
const agentChatIsInitialScrollPendingOnThreadChange = useAtomStateValue(
agentChatIsInitialScrollPendingOnThreadChangeState,
);
@@ -64,25 +71,30 @@ export const AiChatTabMessageList = () => {
}
return (
- <StyledScrollWrapperContainer
- style={{
- visibility: agentChatIsInitialScrollPendingOnThreadChange
- ? 'hidden'
- : 'visible',
- }}
+ <ScrollWrapperComponentInstanceContext.Provider
+ value={{ instanceId: scrollWrapperInstanceId }}
>
- <ScrollWrapper componentInstanceId={AI_CHAT_SCROLL_WRAPPER_ID}>
- <StyledMessageListContent>
- {messageListPreamble}
- <AiChatNonLastMessageIdsList />
- <AiChatLastMessageWithStreamingState />
- <AiChatPendingResponseIndicator />
- <AiChatErrorUnderMessageList />
- </StyledMessageListContent>
- <AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect />
- <AgentChatScrollToBottomOnMountLayoutEffect />
- </ScrollWrapper>
- <AiChatScrollToBottomButton />
- </StyledScrollWrapperContainer>
+ <StyledScrollWrapperContainer
+ style={{
+ visibility: agentChatIsInitialScrollPendingOnThreadChange
+ ? 'hidden'
+ : 'visible',
+ }}
+ >
+ <ScrollWrapper componentInstanceId={scrollWrapperInstanceId}>
+ <StyledMessageListContent>
+ {messageListPreamble}
+ <AiChatNonLastMessageIdsList />
+ <AiChatLastMessageWithStreamingState />
+ <AiChatPendingResponseIndicator />
+ <AiChatErrorUnderMessageList />
+ </StyledMessageListContent>
+ <AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect />
+ <AgentChatPinScrollToBottomOnMountLayoutEffect />
+ <AgentChatStreamingAutoScrollEffect />
+ </ScrollWrapper>
+ <AiChatScrollToBottomButton />
+ </StyledScrollWrapperContainer>
+ </ScrollWrapperComponentInstanceContext.Provider>
);
};
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.tsx
index 6ac31eb56e1..0d5f77f7a8a 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
@@ -239,6 +239,104 @@ describe('AiChatAssistantMessageRenderer', () => {
expect(screen.getByTestId('code-execution-display')).toBeInTheDocument();
});
+ it('should hide the workspace setup completion tool part without splitting the thinking steps around it', () => {
+ const messageParts = [
+ {
+ type: 'tool-web_search',
+ toolCallId: 'tool-1',
+ input: { query: 'crm software' },
+ output: { result: { ok: true } },
+ state: 'output-available',
+ },
+ {
+ type: 'tool-complete_workspace_setup',
+ toolCallId: 'tool-2',
+ input: {},
+ output: { success: true, message: 'Setup marked as finished.' },
+ state: 'output-available',
+ },
+ {
+ type: 'tool-web_search',
+ toolCallId: 'tool-3',
+ input: { query: 'crm pricing' },
+ output: { result: { ok: true } },
+ state: 'output-available',
+ },
+ {
+ type: 'text',
+ text: 'Here is what we built together.',
+ },
+ ] as ExtendedUIMessagePart[];
+
+ renderAssistantRenderer(messageParts);
+
+ expect(screen.queryByTestId('tool-step-renderer')).toBeNull();
+ expect(screen.getByTestId('thinking-steps-display')).toHaveTextContent(
+ 'thinking-2-answer-started',
+ );
+ });
+
+ it('should render nothing when the workspace setup completion is the only content', () => {
+ const messageParts = [
+ { type: 'step-start' },
+ {
+ type: 'tool-complete_workspace_setup',
+ toolCallId: 'tool-1',
+ input: {},
+ output: { success: true, message: 'Setup marked as finished.' },
+ state: 'output-available',
+ },
+ ] as ExtendedUIMessagePart[];
+
+ const { container } = renderAssistantRenderer(messageParts);
+
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('should still show the loading indicator for a message whose content has not arrived yet', () => {
+ const messageParts = [{ type: 'step-start' }] as ExtendedUIMessagePart[];
+
+ const { container } = renderAssistantRenderer(messageParts);
+
+ expect(container).not.toBeEmptyDOMElement();
+ });
+
+ it('should keep the loading indicator while the workspace setup completion is still running', () => {
+ const messageParts = [
+ { type: 'step-start' },
+ {
+ type: 'tool-complete_workspace_setup',
+ toolCallId: 'tool-1',
+ input: {},
+ state: 'input-streaming',
+ },
+ ] as ExtendedUIMessagePart[];
+
+ const { container } = renderAssistantRenderer(messageParts);
+
+ expect(container).not.toBeEmptyDOMElement();
+ expect(screen.queryByTestId('tool-step-renderer')).toBeNull();
+ });
+
+ it('should show a failed workspace setup completion instead of hiding it', () => {
+ const messageParts = [
+ { type: 'step-start' },
+ {
+ type: 'tool-complete_workspace_setup',
+ toolCallId: 'tool-1',
+ input: {},
+ state: 'output-error',
+ errorText: 'Tool execution failed',
+ },
+ ] as ExtendedUIMessagePart[];
+
+ renderAssistantRenderer(messageParts);
+
+ expect(screen.getByTestId('thinking-steps-display')).toHaveTextContent(
+ 'thinking-1',
+ );
+ });
+
it('should flag the trailing thinking steps group while streaming', () => {
const messageParts = [
{
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.tsx
index 5561df2fc92..e4130da489c 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
@@ -2,7 +2,10 @@ import { render } from '@testing-library/react';
import { type ReactNode } from 'react';
import { AiChatTabMessageList } from '@/ai/components/AiChatTabMessageList';
+import { AI_CHAT_SURFACE } from '@/ai/constants/AiChatSurface';
import { AiChatMessageListPreambleContext } from '@/ai/contexts/AiChatMessageListPreambleContext';
+import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';
+import { type AiChatSurface } from '@/ai/types/AiChatSurface';
const renderWithPreamble = (preamble: ReactNode) =>
render(
@@ -25,8 +28,19 @@ jest.mock('@/ui/utilities/state/jotai/hooks/useAtomStateValue', () => ({
}));
jest.mock('@/ui/utilities/scroll/components/ScrollWrapper', () => ({
- ScrollWrapper: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="scroll-wrapper">{children}</div>
+ ScrollWrapper: ({
+ children,
+ componentInstanceId,
+ }: {
+ children: React.ReactNode;
+ componentInstanceId: string;
+ }) => (
+ <div
+ data-testid="scroll-wrapper"
+ data-component-instance-id={componentInstanceId}
+ >
+ {children}
+ </div>
),
}));
@@ -51,8 +65,14 @@ jest.mock(
AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect: () => null,
}),
);
-jest.mock('@/ai/components/AgentChatScrollToBottomOnMountLayoutEffect', () => ({
- AgentChatScrollToBottomOnMountLayoutEffect: () => null,
+jest.mock(
+ '@/ai/components/AgentChatPinScrollToBottomOnMountLayoutEffect',
+ () => ({
+ AgentChatPinScrollToBottomOnMountLayoutEffect: () => null,
+ }),
+);
+jest.mock('@/ai/components/AgentChatStreamingAutoScrollEffect', () => ({
+ AgentChatStreamingAutoScrollEffect: () => null,
}));
describe('AiChatTabMessageList', () => {
@@ -88,4 +108,22 @@ describe('AiChatTabMessageList', () => {
getByTestId('preamble'),
);
});
+
+ it('should give each surface its own scroll wrapper instance id', () => {
+ mockUseAtomComponentSelectorValue.mockReturnValue(true);
+
+ const renderForSurface = (surface: AiChatSurface) =>
+ render(
+ <AiChatSurfaceContext.Provider value={surface}>
+ <AiChatTabMessageList />
+ </AiChatSurfaceContext.Provider>,
+ )
+ .container.querySelector('[data-testid="scroll-wrapper"]')
+ ?.getAttribute('data-component-instance-id');
+
+ const pageInstanceId = renderForSurface(AI_CHAT_SURFACE.PAGE);
+ const sidePanelInstanceId = renderForSurface(AI_CHAT_SURFACE.SIDE_PANEL);
+
+ expect(pageInstanceId).not.toBe(sidePanelInstanceId);
+ });
});
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.tsx
index 19d76af479d..f41d86b7905 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
@@ -42,8 +42,14 @@ jest.mock(
AgentChatScrollToBottomOnDisplayedThreadChangeLayoutEffect: () => null,
}),
);
-jest.mock('@/ai/components/AgentChatScrollToBottomOnMountLayoutEffect', () => ({
- AgentChatScrollToBottomOnMountLayoutEffect: () => null,
+jest.mock(
+ '@/ai/components/AgentChatPinScrollToBottomOnMountLayoutEffect',
+ () => ({
+ AgentChatPinScrollToBottomOnMountLayoutEffect: () => null,
+ }),
+);
+jest.mock('@/ai/components/AgentChatStreamingAutoScrollEffect', () => ({
+ AgentChatStreamingAutoScrollEffect: () => null,
}));
const INSTANCE_ID = 'aiChatTabMessageListPreambleTest';
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatScrollBottomThresholdInPx.ts b/packages/twenty-front/src/modules/ai/constants/AiChatScrollBottomThresholdInPx.ts
new file mode 100644
index 00000000000..3bcbaef166f
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AiChatScrollBottomThresholdInPx.ts
@@ -0,0 +1 @@
+export const AI_CHAT_SCROLL_BOTTOM_THRESHOLD_IN_PX = 100;
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinAnimationTailMarginInMs.ts b/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinAnimationTailMarginInMs.ts
new file mode 100644
index 00000000000..080c2fc6b53
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinAnimationTailMarginInMs.ts
@@ -0,0 +1 @@
+export const AI_CHAT_SCROLL_PIN_ANIMATION_TAIL_MARGIN_IN_MS = 100;
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinInterruptingEventNames.ts b/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinInterruptingEventNames.ts
new file mode 100644
index 00000000000..2b30646fcbb
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinInterruptingEventNames.ts
@@ -0,0 +1,5 @@
+export const AI_CHAT_SCROLL_PIN_INTERRUPTING_EVENT_NAMES = [
+ 'wheel',
+ 'pointerdown',
+ 'keydown',
+] as const;
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinMaxDurationInMs.ts b/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinMaxDurationInMs.ts
new file mode 100644
index 00000000000..f5715ab8322
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinMaxDurationInMs.ts
@@ -0,0 +1 @@
+export const AI_CHAT_SCROLL_PIN_MAX_DURATION_IN_MS = 3000;
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinMinDurationInMs.ts b/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinMinDurationInMs.ts
new file mode 100644
index 00000000000..6c867714c27
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinMinDurationInMs.ts
@@ -0,0 +1,7 @@
+import { ANIMATION } from 'twenty-ui/theme';
+
+import { AI_CHAT_SCROLL_PIN_ANIMATION_TAIL_MARGIN_IN_MS } from '@/ai/constants/AiChatScrollPinAnimationTailMarginInMs';
+
+export const AI_CHAT_SCROLL_PIN_MIN_DURATION_IN_MS =
+ ANIMATION.duration.normal * 1000 +
+ AI_CHAT_SCROLL_PIN_ANIMATION_TAIL_MARGIN_IN_MS;
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinQuietDurationInMs.ts b/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinQuietDurationInMs.ts
new file mode 100644
index 00000000000..869a6fd7bef
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AiChatScrollPinQuietDurationInMs.ts
@@ -0,0 +1 @@
+export const AI_CHAT_SCROLL_PIN_QUIET_DURATION_IN_MS = 150;
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatScrollWrapperId.ts b/packages/twenty-front/src/modules/ai/constants/AiChatScrollWrapperId.ts
deleted file mode 100644
index 704a920a8c4..00000000000
--- a/packages/twenty-front/src/modules/ai/constants/AiChatScrollWrapperId.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const AI_CHAT_SCROLL_WRAPPER_ID = 'ai-chat-scroll-wrapper';
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatSurface.ts b/packages/twenty-front/src/modules/ai/constants/AiChatSurface.ts
new file mode 100644
index 00000000000..157da7c54ef
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AiChatSurface.ts
@@ -0,0 +1,4 @@
+export const AI_CHAT_SURFACE = {
+ PAGE: 'page',
+ SIDE_PANEL: 'side-panel',
+} as const;
diff --git a/packages/twenty-front/src/modules/ai/contexts/AiChatSurfaceContext.ts b/packages/twenty-front/src/modules/ai/contexts/AiChatSurfaceContext.ts
new file mode 100644
index 00000000000..aa4ddf0035d
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/contexts/AiChatSurfaceContext.ts
@@ -0,0 +1,8 @@
+import { createContext } from 'react';
+
+import { AI_CHAT_SURFACE } from '@/ai/constants/AiChatSurface';
+import { type AiChatSurface } from '@/ai/types/AiChatSurface';
+
+export const AiChatSurfaceContext = createContext<AiChatSurface>(
+ AI_CHAT_SURFACE.SIDE_PANEL,
+);
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useProcessWorkspaceSetupCompletion.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useProcessWorkspaceSetupCompletion.test.tsx
new file mode 100644
index 00000000000..53f2792ed82
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useProcessWorkspaceSetupCompletion.test.tsx
@@ -0,0 +1,179 @@
+import { act, renderHook } from '@testing-library/react';
+import { Provider as JotaiProvider } from 'jotai';
+import { type ReactNode } from 'react';
+import { type ExtendedUIMessage } from 'twenty-shared/ai';
+
+import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';
+import { useProcessWorkspaceSetupCompletion } from '@/ai/hooks/useProcessWorkspaceSetupCompletion';
+import { processedToolExecutionPartIdsComponentState } from '@/ai/states/processedToolExecutionPartIdsComponentState';
+import { shouldContinueAiChatInSidePanelState } from '@/ai/states/shouldContinueAiChatInSidePanelState';
+import {
+ jotaiStore,
+ resetJotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
+
+const navigateMock = jest.fn();
+
+jest.mock('react-router-dom', () => ({
+ ...jest.requireActual('react-router-dom'),
+ useNavigate: () => navigateMock,
+ useLocation: () => ({ state: null }),
+}));
+
+jest.mock('@/navigation/hooks/useDefaultHomePagePath', () => ({
+ useDefaultHomePagePath: () => ({ defaultHomePagePath: '/objects/people' }),
+}));
+
+const closeSidePanelMenuMock = jest.fn();
+
+jest.mock('@/side-panel/hooks/useSidePanelMenu', () => ({
+ useSidePanelMenu: () => ({ closeSidePanelMenu: closeSidePanelMenuMock }),
+}));
+
+let isWorkspaceSetupChat = true;
+
+jest.mock('@/ai/hooks/useIsWorkspaceSetupChat', () => ({
+ useIsWorkspaceSetupChat: () => isWorkspaceSetupChat,
+}));
+
+const INSTANCE_ID = 'processWorkspaceSetupCompletionTest';
+
+const Wrapper = ({ children }: { children: ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>
+ <AgentChatComponentInstanceContext.Provider
+ value={{ instanceId: INSTANCE_ID }}
+ >
+ {children}
+ </AgentChatComponentInstanceContext.Provider>
+ </JotaiProvider>
+);
+
+const buildMessageParts = (parts: unknown[]) =>
+ ({ parts }) as Pick<ExtendedUIMessage, 'parts'>;
+
+const buildCompletionMessage = (toolCallId: string) =>
+ buildMessageParts([
+ { type: 'text', text: 'Here is what we built together.' },
+ {
+ type: 'tool-complete_workspace_setup',
+ toolCallId,
+ input: {},
+ output: { success: true, message: 'Setup marked as finished.' },
+ state: 'output-available',
+ },
+ ]);
+
+const getProcessedToolCallIds = () =>
+ jotaiStore.get(
+ processedToolExecutionPartIdsComponentState.atomFamily({
+ instanceId: INSTANCE_ID,
+ }),
+ );
+
+describe('useProcessWorkspaceSetupCompletion', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ sessionStorage.clear();
+ resetJotaiStore();
+ isWorkspaceSetupChat = true;
+ });
+
+ it('should redirect to the companies view and move the chat to the side panel', () => {
+ jotaiStore.set(shouldContinueAiChatInSidePanelState.atom, true);
+
+ const { result } = renderHook(() => useProcessWorkspaceSetupCompletion(), {
+ wrapper: Wrapper,
+ });
+
+ act(() => {
+ result.current.processWorkspaceSetupCompletion(
+ buildCompletionMessage('call-1'),
+ );
+ });
+
+ expect(navigateMock).toHaveBeenCalledWith('/objects/companies');
+ expect(closeSidePanelMenuMock).not.toHaveBeenCalled();
+ expect(jotaiStore.get(shouldContinueAiChatInSidePanelState.atom)).toBe(
+ true,
+ );
+ expect(getProcessedToolCallIds()).toEqual(['call-1']);
+ });
+
+ it('should redirect only once when the same message is processed again', () => {
+ const { result } = renderHook(() => useProcessWorkspaceSetupCompletion(), {
+ wrapper: Wrapper,
+ });
+
+ const message = buildCompletionMessage('call-1');
+
+ act(() => {
+ result.current.processWorkspaceSetupCompletion(message);
+ result.current.processWorkspaceSetupCompletion(message);
+ });
+
+ expect(navigateMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not redirect when the chat already left the setup page', () => {
+ isWorkspaceSetupChat = false;
+
+ const { result } = renderHook(() => useProcessWorkspaceSetupCompletion(), {
+ wrapper: Wrapper,
+ });
+
+ act(() => {
+ result.current.processWorkspaceSetupCompletion(
+ buildCompletionMessage('call-1'),
+ );
+ });
+
+ expect(navigateMock).not.toHaveBeenCalled();
+ expect(closeSidePanelMenuMock).not.toHaveBeenCalled();
+ expect(getProcessedToolCallIds()).toEqual(['call-1']);
+ });
+
+ it('should ignore a message without a successful completion part', () => {
+ const { result } = renderHook(() => useProcessWorkspaceSetupCompletion(), {
+ wrapper: Wrapper,
+ });
+
+ act(() => {
+ result.current.processWorkspaceSetupCompletion(
+ buildMessageParts([
+ {
+ type: 'tool-complete_workspace_setup',
+ toolCallId: 'call-1',
+ input: {},
+ state: 'input-streaming',
+ },
+ ]),
+ );
+ });
+
+ expect(navigateMock).not.toHaveBeenCalled();
+ expect(getProcessedToolCallIds()).toEqual([]);
+ });
+
+ it('should not redirect nor consume the tool call when the completion failed', () => {
+ const { result } = renderHook(() => useProcessWorkspaceSetupCompletion(), {
+ wrapper: Wrapper,
+ });
+
+ act(() => {
+ result.current.processWorkspaceSetupCompletion(
+ buildMessageParts([
+ {
+ type: 'tool-complete_workspace_setup',
+ toolCallId: 'call-1',
+ input: {},
+ state: 'output-available',
+ output: { success: false, message: 'Something went wrong.' },
+ },
+ ]),
+ );
+ });
+
+ expect(navigateMock).not.toHaveBeenCalled();
+ expect(getProcessedToolCallIds()).toEqual([]);
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useReturnFromExpandedAiChat.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useReturnFromExpandedAiChat.test.tsx
index a16a51a7f69..21c317df8b5 100644
--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useReturnFromExpandedAiChat.test.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useReturnFromExpandedAiChat.test.tsx
@@ -76,6 +76,25 @@ describe('useReturnFromExpandedAiChat', () => {
expect(navigateMock).toHaveBeenCalledWith(defaultHomePagePath);
});
+ it('should prefer the destination path over the return location carried by the history entry', () => {
+ locationState = { returnLocation: '/objects/people' };
+
+ const { result } = renderHook(
+ () =>
+ useReturnFromExpandedAiChat({
+ reopenSidePanel: true,
+ destinationPath: '/objects/opportunities',
+ }),
+ { wrapper: Wrapper },
+ );
+
+ act(() => {
+ result.current();
+ });
+
+ expect(navigateMock).toHaveBeenCalledWith('/objects/opportunities');
+ });
+
it('should cancel the side panel continuation when closing', () => {
jotaiStore.set(shouldContinueAiChatInSidePanelState.atom, true);
jotaiStore.set(shouldOpenAiChatAfterOnboardingState.atom, true);
diff --git a/packages/twenty-front/src/modules/ai/hooks/useProcessStreamingMessageUpdate.ts b/packages/twenty-front/src/modules/ai/hooks/useProcessStreamingMessageUpdate.ts
index 058a7310e39..9da6000ec04 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useProcessStreamingMessageUpdate.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useProcessStreamingMessageUpdate.ts
@@ -1,10 +1,14 @@
import { useProcessUIToolCallMessage } from '@/ai/hooks/useProcessUIToolCallMessage';
+import { useProcessWorkspaceSetupCompletion } from '@/ai/hooks/useProcessWorkspaceSetupCompletion';
import { agentChatUISessionStartTimeState } from '@/ai/states/agentChatUISessionStartTimeState';
import { isUIToolCallMessage } from '@/ai/utils/isUIToolCallMessage';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { isNonEmptyString } from '@sniptt/guards';
import { Temporal } from 'temporal-polyfill';
-import { type ExtendedUIMessage } from 'twenty-shared/ai';
+import {
+ type ExtendedUIMessage,
+ isSucceededCompleteWorkspaceSetupToolPart,
+} from 'twenty-shared/ai';
export const useProcessStreamingMessageUpdate = () => {
const agentChatUISessionStartTime = useAtomStateValue(
@@ -13,6 +17,9 @@ export const useProcessStreamingMessageUpdate = () => {
const { processUIToolCallMessage } = useProcessUIToolCallMessage();
+ const { processWorkspaceSetupCompletion } =
+ useProcessWorkspaceSetupCompletion();
+
const processStreamingMessageUpdate = (
streamingMessage: ExtendedUIMessage,
) => {
@@ -39,6 +46,14 @@ export const useProcessStreamingMessageUpdate = () => {
if (messageIsUIToolCall) {
processUIToolCallMessage(streamingMessage);
}
+
+ const messageCompletesWorkspaceSetup = streamingMessage.parts.some(
+ isSucceededCompleteWorkspaceSetupToolPart,
+ );
+
+ if (messageCompletesWorkspaceSetup) {
+ processWorkspaceSetupCompletion(streamingMessage);
+ }
};
return {
diff --git a/packages/twenty-front/src/modules/ai/hooks/useProcessWorkspaceSetupCompletion.ts b/packages/twenty-front/src/modules/ai/hooks/useProcessWorkspaceSetupCompletion.ts
new file mode 100644
index 00000000000..96b4b44849b
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/hooks/useProcessWorkspaceSetupCompletion.ts
@@ -0,0 +1,64 @@
+import { useIsWorkspaceSetupChat } from '@/ai/hooks/useIsWorkspaceSetupChat';
+import { useReturnFromExpandedAiChat } from '@/ai/hooks/useReturnFromExpandedAiChat';
+import { processedToolExecutionPartIdsComponentState } from '@/ai/states/processedToolExecutionPartIdsComponentState';
+import { extractCompletedWorkspaceSetupToolParts } from '@/ai/utils/extractCompletedWorkspaceSetupToolParts';
+import { CoreObjectNamePlural } from '@/object-metadata/types/CoreObjectNamePlural';
+import { useAtomComponentStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateCallbackState';
+import { isNonEmptyArray } from '@sniptt/guards';
+import { useStore } from 'jotai';
+import { type ExtendedUIMessage } from 'twenty-shared/ai';
+import { AppPath } from 'twenty-shared/types';
+import { getAppPath } from 'twenty-shared/utils';
+
+export const useProcessWorkspaceSetupCompletion = () => {
+ const isWorkspaceSetupChat = useIsWorkspaceSetupChat();
+
+ const returnFromExpandedAiChat = useReturnFromExpandedAiChat({
+ reopenSidePanel: true,
+ destinationPath: getAppPath(AppPath.RecordIndexPage, {
+ objectNamePlural: CoreObjectNamePlural.Company,
+ }),
+ });
+
+ const processedToolExecutionPartIdsCallbackState =
+ useAtomComponentStateCallbackState(
+ processedToolExecutionPartIdsComponentState,
+ );
+
+ const store = useStore();
+
+ const processWorkspaceSetupCompletion = (
+ message: Pick<ExtendedUIMessage, 'parts'>,
+ ) => {
+ const completedParts = extractCompletedWorkspaceSetupToolParts(
+ message.parts,
+ );
+
+ const alreadyProcessedToolExecutionPartIds = store.get(
+ processedToolExecutionPartIdsCallbackState,
+ );
+
+ const partsToProcess = completedParts.filter(
+ (part) => !alreadyProcessedToolExecutionPartIds.includes(part.toolCallId),
+ );
+
+ if (!isNonEmptyArray(partsToProcess)) {
+ return;
+ }
+
+ store.set(processedToolExecutionPartIdsCallbackState, [
+ ...alreadyProcessedToolExecutionPartIds,
+ ...partsToProcess.map((part) => part.toolCallId),
+ ]);
+
+ if (!isWorkspaceSetupChat) {
+ return;
+ }
+
+ returnFromExpandedAiChat();
+ };
+
+ return {
+ processWorkspaceSetupCompletion,
+ };
+};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useReturnFromExpandedAiChat.ts b/packages/twenty-front/src/modules/ai/hooks/useReturnFromExpandedAiChat.ts
index 7320d85823c..42d91c61a3c 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useReturnFromExpandedAiChat.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useReturnFromExpandedAiChat.ts
@@ -10,10 +10,12 @@ import { useSidePanelMenu } from '@/side-panel/hooks/useSidePanelMenu';
type UseReturnFromExpandedAiChatParams = {
reopenSidePanel: boolean;
+ destinationPath?: string;
};
export const useReturnFromExpandedAiChat = ({
reopenSidePanel,
+ destinationPath,
}: UseReturnFromExpandedAiChatParams) => {
const store = useStore();
const navigate = useNavigate();
@@ -30,9 +32,10 @@ export const useReturnFromExpandedAiChat = ({
void closeSidePanelMenu();
}
- navigate(returnLocation ?? defaultHomePagePath);
+ navigate(destinationPath ?? returnLocation ?? defaultHomePagePath);
}, [
reopenSidePanel,
+ destinationPath,
closeSidePanelMenu,
store,
navigate,
diff --git a/packages/twenty-front/src/modules/ai/states/selectors/agentChatIsScrolledToBottomComponentSelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/agentChatIsScrolledToBottomComponentSelector.ts
new file mode 100644
index 00000000000..121fbe535fb
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/states/selectors/agentChatIsScrolledToBottomComponentSelector.ts
@@ -0,0 +1,19 @@
+import { AI_CHAT_SCROLL_BOTTOM_THRESHOLD_IN_PX } from '@/ai/constants/AiChatScrollBottomThresholdInPx';
+import { ScrollWrapperComponentInstanceContext } from '@/ui/utilities/scroll/states/contexts/ScrollWrapperComponentInstanceContext';
+import { scrollWrapperScrollBottomComponentState } from '@/ui/utilities/scroll/states/scrollWrapperScrollBottomComponentState';
+import { createAtomComponentSelector } from '@/ui/utilities/state/jotai/utils/createAtomComponentSelector';
+
+export const agentChatIsScrolledToBottomComponentSelector =
+ createAtomComponentSelector<boolean>({
+ key: 'agentChatIsScrolledToBottomComponentSelector',
+ componentInstanceContext: ScrollWrapperComponentInstanceContext,
+ get:
+ ({ instanceId }) =>
+ ({ get }) => {
+ const scrollBottom = get(scrollWrapperScrollBottomComponentState, {
+ instanceId,
+ });
+
+ return scrollBottom <= AI_CHAT_SCROLL_BOTTOM_THRESHOLD_IN_PX;
+ },
+ });
diff --git a/packages/twenty-front/src/modules/ai/states/selectors/agentChatIsScrolledToBottomSelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/agentChatIsScrolledToBottomSelector.ts
deleted file mode 100644
index 03e8a6c10f6..00000000000
--- a/packages/twenty-front/src/modules/ai/states/selectors/agentChatIsScrolledToBottomSelector.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { AI_CHAT_SCROLL_WRAPPER_ID } from '@/ai/constants/AiChatScrollWrapperId';
-import { scrollWrapperScrollBottomComponentState } from '@/ui/utilities/scroll/states/scrollWrapperScrollBottomComponentState';
-import { createAtomSelector } from '@/ui/utilities/state/jotai/utils/createAtomSelector';
-
-const SCROLL_BOTTOM_THRESHOLD_PX = 100;
-
-export const agentChatIsScrolledToBottomSelector = createAtomSelector<boolean>({
- key: 'agentChatIsScrolledToBottomSelector',
- get: ({ get }) => {
- const scrollBottom = get(scrollWrapperScrollBottomComponentState, {
- instanceId: AI_CHAT_SCROLL_WRAPPER_ID,
- });
-
- return scrollBottom <= SCROLL_BOTTOM_THRESHOLD_PX;
- },
-});
diff --git a/packages/twenty-front/src/modules/ai/types/AiChatSurface.ts b/packages/twenty-front/src/modules/ai/types/AiChatSurface.ts
new file mode 100644
index 00000000000..d2385885e8d
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/types/AiChatSurface.ts
@@ -0,0 +1,4 @@
+import { type AI_CHAT_SURFACE } from '@/ai/constants/AiChatSurface';
+
+export type AiChatSurface =
+ (typeof AI_CHAT_SURFACE)[keyof typeof AI_CHAT_SURFACE];
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/extractCompletedWorkspaceSetupToolParts.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/extractCompletedWorkspaceSetupToolParts.test.ts
new file mode 100644
index 00000000000..d8661a76c38
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/extractCompletedWorkspaceSetupToolParts.test.ts
@@ -0,0 +1,76 @@
+import { extractCompletedWorkspaceSetupToolParts } from '@/ai/utils/extractCompletedWorkspaceSetupToolParts';
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
+
+const completedPart = {
+ type: 'tool-complete_workspace_setup',
+ toolCallId: 'completed-call',
+ input: {},
+ output: { success: true, message: 'Setup marked as finished.' },
+ state: 'output-available',
+};
+
+describe('extractCompletedWorkspaceSetupToolParts', () => {
+ it('should keep only the completed workspace setup tool parts', () => {
+ const messageParts = [
+ { type: 'text', text: 'All set.' },
+ {
+ type: 'tool-execute_tool',
+ toolCallId: 'navigate-call',
+ input: { toolName: 'navigate_app' },
+ output: { success: true, result: { action: 'navigateToObject' } },
+ state: 'output-available',
+ },
+ completedPart,
+ ] as ExtendedUIMessagePart[];
+
+ expect(extractCompletedWorkspaceSetupToolParts(messageParts)).toEqual([
+ { toolCallId: 'completed-call' },
+ ]);
+ });
+
+ it('should ignore the tool part while its output has not landed yet', () => {
+ const messageParts = [
+ {
+ type: 'tool-complete_workspace_setup',
+ toolCallId: 'streaming-call',
+ input: {},
+ state: 'input-streaming',
+ },
+ ] as ExtendedUIMessagePart[];
+
+ expect(extractCompletedWorkspaceSetupToolParts(messageParts)).toEqual([]);
+ });
+
+ it('should ignore the tool part when it did not succeed', () => {
+ const messageParts = [
+ {
+ ...completedPart,
+ output: { success: false, message: 'Something went wrong.' },
+ },
+ ] as ExtendedUIMessagePart[];
+
+ expect(extractCompletedWorkspaceSetupToolParts(messageParts)).toEqual([]);
+ });
+
+ it('should ignore the tool part when it errored', () => {
+ const messageParts = [
+ {
+ type: 'tool-complete_workspace_setup',
+ toolCallId: 'errored-call',
+ input: {},
+ state: 'output-error',
+ errorText: 'Tool execution failed',
+ },
+ ] as ExtendedUIMessagePart[];
+
+ expect(extractCompletedWorkspaceSetupToolParts(messageParts)).toEqual([]);
+ });
+
+ it('should ignore an output that is not an object', () => {
+ const messageParts = [
+ { ...completedPart, output: 'done' },
+ ] as ExtendedUIMessagePart[];
+
+ expect(extractCompletedWorkspaceSetupToolParts(messageParts)).toEqual([]);
+ });
+});
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.ts
new file mode 100644
index 00000000000..26907f7527e
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/pinAiChatScrollToBottom.test.ts
@@ -0,0 +1,255 @@
+import { AI_CHAT_SCROLL_PIN_MAX_DURATION_IN_MS } from '@/ai/constants/AiChatScrollPinMaxDurationInMs';
+import { AI_CHAT_SCROLL_PIN_MIN_DURATION_IN_MS } from '@/ai/constants/AiChatScrollPinMinDurationInMs';
+import { AI_CHAT_SCROLL_PIN_QUIET_DURATION_IN_MS } from '@/ai/constants/AiChatScrollPinQuietDurationInMs';
+import { pinAiChatScrollToBottom } from '@/ai/utils/pinAiChatScrollToBottom';
+
+const FRAME_DURATION_IN_MS = 16;
+
+type FakeScrollWrapperElement = HTMLElement & {
+ scrollHeight: number;
+ clientHeight: number;
+ clientWidth: number;
+ scrollTop: number;
+};
+
+let currentTimeInMs = 0;
+let nextFrameId = 0;
+let pendingFrameCallbacksById: Map<number, FrameRequestCallback>;
+let listenersByEventName: Map<string, EventListener>;
+
+const buildScrollWrapperElement = () => {
+ listenersByEventName = new Map();
+
+ return {
+ scrollHeight: 1000,
+ clientHeight: 400,
+ clientWidth: 300,
+ scrollTop: 0,
+ addEventListener: (eventName: string, listener: EventListener) => {
+ listenersByEventName.set(eventName, listener);
+ },
+ removeEventListener: (eventName: string) => {
+ listenersByEventName.delete(eventName);
+ },
+ } as unknown as FakeScrollWrapperElement;
+};
+
+const advanceOneFrame = () => {
+ currentTimeInMs += FRAME_DURATION_IN_MS;
+
+ const frameCallbacks = [...pendingFrameCallbacksById.values()];
+ pendingFrameCallbacksById.clear();
+ frameCallbacks.forEach((frameCallback) => frameCallback(currentTimeInMs));
+};
+
+const advanceFrames = (frameCount: number) => {
+ for (let frameIndex = 0; frameIndex < frameCount; frameIndex++) {
+ advanceOneFrame();
+ }
+};
+
+const framesToCover = (durationInMs: number) =>
+ Math.ceil(durationInMs / FRAME_DURATION_IN_MS) + 2;
+
+describe('pinAiChatScrollToBottom', () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ currentTimeInMs = 0;
+ nextFrameId = 0;
+ pendingFrameCallbacksById = new Map();
+
+ jest.spyOn(performance, 'now').mockImplementation(() => currentTimeInMs);
+
+ jest
+ .spyOn(globalThis, 'requestAnimationFrame')
+ .mockImplementation((frameCallback: FrameRequestCallback) => {
+ nextFrameId++;
+ pendingFrameCallbacksById.set(nextFrameId, frameCallback);
+ return nextFrameId;
+ });
+
+ jest
+ .spyOn(globalThis, 'cancelAnimationFrame')
+ .mockImplementation((frameId: number) => {
+ pendingFrameCallbacksById.delete(frameId);
+ });
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ jest.useRealTimers();
+ });
+
+ it('should pin to the bottom synchronously before any frame runs', () => {
+ const scrollWrapperElement = buildScrollWrapperElement();
+
+ pinAiChatScrollToBottom({ scrollWrapperElement });
+
+ expect(scrollWrapperElement.scrollTop).toBe(1000);
+ });
+
+ it('should keep re-pinning while the content keeps growing', () => {
+ const scrollWrapperElement = buildScrollWrapperElement();
+
+ pinAiChatScrollToBottom({ scrollWrapperElement });
+
+ scrollWrapperElement.scrollHeight = 5000;
+ advanceOneFrame();
+
+ expect(scrollWrapperElement.scrollTop).toBe(5000);
+
+ scrollWrapperElement.scrollHeight = 9000;
+ advanceOneFrame();
+
+ expect(scrollWrapperElement.scrollTop).toBe(9000);
+ });
+
+ it('should keep re-pinning past the minimum duration while only the width changes', () => {
+ const scrollWrapperElement = buildScrollWrapperElement();
+ const onPinningStopped = jest.fn();
+
+ pinAiChatScrollToBottom({ scrollWrapperElement, onPinningStopped });
+
+ for (
+ let frameIndex = 0;
+ frameIndex < framesToCover(AI_CHAT_SCROLL_PIN_MIN_DURATION_IN_MS);
+ frameIndex++
+ ) {
+ scrollWrapperElement.clientWidth -= 1;
+ advanceOneFrame();
+ }
+
+ expect(currentTimeInMs).toBeGreaterThan(
+ AI_CHAT_SCROLL_PIN_MIN_DURATION_IN_MS,
+ );
+ expect(onPinningStopped).not.toHaveBeenCalled();
+
+ advanceFrames(framesToCover(AI_CHAT_SCROLL_PIN_QUIET_DURATION_IN_MS));
+
+ expect(onPinningStopped).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not stop before the minimum duration even when nothing changes', () => {
+ const scrollWrapperElement = buildScrollWrapperElement();
+ const onPinningStopped = jest.fn();
+
+ pinAiChatScrollToBottom({ scrollWrapperElement, onPinningStopped });
+
+ advanceFrames(
+ Math.floor(
+ AI_CHAT_SCROLL_PIN_QUIET_DURATION_IN_MS / FRAME_DURATION_IN_MS,
+ ) + 1,
+ );
+
+ expect(currentTimeInMs).toBeLessThan(AI_CHAT_SCROLL_PIN_MIN_DURATION_IN_MS);
+ expect(onPinningStopped).not.toHaveBeenCalled();
+ });
+
+ 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);
+ });
+
+ it('should extend the window when the content grows after the minimum duration', () => {
+ const scrollWrapperElement = buildScrollWrapperElement();
+ const onPinningStopped = jest.fn();
+
+ pinAiChatScrollToBottom({ scrollWrapperElement, onPinningStopped });
+
+ const quietFrameCount = Math.floor(
+ AI_CHAT_SCROLL_PIN_QUIET_DURATION_IN_MS / FRAME_DURATION_IN_MS,
+ );
+
+ while (
+ currentTimeInMs <
+ AI_CHAT_SCROLL_PIN_MIN_DURATION_IN_MS + FRAME_DURATION_IN_MS
+ ) {
+ scrollWrapperElement.scrollHeight += 100;
+ advanceOneFrame();
+ }
+
+ expect(onPinningStopped).not.toHaveBeenCalled();
+
+ scrollWrapperElement.scrollHeight = 8000;
+ advanceOneFrame();
+ advanceFrames(quietFrameCount - 2);
+
+ expect(onPinningStopped).not.toHaveBeenCalled();
+ expect(scrollWrapperElement.scrollTop).toBe(8000);
+
+ advanceFrames(4);
+
+ expect(onPinningStopped).toHaveBeenCalledTimes(1);
+ });
+
+ 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;
+ advanceOneFrame();
+
+ expect(scrollWrapperElement.scrollTop).toBe(1000);
+ });
+
+ 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', () => {
+ const scrollWrapperElement = buildScrollWrapperElement();
+ const onContentSettled = jest.fn();
+ const onPinningStopped = jest.fn();
+
+ const stop = pinAiChatScrollToBottom({
+ scrollWrapperElement,
+ onContentSettled,
+ onPinningStopped,
+ });
+
+ stop();
+ 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/extractCompletedWorkspaceSetupToolParts.ts b/packages/twenty-front/src/modules/ai/utils/extractCompletedWorkspaceSetupToolParts.ts
new file mode 100644
index 00000000000..de7a5c7f531
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/extractCompletedWorkspaceSetupToolParts.ts
@@ -0,0 +1,11 @@
+import {
+ type ExtendedUIMessagePart,
+ isSucceededCompleteWorkspaceSetupToolPart,
+} from 'twenty-shared/ai';
+
+export const extractCompletedWorkspaceSetupToolParts = (
+ messageParts: ExtendedUIMessagePart[],
+): { toolCallId: string }[] =>
+ messageParts
+ .filter(isSucceededCompleteWorkspaceSetupToolPart)
+ .map((part) => ({ toolCallId: part.toolCallId }));
diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatScrollWrapperInstanceId.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatScrollWrapperInstanceId.ts
new file mode 100644
index 00000000000..41553938f5a
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatScrollWrapperInstanceId.ts
@@ -0,0 +1,4 @@
+import { type AiChatSurface } from '@/ai/types/AiChatSurface';
+
+export const getAiChatScrollWrapperInstanceId = (surface: AiChatSurface) =>
+ `ai-chat-scroll-wrapper-${surface}`;
diff --git a/packages/twenty-front/src/modules/ai/utils/isHiddenCompleteWorkspaceSetupToolPart.ts b/packages/twenty-front/src/modules/ai/utils/isHiddenCompleteWorkspaceSetupToolPart.ts
new file mode 100644
index 00000000000..dbeb2d44da3
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/isHiddenCompleteWorkspaceSetupToolPart.ts
@@ -0,0 +1,11 @@
+import {
+ type ExtendedUIMessagePart,
+ isCompleteWorkspaceSetupToolPart,
+} from 'twenty-shared/ai';
+
+export const isHiddenCompleteWorkspaceSetupToolPart = (
+ part: ExtendedUIMessagePart,
+): boolean =>
+ isCompleteWorkspaceSetupToolPart(part) &&
+ part.state !== 'output-error' &&
+ part.state !== 'output-denied';
diff --git a/packages/twenty-front/src/modules/ai/utils/pinAiChatScrollToBottom.ts b/packages/twenty-front/src/modules/ai/utils/pinAiChatScrollToBottom.ts
new file mode 100644
index 00000000000..8ba68eba295
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/pinAiChatScrollToBottom.ts
@@ -0,0 +1,109 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { AI_CHAT_SCROLL_PIN_INTERRUPTING_EVENT_NAMES } from '@/ai/constants/AiChatScrollPinInterruptingEventNames';
+import { AI_CHAT_SCROLL_PIN_MAX_DURATION_IN_MS } from '@/ai/constants/AiChatScrollPinMaxDurationInMs';
+import { AI_CHAT_SCROLL_PIN_MIN_DURATION_IN_MS } from '@/ai/constants/AiChatScrollPinMinDurationInMs';
+import { AI_CHAT_SCROLL_PIN_QUIET_DURATION_IN_MS } from '@/ai/constants/AiChatScrollPinQuietDurationInMs';
+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();
+
+ let lastScrollHeightInPx = -1;
+ let lastClientHeightInPx = -1;
+ 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;
+ }
+
+ hasStopped = true;
+
+ if (isDefined(animationFrameId)) {
+ cancelAnimationFrame(animationFrameId);
+ }
+
+ clearTimeout(watchdogTimeoutId);
+
+ AI_CHAT_SCROLL_PIN_INTERRUPTING_EVENT_NAMES.forEach((eventName) =>
+ scrollWrapperElement.removeEventListener(eventName, stop),
+ );
+
+ settle();
+ onPinningStopped?.();
+ };
+
+ const pinCurrentFrame = () => {
+ scrollAiChatToBottom(scrollWrapperElement);
+
+ const nowInMs = performance.now();
+ const scrollHeightInPx = scrollWrapperElement.scrollHeight;
+ const clientHeightInPx = scrollWrapperElement.clientHeight;
+ const clientWidthInPx = scrollWrapperElement.clientWidth;
+
+ if (
+ scrollHeightInPx !== lastScrollHeightInPx ||
+ clientHeightInPx !== lastClientHeightInPx ||
+ clientWidthInPx !== lastClientWidthInPx
+ ) {
+ lastScrollHeightInPx = scrollHeightInPx;
+ lastClientHeightInPx = clientHeightInPx;
+ lastClientWidthInPx = clientWidthInPx;
+ lastChangeAtInMs = nowInMs;
+ }
+
+ 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_MS
+ ) {
+ stop();
+ return;
+ }
+
+ animationFrameId = requestAnimationFrame(pinCurrentFrame);
+ };
+
+ const watchdogTimeoutId = setTimeout(
+ stop,
+ AI_CHAT_SCROLL_PIN_MAX_DURATION_IN_MS,
+ );
+
+ AI_CHAT_SCROLL_PIN_INTERRUPTING_EVENT_NAMES.forEach((eventName) =>
+ scrollWrapperElement.addEventListener(eventName, stop, { passive: true }),
+ );
+
+ pinCurrentFrame();
+
+ return stop;
+};
diff --git a/packages/twenty-front/src/modules/ai/utils/scrollAiChatToBottom.ts b/packages/twenty-front/src/modules/ai/utils/scrollAiChatToBottom.ts
index 3b54fe1fadf..c55149f162a 100644
--- a/packages/twenty-front/src/modules/ai/utils/scrollAiChatToBottom.ts
+++ b/packages/twenty-front/src/modules/ai/utils/scrollAiChatToBottom.ts
@@ -1,11 +1,3 @@
-import { AI_CHAT_SCROLL_WRAPPER_ID } from '@/ai/constants/AiChatScrollWrapperId';
-
-export const scrollAiChatToBottom = () => {
- const scrollWrapperElement = document.getElementById(
- `scroll-wrapper-${AI_CHAT_SCROLL_WRAPPER_ID}`,
- );
-
- if (scrollWrapperElement) {
- scrollWrapperElement.scrollTop = scrollWrapperElement.scrollHeight;
- }
+export const scrollAiChatToBottom = (scrollWrapperElement: HTMLElement) => {
+ scrollWrapperElement.scrollTop = scrollWrapperElement.scrollHeight;
};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/ask-ai/components/SidePanelAskAiPage.tsx b/packages/twenty-front/src/modules/side-panel/pages/ask-ai/components/SidePanelAskAiPage.tsx
index 14404bf0be7..fccb1f2f406 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/ask-ai/components/SidePanelAskAiPage.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/ask-ai/components/SidePanelAskAiPage.tsx
@@ -1,5 +1,7 @@
import { styled } from '@linaria/react';
import { AiChatTab } from '@/ai/components/AiChatTab';
+import { AI_CHAT_SURFACE } from '@/ai/constants/AiChatSurface';
+import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';
const StyledContainer = styled.div`
height: 100%;
@@ -8,8 +10,10 @@ const StyledContainer = styled.div`
export const SidePanelAskAiPage = () => {
return (
- <StyledContainer>
- <AiChatTab />
- </StyledContainer>
+ <AiChatSurfaceContext.Provider value={AI_CHAT_SURFACE.SIDE_PANEL}>
+ <StyledContainer>
+ <AiChatTab />
+ </StyledContainer>
+ </AiChatSurfaceContext.Provider>
);
};
diff --git a/packages/twenty-front/src/modules/ui/utilities/scroll/components/ScrollWrapper.tsx b/packages/twenty-front/src/modules/ui/utilities/scroll/components/ScrollWrapper.tsx
index 5dc7f764919..2d6e99ab445 100644
--- a/packages/twenty-front/src/modules/ui/utilities/scroll/components/ScrollWrapper.tsx
+++ b/packages/twenty-front/src/modules/ui/utilities/scroll/components/ScrollWrapper.tsx
@@ -5,6 +5,7 @@ import { ScrollWrapperComponentInstanceContext } from '@/ui/utilities/scroll/sta
import { scrollWrapperScrollBottomComponentState } from '@/ui/utilities/scroll/states/scrollWrapperScrollBottomComponentState';
import { scrollWrapperScrollLeftComponentState } from '@/ui/utilities/scroll/states/scrollWrapperScrollLeftComponentState';
import { scrollWrapperScrollTopComponentState } from '@/ui/utilities/scroll/states/scrollWrapperScrollTopComponentState';
+import { getScrollBottomInPx } from '@/ui/utilities/scroll/utils/getScrollBottomInPx';
import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
const StyledScrollWrapper = styled.div<{ autoHeight?: boolean }>`
@@ -56,9 +57,7 @@ export const ScrollWrapper = ({
const target = event.currentTarget;
setScrollWrapperScrollTop(target.scrollTop);
setScrollWrapperScrollLeft(target.scrollLeft);
- setScrollWrapperScrollBottom(
- target.scrollHeight - target.clientHeight - target.scrollTop,
- );
+ setScrollWrapperScrollBottom(getScrollBottomInPx(target));
};
return (
diff --git a/packages/twenty-front/src/modules/ui/utilities/scroll/utils/getScrollBottomInPx.ts b/packages/twenty-front/src/modules/ui/utilities/scroll/utils/getScrollBottomInPx.ts
new file mode 100644
index 00000000000..fea9fc6b76f
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/utilities/scroll/utils/getScrollBottomInPx.ts
@@ -0,0 +1,4 @@
+export const getScrollBottomInPx = (scrollWrapperElement: HTMLElement) =>
+ scrollWrapperElement.scrollHeight -
+ scrollWrapperElement.clientHeight -
+ scrollWrapperElement.scrollTop;
diff --git a/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx
index 9638d3aee1f..6c03bd3cefa 100644
--- a/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx
+++ b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx
@@ -6,7 +6,9 @@ import { AiChatPageContinueInSidePanelEffect } from '@/ai/components/AiChatPageC
import { AiChatPageHeader } from '@/ai/components/AiChatPageHeader';
import { AiChatPageThreadUrlSyncEffect } from '@/ai/components/AiChatPageThreadUrlSyncEffect';
import { AiChatTab } from '@/ai/components/AiChatTab';
+import { AI_CHAT_SURFACE } from '@/ai/constants/AiChatSurface';
import { AiChatMessageListPreambleContext } from '@/ai/contexts/AiChatMessageListPreambleContext';
+import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';
import { WorkspaceSetupChatPreamble } from '@/onboarding/components/WorkspaceSetupChatPreamble';
import { WorkspaceSetupChatKickoffEffect } from '@/onboarding/effect-components/WorkspaceSetupChatKickoffEffect';
import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';
@@ -56,7 +58,9 @@ export const AiChatPage = () => {
) : null
}
>
- <AiChatTab />
+ <AiChatSurfaceContext.Provider value={AI_CHAT_SURFACE.PAGE}>
+ <AiChatTab />
+ </AiChatSurfaceContext.Provider>
</AiChatMessageListPreambleContext.Provider>
</StyledCenteredChatContainer>
</StyledPanel>
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
index c91cfafae3d..0cd785c7dcd 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
@@ -62,7 +62,13 @@ import {
ASK_QUESTIONS_TOOL_NAME,
createAskQuestionsTool,
} from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool';
+import {
+ COMPLETE_WORKSPACE_SETUP_TOOL_NAME,
+ createCompleteWorkspaceSetupTool,
+} from 'src/engine/metadata-modules/ai/ai-chat/tools/complete-workspace-setup.tool';
import { type ExtractedFile } from 'src/engine/metadata-modules/ai/ai-chat/types/extracted-file.type';
+import { buildWorkspaceSetupChatThreadId } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-chat-thread-id.util';
+import { hasSucceededWorkspaceSetupCompletion } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-succeeded-workspace-setup-completion.util';
import { extractCodeInterpreterFiles } from 'src/engine/metadata-modules/ai/ai-chat/utils/extract-code-interpreter-files.util';
import { injectMessageTimestamps } from 'src/engine/metadata-modules/ai/ai-chat/utils/inject-message-timestamps.util';
import {
@@ -208,10 +214,20 @@ export class ChatExecutionService {
...nativeTools,
};
+ const isWorkspaceSetupThread =
+ isDefined(threadId) &&
+ threadId ===
+ buildWorkspaceSetupChatThreadId({
+ workspaceId: workspace.id,
+ userWorkspaceId,
+ }) &&
+ !hasSucceededWorkspaceSetupCompletion(messages);
+
const preloadedToolNames = [
...Object.keys(preloadedTools),
...Object.keys(nativeTools),
ASK_QUESTIONS_TOOL_NAME,
+ ...(isWorkspaceSetupThread ? [COMPLETE_WORKSPACE_SETUP_TOOL_NAME] : []),
];
// ToolSet is constant for the entire conversation — no mutation.
@@ -219,6 +235,12 @@ export class ChatExecutionService {
const activeTools: ToolSet = {
...directTools,
[ASK_QUESTIONS_TOOL_NAME]: createAskQuestionsTool(),
+ ...(isWorkspaceSetupThread
+ ? {
+ [COMPLETE_WORKSPACE_SETUP_TOOL_NAME]:
+ createCompleteWorkspaceSetupTool(),
+ }
+ : {}),
[LEARN_TOOLS_TOOL_NAME]: createLearnToolsTool(
this.toolRegistry,
toolContext,
@@ -446,6 +468,7 @@ export class ChatExecutionService {
stopWhen: (step) =>
stepCountIs(AGENT_CONFIG.MAX_STEPS)(step) ||
hasToolCall(ASK_QUESTIONS_TOOL_NAME)(step) ||
+ hasToolCall(COMPLETE_WORKSPACE_SETUP_TOOL_NAME)(step) ||
hasNoMoreAvailableCredits,
experimental_telemetry: {
...AI_TELEMETRY_CONFIG,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts
index d9eb4a3b9a6..63ba1361b64 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts
@@ -5,7 +5,6 @@ import { type APP_LOCALES, SOURCE_LOCALE } from 'twenty-shared/translations';
import { isDefined } from 'twenty-shared/utils';
import { type WorkspaceCompanyEnrichment } from 'twenty-shared/workspace';
import { QueryFailedError } from 'typeorm';
-import { v5 } from 'uuid';
import { POSTGRESQL_ERROR_CODES } from 'src/engine/api/graphql/workspace-query-runner/constants/postgres-error-codes.constants';
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
@@ -13,11 +12,11 @@ import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
-import { WORKSPACE_SETUP_CHAT_THREAD_ID_NAMESPACE } from 'src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-chat-thread-id-namespace.constant';
import { type AgentChatThreadEntity } from 'src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity';
import { WorkspaceSetupChatOutcome } from 'src/engine/metadata-modules/ai/ai-chat/enums/workspace-setup-chat-outcome.enum';
import { AgentChatStreamingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service';
import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { buildWorkspaceSetupChatThreadId } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-chat-thread-id.util';
import { buildWorkspaceSetupPromptText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-prompt-text.util';
import { tagAiChatStreamScope } from 'src/engine/metadata-modules/ai/ai-chat/utils/tag-ai-chat-stream-scope.util';
import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
@@ -91,10 +90,10 @@ export class WorkspaceSetupChatService {
workspaceId: workspace.id,
});
- const threadId = v5(
- `${workspace.id}:${userWorkspaceId}`,
- WORKSPACE_SETUP_CHAT_THREAD_ID_NAMESPACE,
- );
+ const threadId = buildWorkspaceSetupChatThreadId({
+ workspaceId: workspace.id,
+ userWorkspaceId,
+ });
let thread = await this.agentChatService.findThreadById({
threadId,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/complete-workspace-setup.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/complete-workspace-setup.tool.ts
new file mode 100644
index 00000000000..e02c1b589b8
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/complete-workspace-setup.tool.ts
@@ -0,0 +1,29 @@
+import { z } from 'zod';
+
+import { COMPLETE_WORKSPACE_SETUP_TOOL_NAME } from 'twenty-shared/ai';
+
+export { COMPLETE_WORKSPACE_SETUP_TOOL_NAME };
+
+export const completeWorkspaceSetupInputSchema = z.object({});
+
+type CompleteWorkspaceSetupOutput = {
+ success: true;
+ message: string;
+};
+
+export const createCompleteWorkspaceSetupTool = () => ({
+ description:
+ 'Mark the workspace setup conversation as finished. Call it exactly once, at the very end ' +
+ 'of your final reply, right after the closing recap, and only once every remaining ' +
+ 'capability has been accepted and built or declined, or the user says they are done. The ' +
+ 'call closes the full-page setup screen: the user lands on their Companies view and this ' +
+ 'conversation continues in a side panel next to their work. Never call it while a question ' +
+ 'is unanswered or while anything the user accepted is still unbuilt, and never call it twice.',
+ inputSchema: completeWorkspaceSetupInputSchema,
+ execute: async (): Promise<CompleteWorkspaceSetupOutput> => ({
+ success: true,
+ message:
+ 'Setup marked as finished. The setup screen is closing; the user now sees their ' +
+ 'Companies view and this conversation continues in the side panel.',
+ }),
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-chat-thread-id.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-chat-thread-id.util.spec.ts
new file mode 100644
index 00000000000..c387aa06a03
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-chat-thread-id.util.spec.ts
@@ -0,0 +1,38 @@
+import { buildWorkspaceSetupChatThreadId } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-chat-thread-id.util';
+
+const workspaceId = '20202020-1c25-4d02-bf25-6aeccf7ea419';
+const userWorkspaceId = '20202020-9e3b-46d4-a556-88b9ddc2b034';
+
+const THREAD_ID_ALREADY_STORED_FOR_THIS_PAIR =
+ 'b23986d5-fd50-5d81-8bd5-311e3a4b6a0d';
+
+describe('buildWorkspaceSetupChatThreadId', () => {
+ it('should keep deriving the thread id already stored for existing workspaces', () => {
+ expect(
+ buildWorkspaceSetupChatThreadId({ workspaceId, userWorkspaceId }),
+ ).toBe(THREAD_ID_ALREADY_STORED_FOR_THIS_PAIR);
+ });
+
+ it('should give each workspace and user workspace pair its own thread id', () => {
+ const otherWorkspaceId = '20202020-3d15-4f4d-a9b6-1fd1d0a8b5c0';
+ const otherUserWorkspaceId = '20202020-7a6f-4b2e-9c33-2f1e6b7c8d90';
+
+ expect(
+ buildWorkspaceSetupChatThreadId({ workspaceId, userWorkspaceId }),
+ ).not.toBe(
+ buildWorkspaceSetupChatThreadId({
+ workspaceId: otherWorkspaceId,
+ userWorkspaceId,
+ }),
+ );
+
+ expect(
+ buildWorkspaceSetupChatThreadId({ workspaceId, userWorkspaceId }),
+ ).not.toBe(
+ buildWorkspaceSetupChatThreadId({
+ workspaceId,
+ userWorkspaceId: otherUserWorkspaceId,
+ }),
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-prompt-text.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-prompt-text.util.spec.ts
index 7d5020a5703..e06a8ad29b8 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-prompt-text.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-workspace-setup-prompt-text.util.spec.ts
@@ -256,6 +256,20 @@ describe('buildWorkspaceSetupPromptText', () => {
expect(result).toContain('Build only what they accept');
});
+ it('should end the setup by calling the completion tool once nothing is left to build', () => {
+ const result = buildWorkspaceSetupPromptText({
+ companyEnrichment,
+ locale: 'en',
+ });
+
+ expect(result).toContain('## Ending the setup');
+ expect(result).toContain(
+ 'end that same reply by calling complete_workspace_setup',
+ );
+ expect(result).toContain('moving to a side panel');
+ expect(result).toContain('never make it twice');
+ });
+
it('should propose a dashboard built with the dashboard tools', () => {
const result = buildWorkspaceSetupPromptText({
companyEnrichment,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-succeeded-workspace-setup-completion.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-succeeded-workspace-setup-completion.util.spec.ts
new file mode 100644
index 00000000000..a0ebe693024
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-succeeded-workspace-setup-completion.util.spec.ts
@@ -0,0 +1,80 @@
+import { type ExtendedUIMessage } from 'twenty-shared/ai';
+
+import { hasSucceededWorkspaceSetupCompletion } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-succeeded-workspace-setup-completion.util';
+
+const buildMessage = (parts: unknown[]): Pick<ExtendedUIMessage, 'parts'> =>
+ ({ parts }) as Pick<ExtendedUIMessage, 'parts'>;
+
+describe('hasSucceededWorkspaceSetupCompletion', () => {
+ it('should detect a succeeded completion in an earlier message', () => {
+ const messages = [
+ buildMessage([{ type: 'text', text: 'All set.' }]),
+ buildMessage([
+ {
+ type: 'tool-complete_workspace_setup',
+ toolCallId: 'call-1',
+ input: {},
+ state: 'output-available',
+ output: { success: true, message: 'Setup marked as finished.' },
+ },
+ ]),
+ ];
+
+ expect(hasSucceededWorkspaceSetupCompletion(messages)).toBe(true);
+ });
+
+ it('should ignore a completion that has not produced its output yet', () => {
+ const messages = [
+ buildMessage([
+ {
+ type: 'tool-complete_workspace_setup',
+ toolCallId: 'call-1',
+ input: {},
+ state: 'input-streaming',
+ },
+ ]),
+ ];
+
+ expect(hasSucceededWorkspaceSetupCompletion(messages)).toBe(false);
+ });
+
+ it('should ignore a completion that failed', () => {
+ const messages = [
+ buildMessage([
+ {
+ type: 'tool-complete_workspace_setup',
+ toolCallId: 'call-1',
+ input: {},
+ state: 'output-available',
+ output: { success: false, message: 'Something went wrong.' },
+ },
+ ]),
+ ];
+
+ expect(hasSucceededWorkspaceSetupCompletion(messages)).toBe(false);
+ });
+
+ it('should ignore other tools that succeeded', () => {
+ const messages = [
+ buildMessage([
+ {
+ type: 'tool-ask_questions',
+ toolCallId: 'call-1',
+ input: {},
+ state: 'output-available',
+ output: { success: true },
+ },
+ ]),
+ ];
+
+ expect(hasSucceededWorkspaceSetupCompletion(messages)).toBe(false);
+ });
+
+ it('should return false for a conversation without any tool call', () => {
+ expect(
+ hasSucceededWorkspaceSetupCompletion([
+ buildMessage([{ type: 'text', text: 'Hello.' }]),
+ ]),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-chat-thread-id.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-chat-thread-id.util.ts
new file mode 100644
index 00000000000..93381b05763
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-chat-thread-id.util.ts
@@ -0,0 +1,15 @@
+import { v5 } from 'uuid';
+
+import { WORKSPACE_SETUP_CHAT_THREAD_ID_NAMESPACE } from 'src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-chat-thread-id-namespace.constant';
+
+export const buildWorkspaceSetupChatThreadId = ({
+ workspaceId,
+ userWorkspaceId,
+}: {
+ workspaceId: string;
+ userWorkspaceId: string;
+}): string =>
+ v5(
+ `${workspaceId}:${userWorkspaceId}`,
+ WORKSPACE_SETUP_CHAT_THREAD_ID_NAMESPACE,
+ );
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-prompt-text.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-prompt-text.util.ts
index 04ae37de692..bd992c0a154 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-prompt-text.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-prompt-text.util.ts
@@ -69,6 +69,10 @@ For whichever you propose:
Close with a short recap of what was built, and never close while they are still unaware of the rest: give whatever you did not build, workflows, dashboards or roles, one line each on what it would do for this team, and offer to set one up. Build only what they accept.
+## Ending the setup
+
+The setup ends only once there is nothing left they want built: everything they accepted is built and the rest is declined, or they tell you they are done. At that point write the closing recap described above, add one line saying this chat is moving to a side panel where the conversation continues while they explore their workspace, and end that same reply by calling complete_workspace_setup. That call closes the setup screen and lands them on their Companies view, so never make it while a question is unanswered, and when they tell you they are done while something they accepted is still unbuilt, ask once whether to drop it and end as soon as they answer. Never announce the move without making the call, and never make it twice.
+
## In every turn
Twenty is new to this admin. Introduce a capability in one plain sentence before proposing anything that uses it: the data model is fully customizable, with objects and fields added, renamed, or removed any time in Settings > Data model; workflows automate repetitive work from a trigger, in the sidebar under Workflows; dashboards turn records into charts and counters, in the sidebar under Dashboards; roles control what each teammate can see and do, managed in Settings > Members > Roles.
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/has-succeeded-workspace-setup-completion.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/has-succeeded-workspace-setup-completion.util.ts
new file mode 100644
index 00000000000..a334da24c3f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/has-succeeded-workspace-setup-completion.util.ts
@@ -0,0 +1,11 @@
+import {
+ type ExtendedUIMessage,
+ isSucceededCompleteWorkspaceSetupToolPart,
+} from 'twenty-shared/ai';
+
+export const hasSucceededWorkspaceSetupCompletion = (
+ messages: Pick<ExtendedUIMessage, 'parts'>[],
+): boolean =>
+ messages.some((message) =>
+ message.parts.some(isSucceededCompleteWorkspaceSetupToolPart),
+ );
diff --git a/packages/twenty-shared/src/ai/constants/complete-workspace-setup-tool-name.const.ts b/packages/twenty-shared/src/ai/constants/complete-workspace-setup-tool-name.const.ts
new file mode 100644
index 00000000000..f59951de4f4
--- /dev/null
+++ b/packages/twenty-shared/src/ai/constants/complete-workspace-setup-tool-name.const.ts
@@ -0,0 +1 @@
+export const COMPLETE_WORKSPACE_SETUP_TOOL_NAME = 'complete_workspace_setup';
diff --git a/packages/twenty-shared/src/ai/index.ts b/packages/twenty-shared/src/ai/index.ts
index de5765782ce..8b98c623aa4 100644
--- a/packages/twenty-shared/src/ai/index.ts
+++ b/packages/twenty-shared/src/ai/index.ts
@@ -11,6 +11,7 @@ export { AI_SDK_PACKAGE_LABELS } from './constants/ai-sdk-package-labels.const';
export type { AiSdkPackage } from './constants/ai-sdk-packages.const';
export { AI_SDK_PACKAGES } from './constants/ai-sdk-packages.const';
export { ASK_QUESTIONS_TOOL_NAME } from './constants/ask-questions-tool-name.const';
+export { COMPLETE_WORKSPACE_SETUP_TOOL_NAME } from './constants/complete-workspace-setup-tool-name.const';
export type { DataResidency } from './constants/data-residency.const';
export { DATA_RESIDENCY_KEYS } from './constants/data-residency.const';
export type { DatabaseCrudOperation } from './constants/database-crud-operation.const';
@@ -54,5 +55,7 @@ export type { NavigateAppToolOutput } from './types/NavigateAppToolOutput';
export { formatRecordReference } from './utils/format-record-reference.util';
export { inferAiSdkPackage } from './utils/infer-ai-sdk-package.util';
export { isAiSdkPackage } from './utils/is-ai-sdk-package.util';
+export { isCompleteWorkspaceSetupToolPart } from './utils/is-complete-workspace-setup-tool-part.util';
export { isDataResidency } from './utils/is-data-residency.util';
+export { isSucceededCompleteWorkspaceSetupToolPart } from './utils/is-succeeded-complete-workspace-setup-tool-part.util';
export { isValidAgentResponseSchemaPropertyKey } from './utils/is-valid-agent-response-schema-property-key.util';
diff --git a/packages/twenty-shared/src/ai/utils/is-complete-workspace-setup-tool-part.util.ts b/packages/twenty-shared/src/ai/utils/is-complete-workspace-setup-tool-part.util.ts
new file mode 100644
index 00000000000..31568cc59d4
--- /dev/null
+++ b/packages/twenty-shared/src/ai/utils/is-complete-workspace-setup-tool-part.util.ts
@@ -0,0 +1,10 @@
+import { getToolName, isToolUIPart, type ToolUIPart } from 'ai';
+
+import { COMPLETE_WORKSPACE_SETUP_TOOL_NAME } from '../constants/complete-workspace-setup-tool-name.const';
+import { type ExtendedUIMessagePart } from '../types/ExtendedUIMessagePart';
+
+export const isCompleteWorkspaceSetupToolPart = (
+ part: ExtendedUIMessagePart,
+): part is ToolUIPart =>
+ isToolUIPart(part) &&
+ getToolName(part) === COMPLETE_WORKSPACE_SETUP_TOOL_NAME;
diff --git a/packages/twenty-shared/src/ai/utils/is-succeeded-complete-workspace-setup-tool-part.util.ts b/packages/twenty-shared/src/ai/utils/is-succeeded-complete-workspace-setup-tool-part.util.ts
new file mode 100644
index 00000000000..d7def0a8179
--- /dev/null
+++ b/packages/twenty-shared/src/ai/utils/is-succeeded-complete-workspace-setup-tool-part.util.ts
@@ -0,0 +1,21 @@
+import { type ToolUIPart } from 'ai';
+
+import { type ExtendedUIMessagePart } from '../types/ExtendedUIMessagePart';
+import { isCompleteWorkspaceSetupToolPart } from './is-complete-workspace-setup-tool-part.util';
+
+export const isSucceededCompleteWorkspaceSetupToolPart = (
+ part: ExtendedUIMessagePart,
+): part is ToolUIPart => {
+ if (!isCompleteWorkspaceSetupToolPart(part)) {
+ return false;
+ }
+
+ const output: unknown = part.output;
+
+ return (
+ typeof output === 'object' &&
+ output !== null &&
+ 'success' in output &&
+ output.success === true
+ );
+};