The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Show inbox conversations in record panels (#29156)
Raphaël Bosi8cb0a1b40749
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadActivityTime.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadActivityTime.tsxindex 94afbd82868..0b64530df24 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadActivityTime.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadActivityTime.tsx@@ -6,6 +6,7 @@ import { useIsAgentChatThreadShownAsUnread } from '@/ai/hooks/useIsAgentChatThreimport { useFormatAgentChatThreadDate } from '@/ai/hooks/useFormatAgentChatThreadDate';import { agentChatThreadInboxStatusFamilySelector } from '@/ai/states/selectors/agentChatThreadInboxStatusFamilySelector';import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { type AiChatThreadListVariant } from '@/ai/types/AiChatThreadListVariant';import { getAgentChatThreadLastActivityAt } from '@/ai/utils/getAgentChatThreadLastActivityAt';import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';import { beautifyPastDateRelativeToNowShort } from '~/utils/date-utils';@@ -16,10 +17,12 @@ const StyledActivityTime = styled.div`type AiChatThreadActivityTimeProps = {thread: AgentChatThreadRecord;+ variant?: AiChatThreadListVariant;};export const AiChatThreadActivityTime = ({thread,+ variant = 'default',}: AiChatThreadActivityTimeProps) => {const { t } = useLingui();const isUnread = useIsAgentChatThreadShownAsUnread(thread);@@ -55,11 +58,14 @@ export const AiChatThreadActivityTime = ({}};+ const readActivityTimeColor =+ variant === 'compact' ? 'secondary' : 'tertiary';+return (<Textrender={<StyledActivityTime />}- size="sm"- color={isUnread ? 'primary' : 'tertiary'}+ size={variant === 'compact' ? 'md' : 'sm'}+ color={isUnread ? 'primary' : readActivityTimeColor}>{getActivityTimeLabel()}</Text>diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadAvatar.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadAvatar.tsxindex 73ac133f566..be7ee82323d 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadAvatar.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadAvatar.tsx@@ -1,6 +1,6 @@import { useLingui } from '@lingui/react/macro';import { isDefined } from 'twenty-shared/utils';-import { Avatar } from 'twenty-ui/primitives/data-display';+import { Avatar, type AvatarSize } from 'twenty-ui/primitives/data-display';import { useAgentChatThreadMembers } from '@/ai/hooks/useAgentChatThreadMembers';import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';@@ -10,9 +10,13 @@ import { WorkspaceMemberAvatarStack } from '@/workspace-member/components/Worksptype AiChatThreadAvatarProps = {thread: AgentChatThreadRecord;+ size?: AvatarSize;};-export const AiChatThreadAvatar = ({ thread }: AiChatThreadAvatarProps) => {+export const AiChatThreadAvatar = ({+ thread,+ size = 'lg',+}: AiChatThreadAvatarProps) => {const { t } = useLingui();const threadMembers = useAgentChatThreadMembers(thread);@@ -27,7 +31,7 @@ export const AiChatThreadAvatar = ({ thread }: AiChatThreadAvatarProps) => {name={name}imageProps={{ alt: name }}colorSeed={onlyMember.id}- size="lg"+ size={size}shape="circle"/>);diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadCompactContent.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadCompactContent.tsxnew file mode 100644index 00000000000..45d00dcac93--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadCompactContent.tsx@@ -0,0 +1,60 @@+import { styled } from '@linaria/react';+import { type ReactNode } from 'react';+import { isDefined } from 'twenty-shared/utils';+import { themeCssVariables } from 'twenty-ui/theme';++import { ShimmeringText } from '@/ai/components/ShimmeringText';++const StyledContent = styled.div`+ align-items: center;+ display: flex;+ font-size: ${themeCssVariables.font.size.md};+ gap: ${themeCssVariables.spacing[1]};+ min-width: 0;+`;++const StyledTitle = styled.div`+ flex: 0 1 auto;+ max-width: 60%;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+`;++const StyledSeparator = styled.span`+ color: ${themeCssVariables.font.color.tertiary};+ flex-shrink: 0;+`;++const StyledPreview = styled.div`+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+`;++type AiChatThreadCompactContentProps = {+ title: ReactNode;+ subtitle: ReactNode;+ isStreaming: boolean;+};++export const AiChatThreadCompactContent = ({+ title,+ subtitle,+ isStreaming,+}: AiChatThreadCompactContentProps) => (+ <StyledContent>+ <StyledTitle>{title}</StyledTitle>+ {isDefined(subtitle) && (+ <>+ <StyledSeparator aria-hidden>·</StyledSeparator>+ <StyledPreview>+ {isStreaming ? <ShimmeringText>{subtitle}</ShimmeringText> : subtitle}+ </StyledPreview>+ </>+ )}+ </StyledContent>+);diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadList.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadList.tsxindex 63b08c734cb..e670bf5a242 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadList.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadList.tsx@@ -4,10 +4,13 @@ import { isDefined } from 'twenty-shared/utils';import { AiChatThreadListGroup } from '@/ai/components/AiChatThreadListGroup';import { AiChatThreadListItem } from '@/ai/components/AiChatThreadListItem';import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { type AiChatThreadListVariant } from '@/ai/types/AiChatThreadListVariant';import { groupThreadsByDate } from '@/ai/utils/groupThreadsByDate';+import { useDateTimeFormat } from '@/localization/hooks/useDateTimeFormat';type AiChatThreadListProps = {threads: AgentChatThreadRecord[];+ variant?: AiChatThreadListVariant;selectedThreadIds?: string[];checkedThreadIds?: string[];onThreadClick: (@@ -27,6 +30,7 @@ type AiChatThreadListProps = {export const AiChatThreadList = ({threads,+ variant = 'default',selectedThreadIds = [],checkedThreadIds = [],onThreadClick,@@ -34,6 +38,7 @@ export const AiChatThreadList = ({onThreadContextMenu,onDetachThread,}: AiChatThreadListProps) => {+ const { calendarStartDay } = useDateTimeFormat();const selectedThreadIdSet = new Set(selectedThreadIds);const checkedThreadIdSet = new Set(checkedThreadIds);@@ -41,6 +46,7 @@ export const AiChatThreadList = ({<AiChatThreadListItemkey={thread.id}thread={thread}+ variant={variant}isSelected={selectedThreadIdSet.has(thread.id)}isChecked={checkedThreadIdSet.has(thread.id)}onClick={onThreadClick}@@ -54,11 +60,17 @@ export const AiChatThreadList = ({return (<>- {groupThreadsByDate(threads).map((dateGroup) => (- <AiChatThreadListGroup key={dateGroup.id} title={dateGroup.title}>- {dateGroup.threads.map(renderThread)}- </AiChatThreadListGroup>- ))}+ {groupThreadsByDate({ threads, variant, calendarStartDay }).map(+ (dateGroup) => (+ <AiChatThreadListGroup+ key={dateGroup.id}+ title={dateGroup.title}+ variant={variant}+ >+ {dateGroup.threads.map(renderThread)}+ </AiChatThreadListGroup>+ ),+ )}</>);};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadListGroup.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadListGroup.tsxindex 674f7016134..929a4ba865d 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadListGroup.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadListGroup.tsx@@ -4,41 +4,58 @@ import { isDefined } from 'twenty-shared/utils';import { Text } from 'twenty-ui/primitives/typography';import { themeCssVariables } from 'twenty-ui/theme';-const StyledHeader = styled.div`+import { type AiChatThreadListVariant } from '@/ai/types/AiChatThreadListVariant';++const COMPACT_HEADER_PADDING = `0 ${themeCssVariables.spacing[1]}`;+const DEFAULT_HEADER_PADDING = `${themeCssVariables.spacing[4]} ${themeCssVariables.spacing[4]} ${themeCssVariables.spacing[2]}`;++const StyledGroup = styled.section<{ $isCompact: boolean }>`+ display: ${({ $isCompact }) => ($isCompact ? 'flex' : 'block')};+ flex-direction: column;+ gap: ${themeCssVariables.spacing[0.5]};+`;++const StyledHeader = styled.div<{ $isCompact: boolean }>`align-items: center;display: flex;gap: ${themeCssVariables.spacing[1]};- padding: ${themeCssVariables.spacing[4]} ${themeCssVariables.spacing[4]}- ${themeCssVariables.spacing[2]};+ margin-bottom: ${({ $isCompact }) =>+ $isCompact ? themeCssVariables.spacing[1.5] : '0'};+ padding: ${({ $isCompact }) =>+ $isCompact ? COMPACT_HEADER_PADDING : DEFAULT_HEADER_PADDING};`;-const StyledTitle = styled.h3`+const StyledTitle = styled.h3<{ $isCompact: boolean }>`margin: 0;- padding: ${themeCssVariables.spacing[1]} 0;+ padding: ${({ $isCompact }) =>+ $isCompact ? '0' : `${themeCssVariables.spacing[1]} 0`};`;type AiChatThreadListGroupProps = {title: string;+ variant?: AiChatThreadListVariant;count?: number;children: ReactNode;};export const AiChatThreadListGroup = ({title,+ variant = 'default',count,children,}: AiChatThreadListGroupProps) => {const titleId = useId();+ const isCompact = variant === 'compact';return (- <section aria-labelledby={titleId}>- <StyledHeader>+ <StyledGroup $isCompact={isCompact} aria-labelledby={titleId}>+ <StyledHeader $isCompact={isCompact}><Text- render={<StyledTitle />}+ render={<StyledTitle $isCompact={isCompact} />}id={titleId}- size="md"- weight="medium"- color="primary"+ size={isCompact ? 'sm' : 'md'}+ weight={isCompact ? 'semibold' : 'medium'}+ color={isCompact ? 'tertiary' : 'primary'}>{title}</Text>@@ -49,6 +66,6 @@ export const AiChatThreadListGroup = ({)}</StyledHeader>{children}- </section>+ </StyledGroup>);};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsxindex 4cbdc1849ee..2cb8c6d6a40 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx@@ -12,13 +12,17 @@ import { AiChatThreadChannelIcon } from '@/ai/components/AiChatThreadChannelIconimport { AiChatThreadRow } from '@/ai/components/AiChatThreadRow';import { AiChatThreadSubtitle } from '@/ai/components/AiChatThreadSubtitle';import { AiChatThreadTitle } from '@/ai/components/AiChatThreadTitle';+import { useAgentChatThreadSubtitleContent } from '@/ai/hooks/useAgentChatThreadSubtitleContent';import { useAiChatThreadRename } from '@/ai/hooks/useAiChatThreadRename';import { useAiChatThreadTriage } from '@/ai/hooks/useAiChatThreadTriage';+import { agentChatIsStreamingFamilyState } from '@/ai/states/agentChatIsStreamingFamilyState';import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { type AiChatThreadListVariant } from '@/ai/types/AiChatThreadListVariant';import { getCommandMenuDropdownIdFromCommandMenuId } from '@/command-menu-item/utils/getCommandMenuDropdownIdFromCommandMenuId';import { TextInput } from '@/ui/input/components/TextInput';import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropdownOpenComponentState';import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';+import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyStateValue';const StyledActivityTime = styled.div`align-items: center;@@ -28,6 +32,7 @@ const StyledActivityTime = styled.div`type AiChatThreadListItemProps = {thread: AgentChatThreadRecord;+ variant?: AiChatThreadListVariant;isSelected: boolean;isChecked?: boolean;onClick: (@@ -47,6 +52,7 @@ type AiChatThreadListItemProps = {export const AiChatThreadListItem = ({thread,+ variant = 'default',isSelected,isChecked = false,onClick,@@ -74,6 +80,13 @@ export const AiChatThreadListItem = ({const { status: triageStatus } = useAiChatThreadTriage({threadId: thread.id,});+ const agentChatIsStreaming = useAtomFamilyStateValue(+ agentChatIsStreamingFamilyState,+ { threadId: thread.id },+ );+ const { hasContent: hasSubtitleContent } =+ useAgentChatThreadSubtitleContent(thread);+ const isCompact = variant === 'compact';const shouldShowMore =isDefined(onDetach) ||isDefined(thread.deletedAt) ||@@ -82,12 +95,14 @@ export const AiChatThreadListItem = ({return (<AiChatThreadRow+ variant={variant}id={thread.id}label={thread.title ?? t`Untitled`}isSelected={isSelected}isChecked={isChecked}isEditing={isRenaming}isActionMenuOpen={isDropdownOpen}+ isStreaming={agentChatIsStreaming}onClick={(event) => onClick(thread, event)}onCheckboxClick={isDefined(onCheckboxClick)@@ -99,7 +114,9 @@ export const AiChatThreadListItem = ({? (event) => onContextMenu(thread, event): undefined}- avatar={<AiChatThreadAvatar thread={thread} />}+ avatar={+ <AiChatThreadAvatar thread={thread} size={isCompact ? 'md' : 'lg'} />+ }title={isRenaming ? (<TextInput@@ -135,18 +152,25 @@ export const AiChatThreadListItem = ({!isRenaming && (<StyledActivityTime><AiChatThreadChannelIcon thread={thread} />- <AiChatThreadActivityTime thread={thread} />+ <AiChatThreadActivityTime thread={thread} variant={variant} /></StyledActivityTime>)}- subtitle={<AiChatThreadSubtitle thread={thread} />}+ subtitle={+ !isCompact || hasSubtitleContent ? (+ <AiChatThreadSubtitle+ thread={thread}+ size={isCompact ? 'md' : 'sm'}+ />+ ) : undefined+ }actions={<AiChatThreadActionsDropdownthread={thread}instanceId={actionsInstanceId}onRenameRequested={startRename}onDetach={onDetach}- shouldShowTriageActions+ shouldShowTriageActions={!isCompact}shouldShowMore={shouldShowMore}/>}diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadRow.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadRow.tsxindex 73c0e80cf09..96f520e6064 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadRow.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadRow.tsx@@ -3,25 +3,39 @@ import { useLingui } from '@lingui/react/macro';import { type MouseEvent, type ReactNode } from 'react';import { Key } from 'ts-key-enum';import { isDefined } from 'twenty-shared/utils';+import { ThinkingOrbitLoaderIcon } from 'twenty-ui/icon';import { Checkbox } from 'twenty-ui/primitives/input';import { ListItem } from 'twenty-ui/primitives/navigation';import { themeCssVariables } from 'twenty-ui/theme';-const StyledRow = styled.div`- border-bottom: 1px solid ${themeCssVariables.border.color.light};- border-radius: 0;- column-gap: ${themeCssVariables.spacing[4]};- padding: ${themeCssVariables.spacing[4]};+import { AiChatThreadRowContent } from '@/ai/components/AiChatThreadRowContent';+import { type AiChatThreadListVariant } from '@/ai/types/AiChatThreadListVariant';++const StyledRow = styled.div<{ $isCompact: boolean }>`+ border-bottom: ${({ $isCompact }) =>+ $isCompact ? 'none' : `1px solid ${themeCssVariables.border.color.light}`};+ border-radius: ${({ $isCompact }) =>+ $isCompact ? themeCssVariables.border.radius.sm : '0'};+ column-gap: ${({ $isCompact }) =>+ $isCompact ? themeCssVariables.spacing[2] : themeCssVariables.spacing[4]};+ height: ${({ $isCompact }) =>+ $isCompact ? themeCssVariables.spacing[8] : 'auto'};+ padding: ${({ $isCompact }) =>+ $isCompact+ ? `0 ${themeCssVariables.spacing[1]}`+ : themeCssVariables.spacing[4]};row-gap: ${themeCssVariables.spacing[2]};`;-const StyledLeading = styled.div`+const StyledLeading = styled.div<{ $isCompact: boolean }>`align-items: center;display: flex;flex-shrink: 0;height: ${themeCssVariables.spacing[8]};- justify-content: center;- width: ${themeCssVariables.spacing[6]};+ justify-content: ${({ $isCompact }) =>+ $isCompact ? 'flex-start' : 'center'};+ width: ${({ $isCompact }) =>+ $isCompact ? themeCssVariables.spacing[7] : themeCssVariables.spacing[6]};`;const StyledCheckbox = styled.div<{ $isChecked: boolean }>`@@ -54,44 +68,61 @@ const StyledAvatar = styled.div<{ $isCheckable: boolean; $isChecked: boolean }>`}`;-const StyledHeading = styled.div`- align-items: center;- display: flex;- gap: ${themeCssVariables.spacing[2]};- line-height: ${themeCssVariables.spacing[4]};- min-width: 0;-`;--const StyledTitle = styled.div`- display: flex;- flex: 1;- min-width: 0;-`;-const StyledTime = styled.div<{$isActionMenuOpen: boolean;$hasActions: boolean;}>`- display: block;+ align-items: center;+ display: flex;flex-shrink: 0;+ gap: ${themeCssVariables.spacing[1]};white-space: nowrap;@media (hover: hover) and (not (any-pointer: coarse)) {display: ${({ $isActionMenuOpen, $hasActions }) =>- $isActionMenuOpen && $hasActions ? 'none' : 'block'};+ $isActionMenuOpen && $hasActions ? 'none' : 'flex'};${StyledRow}:hover &,${StyledRow}:focus-within & {- display: ${({ $hasActions }) => ($hasActions ? 'none' : 'block')};+ display: ${({ $hasActions }) => ($hasActions ? 'none' : 'flex')};}}`;-const StyledActions = styled.div`+const StyledActions = styled.div<{+ $isCompact: boolean;+ $isActionMenuOpen: boolean;+}>`align-items: center;display: flex;gap: ${themeCssVariables.spacing[1]};height: ${themeCssVariables.spacing[8]};++ @media (hover: hover) and (not (any-pointer: coarse)) {+ display: ${({ $isCompact, $isActionMenuOpen }) =>+ $isCompact && !$isActionMenuOpen ? 'none' : 'flex'};++ ${StyledRow}:hover &,+ ${StyledRow}:focus-within & {+ display: flex;+ }+ }+`;++const StyledCompactTrailing = styled.div`+ align-items: center;+ display: flex;+ gap: ${themeCssVariables.spacing[1]};+ height: ${themeCssVariables.spacing[8]};+`;++const StyledStreamingIcon = styled(ThinkingOrbitLoaderIcon)`+ color: ${themeCssVariables.font.color.tertiary};+ flex-shrink: 0;++ @media (prefers-reduced-motion: reduce) {+ display: none;+ }`;const StyledDescription = styled.div`@@ -107,6 +138,7 @@ const StyledRequestActions = styled.div``;type AiChatThreadRowProps = {+ variant?: AiChatThreadListVariant;id: string;label: string;avatar: ReactNode;@@ -119,6 +151,7 @@ type AiChatThreadRowProps = {isChecked?: boolean;isEditing?: boolean;isActionMenuOpen?: boolean;+ isStreaming?: boolean;onClick: (event: MouseEvent<HTMLDivElement>) => void;onCheckboxClick?: (event: MouseEvent<HTMLDivElement>) => void;onContextMenu?: (event: MouseEvent<HTMLDivElement>) => void;@@ -128,6 +161,7 @@ const stopPropagation = (event: MouseEvent<HTMLDivElement>) =>event.stopPropagation();export const AiChatThreadRow = ({+ variant = 'default',id,label,avatar,@@ -140,22 +174,53 @@ export const AiChatThreadRow = ({isChecked = false,isEditing = false,isActionMenuOpen = false,+ isStreaming = false,onClick,onCheckboxClick,onContextMenu,}: AiChatThreadRowProps) => {const { t } = useLingui();+ const isCompact = variant === 'compact';+ const time = (+ <StyledTime+ $isActionMenuOpen={isActionMenuOpen}+ $hasActions={isDefined(actions)}+ >+ {isCompact && isStreaming && <StyledStreamingIcon />}+ {activityTime}+ </StyledTime>+ );+ const actionButtons = isDefined(actions) && (+ <StyledActions+ $isCompact={isCompact}+ $isActionMenuOpen={isActionMenuOpen}+ data-select-disable+ onClick={stopPropagation}+ onContextMenu={stopPropagation}+ >+ {actions}+ </StyledActions>+ );+ const rowActions = isCompact ? (+ <StyledCompactTrailing>+ {time}+ {actionButtons}+ </StyledCompactTrailing>+ ) : (+ actionButtons+ );return (<ListItemactive={isSelected}selected={isChecked}selectionAppearance="accent"- descriptionPlacement="below"+ descriptionPlacement={isCompact ? 'inline' : 'below'}actionsPlacement="end"- actionsVisibility={isActionMenuOpen ? 'always' : 'hover'}+ actionsVisibility={isCompact || isActionMenuOpen ? 'always' : 'hover'}render={<StyledRow+ $isCompact={isCompact}aria-label={label}role="group"tabIndex={0}@@ -185,6 +250,7 @@ export const AiChatThreadRow = ({}startIcon={<StyledLeading+ $isCompact={isCompact}data-select-disable={isDefined(onCheckboxClick) || undefined}onClick={isDefined(onCheckboxClick)@@ -209,40 +275,30 @@ export const AiChatThreadRow = ({</StyledLeading>}description={- <>- <StyledDescription>{subtitle}</StyledDescription>- {isDefined(children) && (- <StyledRequestActions- data-select-disable- onClick={stopPropagation}- onContextMenu={stopPropagation}- >- {children}- </StyledRequestActions>- )}- </>- }- actions={- isDefined(actions) && (- <StyledActions- data-select-disable- onClick={stopPropagation}- onContextMenu={stopPropagation}- >- {actions}- </StyledActions>+ !isCompact && (+ <>+ <StyledDescription>{subtitle}</StyledDescription>+ {isDefined(children) && (+ <StyledRequestActions+ data-select-disable+ onClick={stopPropagation}+ onContextMenu={stopPropagation}+ >+ {children}+ </StyledRequestActions>+ )}+ </>)}+ actions={rowActions}>- <StyledHeading>- <StyledTitle>{title}</StyledTitle>- <StyledTime- $isActionMenuOpen={isActionMenuOpen}- $hasActions={isDefined(actions)}- >- {activityTime}- </StyledTime>- </StyledHeading>+ <AiChatThreadRowContent+ variant={variant}+ title={title}+ subtitle={subtitle}+ activityTime={time}+ isStreaming={isStreaming}+ /></ListItem>);};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadRowContent.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadRowContent.tsxnew file mode 100644index 00000000000..c09c2ef0db9--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadRowContent.tsx@@ -0,0 +1,53 @@+import { styled } from '@linaria/react';+import { type ReactNode } from 'react';+import { themeCssVariables } from 'twenty-ui/theme';++import { AiChatThreadCompactContent } from '@/ai/components/AiChatThreadCompactContent';+import { type AiChatThreadListVariant } from '@/ai/types/AiChatThreadListVariant';++const StyledHeading = styled.div`+ align-items: center;+ display: flex;+ gap: ${themeCssVariables.spacing[2]};+ line-height: ${themeCssVariables.spacing[4]};+ min-width: 0;+`;++const StyledTitle = styled.div`+ display: flex;+ flex: 1;+ min-width: 0;+`;++type AiChatThreadRowContentProps = {+ variant: AiChatThreadListVariant;+ title: ReactNode;+ subtitle: ReactNode;+ activityTime: ReactNode;+ isStreaming: boolean;+};++export const AiChatThreadRowContent = ({+ variant,+ title,+ subtitle,+ activityTime,+ isStreaming,+}: AiChatThreadRowContentProps) => {+ if (variant === 'compact') {+ return (+ <AiChatThreadCompactContent+ title={title}+ subtitle={subtitle}+ isStreaming={isStreaming}+ />+ );+ }++ return (+ <StyledHeading>+ <StyledTitle>{title}</StyledTitle>+ {activityTime}+ </StyledHeading>+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadSubtitle.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadSubtitle.tsxindex 7e106c0e604..f76ac50d1be 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadSubtitle.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadSubtitle.tsx@@ -1,17 +1,12 @@import { styled } from '@linaria/react';-import { isDefined, isNonEmptyString } from 'twenty-shared/utils';+import { isNonEmptyString } from 'twenty-shared/utils';import { Text } from 'twenty-ui/primitives/typography';import { themeCssVariables } from 'twenty-ui/theme';import { AiChatThreadReasonBadge } from '@/ai/components/AiChatThreadReasonBadge';+import { useAgentChatThreadSubtitleContent } from '@/ai/hooks/useAgentChatThreadSubtitleContent';import { useIsAgentChatThreadShownAsUnread } from '@/ai/hooks/useIsAgentChatThreadShownAsUnread';-import { agentChatDraftPreviewTextFamilySelector } from '@/ai/states/selectors/agentChatDraftPreviewTextFamilySelector';import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';-import { getAgentChatThreadPreviewText } from '@/ai/utils/getAgentChatThreadPreviewText';-import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';-import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';-import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';const StyledSubtitle = styled.div`align-items: center;@@ -32,33 +27,21 @@ const StyledPreview = styled.div`type AiChatThreadSubtitleProps = {thread: AgentChatThreadRecord;+ size?: 'sm' | 'md';};-export const AiChatThreadSubtitle = ({ thread }: AiChatThreadSubtitleProps) => {+export const AiChatThreadSubtitle = ({+ thread,+ size = 'sm',+}: AiChatThreadSubtitleProps) => {const isUnread = useIsAgentChatThreadShownAsUnread(thread);- const currentWorkspaceMember = useAtomStateValue(currentWorkspaceMemberState);- const currentWorkspaceMembers = useAtomStateValue(- currentWorkspaceMembersState,- );- const isAwaitingAnswer =- !isDefined(thread.deletedAt) && isDefined(thread.pendingQuestionMessageId);- const draftPreviewText = useAtomFamilySelectorValue(- agentChatDraftPreviewTextFamilySelector,- thread.id,- );- const hasDraft = isNonEmptyString(draftPreviewText);- const previewText = hasDraft- ? draftPreviewText- : getAgentChatThreadPreviewText({- thread,- workspaceMembers: currentWorkspaceMembers,- currentWorkspaceMemberId: currentWorkspaceMember?.id,- });+ const { isAwaitingAnswer, hasDraft, previewText } =+ useAgentChatThreadSubtitleContent(thread);return (<Textrender={<StyledSubtitle />}- size="sm"+ size={size}color={isUnread ? 'secondary' : 'tertiary'}>{isAwaitingAnswer && (diff --git a/packages/twenty-front/src/modules/ai/components/ShimmeringText.tsx b/packages/twenty-front/src/modules/ai/components/ShimmeringText.tsxindex 95a5bab1aa3..cee2ef110fa 100644--- a/packages/twenty-front/src/modules/ai/components/ShimmeringText.tsx+++ b/packages/twenty-front/src/modules/ai/components/ShimmeringText.tsx@@ -17,6 +17,12 @@ const StyledShimmeringText = styled.div`background-repeat: no-repeat;background-size: 200% 100%;+ @media (prefers-reduced-motion: reduce) {+ -webkit-text-fill-color: currentColor;+ animation: none;+ background: none;+ }+@keyframes shimmer-wave {0% {background-position: 200% top;diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatThreadCompactRow.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatThreadCompactRow.stories.tsxnew file mode 100644index 00000000000..5a2f2d77b38--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatThreadCompactRow.stories.tsx@@ -0,0 +1,134 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, fn, userEvent, within } from 'storybook/test';+import { LightIconButton } from 'twenty-ui/components/input';+import { IconUnlink } from 'twenty-ui/icon';+import { Avatar } from 'twenty-ui/primitives/data-display';+import { Input } from 'twenty-ui/primitives/input';+import { Text } from 'twenty-ui/primitives/typography';+import { ComponentDecorator } from 'twenty-ui/testing';++import { AiChatThreadRow } from '@/ai/components/AiChatThreadRow';++const onDetach = fn();++const meta = {+ title: 'Modules/AI/AiChatThreadCompactRow',+ component: AiChatThreadRow,+ decorators: [ComponentDecorator],+ parameters: { container: { width: 368 } },+ args: {+ variant: 'compact',+ id: 'renewal',+ label: 'Cloud renewal prep',+ avatar: <Avatar name="Sarah" size="md" shape="circle" />,+ title: <Text color="primary">Cloud renewal prep</Text>,+ subtitle: (+ <Text color="tertiary" truncate>+ Sarah: Legal is reviewing the new terms+ </Text>+ ),+ activityTime: <Text color="secondary">3d</Text>,+ onClick: fn(),+ onContextMenu: fn(),+ },+} satisfies Meta<typeof AiChatThreadRow>;++export default meta;+type Story = StoryObj<typeof meta>;++export const Default: Story = {+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const row = canvas.getByRole('group', { name: 'Cloud renewal prep' });++ await expect(row.getBoundingClientRect().height).toBe(32);+ await expect(row.scrollWidth).toBeLessThanOrEqual(row.clientWidth);+ await userEvent.tab();+ await expect(row).toHaveFocus();+ await userEvent.keyboard('{Enter}');+ await expect(args.onClick).toHaveBeenCalledTimes(1);+ },+};++export const HoverActions: Story = {+ args: {+ actions: (+ <LightIconButton aria-label="Detach" onClick={onDetach}>+ <IconUnlink />+ </LightIconButton>+ ),+ },+ play: async ({ canvasElement, args }) => {+ const { userEvent: trustedUserEvent } = await import('vitest/browser');+ const canvas = within(canvasElement);+ const row = canvas.getByRole('group', { name: 'Cloud renewal prep' });++ await trustedUserEvent.hover(row);+ const canHoverWithoutTouch = window.matchMedia(+ '(hover: hover) and (not (any-pointer: coarse))',+ ).matches;++ await expect(canvas.getByText('3d').getBoundingClientRect().width > 0).toBe(+ !canHoverWithoutTouch,+ );+ await userEvent.click(canvas.getByRole('button', { name: 'Detach' }));+ await expect(onDetach).toHaveBeenCalledTimes(1);+ await expect(args.onClick).not.toHaveBeenCalled();+ await expect(row.getBoundingClientRect().height).toBe(32);+ },+};++export const NarrowLongTitle: Story = {+ parameters: { container: { width: 288 } },+ args: {+ title: (+ <Text color="primary" truncate>+ Cloud renewal preparation for the international procurement team+ </Text>+ ),+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const row = canvas.getByRole('group', { name: 'Cloud renewal prep' });+ const time = canvas.getByText('3d');++ await expect(row.getBoundingClientRect().height).toBe(32);+ await expect(row.scrollWidth).toBeLessThanOrEqual(row.clientWidth);+ await expect(time).toBeVisible();+ await expect(time.getBoundingClientRect().right).toBeLessThanOrEqual(+ row.getBoundingClientRect().right,+ );+ },+};++export const Editing: Story = {+ args: {+ isEditing: true,+ title: <Input aria-label="Rename chat" defaultValue="Cloud renewal prep" />,+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole('textbox', { name: 'Rename chat' });++ await userEvent.click(input);+ await userEvent.keyboard('{Enter} ');+ await expect(args.onClick).not.toHaveBeenCalled();+ },+};++export const Streaming: Story = {+ args: { isStreaming: true, isSelected: true },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const row = canvas.getByRole('group', { name: 'Cloud renewal prep' });+ const streamingIndicator = row.querySelector('svg[data-twenty-icon]');++ await expect(row).toHaveAttribute('data-active');+ await expect(+ canvas.getByText('Sarah: Legal is reviewing the new terms'),+ ).toBeVisible();+ await expect(streamingIndicator).toBeVisible();+ await expect(canvas.getByText('3d')).toBeVisible();+ await expect(row.scrollWidth).toBeLessThanOrEqual(row.clientWidth);+ },+};diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useChatThreadsForRecord.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useChatThreadsForRecord.test.tsxindex f580bbc011e..912f29efada 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useChatThreadsForRecord.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useChatThreadsForRecord.test.tsx@@ -1,8 +1,11 @@import { act, renderHook } from '@testing-library/react';+import { createStore, Provider as JotaiProvider } from 'jotai';+import { type ReactNode } from 'react';import { useChatThreadsForRecord } from '@/ai/hooks/useChatThreadsForRecord';import { type AgentChatThreadTargetRecord } from '@/ai/types/AgentChatThreadTargetRecord';import { dispatchObjectRecordOperationBrowserEvent } from '@/browser-event/utils/dispatchObjectRecordOperationBrowserEvent';+import { isFetchingMoreRecordsFamilyState } from '@/object-record/states/isFetchingMoreRecordsFamilyState';import { getMockFieldMetadataItemOrThrow } from '~/testing/utils/getMockFieldMetadataItemOrThrow';import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';@@ -14,7 +17,6 @@ const companyObjectMetadataItem = getMockObjectMetadataItemOrThrow('company');const personObjectMetadataItem = getMockObjectMetadataItemOrThrow('person');const opportunityObjectMetadataItem =getMockObjectMetadataItemOrThrow('opportunity');-// Any relation to company stands in for the thread target's company leg.const companyTargetField = getMockFieldMetadataItemOrThrow({objectMetadataItem: personObjectMetadataItem,fieldName: 'company',@@ -59,7 +61,6 @@ const buildLink = ({},});-// The renewal conversation is linked twice, as a custom leg allows.const LINKS = [buildLink({id: 'link-1',@@ -79,11 +80,43 @@ const LINKS = [];const refetch = jest.fn(() => Promise.resolve());-const useFindManyRecords = jest.fn((_params: unknown) => ({+const fetchMoreRecords = jest.fn(() => Promise.resolve());+const buildLinksPage = ({+ linkIds,+ hasNextPage = false,+ endCursor = 'last-link-cursor',+}: {+ linkIds: string[];+ hasNextPage?: boolean;+ endCursor?: string;+}) => ({+ data: {+ agentChatThreadTargets: {+ edges: linkIds.map((id) => ({ node: { id } })),+ pageInfo: { hasNextPage, endCursor },+ },+ },+});+const query = jest.fn();+const FIND_THREAD_LINKS_QUERY = {};+const useFindManyRecordsQuery = jest.fn((_params: unknown) => ({+ findManyRecordsQuery: FIND_THREAD_LINKS_QUERY,+}));+const useObjectPermissionsForObject = jest.fn(() => ({+ canReadObjectRecords: true,+}));+const QUERY_IDENTIFIER = 'chat-threads-for-record-query';+const findManyRecordsResult = {records: LINKS,loading: false,error: undefined,refetch,+ fetchMoreRecords,+ hasNextPage: true,+ queryIdentifier: QUERY_IDENTIFIER,+};+const useFindManyRecords = jest.fn((_params: unknown) => ({+ ...findManyRecordsResult,}));const useListenToEventsForQuery = jest.fn();@@ -91,6 +124,18 @@ jest.mock('@/object-record/hooks/useFindManyRecords', () => ({useFindManyRecords: (params: unknown) => useFindManyRecords(params),}));+jest.mock('@/object-metadata/hooks/useApolloCoreClient', () => ({+ useApolloCoreClient: () => ({ query }),+}));++jest.mock('@/object-record/hooks/useFindManyRecordsQuery', () => ({+ useFindManyRecordsQuery: (params: unknown) => useFindManyRecordsQuery(params),+}));++jest.mock('@/object-record/hooks/useObjectPermissionsForObject', () => ({+ useObjectPermissionsForObject: () => useObjectPermissionsForObject(),+}));+jest.mock('@/sse-db-event/hooks/useListenToEventsForQuery', () => ({useListenToEventsForQuery: (params: unknown) =>useListenToEventsForQuery(params),@@ -113,14 +158,23 @@ jest.mock(() => ({useObjectMorphJunctionConfig: () => ({junctionObjectMetadata: threadTargetObjectMetadataItem,+ sourceJoinColumnName: 'threadId',targetFields: [companyTargetField],}),}),);-const renderChatThreadsForRecord = (targetObjectNameSingular = 'company') =>- renderHook(() =>- useChatThreadsForRecord({ id: COMPANY_ID, targetObjectNameSingular }),+const renderChatThreadsForRecord = ({+ targetObjectNameSingular = 'company',+ store = createStore(),+} = {}) =>+ renderHook(+ () => useChatThreadsForRecord({ id: COMPANY_ID, targetObjectNameSingular }),+ {+ wrapper: ({ children }: { children: ReactNode }) => (+ <JotaiProvider store={store}>{children}</JotaiProvider>+ ),+ },).result;const dispatchThreadOperation = (@@ -140,6 +194,13 @@ const LINKS_FILTER = { or: [{ companyId: { eq: COMPANY_ID } }] };describe('useChatThreadsForRecord', () => {beforeEach(() => {jest.clearAllMocks();+ useFindManyRecords.mockReturnValue(findManyRecordsResult);+ useObjectPermissionsForObject.mockReturnValue({+ canReadObjectRecords: true,+ });+ query.mockResolvedValue(+ buildLinksPage({ linkIds: ['link-1', 'link-3', 'link-4'] }),+ );});it("reads the links on the leg of the record's object and listens for new ones", () => {@@ -151,6 +212,12 @@ describe('useChatThreadsForRecord', () => {skip: false,filter: LINKS_FILTER,orderBy: [{ thread: { lastActivityAt: 'DescNullsLast' } }],+ recordGqlFields: expect.objectContaining({+ thread: expect.objectContaining({+ createdAt: true,+ channelId: true,+ }),+ }),}),);expect(useListenToEventsForQuery).toHaveBeenCalledWith(@@ -164,25 +231,157 @@ describe('useChatThreadsForRecord', () => {);});- it('lists each conversation once and detaches all of its links', () => {+ it('lists each conversation once', () => {const result = renderChatThreadsForRecord();expect(result.current.threads.map(({ title }) => title)).toEqual(['Renewal prep','Onboarding',]);- expect(result.current.getLinkIdsToThread(RENEWAL_THREAD_ID)).toEqual([- 'link-1',- 'link-3',- ]);});- it('reads nothing for an object conversations cannot be attached to', () => {- renderChatThreadsForRecord('opportunity');+ it('finds every link to a conversation before detaching, including links outside the loaded page', async () => {+ query+ .mockResolvedValueOnce(+ buildLinksPage({+ linkIds: ['link-1', 'link-3'],+ hasNextPage: true,+ endCursor: 'first-links-page',+ }),+ )+ .mockResolvedValueOnce(buildLinksPage({ linkIds: ['link-4'] }));+ const result = renderChatThreadsForRecord();++ expect(query).not.toHaveBeenCalled();++ await expect(+ result.current.getAllLinkIdsToThread(RENEWAL_THREAD_ID),+ ).resolves.toEqual(['link-1', 'link-3', 'link-4']);++ expect(useFindManyRecordsQuery).toHaveBeenCalledWith({+ objectNameSingular: 'agentChatThreadTarget',+ recordGqlFields: { id: true, threadId: true },+ });+ const filter = {+ and: [LINKS_FILTER, { threadId: { eq: RENEWAL_THREAD_ID } }],+ };++ expect(query).toHaveBeenCalledTimes(2);+ expect(query).toHaveBeenNthCalledWith(1, {+ query: FIND_THREAD_LINKS_QUERY,+ variables: { filter, limit: 30, lastCursor: undefined },+ fetchPolicy: 'network-only',+ });+ expect(query).toHaveBeenNthCalledWith(2, {+ query: FIND_THREAD_LINKS_QUERY,+ variables: { filter, limit: 30, lastCursor: 'first-links-page' },+ fetchPolicy: 'network-only',+ });+ });++ it('rejects link lookup errors instead of returning a partial set', async () => {+ query.mockRejectedValueOnce(new Error('Link lookup failed'));+ const result = renderChatThreadsForRecord();++ await expect(+ result.current.getAllLinkIdsToThread(RENEWAL_THREAD_ID),+ ).rejects.toThrow('Link lookup failed');+ });++ it('rejects a failed later page instead of detaching only the first links', async () => {+ query+ .mockResolvedValueOnce(+ buildLinksPage({+ linkIds: ['link-1'],+ hasNextPage: true,+ endCursor: 'first-links-page',+ }),+ )+ .mockResolvedValueOnce({ error: new Error('Next page failed') });+ const result = renderChatThreadsForRecord();++ await expect(+ result.current.getAllLinkIdsToThread(RENEWAL_THREAD_ID),+ ).rejects.toThrow('Next page failed');+ });++ it('does not read conversation links without object read permission', async () => {+ useObjectPermissionsForObject.mockReturnValue({+ canReadObjectRecords: false,+ });+ const result = renderChatThreadsForRecord();++ await expect(+ result.current.getAllLinkIdsToThread(RENEWAL_THREAD_ID),+ ).resolves.toEqual([]);+ expect(query).not.toHaveBeenCalled();+ });++ it('reads nothing for an object conversations cannot be attached to', async () => {+ const result = renderChatThreadsForRecord({+ targetObjectNameSingular: 'opportunity',+ });++ act(() => {+ void result.current.fetchMoreThreads();+ });expect(useFindManyRecords).toHaveBeenCalledWith(expect.objectContaining({ skip: true }),);+ expect(fetchMoreRecords).not.toHaveBeenCalled();+ await expect(+ result.current.getAllLinkIdsToThread(RENEWAL_THREAD_ID),+ ).resolves.toEqual([]);+ expect(query).not.toHaveBeenCalled();+ });++ it('loads the next page of linked conversations', async () => {+ const result = renderChatThreadsForRecord();++ await act(async () => {+ await result.current.fetchMoreThreads();+ });++ expect(fetchMoreRecords).toHaveBeenCalledTimes(1);+ expect(result.current.hasNextPage).toBe(true);+ });++ it.each([+ { loading: true, hasNextPage: true },+ { loading: false, hasNextPage: false },+ ])(+ 'skips pagination while loading=$loading and hasNextPage=$hasNextPage',+ ({ loading, hasNextPage }) => {+ useFindManyRecords.mockReturnValue({+ ...findManyRecordsResult,+ loading,+ hasNextPage,+ });+ const result = renderChatThreadsForRecord();++ act(() => {+ void result.current.fetchMoreThreads();+ });++ expect(fetchMoreRecords).not.toHaveBeenCalled();+ },+ );++ it('does not overlap a page request already pending for this query', () => {+ const store = createStore();+ store.set(+ isFetchingMoreRecordsFamilyState.atomFamily(QUERY_IDENTIFIER),+ true,+ );+ const result = renderChatThreadsForRecord({ store });++ act(() => {+ void result.current.fetchMoreThreads();+ });++ expect(result.current.isFetchingMoreThreads).toBe(true);+ expect(fetchMoreRecords).not.toHaveBeenCalled();});it('reads the links again when a conversation is filed under a record', () => {@@ -199,6 +398,45 @@ describe('useChatThreadsForRecord', () => {});expect(refetch).toHaveBeenCalledTimes(1);+ expect(refetch).toHaveBeenCalledWith({+ limit: 20,+ lastCursor: undefined,+ });+ });++ it('keeps every loaded link when refreshing after a mutation or retrying', async () => {+ const loadedLinks = Array.from({ length: 40 }, (_, linkIndex) =>+ buildLink({+ id: `link-${linkIndex}`,+ threadId: RENEWAL_THREAD_ID,+ title: 'Renewal prep',+ }),+ );+ useFindManyRecords.mockReturnValue({+ ...findManyRecordsResult,+ records: loadedLinks,+ });+ const result = renderChatThreadsForRecord();++ dispatchThreadOperation({+ type: 'delete-one',+ deletedRecordId: ONBOARDING_THREAD_ID,+ });++ await act(async () => {+ await result.current.refetch();+ });++ expect(result.current.threads).toHaveLength(1);+ expect(refetch).toHaveBeenCalledTimes(2);+ expect(refetch).toHaveBeenNthCalledWith(1, {+ limit: loadedLinks.length,+ lastCursor: undefined,+ });+ expect(refetch).toHaveBeenNthCalledWith(2, {+ limit: loadedLinks.length,+ lastCursor: undefined,+ });});it.each([diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadSubtitleContent.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadSubtitleContent.tsnew file mode 100644index 00000000000..4386f4b4e34--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadSubtitleContent.ts@@ -0,0 +1,27 @@+import { agentChatDraftPreviewTextFamilySelector } from '@/ai/states/selectors/agentChatDraftPreviewTextFamilySelector';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { getAgentChatThreadSubtitleContent } from '@/ai/utils/getAgentChatThreadSubtitleContent';+import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';+import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';+import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';++export const useAgentChatThreadSubtitleContent = (+ thread: AgentChatThreadRecord,+) => {+ const currentWorkspaceMember = useAtomStateValue(currentWorkspaceMemberState);+ const currentWorkspaceMembers = useAtomStateValue(+ currentWorkspaceMembersState,+ );+ const draftPreviewText = useAtomFamilySelectorValue(+ agentChatDraftPreviewTextFamilySelector,+ thread.id,+ );++ return getAgentChatThreadSubtitleContent({+ thread,+ draftPreviewText,+ workspaceMembers: currentWorkspaceMembers,+ currentWorkspaceMemberId: currentWorkspaceMember?.id,+ });+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useChatThreadsForRecord.ts b/packages/twenty-front/src/modules/ai/hooks/useChatThreadsForRecord.tsindex 960385b8c0d..ca42c0467ac 100644--- a/packages/twenty-front/src/modules/ai/hooks/useChatThreadsForRecord.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useChatThreadsForRecord.ts@@ -1,4 +1,3 @@-import uniqBy from 'lodash.uniqby';import { useCallback, useMemo } from 'react';import {CoreObjectNameSingular,@@ -9,18 +8,28 @@ import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';import { getActivityTargetsFilter } from '@/activities/utils/getActivityTargetsFilter';import { type AgentChatThreadTargetRecord } from '@/ai/types/AgentChatThreadTargetRecord';-import { sortChatThreadsByLastActivityDesc } from '@/ai/utils/sortChatThreadsByLastActivityDesc';+import { fetchAllChatThreadLinkIds } from '@/ai/utils/fetchAllChatThreadLinkIds';+import { getChatThreadsForRecordPage } from '@/ai/utils/getChatThreadsForRecordPage';import { useListenToObjectRecordOperationBrowserEvent } from '@/browser-event/hooks/useListenToObjectRecordOperationBrowserEvent';+import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';import { useFindManyRecords } from '@/object-record/hooks/useFindManyRecords';+import { useFindManyRecordsQuery } from '@/object-record/hooks/useFindManyRecordsQuery';+import { useObjectPermissionsForObject } from '@/object-record/hooks/useObjectPermissionsForObject';import { useObjectMorphJunctionConfig } from '@/object-record/record-field/ui/hooks/useObjectMorphJunctionConfig';+import { isFetchingMoreRecordsFamilyState } from '@/object-record/states/isFetchingMoreRecordsFamilyState';import { type ObjectRecordOperation } from '@/object-record/types/ObjectRecordOperation';import { useListenToEventsForQuery } from '@/sse-db-event/hooks/useListenToEventsForQuery';import { type TargetRecordIdentifier } from '@/ui/layout/contexts/TargetRecordIdentifier';+import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyStateValue';-// A card of recent conversations, never paged further.const CHAT_THREADS_FOR_RECORD_PAGE_SIZE = 20;+const CHAT_THREAD_LINK_GQL_FIELDS = {+ id: true,+ threadId: true,+} satisfies RecordGqlFields;+const CHAT_THREADS_FOR_RECORD_GQL_FIELDS = {id: true,threadId: true,@@ -28,7 +37,9 @@ const CHAT_THREADS_FOR_RECORD_GQL_FIELDS = {id: true,title: true,deletedAt: true,+ createdAt: true,updatedAt: true,+ channelId: true,lastActivityAt: true,lastMessageText: true,lastMessageSenderWorkspaceMemberId: true,@@ -58,6 +69,7 @@ export const useChatThreadsForRecord = ({id,targetObjectNameSingular,}: TargetRecordIdentifier) => {+ const apolloCoreClient = useApolloCoreClient();const { objectMetadataItems } = useObjectMetadataItems();const junctionConfig = useObjectMorphJunctionConfig({objectNameSingular: CoreObjectNameSingular.AgentChatThread,@@ -86,6 +98,9 @@ export const useChatThreadsForRecord = ({loading,error,refetch,+ fetchMoreRecords,+ hasNextPage,+ queryIdentifier,} = useFindManyRecords<AgentChatThreadTargetRecord>({objectNameSingular: CoreObjectNameSingular.AgentChatThreadTarget,skip: !isRecordLinkable,@@ -99,6 +114,39 @@ export const useChatThreadsForRecord = ({limit: CHAT_THREADS_FOR_RECORD_PAGE_SIZE,});+ const { findManyRecordsQuery: findThreadLinksQuery } =+ useFindManyRecordsQuery({+ objectNameSingular: CoreObjectNameSingular.AgentChatThreadTarget,+ recordGqlFields: CHAT_THREAD_LINK_GQL_FIELDS,+ });+ const { canReadObjectRecords } = useObjectPermissionsForObject(+ junctionConfig?.junctionObjectMetadata.id ?? '',+ );++ const { threads, refetchLimit } = getChatThreadsForRecordPage({+ links,+ pageSize: CHAT_THREADS_FOR_RECORD_PAGE_SIZE,+ });++ const isFetchingMoreRecords = useAtomFamilyStateValue(+ isFetchingMoreRecordsFamilyState,+ queryIdentifier,+ );++ const fetchMoreThreads = useCallback(() => {+ if (!isRecordLinkable || !hasNextPage || loading || isFetchingMoreRecords) {+ return;+ }++ return fetchMoreRecords();+ }, [+ fetchMoreRecords,+ hasNextPage,+ isFetchingMoreRecords,+ isRecordLinkable,+ loading,+ ]);+const operationSignature = useMemo(() => ({objectNameSingular: CoreObjectNameSingular.AgentChatThreadTarget,@@ -113,9 +161,18 @@ export const useChatThreadsForRecord = ({skip: !isRecordLinkable,});+ const refetchThreads = useCallback(+ () =>+ refetch({+ limit: refetchLimit,+ lastCursor: undefined,+ }),+ [refetchLimit, refetch],+ );+const refetchLinks = useCallback(() => {- void refetch();- }, [refetch]);+ void refetchThreads();+ }, [refetchThreads]);useListenToObjectRecordOperationBrowserEvent({onObjectRecordOperationBrowserEvent: refetchLinks,@@ -124,17 +181,28 @@ export const useChatThreadsForRecord = ({enabled: isRecordLinkable,});- // Custom legs allow duplicate links; sorted since an update doesn't reorder the fetched page.- const threads = useMemo(- () =>- sortChatThreadsByLastActivityDesc(- uniqBy(links.map(({ thread }) => thread).filter(isDefined), 'id'),- ),- [links],- );-- const getLinkIdsToThread = (threadId: string) =>- links.filter((link) => link.threadId === threadId).map(({ id }) => id);+ const getAllLinkIdsToThread = async (threadId: string) => {+ if (+ !isRecordLinkable ||+ !canReadObjectRecords ||+ !isDefined(junctionConfig) ||+ !isDefined(filter)+ ) {+ return [];+ }++ return fetchAllChatThreadLinkIds({+ apolloCoreClient,+ query: findThreadLinksQuery,+ filter: {+ and: [+ filter,+ { [junctionConfig.sourceJoinColumnName]: { eq: threadId } },+ ],+ },+ objectNamePlural: junctionConfig.junctionObjectMetadata.namePlural,+ });+ };useListenToObjectRecordOperationBrowserEvent({onObjectRecordOperationBrowserEvent: refetchLinks,@@ -143,5 +211,14 @@ export const useChatThreadsForRecord = ({enabled: isRecordLinkable && isDefined(chatObjectMetadataItem),});- return { threads, getLinkIdsToThread, loading, error, refetch };+ return {+ threads,+ getAllLinkIdsToThread,+ loading,+ error,+ refetch: refetchThreads,+ fetchMoreThreads,+ hasNextPage,+ isFetchingMoreThreads: isFetchingMoreRecords,+ };};diff --git a/packages/twenty-front/src/modules/ai/types/AgentChatThreadDateGroup.ts b/packages/twenty-front/src/modules/ai/types/AgentChatThreadDateGroup.tsnew file mode 100644index 00000000000..bb9a47404e7--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AgentChatThreadDateGroup.ts@@ -0,0 +1,7 @@+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';++export type AgentChatThreadDateGroup = {+ id: string;+ title: string;+ threads: AgentChatThreadRecord[];+};diff --git a/packages/twenty-front/src/modules/ai/types/AiChatThreadListVariant.ts b/packages/twenty-front/src/modules/ai/types/AiChatThreadListVariant.tsnew file mode 100644index 00000000000..e7157ba0a62--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AiChatThreadListVariant.ts@@ -0,0 +1 @@+export type AiChatThreadListVariant = 'default' | 'compact';diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatThreadSubtitleContent.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatThreadSubtitleContent.test.tsnew file mode 100644index 00000000000..6ca0482eb64--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatThreadSubtitleContent.test.ts@@ -0,0 +1,71 @@+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { getAgentChatThreadSubtitleContent } from '@/ai/utils/getAgentChatThreadSubtitleContent';++const buildThread = (+ thread: Partial<AgentChatThreadRecord> = {},+): AgentChatThreadRecord => ({+ __typename: 'AgentChatThread',+ id: 'thread',+ title: 'Renewal prep',+ deletedAt: null,+ createdAt: '2026-10-28T10:00:00.000Z',+ updatedAt: '2026-10-28T10:00:00.000Z',+ ...thread,+});++const getContent = ({+ thread = buildThread(),+ draftPreviewText,+}: {+ thread?: AgentChatThreadRecord;+ draftPreviewText?: string;+}) =>+ getAgentChatThreadSubtitleContent({+ thread,+ draftPreviewText,+ workspaceMembers: [],+ currentWorkspaceMemberId: undefined,+ });++describe('getAgentChatThreadSubtitleContent', () => {+ it('has no content without a message, draft or pending question', () => {+ expect(getContent({})).toEqual({+ isAwaitingAnswer: false,+ hasDraft: false,+ previewText: null,+ hasContent: false,+ });+ });++ it('previews the draft over the last message', () => {+ expect(+ getContent({+ thread: buildThread({ lastMessageText: 'Sent earlier' }),+ draftPreviewText: 'Unsent reply',+ }),+ ).toMatchObject({+ hasDraft: true,+ previewText: 'Unsent reply',+ hasContent: true,+ });+ });++ it('has content while a question awaits an answer', () => {+ expect(+ getContent({+ thread: buildThread({ pendingQuestionMessageId: 'question' }),+ }),+ ).toMatchObject({ isAwaitingAnswer: true, hasContent: true });+ });++ it('ignores a pending question on a deleted conversation', () => {+ expect(+ getContent({+ thread: buildThread({+ pendingQuestionMessageId: 'question',+ deletedAt: '2026-10-28T11:00:00.000Z',+ }),+ }),+ ).toMatchObject({ isAwaitingAnswer: false, hasContent: false });+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getChatThreadsForRecordPage.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getChatThreadsForRecordPage.test.tsnew file mode 100644index 00000000000..0cc154d28a2--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getChatThreadsForRecordPage.test.ts@@ -0,0 +1,101 @@+import { QUERY_MAX_RECORDS } from 'twenty-shared/constants';++import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { type AgentChatThreadTargetRecord } from '@/ai/types/AgentChatThreadTargetRecord';+import { getChatThreadsForRecordPage } from '@/ai/utils/getChatThreadsForRecordPage';++const PAGE_SIZE = 20;++const buildThread = ({+ id,+ updatedAt,+ lastActivityAt,+}: {+ id: string;+ updatedAt: string;+ lastActivityAt?: string;+}): AgentChatThreadRecord => ({+ __typename: 'AgentChatThread',+ id,+ title: id,+ deletedAt: null,+ createdAt: updatedAt,+ updatedAt,+ lastActivityAt,+});++const buildLink = ({+ id,+ thread,+}: {+ id: string;+ thread?: AgentChatThreadRecord | null;+}): AgentChatThreadTargetRecord => ({+ __typename: 'AgentChatThreadTarget',+ id,+ threadId: thread?.id ?? 'missing-thread',+ thread,+});++describe('getChatThreadsForRecordPage', () => {+ it('sorts unique conversations by activity while skipping missing records', () => {+ const olderThread = buildThread({+ id: 'older-thread',+ updatedAt: '2026-09-28T10:00:00.000Z',+ lastActivityAt: '2026-09-28T09:00:00.000Z',+ });+ const newerThread = buildThread({+ id: 'newer-thread',+ updatedAt: '2026-09-29T10:00:00.000Z',+ });+ const links = [+ buildLink({ id: 'older-link', thread: olderThread }),+ buildLink({ id: 'missing-link' }),+ buildLink({ id: 'newer-link', thread: newerThread }),+ buildLink({ id: 'duplicate-link', thread: olderThread }),+ buildLink({ id: 'deleted-link', thread: null }),+ ];++ const page = getChatThreadsForRecordPage({ links, pageSize: PAGE_SIZE });++ expect(page.threads).toEqual([newerThread, olderThread]);+ expect(links[0].thread).toBe(olderThread);+ });++ it('refreshes every loaded link even when all links describe one conversation', () => {+ const thread = buildThread({+ id: 'repeated-thread',+ updatedAt: '2026-09-28T10:00:00.000Z',+ });+ const links = Array.from({ length: 40 }, (_, index) =>+ buildLink({ id: `link-${index}`, thread }),+ );++ const page = getChatThreadsForRecordPage({ links, pageSize: PAGE_SIZE });++ expect(page.threads).toEqual([thread]);+ expect(page.refetchLimit).toBe(40);+ });++ it('caps the refresh at the maximum records per query', () => {+ const links = Array.from({ length: QUERY_MAX_RECORDS + 20 }, (_, index) =>+ buildLink({+ id: `link-${index}`,+ thread: buildThread({+ id: `thread-${index}`,+ updatedAt: '2026-09-28T10:00:00.000Z',+ }),+ }),+ );++ const page = getChatThreadsForRecordPage({ links, pageSize: PAGE_SIZE });++ expect(page.refetchLimit).toBe(QUERY_MAX_RECORDS);+ });++ it('requests a full first page when no links are loaded', () => {+ expect(+ getChatThreadsForRecordPage({ links: [], pageSize: PAGE_SIZE }),+ ).toEqual({ threads: [], refetchLimit: PAGE_SIZE });+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.tsindex 5c893dea570..2699dc1396e 100644--- a/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts@@ -1,3 +1,5 @@+import { CalendarStartDay } from 'twenty-shared/constants';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';import { groupThreadsByDate } from '@/ai/utils/groupThreadsByDate';@@ -17,7 +19,13 @@ describe('groupThreadsByDate', () => {const eightDaysAgo = getDateDaysAgo(8);const fourteenDaysAgo = getDateDaysAgo(14);- const buildThread = (id: string, updatedAt: Date): AgentChatThreadRecord => ({+ const buildThread = ({+ id,+ updatedAt,+ }: {+ id: string;+ updatedAt: Date;+ }): AgentChatThreadRecord => ({__typename: 'AgentChatThread',id,title: 'Test Thread',@@ -33,15 +41,15 @@ describe('groupThreadsByDate', () => {});const threads: AgentChatThreadRecord[] = [- buildThread('1', today),- buildThread('2', yesterday),- buildThread('3', twoDaysAgo),- buildThread('4', sevenDaysAgo),- buildThread('5', eightDaysAgo),- buildThread('6', fourteenDaysAgo),+ buildThread({ id: '1', updatedAt: today }),+ buildThread({ id: '2', updatedAt: yesterday }),+ buildThread({ id: '3', updatedAt: twoDaysAgo }),+ buildThread({ id: '4', updatedAt: sevenDaysAgo }),+ buildThread({ id: '5', updatedAt: eightDaysAgo }),+ buildThread({ id: '6', updatedAt: fourteenDaysAgo }),];- const result = groupThreadsByDate(threads, today);+ const result = groupThreadsByDate({ threads, today });expect(result).toHaveLength(4);expect(result[0]).toMatchObject({@@ -67,24 +75,126 @@ describe('groupThreadsByDate', () => {});it('returns no groups if no threads', () => {- expect(groupThreadsByDate([], today)).toEqual([]);+ expect(groupThreadsByDate({ threads: [], today })).toEqual([]);+ expect(+ groupThreadsByDate({ threads: [], today, variant: 'compact' }),+ ).toEqual([]);});it('groups a thread by its last update', () => {- const [group] = groupThreadsByDate([buildThread('1', yesterday)], today);+ const [group] = groupThreadsByDate({+ threads: [buildThread({ id: '1', updatedAt: yesterday })],+ today,+ });expect(group.id).toBe('yesterday');});+ describe('compact groups', () => {+ const compactToday = new Date('2026-10-28T12:00:00Z');++ it('uses the current calendar week and keeps group order for compact lists', () => {+ const threads = [+ buildThread({+ id: 'sunday',+ updatedAt: new Date('2026-10-25T10:00:00Z'),+ }),+ buildThread({+ id: 'yesterday',+ updatedAt: new Date('2026-10-27T10:00:00Z'),+ }),+ buildThread({+ id: 'today',+ updatedAt: new Date('2026-10-28T10:00:00Z'),+ }),+ buildThread({+ id: 'september',+ updatedAt: new Date('2026-09-12T10:00:00Z'),+ }),+ buildThread({+ id: 'monday',+ updatedAt: new Date('2026-10-26T10:00:00Z'),+ }),+ ];++ const groups = groupThreadsByDate({+ threads,+ today: compactToday,+ variant: 'compact',+ });++ expect(+ groups.map(({ id, threads: groupedThreads }) => ({+ id,+ threadIds: groupedThreads.map(({ id: threadId }) => threadId),+ })),+ ).toEqual([+ { id: 'today', threadIds: ['today'] },+ { id: 'this-week', threadIds: ['yesterday', 'monday'] },+ { id: 'earlier', threadIds: ['sunday', 'september'] },+ ]);+ });++ it('starts the compact week on the calendar start day', () => {+ const groups = groupThreadsByDate({+ threads: [+ buildThread({+ id: 'sunday',+ updatedAt: new Date('2026-10-25T10:00:00Z'),+ }),+ buildThread({+ id: 'saturday',+ updatedAt: new Date('2026-10-24T10:00:00Z'),+ }),+ ],+ today: compactToday,+ variant: 'compact',+ calendarStartDay: CalendarStartDay.SUNDAY,+ });++ expect(+ groups.map(({ id, threads: groupedThreads }) => ({+ id,+ threadIds: groupedThreads.map(({ id: threadId }) => threadId),+ })),+ ).toEqual([+ { id: 'this-week', threadIds: ['sunday'] },+ { id: 'earlier', threadIds: ['saturday'] },+ ]);+ });++ it('omits empty compact groups and keeps future activity in Today', () => {+ const groups = groupThreadsByDate({+ threads: [+ buildThread({+ id: 'future',+ updatedAt: new Date('2026-10-29T10:00:00Z'),+ }),+ buildThread({+ id: 'earlier',+ updatedAt: new Date('2026-09-12T10:00:00Z'),+ }),+ ],+ today: compactToday,+ variant: 'compact',+ });++ expect(groups.map(({ id }) => id)).toEqual(['today', 'earlier']);+ });+ });+describe('timezone handling', () => {it('keeps a thread last touched a few hours ago in Today across DST/midnight boundaries', () => {const todayLate = new Date('2026-04-26T23:30:00');const todayEarly = new Date('2026-04-26T00:15:00');- const result = groupThreadsByDate(- [buildThread('late', todayLate), buildThread('early', todayEarly)],+ const result = groupThreadsByDate({+ threads: [+ buildThread({ id: 'late', updatedAt: todayLate }),+ buildThread({ id: 'early', updatedAt: todayEarly }),+ ],today,- );+ });expect(result).toHaveLength(1);expect(result[0]).toMatchObject({@@ -96,10 +206,12 @@ describe('groupThreadsByDate', () => {it('places a thread last touched late yesterday in the Yesterday bucket', () => {const yesterdayJustBeforeMidnight = new Date('2026-04-25T23:59:00');- const [group] = groupThreadsByDate(- [buildThread('y', yesterdayJustBeforeMidnight)],+ const [group] = groupThreadsByDate({+ threads: [+ buildThread({ id: 'y', updatedAt: yesterdayJustBeforeMidnight }),+ ],today,- );+ });expect(group.id).toBe('yesterday');});@@ -107,10 +219,10 @@ describe('groupThreadsByDate', () => {it('does not slip a thread from yesterday into Today when local times differ by hours', () => {const yesterdayMorning = new Date('2026-04-25T08:00:00');- const [group] = groupThreadsByDate(- [buildThread('y', yesterdayMorning)],+ const [group] = groupThreadsByDate({+ threads: [buildThread({ id: 'y', updatedAt: yesterdayMorning })],today,- );+ });expect(group.id).toBe('yesterday');});diff --git a/packages/twenty-front/src/modules/ai/utils/fetchAllChatThreadLinkIds.ts b/packages/twenty-front/src/modules/ai/utils/fetchAllChatThreadLinkIds.tsnew file mode 100644index 00000000000..9f13afd2cd6--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/fetchAllChatThreadLinkIds.ts@@ -0,0 +1,64 @@+import { type ApolloClient } from '@apollo/client';+import { isNonEmptyString } from '@sniptt/guards';+import { type DocumentNode } from 'graphql';+import { doNotTranslate } from 'twenty-shared/i18n';+import { type RecordGqlOperationFilter } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { DEFAULT_QUERY_PAGE_SIZE } from '@/object-record/constants/DefaultQueryPageSize';+import { type RecordGqlOperationFindManyResult } from '@/object-record/graphql/types/RecordGqlOperationFindManyResult';++export const fetchAllChatThreadLinkIds = async ({+ apolloCoreClient,+ query,+ filter,+ objectNamePlural,+}: {+ apolloCoreClient: ApolloClient;+ query: DocumentNode;+ filter: RecordGqlOperationFilter;+ objectNamePlural: string;+}): Promise<string[]> => {+ const linkIds: string[] = [];+ let lastCursor: string | undefined;+ let hasNextPage = true;++ while (hasNextPage) {+ const { data, error } =+ await apolloCoreClient.query<RecordGqlOperationFindManyResult>({+ query,+ variables: {+ filter,+ limit: DEFAULT_QUERY_PAGE_SIZE,+ lastCursor,+ },+ fetchPolicy: 'network-only',+ });++ if (isDefined(error)) {+ throw error;+ }++ const connection = data?.[objectNamePlural];++ for (const { node } of connection?.edges ?? []) {+ linkIds.push(node.id);+ }++ hasNextPage = connection?.pageInfo?.hasNextPage === true;++ const nextCursor = connection?.pageInfo?.endCursor;+ const canAdvanceCursor =+ isNonEmptyString(nextCursor) && nextCursor !== lastCursor;++ if (hasNextPage && !canAdvanceCursor) {+ throw new Error(+ doNotTranslate('Unable to load the next page of conversation links.'),+ );+ }++ lastCursor = nextCursor ?? undefined;+ }++ return linkIds;+};diff --git a/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadSubtitleContent.ts b/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadSubtitleContent.tsnew file mode 100644index 00000000000..55dc5560794--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadSubtitleContent.ts@@ -0,0 +1,35 @@+import { isDefined, isNonEmptyString } from 'twenty-shared/utils';++import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { getAgentChatThreadPreviewText } from '@/ai/utils/getAgentChatThreadPreviewText';+import { type PartialWorkspaceMember } from '@/settings/roles/types/RoleWithPartialMembers';++export const getAgentChatThreadSubtitleContent = ({+ thread,+ draftPreviewText,+ workspaceMembers,+ currentWorkspaceMemberId,+}: {+ thread: AgentChatThreadRecord;+ draftPreviewText: string | null | undefined;+ workspaceMembers: PartialWorkspaceMember[];+ currentWorkspaceMemberId: string | undefined;+}) => {+ const isAwaitingAnswer =+ !isDefined(thread.deletedAt) && isDefined(thread.pendingQuestionMessageId);+ const hasDraft = isNonEmptyString(draftPreviewText);+ const previewText = hasDraft+ ? draftPreviewText+ : getAgentChatThreadPreviewText({+ thread,+ workspaceMembers,+ currentWorkspaceMemberId,+ });++ return {+ isAwaitingAnswer,+ hasDraft,+ previewText,+ hasContent: isAwaitingAnswer || hasDraft || isNonEmptyString(previewText),+ };+};diff --git a/packages/twenty-front/src/modules/ai/utils/getChatThreadsForRecordPage.ts b/packages/twenty-front/src/modules/ai/utils/getChatThreadsForRecordPage.tsnew file mode 100644index 00000000000..8eb7b69e6ef--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getChatThreadsForRecordPage.ts@@ -0,0 +1,19 @@+import uniqBy from 'lodash.uniqby';+import { QUERY_MAX_RECORDS } from 'twenty-shared/constants';+import { isDefined } from 'twenty-shared/utils';++import { type AgentChatThreadTargetRecord } from '@/ai/types/AgentChatThreadTargetRecord';+import { sortChatThreadsByLastActivityDesc } from '@/ai/utils/sortChatThreadsByLastActivityDesc';++export const getChatThreadsForRecordPage = ({+ links,+ pageSize,+}: {+ links: AgentChatThreadTargetRecord[];+ pageSize: number;+}) => ({+ threads: sortChatThreadsByLastActivityDesc(+ uniqBy(links.map(({ thread }) => thread).filter(isDefined), 'id'),+ ),+ refetchLimit: Math.min(Math.max(links.length, pageSize), QUERY_MAX_RECORDS),+});diff --git a/packages/twenty-front/src/modules/ai/utils/groupThreadsByDate.ts b/packages/twenty-front/src/modules/ai/utils/groupThreadsByDate.tsindex 57065df202d..843eb6c536f 100644--- a/packages/twenty-front/src/modules/ai/utils/groupThreadsByDate.ts+++ b/packages/twenty-front/src/modules/ai/utils/groupThreadsByDate.ts@@ -1,17 +1,15 @@import { t } from '@lingui/core/macro';-import { differenceInCalendarDays } from 'date-fns';+import { differenceInCalendarDays, startOfWeek } from 'date-fns';+import { CalendarStartDay } from 'twenty-shared/constants';+import { isDefined } from 'twenty-shared/utils';+import { type AgentChatThreadDateGroup } from '@/ai/types/AgentChatThreadDateGroup';import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { type AiChatThreadListVariant } from '@/ai/types/AiChatThreadListVariant';import { getAgentChatThreadLastActivityAt } from '@/ai/utils/getAgentChatThreadLastActivityAt';-export type AgentChatThreadDateGroup = {- id: string;- title: string;- threads: AgentChatThreadRecord[];-};--const getLocalDayDifference = (date: Date, today: Date) =>- differenceInCalendarDays(today, date);+const RECENT_THREAD_DAY_COUNT = 7;+const COMPACT_DATE_GROUP_IDS = ['today', 'this-week', 'earlier'];const getMonthGroupId = (date: Date) =>`month:${date.getFullYear()}-${date.getMonth() + 1}`;@@ -22,27 +20,81 @@ const formatMonthGroupTitle = (date: Date) =>year: 'numeric',}).format(date);-const getThreadDateGroup = (- threadActivityAt: Date,- today: Date,-): Omit<AgentChatThreadDateGroup, 'threads'> => {- const localDayDifference = getLocalDayDifference(threadActivityAt, today);+const getDaysSinceWeekStart = ({+ today,+ calendarStartDay,+}: {+ today: Date;+ calendarStartDay: CalendarStartDay;+}) =>+ differenceInCalendarDays(+ today,+ startOfWeek(today, {+ weekStartsOn:+ calendarStartDay === CalendarStartDay.SYSTEM+ ? CalendarStartDay.MONDAY+ : calendarStartDay,+ }),+ );++const getCompactPastThreadDateGroup = ({+ daysSinceActivity,+ daysSinceWeekStart,+}: {+ daysSinceActivity: number;+ daysSinceWeekStart: number;+}): Omit<AgentChatThreadDateGroup, 'threads'> => {+ if (daysSinceActivity <= daysSinceWeekStart) {+ return {+ id: 'this-week',+ title: t`This week`,+ };+ }++ return {+ id: 'earlier',+ title: t`Earlier`,+ };+};++const getThreadDateGroup = ({+ threadActivityAt,+ today,+ variant,+ daysSinceWeekStart,+}: {+ threadActivityAt: Date;+ today: Date;+ variant: AiChatThreadListVariant;+ daysSinceWeekStart: number;+}): Omit<AgentChatThreadDateGroup, 'threads'> => {+ const daysSinceActivity = differenceInCalendarDays(today, threadActivityAt);+ const isToday = daysSinceActivity === 0;+ const isUpcomingCompactThread =+ variant === 'compact' && daysSinceActivity < 0;- if (localDayDifference === 0) {+ if (isToday || isUpcomingCompactThread) {return {id: 'today',title: t`Today`,};}- if (localDayDifference === 1) {+ if (variant === 'compact') {+ return getCompactPastThreadDateGroup({+ daysSinceActivity,+ daysSinceWeekStart,+ });+ }++ if (daysSinceActivity === 1) {return {id: 'yesterday',title: t`Yesterday`,};}- if (localDayDifference >= 2 && localDayDifference <= 7) {+ if (daysSinceActivity >= 2 && daysSinceActivity <= RECENT_THREAD_DAY_COUNT) {return {id: 'previous-7-days',title: t`Previous 7 days`,@@ -55,29 +107,47 @@ const getThreadDateGroup = (};};-export const groupThreadsByDate = (- threads: AgentChatThreadRecord[],+export const groupThreadsByDate = ({+ threads,today = new Date(),-): AgentChatThreadDateGroup[] => {+ variant = 'default',+ calendarStartDay = CalendarStartDay.MONDAY,+}: {+ threads: AgentChatThreadRecord[];+ today?: Date;+ variant?: AiChatThreadListVariant;+ calendarStartDay?: CalendarStartDay;+}): AgentChatThreadDateGroup[] => {const groupedThreadsByDate = new Map<string, AgentChatThreadDateGroup>();+ const daysSinceWeekStart = getDaysSinceWeekStart({ today, calendarStartDay });for (const thread of threads) {- const threadDateGroup = getThreadDateGroup(- new Date(getAgentChatThreadLastActivityAt(thread)),+ const threadDateGroup = getThreadDateGroup({+ threadActivityAt: new Date(getAgentChatThreadLastActivityAt(thread)),today,- );+ variant,+ daysSinceWeekStart,+ });const existingThreadDateGroup = groupedThreadsByDate.get(threadDateGroup.id,);- if (existingThreadDateGroup !== undefined) {+ if (isDefined(existingThreadDateGroup)) {existingThreadDateGroup.threads.push(thread);- } else {- groupedThreadsByDate.set(threadDateGroup.id, {- ...threadDateGroup,- threads: [thread],- });++ continue;}++ groupedThreadsByDate.set(threadDateGroup.id, {+ ...threadDateGroup,+ threads: [thread],+ });+ }++ if (variant === 'compact') {+ return COMPACT_DATE_GROUP_IDS.map((groupId) =>+ groupedThreadsByDate.get(groupId),+ ).filter(isDefined);}return [...groupedThreadsByDate.values()];diff --git a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/ChatThreadsCard.tsx b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/ChatThreadsCard.tsxindex 8e42d5a800a..e8bc3ec9c2c 100644--- a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/ChatThreadsCard.tsx+++ b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/ChatThreadsCard.tsx@@ -1,24 +1,57 @@+import { t } from '@lingui/core/macro';+import { useChatThreadsForRecord } from '@/ai/hooks/useChatThreadsForRecord';import { useDetachChatThreadFromRecord } from '@/ai/hooks/useDetachChatThreadFromRecord';import { ChatThreadsCardContent } from '@/page-layout/widgets/chat-threads/components/ChatThreadsCardContent';import { useTargetRecord } from '@/ui/layout/contexts/useTargetRecord';+import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';+import { useToast } from 'twenty-ui/components/feedback';+import { Button } from 'twenty-ui/primitives/input';-// No WidgetHeaderCountEffect: only one page is fetched, so the row count isn't the total.export const ChatThreadsCard = () => {const targetRecord = useTargetRecord();- const { threads, getLinkIdsToThread, loading, error, refetch } =- useChatThreadsForRecord(targetRecord);+ const {+ threads,+ getAllLinkIdsToThread,+ loading,+ error,+ refetch,+ hasNextPage,+ fetchMoreThreads,+ isFetchingMoreThreads,+ } = useChatThreadsForRecord(targetRecord);const { detachChatThreadFromRecord } = useDetachChatThreadFromRecord();+ const { enqueueToast } = useToast();++ const handleDetachThread = async (threadId: string) => {+ try {+ const linkIds = await getAllLinkIdsToThread(threadId);++ await detachChatThreadFromRecord(linkIds);+ } catch (error) {+ enqueueToast(getToastOptionsFromError({ error }));+ }+ };return (<ChatThreadsCardContentloading={loading}error={error}onRetry={() => void refetch()}- onDetachThread={(threadId) =>- void detachChatThreadFromRecord(getLinkIdsToThread(threadId))- }+ onDetachThread={(threadId) => void handleDetachThread(threadId)}threads={threads}+ hasNextPage={hasNextPage}+ pagination={+ hasNextPage && (+ <Button+ variant="ghost"+ onClick={() => void fetchMoreThreads()}+ disabled={loading || isFetchingMoreThreads}+ >+ {isFetchingMoreThreads ? t`Loading…` : t`Load more conversations`}+ </Button>+ )+ }/>);};diff --git a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/ChatThreadsCardContent.tsx b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/ChatThreadsCardContent.tsxindex 091fc662355..5998576a4ff 100644--- a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/ChatThreadsCardContent.tsx+++ b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/ChatThreadsCardContent.tsx@@ -1,7 +1,8 @@import { styled } from '@linaria/react';import { t } from '@lingui/core/macro';+import { type ReactNode } from 'react';import { CoreObjectNameSingular } from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';import { IconRefresh } from 'twenty-ui/icon';import { Button } from 'twenty-ui/primitives/input';import { themeCssVariables } from 'twenty-ui/theme';@@ -22,9 +23,10 @@ const StyledThreadsContainer = styled.div`display: flex;flex: 1;flex-direction: column;+ gap: ${themeCssVariables.spacing[2]};height: 100%;+ min-width: 0;overflow: auto;- padding: ${themeCssVariables.spacing[2]};`;type ChatThreadsCardContentProps = {@@ -33,6 +35,8 @@ type ChatThreadsCardContentProps = {onRetry: () => void;onDetachThread: (threadId: string) => void;threads: AgentChatThreadRecord[];+ hasNextPage?: boolean;+ pagination?: ReactNode;};export const ChatThreadsCardContent = ({@@ -41,6 +45,8 @@ export const ChatThreadsCardContent = ({onRetry,onDetachThread,threads,+ hasNextPage = false,+ pagination,}: ChatThreadsCardContentProps) => {const { openRecordInSidePanel } = useOpenRecordInSidePanel();const isSidePanelOpened = useAtomStateValue(isSidePanelOpenedState);@@ -54,7 +60,7 @@ export const ChatThreadsCardContent = ({CoreObjectNameSingular.AgentChatThread? sidePanelRecord.objectRecordId: undefined;- const isThreadsEmpty = threads.length === 0;+ const isThreadsEmpty = !isNonEmptyArray(threads);if (loading && isThreadsEmpty) {return <SkeletonLoader />;@@ -81,7 +87,7 @@ export const ChatThreadsCardContent = ({);}- if (isThreadsEmpty) {+ if (isThreadsEmpty && !hasNextPage) {return (<EmptyState.Root><AnimatedPlaceholder type="emptyInbox" />@@ -99,6 +105,7 @@ export const ChatThreadsCardContent = ({<StyledThreadsContainer><AiChatThreadListthreads={threads}+ variant="compact"selectedThreadIds={isDefined(sidePanelThreadId) ? [sidePanelThreadId] : []}@@ -110,6 +117,7 @@ export const ChatThreadsCardContent = ({}onDetachThread={onDetachThread}/>+ {pagination}</StyledThreadsContainer>);};diff --git a/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/__stories__/ChatThreadsCardContent.stories.tsx b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/__stories__/ChatThreadsCardContent.stories.tsxnew file mode 100644index 00000000000..e4ad4ea6db6--- /dev/null+++ b/packages/twenty-front/src/modules/page-layout/widgets/chat-threads/components/__stories__/ChatThreadsCardContent.stories.tsx@@ -0,0 +1,269 @@+import { styled } from '@linaria/react';+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { isArray } from '@sniptt/guards';+import { type ComponentProps } from 'react';+import mockDatePreview from 'storybook-addon-mock-date/preview';+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';+import { Button } from 'twenty-ui/primitives/input';+import { themeCssVariables } from 'twenty-ui/theme';++import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { currentWorkspaceMembersState } from '@/auth/states/currentWorkspaceMembersState';+import { ChatThreadsCardContent } from '@/page-layout/widgets/chat-threads/components/ChatThreadsCardContent';+import { type PartialWorkspaceMember } from '@/settings/roles/types/RoleWithPartialMembers';+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';+import { MOCKED_DATE } from '~/testing/constants/MockedDate';+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';+import { ToastDecorator } from '~/testing/decorators/ToastDecorator';+import { mockedWorkspaceMemberData } from '~/testing/mock-data/users';+import { getMockedDateWithOffset } from '~/testing/utils/getMockedDateWithOffset';++const WORKSPACE_MEMBERS = [+ {+ ...mockedWorkspaceMemberData,+ id: '20202020-0000-4000-8000-000000000001',+ name: { firstName: 'Sarah', lastName: 'Lin' },+ avatarUrl: null,+ },+ {+ ...mockedWorkspaceMemberData,+ id: '20202020-0000-4000-8000-000000000002',+ name: { firstName: 'Alex', lastName: 'Morgan' },+ avatarUrl: null,+ },+] satisfies PartialWorkspaceMember[];++const createThread = ({+ id,+ title,+ lastActivityAt,+ lastMessageText,+ workspaceMemberId = WORKSPACE_MEMBERS[0].id,+}: {+ id: string;+ title: string;+ lastActivityAt: string;+ lastMessageText: string;+ workspaceMemberId?: string;+}): AgentChatThreadRecord => ({+ __typename: 'AgentChatThread',+ id,+ title,+ deletedAt: null,+ createdAt: lastActivityAt,+ updatedAt: lastActivityAt,+ lastActivityAt,+ lastMessageText,+ workspaceMemberId,+ lastMessageSenderWorkspaceMemberId: workspaceMemberId,+});++const THREADS = [+ createThread({+ id: '20202020-0000-4000-8000-000000000011',+ title: 'Renewal outreach',+ lastActivityAt: MOCKED_DATE,+ lastMessageText:+ 'I shared the renewal details and next steps with the team.',+ }),+ createThread({+ id: '20202020-0000-4000-8000-000000000012',+ title: 'Onboarding follow-up',+ lastActivityAt: getMockedDateWithOffset({ days: -1 }),+ lastMessageText: 'The onboarding checklist is ready for your review.',+ workspaceMemberId: WORKSPACE_MEMBERS[1].id,+ }),+ createThread({+ id: '20202020-0000-4000-8000-000000000013',+ title:+ 'Contract renewal and onboarding details for the upcoming annual agreement',+ lastActivityAt: getMockedDateWithOffset({ days: -8 }),+ lastMessageText: 'The signed agreement is attached to the company record.',+ }),+];++const StyledWidget = styled.div`+ box-sizing: border-box;+ height: 360px;+ min-width: 0;+ padding: ${themeCssVariables.spacing[4]};+ width: 400px;+`;++type ChatThreadsCardContentStoryArgs = ComponentProps<+ typeof ChatThreadsCardContent+> & {+ isFetchingMoreThreads: boolean;+ onLoadMore: () => void;+};++const meta = {+ title: 'Modules/PageLayout/Widgets/ChatThreadsCardContent',+ component: ChatThreadsCardContent,+ decorators: [+ (Story, context) => {+ if ('clock' in Date) {+ return <Story />;+ }++ const mockDateDecorator = isArray(mockDatePreview.decorators)+ ? mockDatePreview.decorators[0]+ : mockDatePreview.decorators;++ mockDateDecorator?.(() => null, context);++ return <Story />;+ },+ MemoryRouterDecorator,+ ToastDecorator,+ ],+ args: {+ loading: false,+ threads: THREADS,+ onRetry: fn(),+ onDetachThread: fn(),+ isFetchingMoreThreads: false,+ onLoadMore: fn(),+ },+ beforeEach: () => {+ jotaiStore.set(currentWorkspaceMembersState.atom, WORKSPACE_MEMBERS);+ },+ render: (args) => (+ <StyledWidget>+ <ChatThreadsCardContent+ loading={args.loading}+ error={args.error}+ threads={args.threads}+ onRetry={args.onRetry}+ onDetachThread={args.onDetachThread}+ hasNextPage={args.hasNextPage}+ pagination={+ args.hasNextPage && (+ <Button+ variant="ghost"+ onClick={args.onLoadMore}+ disabled={args.loading || args.isFetchingMoreThreads}+ >+ {args.isFetchingMoreThreads+ ? 'Loading…'+ : 'Load more conversations'}+ </Button>+ )+ }+ />+ </StyledWidget>+ ),+} satisfies Meta<ChatThreadsCardContentStoryArgs>;++export default meta;+type Story = StoryObj<typeof meta>;++export const Default: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ for (const title of ['Today', 'This week', 'Earlier']) {+ await expect(canvas.getByRole('heading', { name: title })).toBeVisible();+ }++ for (const thread of THREADS) {+ const row = canvas.getByRole('group', { name: thread.title ?? '' });++ await expect(row.getBoundingClientRect().height).toBe(32);+ await expect(row.getBoundingClientRect().width).toBe(368);+ await expect(row.scrollWidth).toBeLessThanOrEqual(row.clientWidth);+ }++ await expect(+ canvas.getByText(+ 'Sarah Lin: I shared the renewal details and next steps with the team.',+ ),+ ).toBeVisible();+ },+};++export const Empty: Story = {+ args: { threads: [] },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await waitFor(() =>+ expect(canvas.getByText('No conversations')).toBeVisible(),+ );+ await expect(+ canvas.queryByRole('button', { name: 'Load more conversations' }),+ ).not.toBeInTheDocument();+ },+};++export const Loading: Story = {+ args: { threads: [], loading: true },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const loadingIndicator = canvasElement.querySelector('[aria-busy="true"]');++ await expect(loadingIndicator).toBeVisible();+ await expect(+ canvas.queryByText('No conversations'),+ ).not.toBeInTheDocument();+ await expect(+ canvas.queryByText("We couldn't load the conversations"),+ ).not.toBeInTheDocument();+ },+};++export const Error: Story = {+ args: {+ threads: [],+ error: new globalThis.Error('Conversations are unavailable'),+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ await expect(+ canvas.getByText("We couldn't load the conversations"),+ ).toBeVisible();+ await userEvent.click(canvas.getByRole('button', { name: 'Try again' }));+ await expect(args.onRetry).toHaveBeenCalledTimes(1);+ },+};++export const LoadMore: Story = {+ args: { hasNextPage: true },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ canvas.getByRole('button', { name: 'Load more conversations' }),+ );+ await expect(args.onLoadMore).toHaveBeenCalledTimes(1);+ },+};++export const EmptyFirstPage: Story = {+ args: { threads: [], hasNextPage: true },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ await expect(+ canvas.queryByText('No conversations'),+ ).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Load more conversations' }),+ );+ await expect(args.onLoadMore).toHaveBeenCalledTimes(1);+ },+};++export const LoadingMore: Story = {+ args: { hasNextPage: true, isFetchingMoreThreads: true },+ play: async ({ canvasElement, args }) => {+ const button = within(canvasElement).getByRole('button', {+ name: 'Loading…',+ });++ await expect(button).toBeDisabled();+ await userEvent.click(button);+ await expect(args.onLoadMore).not.toHaveBeenCalled();+ },+};diff --git a/packages/twenty-front/vitest.config.ts b/packages/twenty-front/vitest.config.tsindex 45d0c675f4a..f6b83baef4b 100644--- a/packages/twenty-front/vitest.config.ts+++ b/packages/twenty-front/vitest.config.ts@@ -26,6 +26,9 @@ export default defineConfig({projects: [{extends: './vite.config.ts',+ optimizeDeps: {+ include: ['storybook-addon-mock-date/preview'],+ },plugins: [storybookTest({configDir: path.join(dirname, '.storybook'),