The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Add full-page AI chat mode with records as side panel artifacts (#23929)
Félix Malfait1f5ce0fbe7e8
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex 94c6225a786..f3a4027206c 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -1800,6 +1800,7 @@ type FeatureFlag {}enum FeatureFlagKey {+ IS_AI_CHAT_PAGE_ENABLEDIS_APP_CLAIMING_ENABLEDIS_UNIQUE_INDEXES_ENABLEDIS_JSON_FILTER_ENABLEDdiff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex cae780b6ff0..6c9e1a97cb9 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -1446,7 +1446,7 @@ export interface FeatureFlag {__typename: 'FeatureFlag'}-export type FeatureFlagKey = 'IS_APP_CLAIMING_ENABLED' | 'IS_UNIQUE_INDEXES_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_CALENDAR_WEEK_VIEW_ENABLED' | 'IS_EMAIL_GROUP_ENABLED' | 'IS_JUNCTION_RELATIONS_ENABLED' | 'IS_LIST_VIEW_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_SETTINGS_DISCOVERY_HERO_ENABLED' | 'IS_WORKFLOW_VERSION_IN_CORE_ENABLED' | 'IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED'+export type FeatureFlagKey = 'IS_AI_CHAT_PAGE_ENABLED' | 'IS_APP_CLAIMING_ENABLED' | 'IS_UNIQUE_INDEXES_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_CALENDAR_WEEK_VIEW_ENABLED' | 'IS_EMAIL_GROUP_ENABLED' | 'IS_JUNCTION_RELATIONS_ENABLED' | 'IS_LIST_VIEW_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_SETTINGS_DISCOVERY_HERO_ENABLED' | 'IS_WORKFLOW_VERSION_IN_CORE_ENABLED' | 'IS_WORKFLOW_DISPATCH_FROM_CORE_ENABLED'export interface WorkspaceUrls {customUrl?: Scalars['String']@@ -9677,6 +9677,7 @@ export const enumDatabaseEventAction = {}export const enumFeatureFlagKey = {+ IS_AI_CHAT_PAGE_ENABLED: 'IS_AI_CHAT_PAGE_ENABLED' as const,IS_APP_CLAIMING_ENABLED: 'IS_APP_CLAIMING_ENABLED' as const,IS_UNIQUE_INDEXES_ENABLED: 'IS_UNIQUE_INDEXES_ENABLED' as const,IS_JSON_FILTER_ENABLED: 'IS_JSON_FILTER_ENABLED' as const,diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.tsindex 115f44fb705..1ce0033c05f 100644--- a/packages/twenty-front/src/generated-admin/graphql.ts+++ b/packages/twenty-front/src/generated-admin/graphql.ts@@ -368,6 +368,7 @@ export type FeatureFlag = {};export enum FeatureFlagKey {+ IS_AI_CHAT_PAGE_ENABLED = 'IS_AI_CHAT_PAGE_ENABLED',IS_APP_CLAIMING_ENABLED = 'IS_APP_CLAIMING_ENABLED',IS_CALENDAR_WEEK_VIEW_ENABLED = 'IS_CALENDAR_WEEK_VIEW_ENABLED',IS_EMAIL_GROUP_ENABLED = 'IS_EMAIL_GROUP_ENABLED',diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex a4fd9b8b1a9..3e611b1d246 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -1814,6 +1814,7 @@ export type FeatureFlag = {};export enum FeatureFlagKey {+ IS_AI_CHAT_PAGE_ENABLED = 'IS_AI_CHAT_PAGE_ENABLED',IS_APP_CLAIMING_ENABLED = 'IS_APP_CLAIMING_ENABLED',IS_CALENDAR_WEEK_VIEW_ENABLED = 'IS_CALENDAR_WEEK_VIEW_ENABLED',IS_EMAIL_GROUP_ENABLED = 'IS_EMAIL_GROUP_ENABLED',diff --git a/packages/twenty-front/src/hooks/__tests__/usePageChangeEffectNavigateLocation.test.ts b/packages/twenty-front/src/hooks/__tests__/usePageChangeEffectNavigateLocation.test.tsindex 2b206e12c56..afbcd715402 100644--- a/packages/twenty-front/src/hooks/__tests__/usePageChangeEffectNavigateLocation.test.ts+++ b/packages/twenty-front/src/hooks/__tests__/usePageChangeEffectNavigateLocation.test.ts@@ -6,7 +6,7 @@ import { useQuery } from '@apollo/client/react';import { useParams } from 'react-router-dom';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { AppPath, SettingsPath } from 'twenty-shared/types';-import { getSettingsPath } from 'twenty-shared/utils';+import { getAppPath, getSettingsPath } from 'twenty-shared/utils';import { OnboardingStatus, PageLayoutType } from '~/generated-metadata/graphql';@@ -120,17 +120,6 @@ const testCases: {shouldOpenAiChatAfterOnboarding?: boolean;isOnboardingCheckoutPending?: boolean;}[] = [- { loc: AppPath.WorkspaceSetup, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.PLAN_REQUIRED, res: AppPath.PlanRequired },- { loc: AppPath.WorkspaceSetup, isLogged: true, isWorkspaceSuspended: true, onboardingStatus: OnboardingStatus.COMPLETED, res: getSettingsPath(SettingsPath.Billing) },- { loc: AppPath.WorkspaceSetup, isLogged: false, isWorkspaceSuspended: false, onboardingStatus: undefined, res: AppPath.SignInUp },- { loc: AppPath.WorkspaceSetup, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.WORKSPACE_ACTIVATION, res: AppPath.WorkspaceActivation },- { loc: AppPath.WorkspaceSetup, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.PROFILE_CREATION, res: AppPath.CreateProfile },- { loc: AppPath.WorkspaceSetup, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.SYNC_EMAIL, res: AppPath.SyncEmails },- { loc: AppPath.WorkspaceSetup, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.APPS_INSTALLATION, res: AppPath.InstallApps },- { loc: AppPath.WorkspaceSetup, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.INVITE_TEAM, res: AppPath.InviteTeam },- { loc: AppPath.WorkspaceSetup, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.BOOK_CALL, res: AppPath.BookCall },- { loc: AppPath.WorkspaceSetup, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, res: undefined },-{ loc: AppPath.Verify, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.PLAN_REQUIRED, res: AppPath.PlanRequired },{ loc: AppPath.Verify, isLogged: true, isWorkspaceSuspended: true, onboardingStatus: OnboardingStatus.COMPLETED, res: getSettingsPath(SettingsPath.Billing) },{ loc: AppPath.Verify, isLogged: false, isWorkspaceSuspended: false, onboardingStatus: undefined, res: undefined },@@ -298,6 +287,17 @@ const testCases: {{ loc: AppPath.TasksPage, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.BOOK_CALL, res: AppPath.BookCall },{ loc: AppPath.TasksPage, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, res: undefined },+ { loc: AppPath.AiChat, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.PLAN_REQUIRED, res: AppPath.PlanRequired },+ { loc: AppPath.AiChat, isLogged: true, isWorkspaceSuspended: true, onboardingStatus: OnboardingStatus.COMPLETED, res: getSettingsPath(SettingsPath.Billing) },+ { loc: AppPath.AiChat, isLogged: false, isWorkspaceSuspended: false, onboardingStatus: undefined, res: AppPath.SignInUp },+ { loc: AppPath.AiChat, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.WORKSPACE_ACTIVATION, res: AppPath.WorkspaceActivation },+ { loc: AppPath.AiChat, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.PROFILE_CREATION, res: AppPath.CreateProfile },+ { loc: AppPath.AiChat, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.SYNC_EMAIL, res: AppPath.SyncEmails },+ { loc: AppPath.AiChat, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.APPS_INSTALLATION, res: AppPath.InstallApps },+ { loc: AppPath.AiChat, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.INVITE_TEAM, res: AppPath.InviteTeam },+ { loc: AppPath.AiChat, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.BOOK_CALL, res: AppPath.BookCall },+ { loc: AppPath.AiChat, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, res: undefined },+{ loc: AppPath.OpportunitiesPage, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.PLAN_REQUIRED, res: AppPath.PlanRequired },{ loc: AppPath.OpportunitiesPage, isLogged: true, isWorkspaceSuspended: true, onboardingStatus: OnboardingStatus.COMPLETED, res: getSettingsPath(SettingsPath.Billing) },{ loc: AppPath.OpportunitiesPage, isLogged: false, isWorkspaceSuspended: false, onboardingStatus: undefined, res: AppPath.SignInUp },@@ -413,9 +413,9 @@ const testCases: {{ loc: AppPath.SignInUp, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, returnToPath: '/objects/tasks', res: '/objects/tasks' },{ loc: AppPath.Index, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, returnToPath: '/settings/api-keys', res: '/settings/api-keys' },- { loc: AppPath.InviteTeam, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, isBillingEnabled: false, shouldOpenAiChatAfterOnboarding: true, res: AppPath.WorkspaceSetup },+ { loc: AppPath.InviteTeam, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, isBillingEnabled: false, shouldOpenAiChatAfterOnboarding: true, res: getAppPath(AppPath.AiChat, { threadId: null }) },{ loc: AppPath.InviteTeam, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, isBillingEnabled: false, shouldOpenAiChatAfterOnboarding: false, res: defaultHomePagePath },- { loc: AppPath.PlanRequiredSuccess, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, shouldOpenAiChatAfterOnboarding: true, res: AppPath.WorkspaceSetup },+ { loc: AppPath.PlanRequiredSuccess, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, shouldOpenAiChatAfterOnboarding: true, res: getAppPath(AppPath.AiChat, { threadId: null }) },{ loc: AppPath.SignInUp, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, shouldOpenAiChatAfterOnboarding: true, returnToPath: '/objects/tasks', res: '/objects/tasks' },{ loc: AppPath.PlanRequiredSuccess, isLogged: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, isOnboardingCheckoutPending: true, res: undefined },diff --git a/packages/twenty-front/src/hooks/usePageChangeEffectNavigateLocation.ts b/packages/twenty-front/src/hooks/usePageChangeEffectNavigateLocation.tsindex 6100788b70f..c91bb2d5c9e 100644--- a/packages/twenty-front/src/hooks/usePageChangeEffectNavigateLocation.ts+++ b/packages/twenty-front/src/hooks/usePageChangeEffectNavigateLocation.ts@@ -19,7 +19,7 @@ import { useQuery } from '@apollo/client/react';import { isNonEmptyString } from '@sniptt/guards';import { useLocation, useParams } from 'react-router-dom';import { AppPath, SettingsPath } from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';+import { isDefined, getAppPath } from 'twenty-shared/utils';import { WorkspaceActivationStatus } from 'twenty-shared/workspace';import {FindOnePageLayoutTypeDocument,@@ -85,7 +85,7 @@ export const usePageChangeEffectNavigateLocation = () => {shouldOpenAiChatAfterOnboardingState,);const onboardingCompletedPath = shouldOpenAiChatAfterOnboarding- ? AppPath.WorkspaceSetup+ ? getAppPath(AppPath.AiChat, { threadId: null }): defaultHomePagePath;const isOnboardingCheckoutPending = useAtomStateValue(diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPageCloseAskAiPanelEffect.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPageCloseAskAiPanelEffect.tsxnew file mode 100644index 00000000000..884b69636ef--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatPageCloseAskAiPanelEffect.tsx@@ -0,0 +1,23 @@+import { useStore } from 'jotai';+import { useEffect } from 'react';+import { SidePanelPages } from 'twenty-shared/types';++import { useSidePanelMenu } from '@/side-panel/hooks/useSidePanelMenu';+import { isSidePanelOpenedState } from '@/side-panel/states/isSidePanelOpenedState';+import { sidePanelPageState } from '@/side-panel/states/sidePanelPageState';++export const AiChatPageCloseAskAiPanelEffect = () => {+ const store = useStore();+ const { closeSidePanelMenu } = useSidePanelMenu();++ useEffect(() => {+ const isSidePanelOpened = store.get(isSidePanelOpenedState.atom);+ const sidePanelPage = store.get(sidePanelPageState.atom);++ if (isSidePanelOpened && sidePanelPage === SidePanelPages.AskAI) {+ void closeSidePanelMenu();+ }+ }, [store, closeSidePanelMenu]);++ return null;+};diff --git a/packages/twenty-front/src/modules/onboarding/effect-components/WorkspaceSetupChatSidePanelHandoffEffect.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPageContinueInSidePanelEffect.tsxsimilarity index 89%rename from packages/twenty-front/src/modules/onboarding/effect-components/WorkspaceSetupChatSidePanelHandoffEffect.tsxrename to packages/twenty-front/src/modules/ai/components/AiChatPageContinueInSidePanelEffect.tsxindex 0839cc096b6..6f65848fbe3 100644--- a/packages/twenty-front/src/modules/onboarding/effect-components/WorkspaceSetupChatSidePanelHandoffEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatPageContinueInSidePanelEffect.tsx@@ -3,7 +3,7 @@ import { useEffect } from 'react';import { shouldContinueAiChatInSidePanelState } from '@/ai/states/shouldContinueAiChatInSidePanelState';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';-export const WorkspaceSetupChatSidePanelHandoffEffect = () => {+export const AiChatPageContinueInSidePanelEffect = () => {const setShouldContinueAiChatInSidePanel = useSetAtomState(shouldContinueAiChatInSidePanelState,);diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsxnew file mode 100644index 00000000000..301804f6dba--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatPageHeader.tsx@@ -0,0 +1,78 @@+import { styled } from '@linaria/react';+import { useLingui } from '@lingui/react/macro';+import { useContext } from 'react';+import { IconEdit, IconSparkles } from 'twenty-ui/icon';+import { IconButton } from 'twenty-ui/input';+import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';+import { useIsMobile } from 'twenty-ui/utilities';++import { AiChatCloseButton } from '@/ai/components/AiChatCloseButton';+import { AiChatCollapseButton } from '@/ai/components/AiChatCollapseButton';+import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';+import { useNavigationDrawerExpanded } from '@/navigation/hooks/useNavigationDrawerExpanded';+import { SIDE_PANEL_TOP_BAR_HEIGHT } from '@/side-panel/constants/SidePanelTopBarHeight';+import { NavigationDrawerCollapseButton } from '@/ui/navigation/navigation-drawer/components/NavigationDrawerCollapseButton';++const StyledHeader = styled.header`+ align-items: center;+ background-color: ${themeCssVariables.background.secondary};+ border-bottom: 1px solid ${themeCssVariables.border.color.light};+ box-sizing: border-box;+ display: flex;+ flex-shrink: 0;+ gap: ${themeCssVariables.spacing['0.5']};+ height: ${SIDE_PANEL_TOP_BAR_HEIGHT}px;+ padding: 0 ${themeCssVariables.spacing[2]};+`;++const StyledHeaderTitle = styled.div`+ align-items: center;+ color: ${themeCssVariables.font.color.primary};+ display: flex;+ flex: 1;+ font-size: ${themeCssVariables.font.size.md};+ font-weight: ${themeCssVariables.font.weight.semiBold};+ gap: ${themeCssVariables.spacing[1]};+ min-width: 0;+ overflow: hidden;+ padding: 0 ${themeCssVariables.spacing[1]};+ text-overflow: ellipsis;+ white-space: nowrap;+`;++type AiChatPageHeaderProps = {+ isOnboarding: boolean;+};++export const AiChatPageHeader = ({ isOnboarding }: AiChatPageHeaderProps) => {+ const { t } = useLingui();+ const { theme } = useContext(ThemeContext);+ const isMobile = useIsMobile();+ const isNavigationDrawerExpanded = useNavigationDrawerExpanded();+ const { switchToNewChat } = useSwitchToNewAiChat();++ return (+ <StyledHeader>+ {!isNavigationDrawerExpanded && !isMobile && (+ <NavigationDrawerCollapseButton direction="right" />+ )}+ <StyledHeaderTitle>+ <IconSparkles size={theme.icon.size.md} />+ {isOnboarding ? t`Onboarding` : t`Ask AI`}+ </StyledHeaderTitle>+ {/* The onboarding conversation is single-threaded: switching or+ starting threads would abandon the workspace setup. */}+ {!isOnboarding && (+ <IconButton+ Icon={IconEdit}+ size="small"+ variant="tertiary"+ onClick={() => switchToNewChat()}+ ariaLabel={t`New conversation`}+ />+ )}+ <AiChatCollapseButton />+ {isOnboarding && <AiChatCloseButton />}+ </StyledHeader>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsxnew file mode 100644index 00000000000..356b740c9e7--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsx@@ -0,0 +1,27 @@+import { useEffect } from 'react';+import { useParams } from 'react-router-dom';+import { isDefined, isValidUuid } from 'twenty-shared/utils';++import { useSwitchAgentChatThreadWithDraft } from '@/ai/hooks/useSwitchAgentChatThreadWithDraft';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';++export const AiChatPageThreadUrlSyncEffect = () => {+ const { threadId } = useParams();+ const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);+ const { switchThreadWithDraft } = useSwitchAgentChatThreadWithDraft();++ useEffect(() => {+ if (!isDefined(threadId) || !isValidUuid(threadId)) {+ return;+ }++ if (threadId === currentAiChatThread) {+ return;+ }++ switchThreadWithDraft(threadId);+ }, [threadId, currentAiChatThread, switchThreadWithDraft]);++ return null;+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadsList.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadsList.tsxdeleted file mode 100644index 0ed7d3106cb..00000000000--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadsList.tsx+++ /dev/null@@ -1,128 +0,0 @@-import { styled } from '@linaria/react';--import { AiChatThreadDeleteConfirmationModal } from '@/ai/components/AiChatThreadDeleteConfirmationModal';-import { AiChatThreadFilterDropdown } from '@/ai/components/AiChatThreadFilterDropdown';-import { AiChatThreadGroup } from '@/ai/components/AiChatThreadGroup';-import { AiChatThreadListItem } from '@/ai/components/AiChatThreadListItem';-import { AiChatThreadsListFocusEffect } from '@/ai/components/AiChatThreadsListFocusEffect';-import { AiChatSkeletonLoader } from '@/ai/components/internal/AiChatSkeletonLoader';-import { AGENT_CHAT_THREAD_GROUP_BY } from '@/ai/constants/AgentChatThreadGroupBy';-import { AI_CHAT_THREADS_LIST_FOCUS_ID } from '@/ai/constants/AiChatThreadsListFocusId';-import { AI_CHAT_THREAD_ACTIONS_SURFACE } from '@/ai/constants/AiChatThreadActionsSurface';-import { useChatThreads } from '@/ai/hooks/useChatThreads';-import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';-import { agentChatThreadGroupByState } from '@/ai/states/agentChatThreadGroupByState';-import { groupThreadsByDate } from '@/ai/utils/groupThreadsByDate';-import { NavigationDrawerSectionTitle } from '@/ui/navigation/navigation-drawer/components/NavigationDrawerSectionTitle';-import { useHotkeysOnFocusedElement } from '@/ui/utilities/hotkey/hooks/useHotkeysOnFocusedElement';-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';-import { t } from '@lingui/core/macro';-import { Key } from 'ts-key-enum';-import { Button } from 'twenty-ui/input';-import { themeCssVariables } from 'twenty-ui/theme-constants';-import { getOsControlSymbol } from 'twenty-ui/utilities';--const StyledContainer = styled.div`- background: ${themeCssVariables.background.secondary};- border-right: 1px solid ${themeCssVariables.border.color.light};- display: flex;- flex-direction: column;- height: 100%;-`;--const StyledThreadsContainer = styled.div`- flex: 1;- overflow-y: auto;- padding: ${themeCssVariables.spacing[3]};-`;--const StyledFlatThreadList = styled.div`- display: flex;- flex-direction: column;- gap: ${themeCssVariables.spacing[1]};-`;--const StyledButtonsContainer = styled.div`- border-top: 1px solid ${themeCssVariables.border.color.medium};- display: flex;- justify-content: flex-end;- padding: ${themeCssVariables.spacing[2]} ${themeCssVariables.spacing[2]};-`;--export const AiChatThreadsList = () => {- const { switchToNewChat } = useSwitchToNewAiChat();-- useHotkeysOnFocusedElement({- keys: [`${Key.Control}+${Key.Enter}`, `${Key.Meta}+${Key.Enter}`],- callback: () => switchToNewChat(),- focusId: AI_CHAT_THREADS_LIST_FOCUS_ID,- dependencies: [switchToNewChat],- });-- const { threads, hasNextPage, loading, fetchMoreRef } = useChatThreads();- const agentChatThreadGroupBy = useAtomStateValue(agentChatThreadGroupByState);-- if (loading && threads.length === 0) {- return <AiChatSkeletonLoader />;- }-- const isGroupedByDate =- agentChatThreadGroupBy === AGENT_CHAT_THREAD_GROUP_BY.DATE;- const dateGroups = isGroupedByDate ? groupThreadsByDate(threads) : [];- const shouldRenderDateGroups = isGroupedByDate && dateGroups.length > 0;- const filterDropdown = (- <AiChatThreadFilterDropdown- surface={AI_CHAT_THREAD_ACTIONS_SURFACE.SIDE_PANEL}- />- );-- return (- <>- <AiChatThreadsListFocusEffect focusId={AI_CHAT_THREADS_LIST_FOCUS_ID} />- <StyledContainer>- <StyledThreadsContainer>- {shouldRenderDateGroups ? (- dateGroups.map((dateGroup, index) => (- <AiChatThreadGroup- key={dateGroup.id}- title={dateGroup.title}- threads={dateGroup.threads}- rightIcon={index === 0 ? filterDropdown : undefined}- alwaysShowRightIcon={index === 0}- />- ))- ) : (- <>- <NavigationDrawerSectionTitle- label={t`Recents`}- alwaysShowRightIcon- rightIcon={filterDropdown}- />- <StyledFlatThreadList>- {threads.map((thread) => (- <AiChatThreadListItem key={thread.id} thread={thread} />- ))}- </StyledFlatThreadList>- </>- )}- {hasNextPage ? (- <div ref={fetchMoreRef} style={{ minHeight: 1 }} />- ) : null}- </StyledThreadsContainer>- <StyledButtonsContainer>- <Button- variant="primary"- accent="blue"- size="medium"- title={t`New chat`}- onClick={() => switchToNewChat()}- hotkeys={[getOsControlSymbol(), '⏎']}- />- </StyledButtonsContainer>- </StyledContainer>- <AiChatThreadDeleteConfirmationModal- surface={AI_CHAT_THREAD_ACTIONS_SURFACE.SIDE_PANEL}- />- </>- );-};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadsListFocusEffect.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadsListFocusEffect.tsxdeleted file mode 100644index 480bb8c723b..00000000000--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadsListFocusEffect.tsx+++ /dev/null@@ -1,34 +0,0 @@-import { useEffect } from 'react';--import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';-import { useRemoveFocusItemFromFocusStackById } from '@/ui/utilities/focus/hooks/useRemoveFocusItemFromFocusStackById';-import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';--export const AiChatThreadsListFocusEffect = ({- focusId,-}: {- focusId: string;-}) => {- const { pushFocusItemToFocusStack } = usePushFocusItemToFocusStack();- const { removeFocusItemFromFocusStackById } =- useRemoveFocusItemFromFocusStackById();-- useEffect(() => {- pushFocusItemToFocusStack({- focusId,- component: {- type: FocusComponentType.SIDE_PANEL,- instanceId: focusId,- },- globalHotkeysConfig: {- enableGlobalHotkeysConflictingWithKeyboard: false,- },- });-- return () => {- removeFocusItemFromFocusStackById({ focusId });- };- }, [pushFocusItemToFocusStack, removeFocusItemFromFocusStackById, focusId]);-- return null;-};diff --git a/packages/twenty-front/src/modules/ai/components/ChatReferenceChipDisplay.tsx b/packages/twenty-front/src/modules/ai/components/ChatReferenceChipDisplay.tsxindex c6b120c069d..7f34d5355d3 100644--- a/packages/twenty-front/src/modules/ai/components/ChatReferenceChipDisplay.tsx+++ b/packages/twenty-front/src/modules/ai/components/ChatReferenceChipDisplay.tsx@@ -1,5 +1,5 @@import { t } from '@lingui/core/macro';-import { type ReactNode, useContext } from 'react';+import { type MouseEvent, type ReactNode, useContext } from 'react';import { isDefined } from 'twenty-shared/utils';import { Chip, ChipVariant, LinkChip } from 'twenty-ui/data-display';@@ -9,12 +9,14 @@ type ChatReferenceChipDisplayProps = {displayName: string;leftComponent: ReactNode;to?: string;+ onClick?: (event: MouseEvent<HTMLElement>) => void;};export const ChatReferenceChipDisplay = ({displayName,leftComponent,to,+ onClick,}: ChatReferenceChipDisplayProps) => {const isNavigationEnabled = useContext(ChatReferenceNavigationEnabledContext);@@ -35,6 +37,7 @@ export const ChatReferenceChipDisplay = ({label={displayName}emptyLabel={t`Untitled`}to={to}+ onClick={onClick}variant={ChipVariant.Highlighted}leftComponent={leftComponent}/>diff --git a/packages/twenty-front/src/modules/ai/components/ObjectMetadataLink.tsx b/packages/twenty-front/src/modules/ai/components/ObjectMetadataLink.tsxindex 88fd536e275..eb620d2f816 100644--- a/packages/twenty-front/src/modules/ai/components/ObjectMetadataLink.tsx+++ b/packages/twenty-front/src/modules/ai/components/ObjectMetadataLink.tsx@@ -1,10 +1,12 @@import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';+import { useChatTargetNavigation } from '@/ai/hooks/useChatTargetNavigation';import { ObjectMetadataIcon } from '@/object-metadata/components/ObjectMetadataIcon';import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';import { AppPath } from 'twenty-shared/types';import { getAppPath, isDefined } from 'twenty-shared/utils';import { useTheme } from 'twenty-ui/theme-constants';+import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';const PROPOSED_OBJECT_METADATA_ICON = 'IconListNumbers';@@ -18,6 +20,7 @@ export const ObjectMetadataLink = ({displayName,}: ObjectMetadataLinkProps) => {const theme = useTheme();+ const { openViewTarget } = useChatTargetNavigation();const objectMetadataItem = useAtomFamilySelectorValue(objectMetadataItemFamilySelector,@@ -27,6 +30,14 @@ export const ObjectMetadataLink = ({},);+ const handleOpenViewTarget = isDefined(objectMetadataItem)+ ? () => {+ openViewTarget({+ objectNameSingular: objectMetadataItem.nameSingular,+ });+ }+ : undefined;+return (<ChatReferenceChipDisplaydisplayName={displayName}@@ -37,6 +48,7 @@ export const ObjectMetadataLink = ({}): undefined}+ onClick={isCurrentPathAiChatPage() ? handleOpenViewTarget : undefined}leftComponent={<ObjectMetadataIconobjectMetadataItem={diff --git a/packages/twenty-front/src/modules/ai/components/RecordLink.tsx b/packages/twenty-front/src/modules/ai/components/RecordLink.tsxindex a732c515463..1a0f5224028 100644--- a/packages/twenty-front/src/modules/ai/components/RecordLink.tsx+++ b/packages/twenty-front/src/modules/ai/components/RecordLink.tsx@@ -1,9 +1,11 @@import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';+import { useChatTargetNavigation } from '@/ai/hooks/useChatTargetNavigation';import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';import { getLinkToShowPage } from '@/object-metadata/utils/getLinkToShowPage';import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';import { isNonEmptyString } from '@sniptt/guards';import { AvatarOrIcon } from 'twenty-ui/data-display';+import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';type RecordLinkProps = {objectNameSingular: string;@@ -24,14 +26,24 @@ export const RecordLink = ({},);+ const { openRecordTarget } = useChatTargetNavigation();+if (!objectMetadataItem || !isNonEmptyString(recordId)) {return <span>{displayName}</span>;}+ const handleOpenRecordTarget = () => {+ openRecordTarget({+ recordId,+ objectNameSingular,+ });+ };+return (<ChatReferenceChipDisplaydisplayName={displayName}to={getLinkToShowPage(objectNameSingular, { id: recordId })}+ onClick={isCurrentPathAiChatPage() ? handleOpenRecordTarget : undefined}leftComponent={<AvatarOrIconplaceholder={displayName}diff --git a/packages/twenty-front/src/modules/ai/components/ViewLink.tsx b/packages/twenty-front/src/modules/ai/components/ViewLink.tsxindex 1e7f1bf1e05..f318b4868d1 100644--- a/packages/twenty-front/src/modules/ai/components/ViewLink.tsx+++ b/packages/twenty-front/src/modules/ai/components/ViewLink.tsx@@ -1,4 +1,5 @@import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';+import { useChatTargetNavigation } from '@/ai/hooks/useChatTargetNavigation';import { objectMetadataItemsByIdMapSelector } from '@/object-metadata/states/objectMetadataItemsByIdMapSelector';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { useViewById } from '@/views/hooks/useViewById';@@ -6,6 +7,7 @@ import { AppPath } from 'twenty-shared/types';import { getAppPath, isDefined } from 'twenty-shared/utils';import { useIcons } from 'twenty-ui/icon';import { useTheme } from 'twenty-ui/theme-constants';+import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';type ViewLinkProps = {viewId: string;@@ -15,6 +17,7 @@ type ViewLinkProps = {export const ViewLink = ({ viewId, displayName }: ViewLinkProps) => {const theme = useTheme();const { getIcon } = useIcons();+ const { openViewTarget } = useChatTargetNavigation();const { view } = useViewById(viewId);const objectMetadataItemsByIdMap = useAtomStateValue(@@ -31,6 +34,13 @@ export const ViewLink = ({ viewId, displayName }: ViewLinkProps) => {const Icon = getIcon(view.icon);+ const handleOpenViewTarget = () => {+ openViewTarget({+ objectNameSingular: objectMetadataItem.nameSingular,+ viewId,+ });+ };+return (<ChatReferenceChipDisplaydisplayName={displayName}@@ -39,6 +49,7 @@ export const ViewLink = ({ viewId, displayName }: ViewLinkProps) => {{ objectNamePlural: objectMetadataItem.namePlural },{ viewId },)}+ onClick={isCurrentPathAiChatPage() ? handleOpenViewTarget : undefined}leftComponent={<Icon size={theme.icon.size.sm} stroke={theme.icon.stroke.sm} />}diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageCloseAskAiPanelEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageCloseAskAiPanelEffect.test.tsxnew file mode 100644index 00000000000..aa633201fcc--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageCloseAskAiPanelEffect.test.tsx@@ -0,0 +1,65 @@+import { render } from '@testing-library/react';+import { Provider as JotaiProvider } from 'jotai';+import { type ReactNode } from 'react';+import { SidePanelPages } from 'twenty-shared/types';++import { AiChatPageCloseAskAiPanelEffect } from '@/ai/components/AiChatPageCloseAskAiPanelEffect';+import { isSidePanelOpenedState } from '@/side-panel/states/isSidePanelOpenedState';+import { sidePanelPageState } from '@/side-panel/states/sidePanelPageState';+import {+ jotaiStore,+ resetJotaiStore,+} from '@/ui/utilities/state/jotai/jotaiStore';++const closeSidePanelMenuMock = jest.fn();++jest.mock('@/side-panel/hooks/useSidePanelMenu', () => ({+ useSidePanelMenu: () => ({ closeSidePanelMenu: closeSidePanelMenuMock }),+}));++const Wrapper = ({ children }: { children: ReactNode }) => (+ <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>+);++describe('AiChatPageCloseAskAiPanelEffect', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ resetJotaiStore();+ });++ it('should dismiss a panel chat the browser navigated back onto', () => {+ jotaiStore.set(isSidePanelOpenedState.atom, true);+ jotaiStore.set(sidePanelPageState.atom, SidePanelPages.AskAI);++ render(<AiChatPageCloseAskAiPanelEffect />, { wrapper: Wrapper });++ expect(closeSidePanelMenuMock).toHaveBeenCalled();+ });++ it('should leave an open artifact panel alone', () => {+ jotaiStore.set(isSidePanelOpenedState.atom, true);+ jotaiStore.set(sidePanelPageState.atom, SidePanelPages.ViewRecords);++ render(<AiChatPageCloseAskAiPanelEffect />, { wrapper: Wrapper });++ expect(closeSidePanelMenuMock).not.toHaveBeenCalled();+ });++ it('should do nothing when the panel is closed', () => {+ jotaiStore.set(isSidePanelOpenedState.atom, false);+ jotaiStore.set(sidePanelPageState.atom, SidePanelPages.AskAI);++ render(<AiChatPageCloseAskAiPanelEffect />, { wrapper: Wrapper });++ expect(closeSidePanelMenuMock).not.toHaveBeenCalled();+ });++ it('should not fight a panel chat opened after mount', () => {+ render(<AiChatPageCloseAskAiPanelEffect />, { wrapper: Wrapper });++ jotaiStore.set(isSidePanelOpenedState.atom, true);+ jotaiStore.set(sidePanelPageState.atom, SidePanelPages.AskAI);++ expect(closeSidePanelMenuMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageThreadUrlSyncEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageThreadUrlSyncEffect.test.tsxnew file mode 100644index 00000000000..d5f5f22fb06--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageThreadUrlSyncEffect.test.tsx@@ -0,0 +1,128 @@+import { act, render } from '@testing-library/react';+import { Provider as JotaiProvider } from 'jotai';+import { useEffect } from 'react';+import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';+import { AppPath } from 'twenty-shared/types';++import { AiChatPageThreadUrlSyncEffect } from '@/ai/components/AiChatPageThreadUrlSyncEffect';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import {+ jotaiStore,+ resetJotaiStore,+} from '@/ui/utilities/state/jotai/jotaiStore';++const switchThreadWithDraftMock = jest.fn((toThreadId: string) => {+ jotaiStore.set(currentAiChatThreadState.atom, toThreadId);+});++jest.mock('@/ai/hooks/useSwitchAgentChatThreadWithDraft', () => ({+ useSwitchAgentChatThreadWithDraft: () => ({+ switchThreadWithDraft: switchThreadWithDraftMock,+ }),+}));++const THREAD_A = '11111111-1111-4111-8111-111111111111';+const THREAD_B = '22222222-2222-4222-8222-222222222222';++let navigateToThread: ((threadId: string) => void) | undefined;++const RouteUnderTest = () => {+ const navigate = useNavigate();++ useEffect(() => {+ navigateToThread = (threadId: string) => navigate(`/chat/${threadId}`);+ }, [navigate]);++ return <AiChatPageThreadUrlSyncEffect />;+};++const renderEffectAt = (initialPath: string) =>+ render(+ <JotaiProvider store={jotaiStore}>+ <MemoryRouter initialEntries={[initialPath]}>+ <Routes>+ <Route+ path={AppPath.AiChat}+ element={<AiChatPageThreadUrlSyncEffect />}+ />+ </Routes>+ </MemoryRouter>+ </JotaiProvider>,+ );++describe('AiChatPageThreadUrlSyncEffect', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ resetJotaiStore();+ navigateToThread = undefined;+ });++ it('should adopt the thread from the URL on a deep link', () => {+ jotaiStore.set(currentAiChatThreadState.atom, null);++ renderEffectAt(`/chat/${THREAD_A}`);++ expect(switchThreadWithDraftMock).toHaveBeenCalledWith(THREAD_A);+ });++ it('should adopt the thread the browser navigated to', () => {+ jotaiStore.set(currentAiChatThreadState.atom, THREAD_A);++ render(+ <JotaiProvider store={jotaiStore}>+ <MemoryRouter initialEntries={[`/chat/${THREAD_A}`]}>+ <Routes>+ <Route path={AppPath.AiChat} element={<RouteUnderTest />} />+ </Routes>+ </MemoryRouter>+ </JotaiProvider>,+ );++ expect(switchThreadWithDraftMock).not.toHaveBeenCalled();++ act(() => {+ navigateToThread?.(THREAD_B);+ });++ expect(switchThreadWithDraftMock).toHaveBeenCalledWith(THREAD_B);+ });++ it('should do nothing when the URL already names the selected thread', () => {+ jotaiStore.set(currentAiChatThreadState.atom, THREAD_A);++ renderEffectAt(`/chat/${THREAD_A}`);++ expect(switchThreadWithDraftMock).not.toHaveBeenCalled();+ });++ it('should restore the url thread when a selection bypassed the projection', () => {+ jotaiStore.set(currentAiChatThreadState.atom, null);++ renderEffectAt(`/chat/${THREAD_A}`);++ switchThreadWithDraftMock.mockClear();++ act(() => {+ jotaiStore.set(currentAiChatThreadState.atom, THREAD_B);+ });++ expect(switchThreadWithDraftMock).toHaveBeenCalledWith(THREAD_A);+ });++ it('should ignore a malformed thread param and keep the selection', () => {+ jotaiStore.set(currentAiChatThreadState.atom, THREAD_B);++ renderEffectAt('/chat/not-a-thread-id');++ expect(switchThreadWithDraftMock).not.toHaveBeenCalled();+ expect(jotaiStore.get(currentAiChatThreadState.atom)).toBe(THREAD_B);+ });++ it('should leave a bare chat url alone', () => {+ jotaiStore.set(currentAiChatThreadState.atom, THREAD_A);++ renderEffectAt('/chat');++ expect(switchThreadWithDraftMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatThreadsList.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatThreadsList.test.tsxdeleted file mode 100644index e1c2471756a..00000000000--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatThreadsList.test.tsx+++ /dev/null@@ -1,98 +0,0 @@-import { fireEvent, render, screen, waitFor } from '@testing-library/react';-import { createStore, Provider as JotaiProvider } from 'jotai';-import { act } from 'react';-import { MemoryRouter } from 'react-router-dom';--import { AiChatThreadsList } from '@/ai/components/AiChatThreadsList';-import { AI_CHAT_THREADS_LIST_FOCUS_ID } from '@/ai/constants/AiChatThreadsListFocusId';-import { SIDE_PANEL_FOCUS_ID } from '@/side-panel/constants/SidePanelFocusId';-import { focusStackState } from '@/ui/utilities/focus/states/focusStackState';-import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';--const mockSwitchToNewChat = jest.fn();--jest.mock('@/ai/hooks/useSwitchToNewAiChat', () => ({- useSwitchToNewAiChat: () => ({- switchToNewChat: mockSwitchToNewChat,- }),-}));--jest.mock('@/ai/hooks/useChatThreads', () => ({- useChatThreads: () => ({- threads: [],- hasNextPage: false,- loading: false,- fetchMoreRef: jest.fn(),- }),-}));--jest.mock('@/ai/components/AiChatThreadFilterDropdown', () => ({- AiChatThreadFilterDropdown: () => null,-}));--jest.mock('@/ai/components/AiChatThreadDeleteConfirmationModal', () => ({- AiChatThreadDeleteConfirmationModal: () => null,-}));--describe('AiChatThreadsList', () => {- beforeEach(() => {- mockSwitchToNewChat.mockClear();- });-- it('keeps a distinct side panel focus for the new chat hotkey', async () => {- const store = createStore();-- store.set(focusStackState.atom, [- {- focusId: SIDE_PANEL_FOCUS_ID,- componentInstance: {- componentType: FocusComponentType.SIDE_PANEL,- componentInstanceId: SIDE_PANEL_FOCUS_ID,- },- globalHotkeysConfig: {- enableGlobalHotkeysWithModifiers: true,- enableGlobalHotkeysConflictingWithKeyboard: false,- },- },- ]);-- render(- <JotaiProvider store={store}>- <MemoryRouter>- <AiChatThreadsList />- </MemoryRouter>- </JotaiProvider>,- );-- expect(screen.getByText('New chat')).toBeInTheDocument();-- await waitFor(() => {- expect(store.get(focusStackState.atom).at(-1)?.focusId).toBe(- AI_CHAT_THREADS_LIST_FOCUS_ID,- );- });-- act(() => {- store.set(- focusStackState.atom,- store- .get(focusStackState.atom)- .filter((item) => item.focusId !== SIDE_PANEL_FOCUS_ID),- );- });-- expect(store.get(focusStackState.atom).at(-1)?.focusId).toBe(- AI_CHAT_THREADS_LIST_FOCUS_ID,- );-- act(() => {- fireEvent.keyDown(document, {- key: 'Enter',- code: 'Enter',- metaKey: true,- });- });-- expect(mockSwitchToNewChat).toHaveBeenCalledTimes(1);- });-});diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChipDisplay.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChipDisplay.test.tsxindex f52818945aa..0d7b1ef7f98 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChipDisplay.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/ChatReferenceChipDisplay.test.tsx@@ -1,9 +1,15 @@-import { render, screen } from '@testing-library/react';-import { MemoryRouter } from 'react-router-dom';+import { fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter, useLocation } from 'react-router-dom';import { ChatReferenceChipDisplay } from '@/ai/components/ChatReferenceChipDisplay';import { ChatReferenceNavigationEnabledContext } from '@/ai/contexts/ChatReferenceNavigationEnabledContext';+const LocationProbe = () => {+ const location = useLocation();++ return <div data-testid="location-probe">{location.pathname}</div>;+};+const renderChip = ({isNavigationEnabled,}: {@@ -48,4 +54,31 @@ describe('ChatReferenceChipDisplay', () => {expect(chipClassName).not.toMatch(/cursorPointer/);expect(chipClassName).toMatch(/backgroundStatic/);});++ it('should run onClick on a plain click instead of navigating to `to`', () => {+ const onClickMock = jest.fn();++ render(+ <MemoryRouter initialEntries={['/chat/thread-id']}>+ <ChatReferenceNavigationEnabledContext.Provider value={true}>+ <ChatReferenceChipDisplay+ displayName="Acme"+ leftComponent={null}+ to="/objects/companies/acme-id"+ onClick={onClickMock}+ />+ </ChatReferenceNavigationEnabledContext.Provider>+ <LocationProbe />+ </MemoryRouter>,+ );++ const link = screen.getByRole('link');+ fireEvent.mouseDown(link);+ fireEvent.click(link);++ expect(onClickMock).toHaveBeenCalledTimes(1);+ expect(screen.getByTestId('location-probe')).toHaveTextContent(+ '/chat/thread-id',+ );+ });});diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/ViewLink.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/ViewLink.test.tsxindex 1ef439254b0..c46f5a23d1d 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/ViewLink.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/ViewLink.test.tsx@@ -1,4 +1,4 @@-import { render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';import { MemoryRouter } from 'react-router-dom';import { ViewLink } from '@/ai/components/ViewLink';@@ -7,6 +7,14 @@ import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetaimport { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';import { setTestViewsInMetadataStore } from '~/testing/utils/setTestViewsInMetadataStore';+const openViewTargetMock = jest.fn();++jest.mock('@/ai/hooks/useChatTargetNavigation', () => ({+ useChatTargetNavigation: () => ({+ openViewTarget: openViewTargetMock,+ }),+}));+const companyObjectMetadataItem = getMockObjectMetadataItemOrThrow('company');const VIEW_ID = '44444444-4444-4444-4444-444444444444';@@ -43,6 +51,44 @@ const renderViewLink = ({};describe('ViewLink', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ window.history.pushState({}, '', '/objects/companies');+ });++ it('should open the view as an artifact on a plain click on the chat page', () => {+ window.history.pushState({}, '', '/chat');++ renderViewLink({+ viewId: VIEW_ID,+ displayName: 'All Companies',+ views: [allCompaniesView],+ });++ const link = screen.getByText('All Companies').closest('a') as HTMLElement;+ fireEvent.mouseDown(link);+ fireEvent.click(link);++ expect(openViewTargetMock).toHaveBeenCalledWith({+ objectNameSingular: companyObjectMetadataItem.nameSingular,+ viewId: VIEW_ID,+ });+ });++ it('should not open an artifact on click outside the chat page', () => {+ renderViewLink({+ viewId: VIEW_ID,+ displayName: 'All Companies',+ views: [allCompaniesView],+ });++ const link = screen.getByText('All Companies').closest('a') as HTMLElement;+ fireEvent.mouseDown(link);+ fireEvent.click(link);++ expect(openViewTargetMock).not.toHaveBeenCalled();+ });+it('should link a view to its object index page', () => {renderViewLink({viewId: VIEW_ID,diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatThreadsListFocusId.ts b/packages/twenty-front/src/modules/ai/constants/AiChatThreadsListFocusId.tsdeleted file mode 100644index 04dbd082cda..00000000000--- a/packages/twenty-front/src/modules/ai/constants/AiChatThreadsListFocusId.ts+++ /dev/null@@ -1 +0,0 @@-export const AI_CHAT_THREADS_LIST_FOCUS_ID = 'ai-chat-threads-list';diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatModelId.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatModelId.test.tsxindex 335ff7da990..4dcc0b9bd67 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatModelId.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatModelId.test.tsx@@ -2,11 +2,13 @@ import { act, renderHook } from '@testing-library/react';import { Provider as JotaiProvider } from 'jotai';import { MemoryRouter } from 'react-router-dom';import { AppPath } from 'twenty-shared/types';+import { getAppPath } from 'twenty-shared/utils';import { useAgentChatModelId } from '@/ai/hooks/useAgentChatModelId';import { agentChatUserSelectedModelState } from '@/ai/states/agentChatUserSelectedModelState';import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { aiModelsState } from '@/client-config/states/aiModelsState';+import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import {jotaiStore,@@ -62,26 +64,39 @@ const renderHooks = ({return result;};+const onboardingChatPath = getAppPath(AppPath.AiChat, { threadId: null });+describe('useAgentChatModelId', () => {beforeEach(() => {+ sessionStorage.clear();resetJotaiStore();});- it('should request the workspace fast model on the workspace setup page', () => {- const result = renderHooks({ pathname: AppPath.WorkspaceSetup });+ it('should request the workspace fast model during the onboarding chat', () => {+ jotaiStore.set(shouldOpenAiChatAfterOnboardingState.atom, true);++ const result = renderHooks({ pathname: onboardingChatPath });expect(result.current.modelIdForRequest).toBe('openai/gpt-5-mini');});+ it('should request no model on a plain chat page', () => {+ const result = renderHooks({ pathname: onboardingChatPath });++ expect(result.current.modelIdForRequest).toBeUndefined();+ });+it('should request no model elsewhere so the server falls back to the smart model', () => {const result = renderHooks({ pathname: '/objects/companies' });expect(result.current.modelIdForRequest).toBeUndefined();});- it('should let a user selected model win on the workspace setup page', () => {+ it('should let a user selected model win during the onboarding chat', () => {+ jotaiStore.set(shouldOpenAiChatAfterOnboardingState.atom, true);+const result = renderHooks({- pathname: AppPath.WorkspaceSetup,+ pathname: onboardingChatPath,userSelectedModel: 'openai/gpt-4.1',});diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiModelOptions.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiModelOptions.test.tsxindex 36682624475..8b2c9948ec6 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiModelOptions.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiModelOptions.test.tsx@@ -2,10 +2,12 @@ import { act, renderHook } from '@testing-library/react';import { Provider as JotaiProvider } from 'jotai';import { MemoryRouter } from 'react-router-dom';import { AppPath } from 'twenty-shared/types';+import { getAppPath } from 'twenty-shared/utils';import { useAiModelOptions } from '@/ai/hooks/useAiModelOptions';import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { aiModelsState } from '@/client-config/states/aiModelsState';+import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import {jotaiStore,@@ -60,15 +62,24 @@ const renderHooks = (pathname: string) => {describe('useAiModelOptions', () => {beforeEach(() => {+ sessionStorage.clear();resetJotaiStore();});- it('should pin the workspace fast model on the workspace setup page', () => {- const result = renderHooks(AppPath.WorkspaceSetup);+ it('should pin the workspace fast model during the onboarding chat', () => {+ jotaiStore.set(shouldOpenAiChatAfterOnboardingState.atom, true);++ const result = renderHooks(getAppPath(AppPath.AiChat, { threadId: null }));expect(result.current.pinnedOption?.label).toBe('GPT-5.6 Luna');});+ it('should pin the workspace smart model on a plain chat page', () => {+ const result = renderHooks(getAppPath(AppPath.AiChat, { threadId: null }));++ expect(result.current.pinnedOption?.label).toBe('GPT-5.2');+ });+it('should pin the workspace smart model elsewhere', () => {const result = renderHooks('/objects/companies');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.tsxnew file mode 100644index 00000000000..bdfbad9452c--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useProjectAiChatThreadToUrl.test.tsx@@ -0,0 +1,110 @@+import { act, renderHook } from '@testing-library/react';+import { AppPath } from 'twenty-shared/types';++import { useProjectAiChatThreadToUrl } from '@/ai/hooks/useProjectAiChatThreadToUrl';+import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';++const navigateAppMock = jest.fn();++jest.mock('~/hooks/useNavigateApp', () => ({+ useNavigateApp: () => navigateAppMock,+}));++const THREAD_A = '11111111-1111-4111-8111-111111111111';++describe('useProjectAiChatThreadToUrl', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ window.history.pushState(null, '', '/');+ });++ it('should write the selected thread into the chat url', () => {+ window.history.pushState(null, '', '/chat');++ const { result } = renderHook(() => useProjectAiChatThreadToUrl());++ act(() => {+ result.current.projectAiChatThreadToUrl(THREAD_A);+ });++ expect(navigateAppMock).toHaveBeenCalledWith(+ AppPath.AiChat,+ { threadId: THREAD_A },+ undefined,+ { replace: true, state: null },+ );+ });++ it('should clear the url param for a draft thread', () => {+ window.history.pushState(null, '', `/chat/${THREAD_A}`);++ const { result } = renderHook(() => useProjectAiChatThreadToUrl());++ act(() => {+ result.current.projectAiChatThreadToUrl(AGENT_CHAT_NEW_THREAD_DRAFT_KEY);+ });++ expect(navigateAppMock).toHaveBeenCalledWith(+ AppPath.AiChat,+ { threadId: null },+ undefined,+ { replace: true, state: null },+ );+ });++ it('should carry the history entry state forward', () => {+ window.history.pushState(+ { usr: { returnLocation: '/objects/people' } },+ '',+ '/chat',+ );++ const { result } = renderHook(() => useProjectAiChatThreadToUrl());++ act(() => {+ result.current.projectAiChatThreadToUrl(THREAD_A);+ });++ expect(navigateAppMock).toHaveBeenCalledWith(+ AppPath.AiChat,+ { threadId: THREAD_A },+ undefined,+ { replace: true, state: { returnLocation: '/objects/people' } },+ );+ });++ it('should read the entry state as it is when called, not when rendered', () => {+ window.history.pushState(null, '', '/chat');++ const { result } = renderHook(() => useProjectAiChatThreadToUrl());++ window.history.pushState(+ { usr: { returnLocation: '/objects/companies' } },+ '',+ '/chat',+ );++ act(() => {+ result.current.projectAiChatThreadToUrl(THREAD_A);+ });++ expect(navigateAppMock).toHaveBeenCalledWith(+ AppPath.AiChat,+ { threadId: THREAD_A },+ undefined,+ { replace: true, state: { returnLocation: '/objects/companies' } },+ );+ });++ it('should leave the url alone outside the chat page', () => {+ window.history.pushState(null, '', '/objects/companies');++ const { result } = renderHook(() => useProjectAiChatThreadToUrl());++ act(() => {+ result.current.projectAiChatThreadToUrl(THREAD_A);+ });++ expect(navigateAppMock).not.toHaveBeenCalled();+ });+});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.tsxindex 21db51822cd..a16a51a7f69 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@@ -3,7 +3,6 @@ import { Provider as JotaiProvider } from 'jotai';import { type ReactNode } from 'react';import { useReturnFromExpandedAiChat } from '@/ai/hooks/useReturnFromExpandedAiChat';-import { aiChatExpandedReturnLocationState } from '@/ai/states/aiChatExpandedReturnLocationState';import { shouldContinueAiChatInSidePanelState } from '@/ai/states/shouldContinueAiChatInSidePanelState';import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';import {@@ -13,8 +12,11 @@ import {const navigateMock = jest.fn();+let locationState: unknown = null;+jest.mock('react-router-dom', () => ({useNavigate: () => navigateMock,+ useLocation: () => ({ state: locationState }),}));const defaultHomePagePath = '/objects/companies';@@ -23,12 +25,6 @@ jest.mock('@/navigation/hooks/useDefaultHomePagePath', () => ({useDefaultHomePagePath: () => ({ defaultHomePagePath }),}));-const openAskAiPageMock = jest.fn();--jest.mock('@/side-panel/hooks/useOpenAskAiPageInSidePanel', () => ({- useOpenAskAiPageInSidePanel: () => ({ openAskAiPage: openAskAiPageMock }),-}));-const closeSidePanelMenuMock = jest.fn();jest.mock('@/side-panel/hooks/useSidePanelMenu', () => ({@@ -44,11 +40,12 @@ describe('useReturnFromExpandedAiChat', () => {jest.clearAllMocks();sessionStorage.clear();resetJotaiStore();+ locationState = null;});- it('should reopen the side panel and keep the side panel continuation when collapsing', () => {+ it('should navigate to the return location carried by the history entry when collapsing', () => {jotaiStore.set(shouldContinueAiChatInSidePanelState.atom, true);- jotaiStore.set(aiChatExpandedReturnLocationState.atom, '/objects/people');+ locationState = { returnLocation: '/objects/people' };const { result } = renderHook(() => useReturnFromExpandedAiChat({ reopenSidePanel: true }),@@ -59,22 +56,29 @@ describe('useReturnFromExpandedAiChat', () => {result.current();});- expect(openAskAiPageMock).toHaveBeenCalledWith({- resetNavigationStack: true,- });- expect(closeSidePanelMenuMock).not.toHaveBeenCalled();expect(navigateMock).toHaveBeenCalledWith('/objects/people');+ expect(closeSidePanelMenuMock).not.toHaveBeenCalled();expect(jotaiStore.get(shouldContinueAiChatInSidePanelState.atom)).toBe(true,);- expect(jotaiStore.get(aiChatExpandedReturnLocationState.atom)).toBeNull();- expect(jotaiStore.get(shouldOpenAiChatAfterOnboardingState.atom)).toBe(- false,+ });++ it('should navigate home when the history entry has no return location', () => {+ const { result } = renderHook(+ () => useReturnFromExpandedAiChat({ reopenSidePanel: true }),+ { wrapper: Wrapper },);++ act(() => {+ result.current();+ });++ expect(navigateMock).toHaveBeenCalledWith(defaultHomePagePath);});it('should cancel the side panel continuation when closing', () => {jotaiStore.set(shouldContinueAiChatInSidePanelState.atom, true);+ jotaiStore.set(shouldOpenAiChatAfterOnboardingState.atom, true);const { result } = renderHook(() => useReturnFromExpandedAiChat({ reopenSidePanel: false }),@@ -85,11 +89,13 @@ describe('useReturnFromExpandedAiChat', () => {result.current();});- expect(openAskAiPageMock).not.toHaveBeenCalled();- expect(closeSidePanelMenuMock).toHaveBeenCalled();- expect(navigateMock).toHaveBeenCalledWith(defaultHomePagePath);expect(jotaiStore.get(shouldContinueAiChatInSidePanelState.atom)).toBe(false,);+ expect(jotaiStore.get(shouldOpenAiChatAfterOnboardingState.atom)).toBe(+ false,+ );+ expect(closeSidePanelMenuMock).toHaveBeenCalled();+ expect(navigateMock).toHaveBeenCalledWith(defaultHomePagePath);});});diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.tsindex 157f63f15f8..7f4f5851e86 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChat.ts@@ -20,6 +20,7 @@ import { SEND_CHAT_MESSAGE } from '@/ai/graphql/mutations/sendChatMessage';import { STOP_AGENT_CHAT_STREAM } from '@/ai/graphql/mutations/stopAgentChatStream';import { useAgentChatModelId } from '@/ai/hooks/useAgentChatModelId';import { useGetBrowsingContext } from '@/ai/hooks/useBrowsingContext';+import { useProjectAiChatThreadToUrl } from '@/ai/hooks/useProjectAiChatThreadToUrl';import { useOptimisticallyUnarchiveOnSend } from '@/ai/hooks/useOptimisticallyUnarchiveOnSend';import { useWorkspaceAiModelAvailability } from '@/ai/hooks/useWorkspaceAiModelAvailability';import {@@ -50,6 +51,7 @@ export const useAgentChat = (const apolloClient = useApolloClient();const { enqueueErrorSnackBar } = useSnackBar();const setCurrentAiChatThread = useSetAtomState(currentAiChatThreadState);+ const { projectAiChatThreadToUrl } = useProjectAiChatThreadToUrl();const store = useStore();const setAgentChatUploadedFiles = useSetAtomState(@@ -99,6 +101,7 @@ export const useAgentChat = (if (draftKey === AGENT_CHAT_NEW_THREAD_DRAFT_KEY) {setCurrentAiChatThread(threadId);+ projectAiChatThreadToUrl(threadId);}setAgentChatInput('');diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.tsindex 6bb16e0defe..46ff82f1f8e 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts@@ -1,13 +1,14 @@import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';import { currentAiChatThreadTitleComponentFamilyState } from '@/ai/states/currentAiChatThreadTitleComponentFamilyState';import { threadIdCreatedFromDraftState } from '@/ai/states/threadIdCreatedFromDraftState';-import { useSwitchAgentChatThreadWithDraft } from '@/ai/hooks/useSwitchAgentChatThreadWithDraft';+import { useSelectAiChatThread } from '@/ai/hooks/useSelectAiChatThread';import { useOpenAskAiPageInSidePanel } from '@/side-panel/hooks/useOpenAskAiPageInSidePanel';import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { useStore } from 'jotai';import { isDefined } from 'twenty-shared/utils';import { type AgentChatThread } from '~/generated-metadata/graphql';+import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';export type UseAiChatThreadClickOptions = {resetNavigationStack?: boolean;@@ -20,7 +21,7 @@ export const useAiChatThreadClick = (const setThreadIdCreatedFromDraft = useSetAtomState(threadIdCreatedFromDraftState,);- const { switchThreadWithDraft } = useSwitchAgentChatThreadWithDraft();+ const { selectAiChatThread } = useSelectAiChatThread();const threadTitleFamilyCallback = useAtomComponentFamilyStateCallbackState(currentAiChatThreadTitleComponentFamilyState,);@@ -33,7 +34,7 @@ export const useAiChatThreadClick = (const handleThreadClick = (thread: AgentChatThread) => {setThreadIdCreatedFromDraft(null);- switchThreadWithDraft(thread.id);+ selectAiChatThread(thread.id);const clickedFamilyKey = { threadId: thread.id };@@ -60,6 +61,10 @@ export const useAiChatThreadClick = (: null,);+ if (isCurrentPathAiChatPage()) {+ return;+ }+openAskAiPage({resetNavigationStack,});diff --git a/packages/twenty-front/src/modules/ai/hooks/useBrowsingContext.ts b/packages/twenty-front/src/modules/ai/hooks/useBrowsingContext.tsindex f314df91e64..efb984d58ec 100644--- a/packages/twenty-front/src/modules/ai/hooks/useBrowsingContext.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useBrowsingContext.ts@@ -4,6 +4,9 @@ import { isDefined } from 'twenty-shared/utils';import { type BrowsingContext } from '@/ai/types/BrowsingContext';import { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainContextStoreInstanceId';+import { isSidePanelOpenedState } from '@/side-panel/states/isSidePanelOpenedState';+import { sidePanelNavigationStackState } from '@/side-panel/states/sidePanelNavigationStackState';+import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';import { contextStoreCurrentObjectMetadataItemIdComponentState } from '@/context-store/states/contextStoreCurrentObjectMetadataItemIdComponentState';import { contextStoreCurrentViewIdComponentState } from '@/context-store/states/contextStoreCurrentViewIdComponentState';import { contextStoreCurrentPageTypeComponentState } from '@/context-store/states/contextStoreCurrentPageTypeComponentState';@@ -23,7 +26,17 @@ export const useGetBrowsingContext = () => {const store = useStore();const getBrowsingContext = useCallback((): BrowsingContext | null => {- const instanceId = MAIN_CONTEXT_STORE_INSTANCE_ID;+ const isSidePanelOpened = store.get(isSidePanelOpenedState.atom);+ const currentSidePanelPage = store+ .get(sidePanelNavigationStackState.atom)+ .at(-1);++ const instanceId =+ isCurrentPathAiChatPage() &&+ isSidePanelOpened &&+ isDefined(currentSidePanelPage)+ ? currentSidePanelPage.pageId+ : MAIN_CONTEXT_STORE_INSTANCE_ID;const pageType = store.get(contextStoreCurrentPageTypeComponentState.atomFamily({diff --git a/packages/twenty-front/src/modules/ai/hooks/useChatTargetNavigation.ts b/packages/twenty-front/src/modules/ai/hooks/useChatTargetNavigation.tsnew file mode 100644index 00000000000..db5a2a02ed1--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useChatTargetNavigation.ts@@ -0,0 +1,81 @@+import { useStore } from 'jotai';+import { AppPath } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';+import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';+import { useOpenRecordsInSidePanel } from '@/side-panel/hooks/useOpenRecordsInSidePanel';+import { useOpenRecordInSidePanel } from '@/side-panel/hooks/useOpenRecordInSidePanel';+import { useNavigateApp } from '~/hooks/useNavigateApp';+import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';++export const useChatTargetNavigation = () => {+ const store = useStore();+ const navigateApp = useNavigateApp();+ const { openRecordInSidePanel } = useOpenRecordInSidePanel();+ const { openRecordsInSidePanel } = useOpenRecordsInSidePanel();++ const isArtifactSurface = () =>+ isCurrentPathAiChatPage() &&+ !store.get(shouldOpenAiChatAfterOnboardingState.atom);++ const openRecordTarget = ({+ recordId,+ objectNameSingular,+ }: {+ recordId: string;+ objectNameSingular: string;+ }) => {+ if (isArtifactSurface()) {+ openRecordInSidePanel({+ recordId,+ objectNameSingular,+ });++ return;+ }++ navigateApp(AppPath.RecordShowPage, {+ objectNameSingular,+ objectRecordId: recordId,+ });+ };++ const openViewTarget = ({+ objectNameSingular,+ viewId,+ }: {+ objectNameSingular: string;+ viewId?: string;+ }) => {+ if (isArtifactSurface()) {+ openRecordsInSidePanel({+ objectNameSingular,+ viewId,+ });++ return;+ }++ const objectMetadataItem = store.get(+ objectMetadataItemFamilySelector.selectorFamily({+ objectName: objectNameSingular,+ objectNameType: 'singular',+ }),+ );++ if (!isDefined(objectMetadataItem)) {+ throw new Error(+ `Object with singular name ${objectNameSingular} not found.`,+ );+ }++ navigateApp(+ AppPath.RecordIndexPage,+ { objectNamePlural: objectMetadataItem.namePlural },+ isDefined(viewId) ? { viewId } : undefined,+ );+ };++ return { openRecordTarget, openViewTarget };+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts b/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.tsindex 9f17ec0b027..019d3847036 100644--- a/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts@@ -1,5 +1,6 @@import { useStore } from 'jotai';+import { useProjectAiChatThreadToUrl } from '@/ai/hooks/useProjectAiChatThreadToUrl';import {AGENT_CHAT_NEW_THREAD_DRAFT_KEY,agentChatDraftsByThreadIdState,@@ -27,6 +28,7 @@ export const useCreateAgentChatThread = () => {const setAgentChatDraftsByThreadId = useSetAtomState(agentChatDraftsByThreadIdState,);+ const { projectAiChatThreadToUrl } = useProjectAiChatThreadToUrl();const store = useStore();const { addToDraft, applyChanges } = useUpdateMetadataStoreDraft();@@ -76,6 +78,7 @@ export const useCreateAgentChatThread = () => {}setCurrentAiChatThread(newThreadId);+ projectAiChatThreadToUrl(newThreadId);setAgentChatInput(tipTapDocumentToMarkdown(newDraft));},onError: () => {diff --git a/packages/twenty-front/src/modules/ai/hooks/useDeleteChatThread.ts b/packages/twenty-front/src/modules/ai/hooks/useDeleteChatThread.tsindex e6f35a4f5c7..43bbdd06f98 100644--- a/packages/twenty-front/src/modules/ai/hooks/useDeleteChatThread.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useDeleteChatThread.ts@@ -6,6 +6,7 @@ import {AGENT_CHAT_NEW_THREAD_DRAFT_KEY,agentChatDraftsByThreadIdState,} from '@/ai/states/agentChatDraftsByThreadIdState';+import { useProjectAiChatThreadToUrl } from '@/ai/hooks/useProjectAiChatThreadToUrl';import { agentChatInputState } from '@/ai/states/agentChatInputState';import { agentChatVisibleThreadsSelector } from '@/ai/states/selectors/agentChatVisibleThreadsSelector';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';@@ -21,6 +22,7 @@ export const useDeleteChatThread = () => {const { enqueueErrorSnackBar } = useSnackBar();const setCurrentAiChatThread = useSetAtomState(currentAiChatThreadState);const setAgentChatInput = useSetAtomState(agentChatInputState);+ const { projectAiChatThreadToUrl } = useProjectAiChatThreadToUrl();const store = useStore();const [deleteMutation] = useMutation(DeleteChatThreadDocument);@@ -49,11 +51,13 @@ export const useDeleteChatThread = () => {const nextThreadId = remaining[0].id;setCurrentAiChatThread(nextThreadId);+ projectAiChatThreadToUrl(nextThreadId);setAgentChatInput(tipTapDocumentToMarkdown(draftsByThreadId[nextThreadId] ?? ''),);} else {setCurrentAiChatThread(AGENT_CHAT_NEW_THREAD_DRAFT_KEY);+ projectAiChatThreadToUrl(AGENT_CHAT_NEW_THREAD_DRAFT_KEY);setAgentChatInput(tipTapDocumentToMarkdown(draftsByThreadId[AGENT_CHAT_NEW_THREAD_DRAFT_KEY] ?? '',diff --git a/packages/twenty-front/src/modules/ai/hooks/useIsWorkspaceSetupChat.ts b/packages/twenty-front/src/modules/ai/hooks/useIsWorkspaceSetupChat.tsindex ac765387227..073a4c7c122 100644--- a/packages/twenty-front/src/modules/ai/hooks/useIsWorkspaceSetupChat.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useIsWorkspaceSetupChat.ts@@ -1,8 +1,14 @@import { useLocation } from 'react-router-dom';-import { AppPath } from 'twenty-shared/types';++import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { isAiChatPath } from '~/utils/isAiChatPath';export const useIsWorkspaceSetupChat = () => {const { pathname } = useLocation();+ const shouldOpenAiChatAfterOnboarding = useAtomStateValue(+ shouldOpenAiChatAfterOnboardingState,+ );- return pathname === AppPath.WorkspaceSetup;+ return shouldOpenAiChatAfterOnboarding && isAiChatPath(pathname);};diff --git a/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiThread.ts b/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiThread.tsindex e935cdb5f72..02ac10c5852 100644--- a/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiThread.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiThread.ts@@ -1,5 +1,5 @@import { useAiChatThreadClick } from '@/ai/hooks/useAiChatThreadClick';-import { useSwitchAgentChatThreadWithDraft } from '@/ai/hooks/useSwitchAgentChatThreadWithDraft';+import { useSelectAiChatThread } from '@/ai/hooks/useSelectAiChatThread';import { agentChatVisibleThreadsSelector } from '@/ai/states/selectors/agentChatVisibleThreadsSelector';import { useOpenAskAiPageInSidePanel } from '@/side-panel/hooks/useOpenAskAiPageInSidePanel';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';@@ -9,7 +9,7 @@ export const useOpenAskAiThread = () => {const agentChatVisibleThreads = useAtomStateValue(agentChatVisibleThreadsSelector,);- const { switchThreadWithDraft } = useSwitchAgentChatThreadWithDraft();+ const { selectAiChatThread } = useSelectAiChatThread();const { handleThreadClick } = useAiChatThreadClick({resetNavigationStack: true,@@ -27,7 +27,7 @@ export const useOpenAskAiThread = () => {}if (isValidUuid(threadId)) {- switchThreadWithDraft(threadId);+ selectAiChatThread(threadId);}openAskAiPage({ resetNavigationStack: true });diff --git a/packages/twenty-front/src/modules/ai/hooks/useProcessUIToolCallMessage.ts b/packages/twenty-front/src/modules/ai/hooks/useProcessUIToolCallMessage.tsindex 403945c7cfe..60425185ce4 100644--- a/packages/twenty-front/src/modules/ai/hooks/useProcessUIToolCallMessage.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useProcessUIToolCallMessage.ts@@ -1,19 +1,15 @@+import { useChatTargetNavigation } from '@/ai/hooks/useChatTargetNavigation';import { processedToolExecutionPartIdsComponentState } from '@/ai/states/processedToolExecutionPartIdsComponentState';import { extractUIToolCallParts } from '@/ai/utils/extractUIToolCallParts';-import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';import { useAtomComponentStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateCallbackState';import { useStore } from 'jotai';import { type ExtendedUIMessage } from 'twenty-shared/ai';-import { AppPath } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';-import { useNavigateApp } from '~/hooks/useNavigateApp';import { sleep } from '~/utils/sleep';export const useProcessUIToolCallMessage = () => {- const navigateApp = useNavigateApp();-- const { objectMetadataItems } = useObjectMetadataItems();+ const { openRecordTarget, openViewTarget } = useChatTargetNavigation();const processedToolExecutionPartIdsCallbackState =useAtomComponentStateCallbackState(@@ -59,48 +55,25 @@ export const useProcessUIToolCallMessage = () => {switch (navigateAppOutput.action) {case 'navigateToObject': {- const objectNamePlural = objectMetadataItems.find(- (item) =>- item.nameSingular === navigateAppOutput.objectNameSingular,- )?.namePlural;-- if (!isDefined(objectNamePlural)) {- throw new Error(- `Object with singular name ${navigateAppOutput.objectNameSingular} not found, cannot navigate to object page from chat.`,- );- }-- navigateApp(AppPath.RecordIndexPage, {- objectNamePlural: objectNamePlural,+ openViewTarget({+ objectNameSingular: navigateAppOutput.objectNameSingular,});break;}case 'navigateToRecord': {- navigateApp(AppPath.RecordShowPage, {+ openRecordTarget({+ recordId: navigateAppOutput.recordId,objectNameSingular: navigateAppOutput.objectNameSingular,- objectRecordId: navigateAppOutput.recordId,});break;}case 'navigateToView': {- const viewObjectNamePlural = objectMetadataItems.find(- (item) =>- item.nameSingular === navigateAppOutput.objectNameSingular,- )?.namePlural;-- if (!isDefined(viewObjectNamePlural)) {- throw new Error(- `Object with singular name ${navigateAppOutput.objectNameSingular} not found, cannot navigate to view from chat.`,- );- }-- navigateApp(- AppPath.RecordIndexPage,- { objectNamePlural: viewObjectNamePlural },- { viewId: navigateAppOutput.viewId },- );+ openViewTarget({+ objectNameSingular: navigateAppOutput.objectNameSingular,+ viewId: navigateAppOutput.viewId,+ });break;}diff --git a/packages/twenty-front/src/modules/ai/hooks/useProjectAiChatThreadToUrl.ts b/packages/twenty-front/src/modules/ai/hooks/useProjectAiChatThreadToUrl.tsnew file mode 100644index 00000000000..591be44df90--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useProjectAiChatThreadToUrl.ts@@ -0,0 +1,25 @@+import { AppPath } from 'twenty-shared/types';+import { isValidUuid } from 'twenty-shared/utils';++import { useNavigateApp } from '~/hooks/useNavigateApp';+import { getCurrentHistoryEntryState } from '~/utils/getCurrentHistoryEntryState';+import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';++export const useProjectAiChatThreadToUrl = () => {+ const navigateApp = useNavigateApp();++ const projectAiChatThreadToUrl = (threadId: string) => {+ if (!isCurrentPathAiChatPage()) {+ return;+ }++ navigateApp(+ AppPath.AiChat,+ { threadId: isValidUuid(threadId) ? threadId : null },+ undefined,+ { replace: true, state: getCurrentHistoryEntryState() },+ );+ };++ return { projectAiChatThreadToUrl };+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useReturnFromExpandedAiChat.ts b/packages/twenty-front/src/modules/ai/hooks/useReturnFromExpandedAiChat.tsindex 313ee50e9bb..7320d85823c 100644--- a/packages/twenty-front/src/modules/ai/hooks/useReturnFromExpandedAiChat.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useReturnFromExpandedAiChat.ts@@ -1,12 +1,11 @@import { useStore } from 'jotai';import { useCallback } from 'react';-import { useNavigate } from 'react-router-dom';+import { useLocation, useNavigate } from 'react-router-dom';-import { aiChatExpandedReturnLocationState } from '@/ai/states/aiChatExpandedReturnLocationState';import { shouldContinueAiChatInSidePanelState } from '@/ai/states/shouldContinueAiChatInSidePanelState';+import { getExpandedAiChatReturnLocation } from '@/ai/utils/getExpandedAiChatReturnLocation';import { useDefaultHomePagePath } from '@/navigation/hooks/useDefaultHomePagePath';import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';-import { useOpenAskAiPageInSidePanel } from '@/side-panel/hooks/useOpenAskAiPageInSidePanel';import { useSidePanelMenu } from '@/side-panel/hooks/useSidePanelMenu';type UseReturnFromExpandedAiChatParams = {@@ -18,29 +17,26 @@ export const useReturnFromExpandedAiChat = ({}: UseReturnFromExpandedAiChatParams) => {const store = useStore();const navigate = useNavigate();+ const location = useLocation();const { defaultHomePagePath } = useDefaultHomePagePath();- const { openAskAiPage } = useOpenAskAiPageInSidePanel();const { closeSidePanelMenu } = useSidePanelMenu();+ const returnLocation = getExpandedAiChatReturnLocation(location.state);+return useCallback(() => {- if (reopenSidePanel) {- openAskAiPage({ resetNavigationStack: true });- } else {+ if (!reopenSidePanel) {store.set(shouldContinueAiChatInSidePanelState.atom, false);+ store.set(shouldOpenAiChatAfterOnboardingState.atom, false);void closeSidePanelMenu();}- const returnLocation = store.get(aiChatExpandedReturnLocationState.atom);navigate(returnLocation ?? defaultHomePagePath);-- store.set(aiChatExpandedReturnLocationState.atom, null);- store.set(shouldOpenAiChatAfterOnboardingState.atom, false);}, [reopenSidePanel,- openAskAiPage,closeSidePanelMenu,store,navigate,+ returnLocation,defaultHomePagePath,]);};diff --git a/packages/twenty-front/src/modules/ai/hooks/useSelectAiChatThread.ts b/packages/twenty-front/src/modules/ai/hooks/useSelectAiChatThread.tsnew file mode 100644index 00000000000..e7ba9a5a052--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useSelectAiChatThread.ts@@ -0,0 +1,14 @@+import { useProjectAiChatThreadToUrl } from '@/ai/hooks/useProjectAiChatThreadToUrl';+import { useSwitchAgentChatThreadWithDraft } from '@/ai/hooks/useSwitchAgentChatThreadWithDraft';++export const useSelectAiChatThread = () => {+ const { switchThreadWithDraft } = useSwitchAgentChatThreadWithDraft();+ const { projectAiChatThreadToUrl } = useProjectAiChatThreadToUrl();++ const selectAiChatThread = (toThreadId: string) => {+ switchThreadWithDraft(toThreadId);+ projectAiChatThreadToUrl(toThreadId);+ };++ return { selectAiChatThread };+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts b/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.tsindex 234b9f578cf..d5e5c354948 100644--- a/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts@@ -4,6 +4,7 @@ import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { useStore } from 'jotai';+import { useCallback } from 'react';import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';export const useSwitchAgentChatThreadWithDraft = () => {@@ -13,17 +14,20 @@ export const useSwitchAgentChatThreadWithDraft = () => {const setAgentChatInput = useSetAtomState(agentChatInputState);const store = useStore();- const switchThreadWithDraft = (toThreadId: string) => {- const isSameThread = toThreadId === currentAiChatThread;+ const switchThreadWithDraft = useCallback(+ (toThreadId: string) => {+ const isSameThread = toThreadId === currentAiChatThread;- setCurrentAiChatThread(toThreadId);+ setCurrentAiChatThread(toThreadId);- if (!isSameThread) {- const destinationDraft =- store.get(agentChatDraftsByThreadIdState.atom)[toThreadId] ?? '';- setAgentChatInput(tipTapDocumentToMarkdown(destinationDraft));- }- };+ if (!isSameThread) {+ const destinationDraft =+ store.get(agentChatDraftsByThreadIdState.atom)[toThreadId] ?? '';+ setAgentChatInput(tipTapDocumentToMarkdown(destinationDraft));+ }+ },+ [currentAiChatThread, setCurrentAiChatThread, setAgentChatInput, store],+ );return { switchThreadWithDraft };};diff --git a/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAiChat.ts b/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAiChat.tsindex 501431a0ef1..7b273435bf3 100644--- a/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAiChat.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useSwitchToNewAiChat.ts@@ -1,6 +1,6 @@import { useStore } from 'jotai';-import { useSwitchAgentChatThreadWithDraft } from '@/ai/hooks/useSwitchAgentChatThreadWithDraft';+import { useSelectAiChatThread } from '@/ai/hooks/useSelectAiChatThread';import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';import { shouldFocusChatEditorState } from '@/ai/states/shouldFocusChatEditorState';import { hasTriggeredCreateForDraftState } from '@/ai/states/hasTriggeredCreateForDraftState';@@ -12,14 +12,14 @@ export const useSwitchToNewAiChat = () => {const setThreadIdCreatedFromDraft = useSetAtomState(threadIdCreatedFromDraftState,);- const { switchThreadWithDraft } = useSwitchAgentChatThreadWithDraft();+ const { selectAiChatThread } = useSelectAiChatThread();const store = useStore();const { openAskAiPage } = useOpenAskAiPageInSidePanel();const switchToNewChat = () => {setThreadIdCreatedFromDraft(null);store.set(hasTriggeredCreateForDraftState.atom, false);- switchThreadWithDraft(AGENT_CHAT_NEW_THREAD_DRAFT_KEY);+ selectAiChatThread(AGENT_CHAT_NEW_THREAD_DRAFT_KEY);openAskAiPage();store.set(shouldFocusChatEditorState.atom, true);};diff --git a/packages/twenty-front/src/modules/ai/states/aiChatExpandedReturnLocationState.ts b/packages/twenty-front/src/modules/ai/states/aiChatExpandedReturnLocationState.tsdeleted file mode 100644index aa6122696fc..00000000000--- a/packages/twenty-front/src/modules/ai/states/aiChatExpandedReturnLocationState.ts+++ /dev/null@@ -1,8 +0,0 @@-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';--export const aiChatExpandedReturnLocationState = createAtomState<string | null>(- {- key: 'aiChatExpandedReturnLocationState',- defaultValue: null,- },-);diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getExpandedAiChatReturnLocation.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getExpandedAiChatReturnLocation.test.tsnew file mode 100644index 00000000000..7c9148914c9--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getExpandedAiChatReturnLocation.test.ts@@ -0,0 +1,23 @@+import { getExpandedAiChatReturnLocation } from '@/ai/utils/getExpandedAiChatReturnLocation';++describe('getExpandedAiChatReturnLocation', () => {+ it('should return the location the chat was expanded from', () => {+ expect(+ getExpandedAiChatReturnLocation({+ returnLocation: '/objects/people?viewId=1#top',+ }),+ ).toBe('/objects/people?viewId=1#top');+ });++ it.each([+ ['no history state', null],+ ['a history state without a return location', { other: '/objects/people' }],+ ['a non-string return location', { returnLocation: 42 }],+ ['an absolute url', { returnLocation: 'https://evil.example.com' }],+ ['a protocol-relative url', { returnLocation: '//evil.example.com' }],+ ['a backslash escape', { returnLocation: '/objects\\..\\people' }],+ ['an onboarding path', { returnLocation: '/create/profile' }],+ ])('should return null for %s', (_case, historyState) => {+ expect(getExpandedAiChatReturnLocation(historyState)).toBeNull();+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/getExpandedAiChatReturnLocation.ts b/packages/twenty-front/src/modules/ai/utils/getExpandedAiChatReturnLocation.tsnew file mode 100644index 00000000000..6638efd359b--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getExpandedAiChatReturnLocation.ts@@ -0,0 +1,18 @@+import { isValidReturnToPath } from '@/auth/utils/isValidReturnToPath';++export const getExpandedAiChatReturnLocation = (historyState: unknown) => {+ if (+ typeof historyState !== 'object' ||+ historyState === null ||+ !('returnLocation' in historyState)+ ) {+ return null;+ }++ const { returnLocation } = historyState;++ return typeof returnLocation === 'string' &&+ isValidReturnToPath(returnLocation)+ ? returnLocation+ : null;+};diff --git a/packages/twenty-front/src/modules/app/effect-components/PageChangeEffect.tsx b/packages/twenty-front/src/modules/app/effect-components/PageChangeEffect.tsxindex dfe7851d139..d8eef6d391f 100644--- a/packages/twenty-front/src/modules/app/effect-components/PageChangeEffect.tsx+++ b/packages/twenty-front/src/modules/app/effect-components/PageChangeEffect.tsx@@ -39,6 +39,7 @@ import { AppBasePath, AppPath, SidePanelPages } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { usePageChangeEffectNavigateLocation } from '~/hooks/usePageChangeEffectNavigateLocation';import { getPageLayoutIdForLocation } from '~/modules/app/utils/getPageLayoutIdForLocation';+import { isAiChatPath } from '~/utils/isAiChatPath';import { isMatchingLocation } from '~/utils/isMatchingLocation';// TODO: break down into smaller functions and / or hooks@@ -162,7 +163,7 @@ export const PageChangeEffect = () => {if (store.get(shouldOpenAiChatAfterOnboardingState.atom) &&- pageChangeEffectNavigateLocation !== AppPath.WorkspaceSetup+ !isAiChatPath(pageChangeEffectNavigateLocation)) {store.set(shouldOpenAiChatAfterOnboardingState.atom, false);}diff --git a/packages/twenty-front/src/modules/app/hooks/useCreateWorkspaceAppRouter.tsx b/packages/twenty-front/src/modules/app/hooks/useCreateWorkspaceAppRouter.tsxindex f4b27fc4504..d0215379d8a 100644--- a/packages/twenty-front/src/modules/app/hooks/useCreateWorkspaceAppRouter.tsx+++ b/packages/twenty-front/src/modules/app/hooks/useCreateWorkspaceAppRouter.tsx@@ -111,9 +111,9 @@ const StandalonePageLayoutPage = lazy(() =>})),);-const WorkspaceSetup = lazyWithPreload(() =>- import('~/pages/onboarding/WorkspaceSetup').then((module) => ({- default: module.WorkspaceSetup,+const AiChatPage = lazy(() =>+ import('~/pages/ai-chat/AiChatPage').then((module) => ({+ default: module.AiChatPage,})),);@@ -131,7 +131,6 @@ const preloadOnboardingPages = () => {InviteTeam.preload();BookCall.preload();ChooseYourPlan.preload();- WorkspaceSetup.preload();return null;};@@ -148,14 +147,6 @@ const createWorkspaceAppRouter = (><Route element={<MinimalMetadataGate />}><Route element={<DefaultLayout />}>- <Route- path={AppPath.WorkspaceSetup}- element={- <LazyRoute fallback={null}>- <WorkspaceSetup />- </LazyRoute>- }- /><Route element={<MainAppLayoutWithSidePanel />}><Routepath={indexAppPath.getIndexAppPath()}@@ -185,6 +176,14 @@ const createWorkspaceAppRouter = (</LazyRoute>}/>+ <Route+ path={AppPath.AiChat}+ element={+ <LazyRoute>+ <AiChatPage />+ </LazyRoute>+ }+ /><Routepath={AppPath.SettingsCatchAll}element={diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/components/HeadlessOpenAiChatHistoryTabEngineCommand.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/components/HeadlessOpenAiChatHistoryTabEngineCommand.tsxnew file mode 100644index 00000000000..0347aa7255e--- /dev/null+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/components/HeadlessOpenAiChatHistoryTabEngineCommand.tsx@@ -0,0 +1,21 @@+import { HeadlessEngineCommandWrapperEffect } from '@/command-menu-item/engine-command/components/HeadlessEngineCommandWrapperEffect';+import { isNavigationDrawerExpandedState } from '@/ui/navigation/states/isNavigationDrawerExpanded';+import { navigationDrawerActiveTabState } from '@/ui/navigation/states/navigationDrawerActiveTabState';+import { NAVIGATION_DRAWER_TABS } from '@/ui/navigation/states/navigationDrawerTabs';+import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';++export const HeadlessOpenAiChatHistoryTabEngineCommand = () => {+ const setIsNavigationDrawerExpanded = useSetAtomState(+ isNavigationDrawerExpandedState,+ );+ const setNavigationDrawerActiveTab = useSetAtomState(+ navigationDrawerActiveTabState,+ );++ const onExecute = () => {+ setIsNavigationDrawerExpanded(true);+ setNavigationDrawerActiveTab(NAVIGATION_DRAWER_TABS.AI_CHAT_HISTORY);+ };++ return <HeadlessEngineCommandWrapperEffect execute={onExecute} />;+};diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsxindex f205e51b23d..7b3f9831884 100644--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx@@ -1,5 +1,6 @@import { HeadlessFrontComponentRendererEngineCommand } from '@/command-menu-item/engine-command/components/HeadlessFrontComponentRendererEngineCommand';import { HeadlessNavigateEngineCommand } from '@/command-menu-item/engine-command/components/HeadlessNavigateEngineCommand';+import { HeadlessOpenAiChatHistoryTabEngineCommand } from '@/command-menu-item/engine-command/components/HeadlessOpenAiChatHistoryTabEngineCommand';import { HeadlessOpenSidePanelPageEngineCommand } from '@/command-menu-item/engine-command/components/HeadlessOpenSidePanelPageEngineCommand';import { NavigationEngineCommand } from '@/command-menu-item/engine-command/components/NavigationEngineCommand';import { ComposeCampaignCommand } from '@/command-menu-item/engine-command/global/components/ComposeCampaignCommand';@@ -51,7 +52,7 @@ import { TidyUpWorkflowSingleRecordCommand } from '@/command-menu-item/engine-coimport { CoreObjectNamePlural } from '@/object-metadata/types/CoreObjectNamePlural';import { msg } from '@lingui/core/macro';import { AppPath, SettingsPath, SidePanelPages } from 'twenty-shared/types';-import { IconHistory, IconSearch, IconSparkles } from 'twenty-ui/icon';+import { IconSearch, IconSparkles } from 'twenty-ui/icon';import { EngineComponentKey } from '~/generated-metadata/graphql';export const ENGINE_COMPONENT_KEY_COMPONENT_MAP: Record<@@ -215,11 +216,7 @@ export const ENGINE_COMPONENT_KEY_COMPONENT_MAP: Record</>),[EngineComponentKey.VIEW_PREVIOUS_AI_CHATS]: (- <HeadlessOpenSidePanelPageEngineCommand- page={SidePanelPages.ViewPreviousAiChats}- pageTitle={msg`View Previous AI Chats`}- pageIcon={IconHistory}- />+ <HeadlessOpenAiChatHistoryTabEngineCommand />),[EngineComponentKey.SEE_ACTIVE_VERSION_WORKFLOW]: (<SeeActiveVersionWorkflowSingleRecordCommand />diff --git a/packages/twenty-front/src/modules/command-menu/hooks/useCommandMenuHotKeys.ts b/packages/twenty-front/src/modules/command-menu/hooks/useCommandMenuHotKeys.tsindex f7955a8d448..22a33e91b73 100644--- a/packages/twenty-front/src/modules/command-menu/hooks/useCommandMenuHotKeys.ts+++ b/packages/twenty-front/src/modules/command-menu/hooks/useCommandMenuHotKeys.ts@@ -1,4 +1,3 @@-import { AI_CHAT_THREADS_LIST_FOCUS_ID } from '@/ai/constants/AiChatThreadsListFocusId';import { useKeyboardShortcutMenu } from '@/keyboard-shortcut-menu/hooks/useKeyboardShortcutMenu';import { SIDE_PANEL_FOCUS_ID } from '@/side-panel/constants/SidePanelFocusId';import { useHandleSidePanelEscape } from '@/side-panel/hooks/useHandleSidePanelEscape';@@ -65,16 +64,4 @@ export const useCommandMenuHotKeys = () => {enableOnFormTags: false,},});-- useHotkeysOnFocusedElement({- keys: [Key.Escape],- callback: () => {- handleSidePanelEscape();- },- focusId: AI_CHAT_THREADS_LIST_FOCUS_ID,- dependencies: [handleSidePanelEscape],- options: {- enableOnFormTags: false,- },- });};diff --git a/packages/twenty-front/src/modules/context-store/components/MainContextStoreProvider.tsx b/packages/twenty-front/src/modules/context-store/components/MainContextStoreProvider.tsxindex 11d7a9ceaec..a95e4e8446c 100644--- a/packages/twenty-front/src/modules/context-store/components/MainContextStoreProvider.tsx+++ b/packages/twenty-front/src/modules/context-store/components/MainContextStoreProvider.tsx@@ -45,6 +45,7 @@ export const MainContextStoreProvider = () => {);const isRecordShowPage = isMatchingLocation(location, AppPath.RecordShowPage);const isStandalonePage = isMatchingLocation(location, AppPath.PageLayoutPage);+ const isAiChatPage = isMatchingLocation(location, AppPath.AiChat);const isSettingsPage = useIsSettingsPage();const objectNamePlural = useParams().objectNamePlural ?? '';@@ -112,6 +113,7 @@ export const MainContextStoreProvider = () => {(isRecordIndexPage ||isRecordShowPage ||isStandalonePage ||+ isAiChatPage ||isSettingsPage) &&metadataStore.status === 'up-to-date';diff --git a/packages/twenty-front/src/modules/context-store/utils/getContextStoreViewType.ts b/packages/twenty-front/src/modules/context-store/utils/getContextStoreViewType.tsnew file mode 100644index 00000000000..4aa240e1fcd--- /dev/null+++ b/packages/twenty-front/src/modules/context-store/utils/getContextStoreViewType.ts@@ -0,0 +1,22 @@+import { ContextStoreViewType } from '@/context-store/types/ContextStoreViewType';+import { ViewType } from '~/generated-metadata/graphql';++type ViewTypeValue = `${ViewType}`;++const VIEW_TYPE_TO_CONTEXT_STORE_VIEW_TYPE: Record<+ ViewTypeValue,+ ContextStoreViewType+> = {+ [ViewType.TABLE]: ContextStoreViewType.Table,+ [ViewType.TABLE_WIDGET]: ContextStoreViewType.Table,+ [ViewType.LIST]: ContextStoreViewType.Table,+ [ViewType.FIELDS_WIDGET]: ContextStoreViewType.Table,+ [ViewType.KANBAN]: ContextStoreViewType.Kanban,+ [ViewType.KANBAN_WIDGET]: ContextStoreViewType.Kanban,+ [ViewType.CALENDAR]: ContextStoreViewType.Calendar,+ [ViewType.CALENDAR_WIDGET]: ContextStoreViewType.Calendar,+};++export const getContextStoreViewType = (+ viewType: ViewTypeValue,+): ContextStoreViewType => VIEW_TYPE_TO_CONTEXT_STORE_VIEW_TYPE[viewType];diff --git a/packages/twenty-front/src/modules/object-record/record-board-widget/components/RecordBoardWidget.tsx b/packages/twenty-front/src/modules/object-record/record-board-widget/components/RecordBoardWidget.tsxindex be27449cbe6..72718ab4079 100644--- a/packages/twenty-front/src/modules/object-record/record-board-widget/components/RecordBoardWidget.tsx+++ b/packages/twenty-front/src/modules/object-record/record-board-widget/components/RecordBoardWidget.tsx@@ -2,11 +2,8 @@ import { RecordBoardContainer } from '@/object-record/record-board/components/Reimport { RecordBoardWidgetViewSettingsReadOnlyEffect } from '@/object-record/record-board-widget/components/RecordBoardWidgetViewSettingsReadOnlyEffect';import { useRecordIndexContextOrThrow } from '@/object-record/record-index/contexts/RecordIndexContext';import { styled } from '@linaria/react';-import { themeCssVariables } from 'twenty-ui/theme-constants';const StyledBoardContainer = styled.div`- border: 1px solid ${themeCssVariables.border.color.light};- border-radius: ${themeCssVariables.border.radius.sm};display: flex;flex: 1;flex-direction: column;diff --git a/packages/twenty-front/src/modules/object-record/record-calendar-widget/components/RecordCalendarWidget.tsx b/packages/twenty-front/src/modules/object-record/record-calendar-widget/components/RecordCalendarWidget.tsxindex 3a1375603e0..563c120da2d 100644--- a/packages/twenty-front/src/modules/object-record/record-calendar-widget/components/RecordCalendarWidget.tsx+++ b/packages/twenty-front/src/modules/object-record/record-calendar-widget/components/RecordCalendarWidget.tsx@@ -11,11 +11,8 @@ import { useRecordIndexContextOrThrow } from '@/object-record/record-index/conteimport { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';import { styled } from '@linaria/react';import { isDefined } from 'twenty-shared/utils';-import { themeCssVariables } from 'twenty-ui/theme-constants';const StyledCalendarContainer = styled.div`- border: 1px solid ${themeCssVariables.border.color.light};- border-radius: ${themeCssVariables.border.radius.sm};display: flex;flex: 1;flex-direction: column;diff --git a/packages/twenty-front/src/modules/object-record/record-table-widget/components/RecordTableWidget.tsx b/packages/twenty-front/src/modules/object-record/record-table-widget/components/RecordTableWidget.tsxindex 2867d51cea2..10be7a7cf09 100644--- a/packages/twenty-front/src/modules/object-record/record-table-widget/components/RecordTableWidget.tsx+++ b/packages/twenty-front/src/modules/object-record/record-table-widget/components/RecordTableWidget.tsx@@ -3,11 +3,8 @@ import { useRecordIndexContextOrThrow } from '@/object-record/record-index/conteimport { RecordTableWidgetSetReadOnlyColumnHeadersEffect } from '@/object-record/record-table-widget/components/RecordTableWidgetSetReadOnlyColumnHeadersEffect';import { RecordTableWithWrappers } from '@/object-record/record-table/components/RecordTableWithWrappers';import { styled } from '@linaria/react';-import { themeCssVariables } from 'twenty-ui/theme-constants';const StyledTableContainer = styled.div`- border: 1px solid ${themeCssVariables.border.color.light};- border-radius: ${themeCssVariables.border.radius.sm};min-height: 0;overflow: hidden;`;diff --git a/packages/twenty-front/src/modules/onboarding/components/WorkspaceSetupHeader.tsx b/packages/twenty-front/src/modules/onboarding/components/WorkspaceSetupHeader.tsxdeleted file mode 100644index ab214dec16c..00000000000--- a/packages/twenty-front/src/modules/onboarding/components/WorkspaceSetupHeader.tsx+++ /dev/null@@ -1,47 +0,0 @@-import { styled } from '@linaria/react';-import { themeCssVariables } from 'twenty-ui/theme-constants';--import { AiChatCloseButton } from '@/ai/components/AiChatCloseButton';-import { AiChatCollapseButton } from '@/ai/components/AiChatCollapseButton';-import { SIDE_PANEL_TOP_BAR_HEIGHT } from '@/side-panel/constants/SidePanelTopBarHeight';--const StyledHeader = styled.header`- align-items: center;- background-color: ${themeCssVariables.background.secondary};- border-bottom: 1px solid ${themeCssVariables.border.color.light};- box-sizing: border-box;- display: flex;- flex-shrink: 0;- gap: ${themeCssVariables.spacing['0.5']};- height: ${SIDE_PANEL_TOP_BAR_HEIGHT}px;- padding: 0 ${themeCssVariables.spacing[2]};-`;--const StyledHeaderTitle = styled.div`- align-items: center;- border-radius: ${themeCssVariables.border.radius.sm};- color: ${themeCssVariables.font.color.primary};- display: flex;- flex: 1;- font-size: ${themeCssVariables.font.size.md};- font-weight: ${themeCssVariables.font.weight.semiBold};- height: ${themeCssVariables.spacing[6]};- line-height: 1.4;- min-width: 0;- overflow: hidden;- padding: 0 ${themeCssVariables.spacing[1]};- text-overflow: ellipsis;- white-space: nowrap;-`;--type WorkspaceSetupHeaderProps = {- title: string;-};--export const WorkspaceSetupHeader = ({ title }: WorkspaceSetupHeaderProps) => (- <StyledHeader>- <StyledHeaderTitle>{title}</StyledHeaderTitle>- <AiChatCollapseButton />- <AiChatCloseButton />- </StyledHeader>-);diff --git a/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetRelationTable.tsx b/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetRelationTable.tsxindex af68686b14a..ba2a6cb7bb4 100644--- a/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetRelationTable.tsx+++ b/packages/twenty-front/src/modules/page-layout/widgets/field/components/FieldWidgetRelationTable.tsx@@ -13,6 +13,7 @@ import { useCurrentWidget } from '@/page-layout/widgets/hooks/useCurrentWidget';import { useLayoutRenderingContext } from '@/ui/layout/contexts/LayoutRenderingContext';import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';import { styled } from '@linaria/react';+import { themeCssVariables } from 'twenty-ui/theme-constants';import { isNonEmptyString } from '@sniptt/guards';import { useMemo } from 'react';import {@@ -28,10 +29,13 @@ const FIELD_WIDGET_RELATION_TABLE_MAX_HEIGHT_IN_PX =RECORD_TABLE_ROW_HEIGHT;const StyledContainer = styled.div`+ border: 1px solid ${themeCssVariables.border.color.light};+ border-radius: ${themeCssVariables.border.radius.sm};display: flex;flex-direction: column;max-height: ${FIELD_WIDGET_RELATION_TABLE_MAX_HEIGHT_IN_PX}px;min-height: 0;+ overflow: hidden;`;type FieldWidgetRelationTableProps = {diff --git a/packages/twenty-front/src/modules/page-layout/widgets/record-table/components/RecordTableWidgetRendererContent.tsx b/packages/twenty-front/src/modules/page-layout/widgets/record-table/components/RecordTableWidgetRendererContent.tsxindex 62611b0894b..b4240734dc0 100644--- a/packages/twenty-front/src/modules/page-layout/widgets/record-table/components/RecordTableWidgetRendererContent.tsx+++ b/packages/twenty-front/src/modules/page-layout/widgets/record-table/components/RecordTableWidgetRendererContent.tsx@@ -1,4 +1,4 @@-import { ContextStoreViewType } from '@/context-store/types/ContextStoreViewType';+import { getContextStoreViewType } from '@/context-store/utils/getContextStoreViewType';import { useObjectMetadataItemById } from '@/object-metadata/hooks/useObjectMetadataItemById';import { RecordBoardWidget } from '@/object-record/record-board-widget/components/RecordBoardWidget';import { RecordCalendarWidget } from '@/object-record/record-calendar-widget/components/RecordCalendarWidget';@@ -92,13 +92,7 @@ export const RecordTableWidgetRendererContent = ({recordLimit={recordLimit}instanceIdSuffix={instanceIdSuffix}nestedRelationCreateThrough={nestedRelationCreateThrough}- contextStoreViewType={- isKanbanLayout- ? ContextStoreViewType.Kanban- : isCalendarLayout- ? ContextStoreViewType.Calendar- : ContextStoreViewType.Table- }+ contextStoreViewType={getContextStoreViewType(widgetViewLayout)}>{isKanbanLayout ? (<RecordBoardWidget isReadOnly={isReadOnly} />diff --git a/packages/twenty-front/src/modules/page-layout/widgets/widget-card/components/WidgetCardContent.tsx b/packages/twenty-front/src/modules/page-layout/widgets/widget-card/components/WidgetCardContent.tsxindex dc612a15911..b6e764d82f6 100644--- a/packages/twenty-front/src/modules/page-layout/widgets/widget-card/components/WidgetCardContent.tsx+++ b/packages/twenty-front/src/modules/page-layout/widgets/widget-card/components/WidgetCardContent.tsx@@ -12,6 +12,15 @@ type WidgetCardContentStyledProps = {hasBoundedHeight: boolean;};+const StyledRecordWidgetOutline = styled.div`+ border: 1px solid ${themeCssVariables.border.color.light};+ border-radius: ${themeCssVariables.border.radius.sm};+ display: flex;+ flex-direction: column;+ min-height: 0;+ overflow: hidden;+`;+const StyledWidgetCardContent = styled.div<WidgetCardContentStyledProps>`background-color: ${({ variant, isInVerticalListTab, isMobile }) =>variant === 'record-page' && isInVerticalListTab && !isMobile@@ -101,7 +110,11 @@ export const WidgetCardContent = ({className={className}onClick={handleContentClick}>- {children}+ {hasInteractiveContent ? (+ <StyledRecordWidgetOutline>{children}</StyledRecordWidgetOutline>+ ) : (+ children+ )}</StyledWidgetCardContent>);};diff --git a/packages/twenty-front/src/modules/side-panel/components/SidePanelAskAiHandoffEffect.tsx b/packages/twenty-front/src/modules/side-panel/components/SidePanelAskAiHandoffEffect.tsxindex 7412e52a05e..c33460130fd 100644--- a/packages/twenty-front/src/modules/side-panel/components/SidePanelAskAiHandoffEffect.tsx+++ b/packages/twenty-front/src/modules/side-panel/components/SidePanelAskAiHandoffEffect.tsx@@ -1,26 +1,38 @@import { useStore } from 'jotai';import { useLayoutEffect } from 'react';+import { useLocation } from 'react-router-dom';-import { aiChatExpandedReturnLocationState } from '@/ai/states/aiChatExpandedReturnLocationState';import { shouldContinueAiChatInSidePanelState } from '@/ai/states/shouldContinueAiChatInSidePanelState';import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';import { useOpenAskAiPageInSidePanel } from '@/side-panel/hooks/useOpenAskAiPageInSidePanel';+import { isAiChatPath } from '~/utils/isAiChatPath';-export const SidePanelAskAiHandoffEffect = () => {+type SidePanelAskAiHandoffEffectProps = {+ onContinueChatFromFullWidth: () => void;+};++export const SidePanelAskAiHandoffEffect = ({+ onContinueChatFromFullWidth,+}: SidePanelAskAiHandoffEffectProps) => {const store = useStore();+ const { pathname } = useLocation();const { openAskAiPage } = useOpenAskAiPageInSidePanel();useLayoutEffect(() => {+ if (isAiChatPath(pathname)) {+ return;+ }+if (!store.get(shouldContinueAiChatInSidePanelState.atom)) {return;}store.set(shouldContinueAiChatInSidePanelState.atom, false);store.set(shouldOpenAiChatAfterOnboardingState.atom, false);- store.set(aiChatExpandedReturnLocationState.atom, null);+ onContinueChatFromFullWidth();openAskAiPage({ resetNavigationStack: true });- }, [store, openAskAiPage]);+ }, [pathname, store, openAskAiPage, onContinueChatFromFullWidth]);return null;};diff --git a/packages/twenty-front/src/modules/side-panel/components/SidePanelExpandAiChatButton.tsx b/packages/twenty-front/src/modules/side-panel/components/SidePanelExpandAiChatButton.tsxindex a4a1f642a5a..574ad6762fa 100644--- a/packages/twenty-front/src/modules/side-panel/components/SidePanelExpandAiChatButton.tsx+++ b/packages/twenty-front/src/modules/side-panel/components/SidePanelExpandAiChatButton.tsx@@ -1,40 +1,55 @@import { useLingui } from '@lingui/react/macro';-import { useLocation, useNavigate } from 'react-router-dom';+import { useLocation } from 'react-router-dom';import { AppPath, SidePanelPages } from 'twenty-shared/types';+import { isDefined, isValidUuid } from 'twenty-shared/utils';import { IconLayoutSidebarRightExpand } from 'twenty-ui/icon';import { IconButton } from 'twenty-ui/input';import { useIsMobile } from 'twenty-ui/utilities';-import { aiChatExpandedReturnLocationState } from '@/ai/states/aiChatExpandedReturnLocationState';-import { isOnboardingAiChatEnabledState } from '@/client-config/states/isOnboardingAiChatEnabledState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { useSidePanelMenu } from '@/side-panel/hooks/useSidePanelMenu';import { sidePanelPageState } from '@/side-panel/states/sidePanelPageState';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';-import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';+import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';+import { FeatureFlagKey } from '~/generated-metadata/graphql';+import { useNavigateApp } from '~/hooks/useNavigateApp';export const SidePanelExpandAiChatButton = () => {const { t } = useLingui();- const navigate = useNavigate();+ const navigateApp = useNavigateApp();const location = useLocation();const isMobile = useIsMobile();const sidePanelPage = useAtomStateValue(sidePanelPageState);- const isOnboardingAiChatEnabled = useAtomStateValue(- isOnboardingAiChatEnabledState,- );- const setAiChatExpandedReturnLocation = useSetAtomState(- aiChatExpandedReturnLocationState,+ const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);+ const { closeSidePanelMenu } = useSidePanelMenu();+ const isAiChatPageEnabled = useIsFeatureEnabled(+ FeatureFlagKey.IS_AI_CHAT_PAGE_ENABLED,);const isOnAskAiPage = sidePanelPage === SidePanelPages.AskAI;- if (!isOnboardingAiChatEnabled || isMobile || !isOnAskAiPage) {+ if (!isAiChatPageEnabled || isMobile || !isOnAskAiPage) {return null;}const handleClick = () => {- setAiChatExpandedReturnLocation(- `${location.pathname}${location.search}${location.hash}`,+ void closeSidePanelMenu();++ navigateApp(+ AppPath.AiChat,+ {+ threadId:+ isDefined(currentAiChatThread) && isValidUuid(currentAiChatThread)+ ? currentAiChatThread+ : null,+ },+ undefined,+ {+ state: {+ returnLocation: `${location.pathname}${location.search}${location.hash}`,+ },+ },);- navigate(AppPath.WorkspaceSetup);};return (diff --git a/packages/twenty-front/src/modules/side-panel/components/SidePanelForDesktop.tsx b/packages/twenty-front/src/modules/side-panel/components/SidePanelForDesktop.tsxindex 6b93955aa9c..f86470101f2 100644--- a/packages/twenty-front/src/modules/side-panel/components/SidePanelForDesktop.tsx+++ b/packages/twenty-front/src/modules/side-panel/components/SidePanelForDesktop.tsx@@ -4,7 +4,6 @@ import { SidePanelRouter } from '@/side-panel/components/SidePanelRouter';import { SidePanelWidthEffect } from '@/side-panel/components/SidePanelWidthEffect';import { SIDE_PANEL_CLICK_OUTSIDE_ID } from '@/side-panel/constants/SidePanelClickOutsideId';import { SIDE_PANEL_CONSTRAINTS } from '@/side-panel/constants/SidePanelConstraints';-import { useShouldShrinkSidePanelFromFullWidth } from '@/side-panel/hooks/useShouldShrinkSidePanelFromFullWidth';import { useSidePanelCloseAnimationCompleteCleanup } from '@/side-panel/hooks/useSidePanelCloseAnimationCompleteCleanup';import { useSidePanelMenu } from '@/side-panel/hooks/useSidePanelMenu';import { isSidePanelClosingState } from '@/side-panel/states/isSidePanelClosingState';@@ -20,6 +19,7 @@ import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { styled } from '@linaria/react';+import { useReducedMotion } from 'framer-motion';import { useStore } from 'jotai';import { type AnimationEvent, useCallback, useState } from 'react';import { themeCssVariables } from 'twenty-ui/theme-constants';@@ -79,7 +79,7 @@ export const SidePanelForDesktop = () => {const { closeSidePanelMenu } = useSidePanelMenu();const { sidePanelCloseAnimationCompleteCleanup } =useSidePanelCloseAnimationCompleteCleanup();- const shouldShrinkFromFullWidth = useShouldShrinkSidePanelFromFullWidth();+ const shouldReduceMotion = useReducedMotion();const [modalContainer, setModalContainer] = useState<HTMLDivElement | null>(null,@@ -87,9 +87,16 @@ export const SidePanelForDesktop = () => {const [isResizing, setIsResizing] = useState(false);const [shouldRenderContent, setShouldRenderContent] =useState(isSidePanelOpened);- const [isShrinkingFromFullWidth, setIsShrinkingFromFullWidth] = useState(- shouldShrinkFromFullWidth,- );+ const [isShrinkingFromFullWidth, setIsShrinkingFromFullWidth] =+ useState(false);++ const handleContinueChatFromFullWidth = useCallback(() => {+ if (shouldReduceMotion === true) {+ return;+ }++ setIsShrinkingFromFullWidth(true);+ }, [shouldReduceMotion]);const setTableWidthResizeIsActive = useSetAtomState(tableWidthResizeIsActiveState,@@ -152,7 +159,9 @@ export const SidePanelForDesktop = () => {return (<><SidePanelWidthEffect />- <SidePanelAskAiHandoffEffect />+ <SidePanelAskAiHandoffEffect+ onContinueChatFromFullWidth={handleContinueChatFromFullWidth}+ /><ResizablePanelGapside="left"constraints={SIDE_PANEL_CONSTRAINTS}diff --git a/packages/twenty-front/src/modules/side-panel/components/SidePanelTopBarRightCornerIcon.tsx b/packages/twenty-front/src/modules/side-panel/components/SidePanelTopBarRightCornerIcon.tsxindex 55bda587616..cad67beaa56 100644--- a/packages/twenty-front/src/modules/side-panel/components/SidePanelTopBarRightCornerIcon.tsx+++ b/packages/twenty-front/src/modules/side-panel/components/SidePanelTopBarRightCornerIcon.tsx@@ -34,10 +34,7 @@ export const SidePanelTopBarRightCornerIcon = () => {);}- const isOnAskAiPage = [- SidePanelPages.AskAI,- SidePanelPages.ViewPreviousAiChats,- ].includes(sidePanelPage);+ const isOnAskAiPage = sidePanelPage === SidePanelPages.AskAI;if (isMobile || !isOnAskAiPage) {return null;diff --git a/packages/twenty-front/src/modules/side-panel/components/__tests__/SidePanelAskAiHandoffEffect.test.tsx b/packages/twenty-front/src/modules/side-panel/components/__tests__/SidePanelAskAiHandoffEffect.test.tsxindex bd61d3838b8..dcab40bad89 100644--- a/packages/twenty-front/src/modules/side-panel/components/__tests__/SidePanelAskAiHandoffEffect.test.tsx+++ b/packages/twenty-front/src/modules/side-panel/components/__tests__/SidePanelAskAiHandoffEffect.test.tsx@@ -2,12 +2,10 @@ import { act, render } from '@testing-library/react';import { Provider as JotaiProvider } from 'jotai';import { MemoryRouter, Route, Routes, useNavigate } from 'react-router-dom';-import { aiChatExpandedReturnLocationState } from '@/ai/states/aiChatExpandedReturnLocationState';+import { AiChatPageContinueInSidePanelEffect } from '@/ai/components/AiChatPageContinueInSidePanelEffect';import { shouldContinueAiChatInSidePanelState } from '@/ai/states/shouldContinueAiChatInSidePanelState';-import { WorkspaceSetupChatSidePanelHandoffEffect } from '@/onboarding/effect-components/WorkspaceSetupChatSidePanelHandoffEffect';import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';import { SidePanelAskAiHandoffEffect } from '@/side-panel/components/SidePanelAskAiHandoffEffect';-import { useShouldShrinkSidePanelFromFullWidth } from '@/side-panel/hooks/useShouldShrinkSidePanelFromFullWidth';import {jotaiStore,resetJotaiStore,@@ -19,37 +17,28 @@ jest.mock('@/side-panel/hooks/useOpenAskAiPageInSidePanel', () => ({useOpenAskAiPageInSidePanel: () => ({ openAskAiPage: openAskAiPageMock }),}));-jest.mock('framer-motion', () => ({- useReducedMotion: () => false,-}));+const onContinueChatFromFullWidthMock = jest.fn();-let navigateAwayFromWorkspaceSetup: (() => void) | undefined;+let navigateAwayFromChatPage: (() => void) | undefined;-const WorkspaceSetupRoute = () => {+const ChatPageRoute = () => {const navigate = useNavigate();- navigateAwayFromWorkspaceSetup = () => navigate('/objects/companies');-- return <WorkspaceSetupChatSidePanelHandoffEffect />;-};--const SidePanelRoute = () => {- const shouldShrinkFromFullWidth = useShouldShrinkSidePanelFromFullWidth();+ navigateAwayFromChatPage = () => navigate('/objects/companies');- return (- <>- <SidePanelAskAiHandoffEffect />- <div data-testid="side-panel">{String(shouldShrinkFromFullWidth)}</div>- </>- );+ return <AiChatPageContinueInSidePanelEffect />;};-const RouterUnderTest = () => (+const RouterUnderTest = ({ initialPath }: { initialPath: string }) => (<JotaiProvider store={jotaiStore}>- <MemoryRouter initialEntries={['/workspace-setup']}>+ <MemoryRouter initialEntries={[initialPath]}>+ {/* The handoff lives in the persistent layout, outside the routes. */}+ <SidePanelAskAiHandoffEffect+ onContinueChatFromFullWidth={onContinueChatFromFullWidthMock}+ /><Routes>- <Route path="/workspace-setup" element={<WorkspaceSetupRoute />} />- <Route path="/objects/companies" element={<SidePanelRoute />} />+ <Route path="/chat/:threadId?" element={<ChatPageRoute />} />+ <Route path="/objects/companies" element={<div />} /></Routes></MemoryRouter></JotaiProvider>@@ -60,43 +49,51 @@ describe('SidePanelAskAiHandoffEffect', () => {jest.clearAllMocks();sessionStorage.clear();resetJotaiStore();- navigateAwayFromWorkspaceSetup = undefined;+ navigateAwayFromChatPage = undefined;});- it('should consume the marker and open the ask ai page when the workspace setup page unmounts in the same commit', () => {+ it('should continue the chat in the side panel on the navigation leaving the chat page', () => {jotaiStore.set(shouldOpenAiChatAfterOnboardingState.atom, true);- jotaiStore.set(aiChatExpandedReturnLocationState.atom, '/objects/people');- const { getByTestId } = render(<RouterUnderTest />);+ render(<RouterUnderTest initialPath="/chat" />);expect(jotaiStore.get(shouldContinueAiChatInSidePanelState.atom)).toBe(true,);+ expect(openAskAiPageMock).not.toHaveBeenCalled();act(() => {- navigateAwayFromWorkspaceSetup?.();+ navigateAwayFromChatPage?.();});expect(openAskAiPageMock).toHaveBeenCalledWith({resetNavigationStack: true,});- expect(getByTestId('side-panel')).toHaveTextContent('true');+ expect(onContinueChatFromFullWidthMock).toHaveBeenCalled();expect(jotaiStore.get(shouldContinueAiChatInSidePanelState.atom)).toBe(false,);expect(jotaiStore.get(shouldOpenAiChatAfterOnboardingState.atom)).toBe(false,);- expect(jotaiStore.get(aiChatExpandedReturnLocationState.atom)).toBeNull();});- it('should do nothing when the marker is not set', () => {- render(- <JotaiProvider store={jotaiStore}>- <SidePanelAskAiHandoffEffect />- </JotaiProvider>,- );+ it('should stay silent when the continuation marker was cleared before leaving', () => {+ render(<RouterUnderTest initialPath="/chat" />);++ act(() => {+ jotaiStore.set(shouldContinueAiChatInSidePanelState.atom, false);+ navigateAwayFromChatPage?.();+ });++ expect(openAskAiPageMock).not.toHaveBeenCalled();+ expect(onContinueChatFromFullWidthMock).not.toHaveBeenCalled();+ });++ it('should do nothing away from the chat page when the marker is not set', () => {+ render(<RouterUnderTest initialPath="/objects/companies" />);expect(openAskAiPageMock).not.toHaveBeenCalled();+ expect(onContinueChatFromFullWidthMock).not.toHaveBeenCalled();});});diff --git a/packages/twenty-front/src/modules/side-panel/components/__tests__/SidePanelForDesktop.test.tsx b/packages/twenty-front/src/modules/side-panel/components/__tests__/SidePanelForDesktop.test.tsxindex 26bbb6f7ba1..d86e6493c6a 100644--- a/packages/twenty-front/src/modules/side-panel/components/__tests__/SidePanelForDesktop.test.tsx+++ b/packages/twenty-front/src/modules/side-panel/components/__tests__/SidePanelForDesktop.test.tsx@@ -10,15 +10,23 @@ import {resetJotaiStore,} from '@/ui/utilities/state/jotai/jotaiStore';-const shouldShrinkFromFullWidthMock = jest.fn();const sidePanelCloseAnimationCompleteCleanupMock = jest.fn();-jest.mock('@/side-panel/hooks/useShouldShrinkSidePanelFromFullWidth', () => ({- useShouldShrinkSidePanelFromFullWidth: () => shouldShrinkFromFullWidthMock(),-}));+let capturedOnContinueChatFromFullWidth: (() => void) | undefined;jest.mock('@/side-panel/components/SidePanelAskAiHandoffEffect', () => ({- SidePanelAskAiHandoffEffect: () => null,+ SidePanelAskAiHandoffEffect: ({+ onContinueChatFromFullWidth,+ }: {+ onContinueChatFromFullWidth: () => void;+ }) => {+ capturedOnContinueChatFromFullWidth = onContinueChatFromFullWidth;+ return null;+ },+}));++jest.mock('framer-motion', () => ({+ useReducedMotion: () => false,}));jest.mock('@/side-panel/components/SidePanelRouter', () => ({@@ -51,24 +59,31 @@ const Wrapper = ({ children }: { children: ReactNode }) => (<JotaiProvider store={jotaiStore}>{children}</JotaiProvider>);+const startHandoffShrink = () => {+ act(() => {+ capturedOnContinueChatFromFullWidth?.();+ });+};+describe('SidePanelForDesktop', () => {beforeEach(() => {jest.clearAllMocks();resetJotaiStore();- shouldShrinkFromFullWidthMock.mockReturnValue(false);+ capturedOnContinueChatFromFullWidth = undefined;sidePanelCloseAnimationCompleteCleanupMock.mockImplementation(() => {jotaiStore.set(isSidePanelClosingState.atom, false);});});it('should keep the content mounted while closing after a handoff entrance', () => {- shouldShrinkFromFullWidthMock.mockReturnValue(true);jotaiStore.set(isSidePanelOpenedState.atom, true);const { queryByTestId } = render(<SidePanelForDesktop />, {wrapper: Wrapper,});+ startHandoffShrink();+expect(queryByTestId('side-panel-content')).toBeInTheDocument();act(() => {@@ -78,8 +93,31 @@ describe('SidePanelForDesktop', () => {expect(queryByTestId('side-panel-content')).toBeInTheDocument();});+ it('should shrink from full width when the handoff continues the chat', () => {+ jotaiStore.set(isSidePanelOpenedState.atom, true);++ const { container } = render(<SidePanelForDesktop />, { wrapper: Wrapper });++ const wrapperElement = container.querySelector('[data-side-panel]');++ if (wrapperElement === null) {+ throw new Error('side panel wrapper not found');+ }++ expect(wrapperElement).toHaveAttribute(+ 'data-shrink-from-full-width',+ 'false',+ );++ startHandoffShrink();++ expect(wrapperElement).toHaveAttribute(+ 'data-shrink-from-full-width',+ 'true',+ );+ });+it('should stop shrinking from full width once the entrance animation ends', () => {- shouldShrinkFromFullWidthMock.mockReturnValue(true);jotaiStore.set(isSidePanelOpenedState.atom, true);const { container } = render(<SidePanelForDesktop />, { wrapper: Wrapper });@@ -90,6 +128,8 @@ describe('SidePanelForDesktop', () => {throw new Error('side panel wrapper not found');}+ startHandoffShrink();+expect(wrapperElement).toHaveAttribute('data-shrink-from-full-width','true',@@ -104,7 +144,6 @@ describe('SidePanelForDesktop', () => {});it('should complete the close lifecycle when closed while the entrance animation is still running', () => {- shouldShrinkFromFullWidthMock.mockReturnValue(true);jotaiStore.set(isSidePanelOpenedState.atom, true);const { container, queryByTestId } = render(<SidePanelForDesktop />, {@@ -117,6 +156,8 @@ describe('SidePanelForDesktop', () => {throw new Error('side panel wrapper not found');}+ startHandoffShrink();+act(() => {jotaiStore.set(isSidePanelOpenedState.atom, false);jotaiStore.set(isSidePanelClosingState.atom, true);@@ -129,7 +170,6 @@ describe('SidePanelForDesktop', () => {});it('should run the close cleanup once when both the animation and the transition end', () => {- shouldShrinkFromFullWidthMock.mockReturnValue(true);jotaiStore.set(isSidePanelOpenedState.atom, true);const { container } = render(<SidePanelForDesktop />, { wrapper: Wrapper });@@ -140,6 +180,8 @@ describe('SidePanelForDesktop', () => {throw new Error('side panel wrapper not found');}+ startHandoffShrink();+act(() => {jotaiStore.set(isSidePanelOpenedState.atom, false);jotaiStore.set(isSidePanelClosingState.atom, true);diff --git a/packages/twenty-front/src/modules/side-panel/constants/SidePanelPagesConfig.tsx b/packages/twenty-front/src/modules/side-panel/constants/SidePanelPagesConfig.tsxindex 23dbb1ef9cb..a6fa8c11e82 100644--- a/packages/twenty-front/src/modules/side-panel/constants/SidePanelPagesConfig.tsx+++ b/packages/twenty-front/src/modules/side-panel/constants/SidePanelPagesConfig.tsx@@ -2,7 +2,6 @@ import { SidePanelCommandMenuItemDisplayPage } from '@/command-menu-item/displayimport { SidePanelCommandMenuItemEditPage } from '@/command-menu-item/edit/components/SidePanelCommandMenuItemEditPage';import { SidePanelNavigationMenuItemEditPage } from '@/navigation-menu-item/edit/side-panel/components/SidePanelNavigationMenuItemEditPage';import { SidePanelNewSidebarItemPage } from '@/navigation-menu-item/edit/side-panel/components/SidePanelNewSidebarItemPage';-import { SidePanelAiChatThreadsPage } from '@/side-panel/pages/ai-chat-threads/components/SidePanelAiChatThreadsPage';import { SidePanelEmailBlockSettingsPage } from '@/side-panel/pages/email-block-settings/components/SidePanelEmailBlockSettingsPage';import { SidePanelAskAiPage } from '@/side-panel/pages/ask-ai/components/SidePanelAskAiPage';import { SidePanelComposeEmailPage } from '@/side-panel/pages/compose-email/components/SidePanelComposeEmailPage';@@ -17,6 +16,7 @@ import { SidePanelPageLayoutDashboardWidgetTypeSelect } from '@/side-panel/pagesimport { SidePanelPageLayoutRecordPageWidgetTypeSelect } from '@/side-panel/pages/page-layout/components/SidePanelPageLayoutRecordPageWidgetTypeSelect';import { SidePanelPageLayoutTabSettings } from '@/side-panel/pages/page-layout/components/SidePanelPageLayoutTabSettings';import { SidePanelMergeRecordPage } from '@/side-panel/pages/record-page/components/SidePanelMergeRecordPage';+import { SidePanelRecordsPage } from '@/side-panel/pages/records-page/components/SidePanelRecordsPage';import { SidePanelRecordPage } from '@/side-panel/pages/record-page/components/SidePanelRecordPage';import { SidePanelUpdateMultipleRecords } from '@/side-panel/pages/record-page/components/SidePanelUpdateMultipleRecords';import { SidePanelEditRichTextPage } from '@/side-panel/pages/rich-text-page/components/SidePanelEditRichTextPage';@@ -36,6 +36,7 @@ export const SIDE_PANEL_PAGES_CONFIG = new Map<SidePanelPages, React.ReactNode>(<SidePanelCommandMenuItemDisplayPage />,],[SidePanelPages.ViewRecord, <SidePanelRecordPage />],+ [SidePanelPages.ViewRecords, <SidePanelRecordsPage />],[SidePanelPages.MergeRecords, <SidePanelMergeRecordPage />],[SidePanelPages.UpdateRecords, <SidePanelUpdateMultipleRecords />],[SidePanelPages.EditRichText, <SidePanelEditRichTextPage />],@@ -50,7 +51,6 @@ export const SIDE_PANEL_PAGES_CONFIG = new Map<SidePanelPages, React.ReactNode>([SidePanelPages.WorkflowRunStepView, <SidePanelWorkflowRunViewStep />],[SidePanelPages.SearchRecords, <SidePanelSearchRecordsPage />],[SidePanelPages.AskAI, <SidePanelAskAiPage />],- [SidePanelPages.ViewPreviousAiChats, <SidePanelAiChatThreadsPage />],[SidePanelPages.PageLayoutDashboardWidgetTypeSelect,<SidePanelPageLayoutDashboardWidgetTypeSelect />,diff --git a/packages/twenty-front/src/modules/side-panel/hooks/__tests__/useOpenAskAiPageInSidePanel.test.tsx b/packages/twenty-front/src/modules/side-panel/hooks/__tests__/useOpenAskAiPageInSidePanel.test.tsxindex 6d411627e39..07458f1f0d9 100644--- a/packages/twenty-front/src/modules/side-panel/hooks/__tests__/useOpenAskAiPageInSidePanel.test.tsx+++ b/packages/twenty-front/src/modules/side-panel/hooks/__tests__/useOpenAskAiPageInSidePanel.test.tsx@@ -27,6 +27,7 @@ describe('useOpenAskAiPageInSidePanel', () => {beforeEach(() => {jest.clearAllMocks();jotaiStore.set(isSidePanelOpenedState.atom, false);+ window.history.pushState({}, '', '/objects/companies');});it('should navigate to AskAI page with correct defaults', () => {@@ -82,4 +83,18 @@ describe('useOpenAskAiPageInSidePanel', () => {}),);});++ it('should not open the panel AskAI page while on the AI chat page', () => {+ window.history.pushState({}, '', '/chat');++ const { result } = renderHook(() => useOpenAskAiPageInSidePanel(), {+ wrapper: Wrapper,+ });++ act(() => {+ result.current.openAskAiPage();+ });++ expect(navigateSidePanelMenuMock).not.toHaveBeenCalled();+ });});diff --git a/packages/twenty-front/src/modules/side-panel/hooks/__tests__/useOpenRecordsInSidePanel.test.tsx b/packages/twenty-front/src/modules/side-panel/hooks/__tests__/useOpenRecordsInSidePanel.test.tsxnew file mode 100644index 00000000000..4a1fb78540a--- /dev/null+++ b/packages/twenty-front/src/modules/side-panel/hooks/__tests__/useOpenRecordsInSidePanel.test.tsx@@ -0,0 +1,242 @@+import { renderHook } from '@testing-library/react';+import { type createStore } from 'jotai';+import { act } from 'react';+import { ContextStorePageType, SidePanelPages } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { contextStoreCurrentPageTypeComponentState } from '@/context-store/states/contextStoreCurrentPageTypeComponentState';+import { contextStoreCurrentViewTypeComponentState } from '@/context-store/states/contextStoreCurrentViewTypeComponentState';+import { ContextStoreViewType } from '@/context-store/types/ContextStoreViewType';+import { useOpenRecordsInSidePanel } from '@/side-panel/hooks/useOpenRecordsInSidePanel';+import { viewableRecordsViewIdComponentState } from '@/side-panel/pages/records-page/states/viewableRecordsViewIdComponentState';+import { type ViewWithRelations } from '@/views/types/ViewWithRelations';+import { ViewKey, ViewType } from '~/generated-metadata/graphql';+import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';+import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';+import { setTestViewsInMetadataStore } from '~/testing/utils/setTestViewsInMetadataStore';++const navigateSidePanelMenuMock = jest.fn();++jest.mock('@/side-panel/hooks/useSidePanelMenu', () => ({+ useSidePanelMenu: () => ({+ navigateSidePanelMenu: navigateSidePanelMenuMock,+ openSidePanelMenu: jest.fn(),+ closeSidePanelMenu: jest.fn(),+ toggleSidePanelMenu: jest.fn(),+ }),+}));++const companyObjectMetadataItem = getMockObjectMetadataItemOrThrow('company');++const INDEX_VIEW_ID = '11111111-1111-4111-8111-111111111111';+const KANBAN_VIEW_ID = '22222222-2222-4222-8222-222222222222';+const WIDGET_VIEW_ID = '33333333-3333-4333-8333-333333333333';++const buildCompanyView = (view: Partial<ViewWithRelations>) =>+ ({+ name: 'All Companies',+ icon: 'IconBuildingSkyscraper',+ objectMetadataId: companyObjectMetadataItem.id,+ type: ViewType.TABLE,+ key: null,+ position: 0,+ isActive: true,+ ...view,+ }) as ViewWithRelations;++const indexView = buildCompanyView({+ id: INDEX_VIEW_ID,+ name: 'All Companies',+ key: ViewKey.INDEX,+ position: 1,+});++const kanbanView = buildCompanyView({+ id: KANBAN_VIEW_ID,+ name: 'Companies by Stage',+ type: ViewType.KANBAN,+ position: 2,+});++const widgetView = buildCompanyView({+ id: WIDGET_VIEW_ID,+ name: 'Dashboard widget view',+ type: ViewType.KANBAN_WIDGET,+ position: 0,+});++const renderOpenRecordsInSidePanel = (views: ViewWithRelations[]) => {+ let store: ReturnType<typeof createStore> | undefined;++ const Wrapper = getJestMetadataAndApolloMocksWrapper({+ apolloMocks: [],+ onInitializeJotaiStore: (initializedStore) => {+ store = initializedStore;+ setTestViewsInMetadataStore(initializedStore, views);+ },+ });++ const { result } = renderHook(() => useOpenRecordsInSidePanel(), {+ wrapper: Wrapper,+ });++ if (!isDefined(store)) {+ throw new Error('Jotai store was not initialized');+ }++ return { result, store };+};++const getNavigatedPageId = () =>+ navigateSidePanelMenuMock.mock.calls[0][0].pageId as string;++describe('useOpenRecordsInSidePanel', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it('should open the requested view when the view id is user-facing', () => {+ const { result, store } = renderOpenRecordsInSidePanel([+ indexView,+ kanbanView,+ ]);++ act(() => {+ result.current.openRecordsInSidePanel({+ objectNameSingular: companyObjectMetadataItem.nameSingular,+ viewId: KANBAN_VIEW_ID,+ });+ });++ expect(navigateSidePanelMenuMock).toHaveBeenCalledWith(+ expect.objectContaining({+ page: SidePanelPages.ViewRecords,+ pageTitle: 'Companies by Stage',+ }),+ );++ const pageId = getNavigatedPageId();++ expect(+ store.get(+ viewableRecordsViewIdComponentState.atomFamily({+ instanceId: pageId,+ }),+ ),+ ).toBe(KANBAN_VIEW_ID);+ expect(+ store.get(+ contextStoreCurrentViewTypeComponentState.atomFamily({+ instanceId: pageId,+ }),+ ),+ ).toBe(ContextStoreViewType.Kanban);+ });++ it('should fall back to the index view when no view id is given', () => {+ const { result, store } = renderOpenRecordsInSidePanel([+ kanbanView,+ indexView,+ ]);++ act(() => {+ result.current.openRecordsInSidePanel({+ objectNameSingular: companyObjectMetadataItem.nameSingular,+ });+ });++ const pageId = getNavigatedPageId();++ expect(+ store.get(+ viewableRecordsViewIdComponentState.atomFamily({+ instanceId: pageId,+ }),+ ),+ ).toBe(INDEX_VIEW_ID);+ expect(+ store.get(+ contextStoreCurrentViewTypeComponentState.atomFamily({+ instanceId: pageId,+ }),+ ),+ ).toBe(ContextStoreViewType.Table);+ });++ it('should fall back to the first view by position when the object has no index view', () => {+ const { result, store } = renderOpenRecordsInSidePanel([+ buildCompanyView({+ id: KANBAN_VIEW_ID,+ type: ViewType.KANBAN,+ position: 5,+ }),+ buildCompanyView({ id: INDEX_VIEW_ID, position: 2 }),+ ]);++ act(() => {+ result.current.openRecordsInSidePanel({+ objectNameSingular: companyObjectMetadataItem.nameSingular,+ });+ });++ expect(+ store.get(+ viewableRecordsViewIdComponentState.atomFamily({+ instanceId: getNavigatedPageId(),+ }),+ ),+ ).toBe(INDEX_VIEW_ID);+ });++ it('should fall back to the index view when the view id points at a widget-backing view', () => {+ const { result, store } = renderOpenRecordsInSidePanel([+ widgetView,+ indexView,+ ]);++ act(() => {+ result.current.openRecordsInSidePanel({+ objectNameSingular: companyObjectMetadataItem.nameSingular,+ viewId: WIDGET_VIEW_ID,+ });+ });++ expect(+ store.get(+ viewableRecordsViewIdComponentState.atomFamily({+ instanceId: getNavigatedPageId(),+ }),+ ),+ ).toBe(INDEX_VIEW_ID);+ });++ it('should throw when the object has no user-facing view', () => {+ const { result } = renderOpenRecordsInSidePanel([widgetView]);++ expect(() =>+ result.current.openRecordsInSidePanel({+ objectNameSingular: companyObjectMetadataItem.nameSingular,+ }),+ ).toThrow('No view found for object company');++ expect(navigateSidePanelMenuMock).not.toHaveBeenCalled();+ });++ it('should publish the index page type as the artifact browsing context', () => {+ const { result, store } = renderOpenRecordsInSidePanel([indexView]);++ act(() => {+ result.current.openRecordsInSidePanel({+ objectNameSingular: companyObjectMetadataItem.nameSingular,+ });+ });++ expect(+ store.get(+ contextStoreCurrentPageTypeComponentState.atomFamily({+ instanceId: getNavigatedPageId(),+ }),+ ),+ ).toBe(ContextStorePageType.Index);+ });+});diff --git a/packages/twenty-front/src/modules/side-panel/hooks/__tests__/useShouldShrinkSidePanelFromFullWidth.test.tsx b/packages/twenty-front/src/modules/side-panel/hooks/__tests__/useShouldShrinkSidePanelFromFullWidth.test.tsxdeleted file mode 100644index 6ef0984d3f8..00000000000--- a/packages/twenty-front/src/modules/side-panel/hooks/__tests__/useShouldShrinkSidePanelFromFullWidth.test.tsx+++ /dev/null@@ -1,72 +0,0 @@-import { renderHook } from '@testing-library/react';-import { Provider as JotaiProvider } from 'jotai';-import { type ReactNode } from 'react';--import { shouldContinueAiChatInSidePanelState } from '@/ai/states/shouldContinueAiChatInSidePanelState';-import { useShouldShrinkSidePanelFromFullWidth } from '@/side-panel/hooks/useShouldShrinkSidePanelFromFullWidth';-import {- jotaiStore,- resetJotaiStore,-} from '@/ui/utilities/state/jotai/jotaiStore';--const useReducedMotionMock = jest.fn();--jest.mock('framer-motion', () => ({- useReducedMotion: () => useReducedMotionMock(),-}));--const Wrapper = ({ children }: { children: ReactNode }) => (- <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>-);--describe('useShouldShrinkSidePanelFromFullWidth', () => {- beforeEach(() => {- jest.clearAllMocks();- resetJotaiStore();- useReducedMotionMock.mockReturnValue(false);- });-- it('should shrink from full width when arriving from the workspace setup page', () => {- jotaiStore.set(shouldContinueAiChatInSidePanelState.atom, true);-- const { result } = renderHook(- () => useShouldShrinkSidePanelFromFullWidth(),- { wrapper: Wrapper },- );-- expect(result.current).toBe(true);- });-- it('should keep the marker untouched so the handoff effect can consume it', () => {- jotaiStore.set(shouldContinueAiChatInSidePanelState.atom, true);-- renderHook(() => useShouldShrinkSidePanelFromFullWidth(), {- wrapper: Wrapper,- });-- expect(jotaiStore.get(shouldContinueAiChatInSidePanelState.atom)).toBe(- true,- );- });-- it('should not shrink from full width when not arriving from the workspace setup page', () => {- const { result } = renderHook(- () => useShouldShrinkSidePanelFromFullWidth(),- { wrapper: Wrapper },- );-- expect(result.current).toBe(false);- });-- it('should not shrink from full width when reduced motion is preferred', () => {- useReducedMotionMock.mockReturnValue(true);- jotaiStore.set(shouldContinueAiChatInSidePanelState.atom, true);-- const { result } = renderHook(- () => useShouldShrinkSidePanelFromFullWidth(),- { wrapper: Wrapper },- );-- expect(result.current).toBe(false);- });-});diff --git a/packages/twenty-front/src/modules/side-panel/hooks/useOpenAskAiPageInSidePanel.ts b/packages/twenty-front/src/modules/side-panel/hooks/useOpenAskAiPageInSidePanel.tsindex 3ba62589733..2780df3eccd 100644--- a/packages/twenty-front/src/modules/side-panel/hooks/useOpenAskAiPageInSidePanel.ts+++ b/packages/twenty-front/src/modules/side-panel/hooks/useOpenAskAiPageInSidePanel.ts@@ -8,6 +8,7 @@ import { useCallback } from 'react';import { SidePanelPages } from 'twenty-shared/types';import { IconSparkles } from 'twenty-ui/icon';import { v4 } from 'uuid';+import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';export const useOpenAskAiPageInSidePanel = () => {const { navigateSidePanelMenu } = useSidePanelMenu();@@ -22,6 +23,10 @@ export const useOpenAskAiPageInSidePanel = () => {}: {resetNavigationStack?: boolean;} = {}) => {+ if (isCurrentPathAiChatPage()) {+ return;+ }+const shouldReset =resetNavigationStack !== undefined? resetNavigationStackdiff --git a/packages/twenty-front/src/modules/side-panel/hooks/useOpenRecordsInSidePanel.ts b/packages/twenty-front/src/modules/side-panel/hooks/useOpenRecordsInSidePanel.tsnew file mode 100644index 00000000000..82816dfacd3--- /dev/null+++ b/packages/twenty-front/src/modules/side-panel/hooks/useOpenRecordsInSidePanel.ts@@ -0,0 +1,114 @@+import { useStore } from 'jotai';+import { useCallback } from 'react';+import { ContextStorePageType, SidePanelPages } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';+import { useIcons } from 'twenty-ui/icon';+import { v4 } from 'uuid';++import { contextStoreCurrentObjectMetadataItemIdComponentState } from '@/context-store/states/contextStoreCurrentObjectMetadataItemIdComponentState';+import { contextStoreCurrentPageTypeComponentState } from '@/context-store/states/contextStoreCurrentPageTypeComponentState';+import { contextStoreCurrentViewIdComponentState } from '@/context-store/states/contextStoreCurrentViewIdComponentState';+import { contextStoreCurrentViewTypeComponentState } from '@/context-store/states/contextStoreCurrentViewTypeComponentState';+import { getContextStoreViewType } from '@/context-store/utils/getContextStoreViewType';+import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';+import { useSidePanelMenu } from '@/side-panel/hooks/useSidePanelMenu';+import { viewableRecordsObjectMetadataIdComponentState } from '@/side-panel/pages/records-page/states/viewableRecordsObjectMetadataIdComponentState';+import { viewableRecordsViewIdComponentState } from '@/side-panel/pages/records-page/states/viewableRecordsViewIdComponentState';+import { viewsFromObjectMetadataItemFamilySelector } from '@/views/states/selectors/viewsFromObjectMetadataItemFamilySelector';+import { ViewKey } from '~/generated-metadata/graphql';++export const useOpenRecordsInSidePanel = () => {+ const store = useStore();+ const { getIcon } = useIcons();+ const { navigateSidePanelMenu } = useSidePanelMenu();++ const openRecordsInSidePanel = useCallback(+ ({+ objectNameSingular,+ viewId,+ }: {+ objectNameSingular: string;+ viewId?: string;+ }) => {+ const objectMetadataItem = store.get(+ objectMetadataItemFamilySelector.selectorFamily({+ objectName: objectNameSingular,+ objectNameType: 'singular',+ }),+ );++ if (!isDefined(objectMetadataItem)) {+ throw new Error(+ `Object with singular name ${objectNameSingular} not found, cannot open its records in the side panel.`,+ );+ }++ const objectViews = store.get(+ viewsFromObjectMetadataItemFamilySelector.selectorFamily({+ objectMetadataItemId: objectMetadataItem.id,+ }),+ );++ const resolvedView =+ objectViews.find((view) => view.id === viewId) ??+ objectViews.find((view) => view.key === ViewKey.INDEX) ??+ objectViews[0];++ if (!isDefined(resolvedView)) {+ throw new Error(+ `No view found for object ${objectNameSingular}, cannot open its records in the side panel.`,+ );+ }++ const pageComponentInstanceId = v4();++ store.set(+ viewableRecordsObjectMetadataIdComponentState.atomFamily({+ instanceId: pageComponentInstanceId,+ }),+ objectMetadataItem.id,+ );+ store.set(+ viewableRecordsViewIdComponentState.atomFamily({+ instanceId: pageComponentInstanceId,+ }),+ resolvedView.id,+ );++ store.set(+ contextStoreCurrentObjectMetadataItemIdComponentState.atomFamily({+ instanceId: pageComponentInstanceId,+ }),+ objectMetadataItem.id,+ );+ store.set(+ contextStoreCurrentViewIdComponentState.atomFamily({+ instanceId: pageComponentInstanceId,+ }),+ resolvedView.id,+ );+ store.set(+ contextStoreCurrentPageTypeComponentState.atomFamily({+ instanceId: pageComponentInstanceId,+ }),+ ContextStorePageType.Index,+ );+ store.set(+ contextStoreCurrentViewTypeComponentState.atomFamily({+ instanceId: pageComponentInstanceId,+ }),+ getContextStoreViewType(resolvedView.type),+ );++ navigateSidePanelMenu({+ page: SidePanelPages.ViewRecords,+ pageTitle: resolvedView.name,+ pageIcon: getIcon(resolvedView.icon),+ pageId: pageComponentInstanceId,+ });+ },+ [store, getIcon, navigateSidePanelMenu],+ );++ return { openRecordsInSidePanel };+};diff --git a/packages/twenty-front/src/modules/side-panel/hooks/useShouldShrinkSidePanelFromFullWidth.ts b/packages/twenty-front/src/modules/side-panel/hooks/useShouldShrinkSidePanelFromFullWidth.tsdeleted file mode 100644index 3f9b80af46c..00000000000--- a/packages/twenty-front/src/modules/side-panel/hooks/useShouldShrinkSidePanelFromFullWidth.ts+++ /dev/null@@ -1,16 +0,0 @@-import { useReducedMotion } from 'framer-motion';-import { useStore } from 'jotai';-import { useState } from 'react';--import { shouldContinueAiChatInSidePanelState } from '@/ai/states/shouldContinueAiChatInSidePanelState';--export const useShouldShrinkSidePanelFromFullWidth = () => {- const store = useStore();- const shouldReduceMotion = useReducedMotion();-- const [isContinuingChatFromWorkspaceSetup] = useState(() =>- store.get(shouldContinueAiChatInSidePanelState.atom),- );-- return isContinuingChatFromWorkspaceSetup && !shouldReduceMotion;-};diff --git a/packages/twenty-front/src/modules/side-panel/pages/ai-chat-threads/components/SidePanelAiChatThreadsPage.tsx b/packages/twenty-front/src/modules/side-panel/pages/ai-chat-threads/components/SidePanelAiChatThreadsPage.tsxdeleted file mode 100644index b13cdd4c0bd..00000000000--- a/packages/twenty-front/src/modules/side-panel/pages/ai-chat-threads/components/SidePanelAiChatThreadsPage.tsx+++ /dev/null@@ -1,15 +0,0 @@-import { AiChatThreadsList } from '@/ai/components/AiChatThreadsList';-import { styled } from '@linaria/react';--const StyledContainer = styled.div`- height: 100%;- width: 100%;-`;--export const SidePanelAiChatThreadsPage = () => {- return (- <StyledContainer>- <AiChatThreadsList />- </StyledContainer>- );-};diff --git a/packages/twenty-front/src/modules/side-panel/pages/records-page/components/SidePanelRecordsPage.tsx b/packages/twenty-front/src/modules/side-panel/pages/records-page/components/SidePanelRecordsPage.tsxnew file mode 100644index 00000000000..454053fdc1e--- /dev/null+++ b/packages/twenty-front/src/modules/side-panel/pages/records-page/components/SidePanelRecordsPage.tsx@@ -0,0 +1,60 @@+import { styled } from '@linaria/react';+import { isDefined } from 'twenty-shared/utils';++import { PageLayoutEditModeProviderContext } from '@/page-layout/contexts/PageLayoutEditModeContext';+import { PageLayoutComponentInstanceContext } from '@/page-layout/states/contexts/PageLayoutComponentInstanceContext';+import { RecordTableWidgetRendererContent } from '@/page-layout/widgets/record-table/components/RecordTableWidgetRendererContent';+import { viewableRecordsObjectMetadataIdComponentState } from '@/side-panel/pages/records-page/states/viewableRecordsObjectMetadataIdComponentState';+import { viewableRecordsViewIdComponentState } from '@/side-panel/pages/records-page/states/viewableRecordsViewIdComponentState';+import { SidePanelPageComponentInstanceContext } from '@/side-panel/states/contexts/SidePanelPageComponentInstanceContext';+import { useComponentInstanceStateContext } from '@/ui/utilities/state/component-state/hooks/useComponentInstanceStateContext';+import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';++const StyledContainer = styled.div`+ display: flex;+ flex-direction: column;+ height: 100%;+ overflow: hidden;+ width: 100%;+`;++export const SidePanelRecordsPage = () => {+ const viewableRecordsObjectMetadataId = useAtomComponentStateValue(+ viewableRecordsObjectMetadataIdComponentState,+ );+ const viewableRecordsViewId = useAtomComponentStateValue(+ viewableRecordsViewIdComponentState,+ );+ const sidePanelPageInstanceContext = useComponentInstanceStateContext(+ SidePanelPageComponentInstanceContext,+ );++ if (!isDefined(viewableRecordsObjectMetadataId)) {+ throw new Error('Object metadata id is not defined');+ }++ if (!isDefined(viewableRecordsViewId)) {+ throw new Error('View id is not defined');+ }++ const widgetInstanceId = `side-panel-records-${sidePanelPageInstanceContext?.instanceId}`;++ return (+ <StyledContainer>+ {/* The widget machinery is shared with dashboards, whose page provides+ the page layout scope and edit mode context; the side panel hosts a+ synthetic layout scope and is never in edit mode. */}+ <PageLayoutComponentInstanceContext.Provider+ value={{ instanceId: widgetInstanceId }}+ >+ <PageLayoutEditModeProviderContext value={{ isInEditMode: false }}>+ <RecordTableWidgetRendererContent+ objectMetadataId={viewableRecordsObjectMetadataId}+ viewId={viewableRecordsViewId}+ widgetId={widgetInstanceId}+ />+ </PageLayoutEditModeProviderContext>+ </PageLayoutComponentInstanceContext.Provider>+ </StyledContainer>+ );+};diff --git a/packages/twenty-front/src/modules/side-panel/pages/records-page/states/viewableRecordsObjectMetadataIdComponentState.ts b/packages/twenty-front/src/modules/side-panel/pages/records-page/states/viewableRecordsObjectMetadataIdComponentState.tsnew file mode 100644index 00000000000..694b64f0b08--- /dev/null+++ b/packages/twenty-front/src/modules/side-panel/pages/records-page/states/viewableRecordsObjectMetadataIdComponentState.ts@@ -0,0 +1,9 @@+import { SidePanelPageComponentInstanceContext } from '@/side-panel/states/contexts/SidePanelPageComponentInstanceContext';+import { createAtomComponentState } from '@/ui/utilities/state/jotai/utils/createAtomComponentState';++export const viewableRecordsObjectMetadataIdComponentState =+ createAtomComponentState<string | null>({+ key: 'side-panel/viewable-record-index-object-metadata-id',+ defaultValue: null,+ componentInstanceContext: SidePanelPageComponentInstanceContext,+ });diff --git a/packages/twenty-front/src/modules/side-panel/pages/records-page/states/viewableRecordsViewIdComponentState.ts b/packages/twenty-front/src/modules/side-panel/pages/records-page/states/viewableRecordsViewIdComponentState.tsnew file mode 100644index 00000000000..c346c444bd7--- /dev/null+++ b/packages/twenty-front/src/modules/side-panel/pages/records-page/states/viewableRecordsViewIdComponentState.ts@@ -0,0 +1,10 @@+import { SidePanelPageComponentInstanceContext } from '@/side-panel/states/contexts/SidePanelPageComponentInstanceContext';+import { createAtomComponentState } from '@/ui/utilities/state/jotai/utils/createAtomComponentState';++export const viewableRecordsViewIdComponentState = createAtomComponentState<+ string | null+>({+ key: 'side-panel/viewable-record-index-view-id',+ defaultValue: null,+ componentInstanceContext: SidePanelPageComponentInstanceContext,+});diff --git a/packages/twenty-front/src/pages/onboarding/WorkspaceSetup.tsx b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsxsimilarity index 56%rename from packages/twenty-front/src/pages/onboarding/WorkspaceSetup.tsxrename to packages/twenty-front/src/pages/ai-chat/AiChatPage.tsxindex 9967db40155..d3bdfc14c56 100644--- a/packages/twenty-front/src/pages/onboarding/WorkspaceSetup.tsx+++ b/packages/twenty-front/src/pages/ai-chat/AiChatPage.tsx@@ -1,19 +1,20 @@import { styled } from '@linaria/react';-import { useLingui } from '@lingui/react/macro';import { Navigate } from 'react-router-dom';import { themeCssVariables } from 'twenty-ui/theme-constants';-import { AiChatMessageListPreambleContext } from '@/ai/contexts/AiChatMessageListPreambleContext';+import { AiChatPageCloseAskAiPanelEffect } from '@/ai/components/AiChatPageCloseAskAiPanelEffect';+import { AiChatPageContinueInSidePanelEffect } from '@/ai/components/AiChatPageContinueInSidePanelEffect';+import { AiChatPageHeader } from '@/ai/components/AiChatPageHeader';+import { AiChatPageThreadUrlSyncEffect } from '@/ai/components/AiChatPageThreadUrlSyncEffect';import { AiChatTab } from '@/ai/components/AiChatTab';-import { currentUserState } from '@/auth/states/currentUserState';-import { isOnboardingAiChatEnabledState } from '@/client-config/states/isOnboardingAiChatEnabledState';+import { AiChatMessageListPreambleContext } from '@/ai/contexts/AiChatMessageListPreambleContext';import { useDefaultHomePagePath } from '@/navigation/hooks/useDefaultHomePagePath';import { WorkspaceSetupChatPreamble } from '@/onboarding/components/WorkspaceSetupChatPreamble';-import { WorkspaceSetupHeader } from '@/onboarding/components/WorkspaceSetupHeader';import { WorkspaceSetupChatKickoffEffect } from '@/onboarding/effect-components/WorkspaceSetupChatKickoffEffect';-import { WorkspaceSetupChatSidePanelHandoffEffect } from '@/onboarding/effect-components/WorkspaceSetupChatSidePanelHandoffEffect';import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';+import { FeatureFlagKey } from '~/generated-metadata/graphql';const PANEL_CORNER_RADIUS_DERIVED_FROM_THEME_SCALE = `calc(${themeCssVariables.border.radius.md} + ${themeCssVariables.spacing[1]})`;@@ -29,45 +30,47 @@ const StyledPanel = styled.div`overflow: hidden;`;-const StyledContent = styled.div`+const StyledCenteredChatContainer = styled.div`display: flex;flex: 1;flex-direction: column;+ margin: 0 auto;+ max-width: 768px;min-height: 0;- overflow-x: clip;width: 100%;`;-export const WorkspaceSetup = () => {- const { t } = useLingui();+export const AiChatPage = () => {const { defaultHomePagePath } = useDefaultHomePagePath();- const currentUser = useAtomStateValue(currentUserState);- const isOnboardingAiChatEnabled = useAtomStateValue(- isOnboardingAiChatEnabledState,+ const isAiChatPageEnabled = useIsFeatureEnabled(+ FeatureFlagKey.IS_AI_CHAT_PAGE_ENABLED,);const shouldOpenAiChatAfterOnboarding = useAtomStateValue(shouldOpenAiChatAfterOnboardingState,);- if (!isOnboardingAiChatEnabled || currentUser?.isWorkspaceCreator !== true) {+ if (!isAiChatPageEnabled && !shouldOpenAiChatAfterOnboarding) {return <Navigate to={defaultHomePagePath} replace />;}- const title = shouldOpenAiChatAfterOnboarding ? t`Onboarding` : t`Ask AI`;- const preamble = shouldOpenAiChatAfterOnboarding ? (- <WorkspaceSetupChatPreamble />- ) : null;-return (<StyledPanel>- <WorkspaceSetupHeader title={title} />- <StyledContent>- <WorkspaceSetupChatSidePanelHandoffEffect />- {shouldOpenAiChatAfterOnboarding && <WorkspaceSetupChatKickoffEffect />}- <AiChatMessageListPreambleContext.Provider value={preamble}>+ <AiChatPageThreadUrlSyncEffect />+ <AiChatPageCloseAskAiPanelEffect />+ <AiChatPageContinueInSidePanelEffect />+ {shouldOpenAiChatAfterOnboarding && <WorkspaceSetupChatKickoffEffect />}+ <AiChatPageHeader isOnboarding={shouldOpenAiChatAfterOnboarding} />+ <StyledCenteredChatContainer>+ <AiChatMessageListPreambleContext.Provider+ value={+ shouldOpenAiChatAfterOnboarding ? (+ <WorkspaceSetupChatPreamble />+ ) : null+ }+ ><AiChatTab /></AiChatMessageListPreambleContext.Provider>- </StyledContent>+ </StyledCenteredChatContainer></StyledPanel>);};diff --git a/packages/twenty-front/src/pages/onboarding/__tests__/WorkspaceSetup.test.tsx b/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatPage.test.tsxsimilarity index 55%rename from packages/twenty-front/src/pages/onboarding/__tests__/WorkspaceSetup.test.tsxrename to packages/twenty-front/src/pages/ai-chat/__tests__/AiChatPage.test.tsxindex c6623a0f271..9a028af3ccf 100644--- a/packages/twenty-front/src/pages/onboarding/__tests__/WorkspaceSetup.test.tsx+++ b/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatPage.test.tsx@@ -6,16 +6,13 @@ import { type ReactNode } from 'react';import { SOURCE_LOCALE } from 'twenty-shared/translations';import { shouldContinueAiChatInSidePanelState } from '@/ai/states/shouldContinueAiChatInSidePanelState';-import { currentUserState } from '@/auth/states/currentUserState';-import { isOnboardingAiChatEnabledState } from '@/client-config/states/isOnboardingAiChatEnabledState';import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';import {jotaiStore,resetJotaiStore,} from '@/ui/utilities/state/jotai/jotaiStore';import { messages } from '~/locales/generated/en';-import { WorkspaceSetup } from '~/pages/onboarding/WorkspaceSetup';-import { mockedUserData } from '~/testing/mock-data/users';+import { AiChatPage } from '~/pages/ai-chat/AiChatPage';i18n.load({ [SOURCE_LOCALE]: messages });i18n.activate(SOURCE_LOCALE);@@ -26,6 +23,12 @@ jest.mock('@/navigation/hooks/useDefaultHomePagePath', () => ({useDefaultHomePagePath: () => ({ defaultHomePagePath }),}));+let isAiChatPageEnabled = true;++jest.mock('@/workspace/hooks/useIsFeatureEnabled', () => ({+ useIsFeatureEnabled: () => isAiChatPageEnabled,+}));+jest.mock('@/ai/components/AiChatTab', () => {const { useContext } = jest.requireActual('react');const { AiChatMessageListPreambleContext } = jest.requireActual(@@ -40,10 +43,21 @@ jest.mock('@/ai/components/AiChatTab', () => {};});-jest.mock('@/onboarding/components/WorkspaceSetupHeader', () => ({- WorkspaceSetupHeader: ({ title }: { title: string }) => (- <div data-testid="header-title">{title}</div>- ),+const headerMock = jest.fn();++jest.mock('@/ai/components/AiChatPageHeader', () => ({+ AiChatPageHeader: ({ isOnboarding }: { isOnboarding: boolean }) => {+ headerMock(isOnboarding);+ return null;+ },+}));++jest.mock('@/ai/components/AiChatPageThreadUrlSyncEffect', () => ({+ AiChatPageThreadUrlSyncEffect: () => null,+}));++jest.mock('@/ai/components/AiChatPageCloseAskAiPanelEffect', () => ({+ AiChatPageCloseAskAiPanelEffect: () => null,}));jest.mock('@/onboarding/components/WorkspaceSetupChatPreamble', () => ({@@ -67,75 +81,63 @@ jest.mock('react-router-dom', () => ({},}));-const setIsOnboardingAiChatEnabled = (value: boolean) => {- jotaiStore.set(isOnboardingAiChatEnabledState.atom, value);-};--const setIsWorkspaceCreator = (value: boolean) => {- jotaiStore.set(currentUserState.atom, {- ...mockedUserData,- isWorkspaceCreator: value,- });-};-const Wrapper = ({ children }: { children: ReactNode }) => (<JotaiProvider store={jotaiStore}><I18nProvider i18n={i18n}>{children}</I18nProvider></JotaiProvider>);-describe('WorkspaceSetup', () => {+describe('AiChatPage', () => {beforeEach(() => {+ jest.clearAllMocks();sessionStorage.clear();resetJotaiStore();- mockNavigate.mockClear();- setIsWorkspaceCreator(true);+ isAiChatPageEnabled = true;});it('should dress the chat for onboarding when the post-onboarding hint is set', () => {- setIsOnboardingAiChatEnabled(true);jotaiStore.set(shouldOpenAiChatAfterOnboardingState.atom, true);- const { getByTestId } = render(<WorkspaceSetup />, { wrapper: Wrapper });+ const { getByTestId } = render(<AiChatPage />, { wrapper: Wrapper });expect(getByTestId('ai-chat-tab')).toBeInTheDocument();expect(getByTestId('preamble')).toBeInTheDocument();- expect(getByTestId('header-title')).toHaveTextContent('Onboarding');+ expect(getByTestId('chat-kickoff-effect')).toBeInTheDocument();+ expect(headerMock).toHaveBeenCalledWith(true);});it('should render a plain chat when the post-onboarding hint is not set', () => {- setIsOnboardingAiChatEnabled(true);-- const { getByTestId, queryByTestId } = render(<WorkspaceSetup />, {+ const { getByTestId, queryByTestId } = render(<AiChatPage />, {wrapper: Wrapper,});expect(getByTestId('ai-chat-tab')).toBeInTheDocument();expect(queryByTestId('preamble')).not.toBeInTheDocument();- expect(getByTestId('header-title')).toHaveTextContent('Ask AI');+ expect(queryByTestId('chat-kickoff-effect')).not.toBeInTheDocument();+ expect(headerMock).toHaveBeenCalledWith(false);});- it('should mount the chat kickoff effect when the post-onboarding hint is set', () => {- setIsOnboardingAiChatEnabled(true);+ it('should host the onboarding chat even when the chat page flag is disabled', () => {+ isAiChatPageEnabled = false;jotaiStore.set(shouldOpenAiChatAfterOnboardingState.atom, true);- const { getByTestId } = render(<WorkspaceSetup />, { wrapper: Wrapper });+ const { getByTestId } = render(<AiChatPage />, { wrapper: Wrapper });- expect(getByTestId('chat-kickoff-effect')).toBeInTheDocument();+ expect(getByTestId('ai-chat-tab')).toBeInTheDocument();+ expect(mockNavigate).not.toHaveBeenCalled();});- it('should not mount the chat kickoff effect when the post-onboarding hint is not set', () => {- setIsOnboardingAiChatEnabled(true);+ it('should redirect home when the flag is disabled outside onboarding', () => {+ isAiChatPageEnabled = false;- const { queryByTestId } = render(<WorkspaceSetup />, { wrapper: Wrapper });+ const { queryByTestId } = render(<AiChatPage />, { wrapper: Wrapper });- expect(queryByTestId('chat-kickoff-effect')).not.toBeInTheDocument();+ expect(queryByTestId('ai-chat-tab')).not.toBeInTheDocument();+ expect(mockNavigate).toHaveBeenCalledWith(defaultHomePagePath);});it('should mark the chat for side panel continuation while mounted', () => {- setIsOnboardingAiChatEnabled(true);-- const { unmount } = render(<WorkspaceSetup />, { wrapper: Wrapper });+ const { unmount } = render(<AiChatPage />, { wrapper: Wrapper });expect(jotaiStore.get(shouldContinueAiChatInSidePanelState.atom)).toBe(true,@@ -147,33 +149,4 @@ describe('WorkspaceSetup', () => {false,);});-- it('should not mark the chat for side panel continuation when the onboarding ai chat is disabled', () => {- setIsOnboardingAiChatEnabled(false);-- render(<WorkspaceSetup />, { wrapper: Wrapper });-- expect(jotaiStore.get(shouldContinueAiChatInSidePanelState.atom)).toBe(- false,- );- });-- it('should redirect home when the onboarding ai chat is disabled', () => {- setIsOnboardingAiChatEnabled(false);-- const { queryByTestId } = render(<WorkspaceSetup />, { wrapper: Wrapper });-- expect(queryByTestId('ai-chat-tab')).not.toBeInTheDocument();- expect(mockNavigate).toHaveBeenCalledWith(defaultHomePagePath);- });-- it('should redirect home for an invitee', () => {- setIsOnboardingAiChatEnabled(true);- setIsWorkspaceCreator(false);-- const { queryByTestId } = render(<WorkspaceSetup />, { wrapper: Wrapper });-- expect(queryByTestId('ai-chat-tab')).not.toBeInTheDocument();- expect(mockNavigate).toHaveBeenCalledWith(defaultHomePagePath);- });});diff --git a/packages/twenty-front/src/utils/getCurrentHistoryEntryState.ts b/packages/twenty-front/src/utils/getCurrentHistoryEntryState.tsnew file mode 100644index 00000000000..e151ff762ac--- /dev/null+++ b/packages/twenty-front/src/utils/getCurrentHistoryEntryState.ts@@ -0,0 +1,13 @@+export const getCurrentHistoryEntryState = (): unknown => {+ const historyState: unknown = window.history.state;++ if (+ typeof historyState !== 'object' ||+ historyState === null ||+ !('usr' in historyState)+ ) {+ return null;+ }++ return historyState.usr;+};diff --git a/packages/twenty-front/src/utils/isAiChatPath.ts b/packages/twenty-front/src/utils/isAiChatPath.tsnew file mode 100644index 00000000000..295bc6cadc4--- /dev/null+++ b/packages/twenty-front/src/utils/isAiChatPath.ts@@ -0,0 +1,6 @@+import { AppPath } from 'twenty-shared/types';++import { isMatchingPathname } from '~/utils/isMatchingPathname';++export const isAiChatPath = (pathname: string) =>+ isMatchingPathname(pathname, AppPath.AiChat);diff --git a/packages/twenty-front/src/utils/isCurrentPathAiChatPage.ts b/packages/twenty-front/src/utils/isCurrentPathAiChatPage.tsnew file mode 100644index 00000000000..8b31a9c2ac8--- /dev/null+++ b/packages/twenty-front/src/utils/isCurrentPathAiChatPage.ts@@ -0,0 +1,4 @@+import { isAiChatPath } from '~/utils/isAiChatPath';++export const isCurrentPathAiChatPage = () =>+ isAiChatPath(window.location.pathname);diff --git a/packages/twenty-front/src/utils/isMatchingLocation.ts b/packages/twenty-front/src/utils/isMatchingLocation.tsindex 9c63a072fa5..bfe3db2c82a 100644--- a/packages/twenty-front/src/utils/isMatchingLocation.ts+++ b/packages/twenty-front/src/utils/isMatchingLocation.ts@@ -1,26 +1,10 @@-import { type Location, matchPath } from 'react-router-dom';+import { type Location } from 'react-router-dom';-import { isNonEmptyString } from '@sniptt/guards';import { type AppBasePath } from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';--const addTrailingSlash = (path: string) =>- path.endsWith('/') ? path : path + '/';--const getConstructedPath = (path: string, basePath?: AppBasePath) => {- if (!isNonEmptyString(basePath)) return path;-- return addTrailingSlash(basePath) + path;-};+import { isMatchingPathname } from '~/utils/isMatchingPathname';export const isMatchingLocation = (location: Location,path: string,basePath?: AppBasePath,-): boolean => {- const match = matchPath(- getConstructedPath(path, basePath),- location.pathname,- );- return isDefined(match);-};+): boolean => isMatchingPathname(location.pathname, path, basePath);diff --git a/packages/twenty-front/src/utils/isMatchingPathname.ts b/packages/twenty-front/src/utils/isMatchingPathname.tsnew file mode 100644index 00000000000..463db4f21bf--- /dev/null+++ b/packages/twenty-front/src/utils/isMatchingPathname.ts@@ -0,0 +1,21 @@+import { matchPath } from 'react-router-dom';++import { isNonEmptyString } from '@sniptt/guards';+import { type AppBasePath } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++const addTrailingSlash = (path: string) =>+ path.endsWith('/') ? path : path + '/';++const getConstructedPath = (path: string, basePath?: AppBasePath) => {+ if (!isNonEmptyString(basePath)) return path;++ return addTrailingSlash(basePath) + path;+};++export const isMatchingPathname = (+ pathname: string,+ path: string,+ basePath?: AppBasePath,+): boolean =>+ isDefined(matchPath(getConstructedPath(path, basePath), pathname));diff --git a/packages/twenty-sdk/project.json b/packages/twenty-sdk/project.jsonindex aee221c7968..9a5adc20738 100644--- a/packages/twenty-sdk/project.json+++ b/packages/twenty-sdk/project.json@@ -90,7 +90,7 @@"executor": "nx:run-commands","cache": true,"dependsOn": ["^build"],- "inputs": ["{projectRoot}/src/sdk/**/*"],+ "inputs": ["{projectRoot}/src/sdk/**/*", "^production"],"outputs": ["{projectRoot}/dist/billing","{projectRoot}/dist/define",diff --git a/packages/twenty-server/src/engine/core-modules/feature-flag/constants/public-feature-flag.const.ts b/packages/twenty-server/src/engine/core-modules/feature-flag/constants/public-feature-flag.const.tsindex 73e14f61a5c..efdeeaff6f5 100644--- a/packages/twenty-server/src/engine/core-modules/feature-flag/constants/public-feature-flag.const.ts+++ b/packages/twenty-server/src/engine/core-modules/feature-flag/constants/public-feature-flag.const.ts@@ -13,6 +13,15 @@ export type PublicFeatureFlag = {};export const PUBLIC_FEATURE_FLAGS: PublicFeatureFlag[] = [+ {+ key: FeatureFlagKey.IS_AI_CHAT_PAGE_ENABLED,+ metadata: {+ label: 'Full-Page AI Chat',+ description:+ 'Open the AI chat as a full page, with the records it surfaces appearing in the side panel',+ icon: 'IconSparkles',+ },+ },{key: FeatureFlagKey.IS_CALENDAR_WEEK_VIEW_ENABLED,metadata: {diff --git a/packages/twenty-server/src/engine/twenty-orm/entity-manager/workspace-entity-manager.spec.ts b/packages/twenty-server/src/engine/twenty-orm/entity-manager/workspace-entity-manager.spec.tsindex 8ec193d46ca..3f6975d4b2a 100644--- a/packages/twenty-server/src/engine/twenty-orm/entity-manager/workspace-entity-manager.spec.ts+++ b/packages/twenty-server/src/engine/twenty-orm/entity-manager/workspace-entity-manager.spec.ts@@ -239,6 +239,7 @@ describe('WorkspaceEntityManager', () => {'test-entity': 'test-entity-id',},featureFlagsMap: {+ IS_AI_CHAT_PAGE_ENABLED: false,IS_APP_CLAIMING_ENABLED: false,IS_UNIQUE_INDEXES_ENABLED: false,IS_JSON_FILTER_ENABLED: false,diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.tsindex 13f94e92181..e15cf77a0dc 100644--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts@@ -20,6 +20,11 @@ export const seedFeatureFlags = async ({.into(`${schemaName}.${tableName}`, ['key', 'workspaceId', 'value']).orIgnore().values([+ {+ key: FeatureFlagKey.IS_AI_CHAT_PAGE_ENABLED,+ workspaceId: workspaceId,+ value: true,+ },{key: FeatureFlagKey.IS_APP_CLAIMING_ENABLED,workspaceId: workspaceId,diff --git a/packages/twenty-shared/src/types/AppPath.ts b/packages/twenty-shared/src/types/AppPath.tsindex 561eb7a9748..c6840c94803 100644--- a/packages/twenty-shared/src/types/AppPath.ts+++ b/packages/twenty-shared/src/types/AppPath.ts@@ -17,7 +17,7 @@ export enum AppPath {BookCall = '/book-call',// Onboarded- WorkspaceSetup = '/workspace-setup',+ AiChat = '/chat/:threadId?',Index = '/',TasksPage = '/objects/tasks',OpportunitiesPage = '/objects/opportunities',diff --git a/packages/twenty-shared/src/types/FeatureFlagKey.ts b/packages/twenty-shared/src/types/FeatureFlagKey.tsindex 2c6521e3f3f..d9beb16545c 100644--- a/packages/twenty-shared/src/types/FeatureFlagKey.ts+++ b/packages/twenty-shared/src/types/FeatureFlagKey.ts@@ -1,4 +1,5 @@export enum FeatureFlagKey {+ IS_AI_CHAT_PAGE_ENABLED = 'IS_AI_CHAT_PAGE_ENABLED',IS_APP_CLAIMING_ENABLED = 'IS_APP_CLAIMING_ENABLED',IS_UNIQUE_INDEXES_ENABLED = 'IS_UNIQUE_INDEXES_ENABLED',IS_JSON_FILTER_ENABLED = 'IS_JSON_FILTER_ENABLED',diff --git a/packages/twenty-shared/src/types/SidePanelPages.ts b/packages/twenty-shared/src/types/SidePanelPages.tsindex d75d6f20424..be79defc3b0 100644--- a/packages/twenty-shared/src/types/SidePanelPages.ts+++ b/packages/twenty-shared/src/types/SidePanelPages.ts@@ -1,6 +1,7 @@export enum SidePanelPages {CommandMenuDisplay = 'command-menu-display',ViewRecord = 'view-record',+ ViewRecords = 'view-records',MergeRecords = 'merge-records',UpdateRecords = 'update-records',EditRichText = 'edit-rich-text',@@ -13,7 +14,6 @@ export enum SidePanelPages {WorkflowRunStepView = 'workflow-run-step-view',SearchRecords = 'search-records',AskAI = 'ask-ai',- ViewPreviousAiChats = 'view-previous-ai-chats',PageLayoutDashboardWidgetTypeSelect = 'page-layout-dashboard-widget-type-select',PageLayoutTabSettings = 'page-layout-tab-settings',DashboardChartSettings = 'dashboard-chart-settings',