The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Update the new chat design (#28546)
Raphaël Bosia2d3aae9a78a
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatCloseButton.tsx b/packages/twenty-front/src/modules/ai/components/AiChatCloseButton.tsxindex d92f962e1ab..f69e5bc5025 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatCloseButton.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatCloseButton.tsx@@ -6,10 +6,17 @@ import { useReturnFromExpandedAiChat } from '@/ai/hooks/useReturnFromExpandedAiCimport { isWelcomeAnimationVisibleState } from '@/onboarding/states/isWelcomeAnimationVisibleState';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';-export const AiChatCloseButton = () => {+type AiChatCloseButtonProps = {+ destinationPath?: string;+};++export const AiChatCloseButton = ({+ destinationPath,+}: AiChatCloseButtonProps = {}) => {const { t } = useLingui();const returnFromExpandedAiChat = useReturnFromExpandedAiChat({reopenSidePanel: false,+ destinationPath,});const isWelcomeAnimationVisible = useAtomStateValue(isWelcomeAnimationVisibleState,diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsxindex 1fc6e63e6dd..40f725bf7e4 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx@@ -36,6 +36,7 @@ import { useCanSendAgentChatMessage } from '@/ai/hooks/useCanSendAgentChatMessagconst StyledInputArea = styled(StyledAiChatContentContainer)<{isMobile: boolean;+ isCentered?: boolean;}>`align-items: flex-end;background: ${themeCssVariables.background.primary};@@ -46,10 +47,14 @@ const StyledInputArea = styled(StyledAiChatContentContainer)<{margin-top: auto;padding-block: ${({ isMobile }) =>isMobile ? '0' : themeCssVariables.spacing[3]};- padding-inline: ${themeCssVariables.spacing[3]};+ padding-inline: ${({ isCentered }) =>+ isCentered ? themeCssVariables.spacing[4] : themeCssVariables.spacing[3]};`;-const StyledInputBox = styled.div<{ isMobile: boolean }>`+const StyledInputBox = styled.div<{+ isMobile: boolean;+ isCentered: boolean;+}>`background-color: ${themeCssVariables.background.transparent.lighter};border: 1px solid ${themeCssVariables.border.color.medium};border-radius: calc(@@ -59,7 +64,13 @@ const StyledInputBox = styled.div<{ isMobile: boolean }>`display: flex;flex-direction: column;gap: ${themeCssVariables.spacing[2]};- min-height: ${({ isMobile }) => (isMobile ? 'auto' : '140px')};+ min-height: ${({ isMobile, isCentered }) => {+ if (isMobile) {+ return 'auto';+ }++ return isCentered ? themeCssVariables.spacing[20] : '140px';+ }};padding: ${themeCssVariables.spacing[2]};width: 100%;@@ -69,7 +80,10 @@ const StyledInputBox = styled.div<{ isMobile: boolean }>`}`;-const StyledEditorWrapper = styled.div<{ isMobile: boolean }>`+const StyledEditorWrapper = styled.div<{+ isMobile: boolean;+ isCentered: boolean;+}>`display: flex;flex: 1;flex-direction: column;@@ -85,7 +99,15 @@ const StyledEditorWrapper = styled.div<{ isMobile: boolean }>`font-weight: ${themeCssVariables.font.weight.regular};line-height: 16px;max-height: ${({ isMobile }) => (isMobile ? '160px' : '320px')};- min-height: ${({ isMobile }) => (isMobile ? 'auto' : '48px')};+ min-height: ${({ isMobile, isCentered }) => {+ if (isMobile) {+ return 'auto';+ }++ return isCentered+ ? themeCssVariables.spacing[6]+ : themeCssVariables.spacing[12];+ }};outline: none;overflow-y: auto;padding: 0;@@ -150,8 +172,8 @@ const EditableAiChatEditorSection = () => {const [dictationInterimText, setDictationInterimText] = useState('');const composer = (- <StyledInputBox isMobile={isMobile}>- <StyledEditorWrapper isMobile={isMobile}>+ <StyledInputBox isMobile={isMobile} isCentered={isComposerCentered}>+ <StyledEditorWrapper isMobile={isMobile} isCentered={isComposerCentered}><EditorContent editor={editor} /></StyledEditorWrapper><AiChatDictationHint interimText={dictationInterimText} />@@ -182,12 +204,13 @@ const EditableAiChatEditorSection = () => {/>{!agentChatHasMessage && (<StyledMessageListPlaceholder>- <AiChatEmptyState isCentered={isComposerCentered} />+ {!isComposerCentered && <AiChatEmptyState />}<AiChatStandaloneError /></StyledMessageListPlaceholder>)}- <StyledInputArea isMobile={isMobile}>+ <StyledInputArea isMobile={isMobile} isCentered={isComposerCentered}>+ {isComposerCentered && <AiChatEmptyState isCentered />}<AgentChatContextPreview />{hasNoEnabledModels && (<AiChatInlineBanner>{t`No AI provider is configured on this instance.`}</AiChatInlineBanner>diff --git a/packages/twenty-front/src/modules/ai/components/AiChatInboxListHeader.tsx b/packages/twenty-front/src/modules/ai/components/AiChatInboxListHeader.tsxindex 4d8c4998ade..88f320d94bc 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatInboxListHeader.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatInboxListHeader.tsx@@ -15,6 +15,7 @@ import { CommandMenuContextProvider } from '@/command-menu-item/contexts/Commandimport { PinnedCommandMenuItemButtons } from '@/command-menu-item/display/components/PinnedCommandMenuItemButtons';import { CommandMenuItemContainerType } from '@/command-menu-item/types/CommandMenuItemContainerType';import { RecordIndexPageHeaderTitle } from '@/object-record/record-index/components/RecordIndexPageHeaderTitle';+import { useResetRecordSelection } from '@/object-record/record-selection/hooks/useResetRecordSelection';import { SidePanelToggleButton } from '@/side-panel/components/SidePanelToggleButton';import { PageCardHeader } from '@/ui/layout/page/components/PageCardHeader';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';@@ -38,6 +39,12 @@ export const AiChatInboxListHeader = ({const { switchToNewChat } = useSwitchToNewAiChat({shouldOpenInFullPage: true,});+ const { resetRecordSelection } = useResetRecordSelection();++ const handleNewChat = () => {+ resetRecordSelection();+ switchToNewChat();+ };return (<PageCardHeader@@ -71,7 +78,7 @@ export const AiChatInboxListHeader = ({variant="solid"color="accent"startIcon={<IconPlus />}- onClick={switchToNewChat}+ onClick={handleNewChat}>{t`New chat`}</Button>diff --git a/packages/twenty-front/src/modules/ai/components/AiChatNewThreadInboxListToggle.tsx b/packages/twenty-front/src/modules/ai/components/AiChatNewThreadInboxListToggle.tsxnew file mode 100644index 00000000000..bb71e07378d--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatNewThreadInboxListToggle.tsx@@ -0,0 +1,42 @@+import { useLingui } from '@lingui/react/macro';+import { useLocation } from 'react-router-dom';+import { IconButton } from 'twenty-ui/components/input';+import { useIsMobile } from 'twenty-ui/utilities';++import { AI_CHAT_INBOX_LAYOUT } from '@/ai/constants/AiChatInboxLayout';+import { AI_CHAT_INBOX_LAYOUT_OPTIONS } from '@/ai/constants/AiChatInboxLayoutOptions';+import { aiChatInboxLayoutState } from '@/ai/states/aiChatInboxLayoutState';+import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';+import { isAiChatInboxPath } from '~/utils/isAiChatInboxPath';++export const AiChatNewThreadInboxListToggle = () => {+ const { t } = useLingui();+ const { pathname } = useLocation();+ const isMobile = useIsMobile();+ const [aiChatInboxLayout, setAiChatInboxLayout] = useAtomState(+ aiChatInboxLayoutState,+ );+ const isSplitView = aiChatInboxLayout === AI_CHAT_INBOX_LAYOUT.SPLIT_VIEW;+ const LayoutIcon = AI_CHAT_INBOX_LAYOUT_OPTIONS[aiChatInboxLayout].Icon;++ if (isMobile || !isAiChatInboxPath(pathname)) {+ return null;+ }++ return (+ <IconButton+ size="sm"+ variant="ghost"+ aria-label={isSplitView ? t`Hide inbox` : t`Show inbox`}+ onClick={() =>+ setAiChatInboxLayout(+ isSplitView+ ? AI_CHAT_INBOX_LAYOUT.RECORD_PAGE+ : AI_CHAT_INBOX_LAYOUT.SPLIT_VIEW,+ )+ }+ >+ <LayoutIcon />+ </IconButton>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatNewThreadPageActions.tsx b/packages/twenty-front/src/modules/ai/components/AiChatNewThreadPageActions.tsxnew file mode 100644index 00000000000..ed1392a5306--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatNewThreadPageActions.tsx@@ -0,0 +1,45 @@+import { useLingui } from '@lingui/react/macro';+import { Link, useLocation } from 'react-router-dom';+import { AppPath } from 'twenty-shared/types';+import { getAppPath } from 'twenty-shared/utils';+import { IconButton } from 'twenty-ui/components/input';+import { IconHome } from 'twenty-ui/icon';++import { AiChatCloseButton } from '@/ai/components/AiChatCloseButton';+import { useDefaultHomePagePath } from '@/navigation/hooks/useDefaultHomePagePath';+import { isWelcomeAnimationVisibleState } from '@/onboarding/states/isWelcomeAnimationVisibleState';+import { SidePanelToggleButton } from '@/side-panel/components/SidePanelToggleButton';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { isAiChatInboxPath } from '~/utils/isAiChatInboxPath';++export const AiChatNewThreadPageActions = () => {+ const { t } = useLingui();+ const { pathname } = useLocation();+ const { defaultHomePagePath } = useDefaultHomePagePath();+ const isWelcomeAnimationVisible = useAtomStateValue(+ isWelcomeAnimationVisibleState,+ );++ return (+ <>+ <IconButton+ size="sm"+ variant="outline"+ aria-label={t`Home`}+ disabled={isWelcomeAnimationVisible}+ nativeButton={false}+ render={<Link to={defaultHomePagePath} />}+ >+ <IconHome />+ </IconButton>+ <AiChatCloseButton+ destinationPath={+ isAiChatInboxPath(pathname)+ ? getAppPath(AppPath.AiChatInbox, { threadId: null })+ : undefined+ }+ />+ <SidePanelToggleButton />+ </>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsxindex 046b5d0d776..18167192063 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsx@@ -1,17 +1,30 @@import { useLingui } from '@lingui/react/macro';+import { type ReactNode } from 'react';import { useIsMobile } from 'twenty-ui/utilities';import { AiChatCloseButton } from '@/ai/components/AiChatCloseButton';+import { AiChatNewThreadInboxListToggle } from '@/ai/components/AiChatNewThreadInboxListToggle';+import { AiChatNewThreadPageActions } from '@/ai/components/AiChatNewThreadPageActions';import { PageCardHeader } from '@/ui/layout/page/components/PageCardHeader';-export const AiChatPageHeader = () => {+type AiChatPageHeaderProps = {+ actionButton?: ReactNode;+};++export const AiChatPageHeader = ({+ actionButton,+}: AiChatPageHeaderProps = {}) => {const { t } = useLingui();const isMobile = useIsMobile();return (<PageCardHeader+ icon={<AiChatNewThreadInboxListToggle />}title={t`New chat`}- actionButton={isMobile ? <AiChatCloseButton /> : undefined}+ actionButton={+ actionButton ??+ (isMobile ? <AiChatCloseButton /> : <AiChatNewThreadPageActions />)+ }/>);};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPageThreadSelection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPageThreadSelection.tsxnew file mode 100644index 00000000000..78729f4b429--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatPageThreadSelection.tsx@@ -0,0 +1,13 @@+import { useLocation, useParams } from 'react-router-dom';++import { AiChatPageThreadUrlSyncEffect } from '@/ai/components/AiChatPageThreadUrlSyncEffect';+import { AI_CHAT_NEW_THREAD_PATH_SEGMENT } from '@/ai/constants/AiChatNewThreadPathSegment';++export const AiChatPageThreadSelection = () => {+ const { key } = useLocation();+ const { threadId } = useParams();+ const threadSelectionKey =+ threadId === AI_CHAT_NEW_THREAD_PATH_SEGMENT ? key : threadId;++ return <AiChatPageThreadUrlSyncEffect key={threadSelectionKey} />;+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsxindex f253216e40f..ac7fb1c14d4 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsx@@ -1,17 +1,26 @@-import { useLayoutEffect } from 'react';+import { useStore } from 'jotai';+import { useLayoutEffect, useState } from 'react';import { useParams } from 'react-router-dom';import { isDefined, isValidUuid } from 'twenty-shared/utils';+import { AI_CHAT_NEW_THREAD_PATH_SEGMENT } from '@/ai/constants/AiChatNewThreadPathSegment';import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';import { useSwitchAgentChatThreadWithDraft } from '@/ai/hooks/useSwitchAgentChatThreadWithDraft';import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';import { currentAiChatThreadDataSelector } from '@/ai/states/selectors/currentAiChatThreadDataSelector';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';export const AiChatPageThreadUrlSyncEffect = () => {+ const store = useStore();const { threadId } = useParams();+ const [newRouteThreadId] = useState(() =>+ store.get(newAiChatThreadIdState.atom),+ );+ const isNewThreadRoute = threadId === AI_CHAT_NEW_THREAD_PATH_SEGMENT;+ const selectedThreadId = isNewThreadRoute ? newRouteThreadId : threadId;const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);const currentAiChatThreadData = useAtomStateValue(currentAiChatThreadDataSelector,@@ -25,19 +34,23 @@ export const AiChatPageThreadUrlSyncEffect = () => {});useLayoutEffect(() => {- if (!isDefined(threadId) || !isValidUuid(threadId)) {+ if (!isDefined(selectedThreadId) || !isValidUuid(selectedThreadId)) {+ return;+ }++ if (selectedThreadId !== currentAiChatThread) {+ switchThreadWithDraft(selectedThreadId);return;}- if (threadId !== currentAiChatThread) {- switchThreadWithDraft(threadId);+ if (isNewThreadRoute) {return;}if (areAgentChatThreadsLoaded && !isDefined(currentAiChatThreadData)) {let isCurrentThread = true;- void loadAgentChatThread(threadId).then((chatThread) => {+ void loadAgentChatThread(selectedThreadId).then((chatThread) => {if (!isCurrentThread || chatThread !== null) {return;}@@ -50,7 +63,8 @@ export const AiChatPageThreadUrlSyncEffect = () => {};}}, [- threadId,+ selectedThreadId,+ isNewThreadRoute,currentAiChatThread,currentAiChatThreadData,areAgentChatThreadsLoaded,diff --git a/packages/twenty-front/src/modules/ai/components/AiChatWelcomeAvatar.tsx b/packages/twenty-front/src/modules/ai/components/AiChatWelcomeAvatar.tsxnew file mode 100644index 00000000000..eca596d970c--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatWelcomeAvatar.tsx@@ -0,0 +1,27 @@+import { styled } from '@linaria/react';+import { themeCssVariables } from 'twenty-ui/theme';++const StyledAvatar = styled.div`+ --t-corner-shape: round;++ align-items: center;+ background: ${themeCssVariables.color.blue3};+ border-radius: 50%;+ display: flex;+ flex-shrink: 0;+ gap: ${themeCssVariables.spacing[1]};+ height: 40px;+ justify-content: center;+ width: 40px;++ &::before,+ &::after {+ background: ${themeCssVariables.color.blue11};+ border-radius: ${themeCssVariables.border.radius.pill};+ content: '';+ height: 10px;+ width: ${themeCssVariables.spacing[1]};+ }+`;++export const AiChatWelcomeAvatar = () => <StyledAvatar aria-hidden />;diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatTab.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatTab.stories.tsxindex 2ffaaed80bf..557d38b1120 100644--- a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatTab.stories.tsx+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatTab.stories.tsx@@ -1,19 +1,44 @@import { type Meta, type StoryObj } from '@storybook/react-vite';+import { styled } from '@linaria/react';import { useStore } from 'jotai';+import { graphql, HttpResponse } from 'msw';import { Suspense, useEffect, useState } from 'react';-import { expect, waitFor, within } from 'storybook/test';+import { expect, userEvent, waitFor, within } from 'storybook/test';+import { assertIsDefinedOrThrow } from 'twenty-shared/utils';import { ComponentDecorator } from 'twenty-ui/testing';+import { ThemeProvider } from 'twenty-ui/theme';+import { AgentChatPrepromptEffect } from '@/ai/components/AgentChatPrepromptEffect';import { AiChatTab } from '@/ai/components/AiChatTab';import { AI_CHAT_SURFACE } from '@/ai/constants/AiChatSurface';import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';+import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';+import { initializeNewAiChatStory } from '@/ai/testing/initializeNewAiChatStory';import { hasRequestedWorkspaceSetupChatState } from '@/onboarding/states/hasRequestedWorkspaceSetupChatState';import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';+import { AiChatNewThreadPageContent } from '~/pages/ai-chat/AiChatNewThreadPageContent';import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';import { RootDecorator } from '~/testing/decorators/RootDecorator';import { ToastDecorator } from '~/testing/decorators/ToastDecorator';+const StyledPageChat = styled.div`+ display: flex;+ height: 100%;+ width: 100%;+`;++const NewChatStory = () => (+ <StyledPageChat>+ <Suspense fallback={null}>+ <AiChatNewThreadPageContent showInformationBanner={false} />+ <AgentChatPrepromptEffect />+ </Suspense>+ </StyledPageChat>+);+const WorkspaceSetupChatStory = () => {const store = useStore();const [isReady, setIsReady] = useState(false);@@ -53,6 +78,112 @@ const meta = {export default meta;type Story = StoryObj<typeof meta>;+const newChatParameters = {+ msw: {+ handlers: [+ graphql.query('GetAiChatUsage', () =>+ HttpResponse.json({ data: { aiChatUsage: null } }),+ ),+ ],+ },+};++const expectNewChatWelcome = async (canvasElement: HTMLElement) => {+ const canvas = within(canvasElement);+ const heading = await canvas.findByRole('heading', {+ name: 'How can I help you?',+ });++ await expect(heading).toBeVisible();++ const avatar = heading.previousElementSibling;++ assertIsDefinedOrThrow(avatar);++ const avatarStyle = getComputedStyle(avatar);++ await expect(avatarStyle.width).toBe(avatarStyle.height);+ await expect(avatarStyle.borderRadius).toBe('50%');++ if (CSS.supports('corner-shape', 'round')) {+ await expect(['round', 'superellipse(1)']).toContain(+ avatarStyle.getPropertyValue('corner-shape'),+ );+ }++ await expect(+ canvas.getByRole('button', { name: 'Create a workflow' }),+ ).toBeVisible();+ await expect(+ canvas.getByRole('button', { name: 'Create a record' }),+ ).toBeVisible();+ await expect(+ canvas.getByRole('button', { name: 'See what I can do' }),+ ).toBeVisible();+ await expect(canvas.getByRole('textbox')).toBeVisible();+ await expect(+ canvas.getByRole('button', { name: 'Send message' }),+ ).toBeDisabled();+};++export const FullPageNewChat: Story = {+ decorators: [ObjectMetadataItemsDecorator],+ beforeEach: () => initializeNewAiChatStory({ isInboxEnabled: false }),+ parameters: {+ ...newChatParameters,+ container: { width: 1000, height: 784 },+ },+ render: () => <NewChatStory />,+ play: async ({ canvasElement }) => expectNewChatWelcome(canvasElement),+};++export const InboxNewChat: Story = {+ ...FullPageNewChat,+ beforeEach: () => initializeNewAiChatStory({ isInboxEnabled: true }),+ parameters: {+ ...newChatParameters,+ container: { width: 660, height: 784 },+ },+};++export const InboxNewChatDark: Story = {+ ...InboxNewChat,+ render: () => (+ <ThemeProvider colorScheme="dark" applyToRoot={false}>+ <NewChatStory />+ </ThemeProvider>+ ),+};++export const NewChatSuggestedPrompt: Story = {+ ...FullPageNewChat,+ play: async ({ canvasElement }) => {+ await expectNewChatWelcome(canvasElement);++ const canvas = within(canvasElement);+ const editor = canvas.getByRole('textbox');++ await userEvent.click(+ canvas.getByRole('button', { name: 'Create a record' }),+ );+ await waitFor(() => expect(editor).toHaveTextContent('Details:'));+ await expect(editor).toHaveFocus();+ await userEvent.type(editor, 'A new partner');+ await expect(editor).toHaveTextContent('A new partner');+ await expect(+ canvas.getByRole('button', { name: 'Send message' }),+ ).toBeEnabled();++ await waitFor(() =>+ expect(+ jotaiStore.get(agentChatDraftsByThreadIdState.atom)[+ jotaiStore.get(newAiChatThreadIdState.atom)+ ],+ ).toContain('A new partner'),+ );+ },+};+export const WorkspaceSetup: Story = {render: () => <WorkspaceSetupChatStory />,play: async ({ canvasElement }) => {diff --git a/packages/twenty-front/src/modules/ai/components/suggested-prompts/AiChatSuggestedPrompts.tsx b/packages/twenty-front/src/modules/ai/components/suggested-prompts/AiChatSuggestedPrompts.tsxindex e4526b4c554..1322c3009ce 100644--- a/packages/twenty-front/src/modules/ai/components/suggested-prompts/AiChatSuggestedPrompts.tsx+++ b/packages/twenty-front/src/modules/ai/components/suggested-prompts/AiChatSuggestedPrompts.tsx@@ -7,6 +7,7 @@ import { Button } from 'twenty-ui/primitives/input';import { themeCssVariables } from 'twenty-ui/theme';import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';+import { AiChatWelcomeAvatar } from '@/ai/components/AiChatWelcomeAvatar';import { getAiChatSuggestedPrompts } from '@/ai/components/suggested-prompts/getAiChatSuggestedPrompts';import { useAiChatSuggestedPromptsContext } from '@/ai/hooks/useAiChatSuggestedPromptsContext';import { useStageAiChatPreprompt } from '@/ai/hooks/useStageAiChatPreprompt';@@ -17,24 +18,29 @@ const StyledContainer = styled.div<{ isCentered: boolean }>`display: flex;flex-direction: column;gap: ${({ isCentered }) =>- isCentered ? themeCssVariables.spacing[4] : themeCssVariables.spacing[2]};+ isCentered ? themeCssVariables.spacing[6] : themeCssVariables.spacing[2]};padding: ${({ isCentered }) =>- isCentered ? themeCssVariables.spacing[4] : themeCssVariables.spacing[2]};+ isCentered+ ? `0 0 ${themeCssVariables.spacing[4]}`+ : themeCssVariables.spacing[2]};`;-const StyledTitle = styled.div<{ isCentered: boolean }>`+const StyledTitle = styled.h2<{ isCentered: boolean }>`align-content: center;color: ${themeCssVariables.font.color.primary};display: grid;font-size: ${({ isCentered }) =>isCentered- ? themeCssVariables.font.size.xl+ ? themeCssVariables.font.size.xxl: themeCssVariables.font.size.sm};font-weight: ${({ isCentered }) =>isCentered? themeCssVariables.font.weight.semiBold: themeCssVariables.font.weight.medium};height: ${({ isCentered }) => (isCentered ? 'auto' : '24px')};+ line-height: ${({ isCentered }) =>+ isCentered ? themeCssVariables.text.lineHeight.md : 'inherit'};+ margin: 0;padding: 0 ${themeCssVariables.spacing[2]};text-align: ${({ isCentered }) => (isCentered ? 'center' : 'left')};`;@@ -77,8 +83,9 @@ export const AiChatSuggestedPrompts = ({return (<StyledContainer isCentered={isCentered}>+ {isCentered && <AiChatWelcomeAvatar />}<StyledTitle isCentered={isCentered}>- {t`What can I help you with?`}+ {isCentered ? t`How can I help you?` : t`What can I help you with?`}</StyledTitle><StyledPromptList isCentered={isCentered}>{suggestedPrompts.map((suggestedPrompt) => {diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatNewThreadPathSegment.ts b/packages/twenty-front/src/modules/ai/constants/AiChatNewThreadPathSegment.tsnew file mode 100644index 00000000000..0c612577ab9--- /dev/null+++ b/packages/twenty-front/src/modules/ai/constants/AiChatNewThreadPathSegment.ts@@ -0,0 +1 @@+export const AI_CHAT_NEW_THREAD_PATH_SEGMENT = 'new';diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useProjectAiChatThreadToUrl.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useProjectAiChatThreadToUrl.test.tsxindex aac01584c31..51530e3e2a2 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useProjectAiChatThreadToUrl.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useProjectAiChatThreadToUrl.test.tsx@@ -2,6 +2,7 @@ import { act, renderHook } from '@testing-library/react';import { getDefaultStore } from 'jotai';import { AppPath } from 'twenty-shared/types';+import { AI_CHAT_NEW_THREAD_PATH_SEGMENT } from '@/ai/constants/AiChatNewThreadPathSegment';import { useProjectAiChatThreadToUrl } from '@/ai/hooks/useProjectAiChatThreadToUrl';import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';@@ -55,6 +56,46 @@ describe('useProjectAiChatThreadToUrl', () => {);});+ it('keeps the inbox route when selecting a draft', () => {+ window.history.pushState(null, '', `/inbox/${THREAD_A}`);++ const { result } = renderHook(() => useProjectAiChatThreadToUrl());++ act(() => {+ result.current.projectAiChatThreadToUrl(+ getDefaultStore().get(newAiChatThreadIdState.atom),+ );+ });++ expect(navigateAppMock).toHaveBeenCalledWith(+ AppPath.AiChatInbox,+ { threadId: AI_CHAT_NEW_THREAD_PATH_SEGMENT },+ undefined,+ { replace: true, state: null },+ );+ });++ it('keeps the inbox route after the first message creates a thread', () => {+ window.history.pushState(+ { usr: { returnLocation: '/objects/people' } },+ '',+ `/inbox/${AI_CHAT_NEW_THREAD_PATH_SEGMENT}`,+ );++ const { result } = renderHook(() => useProjectAiChatThreadToUrl());++ act(() => {+ result.current.projectAiChatThreadToUrl(THREAD_A);+ });++ expect(navigateAppMock).toHaveBeenCalledWith(+ AppPath.AiChatInbox,+ { threadId: THREAD_A },+ undefined,+ { replace: true, state: { returnLocation: '/objects/people' } },+ );+ });+it('should carry the history entry state forward', () => {window.history.pushState({ usr: { returnLocation: '/objects/people' } },diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.tsindex 4a9e377057f..a82332acf82 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatEditor.ts@@ -52,9 +52,7 @@ export const useAiChatEditor = () => {const initialDraft = agentChatDraftsByThreadId[draftKey] ?? '';const editor = useAdvancedTextEditor({profile: AI_CHAT_EDITOR_PROFILE,- placeholder: isAiChatInboxEnabled- ? t`Ask anything, @ a teammate or record, / a skill...`- : t`Ask anything, @ a record or / a skill...`,+ placeholder: t`Ask, search or make anything...`,readonly: false,defaultValue: initialDraft,editorProps: {diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatInboxRecordSelectionInstanceId.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatInboxRecordSelectionInstanceId.tsnew file mode 100644index 00000000000..b6bae064833--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatInboxRecordSelectionInstanceId.ts@@ -0,0 +1,24 @@+import { useId, useState } from 'react';+import { useLocation, useParams } from 'react-router-dom';++import { getAiChatInboxRecordSelectionScope } from '@/ai/utils/getAiChatInboxRecordSelectionScope';++export const useAiChatInboxRecordSelectionInstanceId = () => {+ const baseInstanceId = useId();+ const { threadId } = useParams();+ const { key: locationKey } = useLocation();+ const [selectionScope, setSelectionScope] = useState(() =>+ getAiChatInboxRecordSelectionScope({ threadId, locationKey }),+ );+ const nextSelectionScope = getAiChatInboxRecordSelectionScope({+ threadId,+ locationKey,+ previousScope: selectionScope,+ });++ if (nextSelectionScope !== selectionScope) {+ setSelectionScope(nextSelectionScope);+ }++ return `${baseInstanceId}-${nextSelectionScope.generation}`;+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.tsindex 9c25123a667..8e6cda7b138 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts@@ -2,9 +2,10 @@ import { useSelectAiChatThread } from '@/ai/hooks/useSelectAiChatThread';import { useNavigateToAiChatPage } from '@/ai/hooks/useNavigateToAiChatPage';import { useOpenAskAiPageInSidePanel } from '@/side-panel/hooks/useOpenAskAiPageInSidePanel';import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { isAiChatInboxPath } from '~/utils/isAiChatInboxPath';import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';-export type UseAiChatThreadClickOptions = {+type UseAiChatThreadClickOptions = {resetNavigationStack?: boolean;shouldOpenInFullPage?: boolean;};@@ -21,7 +22,10 @@ export const useAiChatThreadClick = (const handleThreadClick = (thread: Pick<AgentChatThreadRecord, 'id'>) => {selectAiChatThread(thread.id);- if (isCurrentPathAiChatPage()) {+ const isOnChatPage =+ isCurrentPathAiChatPage() || isAiChatInboxPath(window.location.pathname);++ if (isOnChatPage) {return;}diff --git a/packages/twenty-front/src/modules/ai/hooks/useProjectAiChatThreadToUrl.ts b/packages/twenty-front/src/modules/ai/hooks/useProjectAiChatThreadToUrl.tsindex 778e8913e43..346aa717dfc 100644--- a/packages/twenty-front/src/modules/ai/hooks/useProjectAiChatThreadToUrl.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useProjectAiChatThreadToUrl.ts@@ -2,9 +2,11 @@ import { useStore } from 'jotai';import { useCallback } from 'react';import { AppPath } from 'twenty-shared/types';+import { AI_CHAT_NEW_THREAD_PATH_SEGMENT } from '@/ai/constants/AiChatNewThreadPathSegment';import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';import { useNavigateApp } from '~/hooks/useNavigateApp';import { getCurrentHistoryEntryState } from '~/utils/getCurrentHistoryEntryState';+import { isAiChatInboxPath } from '~/utils/isAiChatInboxPath';import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';export const useProjectAiChatThreadToUrl = () => {@@ -13,16 +15,22 @@ export const useProjectAiChatThreadToUrl = () => {const projectAiChatThreadToUrl = useCallback((threadId: string) => {- if (!isCurrentPathAiChatPage()) {+ const isOnInboxPage = isAiChatInboxPath(window.location.pathname);++ if (!isCurrentPathAiChatPage() && !isOnInboxPage) {return;}- // The new chat has no thread to open yet, so its URL carries no idconst isNewChat = threadId === store.get(newAiChatThreadIdState.atom);+ const newThreadPathSegment = isOnInboxPage+ ? AI_CHAT_NEW_THREAD_PATH_SEGMENT+ : null;navigateApp(- AppPath.AiChat,- { threadId: isNewChat ? null : threadId },+ isOnInboxPage ? AppPath.AiChatInbox : AppPath.AiChat,+ {+ threadId: isNewChat ? newThreadPathSegment : threadId,+ },undefined,{ replace: true, state: getCurrentHistoryEntryState() },);diff --git a/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAiChat.ts b/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAiChat.tsindex 240d84e41e7..56351db6f4f 100644--- a/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAiChat.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAiChat.ts@@ -5,6 +5,7 @@ import { useSelectAiChatThread } from '@/ai/hooks/useSelectAiChatThread';import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';import { shouldFocusChatEditorState } from '@/ai/states/shouldFocusChatEditorState';import { useOpenAskAiPageInSidePanel } from '@/side-panel/hooks/useOpenAskAiPageInSidePanel';+import { isAiChatInboxPath } from '~/utils/isAiChatInboxPath';type UseSwitchToNewAiChatParams = {shouldOpenInFullPage?: boolean;@@ -19,11 +20,17 @@ export const useSwitchToNewAiChat = ({const { navigateToAiChatPage } = useNavigateToAiChatPage();const switchToNewChat = () => {+ const isOnInboxPage = isAiChatInboxPath(window.location.pathname);+selectAiChatThread(store.get(newAiChatThreadIdState.atom));- if (shouldOpenInFullPage) {+ const shouldNavigateToChatPage = shouldOpenInFullPage && !isOnInboxPage;++ if (shouldNavigateToChatPage) {navigateToAiChatPage();- } else {+ }++ if (!shouldOpenInFullPage && !isOnInboxPage) {openAskAiPage();}diff --git a/packages/twenty-front/src/modules/ai/testing/initializeNewAiChatStory.ts b/packages/twenty-front/src/modules/ai/testing/initializeNewAiChatStory.tsnew file mode 100644index 00000000000..a6437624fe5--- /dev/null+++ b/packages/twenty-front/src/modules/ai/testing/initializeNewAiChatStory.ts@@ -0,0 +1,43 @@+import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';+import { aiModelTiersState } from '@/client-config/states/aiModelTiersState';+import { aiModelsState } from '@/client-config/states/aiModelsState';+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';+import { AiModelTier, FeatureFlagKey } from '~/generated-metadata/graphql';+import { mockCurrentWorkspace } from '~/testing/mock-data/users';++const NEW_CHAT_THREAD_ID = '20202020-7c1e-4a0f-9d2b-3f4e5a6b7c8d';+const MODEL_ID = 'new-chat-story-model';++export const initializeNewAiChatStory = ({+ isInboxEnabled,+}: {+ isInboxEnabled: boolean;+}) => {+ jotaiStore.set(newAiChatThreadIdState.atom, NEW_CHAT_THREAD_ID);+ jotaiStore.set(currentAiChatThreadState.atom, NEW_CHAT_THREAD_ID);+ jotaiStore.set(agentChatDisplayedThreadState.atom, NEW_CHAT_THREAD_ID);+ jotaiStore.set(agentChatThreadListState.atom, {+ threadIds: [],+ hasNextPage: false,+ endCursor: null,+ });+ jotaiStore.set(currentWorkspaceState.atom, {+ ...mockCurrentWorkspace,+ featureFlags: [+ {+ key: FeatureFlagKey.IS_AI_CHAT_INBOX_ENABLED,+ value: isInboxEnabled,+ },+ ],+ });+ jotaiStore.set(aiModelsState.atom, [+ { modelId: MODEL_ID, label: 'Story model' },+ ]);+ jotaiStore.set(aiModelTiersState.atom, [+ { tier: AiModelTier.fast, modelId: MODEL_ID },+ ]);+};diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getDisplayedAiChatThreadId.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getDisplayedAiChatThreadId.test.tsindex ccb7041f6ec..f17b7f3b420 100644--- a/packages/twenty-front/src/modules/ai/utils/__tests__/getDisplayedAiChatThreadId.test.ts+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getDisplayedAiChatThreadId.test.ts@@ -1,3 +1,4 @@+import { AI_CHAT_NEW_THREAD_PATH_SEGMENT } from '@/ai/constants/AiChatNewThreadPathSegment';import { getDisplayedAiChatThreadId } from '@/ai/utils/getDisplayedAiChatThreadId';const URL_CHAT_ID = '20202020-0000-4000-8000-0000000000aa';@@ -33,4 +34,14 @@ describe('getDisplayedAiChatThreadId', () => {}),).toBeNull();});++ it('shows a draft route before the current chat has switched', () => {+ expect(+ getDisplayedAiChatThreadId({+ urlThreadId: AI_CHAT_NEW_THREAD_PATH_SEGMENT,+ currentAiChatThread: CURRENT_CHAT_ID,+ isOnNewAiChatSlot: false,+ }),+ ).toBeNull();+ });});diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatInboxRecordSelectionScope.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatInboxRecordSelectionScope.tsnew file mode 100644index 00000000000..ab51f1c2372--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatInboxRecordSelectionScope.ts@@ -0,0 +1,33 @@+import { isDefined } from 'twenty-shared/utils';++import { AI_CHAT_NEW_THREAD_PATH_SEGMENT } from '@/ai/constants/AiChatNewThreadPathSegment';++type AiChatInboxRecordSelectionScope = {+ routeSelectionKey: string | undefined;+ generation: number;+};++export const getAiChatInboxRecordSelectionScope = ({+ threadId,+ locationKey,+ previousScope,+}: {+ threadId: string | undefined;+ locationKey: string;+ previousScope?: AiChatInboxRecordSelectionScope;+}): AiChatInboxRecordSelectionScope => {+ const routeSelectionKey =+ threadId === AI_CHAT_NEW_THREAD_PATH_SEGMENT ? locationKey : threadId;++ if (+ isDefined(previousScope) &&+ previousScope.routeSelectionKey === routeSelectionKey+ ) {+ return previousScope;+ }++ return {+ routeSelectionKey,+ generation: isDefined(previousScope) ? previousScope.generation + 1 : 0,+ };+};diff --git a/packages/twenty-front/src/modules/ai/utils/getDisplayedAiChatThreadId.ts b/packages/twenty-front/src/modules/ai/utils/getDisplayedAiChatThreadId.tsindex 27dfa87279c..8db45ea7c41 100644--- a/packages/twenty-front/src/modules/ai/utils/getDisplayedAiChatThreadId.ts+++ b/packages/twenty-front/src/modules/ai/utils/getDisplayedAiChatThreadId.ts@@ -1,5 +1,7 @@import { isDefined, isValidUuid } from 'twenty-shared/utils';+import { AI_CHAT_NEW_THREAD_PATH_SEGMENT } from '@/ai/constants/AiChatNewThreadPathSegment';+// /chat without an id shows the current chat (initially the latest); a new chat has no record yet.export const getDisplayedAiChatThreadId = ({urlThreadId,@@ -10,6 +12,10 @@ export const getDisplayedAiChatThreadId = ({currentAiChatThread: string | null;isOnNewAiChatSlot: boolean;}): string | null => {+ if (urlThreadId === AI_CHAT_NEW_THREAD_PATH_SEGMENT) {+ return null;+ }+if (isDefined(urlThreadId) && isValidUuid(urlThreadId)) {return urlThreadId;}diff --git a/packages/twenty-front/src/pages/ai-chat/AiChatInboxPage.tsx b/packages/twenty-front/src/pages/ai-chat/AiChatInboxPage.tsxindex 888b2526637..e7b24e24efd 100644--- a/packages/twenty-front/src/pages/ai-chat/AiChatInboxPage.tsx+++ b/packages/twenty-front/src/pages/ai-chat/AiChatInboxPage.tsx@@ -1,6 +1,6 @@import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';-import { type MouseEvent, useId, useRef } from 'react';+import { type MouseEvent, useRef } from 'react';import { Navigate, useParams } from 'react-router-dom';import { Key } from 'ts-key-enum';import { AppPath } from 'twenty-shared/types';@@ -19,6 +19,8 @@ import { AiChatInboxSelectionPane } from '@/ai/components/AiChatInboxSelectionPaimport { AiChatInboxSelectionToContextStoreEffect } from '@/ai/components/AiChatInboxSelectionToContextStoreEffect';import { AiChatInboxThreadList } from '@/ai/components/AiChatInboxThreadList';import { AiChatInboxThreadPagination } from '@/ai/components/AiChatInboxThreadPagination';+import { AI_CHAT_NEW_THREAD_PATH_SEGMENT } from '@/ai/constants/AiChatNewThreadPathSegment';+import { useAiChatInboxRecordSelectionInstanceId } from '@/ai/hooks/useAiChatInboxRecordSelectionInstanceId';import { useChatThreads } from '@/ai/hooks/useChatThreads';import { useIsAiChatInboxSplitView } from '@/ai/hooks/useIsAiChatInboxSplitView';import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';@@ -41,6 +43,7 @@ import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';import { FeatureFlagKey } from '~/generated-metadata/graphql';import { useNavigateApp } from '~/hooks/useNavigateApp';+import { AiChatNewThreadPageContent } from '~/pages/ai-chat/AiChatNewThreadPageContent';import { AiChatPageEffects } from '~/pages/ai-chat/AiChatPageEffects';import { AiChatThreadPageContent } from '~/pages/ai-chat/AiChatThreadPageContent';@@ -78,6 +81,7 @@ const AiChatInboxPageContent = () => {const isSplitView = useIsAiChatInboxSplitView();const navigate = useNavigateApp();const { threadId } = useParams();+ const isNewThreadRoute = threadId === AI_CHAT_NEW_THREAD_PATH_SEGMENT;const selectedThreadId =isDefined(threadId) && isValidUuid(threadId) ? threadId : undefined;const { threads, loading } = useChatThreads(agentChatVisibleThreadsSelector);@@ -142,15 +146,20 @@ const AiChatInboxPageContent = () => {// Split view shows the list beside the chat or the selection; otherwise// the list and a chat each take the whole page- const isListShown = isSplitView || !isDefined(selectedThreadId);+ const isListShown =+ isSplitView || (!isDefined(selectedThreadId) && !isNewThreadRoute);const isSelectionPaneShown = isSplitView && isSelectionShown;const isThreadShown = isDefined(selectedThreadId) && !isSelectionPaneShown;+ const isNewThreadShown = isNewThreadRoute && !isSelectionPaneShown;// Split view always has a chat beside the listconst firstThreadToOpen =- isSplitView && !isDefined(selectedThreadId) ? threads.at(0) : undefined;+ isSplitView && !isDefined(selectedThreadId) && !isNewThreadRoute+ ? threads.at(0)+ : undefined;const isEmptyPaneShown =isSplitView &&!isDefined(selectedThreadId) &&+ !isNewThreadRoute &&!isSelectionShown &&!isDefined(firstThreadToOpen);@@ -246,6 +255,26 @@ const AiChatInboxPageContent = () => {/>)}</AiChatInboxCommandMenuScope>+ {isNewThreadShown && (+ <>+ <AiChatPageEffects />+ <AiChatNewThreadPageContent+ showInformationBanner={!isSplitView}+ headerActions={+ isMobile ? (+ <IconButton+ size="sm"+ variant="outline"+ onClick={() => selectThread(null)}+ aria-label={t`Back to inbox`}+ >+ <IconChevronLeft />+ </IconButton>+ ) : undefined+ }+ />+ </>+ )}{isThreadShown && (<><AiChatPageEffects />@@ -290,7 +319,7 @@ const AiChatInboxPageContent = () => {export const AiChatInboxPage = () => {// A new instance per visit, so a selection does not outlive the inbox- const recordSelectionInstanceId = useId();+ const recordSelectionInstanceId = useAiChatInboxRecordSelectionInstanceId();const { threadId } = useParams();const isAiChatInboxEnabled = useIsFeatureEnabled(FeatureFlagKey.IS_AI_CHAT_INBOX_ENABLED,diff --git a/packages/twenty-front/src/pages/ai-chat/AiChatNewThreadPageContent.tsx b/packages/twenty-front/src/pages/ai-chat/AiChatNewThreadPageContent.tsxnew file mode 100644index 00000000000..533440f40e6--- /dev/null+++ b/packages/twenty-front/src/pages/ai-chat/AiChatNewThreadPageContent.tsx@@ -0,0 +1,39 @@+import { styled } from '@linaria/react';+import { type ReactNode } from 'react';++import { AiChatPageHeader } from '@/ai/components/AiChatPageHeader';+import { AiChatTab } from '@/ai/components/AiChatTab';+import { AI_CHAT_SURFACE } from '@/ai/constants/AiChatSurface';+import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';+import { PageCardLayout } from '@/ui/layout/page/components/PageCardLayout';++const StyledChatContainer = styled.div`+ --ai-chat-content-max-width: 768px;++ display: flex;+ flex: 1;+ flex-direction: column;+ min-height: 0;+ width: 100%;+`;++type AiChatNewThreadPageContentProps = {+ headerActions?: ReactNode;+ showInformationBanner?: boolean;+};++export const AiChatNewThreadPageContent = ({+ headerActions,+ showInformationBanner = true,+}: AiChatNewThreadPageContentProps) => (+ <PageCardLayout+ header={<AiChatPageHeader actionButton={headerActions} />}+ showInformationBanner={showInformationBanner}+ >+ <StyledChatContainer>+ <AiChatSurfaceContext.Provider value={AI_CHAT_SURFACE.PAGE}>+ <AiChatTab />+ </AiChatSurfaceContext.Provider>+ </StyledChatContainer>+ </PageCardLayout>+);diff --git a/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsxindex 112eae5ef74..cbaf2f6b6f4 100644--- a/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx+++ b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx@@ -1,31 +1,16 @@-import { styled } from '@linaria/react';import { useParams } from 'react-router-dom';import { isDefined } from 'twenty-shared/utils';import { useIsMobile } from 'twenty-ui/utilities';import { AiChatCloseButton } from '@/ai/components/AiChatCloseButton';-import { AiChatPageHeader } from '@/ai/components/AiChatPageHeader';-import { AiChatTab } from '@/ai/components/AiChatTab';-import { AI_CHAT_SURFACE } from '@/ai/constants/AiChatSurface';-import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';import { useIsOnNewAiChatSlot } from '@/ai/hooks/useIsOnNewAiChatSlot';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';import { getDisplayedAiChatThreadId } from '@/ai/utils/getDisplayedAiChatThreadId';-import { PageCardLayout } from '@/ui/layout/page/components/PageCardLayout';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { AiChatNewThreadPageContent } from '~/pages/ai-chat/AiChatNewThreadPageContent';import { AiChatPageEffects } from '~/pages/ai-chat/AiChatPageEffects';import { AiChatThreadPageContent } from '~/pages/ai-chat/AiChatThreadPageContent';-const StyledChatContainer = styled.div`- --ai-chat-content-max-width: 768px;-- display: flex;- flex: 1;- flex-direction: column;- min-height: 0;- width: 100%;-`;-export const AiChatPage = () => {const { threadId } = useParams();const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);@@ -47,13 +32,7 @@ export const AiChatPage = () => {/>) : (// A new chat has no record until its first message is sent- <PageCardLayout header={<AiChatPageHeader />}>- <StyledChatContainer>- <AiChatSurfaceContext.Provider value={AI_CHAT_SURFACE.PAGE}>- <AiChatTab />- </AiChatSurfaceContext.Provider>- </StyledChatContainer>- </PageCardLayout>+ <AiChatNewThreadPageContent />)}</>);diff --git a/packages/twenty-front/src/pages/ai-chat/AiChatPageEffects.tsx b/packages/twenty-front/src/pages/ai-chat/AiChatPageEffects.tsxindex dd9545b948f..60d227174b5 100644--- a/packages/twenty-front/src/pages/ai-chat/AiChatPageEffects.tsx+++ b/packages/twenty-front/src/pages/ai-chat/AiChatPageEffects.tsx@@ -1,11 +1,11 @@import { AiChatPageCloseSidePanelChatEffect } from '@/ai/components/AiChatPageCloseSidePanelChatEffect';import { AiChatPageContinueInSidePanelEffect } from '@/ai/components/AiChatPageContinueInSidePanelEffect';-import { AiChatPageThreadUrlSyncEffect } from '@/ai/components/AiChatPageThreadUrlSyncEffect';+import { AiChatPageThreadSelection } from '@/ai/components/AiChatPageThreadSelection';// What a chat shown on the main page needs, full page or in the inboxexport const AiChatPageEffects = () => (<>- <AiChatPageThreadUrlSyncEffect />+ <AiChatPageThreadSelection /><AiChatPageCloseSidePanelChatEffect /><AiChatPageContinueInSidePanelEffect /></>diff --git a/packages/twenty-front/src/pages/ai-chat/__stories__/AiChatInboxPage.stories.tsx b/packages/twenty-front/src/pages/ai-chat/__stories__/AiChatInboxPage.stories.tsxnew file mode 100644index 00000000000..33e56ccc4a4--- /dev/null+++ b/packages/twenty-front/src/pages/ai-chat/__stories__/AiChatInboxPage.stories.tsx@@ -0,0 +1,440 @@+import { HelmetProvider } from '@dr.pogodin/react-helmet';+import {+ type Decorator,+ type Meta,+ type StoryObj,+} from '@storybook/react-vite';+import { graphql, HttpResponse } from 'msw';+import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';+import { expect, userEvent, within } from 'storybook/test';+import { AppPath, CoreObjectNameSingular } from 'twenty-shared/types';+import {+ assertIsDefinedOrThrow,+ getAppPath,+ isDefined,+} from 'twenty-shared/utils';+import { Button } from 'twenty-ui/primitives/input';+import { ComponentDecorator } from 'twenty-ui/testing';+import { v4 as uuidv4 } from 'uuid';++import { AGENT_CHAT_THREAD_FILTER_STATUS } from '@/ai/constants/AgentChatThreadFilterStatus';+import { AI_CHAT_INBOX_LAYOUT } from '@/ai/constants/AiChatInboxLayout';+import { AI_CHAT_NEW_THREAD_PATH_SEGMENT } from '@/ai/constants/AiChatNewThreadPathSegment';+import { agentChatThreadFilterStatusState } from '@/ai/states/agentChatThreadFilterStatusState';+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';+import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';+import { aiChatInboxLayoutState } from '@/ai/states/aiChatInboxLayoutState';+import { initializeNewAiChatStory } from '@/ai/testing/initializeNewAiChatStory';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainContextStoreInstanceId';+import { ContextStoreComponentInstanceContext } from '@/context-store/states/contexts/ContextStoreComponentInstanceContext';+import { objectMetadataItemsSelector } from '@/object-metadata/states/objectMetadataItemsSelector';+import { getRecordConnectionFromRecords } from '@/object-record/cache/utils/getRecordConnectionFromRecords';+import { recordStoreFamilyState } from '@/object-record/record-store/states/recordStoreFamilyState';+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';+import { AiChatInboxPage } from '~/pages/ai-chat/AiChatInboxPage';+import { MemoryRouterAppNavigatorProvider } from '~/testing/components/MemoryRouterAppNavigatorProvider';+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';+import { RootDecorator } from '~/testing/decorators/RootDecorator';+import { ToastDecorator } from '~/testing/decorators/ToastDecorator';+import { setTestObjectMetadataItemsInMetadataStore } from '~/testing/utils/setTestObjectMetadataItemsInMetadataStore';++const FIRST_THREAD_ID = '20202020-0000-4000-8000-0000000000aa';+const SECOND_THREAD_ID = '20202020-0000-4000-8000-0000000000bb';+const FIRST_THREAD_TITLE = 'Qualify the lead';+const SECOND_THREAD_TITLE = 'Prepare the customer call';+const THREAD_ACTIVITY_AT = '2026-10-21T09:00:00.000Z';+const CHAT_OBJECT_METADATA_ID = '20202020-0000-4000-8000-0000000000cc';+const CHAT_TARGET_OBJECT_METADATA_ID = '20202020-0000-4000-8000-0000000000dd';+const CHAT_FIELD_NAMES = ['id', 'title', 'createdAt', 'updatedAt', 'deletedAt'];+const NEW_CHAT_PATH = getAppPath(AppPath.AiChatInbox, {+ threadId: AI_CHAT_NEW_THREAD_PATH_SEGMENT,+});+const THREADS: AgentChatThreadRecord[] = [+ {+ __typename: 'AgentChatThread',+ id: FIRST_THREAD_ID,+ title: FIRST_THREAD_TITLE,+ createdAt: THREAD_ACTIVITY_AT,+ updatedAt: THREAD_ACTIVITY_AT,+ lastActivityAt: THREAD_ACTIVITY_AT,+ deletedAt: null,+ },+ {+ __typename: 'AgentChatThread',+ id: SECOND_THREAD_ID,+ title: SECOND_THREAD_TITLE,+ createdAt: THREAD_ACTIVITY_AT,+ updatedAt: THREAD_ACTIVITY_AT,+ lastActivityAt: THREAD_ACTIVITY_AT,+ deletedAt: null,+ },+];++const InboxRouteNavigation = () => {+ const navigate = useNavigate();++ return (+ <>+ <Button onClick={() => navigate(NEW_CHAT_PATH)}>+ Open new chat route+ </Button>+ <Button onClick={() => navigate(NEW_CHAT_PATH, { replace: true })}>+ Replace new chat route+ </Button>+ <Button+ onClick={() =>+ navigate(+ getAppPath(AppPath.AiChatInbox, { threadId: SECOND_THREAD_ID }),+ { replace: true },+ )+ }+ >+ Open saved chat route+ </Button>+ <Button+ onClick={() =>+ navigate({ search: '?panel=details' }, { replace: true })+ }+ >+ Change search parameters+ </Button>+ <Button onClick={() => navigate(-1)}>Back through history</Button>+ <Button onClick={() => navigate(1)}>Forward through history</Button>+ </>+ );+};++const InboxRouteDecorator: Decorator = (Story) => (+ <HelmetProvider>+ <MemoryRouter+ initialEntries={[getAppPath(AppPath.AiChatInbox, { threadId: null })]}+ >+ <ContextStoreComponentInstanceContext.Provider+ value={{ instanceId: MAIN_CONTEXT_STORE_INSTANCE_ID }}+ >+ <MemoryRouterAppNavigatorProvider>+ <InboxRouteNavigation />+ <Routes>+ <Route path={AppPath.AiChatInbox} element={<Story />} />+ </Routes>+ </MemoryRouterAppNavigatorProvider>+ </ContextStoreComponentInstanceContext.Provider>+ </MemoryRouter>+ </HelmetProvider>+);++const loadChatRecordMetadata = () => {+ const objectMetadataItems = jotaiStore.get(objectMetadataItemsSelector.atom);+ const objectMetadataTemplate = objectMetadataItems.find(+ ({ nameSingular }) => nameSingular === CoreObjectNameSingular.Note,+ );++ assertIsDefinedOrThrow(objectMetadataTemplate);++ const chatObjectDefinitions = [+ {+ id: CHAT_OBJECT_METADATA_ID,+ nameSingular: CoreObjectNameSingular.AgentChatThread,+ namePlural: 'agentChatThreads',+ labelSingular: 'Chat',+ labelPlural: 'Chats',+ labelFieldName: 'title',+ fieldNames: CHAT_FIELD_NAMES,+ },+ {+ id: CHAT_TARGET_OBJECT_METADATA_ID,+ nameSingular: CoreObjectNameSingular.AgentChatThreadTarget,+ namePlural: 'agentChatThreadTargets',+ labelSingular: 'Chat target',+ labelPlural: 'Chat targets',+ labelFieldName: 'id',+ fieldNames: ['id'],+ },+ ];+ const chatObjectMetadataItems = chatObjectDefinitions.map(+ ({ labelFieldName, fieldNames, ...objectDefinition }) => {+ const fields = objectMetadataTemplate.fields+ .filter(({ name }) => fieldNames.includes(name))+ .map((field) => {+ const id = uuidv4();++ return {+ ...field,+ id,+ universalIdentifier: id,+ objectMetadataId: objectDefinition.id,+ };+ });+ const labelField = fields.find(({ name }) => name === labelFieldName);++ assertIsDefinedOrThrow(labelField);++ return {+ ...objectMetadataTemplate,+ ...objectDefinition,+ universalIdentifier: objectDefinition.id,+ labelIdentifierFieldMetadataId: labelField.id,+ isSystem: true,+ isSearchable: false,+ fields,+ readableFields: fields,+ updatableFields: fields,+ indexMetadatas: [],+ searchFieldMetadatas: [],+ };+ },+ );++ setTestObjectMetadataItemsInMetadataStore(jotaiStore, [+ ...objectMetadataItems,+ ...chatObjectMetadataItems,+ ]);+};++const getThreadRow = ({+ canvasElement,+ title,+}: {+ canvasElement: HTMLElement;+ title: string;+}) => {+ const row = within(canvasElement)+ .getAllByText(title)+ .map((element) => element.closest<HTMLDivElement>('[data-selectable-id]'))+ .find(isDefined);++ assertIsDefinedOrThrow(row);++ return row;+};++const meta = {+ title: 'Pages/AiChat/AiChatInboxPage',+ component: AiChatInboxPage,+ decorators: [+ InboxRouteDecorator,+ ComponentDecorator,+ ObjectMetadataItemsDecorator,+ RootDecorator,+ ToastDecorator,+ ],+ beforeEach: () => {+ initializeNewAiChatStory({ isInboxEnabled: true });+ jotaiStore.set(+ aiChatInboxLayoutState.atom,+ AI_CHAT_INBOX_LAYOUT.RECORD_PAGE,+ );+ jotaiStore.set(+ agentChatThreadFilterStatusState.atom,+ AGENT_CHAT_THREAD_FILTER_STATUS.ACTIVE,+ );+ jotaiStore.set(agentChatThreadListState.atom, {+ threadIds: THREADS.map(({ id }) => id),+ hasNextPage: false,+ endCursor: null,+ });+ jotaiStore.set(+ agentChatThreadParticipantsState.atom,+ Object.fromEntries(+ THREADS.map(({ id }) => [+ id,+ {+ id: `participant-${id}`,+ threadId: id,+ isSubscribed: true,+ updatedAt: THREAD_ACTIVITY_AT,+ },+ ]),+ ),+ );++ for (const thread of THREADS) {+ jotaiStore.set(recordStoreFamilyState.atomFamily(thread.id), thread);+ }+ },+ parameters: {+ container: { width: 1200, height: 784 },+ msw: {+ handlers: [+ graphql.query('GetAiChatUsage', () =>+ HttpResponse.json({ data: { aiChatUsage: null } }),+ ),+ graphql.query('MyConnectedAccounts', () =>+ HttpResponse.json({ data: { myConnectedAccounts: [] } }),+ ),+ graphql.query('MyMessageChannels', () =>+ HttpResponse.json({ data: { myMessageChannels: [] } }),+ ),+ graphql.query('MyCalendarChannels', () =>+ HttpResponse.json({ data: { myCalendarChannels: [] } }),+ ),+ graphql.query('FindOneAgentChatThread', ({ variables }) =>+ HttpResponse.json({+ data: {+ agentChatThread:+ THREADS.find(({ id }) => id === variables.objectRecordId) ??+ null,+ },+ }),+ ),+ graphql.query('FindManyAgentChatThreads', () => {+ const objectMetadataItems = jotaiStore.get(+ objectMetadataItemsSelector.atom,+ );+ const objectMetadataItem = objectMetadataItems.find(+ ({ id }) => id === CHAT_OBJECT_METADATA_ID,+ );++ assertIsDefinedOrThrow(objectMetadataItem);++ return HttpResponse.json({+ data: {+ agentChatThreads: getRecordConnectionFromRecords({+ objectMetadataItems,+ objectMetadataItem,+ records: THREADS,+ }),+ },+ });+ }),+ ],+ },+ },+} satisfies Meta<typeof AiChatInboxPage>;++export default meta;+type Story = StoryObj<typeof meta>;++export const NewChatClearsSelection: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const user = userEvent.setup();++ const selectThread = async (title: string) => {+ const row = getThreadRow({ canvasElement, title });++ await user.keyboard('{Control>}');+ await user.click(within(row).getByText(title));+ await user.keyboard('{/Control}');+ await expect(+ within(row).getByRole('checkbox', { name: 'Select chat' }),+ ).toBeChecked();+ };++ const expectThreadUnchecked = async (title: string) => {+ const row = getThreadRow({ canvasElement, title });++ await expect(within(row).getByLabelText('Select chat')).not.toBeChecked();+ };++ await canvas.findByText(FIRST_THREAD_TITLE);+ await selectThread(FIRST_THREAD_TITLE);+ await selectThread(SECOND_THREAD_TITLE);+ await expect(canvas.getByText('2 selected')).toBeVisible();++ await user.click(+ canvas.getByRole('button', { name: 'Open new chat route' }),+ );+ await expect(await canvas.findByRole('textbox')).toBeVisible();+ await user.click(canvas.getByRole('button', { name: 'Show inbox' }));+ await expectThreadUnchecked(FIRST_THREAD_TITLE);+ await expectThreadUnchecked(SECOND_THREAD_TITLE);++ await user.click(canvas.getByRole('button', { name: 'Hide inbox' }));+ await user.click(+ canvas.getByRole('button', { name: 'Back through history' }),+ );+ await canvas.findByText(FIRST_THREAD_TITLE);+ await expectThreadUnchecked(FIRST_THREAD_TITLE);+ await expectThreadUnchecked(SECOND_THREAD_TITLE);+ await expect(+ canvas.getByRole('button', { name: 'New chat' }),+ ).toBeVisible();++ await user.click(+ canvas.getByRole('button', { name: 'Forward through history' }),+ );+ await expect(await canvas.findByRole('textbox')).toBeVisible();+ await user.click(canvas.getByRole('button', { name: 'Show inbox' }));+ const firstThreadRow = getThreadRow({+ canvasElement,+ title: FIRST_THREAD_TITLE,+ });++ await selectThread(FIRST_THREAD_TITLE);+ await expect(canvas.getByText('1 chat selected')).toBeVisible();++ await user.click(+ canvas.getByRole('button', { name: 'Replace new chat route' }),+ );+ await expect(await canvas.findByRole('textbox')).toBeVisible();+ await expectThreadUnchecked(FIRST_THREAD_TITLE);+ await expect(+ getThreadRow({ canvasElement, title: FIRST_THREAD_TITLE }),+ ).toBe(firstThreadRow);+ },+};++export const SavedChatNavigationClearsSelection: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const user = userEvent.setup();++ await canvas.findByText(FIRST_THREAD_TITLE);+ loadChatRecordMetadata();+ jotaiStore.set(+ aiChatInboxLayoutState.atom,+ AI_CHAT_INBOX_LAYOUT.SPLIT_VIEW,+ );+ await canvas.findByRole('button', { name: 'Chat details' });++ const firstThreadRow = getThreadRow({+ canvasElement,+ title: FIRST_THREAD_TITLE,+ });+ const secondThreadRow = getThreadRow({+ canvasElement,+ title: SECOND_THREAD_TITLE,+ });++ await user.keyboard('{Control>}');+ await user.click(within(secondThreadRow).getByText(SECOND_THREAD_TITLE));+ await user.keyboard('{/Control}');+ await expect(canvas.getByText('2 chats selected')).toBeVisible();++ await user.click(+ canvas.getByRole('button', { name: 'Change search parameters' }),+ );+ await expect(canvas.getByText('2 chats selected')).toBeVisible();+ await expect(+ within(firstThreadRow).getByLabelText('Select chat'),+ ).toBeChecked();+ await expect(+ within(secondThreadRow).getByLabelText('Select chat'),+ ).toBeChecked();++ await user.click(+ canvas.getByRole('button', { name: 'Open saved chat route' }),+ );+ await expect(+ await canvas.findByRole('button', { name: 'Chat details' }),+ ).toBeVisible();+ await expect(+ canvas.queryByText('2 chats selected'),+ ).not.toBeInTheDocument();+ await expect(canvas.getAllByText(SECOND_THREAD_TITLE)).toHaveLength(2);+ await expect(+ within(firstThreadRow).getByLabelText('Select chat'),+ ).not.toBeChecked();+ await expect(+ within(secondThreadRow).getByLabelText('Select chat'),+ ).not.toBeChecked();+ await expect(+ getThreadRow({ canvasElement, title: FIRST_THREAD_TITLE }),+ ).toBe(firstThreadRow);+ await expect(+ getThreadRow({ canvasElement, title: SECOND_THREAD_TITLE }),+ ).toBe(secondThreadRow);+ },+};diff --git a/packages/twenty-front/src/pages/ai-chat/__stories__/AiChatPage.stories.tsx b/packages/twenty-front/src/pages/ai-chat/__stories__/AiChatPage.stories.tsxnew file mode 100644index 00000000000..bcb3b607193--- /dev/null+++ b/packages/twenty-front/src/pages/ai-chat/__stories__/AiChatPage.stories.tsx@@ -0,0 +1,283 @@+import {+ type Decorator,+ type Meta,+ type StoryObj,+} from '@storybook/react-vite';+import { graphql, HttpResponse } from 'msw';+import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';+import { expect, userEvent, waitFor, within } from 'storybook/test';+import { AppPath, CoreObjectNameSingular } from 'twenty-shared/types';+import { getAppPath, isDefined } from 'twenty-shared/utils';+import { Button } from 'twenty-ui/primitives/input';+import { ComponentDecorator } from 'twenty-ui/testing';++import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';+import { AI_CHAT_NEW_THREAD_PATH_SEGMENT } from '@/ai/constants/AiChatNewThreadPathSegment';+import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';+import { initializeNewAiChatStory } from '@/ai/testing/initializeNewAiChatStory';+import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';+import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';+import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';+import { flatObjectMetadataItemsSelector } from '@/object-metadata/states/flatObjectMetadataItemsSelector';+import { recordPermissionsFamilyState } from '@/object-record/record-sharing/states/recordPermissionsFamilyState';+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';+import { AiChatPage } from '~/pages/ai-chat/AiChatPage';+import { MemoryRouterAppNavigatorProvider } from '~/testing/components/MemoryRouterAppNavigatorProvider';+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';+import { RootDecorator } from '~/testing/decorators/RootDecorator';+import { ToastDecorator } from '~/testing/decorators/ToastDecorator';++const EXISTING_THREAD_ID = '20202020-0000-4000-8000-0000000000aa';+const NEXT_DRAFT_THREAD_ID = '20202020-0000-4000-8000-0000000000bb';+const RETURNED_DRAFT_THREAD_ID = '20202020-0000-4000-8000-0000000000dd';+const CHAT_OBJECT_METADATA_ID = '20202020-0000-4000-8000-0000000000cc';+const DRAFT_TEXT = 'Draft for the new conversation';+const NEXT_DRAFT_TEXT = 'Draft selected when opening the new chat route';+const RETURNED_DRAFT_TEXT = 'Draft selected when returning through history';+const CONTINUED_DRAFT_TEXT = ' with more details';+const OTHER_PAGE_PATH = '/new-chat-story-other-page';++const ChatRouteNavigation = () => {+ const navigate = useNavigate();++ return (+ <>+ <Button+ onClick={() =>+ navigate(+ getAppPath(AppPath.AiChat, {+ threadId: AI_CHAT_NEW_THREAD_PATH_SEGMENT,+ }),+ )+ }+ >+ Open new chat+ </Button>+ <Button onClick={() => navigate(OTHER_PAGE_PATH)}>Leave chat</Button>+ <Button onClick={() => navigate(-1)}>Back through history</Button>+ <Button onClick={() => navigate(1)}>Forward through history</Button>+ </>+ );+};++const createChatRouteDecorator =+ ({+ initialPath,+ shouldShowNavigation = false,+ }: {+ initialPath: string;+ shouldShowNavigation?: boolean;+ }): Decorator =>+ (Story) => (+ <MemoryRouter initialEntries={[initialPath]}>+ <MemoryRouterAppNavigatorProvider>+ {shouldShowNavigation && <ChatRouteNavigation />}+ <Routes>+ <Route path={AppPath.AiChat} element={<Story />} />+ <Route path={OTHER_PAGE_PATH} element={<div>Outside chat</div>} />+ </Routes>+ </MemoryRouterAppNavigatorProvider>+ </MemoryRouter>+ );++const initializeChatPageStory = () => {+ initializeNewAiChatStory({ isInboxEnabled: false });+ const draftThreadId = jotaiStore.get(newAiChatThreadIdState.atom);++ jotaiStore.set(agentChatDraftsByThreadIdState.atom, {+ [draftThreadId]: serializePlainTextAsAdvancedTextEditorDocument(DRAFT_TEXT),+ });+ jotaiStore.set(currentAiChatThreadState.atom, EXISTING_THREAD_ID);+};++const allowSelectedConversationUpdates = () => {+ const workspace = jotaiStore.get(currentWorkspaceState.atom);+ const workspaceMember = jotaiStore.get(currentWorkspaceMemberState.atom);+ const threadId = jotaiStore.get(currentAiChatThreadState.atom);+ const objectMetadataTemplate = jotaiStore+ .get(flatObjectMetadataItemsSelector.atom)+ .find(({ nameSingular }) => nameSingular === CoreObjectNameSingular.Note);++ if (+ !isDefined(workspace) ||+ !isDefined(workspaceMember) ||+ !isDefined(threadId) ||+ !isDefined(objectMetadataTemplate)+ ) {+ throw new Error('The conversation metadata must be loaded.');+ }++ const chatObjectMetadataItem = {+ ...objectMetadataTemplate,+ id: CHAT_OBJECT_METADATA_ID,+ universalIdentifier: CHAT_OBJECT_METADATA_ID,+ nameSingular: CoreObjectNameSingular.AgentChatThread,+ namePlural: 'agentChatThreads',+ labelSingular: 'Chat',+ labelPlural: 'Chats',+ labelIdentifierFieldMetadataId: '',+ isSystem: true,+ isSearchable: false,+ searchFieldMetadatas: [],+ };++ jotaiStore.set(+ metadataStoreState.atomFamily('objectMetadataItems'),+ (metadataStore) => ({+ ...metadataStore,+ current: [...metadataStore.current, chatObjectMetadataItem],+ }),+ );++ jotaiStore.set(+ recordPermissionsFamilyState.atomFamily({+ objectMetadataId: CHAT_OBJECT_METADATA_ID,+ recordId: threadId,+ workspaceId: workspace.id,+ workspaceMemberId: workspaceMember.id,+ }),+ {+ requestId: 'new-chat-story',+ permissions: {+ canRead: true,+ canUpdate: true,+ canDelete: true,+ canSoftDelete: true,+ },+ userWorkspace: jotaiStore.get(currentUserWorkspaceState.atom),+ },+ );+};++const meta = {+ title: 'Pages/AiChat/AiChatPage',+ component: AiChatPage,+ decorators: [+ ComponentDecorator,+ ObjectMetadataItemsDecorator,+ RootDecorator,+ ToastDecorator,+ ],+ beforeEach: initializeChatPageStory,+ parameters: {+ container: { width: 1000, height: 784 },+ msw: {+ handlers: [+ graphql.query('GetAiChatUsage', () =>+ HttpResponse.json({ data: { aiChatUsage: null } }),+ ),+ ],+ },+ },+} satisfies Meta<typeof AiChatPage>;++export default meta;+type Story = StoryObj<typeof meta>;++export const NewChatDraftSelection: Story = {+ decorators: [+ createChatRouteDecorator({+ initialPath: getAppPath(AppPath.AiChat, {+ threadId: AI_CHAT_NEW_THREAD_PATH_SEGMENT,+ }),+ }),+ ],+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const editor = await canvas.findByRole('textbox');+ const draftThreadId = jotaiStore.get(newAiChatThreadIdState.atom);++ await expect(editor).toHaveTextContent(DRAFT_TEXT);+ await expect(jotaiStore.get(currentAiChatThreadState.atom)).toBe(+ draftThreadId,+ );++ allowSelectedConversationUpdates();+ jotaiStore.set(newAiChatThreadIdState.atom, NEXT_DRAFT_THREAD_ID);++ await userEvent.click(editor);+ const selection = editor.ownerDocument.getSelection();+ selection?.selectAllChildren(editor);+ selection?.collapseToEnd();++ await userEvent.type(editor, CONTINUED_DRAFT_TEXT, { skipClick: true });+ await expect(editor).toHaveTextContent(+ `${DRAFT_TEXT}${CONTINUED_DRAFT_TEXT}`,+ );+ await waitFor(() =>+ expect(jotaiStore.get(currentAiChatThreadState.atom)).toBe(draftThreadId),+ );+ },+};++export const NewChatRouteHistory: Story = {+ decorators: [+ createChatRouteDecorator({+ initialPath: getAppPath(AppPath.AiChat, { threadId: null }),+ shouldShowNavigation: true,+ }),+ ],+ beforeEach: () => {+ initializeChatPageStory();+ jotaiStore.set(currentAiChatThreadState.atom, null);+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(await canvas.findByRole('textbox')).toHaveTextContent(+ DRAFT_TEXT,+ );++ jotaiStore.set(agentChatDraftsByThreadIdState.atom, (drafts) => ({+ ...drafts,+ [NEXT_DRAFT_THREAD_ID]:+ serializePlainTextAsAdvancedTextEditorDocument(NEXT_DRAFT_TEXT),+ }));+ jotaiStore.set(newAiChatThreadIdState.atom, NEXT_DRAFT_THREAD_ID);++ await userEvent.click(+ canvas.getByRole('button', { name: 'Open new chat' }),+ );+ await expect(await canvas.findByRole('textbox')).toHaveTextContent(+ NEXT_DRAFT_TEXT,+ );+ await expect(jotaiStore.get(currentAiChatThreadState.atom)).toBe(+ NEXT_DRAFT_THREAD_ID,+ );++ await userEvent.click(canvas.getByRole('button', { name: 'Leave chat' }));+ await expect(await canvas.findByText('Outside chat')).toBeVisible();++ jotaiStore.set(agentChatDraftsByThreadIdState.atom, (drafts) => ({+ ...drafts,+ [RETURNED_DRAFT_THREAD_ID]:+ serializePlainTextAsAdvancedTextEditorDocument(RETURNED_DRAFT_TEXT),+ }));+ jotaiStore.set(newAiChatThreadIdState.atom, RETURNED_DRAFT_THREAD_ID);++ await userEvent.click(+ canvas.getByRole('button', { name: 'Back through history' }),+ );+ await expect(await canvas.findByRole('textbox')).toHaveTextContent(+ RETURNED_DRAFT_TEXT,+ );+ await expect(jotaiStore.get(currentAiChatThreadState.atom)).toBe(+ RETURNED_DRAFT_THREAD_ID,+ );++ await userEvent.click(+ canvas.getByRole('button', { name: 'Forward through history' }),+ );+ await expect(await canvas.findByText('Outside chat')).toBeVisible();++ await userEvent.click(+ canvas.getByRole('button', { name: 'Back through history' }),+ );+ await expect(await canvas.findByRole('textbox')).toHaveTextContent(+ RETURNED_DRAFT_TEXT,+ );+ },+};diff --git a/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx b/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsxindex c73261c1a09..d279e7b85ed 100644--- a/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx+++ b/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx@@ -16,6 +16,7 @@ import { contextStoreTargetedRecordsRuleComponentState } from '@/context-store/simport { ContextStoreComponentInstanceContext } from '@/context-store/states/contexts/ContextStoreComponentInstanceContext';import { AI_CHAT_INBOX_INSTANCE_ID } from '@/ai/constants/AiChatInboxInstanceId';import { AI_CHAT_INBOX_LAYOUT } from '@/ai/constants/AiChatInboxLayout';+import { AI_CHAT_NEW_THREAD_PATH_SEGMENT } from '@/ai/constants/AiChatNewThreadPathSegment';import { AGENT_CHAT_THREAD_FILTER_STATUS } from '@/ai/constants/AgentChatThreadFilterStatus';import { useOptimisticallyRestoreOnSend } from '@/ai/hooks/useOptimisticallyRestoreOnSend';import { agentChatThreadFilterStatusState } from '@/ai/states/agentChatThreadFilterStatusState';@@ -124,6 +125,19 @@ jest.mock('~/pages/ai-chat/AiChatPageEffects', () => ({AiChatPageEffects: () => null,}));+jest.mock('@/ai/components/AiChatTab', () => ({+ AiChatTab: () => <div>New conversation composer</div>,+}));++jest.mock('@/ai/components/AiChatPageHeader', () => ({+ AiChatPageHeader: ({ actionButton }: { actionButton?: ReactNode }) => (+ <div>+ New chat header+ {actionButton}+ </div>+ ),+}));+// Sending stands in for the composer with what a send applies right awayjest.mock('~/pages/ai-chat/AiChatThreadPageContent', () => ({AiChatThreadPageContent: ({@@ -283,6 +297,17 @@ describe('AiChatInboxPage', () => {).not.toBeInTheDocument();});+ it('shows a new chat beside the list without opening the first saved chat', () => {+ renderInbox(`/inbox/${AI_CHAT_NEW_THREAD_PATH_SEGMENT}`);++ expect(screen.getByText('New conversation composer')).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: 'First chat' }),+ ).toBeInTheDocument();+ expect(isRowOpen('First chat')).toBe(false);+ expect(screen.queryByText(/^Chat page /)).not.toBeInTheDocument();+ });+it('opens the clicked chat', () => {renderInbox();@@ -523,6 +548,16 @@ describe('AiChatInboxPage', () => {);});+ it('shows a new chat in place of the list', () => {+ renderInbox(`/inbox/${AI_CHAT_NEW_THREAD_PATH_SEGMENT}`);++ expect(screen.getByText('New conversation composer')).toBeInTheDocument();+ expect(+ screen.queryByRole('button', { name: 'First chat' }),+ ).not.toBeInTheDocument();+ expect(screen.queryByText(/^Chat page /)).not.toBeInTheDocument();+ });+it('shows the list alone, then the clicked chat alone', () => {renderInbox('/inbox');@@ -597,6 +632,18 @@ describe('AiChatInboxPage', () => {isMobile = true;});+ it('shows a new chat with a way back to the inbox', () => {+ renderInbox(`/inbox/${AI_CHAT_NEW_THREAD_PATH_SEGMENT}`);++ expect(screen.getByText('New conversation composer')).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: 'Back to inbox' }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole('button', { name: 'First chat' }),+ ).not.toBeInTheDocument();+ });+it('opens the tapped chat in place of the list', () => {renderInbox('/inbox');