The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Center the full page AI chat and suggest prompts from the browsed page (#25016)
Félix Malfaitcf838acdc83a
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsxindex 3c9d6bea73d..0ffba71abde 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx@@ -18,6 +18,7 @@ import { AiChatSkeletonLoader } from '@/ai/components/internal/AiChatSkeletonLoaimport { SendMessageButton } from '@/ai/components/internal/SendMessageButton';import { useAgentChatModelId } from '@/ai/hooks/useAgentChatModelId';import { useAiChatEditor } from '@/ai/hooks/useAiChatEditor';+import { useIsAiChatComposerCentered } from '@/ai/hooks/useIsAiChatComposerCentered';import { useAiModelOptions } from '@/ai/hooks/useAiModelOptions';import { useHasReachedAiChatCreditsCap } from '@/ai/hooks/useHasReachedAiChatCreditsCap';import { useWorkspaceAiModelAvailability } from '@/ai/hooks/useWorkspaceAiModelAvailability';@@ -96,6 +97,28 @@ const StyledEditorWrapper = styled.div<{ isMobile: boolean }>`}`;+// Collapsing this spacer is what slides the composer from the middle of an+// empty page down to the bottom once the conversation starts.+const StyledComposerBottomSpacer = styled.div`+ flex-basis: 0;+ flex-grow: 0;+ flex-shrink: 0;+ transition-duration: calc(${themeCssVariables.animation.duration.fast} * 1s);+ transition-property: flex-grow;+ transition-timing-function: ease-out;++ // Only the collapse is animated: the composer becomes centered again on a+ // thread switch, where sliding it back up would trail the content change.+ &.is-centered {+ flex-grow: 1;+ transition-property: none;+ }++ @media (prefers-reduced-motion: reduce) {+ transition-property: none;+ }+`;+const StyledButtonsContainer = styled.div`align-items: center;display: flex;@@ -118,6 +141,7 @@ const StyledRightButtonsContainer = styled.div`export const AiChatEditorSection = () => {const { t } = useLingui();const isMobile = useIsMobile();+ const isComposerCentered = useIsAiChatComposerCentered();const hasReachedAiChatCreditsCap = useHasReachedAiChatCreditsCap();const { enabledModels } = useWorkspaceAiModelAvailability();const hasNoEnabledModels = enabledModels.length === 0;@@ -147,7 +171,7 @@ export const AiChatEditorSection = () => {return (<><AiChatEditorFocusEffect editor={editor} />- <AiChatEmptyState editor={editor} />+ <AiChatEmptyState editor={editor} isCentered={isComposerCentered} /><AiChatStandaloneError /><AiChatSkeletonLoader />@@ -194,6 +218,9 @@ export const AiChatEditorSection = () => {</StyledInputBox>)}</StyledInputArea>+ <StyledComposerBottomSpacer+ className={isComposerCentered ? 'is-centered' : undefined}+ /></>);};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsxindex b04d5414243..3ed1682796f 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatEmptyState.tsx@@ -1,21 +1,8 @@import { styled } from '@linaria/react';import { type Editor } from '@tiptap/react';-import { isDefined } from 'twenty-shared/utils';import { AiChatSuggestedPrompts } from '@/ai/components/suggested-prompts/AiChatSuggestedPrompts';-import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';-import { agentChatErrorComponentFamilyState } from '@/ai/states/agentChatErrorComponentFamilyState';-import { agentChatHasMessageComponentSelector } from '@/ai/states/selectors/agentChatHasMessageComponentSelector';-import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkComponentFamilyState';-import { agentChatIsStreamingComponentFamilyState } from '@/ai/states/agentChatIsStreamingComponentFamilyState';-import { agentChatMessagesLoadingState } from '@/ai/states/agentChatMessagesLoadingState';-import { agentChatThreadsLoadingState } from '@/ai/states/agentChatThreadsLoadingState';-import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';-import { skipMessagesSkeletonUntilLoadedState } from '@/ai/states/skipMessagesSkeletonUntilLoadedState';-import { useIsMobile } from '@/ui/utilities/responsive/hooks/useIsMobile';-import { useAtomComponentFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateValue';-import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { useShouldShowAiChatEmptyState } from '@/ai/hooks/useShouldShowAiChatEmptyState';const StyledEmptyState = styled.div`display: flex;@@ -26,58 +13,22 @@ const StyledEmptyState = styled.div`type AiChatEmptyStateProps = {editor: Editor | null;+ isCentered?: boolean;};-export const AiChatEmptyState = ({ editor }: AiChatEmptyStateProps) => {- const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);- const agentChatError = useAtomComponentFamilyStateValue(- agentChatErrorComponentFamilyState,- { threadId: currentAiChatThread },- );- const agentChatIsAwaitingFirstChunk = useAtomComponentFamilyStateValue(- agentChatIsAwaitingFirstChunkComponentFamilyState,- { threadId: currentAiChatThread },- );- const agentChatIsStreaming = useAtomComponentFamilyStateValue(- agentChatIsStreamingComponentFamilyState,- { threadId: currentAiChatThread },- );- const agentChatThreadsLoading = useAtomStateValue(- agentChatThreadsLoadingState,- );- const agentChatMessagesLoading = useAtomStateValue(- agentChatMessagesLoadingState,- );- const skipMessagesSkeletonUntilLoaded = useAtomStateValue(- skipMessagesSkeletonUntilLoadedState,- );-- const hasMessages = useAtomComponentSelectorValue(- agentChatHasMessageComponentSelector,- );-- const isMobile = useIsMobile();-- const isOnNewChatSlot =- currentAiChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY;- const skeletonShowing =- (agentChatThreadsLoading && isOnNewChatSlot) ||- (agentChatMessagesLoading && !skipMessagesSkeletonUntilLoaded);- const shouldRender =- !isMobile &&- !hasMessages &&- !isDefined(agentChatError) &&- !skeletonShowing &&- !agentChatIsAwaitingFirstChunk &&- !agentChatIsStreaming;+export const AiChatEmptyState = ({+ editor,+ isCentered = false,+}: AiChatEmptyStateProps) => {+ const shouldShowAiChatEmptyState = useShouldShowAiChatEmptyState();- if (!shouldRender) {+ if (!shouldShowAiChatEmptyState) {return null;}return (<StyledEmptyState>- <AiChatSuggestedPrompts editor={editor} />+ <AiChatSuggestedPrompts editor={editor} isCentered={isCentered} /></StyledEmptyState>);};diff --git a/packages/twenty-front/src/modules/ai/components/suggested-prompts/AiChatSuggestedPrompts.tsx b/packages/twenty-front/src/modules/ai/components/suggested-prompts/AiChatSuggestedPrompts.tsxindex f71a4d97a32..4bd478d8a59 100644--- a/packages/twenty-front/src/modules/ai/components/suggested-prompts/AiChatSuggestedPrompts.tsx+++ b/packages/twenty-front/src/modules/ai/components/suggested-prompts/AiChatSuggestedPrompts.tsx@@ -2,35 +2,57 @@ import { styled } from '@linaria/react';import { t } from '@lingui/core/macro';import { useLingui } from '@lingui/react/macro';import { type Editor } from '@tiptap/react';-import { LightButton } from 'twenty-ui/input';+import { Button, LightButton } from 'twenty-ui/input';import { themeCssVariables } from 'twenty-ui/theme-constants';+import { serializePlainTextAsAdvancedTextEditorDocument } from '@/advanced-text-editor/utils/serializePlainTextAsAdvancedTextEditorDocument';+import { getAiChatSuggestedPrompts } from '@/ai/components/suggested-prompts/getAiChatSuggestedPrompts';+import { useAiChatSuggestedPromptsContext } from '@/ai/hooks/useAiChatSuggestedPromptsContext';import {- DEFAULT_SUGGESTED_PROMPTS,- type SuggestedPrompt,-} from '@/ai/components/suggested-prompts/default-suggested-prompts';+ AGENT_CHAT_NEW_THREAD_DRAFT_KEY,+ agentChatDraftsByThreadIdState,+} from '@/ai/states/agentChatDraftsByThreadIdState';import { agentChatInputState } from '@/ai/states/agentChatInputState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { type SuggestedPrompt } from '@/ai/types/SuggestedPrompt';+import { dispatchAgentChatSendMessageEvent } from '@/ai/utils/dispatchAgentChatSendMessageEvent';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';-const StyledContainer = styled.div`+const StyledContainer = styled.div<{ isCentered: boolean }>`+ align-items: ${({ isCentered }) => (isCentered ? 'center' : 'stretch')};display: flex;flex-direction: column;- gap: ${themeCssVariables.spacing[2]};- padding: ${themeCssVariables.spacing[2]};+ gap: ${({ isCentered }) =>+ isCentered ? themeCssVariables.spacing[4] : themeCssVariables.spacing[2]};+ padding: ${({ isCentered }) =>+ isCentered ? themeCssVariables.spacing[4] : themeCssVariables.spacing[2]};`;-const StyledTitle = styled.div`+const StyledTitle = styled.div<{ isCentered: boolean }>`align-content: center;color: ${themeCssVariables.font.color.primary};display: grid;- font-size: ${themeCssVariables.font.size.sm};- font-weight: ${themeCssVariables.font.weight.medium};- height: 24px;+ font-size: ${({ isCentered }) =>+ isCentered+ ? themeCssVariables.font.size.xl+ : themeCssVariables.font.size.sm};+ font-weight: ${({ isCentered }) =>+ isCentered+ ? themeCssVariables.font.weight.semiBold+ : themeCssVariables.font.weight.medium};+ height: ${({ isCentered }) => (isCentered ? 'auto' : '24px')};padding: 0 ${themeCssVariables.spacing[2]};+ text-align: ${({ isCentered }) => (isCentered ? 'center' : 'left')};`;-const StyledSuggestedPromptButtonContainer = styled.div`- align-self: flex-start;+const StyledPromptList = styled.div<{ isCentered: boolean }>`+ align-items: ${({ isCentered }) => (isCentered ? 'center' : 'flex-start')};+ display: flex;+ flex-direction: ${({ isCentered }) => (isCentered ? 'row' : 'column')};+ flex-wrap: wrap;+ gap: ${themeCssVariables.spacing[2]};+ justify-content: center;`;const pickRandom = <T,>(items: T[]): T =>@@ -38,17 +60,41 @@ const pickRandom = <T,>(items: T[]): T =>type AiChatSuggestedPromptsProps = {editor: Editor | null;+ isCentered?: boolean;};export const AiChatSuggestedPrompts = ({editor,+ isCentered = false,}: AiChatSuggestedPromptsProps) => {const { t: resolveMessage } = useLingui();const setAgentChatInput = useSetAtomState(agentChatInputState);+ const setAgentChatDraftsByThreadId = useSetAtomState(+ agentChatDraftsByThreadIdState,+ );+ const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);+ const aiChatSuggestedPromptsContext = useAiChatSuggestedPromptsContext();++ const suggestedPrompts = getAiChatSuggestedPrompts(+ aiChatSuggestedPromptsContext,+ );++ const handleClick = (suggestedPrompt: SuggestedPrompt) => {+ const text = resolveMessage(pickRandom(suggestedPrompt.prompts));++ if (suggestedPrompt.mode === 'SEND') {+ // Sending reads the draft rather than the editor, so it has to be written+ // before the event is dispatched.+ setAgentChatDraftsByThreadId((previousDrafts) => ({+ ...previousDrafts,+ [currentAiChatThread ?? AGENT_CHAT_NEW_THREAD_DRAFT_KEY]:+ serializePlainTextAsAdvancedTextEditorDocument(text),+ }));+ dispatchAgentChatSendMessageEvent();+ editor?.commands.clearContent();- const handleClick = (prompt: SuggestedPrompt) => {- const picked = pickRandom(prompt.prefillPrompts);- const text = resolveMessage(picked);+ return;+ }setAgentChatInput(text);editor?.commands.setContent({@@ -59,18 +105,31 @@ export const AiChatSuggestedPrompts = ({};return (- <StyledContainer>- <StyledTitle>{t`What can I help you with?`}</StyledTitle>- {DEFAULT_SUGGESTED_PROMPTS.map((prompt) => (- <StyledSuggestedPromptButtonContainer key={prompt.id}>- <LightButton- Icon={prompt.Icon}- title={resolveMessage(prompt.label)}- accent="secondary"- onClick={() => handleClick(prompt)}- />- </StyledSuggestedPromptButtonContainer>- ))}+ <StyledContainer isCentered={isCentered}>+ <StyledTitle isCentered={isCentered}>+ {t`What can I help you with?`}+ </StyledTitle>+ <StyledPromptList isCentered={isCentered}>+ {suggestedPrompts.map((suggestedPrompt) =>+ isCentered ? (+ <Button+ key={suggestedPrompt.id}+ Icon={suggestedPrompt.Icon}+ title={resolveMessage(suggestedPrompt.label)}+ variant="secondary"+ onClick={() => handleClick(suggestedPrompt)}+ />+ ) : (+ <LightButton+ key={suggestedPrompt.id}+ Icon={suggestedPrompt.Icon}+ title={resolveMessage(suggestedPrompt.label)}+ accent="secondary"+ onClick={() => handleClick(suggestedPrompt)}+ />+ ),+ )}+ </StyledPromptList></StyledContainer>);};diff --git a/packages/twenty-front/src/modules/ai/components/suggested-prompts/__tests__/getAiChatSuggestedPrompts.test.ts b/packages/twenty-front/src/modules/ai/components/suggested-prompts/__tests__/getAiChatSuggestedPrompts.test.tsnew file mode 100644index 00000000000..4d164be36e6--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/suggested-prompts/__tests__/getAiChatSuggestedPrompts.test.ts@@ -0,0 +1,60 @@+import { CoreObjectNameSingular } from 'twenty-shared/types';++import { getAiChatSuggestedPrompts } from '@/ai/components/suggested-prompts/getAiChatSuggestedPrompts';++const getPromptIds = (...args: Parameters<typeof getAiChatSuggestedPrompts>) =>+ getAiChatSuggestedPrompts(...args).map(({ id }) => id);++describe('getAiChatSuggestedPrompts', () => {+ it('should offer the capability prompt when the user is not browsing anything', () => {+ expect(getPromptIds(null)).toContain('capabilities');+ });++ it('should send the capability prompt straight away rather than prefilling it', () => {+ const capabilitiesPrompt = getAiChatSuggestedPrompts(null).find(+ ({ id }) => id === 'capabilities',+ );++ expect(capabilitiesPrompt?.mode).toBe('SEND');+ });++ it('should offer view prompts while browsing a list', () => {+ expect(+ getPromptIds({+ browsingContextType: 'listView',+ objectNameSingular: CoreObjectNameSingular.Company,+ }),+ ).toEqual(['summarize-view', 'filter-view', 'create-record-in-view']);+ });++ it('should offer workflow prompts on a workflow record', () => {+ expect(+ getPromptIds({+ browsingContextType: 'recordPage',+ objectNameSingular: CoreObjectNameSingular.Workflow,+ }),+ ).toEqual(['explain-workflow', 'add-workflow-step', 'check-workflow-runs']);+ });++ it('should offer company prompts on a company record', () => {+ expect(+ getPromptIds({+ browsingContextType: 'recordPage',+ objectNameSingular: CoreObjectNameSingular.Company,+ }),+ ).toContain('research-company');+ });++ it('should fall back to object-agnostic prompts on a custom object record', () => {+ expect(+ getPromptIds({+ browsingContextType: 'recordPage',+ objectNameSingular: 'petCareAgreement',+ }),+ ).toEqual([+ 'summarize-record',+ 'add-note-to-record',+ 'create-task-for-record',+ ]);+ });+});diff --git a/packages/twenty-front/src/modules/ai/components/suggested-prompts/contextual-suggested-prompts.ts b/packages/twenty-front/src/modules/ai/components/suggested-prompts/contextual-suggested-prompts.tsnew file mode 100644index 00000000000..b621c745c8b--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/suggested-prompts/contextual-suggested-prompts.ts@@ -0,0 +1,115 @@+import { msg } from '@lingui/core/macro';+import { CoreObjectNameSingular } from 'twenty-shared/types';+import {+ IconCheckbox,+ IconFilter,+ IconMail,+ IconNotes,+ IconPlus,+ IconSearch,+ IconSparkles,+ IconTerminal,+} from 'twenty-ui/icon';++import { type SuggestedPrompt } from '@/ai/types/SuggestedPrompt';++export const LIST_VIEW_SUGGESTED_PROMPTS: SuggestedPrompt[] = [+ {+ id: 'summarize-view',+ label: msg`Summarize this view`,+ Icon: IconSparkles,+ mode: 'SEND',+ prompts: [+ msg`Summarize the records in this view and point out anything that needs attention.`,+ ],+ },+ {+ id: 'filter-view',+ label: msg`Filter this view`,+ Icon: IconFilter,+ prompts: [msg`Filter this view to only show `],+ },+ {+ id: 'create-record-in-view',+ label: msg`Create a record`,+ Icon: IconPlus,+ prompts: [msg`Create a new record in this view. Details: `],+ },+];++export const RECORD_PAGE_SUGGESTED_PROMPTS: SuggestedPrompt[] = [+ {+ id: 'summarize-record',+ label: msg`Summarize this record`,+ Icon: IconSparkles,+ mode: 'SEND',+ prompts: [msg`Summarize this record and its recent activity.`],+ },+ {+ id: 'add-note-to-record',+ label: msg`Add a note`,+ Icon: IconNotes,+ prompts: [msg`Add a note to this record: `],+ },+ {+ id: 'create-task-for-record',+ label: msg`Create a task`,+ Icon: IconCheckbox,+ prompts: [msg`Create a task for this record: `],+ },+];++// Only objects whose record page deserves its own wording need an entry: everything+// else, custom objects included, falls back to RECORD_PAGE_SUGGESTED_PROMPTS.+export const RECORD_PAGE_SUGGESTED_PROMPTS_BY_OBJECT_NAME_SINGULAR: Record<+ string,+ SuggestedPrompt[]+> = {+ [CoreObjectNameSingular.Workflow]: [+ {+ id: 'explain-workflow',+ label: msg`Explain this workflow`,+ Icon: IconSparkles,+ mode: 'SEND',+ prompts: [msg`Explain what this workflow does, step by step.`],+ },+ {+ id: 'add-workflow-step',+ label: msg`Add a step`,+ Icon: IconPlus,+ prompts: [msg`Add a step to this workflow that `],+ },+ {+ id: 'check-workflow-runs',+ label: msg`Check recent runs`,+ Icon: IconTerminal,+ mode: 'SEND',+ prompts: [+ msg`Check this workflow's recent runs and tell me whether any failed and why.`,+ ],+ },+ ],+ [CoreObjectNameSingular.Company]: [+ {+ id: 'research-company',+ label: msg`Research this company`,+ Icon: IconSearch,+ mode: 'SEND',+ prompts: [+ msg`Research this company and summarize what they do, how big they are and any recent news.`,+ ],+ },+ {+ id: 'draft-company-email',+ label: msg`Draft an email`,+ Icon: IconMail,+ prompts: [msg`Draft an email to this company about `],+ },+ {+ id: 'create-task-for-company',+ label: msg`Create a task`,+ Icon: IconCheckbox,+ prompts: [msg`Create a task for this company: `],+ },+ ],+};diff --git a/packages/twenty-front/src/modules/ai/components/suggested-prompts/default-suggested-prompts.ts b/packages/twenty-front/src/modules/ai/components/suggested-prompts/default-suggested-prompts.tsindex 02a2802a87b..28cc595f3b2 100644--- a/packages/twenty-front/src/modules/ai/components/suggested-prompts/default-suggested-prompts.ts+++ b/packages/twenty-front/src/modules/ai/components/suggested-prompts/default-suggested-prompts.ts@@ -1,24 +1,14 @@-import type { MessageDescriptor } from '@lingui/core';import { msg } from '@lingui/core/macro';-import {- type IconComponent,- IconPlus,- IconSettingsAutomation,-} from 'twenty-ui/icon';+import { IconPlus, IconSettingsAutomation, IconSparkles } from 'twenty-ui/icon';-export type SuggestedPrompt = {- id: string;- label: MessageDescriptor;- Icon: IconComponent;- prefillPrompts: MessageDescriptor[];-};+import { type SuggestedPrompt } from '@/ai/types/SuggestedPrompt';export const DEFAULT_SUGGESTED_PROMPTS: SuggestedPrompt[] = [{id: 'workflow',label: msg`Create a workflow`,Icon: IconSettingsAutomation,- prefillPrompts: [+ prompts: [msg`When a deal's stage changes to Closed Won, create a task assigned to the deal owner, due 7 days after the close date, with title "Post-sale check-in" and the company name in the description.`,msg`When a new lead is created with source "Website", assign it to the sales rep whose territory (by region/country) matches the lead's address; if no match, assign to the team lead.`,msg`When any deal with amount over $100,000 has its stage or amount updated, send a notification to the sales channel with the deal name, company, new stage, amount and owner.`,@@ -28,10 +18,17 @@ export const DEFAULT_SUGGESTED_PROMPTS: SuggestedPrompt[] = [id: 'record',label: msg`Create a record`,Icon: IconPlus,- prefillPrompts: [+ prompts: [msg`Add a new company we're in touch with (e.g. name, website, industry). Details: `,msg`Create a new contact and link them to a company. Details: `,msg`Log a new deal (company, amount, stage, expected close). Details: `,],},+ {+ id: 'capabilities',+ label: msg`See what I can do`,+ Icon: IconSparkles,+ mode: 'SEND',+ prompts: [msg`What can you do?`],+ },];diff --git a/packages/twenty-front/src/modules/ai/components/suggested-prompts/getAiChatSuggestedPrompts.ts b/packages/twenty-front/src/modules/ai/components/suggested-prompts/getAiChatSuggestedPrompts.tsnew file mode 100644index 00000000000..2eb33086eae--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/suggested-prompts/getAiChatSuggestedPrompts.ts@@ -0,0 +1,30 @@+import { isDefined } from 'twenty-shared/utils';++import {+ LIST_VIEW_SUGGESTED_PROMPTS,+ RECORD_PAGE_SUGGESTED_PROMPTS,+ RECORD_PAGE_SUGGESTED_PROMPTS_BY_OBJECT_NAME_SINGULAR,+} from '@/ai/components/suggested-prompts/contextual-suggested-prompts';+import { DEFAULT_SUGGESTED_PROMPTS } from '@/ai/components/suggested-prompts/default-suggested-prompts';+import { type AiChatSuggestedPromptsContext } from '@/ai/types/AiChatSuggestedPromptsContext';+import { type SuggestedPrompt } from '@/ai/types/SuggestedPrompt';++export const getAiChatSuggestedPrompts = (+ aiChatSuggestedPromptsContext: AiChatSuggestedPromptsContext | null,+): SuggestedPrompt[] => {+ if (!isDefined(aiChatSuggestedPromptsContext)) {+ return DEFAULT_SUGGESTED_PROMPTS;+ }++ const { browsingContextType, objectNameSingular } =+ aiChatSuggestedPromptsContext;++ if (browsingContextType === 'listView') {+ return LIST_VIEW_SUGGESTED_PROMPTS;+ }++ return (+ RECORD_PAGE_SUGGESTED_PROMPTS_BY_OBJECT_NAME_SINGULAR[objectNameSingular] ??+ RECORD_PAGE_SUGGESTED_PROMPTS+ );+};diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiChatSuggestedPromptsContext.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiChatSuggestedPromptsContext.test.tsxnew file mode 100644index 00000000000..7d8ff8e4604--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiChatSuggestedPromptsContext.test.tsx@@ -0,0 +1,121 @@+import { renderHook } from '@testing-library/react';+import { Provider as JotaiProvider } from 'jotai';+import { type ReactNode } from 'react';+import { ContextStorePageType } from 'twenty-shared/types';++import { useAiChatSuggestedPromptsContext } from '@/ai/hooks/useAiChatSuggestedPromptsContext';+import { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainContextStoreInstanceId';+import { contextStoreCurrentObjectMetadataItemIdComponentState } from '@/context-store/states/contextStoreCurrentObjectMetadataItemIdComponentState';+import { contextStoreCurrentPageTypeComponentState } from '@/context-store/states/contextStoreCurrentPageTypeComponentState';+import { contextStoreCurrentViewTypeComponentState } from '@/context-store/states/contextStoreCurrentViewTypeComponentState';+import { ContextStoreViewType } from '@/context-store/types/ContextStoreViewType';+import {+ jotaiStore,+ resetJotaiStore,+} from '@/ui/utilities/state/jotai/jotaiStore';+import { getTestEnrichedObjectMetadataItemsMock } from '~/testing/utils/getTestEnrichedObjectMetadataItemsMock';+import { setTestObjectMetadataItemsInMetadataStore } from '~/testing/utils/setTestObjectMetadataItemsInMetadataStore';++const objectMetadataItems = getTestEnrichedObjectMetadataItemsMock();++const getObjectMetadataItemId = (nameSingular: string) =>+ objectMetadataItems.find((item) => item.nameSingular === nameSingular)?.id;++const Wrapper = ({ children }: { children: ReactNode }) => (+ <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>+);++const setMainContextStore = ({+ pageType = null,+ viewType = null,+ objectNameSingular,+}: {+ pageType?: ContextStorePageType | null;+ viewType?: ContextStoreViewType | null;+ objectNameSingular?: string;+}) => {+ const instanceId = MAIN_CONTEXT_STORE_INSTANCE_ID;++ jotaiStore.set(+ contextStoreCurrentPageTypeComponentState.atomFamily({ instanceId }),+ pageType,+ );+ jotaiStore.set(+ contextStoreCurrentViewTypeComponentState.atomFamily({ instanceId }),+ viewType,+ );+ jotaiStore.set(+ contextStoreCurrentObjectMetadataItemIdComponentState.atomFamily({+ instanceId,+ }),+ objectNameSingular === undefined+ ? undefined+ : getObjectMetadataItemId(objectNameSingular),+ );+};++describe('useAiChatSuggestedPromptsContext', () => {+ beforeEach(() => {+ resetJotaiStore();+ setTestObjectMetadataItemsInMetadataStore(jotaiStore, objectMetadataItems);+ });++ it('should report the record being browsed in the main page', () => {+ setMainContextStore({+ pageType: ContextStorePageType.Record,+ objectNameSingular: 'company',+ });++ const { result } = renderHook(() => useAiChatSuggestedPromptsContext(), {+ wrapper: Wrapper,+ });++ expect(result.current).toEqual({+ browsingContextType: 'recordPage',+ objectNameSingular: 'company',+ });+ });++ it('should report a custom object record just like a standard one', () => {+ setMainContextStore({+ pageType: ContextStorePageType.Record,+ objectNameSingular: 'petCareAgreement',+ });++ const { result } = renderHook(() => useAiChatSuggestedPromptsContext(), {+ wrapper: Wrapper,+ });++ expect(result.current).toEqual({+ browsingContextType: 'recordPage',+ objectNameSingular: 'petCareAgreement',+ });+ });++ it('should report the list being browsed in the main page', () => {+ setMainContextStore({+ pageType: ContextStorePageType.Index,+ viewType: ContextStoreViewType.Table,+ objectNameSingular: 'workflow',+ });++ const { result } = renderHook(() => useAiChatSuggestedPromptsContext(), {+ wrapper: Wrapper,+ });++ expect(result.current).toEqual({+ browsingContextType: 'listView',+ objectNameSingular: 'workflow',+ });+ });++ it('should report nothing when the main page is not about an object', () => {+ setMainContextStore({ pageType: ContextStorePageType.Settings });++ const { result } = renderHook(() => useAiChatSuggestedPromptsContext(), {+ wrapper: Wrapper,+ });++ expect(result.current).toBeNull();+ });+});diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useIsAiChatComposerCentered.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useIsAiChatComposerCentered.test.tsxnew file mode 100644index 00000000000..fb12f20e229--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useIsAiChatComposerCentered.test.tsx@@ -0,0 +1,86 @@+import { renderHook } from '@testing-library/react';+import { Provider as JotaiProvider } from 'jotai';+import { type ReactNode } from 'react';++import { AI_CHAT_SURFACE } from '@/ai/constants/AiChatSurface';+import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';+import { AiChatMessageListPreambleContext } from '@/ai/contexts/AiChatMessageListPreambleContext';+import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';+import { useIsAiChatComposerCentered } from '@/ai/hooks/useIsAiChatComposerCentered';+import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';+import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { type AiChatSurface } from '@/ai/types/AiChatSurface';+import {+ jotaiStore,+ resetJotaiStore,+} from '@/ui/utilities/state/jotai/jotaiStore';++const INSTANCE_ID = 'aiChatComposerCenteredTest';+const THREAD_ID = 'thread-1';++const renderForSurface = ({+ surface = AI_CHAT_SURFACE.PAGE,+ preamble = null,+}: {+ surface?: AiChatSurface;+ preamble?: ReactNode;+} = {}) => {+ const Wrapper = ({ children }: { children: ReactNode }) => (+ <JotaiProvider store={jotaiStore}>+ <AgentChatComponentInstanceContext.Provider+ value={{ instanceId: INSTANCE_ID }}+ >+ <AiChatSurfaceContext.Provider value={surface}>+ <AiChatMessageListPreambleContext.Provider value={preamble}>+ {children}+ </AiChatMessageListPreambleContext.Provider>+ </AiChatSurfaceContext.Provider>+ </AgentChatComponentInstanceContext.Provider>+ </JotaiProvider>+ );++ return renderHook(() => useIsAiChatComposerCentered(), { wrapper: Wrapper });+};++describe('useIsAiChatComposerCentered', () => {+ beforeEach(() => {+ resetJotaiStore();+ jotaiStore.set(currentAiChatThreadState.atom, THREAD_ID);+ jotaiStore.set(agentChatDisplayedThreadState.atom, THREAD_ID);+ });++ it('should center the composer on an empty full page chat', () => {+ const { result } = renderForSurface();++ expect(result.current).toBe(true);+ });++ it('should not center the composer in the side panel', () => {+ const { result } = renderForSurface({+ surface: AI_CHAT_SURFACE.SIDE_PANEL,+ });++ expect(result.current).toBe(false);+ });++ it('should not center the composer once the thread has messages', () => {+ jotaiStore.set(+ agentChatMessagesComponentFamilyState.atomFamily({+ instanceId: INSTANCE_ID,+ familyKey: { threadId: THREAD_ID },+ }),+ [{ id: 'message-1', role: 'user', parts: [] }],+ );++ const { result } = renderForSurface();++ expect(result.current).toBe(false);+ });++ it('should not center the composer while a preamble owns the intro', () => {+ const { result } = renderForSurface({ preamble: <div /> });++ expect(result.current).toBe(false);+ });+});diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatSuggestedPromptsContext.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatSuggestedPromptsContext.tsnew file mode 100644index 00000000000..f0919f0629b--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatSuggestedPromptsContext.ts@@ -0,0 +1,63 @@+import { isDefined } from 'twenty-shared/utils';++import { type AiChatSuggestedPromptsContext } from '@/ai/types/AiChatSuggestedPromptsContext';+import { getAiChatBrowsingContextType } from '@/ai/utils/getAiChatBrowsingContextType';+import { getAiChatContextStoreInstanceId } from '@/ai/utils/getAiChatContextStoreInstanceId';+import { contextStoreCurrentObjectMetadataItemIdComponentState } from '@/context-store/states/contextStoreCurrentObjectMetadataItemIdComponentState';+import { contextStoreCurrentPageTypeComponentState } from '@/context-store/states/contextStoreCurrentPageTypeComponentState';+import { contextStoreCurrentViewTypeComponentState } from '@/context-store/states/contextStoreCurrentViewTypeComponentState';+import { objectMetadataItemsSelector } from '@/object-metadata/states/objectMetadataItemsSelector';+import { isSidePanelOpenedState } from '@/side-panel/states/isSidePanelOpenedState';+import { sidePanelNavigationStackState } from '@/side-panel/states/sidePanelNavigationStackState';+import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';++// The reactive counterpart of useGetBrowsingContext, which reads the store+// imperatively at send time and so cannot drive what the chat renders.+export const useAiChatSuggestedPromptsContext =+ (): AiChatSuggestedPromptsContext | null => {+ const isSidePanelOpened = useAtomStateValue(isSidePanelOpenedState);+ const sidePanelNavigationStack = useAtomStateValue(+ sidePanelNavigationStackState,+ );++ const contextStoreInstanceId = getAiChatContextStoreInstanceId({+ isOnAiChatPage: isCurrentPathAiChatPage(),+ isSidePanelOpened,+ currentSidePanelPageId: sidePanelNavigationStack.at(-1)?.pageId,+ });++ const contextStoreCurrentPageType = useAtomComponentStateValue(+ contextStoreCurrentPageTypeComponentState,+ contextStoreInstanceId,+ );+ const contextStoreCurrentViewType = useAtomComponentStateValue(+ contextStoreCurrentViewTypeComponentState,+ contextStoreInstanceId,+ );+ const contextStoreCurrentObjectMetadataItemId = useAtomComponentStateValue(+ contextStoreCurrentObjectMetadataItemIdComponentState,+ contextStoreInstanceId,+ );++ const objectMetadataItems = useAtomStateValue(objectMetadataItemsSelector);++ const objectMetadataItem = objectMetadataItems.find(+ (item) => item.id === contextStoreCurrentObjectMetadataItemId,+ );++ const browsingContextType = getAiChatBrowsingContextType({+ pageType: contextStoreCurrentPageType,+ viewType: contextStoreCurrentViewType,+ });++ if (!isDefined(objectMetadataItem) || !isDefined(browsingContextType)) {+ return null;+ }++ return {+ browsingContextType,+ objectNameSingular: objectMetadataItem.nameSingular,+ };+ };diff --git a/packages/twenty-front/src/modules/ai/hooks/useBrowsingContext.ts b/packages/twenty-front/src/modules/ai/hooks/useBrowsingContext.tsindex efb984d58ec..632005a4f6e 100644--- a/packages/twenty-front/src/modules/ai/hooks/useBrowsingContext.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useBrowsingContext.ts@@ -3,7 +3,8 @@ import { useCallback } from 'react';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 { getAiChatBrowsingContextType } from '@/ai/utils/getAiChatBrowsingContextType';+import { getAiChatContextStoreInstanceId } from '@/ai/utils/getAiChatContextStoreInstanceId';import { isSidePanelOpenedState } from '@/side-panel/states/isSidePanelOpenedState';import { sidePanelNavigationStackState } from '@/side-panel/states/sidePanelNavigationStackState';import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';@@ -13,8 +14,6 @@ import { contextStoreCurrentPageTypeComponentState } from '@/context-store/stateimport { contextStoreCurrentViewTypeComponentState } from '@/context-store/states/contextStoreCurrentViewTypeComponentState';import { contextStoreFiltersComponentState } from '@/context-store/states/contextStoreFiltersComponentState';import { contextStoreTargetedRecordsRuleComponentState } from '@/context-store/states/contextStoreTargetedRecordsRuleComponentState';-import { ContextStorePageType } from 'twenty-shared/types';-import { ContextStoreViewType } from '@/context-store/types/ContextStoreViewType';import { objectMetadataItemsSelector } from '@/object-metadata/states/objectMetadataItemsSelector';import { recordStoreFamilySelector } from '@/object-record/record-store/states/selectors/recordStoreFamilySelector';import { getTabListInstanceIdFromPageLayoutId } from '@/page-layout/utils/getTabListInstanceIdFromPageLayoutId';@@ -31,12 +30,11 @@ export const useGetBrowsingContext = () => {.get(sidePanelNavigationStackState.atom).at(-1);- const instanceId =- isCurrentPathAiChatPage() &&- isSidePanelOpened &&- isDefined(currentSidePanelPage)- ? currentSidePanelPage.pageId- : MAIN_CONTEXT_STORE_INSTANCE_ID;+ const instanceId = getAiChatContextStoreInstanceId({+ isOnAiChatPage: isCurrentPathAiChatPage(),+ isSidePanelOpened,+ currentSidePanelPageId: currentSidePanelPage?.pageId,+ });const pageType = store.get(contextStoreCurrentPageTypeComponentState.atomFamily({@@ -66,7 +64,12 @@ export const useGetBrowsingContext = () => {return null;}- if (pageType === ContextStorePageType.Record) {+ const browsingContextType = getAiChatBrowsingContextType({+ pageType,+ viewType,+ });++ if (browsingContextType === 'recordPage') {const targetedRecordsRule = store.get(contextStoreTargetedRecordsRuleComponentState.atomFamily({instanceId,@@ -112,10 +115,7 @@ export const useGetBrowsingContext = () => {return recordContext;}- if (- viewType === ContextStoreViewType.Table ||- viewType === ContextStoreViewType.Kanban- ) {+ if (browsingContextType === 'listView') {const currentViewId = store.get(contextStoreCurrentViewIdComponentState.atomFamily({instanceId,diff --git a/packages/twenty-front/src/modules/ai/hooks/useIsAiChatComposerCentered.ts b/packages/twenty-front/src/modules/ai/hooks/useIsAiChatComposerCentered.tsnew file mode 100644index 00000000000..b0aac7d8052--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useIsAiChatComposerCentered.ts@@ -0,0 +1,21 @@+import { useContext } from 'react';+import { isDefined } from 'twenty-shared/utils';++import { AI_CHAT_SURFACE } from '@/ai/constants/AiChatSurface';+import { AiChatMessageListPreambleContext } from '@/ai/contexts/AiChatMessageListPreambleContext';+import { AiChatSurfaceContext } from '@/ai/contexts/AiChatSurfaceContext';+import { useShouldShowAiChatEmptyState } from '@/ai/hooks/useShouldShowAiChatEmptyState';++export const useIsAiChatComposerCentered = () => {+ const aiChatSurface = useContext(AiChatSurfaceContext);+ // A preamble is its own choreographed intro (onboarding); centering the+ // composer would fight with it.+ const messageListPreamble = useContext(AiChatMessageListPreambleContext);+ const shouldShowAiChatEmptyState = useShouldShowAiChatEmptyState();++ return (+ aiChatSurface === AI_CHAT_SURFACE.PAGE &&+ !isDefined(messageListPreamble) &&+ shouldShowAiChatEmptyState+ );+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useShouldShowAiChatEmptyState.ts b/packages/twenty-front/src/modules/ai/hooks/useShouldShowAiChatEmptyState.tsnew file mode 100644index 00000000000..17176c31eec--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useShouldShowAiChatEmptyState.ts@@ -0,0 +1,61 @@+import { isDefined } from 'twenty-shared/utils';++import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';+import { agentChatErrorComponentFamilyState } from '@/ai/states/agentChatErrorComponentFamilyState';+import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkComponentFamilyState';+import { agentChatIsStreamingComponentFamilyState } from '@/ai/states/agentChatIsStreamingComponentFamilyState';+import { agentChatMessagesLoadingState } from '@/ai/states/agentChatMessagesLoadingState';+import { agentChatThreadsLoadingState } from '@/ai/states/agentChatThreadsLoadingState';+import { agentChatHasMessageComponentSelector } from '@/ai/states/selectors/agentChatHasMessageComponentSelector';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { skipMessagesSkeletonUntilLoadedState } from '@/ai/states/skipMessagesSkeletonUntilLoadedState';+import { useIsMobile } from '@/ui/utilities/responsive/hooks/useIsMobile';+import { useAtomComponentFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateValue';+import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';++export const useShouldShowAiChatEmptyState = () => {+ const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);+ const agentChatError = useAtomComponentFamilyStateValue(+ agentChatErrorComponentFamilyState,+ { threadId: currentAiChatThread },+ );+ const agentChatIsAwaitingFirstChunk = useAtomComponentFamilyStateValue(+ agentChatIsAwaitingFirstChunkComponentFamilyState,+ { threadId: currentAiChatThread },+ );+ const agentChatIsStreaming = useAtomComponentFamilyStateValue(+ agentChatIsStreamingComponentFamilyState,+ { threadId: currentAiChatThread },+ );+ const agentChatThreadsLoading = useAtomStateValue(+ agentChatThreadsLoadingState,+ );+ const agentChatMessagesLoading = useAtomStateValue(+ agentChatMessagesLoadingState,+ );+ const skipMessagesSkeletonUntilLoaded = useAtomStateValue(+ skipMessagesSkeletonUntilLoadedState,+ );++ const hasMessages = useAtomComponentSelectorValue(+ agentChatHasMessageComponentSelector,+ );++ const isMobile = useIsMobile();++ const isOnNewChatSlot =+ currentAiChatThread === AGENT_CHAT_NEW_THREAD_DRAFT_KEY;+ const skeletonShowing =+ (agentChatThreadsLoading && isOnNewChatSlot) ||+ (agentChatMessagesLoading && !skipMessagesSkeletonUntilLoaded);++ return (+ !isMobile &&+ !hasMessages &&+ !isDefined(agentChatError) &&+ !skeletonShowing &&+ !agentChatIsAwaitingFirstChunk &&+ !agentChatIsStreaming+ );+};diff --git a/packages/twenty-front/src/modules/ai/types/AiChatSuggestedPromptsContext.ts b/packages/twenty-front/src/modules/ai/types/AiChatSuggestedPromptsContext.tsnew file mode 100644index 00000000000..6d6b4b75a04--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AiChatSuggestedPromptsContext.ts@@ -0,0 +1,6 @@+import { type BrowsingContext } from '@/ai/types/BrowsingContext';++export type AiChatSuggestedPromptsContext = {+ browsingContextType: BrowsingContext['type'];+ objectNameSingular: string;+};diff --git a/packages/twenty-front/src/modules/ai/types/SuggestedPrompt.ts b/packages/twenty-front/src/modules/ai/types/SuggestedPrompt.tsnew file mode 100644index 00000000000..d20d1557c1a--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/SuggestedPrompt.ts@@ -0,0 +1,14 @@+import type { MessageDescriptor } from '@lingui/core';+import { type IconComponent } from 'twenty-ui/icon';++import { type AgentChatPrepromptMode } from '@/ai/states/agentChatPrepromptState';++export type SuggestedPrompt = {+ id: string;+ label: MessageDescriptor;+ Icon: IconComponent;+ // PREFILL drops the prompt in the composer so it can be completed; SEND asks it+ // straight away, for prompts that need nothing from the user.+ mode?: AgentChatPrepromptMode;+ prompts: MessageDescriptor[];+};diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatBrowsingContextType.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatBrowsingContextType.test.tsnew file mode 100644index 00000000000..a5610992cb9--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatBrowsingContextType.test.ts@@ -0,0 +1,45 @@+import { ContextStorePageType } from 'twenty-shared/types';++import { ContextStoreViewType } from '@/context-store/types/ContextStoreViewType';+import { getAiChatBrowsingContextType } from '@/ai/utils/getAiChatBrowsingContextType';++describe('getAiChatBrowsingContextType', () => {+ it('should read a record page from the page type', () => {+ expect(+ getAiChatBrowsingContextType({+ pageType: ContextStorePageType.Record,+ viewType: null,+ }),+ ).toBe('recordPage');+ });++ it.each([ContextStoreViewType.Table, ContextStoreViewType.Kanban])(+ 'should read a list view from the %s view type',+ (viewType) => {+ expect(+ getAiChatBrowsingContextType({+ pageType: ContextStorePageType.Index,+ viewType,+ }),+ ).toBe('listView');+ },+ );++ it('should not read a list view from a calendar view', () => {+ expect(+ getAiChatBrowsingContextType({+ pageType: ContextStorePageType.Index,+ viewType: ContextStoreViewType.Calendar,+ }),+ ).toBeNull();+ });++ it('should return nothing on a page that is neither a record nor a list', () => {+ expect(+ getAiChatBrowsingContextType({+ pageType: ContextStorePageType.Settings,+ viewType: null,+ }),+ ).toBeNull();+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatContextStoreInstanceId.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatContextStoreInstanceId.test.tsnew file mode 100644index 00000000000..7b1551628ee--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAiChatContextStoreInstanceId.test.ts@@ -0,0 +1,34 @@+import { getAiChatContextStoreInstanceId } from '@/ai/utils/getAiChatContextStoreInstanceId';+import { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainContextStoreInstanceId';++describe('getAiChatContextStoreInstanceId', () => {+ it('should follow the side panel when the chat takes the whole page', () => {+ expect(+ getAiChatContextStoreInstanceId({+ isOnAiChatPage: true,+ isSidePanelOpened: true,+ currentSidePanelPageId: 'side-panel-page-1',+ }),+ ).toBe('side-panel-page-1');+ });++ it('should follow the main page when the chat sits in the side panel', () => {+ expect(+ getAiChatContextStoreInstanceId({+ isOnAiChatPage: false,+ isSidePanelOpened: true,+ currentSidePanelPageId: 'side-panel-page-1',+ }),+ ).toBe(MAIN_CONTEXT_STORE_INSTANCE_ID);+ });++ it('should follow the main page when the chat page has no side panel open', () => {+ expect(+ getAiChatContextStoreInstanceId({+ isOnAiChatPage: true,+ isSidePanelOpened: false,+ currentSidePanelPageId: undefined,+ }),+ ).toBe(MAIN_CONTEXT_STORE_INSTANCE_ID);+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatBrowsingContextType.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatBrowsingContextType.tsnew file mode 100644index 00000000000..1828a6dbf6e--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatBrowsingContextType.ts@@ -0,0 +1,25 @@+import { ContextStorePageType } from 'twenty-shared/types';++import { type BrowsingContext } from '@/ai/types/BrowsingContext';+import { ContextStoreViewType } from '@/context-store/types/ContextStoreViewType';++export const getAiChatBrowsingContextType = ({+ pageType,+ viewType,+}: {+ pageType: ContextStorePageType | null;+ viewType: ContextStoreViewType | null;+}): BrowsingContext['type'] | null => {+ if (pageType === ContextStorePageType.Record) {+ return 'recordPage';+ }++ if (+ viewType === ContextStoreViewType.Table ||+ viewType === ContextStoreViewType.Kanban+ ) {+ return 'listView';+ }++ return null;+};diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatContextStoreInstanceId.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatContextStoreInstanceId.tsnew file mode 100644index 00000000000..36e2d9188b9--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatContextStoreInstanceId.ts@@ -0,0 +1,18 @@+import { isDefined } from 'twenty-shared/utils';++import { MAIN_CONTEXT_STORE_INSTANCE_ID } from '@/context-store/constants/MainContextStoreInstanceId';++// On the full page chat the side panel holds whatever the user is still looking at,+// so it owns the context; anywhere else the chat sits beside the main page.+export const getAiChatContextStoreInstanceId = ({+ isOnAiChatPage,+ isSidePanelOpened,+ currentSidePanelPageId,+}: {+ isOnAiChatPage: boolean;+ isSidePanelOpened: boolean;+ currentSidePanelPageId: string | undefined;+}): string =>+ isOnAiChatPage && isSidePanelOpened && isDefined(currentSidePanelPageId)+ ? currentSidePanelPageId+ : MAIN_CONTEXT_STORE_INSTANCE_ID;