Skip to content

The open alternative to Salesforce, designed for AI.

Select several chats in the inbox and act on them at once (#27171)

Félix Malfaitf3da92a07348
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatInboxSelectionPane.tsx b/packages/twenty-front/src/modules/ai/components/AiChatInboxSelectionPane.tsx
new file mode 100644
index 00000000000..3acb511bdef
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatInboxSelectionPane.tsx
@@ -0,0 +1,79 @@
+import { plural } from '@lingui/core/macro';
+import { useLingui } from '@lingui/react/macro';
+import { Key } from 'ts-key-enum';
+import { IconX } from 'twenty-ui/icon';
+import { Button } from 'twenty-ui/primitives/input';
+
+import { AiChatInboxSelectionToContextStoreEffect } from '@/ai/components/AiChatInboxSelectionToContextStoreEffect';
+import { AI_CHAT_INBOX_INSTANCE_ID } from '@/ai/constants/AiChatInboxInstanceId';
+import { CommandMenuContextProvider } from '@/command-menu-item/contexts/CommandMenuContextProvider';
+import { PinnedCommandMenuItemButtons } from '@/command-menu-item/display/components/PinnedCommandMenuItemButtons';
+import { CommandMenuItemContainerType } from '@/command-menu-item/types/CommandMenuItemContainerType';
+import { CommandMenuComponentInstanceContext } from '@/command-menu/states/contexts/CommandMenuComponentInstanceContext';
+import { ContextStoreComponentInstanceContext } from '@/context-store/states/contexts/ContextStoreComponentInstanceContext';
+import { useResetRecordSelection } from '@/object-record/record-selection/hooks/useResetRecordSelection';
+import { selectedRecordIdsComponentSelector } from '@/object-record/record-selection/states/selectors/selectedRecordIdsComponentSelector';
+import { EmptyState } from '@/ui/feedback/empty-state/components/EmptyState';
+import { PageCardHeader } from '@/ui/layout/page/components/PageCardHeader';
+import { PageCardLayout } from '@/ui/layout/page/components/PageCardLayout';
+import { useGlobalHotkeys } from '@/ui/utilities/hotkey/hooks/useGlobalHotkeys';
+import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';
+
+export const AiChatInboxSelectionPane = () => {
+ const { t } = useLingui();
+ const selectedRecordIds = useAtomComponentSelectorValue(
+ selectedRecordIdsComponentSelector,
+ );
+ const { resetRecordSelection } = useResetRecordSelection();
+
+ useGlobalHotkeys({
+ keys: [Key.Escape],
+ callback: resetRecordSelection,
+ containsModifier: false,
+ dependencies: [resetRecordSelection],
+ });
+
+ return (
+ <ContextStoreComponentInstanceContext.Provider
+ value={{ instanceId: AI_CHAT_INBOX_INSTANCE_ID }}
+ >
+ <CommandMenuComponentInstanceContext.Provider
+ value={{ instanceId: AI_CHAT_INBOX_INSTANCE_ID }}
+ >
+ <PageCardLayout
+ header={
+ <PageCardHeader
+ actionButton={
+ <CommandMenuContextProvider
+ displayType="button"
+ containerType={CommandMenuItemContainerType.ShowPageHeader}
+ >
+ <PinnedCommandMenuItemButtons />
+ </CommandMenuContextProvider>
+ }
+ />
+ }
+ >
+ <AiChatInboxSelectionToContextStoreEffect />
+ <EmptyState.Root>
+ <EmptyState.Content>
+ <EmptyState.Title>
+ {plural(selectedRecordIds.length, {
+ one: '# chat selected',
+ other: '# chats selected',
+ })}
+ </EmptyState.Title>
+ </EmptyState.Content>
+ <Button
+ variant="outline"
+ startIcon={<IconX />}
+ onClick={resetRecordSelection}
+ >
+ {t`Clear selection`}
+ </Button>
+ </EmptyState.Root>
+ </PageCardLayout>
+ </CommandMenuComponentInstanceContext.Provider>
+ </ContextStoreComponentInstanceContext.Provider>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatInboxSelectionToContextStoreEffect.tsx b/packages/twenty-front/src/modules/ai/components/AiChatInboxSelectionToContextStoreEffect.tsx
new file mode 100644
index 00000000000..6ea3eb18e8a
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatInboxSelectionToContextStoreEffect.tsx
@@ -0,0 +1,30 @@
+import { useEffect } from 'react';
+
+import { AI_CHAT_INBOX_INSTANCE_ID } from '@/ai/constants/AiChatInboxInstanceId';
+import { useTargetAiChatThreadsInContextStore } from '@/ai/hooks/useTargetAiChatThreadsInContextStore';
+import { selectedRecordIdsComponentSelector } from '@/object-record/record-selection/states/selectors/selectedRecordIdsComponentSelector';
+import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';
+
+export const AiChatInboxSelectionToContextStoreEffect = () => {
+ const selectedRecordIds = useAtomComponentSelectorValue(
+ selectedRecordIdsComponentSelector,
+ );
+ const { targetAiChatThreadsInContextStore } =
+ useTargetAiChatThreadsInContextStore();
+
+ useEffect(() => {
+ targetAiChatThreadsInContextStore({
+ contextStoreInstanceId: AI_CHAT_INBOX_INSTANCE_ID,
+ threadIds: selectedRecordIds,
+ });
+
+ return () => {
+ targetAiChatThreadsInContextStore({
+ contextStoreInstanceId: AI_CHAT_INBOX_INSTANCE_ID,
+ threadIds: [],
+ });
+ };
+ }, [selectedRecordIds, targetAiChatThreadsInContextStore]);
+
+ return null;
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadActionsDropdown.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadActionsDropdown.tsx
index fa6d4707a73..421aa36a165 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadActionsDropdown.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadActionsDropdown.tsx
@@ -1,15 +1,12 @@
import { useLingui } from '@lingui/react/macro';
-import { useStore } from 'jotai';
import { type ReactElement, type MouseEvent, useContext } from 'react';
-import {
- ContextStorePageType,
- CoreObjectNameSingular,
-} from 'twenty-shared/types';
+import { CoreObjectNameSingular } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { Dropdown, LightIconButton } from 'twenty-ui/components';
import { IconDotsVertical, IconPencil, IconUnlink } from 'twenty-ui/icon';
import { useRefreshAgentChatThreadPermissions } from '@/ai/hooks/useRefreshAgentChatThreadPermissions';
+import { useTargetAiChatThreadsInContextStore } from '@/ai/hooks/useTargetAiChatThreadsInContextStore';
import { agentChatThreadPermissionsFamilySelector } from '@/ai/states/selectors/agentChatThreadPermissionsFamilySelector';
import { type AiChatThreadActionsSurface } from '@/ai/types/AiChatThreadActionsSurface';
import { getAiChatThreadActionsInstanceId } from '@/ai/utils/getAiChatThreadActionsInstanceId';
@@ -19,10 +16,6 @@ import { CommandMenuContextProvider } from '@/command-menu-item/contexts/Command
import { CommandMenuItemRenderer } from '@/command-menu-item/display/components/CommandMenuItemRenderer';
import { CommandMenuItemContainerType } from '@/command-menu-item/types/CommandMenuItemContainerType';
import { CommandMenuComponentInstanceContext } from '@/command-menu/states/contexts/CommandMenuComponentInstanceContext';
-import { contextStoreCurrentObjectMetadataItemIdComponentState } from '@/context-store/states/contextStoreCurrentObjectMetadataItemIdComponentState';
-import { contextStoreCurrentPageTypeComponentState } from '@/context-store/states/contextStoreCurrentPageTypeComponentState';
-import { contextStoreNumberOfSelectedRecordsComponentState } from '@/context-store/states/contextStoreNumberOfSelectedRecordsComponentState';
-import { contextStoreTargetedRecordsRuleComponentState } from '@/context-store/states/contextStoreTargetedRecordsRuleComponentState';
import { ContextStoreComponentInstanceContext } from '@/context-store/states/contexts/ContextStoreComponentInstanceContext';
import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';
import { useUpsertRecordsInStore } from '@/object-record/record-store/hooks/useUpsertRecordsInStore';
@@ -69,8 +62,9 @@ export const AiChatThreadActionsDropdown = ({
trigger,
}: AiChatThreadActionsDropdownProps) => {
const { t } = useLingui();
- const store = useStore();
const { upsertRecordsInStore } = useUpsertRecordsInStore();
+ const { targetAiChatThreadsInContextStore } =
+ useTargetAiChatThreadsInContextStore();
const { refreshAgentChatThreadPermissions } =
useRefreshAgentChatThreadPermissions();
const chatObjectMetadataItem = useAtomFamilySelectorValue(
@@ -96,42 +90,6 @@ export const AiChatThreadActionsDropdown = ({
const canUpdate = isDefined(permissions) && permissions.canUpdate;
const isDeleted = isDefined(thread.deletedAt);
- const targetThreadInContextStore = () => {
- const instanceKey = { instanceId };
-
- store.set(
- contextStoreCurrentObjectMetadataItemIdComponentState.atomFamily(
- instanceKey,
- ),
- chatObjectMetadataItem.id,
- );
- store.set(
- contextStoreCurrentPageTypeComponentState.atomFamily(instanceKey),
- ContextStorePageType.Record,
- );
- store.set(
- contextStoreTargetedRecordsRuleComponentState.atomFamily(instanceKey),
- { mode: 'selection', selectedRecordIds: [thread.id] },
- );
- store.set(
- contextStoreNumberOfSelectedRecordsComponentState.atomFamily(instanceKey),
- 1,
- );
- upsertRecordsInStore({
- partialRecords: [
- {
- __typename: 'AgentChatThread',
- id: thread.id,
- title: thread.title ?? null,
- deletedAt: thread.deletedAt ?? null,
- ...(isDefined(thread.lastActivityAt)
- ? { lastActivityAt: thread.lastActivityAt }
- : {}),
- },
- ],
- });
- };
-
const handleRename = (event: MouseEvent) => {
event.stopPropagation();
onRenameRequested();
@@ -153,7 +111,23 @@ export const AiChatThreadActionsDropdown = ({
type="menu"
onOpenChange={(isOpen) => {
if (isOpen) {
- targetThreadInContextStore();
+ targetAiChatThreadsInContextStore({
+ contextStoreInstanceId: instanceId,
+ threadIds: [thread.id],
+ });
+ upsertRecordsInStore({
+ partialRecords: [
+ {
+ __typename: 'AgentChatThread',
+ id: thread.id,
+ title: thread.title ?? null,
+ deletedAt: thread.deletedAt ?? null,
+ ...(isDefined(thread.lastActivityAt)
+ ? { lastActivityAt: thread.lastActivityAt }
+ : {}),
+ },
+ ],
+ });
void refreshAgentChatThreadPermissions([thread.id]);
}
}}
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadList.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadList.tsx
index 646a8ab926f..64b45d6efae 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadList.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadList.tsx
@@ -1,4 +1,5 @@
import { styled } from '@linaria/react';
+import { type MouseEvent } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { themeCssVariables } from 'twenty-ui/theme';
@@ -18,24 +19,29 @@ const StyledGroupTitle = styled.div`
type AiChatThreadListProps = {
threads: AgentChatThreadRecord[];
surface: AiChatThreadActionsSurface;
- selectedThreadId?: string;
- onThreadClick: (thread: AgentChatThreadRecord) => void;
+ selectedThreadIds?: string[];
+ onThreadClick: (
+ thread: AgentChatThreadRecord,
+ event: MouseEvent<HTMLDivElement>,
+ ) => void;
onDetachThread?: (threadId: string) => void;
};
export const AiChatThreadList = ({
threads,
surface,
- selectedThreadId,
+ selectedThreadIds = [],
onThreadClick,
onDetachThread,
}: AiChatThreadListProps) => {
+ const selectedThreadIdSet = new Set(selectedThreadIds);
+
const renderThread = (thread: AgentChatThreadRecord) => (
<AiChatThreadListItem
key={thread.id}
thread={thread}
surface={surface}
- isSelected={thread.id === selectedThreadId}
+ isSelected={selectedThreadIdSet.has(thread.id)}
onClick={onThreadClick}
onDetach={
isDefined(onDetachThread) ? () => onDetachThread(thread.id) : undefined
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx
index 1b417333a4e..21da4ae2581 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx
@@ -1,4 +1,5 @@
import { styled } from '@linaria/react';
+import { type MouseEvent } from 'react';
import { useLingui } from '@lingui/react/macro';
import { Key } from 'ts-key-enum';
import { isDefined } from 'twenty-shared/utils';
@@ -121,7 +122,10 @@ type AiChatThreadListItemProps = {
thread: AgentChatThreadRecord;
surface: AiChatThreadActionsSurface;
isSelected: boolean;
- onClick: (thread: AgentChatThreadRecord) => void;
+ onClick: (
+ thread: AgentChatThreadRecord,
+ event: MouseEvent<HTMLDivElement>,
+ ) => void;
onDetach?: () => void;
};
@@ -192,9 +196,15 @@ export const AiChatThreadListItem = ({
return (
<StyledThreadItem
$isSelected={isSelected}
- onClick={() => {
+ onMouseDown={(event) => {
+ // Shift+click selects a range of chats, not the text in between
+ if (event.shiftKey && !isRenaming) {
+ event.preventDefault();
+ }
+ }}
+ onClick={(event) => {
if (!isRenaming) {
- onClick(thread);
+ onClick(thread, event);
}
}}
>
diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatInboxInstanceId.ts b/packages/twenty-front/src/modules/ai/constants/AiChatInboxInstanceId.ts
new file mode 100644
index 00000000000..06d04d172fd
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/AiChatInboxInstanceId.ts
@@ -0,0 +1 @@
+export const AI_CHAT_INBOX_INSTANCE_ID = 'ai-chat-inbox';
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatThreadParticipants.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatThreadParticipants.test.tsx
index e717a0ee1a5..0518b67fa17 100644
--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatThreadParticipants.test.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatThreadParticipants.test.tsx
@@ -107,8 +107,8 @@ describe('useAgentChatThreadParticipants', () => {
const { result, store } = renderParticipants();
await act(async () => {
- await result.current.snoozeAgentChatThread({
- threadId: THREAD_ID,
+ await result.current.snoozeAgentChatThreads({
+ threadIds: [THREAD_ID],
snoozedUntil: new Date('2026-10-02T09:00:00.000Z'),
});
});
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadParticipants.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadParticipants.ts
index edffe421595..f1c8318c75a 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadParticipants.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadParticipants.ts
@@ -151,16 +151,27 @@ export const useAgentChatThreadParticipants = () => {
[updateParticipant],
);
- const snoozeAgentChatThread = useCallback(
- ({ threadId, snoozedUntil }: { threadId: string; snoozedUntil: Date }) =>
- updateParticipant({
- mutation: SnoozeAgentChatThreadDocument,
- variables: { threadId, snoozedUntil: snoozedUntil.toISOString() },
- optimisticParticipant: {
- archivedAt: new Date().toISOString(),
- snoozedUntil: snoozedUntil.toISOString(),
- },
- }),
+ // One chat at a time: a failed update reloads every chat's state, which
+ // would undo the optimistic change of an update still on its way
+ const snoozeAgentChatThreads = useCallback(
+ async ({
+ threadIds,
+ snoozedUntil,
+ }: {
+ threadIds: string[];
+ snoozedUntil: Date;
+ }) => {
+ for (const threadId of threadIds) {
+ await updateParticipant({
+ mutation: SnoozeAgentChatThreadDocument,
+ variables: { threadId, snoozedUntil: snoozedUntil.toISOString() },
+ optimisticParticipant: {
+ archivedAt: new Date().toISOString(),
+ snoozedUntil: snoozedUntil.toISOString(),
+ },
+ });
+ }
+ },
[updateParticipant],
);
@@ -179,7 +190,7 @@ export const useAgentChatThreadParticipants = () => {
markAgentChatThreadAsRead,
markAgentChatThreadAsUnread,
archiveAgentChatThread,
- snoozeAgentChatThread,
+ snoozeAgentChatThreads,
moveAgentChatThreadToInbox,
};
};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useTargetAiChatThreadsInContextStore.ts b/packages/twenty-front/src/modules/ai/hooks/useTargetAiChatThreadsInContextStore.ts
new file mode 100644
index 00000000000..7f319a8cfad
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/hooks/useTargetAiChatThreadsInContextStore.ts
@@ -0,0 +1,65 @@
+import { useStore } from 'jotai';
+import { useCallback } from 'react';
+import {
+ ContextStorePageType,
+ CoreObjectNameSingular,
+} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { contextStoreCurrentObjectMetadataItemIdComponentState } from '@/context-store/states/contextStoreCurrentObjectMetadataItemIdComponentState';
+import { contextStoreCurrentPageTypeComponentState } from '@/context-store/states/contextStoreCurrentPageTypeComponentState';
+import { contextStoreNumberOfSelectedRecordsComponentState } from '@/context-store/states/contextStoreNumberOfSelectedRecordsComponentState';
+import { contextStoreTargetedRecordsRuleComponentState } from '@/context-store/states/contextStoreTargetedRecordsRuleComponentState';
+import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';
+import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
+
+export const useTargetAiChatThreadsInContextStore = () => {
+ const store = useStore();
+ const chatObjectMetadataItem = useAtomFamilySelectorValue(
+ objectMetadataItemFamilySelector,
+ {
+ objectName: CoreObjectNameSingular.AgentChatThread,
+ objectNameType: 'singular',
+ },
+ );
+
+ const targetAiChatThreadsInContextStore = useCallback(
+ ({
+ contextStoreInstanceId,
+ threadIds,
+ }: {
+ contextStoreInstanceId: string;
+ threadIds: string[];
+ }) => {
+ if (!isDefined(chatObjectMetadataItem)) {
+ return;
+ }
+
+ const instanceKey = { instanceId: contextStoreInstanceId };
+
+ store.set(
+ contextStoreCurrentObjectMetadataItemIdComponentState.atomFamily(
+ instanceKey,
+ ),
+ chatObjectMetadataItem.id,
+ );
+ store.set(
+ contextStoreCurrentPageTypeComponentState.atomFamily(instanceKey),
+ ContextStorePageType.Record,
+ );
+ store.set(
+ contextStoreTargetedRecordsRuleComponentState.atomFamily(instanceKey),
+ { mode: 'selection', selectedRecordIds: threadIds },
+ );
+ store.set(
+ contextStoreNumberOfSelectedRecordsComponentState.atomFamily(
+ instanceKey,
+ ),
+ threadIds.length,
+ );
+ },
+ [store, chatObjectMetadataItem],
+ );
+
+ return { targetAiChatThreadsInContextStore };
+};
diff --git a/packages/twenty-front/src/modules/ai/states/selectors/agentChatThreadInboxStatusByThreadIdFamilySelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/agentChatThreadInboxStatusByThreadIdFamilySelector.ts
new file mode 100644
index 00000000000..3382ff34840
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/states/selectors/agentChatThreadInboxStatusByThreadIdFamilySelector.ts
@@ -0,0 +1,26 @@
+import { agentChatThreadInboxStatusFamilySelector } from '@/ai/states/selectors/agentChatThreadInboxStatusFamilySelector';
+import { type AgentChatThreadInboxStatus } from '@/ai/types/AgentChatThreadInboxStatus';
+import { createAtomFamilySelector } from '@/ui/utilities/state/jotai/utils/createAtomFamilySelector';
+import { isDeeplyEqual } from '~/utils/isDeeplyEqual';
+
+type AgentChatThreadInboxStatusByThreadIdFamilyKey = {
+ threadIds: string[];
+};
+
+export const agentChatThreadInboxStatusByThreadIdFamilySelector =
+ createAtomFamilySelector<
+ Record<string, AgentChatThreadInboxStatus>,
+ AgentChatThreadInboxStatusByThreadIdFamilyKey
+ >({
+ key: 'agentChatThreadInboxStatusByThreadIdFamilySelector',
+ get:
+ ({ threadIds }: AgentChatThreadInboxStatusByThreadIdFamilyKey) =>
+ ({ get }) =>
+ Object.fromEntries(
+ threadIds.map((threadId) => [
+ threadId,
+ get(agentChatThreadInboxStatusFamilySelector, threadId),
+ ]),
+ ),
+ areEqual: isDeeplyEqual,
+ });
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx
index ddb1f80a639..468e796af85 100644
--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/constants/EngineComponentKeyHeadlessComponentMap.tsx
@@ -23,18 +23,18 @@ import { CreateNewViewNoSelectionRecordCommand } from '@/command-menu-item/engin
import { HideDeletedRecordsNoSelectionRecordCommand } from '@/command-menu-item/engine-command/record/no-selection/components/HideDeletedRecordsNoSelectionRecordCommand';
import { ImportRecordsNoSelectionRecordCommand } from '@/command-menu-item/engine-command/record/no-selection/components/ImportRecordsNoSelectionRecordCommand';
import { SeeDeletedRecordsNoSelectionRecordCommand } from '@/command-menu-item/engine-command/record/no-selection/components/SeeDeletedRecordsNoSelectionRecordCommand';
-import { AddToFavoritesSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/components/AddToFavoritesSingleRecordCommand';
+import { AddToFavoritesCommand } from '@/command-menu-item/engine-command/record/components/AddToFavoritesCommand';
import { ExportNoteSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/components/ExportNoteSingleRecordCommand';
import { NavigateToNextRecordSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/components/NavigateToNextRecordSingleRecordCommand';
import { NavigateToPreviousRecordSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/components/NavigateToPreviousRecordSingleRecordCommand';
-import { RemoveFromFavoritesSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/components/RemoveFromFavoritesSingleRecordCommand';
+import { RemoveFromFavoritesCommand } from '@/command-menu-item/engine-command/record/components/RemoveFromFavoritesCommand';
import { CancelDashboardSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/dashboard/components/CancelDashboardSingleRecordCommand';
import { DuplicateDashboardSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/dashboard/components/DuplicateDashboardSingleRecordCommand';
import { DuplicateMessageListSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/message-list/components/DuplicateMessageListSingleRecordCommand';
import { EditDashboardSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/dashboard/components/EditDashboardSingleRecordCommand';
import { SaveDashboardSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/dashboard/components/SaveDashboardSingleRecordCommand';
import { ReplyToEmailThreadCommand } from '@/command-menu-item/engine-command/record/single-record/message-thread/components/ReplyToEmailThreadCommand';
-import { AgentChatThreadInboxSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/agent-chat-thread/components/AgentChatThreadInboxSingleRecordCommand';
+import { AgentChatThreadInboxCommand } from '@/command-menu-item/engine-command/record/components/AgentChatThreadInboxCommand';
import { NewAiChatSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/agent-chat-thread/components/NewAiChatSingleRecordCommand';
import { ShareRecordCommand } from '@/command-menu-item/engine-command/record/components/ShareRecordCommand';
import { SeeVersionWorkflowRunSingleRecordCommand } from '@/command-menu-item/engine-command/record/single-record/workflow-runs/components/SeeVersionWorkflowRunSingleRecordCommand';
@@ -70,10 +70,8 @@ export const ENGINE_COMPONENT_KEY_COMPONENT_MAP: Record<
[EngineComponentKey.DELETE_RECORDS]: <DeleteRecordsCommand />,
[EngineComponentKey.RESTORE_RECORDS]: <RestoreRecordsCommand />,
[EngineComponentKey.DESTROY_RECORDS]: <DestroyRecordsCommand />,
- [EngineComponentKey.ADD_TO_FAVORITES]: <AddToFavoritesSingleRecordCommand />,
- [EngineComponentKey.REMOVE_FROM_FAVORITES]: (
- <RemoveFromFavoritesSingleRecordCommand />
- ),
+ [EngineComponentKey.ADD_TO_FAVORITES]: <AddToFavoritesCommand />,
+ [EngineComponentKey.REMOVE_FROM_FAVORITES]: <RemoveFromFavoritesCommand />,
[EngineComponentKey.MERGE_MULTIPLE_RECORDS]: <MergeMultipleRecordsCommand />,
[EngineComponentKey.DUPLICATE_DASHBOARD]: (
<DuplicateDashboardSingleRecordCommand />
@@ -263,19 +261,19 @@ export const ENGINE_COMPONENT_KEY_COMPONENT_MAP: Record<
[EngineComponentKey.NEW_AI_CHAT]: <NewAiChatSingleRecordCommand />,
[EngineComponentKey.SHARE_RECORD]: <ShareRecordCommand />,
[EngineComponentKey.MARK_AI_CHAT_AS_READ]: (
- <AgentChatThreadInboxSingleRecordCommand action="read" />
+ <AgentChatThreadInboxCommand action="read" />
),
[EngineComponentKey.MARK_AI_CHAT_AS_UNREAD]: (
- <AgentChatThreadInboxSingleRecordCommand action="unread" />
+ <AgentChatThreadInboxCommand action="unread" />
),
[EngineComponentKey.MARK_AI_CHAT_AS_DONE]: (
- <AgentChatThreadInboxSingleRecordCommand action="done" />
+ <AgentChatThreadInboxCommand action="done" />
),
[EngineComponentKey.REOPEN_AI_CHAT]: (
- <AgentChatThreadInboxSingleRecordCommand action="reopen" />
+ <AgentChatThreadInboxCommand action="reopen" />
),
[EngineComponentKey.SNOOZE_AI_CHAT]: (
- <AgentChatThreadInboxSingleRecordCommand action="snooze" />
+ <AgentChatThreadInboxCommand action="snooze" />
),
[EngineComponentKey.COMPOSE_EMAIL]: <ComposeEmailCommand />,
[EngineComponentKey.COMPOSE_CAMPAIGN]: <ComposeCampaignCommand />,
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/components/AddToFavoritesSingleRecordCommand.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/components/AddToFavoritesCommand.tsx
similarity index 74%
rename from packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/components/AddToFavoritesSingleRecordCommand.tsx
rename to packages/twenty-front/src/modules/command-menu-item/engine-command/record/components/AddToFavoritesCommand.tsx
index 6b63ed4b211..b414285ffd4 100644
--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/components/AddToFavoritesSingleRecordCommand.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/components/AddToFavoritesCommand.tsx
@@ -7,12 +7,10 @@ import { useHeadlessCommandContextApi } from '@/command-menu-item/engine-command
import { useCreateManyNavigationMenuItems } from '@/navigation-menu-item/common/hooks/useCreateManyNavigationMenuItems';
import { useNavigationMenuItemsData } from '@/navigation-menu-item/display/hooks/useNavigationMenuItemsData';
-export const AddToFavoritesSingleRecordCommand = () => {
+export const AddToFavoritesCommand = () => {
const { objectMetadataItem, selectedRecords } =
useHeadlessCommandContextApi();
- const selectedRecord = selectedRecords[0];
-
if (!isDefined(objectMetadataItem)) {
throw new Error('Object metadata item is required to add to favorites');
}
@@ -22,9 +20,15 @@ export const AddToFavoritesSingleRecordCommand = () => {
useNavigationMenuItemsData();
const handleExecute = () => {
- if (!isDefined(selectedRecord)) {
- return;
- }
+ const favoriteRecordIds = new Set(
+ navigationMenuItems
+ .filter((item) => item.targetObjectMetadataId === objectMetadataItem.id)
+ .map((item) => item.targetRecordId),
+ );
+
+ const recordsToAdd = selectedRecords.filter(
+ (record) => !favoriteRecordIds.has(record.id),
+ );
const relevantItems = navigationMenuItems.filter(
(item) => !isDefined(item.folderId) && isDefined(item.userWorkspaceId),
@@ -35,16 +39,16 @@ export const AddToFavoritesSingleRecordCommand = () => {
0,
);
- createManyNavigationMenuItems([
- {
+ createManyNavigationMenuItems(
+ recordsToAdd.map((record, index) => ({
id: uuidv4(),
type: NavigationMenuItemType.RECORD,
- targetRecordId: selectedRecord.id,
+ targetRecordId: record.id,
targetObjectMetadataId: objectMetadataItem.id,
userWorkspaceId: currentUserWorkspaceId,
- position: maxPosition + 1,
- },
- ]);
+ position: maxPosition + index + 1,
+ })),
+ );
};
return <HeadlessEngineCommandWrapperEffect execute={handleExecute} />;
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/agent-chat-thread/components/AgentChatThreadInboxSingleRecordCommand.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/components/AgentChatThreadInboxCommand.tsx
similarity index 57%
rename from packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/agent-chat-thread/components/AgentChatThreadInboxSingleRecordCommand.tsx
rename to packages/twenty-front/src/modules/command-menu-item/engine-command/record/components/AgentChatThreadInboxCommand.tsx
index f5e65b2ac04..6f25cb35f60 100644
--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/agent-chat-thread/components/AgentChatThreadInboxSingleRecordCommand.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/components/AgentChatThreadInboxCommand.tsx
@@ -1,17 +1,15 @@
-import { isDefined } from 'twenty-shared/utils';
-
import { useAgentChatThreadParticipants } from '@/ai/hooks/useAgentChatThreadParticipants';
import { HeadlessEngineCommandWrapperEffect } from '@/command-menu-item/engine-command/components/HeadlessEngineCommandWrapperEffect';
import { useHeadlessCommandContextApi } from '@/command-menu-item/engine-command/hooks/useHeadlessCommandContextApi';
import { useOpenSnoozeAiChatInSidePanel } from '@/side-panel/hooks/useOpenSnoozeAiChatInSidePanel';
-type AgentChatThreadInboxSingleRecordCommandProps = {
+type AgentChatThreadInboxCommandProps = {
action: 'read' | 'unread' | 'done' | 'reopen' | 'snooze';
};
-export const AgentChatThreadInboxSingleRecordCommand = ({
+export const AgentChatThreadInboxCommand = ({
action,
-}: AgentChatThreadInboxSingleRecordCommandProps) => {
+}: AgentChatThreadInboxCommandProps) => {
const { selectedRecords } = useHeadlessCommandContextApi();
const {
markAgentChatThreadAsRead,
@@ -22,23 +20,27 @@ export const AgentChatThreadInboxSingleRecordCommand = ({
const { openSnoozeAiChatInSidePanel } = useOpenSnoozeAiChatInSidePanel();
const handleExecute = async () => {
- const threadId = selectedRecords[0]?.id;
+ const threadIds = selectedRecords.map(({ id }) => id);
- if (!isDefined(threadId)) {
+ if (threadIds.length === 0) {
return;
}
- switch (action) {
- case 'read':
- return markAgentChatThreadAsRead(threadId);
- case 'unread':
- return markAgentChatThreadAsUnread(threadId);
- case 'done':
- return archiveAgentChatThread(threadId);
- case 'reopen':
- return moveAgentChatThreadToInbox(threadId);
- case 'snooze':
- return openSnoozeAiChatInSidePanel(threadId);
+ if (action === 'snooze') {
+ return openSnoozeAiChatInSidePanel(threadIds);
+ }
+
+ const updateThread = {
+ read: markAgentChatThreadAsRead,
+ unread: markAgentChatThreadAsUnread,
+ done: archiveAgentChatThread,
+ reopen: moveAgentChatThreadToInbox,
+ }[action];
+
+ // One at a time: a failed update reloads every chat's state, which would
+ // undo the optimistic change of an update still on its way
+ for (const threadId of threadIds) {
+ await updateThread(threadId);
}
};
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/components/RemoveFromFavoritesSingleRecordCommand.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/components/RemoveFromFavoritesCommand.tsx
similarity index 59%
rename from packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/components/RemoveFromFavoritesSingleRecordCommand.tsx
rename to packages/twenty-front/src/modules/command-menu-item/engine-command/record/components/RemoveFromFavoritesCommand.tsx
index 8e3e60314a1..f9b02893e7c 100644
--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/components/RemoveFromFavoritesSingleRecordCommand.tsx
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/components/RemoveFromFavoritesCommand.tsx
@@ -5,16 +5,12 @@ import { useHeadlessCommandContextApi } from '@/command-menu-item/engine-command
import { useDeleteManyNavigationMenuItems } from '@/navigation-menu-item/common/hooks/useDeleteManyNavigationMenuItems';
import { useNavigationMenuItemsData } from '@/navigation-menu-item/display/hooks/useNavigationMenuItemsData';
-export const RemoveFromFavoritesSingleRecordCommand = () => {
+export const RemoveFromFavoritesCommand = () => {
const { selectedRecords, objectMetadataItem } =
useHeadlessCommandContextApi();
- const recordId = selectedRecords[0]?.id;
-
- if (!isDefined(recordId) || !isDefined(objectMetadataItem)) {
- throw new Error(
- 'Record ID and object metadata are required to remove from favorites',
- );
+ if (!isDefined(objectMetadataItem)) {
+ throw new Error('Object metadata is required to remove from favorites');
}
const { navigationMenuItems, workspaceNavigationMenuItems } =
@@ -22,21 +18,23 @@ export const RemoveFromFavoritesSingleRecordCommand = () => {
const { deleteManyNavigationMenuItems } = useDeleteManyNavigationMenuItems();
- const foundNavigationMenuItem = [
- ...navigationMenuItems,
- ...workspaceNavigationMenuItems,
- ].find(
- (item) =>
- item.targetRecordId === recordId &&
- item.targetObjectMetadataId === objectMetadataItem.id,
- );
-
const handleExecute = () => {
- if (!isDefined(foundNavigationMenuItem)) {
+ const navigationMenuItemIdsToDelete = selectedRecords
+ .map((record) =>
+ [...navigationMenuItems, ...workspaceNavigationMenuItems].find(
+ (item) =>
+ item.targetRecordId === record.id &&
+ item.targetObjectMetadataId === objectMetadataItem.id,
+ ),
+ )
+ .filter(isDefined)
+ .map(({ id }) => id);
+
+ if (navigationMenuItemIdsToDelete.length === 0) {
return;
}
- deleteManyNavigationMenuItems([foundNavigationMenuItem.id]);
+ deleteManyNavigationMenuItems(navigationMenuItemIdsToDelete);
};
return <HeadlessEngineCommandWrapperEffect execute={handleExecute} />;
diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/components/__tests__/FavoritesCommands.test.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/components/__tests__/FavoritesCommands.test.tsx
new file mode 100644
index 00000000000..c061d1e6840
--- /dev/null
+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/components/__tests__/FavoritesCommands.test.tsx
@@ -0,0 +1,118 @@
+import { render, waitFor } from '@testing-library/react';
+import { type ReactNode } from 'react';
+
+import { AddToFavoritesCommand } from '@/command-menu-item/engine-command/record/components/AddToFavoritesCommand';
+import { RemoveFromFavoritesCommand } from '@/command-menu-item/engine-command/record/components/RemoveFromFavoritesCommand';
+import { CommandComponentInstanceContext } from '@/command-menu-item/engine-command/states/contexts/CommandComponentInstanceContext';
+import { getJestMetadataAndApolloMocksWrapper } from '~/testing/jest/getJestMetadataAndApolloMocksWrapper';
+import { getMockObjectMetadataItemOrThrow } from '~/testing/utils/getMockObjectMetadataItemOrThrow';
+
+const mockObjectMetadataItem = getMockObjectMetadataItemOrThrow('person');
+const mockCreateManyNavigationMenuItems = jest.fn();
+const mockDeleteManyNavigationMenuItems = jest.fn();
+
+jest.mock(
+ '@/command-menu-item/engine-command/hooks/useHeadlessCommandContextApi',
+ () => ({
+ useHeadlessCommandContextApi: () => ({
+ objectMetadataItem: mockObjectMetadataItem,
+ selectedRecords: [
+ { id: 'record-1' },
+ { id: 'record-2' },
+ { id: 'record-3' },
+ ],
+ }),
+ }),
+);
+
+jest.mock(
+ '@/navigation-menu-item/common/hooks/useCreateManyNavigationMenuItems',
+ () => ({
+ useCreateManyNavigationMenuItems: () => ({
+ createManyNavigationMenuItems: mockCreateManyNavigationMenuItems,
+ }),
+ }),
+);
+
+jest.mock(
+ '@/navigation-menu-item/common/hooks/useDeleteManyNavigationMenuItems',
+ () => ({
+ useDeleteManyNavigationMenuItems: () => ({
+ deleteManyNavigationMenuItems: mockDeleteManyNavigationMenuItems,
+ }),
+ }),
+);
+
+jest.mock(
+ '@/navigation-menu-item/display/hooks/useNavigationMenuItemsData',
+ () => ({
+ useNavigationMenuItemsData: () => ({
+ currentUserWorkspaceId: 'user-workspace',
+ navigationMenuItems: [
+ {
+ id: 'favorite-2',
+ position: 4,
+ userWorkspaceId: 'user-workspace',
+ targetRecordId: 'record-2',
+ targetObjectMetadataId: mockObjectMetadataItem.id,
+ },
+ ],
+ workspaceNavigationMenuItems: [
+ {
+ id: 'workspace-favorite-2',
+ position: 0,
+ targetRecordId: 'record-2',
+ targetObjectMetadataId: mockObjectMetadataItem.id,
+ },
+ {
+ id: 'workspace-favorite-3',
+ position: 1,
+ targetRecordId: 'record-3',
+ targetObjectMetadataId: mockObjectMetadataItem.id,
+ },
+ ],
+ }),
+ }),
+);
+
+const renderCommand = (command: ReactNode) => {
+ const Wrapper = getJestMetadataAndApolloMocksWrapper({ apolloMocks: [] });
+
+ return render(command, {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <Wrapper>
+ <CommandComponentInstanceContext.Provider
+ value={{ instanceId: 'favorites-command' }}
+ >
+ {children}
+ </CommandComponentInstanceContext.Provider>
+ </Wrapper>
+ ),
+ });
+};
+
+beforeEach(() => {
+ jest.clearAllMocks();
+});
+
+it('adds every selected record that is not a favorite yet', async () => {
+ renderCommand(<AddToFavoritesCommand />);
+
+ await waitFor(() =>
+ expect(mockCreateManyNavigationMenuItems).toHaveBeenCalledWith([
+ expect.objectContaining({ targetRecordId: 'record-1', position: 5 }),
+ expect.objectContaining({ targetRecordId: 'record-3', position: 6 }),
+ ]),
+ );
+});
+
+it('removes one favorite per selected record, the personal one first', async () => {
+ renderCommand(<RemoveFromFavoritesCommand />);
+
+ await waitFor(() =>
+ expect(mockDeleteManyNavigationMenuItems).toHaveBeenCalledWith([
+ 'favorite-2',
+ 'workspace-favorite-3',
+ ]),
+ );
+});
diff --git a/packages/twenty-front/src/modules/command-menu-item/hooks/useCurrentCommandMenuContextApi.ts b/packages/twenty-front/src/modules/command-menu-item/hooks/useCurrentCommandMenuContextApi.ts
index 2d2ae7eb03b..4351f931e93 100644
--- a/packages/twenty-front/src/modules/command-menu-item/hooks/useCurrentCommandMenuContextApi.ts
+++ b/packages/twenty-front/src/modules/command-menu-item/hooks/useCurrentCommandMenuContextApi.ts
@@ -1,5 +1,5 @@
import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';
-import { agentChatThreadInboxStatusFamilySelector } from '@/ai/states/selectors/agentChatThreadInboxStatusFamilySelector';
+import { agentChatThreadInboxStatusByThreadIdFamilySelector } from '@/ai/states/selectors/agentChatThreadInboxStatusByThreadIdFamilySelector';
import { currentUserState } from '@/auth/states/currentUserState';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { EMPTY_COMMAND_MENU_CONTEXT_API } from '@/command-menu-item/constants/EmptyCommandMenuContextApi';
@@ -93,21 +93,20 @@ export const useCurrentCommandMenuContextApi = (): CommandMenuContextApi => {
);
// A chat's read and done state belongs to the member, not to the record,
- // so the inbox commands read it from here. Those commands only apply to a
- // single chat, and stay hidden until the member state loads rather than
- // offering the wrong half of a pair
+ // so the inbox commands read it from here. They stay hidden until the
+ // member state loads rather than offering the wrong half of a pair
const agentChatThreadParticipants = useAtomStateValue(
agentChatThreadParticipantsState,
);
- const inboxStatusThreadId =
+ const inboxStatusThreadIds =
objectMetadataItem?.nameSingular ===
CoreObjectNameSingular.AgentChatThread &&
isDefined(agentChatThreadParticipants)
- ? recordIds?.[0]
- : undefined;
- const agentChatThreadInboxStatus = useAtomFamilySelectorValue(
- agentChatThreadInboxStatusFamilySelector,
- inboxStatusThreadId ?? '',
+ ? (recordIds ?? [])
+ : [];
+ const agentChatThreadInboxStatusByThreadId = useAtomFamilySelectorValue(
+ agentChatThreadInboxStatusByThreadIdFamilySelector,
+ { threadIds: inboxStatusThreadIds },
);
// Records shared below the role's access level carry their own permissions, which availability expressions read per record
@@ -117,8 +116,8 @@ export const useCurrentCommandMenuContextApi = (): CommandMenuContextApi => {
...(isDefined(recordPermissionsByRecordId[record.id]) && {
recordPermissions: recordPermissionsByRecordId[record.id],
}),
- ...(record.id === inboxStatusThreadId && {
- inboxStatus: agentChatThreadInboxStatus,
+ ...(isDefined(agentChatThreadInboxStatusByThreadId[record.id]) && {
+ inboxStatus: agentChatThreadInboxStatusByThreadId[record.id],
}),
}),
);
diff --git a/packages/twenty-front/src/modules/object-record/record-selection/components/RecordSelectionRecordIdsEffect.tsx b/packages/twenty-front/src/modules/object-record/record-selection/components/RecordSelectionRecordIdsEffect.tsx
new file mode 100644
index 00000000000..18fb8fda156
--- /dev/null
+++ b/packages/twenty-front/src/modules/object-record/record-selection/components/RecordSelectionRecordIdsEffect.tsx
@@ -0,0 +1,65 @@
+import { useStore } from 'jotai';
+import { useEffect } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+
+import { recordIndexRecordIdsByGroupComponentFamilyState } from '@/object-record/record-index/states/recordIndexRecordIdsByGroupComponentFamilyState';
+import { NO_RECORD_GROUP_FAMILY_KEY } from '@/object-record/record-index/states/selectors/recordIndexAllRecordIdsComponentSelector';
+import { RecordSelectionComponentInstanceContext } from '@/object-record/record-selection/states/contexts/RecordSelectionComponentInstanceContext';
+import { recordSelectionRangeComponentState } from '@/object-record/record-selection/states/recordSelectionRangeComponentState';
+import { isRecordSelectedComponentFamilyState } from '@/object-record/record-selection/states/isRecordSelectedComponentFamilyState';
+import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
+import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';
+
+type RecordSelectionRecordIdsEffectProps = {
+ records: Pick<ObjectRecord, 'id'>[];
+};
+
+// Record selection reads the records where a record index keeps them, so a
+// list that is not a record index keeps its records there, in display order
+export const RecordSelectionRecordIdsEffect = ({
+ records,
+}: RecordSelectionRecordIdsEffectProps) => {
+ const instanceId = useAvailableComponentInstanceIdOrThrow(
+ RecordSelectionComponentInstanceContext,
+ );
+ const store = useStore();
+
+ useEffect(() => {
+ const recordIdsAtom =
+ recordIndexRecordIdsByGroupComponentFamilyState.atomFamily({
+ instanceId,
+ familyKey: NO_RECORD_GROUP_FAMILY_KEY,
+ });
+ const recordIds = records.map(({ id }) => id);
+ const recordIdSet = new Set(recordIds);
+
+ // A record that leaves the list leaves the selection too, so it is not
+ // selected again when it comes back
+ for (const previousRecordId of store.get(recordIdsAtom)) {
+ if (!recordIdSet.has(previousRecordId)) {
+ store.set(
+ isRecordSelectedComponentFamilyState.atomFamily({
+ instanceId,
+ familyKey: previousRecordId,
+ }),
+ false,
+ );
+ }
+ }
+
+ const recordSelectionRangeAtom =
+ recordSelectionRangeComponentState.atomFamily({ instanceId });
+ const recordSelectionRange = store.get(recordSelectionRangeAtom);
+
+ if (
+ isDefined(recordSelectionRange) &&
+ !recordIdSet.has(recordSelectionRange.anchorRecordId)
+ ) {
+ store.set(recordSelectionRangeAtom, null);
+ }
+
+ store.set(recordIdsAtom, recordIds);
+ }, [instanceId, records, store]);
+
+ return null;
+};
diff --git a/packages/twenty-front/src/modules/object-record/record-selection/hooks/useToggleRecordSelection.ts b/packages/twenty-front/src/modules/object-record/record-selection/hooks/useToggleRecordSelection.ts
index df039cfcb9a..3ba15f5a322 100644
--- a/packages/twenty-front/src/modules/object-record/record-selection/hooks/useToggleRecordSelection.ts
+++ b/packages/twenty-front/src/modules/object-record/record-selection/hooks/useToggleRecordSelection.ts
@@ -3,27 +3,34 @@ import { useCallback } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { recordIndexDisplayedRecordIdsComponentSelector } from '@/object-record/record-index/states/selectors/recordIndexDisplayedRecordIdsComponentSelector';
+import { RecordSelectionComponentInstanceContext } from '@/object-record/record-selection/states/contexts/RecordSelectionComponentInstanceContext';
import { isRecordSelectedComponentFamilyState } from '@/object-record/record-selection/states/isRecordSelectedComponentFamilyState';
import { recordSelectionRangeComponentState } from '@/object-record/record-selection/states/recordSelectionRangeComponentState';
import { getRecordIdsBetween } from '@/object-record/record-selection/utils/getRecordIdsBetween';
+import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';
import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';
import { useAtomComponentSelectorCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorCallbackState';
import { useAtomComponentStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateCallbackState';
export const useToggleRecordSelection = (recordIndexId?: string) => {
+ const instanceId = useAvailableComponentInstanceIdOrThrow(
+ RecordSelectionComponentInstanceContext,
+ recordIndexId,
+ );
+
const isRecordSelectedFamilyState = useAtomComponentFamilyStateCallbackState(
isRecordSelectedComponentFamilyState,
- recordIndexId,
+ instanceId,
);
const displayedRecordIds = useAtomComponentSelectorCallbackState(
recordIndexDisplayedRecordIdsComponentSelector,
- recordIndexId,
+ instanceId,
);
const recordSelectionRange = useAtomComponentStateCallbackState(
recordSelectionRangeComponentState,
- recordIndexId,
+ instanceId,
);
const store = useStore();
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.tsx
index ca48695a3d1..13199a21310 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
@@ -101,7 +101,9 @@ export const ChatThreadsCardContent = ({
<AiChatThreadList
threads={threads}
surface={AI_CHAT_THREAD_ACTIONS_SURFACE.RECORD_PAGE}
- selectedThreadId={sidePanelThreadId}
+ selectedThreadIds={
+ isDefined(sidePanelThreadId) ? [sidePanelThreadId] : []
+ }
onThreadClick={({ id }) =>
openRecordInSidePanel({
recordId: id,
diff --git a/packages/twenty-front/src/modules/side-panel/hooks/useOpenSnoozeAiChatInSidePanel.ts b/packages/twenty-front/src/modules/side-panel/hooks/useOpenSnoozeAiChatInSidePanel.ts
index 85a273eb165..7a054f690ef 100644
--- a/packages/twenty-front/src/modules/side-panel/hooks/useOpenSnoozeAiChatInSidePanel.ts
+++ b/packages/twenty-front/src/modules/side-panel/hooks/useOpenSnoozeAiChatInSidePanel.ts
@@ -6,7 +6,7 @@ import { IconClock } from 'twenty-ui/icon';
import { v4 } from 'uuid';
import { useSidePanelMenu } from '@/side-panel/hooks/useSidePanelMenu';
-import { snoozeAiChatThreadIdComponentState } from '@/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdComponentState';
+import { snoozeAiChatThreadIdsComponentState } from '@/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdsComponentState';
export const useOpenSnoozeAiChatInSidePanel = () => {
const { t } = useLingui();
@@ -14,12 +14,12 @@ export const useOpenSnoozeAiChatInSidePanel = () => {
const { navigateSidePanelMenu } = useSidePanelMenu();
const openSnoozeAiChatInSidePanel = useCallback(
- (threadId: string) => {
+ (threadIds: string[]) => {
const pageId = v4();
store.set(
- snoozeAiChatThreadIdComponentState.atomFamily({ instanceId: pageId }),
- threadId,
+ snoozeAiChatThreadIdsComponentState.atomFamily({ instanceId: pageId }),
+ threadIds,
);
navigateSidePanelMenu({
diff --git a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/SidePanelSnoozeAiChatPage.tsx b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/SidePanelSnoozeAiChatPage.tsx
index 74d37d40f4b..7592dce44a3 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/SidePanelSnoozeAiChatPage.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/SidePanelSnoozeAiChatPage.tsx
@@ -1,7 +1,6 @@
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
-import { useState } from 'react';
-import { isDefined } from 'twenty-shared/utils';
+import { useId, useState } from 'react';
import { IconCalendar, IconClock } from 'twenty-ui/icon';
import { themeCssVariables } from 'twenty-ui/theme';
@@ -16,7 +15,7 @@ import { CommandMenuItemDropdown } from '@/command-menu/components/CommandMenuIt
import { SidePanelList } from '@/side-panel/components/SidePanelList';
import { useSidePanelMenu } from '@/side-panel/hooks/useSidePanelMenu';
import { SnoozeAiChatUntilDatePicker } from '@/side-panel/pages/snooze-ai-chat/components/SnoozeAiChatUntilDatePicker';
-import { snoozeAiChatThreadIdComponentState } from '@/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdComponentState';
+import { snoozeAiChatThreadIdsComponentState } from '@/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdsComponentState';
import { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownMenuSeparator';
import { useUserTimezone } from '@/ui/input/components/internal/date/hooks/useUserTimezone';
import { useOpenDropdown } from '@/ui/layout/dropdown/hooks/useOpenDropdown';
@@ -31,17 +30,18 @@ const StyledSeparatorContainer = styled.div`
export const SidePanelSnoozeAiChatPage = () => {
const { t } = useLingui();
- const snoozeAiChatThreadId = useAtomComponentStateValue(
- snoozeAiChatThreadIdComponentState,
+ const snoozeAiChatThreadIds = useAtomComponentStateValue(
+ snoozeAiChatThreadIdsComponentState,
);
- const { snoozeAgentChatThread } = useAgentChatThreadParticipants();
+ const { snoozeAgentChatThreads } = useAgentChatThreadParticipants();
const { formatAgentChatThreadDateTime } = useFormatAgentChatThreadDate();
const { closeSidePanelMenu } = useSidePanelMenu();
const { openDropdown } = useOpenDropdown();
const { userTimezone } = useUserTimezone();
const [optionsComputedAt, setOptionsComputedAt] = useState(() => new Date());
+ const untilDateDropdownId = useId();
- if (!isDefined(snoozeAiChatThreadId)) {
+ if (snoozeAiChatThreadIds.length === 0) {
return null;
}
@@ -61,14 +61,12 @@ export const SidePanelSnoozeAiChatPage = () => {
}
void closeSidePanelMenu();
- void snoozeAgentChatThread({
- threadId: snoozeAiChatThreadId,
+ void snoozeAgentChatThreads({
+ threadIds: snoozeAiChatThreadIds,
snoozedUntil: option.date,
});
};
- const untilDateDropdownId = `snooze-ai-chat-until-date-dropdown-${snoozeAiChatThreadId}`;
-
return (
<SidePanelList
selectableItemIds={[
@@ -111,7 +109,7 @@ export const SidePanelSnoozeAiChatPage = () => {
dropdownPlacement="bottom-start"
dropdownComponents={
<SnoozeAiChatUntilDatePicker
- threadId={snoozeAiChatThreadId}
+ threadIds={snoozeAiChatThreadIds}
onSnoozed={closeSidePanelMenu}
/>
}
diff --git a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/SnoozeAiChatUntilDatePicker.tsx b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/SnoozeAiChatUntilDatePicker.tsx
index 82fadadf9af..cb942a85270 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/SnoozeAiChatUntilDatePicker.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/SnoozeAiChatUntilDatePicker.tsx
@@ -1,6 +1,6 @@
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
-import { useState } from 'react';
+import { useId, useState } from 'react';
import { Temporal } from 'temporal-polyfill';
import { isDefined } from 'twenty-shared/utils';
import { Button } from 'twenty-ui/primitives/input';
@@ -22,18 +22,19 @@ const StyledContainer = styled.div`
`;
type SnoozeAiChatUntilDatePickerProps = {
- threadId: string;
+ threadIds: string[];
onSnoozed: () => void;
};
export const SnoozeAiChatUntilDatePicker = ({
- threadId,
+ threadIds,
onSnoozed,
}: SnoozeAiChatUntilDatePickerProps) => {
const { t } = useLingui();
- const { snoozeAgentChatThread } = useAgentChatThreadParticipants();
+ const { snoozeAgentChatThreads } = useAgentChatThreadParticipants();
const { formatAgentChatThreadDateTime } = useFormatAgentChatThreadDate();
const { userTimezone } = useUserTimezone();
+ const dateTimePickerInstanceId = useId();
const agentChatThreadInboxNow = useAtomStateValue(
agentChatThreadInboxNowState,
);
@@ -66,16 +67,13 @@ export const SnoozeAiChatUntilDatePicker = ({
}
onSnoozed();
- void snoozeAgentChatThread({
- threadId,
- snoozedUntil: snoozedUntilDate,
- });
+ void snoozeAgentChatThreads({ threadIds, snoozedUntil: snoozedUntilDate });
};
return (
<StyledContainer>
<DateTimePicker
- instanceId={`snooze-ai-chat-until-date-${threadId}`}
+ instanceId={dateTimePickerInstanceId}
date={snoozedUntil}
onChange={handleChange}
clearable={false}
diff --git a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SidePanelSnoozeAiChatPage.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SidePanelSnoozeAiChatPage.test.tsx
index baff6f2548e..3d43e58ceff 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SidePanelSnoozeAiChatPage.test.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SidePanelSnoozeAiChatPage.test.tsx
@@ -8,18 +8,18 @@ import { MemoryRouter } from 'react-router-dom';
import { agentChatThreadInboxNowState } from '@/ai/states/agentChatThreadInboxNowState';
import { SidePanelSnoozeAiChatPage } from '@/side-panel/pages/snooze-ai-chat/components/SidePanelSnoozeAiChatPage';
-import { snoozeAiChatThreadIdComponentState } from '@/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdComponentState';
+import { snoozeAiChatThreadIdsComponentState } from '@/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdsComponentState';
import { SidePanelPageComponentInstanceContext } from '@/side-panel/states/contexts/SidePanelPageComponentInstanceContext';
import {
jotaiStore,
resetJotaiStore,
} from '@/ui/utilities/state/jotai/jotaiStore';
-const snoozeAgentChatThread = jest.fn();
+const snoozeAgentChatThreads = jest.fn();
const closeSidePanelMenu = jest.fn();
jest.mock('@/ai/hooks/useAgentChatThreadParticipants', () => ({
- useAgentChatThreadParticipants: () => ({ snoozeAgentChatThread }),
+ useAgentChatThreadParticipants: () => ({ snoozeAgentChatThreads }),
}));
jest.mock('@/side-panel/hooks/useSidePanelMenu', () => ({
@@ -48,8 +48,8 @@ describe('SidePanelSnoozeAiChatPage', () => {
resetJotaiStore();
jotaiStore.set(agentChatThreadInboxNowState.atom, Date.now());
jotaiStore.set(
- snoozeAiChatThreadIdComponentState.atomFamily({ instanceId: PAGE_ID }),
- 'thread-1',
+ snoozeAiChatThreadIdsComponentState.atomFamily({ instanceId: PAGE_ID }),
+ ['thread-1', 'thread-2'],
);
});
@@ -57,14 +57,14 @@ describe('SidePanelSnoozeAiChatPage', () => {
jest.useRealTimers();
});
- it('snoozes the chat until the picked time', () => {
+ it('snoozes the chats until the picked time', () => {
render(<SidePanelSnoozeAiChatPage />, { wrapper: Wrapper });
fireEvent.click(screen.getByText('This evening'));
expect(closeSidePanelMenu).toHaveBeenCalled();
- expect(snoozeAgentChatThread).toHaveBeenCalledWith({
- threadId: 'thread-1',
+ expect(snoozeAgentChatThreads).toHaveBeenCalledWith({
+ threadIds: ['thread-1', 'thread-2'],
snoozedUntil: new Date(2026, 9, 1, 18, 0),
});
});
@@ -85,7 +85,7 @@ describe('SidePanelSnoozeAiChatPage', () => {
expect(
await screen.findByRole('button', { name: /^Snooze until/ }),
).toBeInTheDocument();
- expect(snoozeAgentChatThread).not.toHaveBeenCalled();
+ expect(snoozeAgentChatThreads).not.toHaveBeenCalled();
expect(
screen.getByText('Day & Time').closest('[data-focused]'),
).toHaveAttribute('data-focused', 'true');
@@ -99,7 +99,7 @@ describe('SidePanelSnoozeAiChatPage', () => {
});
fireEvent.click(screen.getByText('This evening'));
- expect(snoozeAgentChatThread).not.toHaveBeenCalled();
+ expect(snoozeAgentChatThreads).not.toHaveBeenCalled();
expect(screen.queryByText('This evening')).not.toBeInTheDocument();
expect(screen.getByText('Tomorrow')).toBeInTheDocument();
});
diff --git a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SnoozeAiChatUntilDatePicker.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SnoozeAiChatUntilDatePicker.test.tsx
index b07dd22165d..297432dafaf 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SnoozeAiChatUntilDatePicker.test.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SnoozeAiChatUntilDatePicker.test.tsx
@@ -12,11 +12,11 @@ import {
resetJotaiStore,
} from '@/ui/utilities/state/jotai/jotaiStore';
-const snoozeAgentChatThread = jest.fn();
+const snoozeAgentChatThreads = jest.fn();
const onSnoozed = jest.fn();
jest.mock('@/ai/hooks/useAgentChatThreadParticipants', () => ({
- useAgentChatThreadParticipants: () => ({ snoozeAgentChatThread }),
+ useAgentChatThreadParticipants: () => ({ snoozeAgentChatThreads }),
}));
jest.mock('@/ui/input/components/internal/date/hooks/useUserTimezone', () => ({
@@ -70,22 +70,28 @@ describe('SnoozeAiChatUntilDatePicker', () => {
it('snoozes the chat until tomorrow morning by default', () => {
render(
- <SnoozeAiChatUntilDatePicker threadId="thread-1" onSnoozed={onSnoozed} />,
+ <SnoozeAiChatUntilDatePicker
+ threadIds={['thread-1']}
+ onSnoozed={onSnoozed}
+ />,
{ wrapper: Wrapper },
);
fireEvent.click(screen.getByRole('button', { name: /Snooze until/ }));
expect(onSnoozed).toHaveBeenCalled();
- expect(snoozeAgentChatThread).toHaveBeenCalledWith({
- threadId: 'thread-1',
+ expect(snoozeAgentChatThreads).toHaveBeenCalledWith({
+ threadIds: ['thread-1'],
snoozedUntil: new Date(2026, 9, 2, 9, 0),
});
});
it('does not snooze until a time that has passed', () => {
render(
- <SnoozeAiChatUntilDatePicker threadId="thread-1" onSnoozed={onSnoozed} />,
+ <SnoozeAiChatUntilDatePicker
+ threadIds={['thread-1']}
+ onSnoozed={onSnoozed}
+ />,
{ wrapper: Wrapper },
);
@@ -97,13 +103,16 @@ describe('SnoozeAiChatUntilDatePicker', () => {
expect(
screen.getByRole('button', { name: 'Pick a time in the future' }),
).toBeDisabled();
- expect(snoozeAgentChatThread).not.toHaveBeenCalled();
+ expect(snoozeAgentChatThreads).not.toHaveBeenCalled();
expect(onSnoozed).not.toHaveBeenCalled();
});
it('turns the button off once the picked time passes', () => {
render(
- <SnoozeAiChatUntilDatePicker threadId="thread-1" onSnoozed={onSnoozed} />,
+ <SnoozeAiChatUntilDatePicker
+ threadIds={['thread-1']}
+ onSnoozed={onSnoozed}
+ />,
{ wrapper: Wrapper },
);
diff --git a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdComponentState.ts b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdsComponentState.ts
similarity index 65%
rename from packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdComponentState.ts
rename to packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdsComponentState.ts
index f3c89a4f442..89e787dcc10 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdComponentState.ts
+++ b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdsComponentState.ts
@@ -1,10 +1,10 @@
import { SidePanelPageComponentInstanceContext } from '@/side-panel/states/contexts/SidePanelPageComponentInstanceContext';
import { createAtomComponentState } from '@/ui/utilities/state/jotai/utils/createAtomComponentState';
-export const snoozeAiChatThreadIdComponentState = createAtomComponentState<
- string | null
+export const snoozeAiChatThreadIdsComponentState = createAtomComponentState<
+ string[]
>({
- key: 'side-panel/snooze-ai-chat-thread-id',
- defaultValue: null,
+ key: 'side-panel/snooze-ai-chat-thread-ids',
+ defaultValue: [],
componentInstanceContext: SidePanelPageComponentInstanceContext,
});
diff --git a/packages/twenty-front/src/pages/ai-chat/AiChatInboxPage.tsx b/packages/twenty-front/src/pages/ai-chat/AiChatInboxPage.tsx
index 2f0aaad29f7..7092f5665ac 100644
--- a/packages/twenty-front/src/pages/ai-chat/AiChatInboxPage.tsx
+++ b/packages/twenty-front/src/pages/ai-chat/AiChatInboxPage.tsx
@@ -1,5 +1,6 @@
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
+import { type MouseEvent, useId } from 'react';
import { useParams } from 'react-router-dom';
import { AppPath } from 'twenty-shared/types';
import { isDefined, isValidUuid } from 'twenty-shared/utils';
@@ -12,6 +13,7 @@ import { useIsMobile } from 'twenty-ui/utilities';
import { SkeletonLoader } from '@/activities/components/SkeletonLoader';
import { AgentChatThreadsFetchMoreTrigger } from '@/ai/components/AgentChatThreadsFetchMoreTrigger';
import { AiChatInboxSelectionEffect } from '@/ai/components/AiChatInboxSelectionEffect';
+import { AiChatInboxSelectionPane } from '@/ai/components/AiChatInboxSelectionPane';
import { AiChatThreadList } from '@/ai/components/AiChatThreadList';
import { AGENT_CHAT_THREAD_FILTER_STATUS_ICONS } from '@/ai/constants/AgentChatThreadFilterStatusIcons';
import { AGENT_CHAT_THREAD_FILTER_STATUS_LABELS } from '@/ai/constants/AgentChatThreadFilterStatusLabels';
@@ -20,10 +22,17 @@ import { useChatThreads } from '@/ai/hooks/useChatThreads';
import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';
import { agentChatThreadFilterStatusState } from '@/ai/states/agentChatThreadFilterStatusState';
import { agentChatVisibleThreadsSelector } from '@/ai/states/selectors/agentChatVisibleThreadsSelector';
+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';
+import { RecordSelectionRecordIdsEffect } from '@/object-record/record-selection/components/RecordSelectionRecordIdsEffect';
+import { useResetRecordSelection } from '@/object-record/record-selection/hooks/useResetRecordSelection';
+import { useToggleRecordSelection } from '@/object-record/record-selection/hooks/useToggleRecordSelection';
+import { RecordSelectionComponentInstanceContext } from '@/object-record/record-selection/states/contexts/RecordSelectionComponentInstanceContext';
+import { selectedRecordIdsComponentSelector } from '@/object-record/record-selection/states/selectors/selectedRecordIdsComponentSelector';
import { AnimatedPlaceholder } from '@/ui/feedback/empty-state/components/AnimatedPlaceholder/AnimatedPlaceholder';
import { EmptyState } from '@/ui/feedback/empty-state/components/EmptyState';
import { PageCardHeader } from '@/ui/layout/page/components/PageCardHeader';
import { PageCardLayout } from '@/ui/layout/page/components/PageCardLayout';
+import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { useNavigateApp } from '~/hooks/useNavigateApp';
import { AiChatPageEffects } from '~/pages/ai-chat/AiChatPageEffects';
@@ -52,7 +61,7 @@ const StyledThreadList = styled.div`
padding: ${themeCssVariables.spacing[2]};
`;
-export const AiChatInboxPage = () => {
+const AiChatInboxPageContent = () => {
const { t } = useLingui();
const isMobile = useIsMobile();
const navigate = useNavigateApp();
@@ -70,17 +79,57 @@ export const AiChatInboxPage = () => {
shouldOpenInFullPage: true,
});
+ const selectedRecordIds = useAtomComponentSelectorValue(
+ selectedRecordIdsComponentSelector,
+ );
+ const { toggleRecordSelection } = useToggleRecordSelection();
+ const { resetRecordSelection } = useResetRecordSelection();
+
// Rows hold a menu and a rename input, which a link cannot contain
const selectThread = (nextThreadId: string | null) =>
// oxlint-disable-next-line twenty/no-navigate-prefer-link
navigate(AppPath.AiChatInbox, { threadId: nextThreadId });
+ const handleThreadClick = (
+ { id }: AgentChatThreadRecord,
+ event: MouseEvent<HTMLDivElement>,
+ ) => {
+ // A phone shows the list or a chat, with no room for the selection pane
+ if (isMobile || (!event.metaKey && !event.ctrlKey && !event.shiftKey)) {
+ resetRecordSelection();
+ selectThread(id);
+ return;
+ }
+
+ // A selection starts from the chat on screen
+ if (
+ selectedRecordIds.length === 0 &&
+ isDefined(selectedThreadId) &&
+ selectedThreadId !== id &&
+ threads.some((thread) => thread.id === selectedThreadId)
+ ) {
+ toggleRecordSelection({ recordId: selectedThreadId });
+ }
+
+ toggleRecordSelection({ recordId: id, shouldSelectRange: event.shiftKey });
+ };
+
+ const isSelectionShown =
+ selectedRecordIds.length > 1 ||
+ (selectedRecordIds.length === 1 &&
+ selectedRecordIds[0] !== selectedThreadId);
+ const openThreadIds = isDefined(selectedThreadId) ? [selectedThreadId] : [];
+ const highlightedThreadIds = isSelectionShown
+ ? selectedRecordIds
+ : openThreadIds;
+
// A phone has room for the list or the chat, not both
const isListShown = !isMobile || !isDefined(selectedThreadId);
const isThreadShown = !isMobile || isDefined(selectedThreadId);
return (
<StyledInbox>
+ <RecordSelectionRecordIdsEffect records={threads} />
{!isMobile && (
<AiChatInboxSelectionEffect
selectedThreadId={selectedThreadId}
@@ -129,8 +178,8 @@ export const AiChatInboxPage = () => {
<AiChatThreadList
threads={threads}
surface={AI_CHAT_THREAD_ACTIONS_SURFACE.INBOX_PAGE}
- selectedThreadId={selectedThreadId}
- onThreadClick={({ id }) => selectThread(id)}
+ selectedThreadIds={highlightedThreadIds}
+ onThreadClick={handleThreadClick}
/>
)}
<AgentChatThreadsFetchMoreTrigger />
@@ -139,7 +188,9 @@ export const AiChatInboxPage = () => {
</StyledListPane>
)}
{isThreadShown &&
- (isDefined(selectedThreadId) ? (
+ (isSelectionShown ? (
+ <AiChatInboxSelectionPane />
+ ) : isDefined(selectedThreadId) ? (
<>
<AiChatPageEffects />
<AiChatThreadPageContent
@@ -170,3 +221,16 @@ export const AiChatInboxPage = () => {
</StyledInbox>
);
};
+
+export const AiChatInboxPage = () => {
+ // A new instance per visit, so a selection does not outlive the inbox
+ const recordSelectionInstanceId = useId();
+
+ return (
+ <RecordSelectionComponentInstanceContext.Provider
+ value={{ instanceId: recordSelectionInstanceId }}
+ >
+ <AiChatInboxPageContent />
+ </RecordSelectionComponentInstanceContext.Provider>
+ );
+};
diff --git a/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx b/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx
new file mode 100644
index 00000000000..7e90f4ca040
--- /dev/null
+++ b/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx
@@ -0,0 +1,218 @@
+import { i18n } from '@lingui/core';
+import { I18nProvider } from '@lingui/react';
+import { fireEvent, render, screen } from '@testing-library/react';
+import { atom, Provider as JotaiProvider } from 'jotai';
+import { type ReactNode } from 'react';
+import { MemoryRouter, Route, Routes } from 'react-router-dom';
+import { AppPath } from 'twenty-shared/types';
+import { SOURCE_LOCALE } from 'twenty-shared/translations';
+
+import { CommandMenuComponentInstanceContext } from '@/command-menu/states/contexts/CommandMenuComponentInstanceContext';
+import { contextStoreTargetedRecordsRuleComponentState } from '@/context-store/states/contextStoreTargetedRecordsRuleComponentState';
+import { ContextStoreComponentInstanceContext } from '@/context-store/states/contexts/ContextStoreComponentInstanceContext';
+import { AI_CHAT_INBOX_INSTANCE_ID } from '@/ai/constants/AiChatInboxInstanceId';
+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';
+import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
+import { useAvailableComponentInstanceIdOrThrow } from '@/ui/utilities/state/component-state/hooks/useAvailableComponentInstanceIdOrThrow';
+import {
+ resetJotaiStore,
+ jotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
+import { messages } from '~/locales/generated/en';
+import { AiChatInboxPage } from '~/pages/ai-chat/AiChatInboxPage';
+
+i18n.load({ [SOURCE_LOCALE]: messages });
+i18n.activate(SOURCE_LOCALE);
+
+const buildThread = (id: string, title: string): AgentChatThreadRecord => ({
+ __typename: 'AgentChatThread',
+ id,
+ title,
+ deletedAt: null,
+ createdAt: '2026-09-07T00:00:00.000Z',
+ updatedAt: '2026-09-07T00:00:00.000Z',
+});
+
+const THREADS = [
+ buildThread('6f1c2b0e-7a4d-4e8b-9c3f-2d5a1b8e7c60', 'First chat'),
+ buildThread('0b6e3f1a-2c4d-4b8e-9a7f-1d3c5e7a9b20', 'Second chat'),
+ buildThread('9d2a4c6e-8b1f-4e3a-8c5d-7f9b1a3c5e40', 'Third chat'),
+];
+
+const chatObjectMetadataItemAtom = atom<Pick<EnrichedObjectMetadataItem, 'id'>>(
+ { id: 'chat-object' },
+);
+
+jest.mock('@/object-metadata/states/objectMetadataItemFamilySelector', () => ({
+ objectMetadataItemFamilySelector: {
+ selectorFamily: () => chatObjectMetadataItemAtom,
+ },
+}));
+
+jest.mock('@/ai/hooks/useChatThreads', () => ({
+ useChatThreads: () => ({ threads: THREADS, loading: false }),
+}));
+
+jest.mock('@/ai/components/AiChatThreadList', () => ({
+ AiChatThreadList: ({
+ threads,
+ selectedThreadIds,
+ onThreadClick,
+ }: {
+ threads: AgentChatThreadRecord[];
+ selectedThreadIds: string[];
+ onThreadClick: (
+ thread: AgentChatThreadRecord,
+ event: React.MouseEvent<HTMLButtonElement>,
+ ) => void;
+ }) =>
+ threads.map((thread) => (
+ <button
+ key={thread.id}
+ aria-pressed={selectedThreadIds.includes(thread.id)}
+ onClick={(event) => onThreadClick(thread, event)}
+ >
+ {thread.title}
+ </button>
+ )),
+}));
+
+jest.mock('@/ai/components/AgentChatThreadsFetchMoreTrigger', () => ({
+ AgentChatThreadsFetchMoreTrigger: () => null,
+}));
+
+jest.mock('@/ai/hooks/useSwitchToNewAiChat', () => ({
+ useSwitchToNewAiChat: () => ({ switchToNewChat: jest.fn() }),
+}));
+
+jest.mock('~/pages/ai-chat/AiChatPageEffects', () => ({
+ AiChatPageEffects: () => null,
+}));
+
+jest.mock('~/pages/ai-chat/AiChatThreadPageContent', () => ({
+ AiChatThreadPageContent: ({ threadId }: { threadId: string }) => (
+ <div>Chat page {threadId}</div>
+ ),
+}));
+
+jest.mock('@/information-banner/components/InformationBannerWrapper', () => ({
+ InformationBannerWrapper: () => null,
+}));
+
+// Command menu items throw without the context store and command menu
+// instances, so the stand-in requires them too
+jest.mock('@/command-menu-item/contexts/CommandMenuContextProvider', () => ({
+ CommandMenuContextProvider: ({ children }: { children: ReactNode }) => {
+ useAvailableComponentInstanceIdOrThrow(
+ ContextStoreComponentInstanceContext,
+ );
+ useAvailableComponentInstanceIdOrThrow(CommandMenuComponentInstanceContext);
+ return children;
+ },
+}));
+
+jest.mock(
+ '@/command-menu-item/display/components/PinnedCommandMenuItemButtons',
+ () => ({ PinnedCommandMenuItemButtons: () => null }),
+);
+
+const [firstThread, secondThread, thirdThread] = THREADS;
+
+const renderInbox = () =>
+ render(
+ <JotaiProvider store={jotaiStore}>
+ <I18nProvider i18n={i18n}>
+ <MemoryRouter initialEntries={[`/inbox/${firstThread.id}`]}>
+ <Routes>
+ <Route path={AppPath.AiChatInbox} element={<AiChatInboxPage />} />
+ </Routes>
+ </MemoryRouter>
+ </I18nProvider>
+ </JotaiProvider>,
+ );
+
+const isRowHighlighted = (title: string) =>
+ screen.getByRole('button', { name: title }).getAttribute('aria-pressed') ===
+ 'true';
+
+describe('AiChatInboxPage', () => {
+ beforeEach(() => {
+ resetJotaiStore();
+ });
+
+ it('opens the clicked chat', () => {
+ renderInbox();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Second chat' }));
+
+ expect(
+ screen.getByText(`Chat page ${secondThread.id}`),
+ ).toBeInTheDocument();
+ });
+
+ it('adds a chat to the one on screen with cmd+click', () => {
+ renderInbox();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Third chat' }), {
+ metaKey: true,
+ });
+
+ expect(screen.getByText('2 chats selected')).toBeInTheDocument();
+ expect(
+ jotaiStore.get(
+ contextStoreTargetedRecordsRuleComponentState.atomFamily({
+ instanceId: AI_CHAT_INBOX_INSTANCE_ID,
+ }),
+ ),
+ ).toEqual({
+ mode: 'selection',
+ selectedRecordIds: [firstThread.id, thirdThread.id],
+ });
+ expect(isRowHighlighted('First chat')).toBe(true);
+ expect(isRowHighlighted('Second chat')).toBe(false);
+ expect(isRowHighlighted('Third chat')).toBe(true);
+ });
+
+ it('selects every chat from the one on screen with shift+click', () => {
+ renderInbox();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Third chat' }), {
+ shiftKey: true,
+ });
+
+ expect(screen.getByText('3 chats selected')).toBeInTheDocument();
+ });
+
+ it('goes back to the chat on screen once the selection is cleared', () => {
+ renderInbox();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Second chat' }), {
+ ctrlKey: true,
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Clear selection' }));
+
+ expect(screen.getByText(`Chat page ${firstThread.id}`)).toBeInTheDocument();
+ });
+
+ it('starts with no selection when coming back to the inbox', () => {
+ const { unmount } = renderInbox();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Second chat' }), {
+ metaKey: true,
+ });
+ unmount();
+
+ expect(
+ jotaiStore.get(
+ contextStoreTargetedRecordsRuleComponentState.atomFamily({
+ instanceId: AI_CHAT_INBOX_INSTANCE_ID,
+ }),
+ ),
+ ).toEqual({ mode: 'selection', selectedRecordIds: [] });
+
+ renderInbox();
+
+ expect(screen.getByText(`Chat page ${firstThread.id}`)).toBeInTheDocument();
+ expect(isRowHighlighted('Second chat')).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module.ts
index b903258e45c..2901bf10aaa 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module.ts
@@ -5,6 +5,7 @@ import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/w
import { AddAgentChatThreadParticipantObjectCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019631-add-agent-chat-thread-participant-object.command';
import { BackfillAgentChatThreadInboxStateCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019632-backfill-agent-chat-thread-inbox-state.command';
import { AddAiChatInboxCommandMenuItemsCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019633-add-ai-chat-inbox-command-menu-items.command';
+import { AllowAiChatInboxCommandsOnSeveralChatsCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791009973891-allow-ai-chat-inbox-commands-on-several-chats.command';
import { UnpinNewAiChatCommandMenuItemCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019634-unpin-new-ai-chat-command-menu-item.command';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@@ -23,6 +24,7 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
BackfillAgentChatThreadInboxStateCommand,
AddAiChatInboxCommandMenuItemsCommand,
UnpinNewAiChatCommandMenuItemCommand,
+ AllowAiChatInboxCommandsOnSeveralChatsCommand,
],
})
export class V2_46_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019631-add-agent-chat-thread-participant-object.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019631-add-agent-chat-thread-participant-object.command.ts
index 2aaeb4ed1b5..19eacfaa132 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019631-add-agent-chat-thread-participant-object.command.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019631-add-agent-chat-thread-participant-object.command.ts
@@ -90,7 +90,8 @@ export class AddAgentChatThreadParticipantObjectCommand extends ProvisionedWorks
const objectsToCreate =
getStandardFlatEntitiesToCreateOrThrow<FlatObjectMetadata>({
- standardFlatEntityMaps: standardAllFlatEntityMaps.flatObjectMetadataMaps,
+ standardFlatEntityMaps:
+ standardAllFlatEntityMaps.flatObjectMetadataMaps,
existingFlatEntityMaps: flatObjectMetadataMaps,
universalIdentifiers: [PARTICIPANT_OBJECT_UNIVERSAL_IDENTIFIER],
});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019632-backfill-agent-chat-thread-inbox-state.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019632-backfill-agent-chat-thread-inbox-state.command.ts
index a315e5d9fc2..0d2565de6ea 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019632-backfill-agent-chat-thread-inbox-state.command.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019632-backfill-agent-chat-thread-inbox-state.command.ts
@@ -186,8 +186,9 @@ const backfillAgentChatThreadInboxState = async ({
return {
threadCount,
participantCount: participants.length,
- archivedThreadCount: new Set(archivedThreads.map(({ threadId }) => threadId))
- .size,
+ archivedThreadCount: new Set(
+ archivedThreads.map(({ threadId }) => threadId),
+ ).size,
};
};
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791009973891-allow-ai-chat-inbox-commands-on-several-chats.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791009973891-allow-ai-chat-inbox-commands-on-several-chats.command.ts
new file mode 100644
index 00000000000..8e0784c06c9
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791009973891-allow-ai-chat-inbox-commands-on-several-chats.command.ts
@@ -0,0 +1,125 @@
+import { Command } from 'nest-commander';
+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { STANDARD_COMMAND_MENU_ITEMS } from 'src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant';
+import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';
+import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';
+
+const INBOX_COMMAND_MENU_ITEM_NAMES = [
+ 'markAiChatAsRead',
+ 'markAiChatAsUnread',
+ 'markAiChatAsDone',
+ 'reopenAiChat',
+ 'unsnoozeAiChat',
+ 'snoozeAiChat',
+] as const;
+
+const ONE_CHAT_CONDITION = 'numberOfSelectedRecords == 1 ';
+const SEVERAL_CHATS_CONDITION = 'numberOfSelectedRecords >= 1 ';
+
+@RegisteredWorkspaceCommand('2.46.0', 1791009973891)
+@Command({
+ name: 'upgrade:2-46:allow-ai-chat-inbox-commands-on-several-chats',
+ description:
+ 'Offer the inbox commands when several chats are selected, for workspaces that got them for a single chat',
+})
+export class AllowAiChatInboxCommandsOnSeveralChatsCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.up(args);
+ }
+
+ async up(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.replaceCondition(args, {
+ from: ONE_CHAT_CONDITION,
+ to: SEVERAL_CHATS_CONDITION,
+ });
+ }
+
+ async down(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.replaceCondition(args, {
+ from: SEVERAL_CHATS_CONDITION,
+ to: ONE_CHAT_CONDITION,
+ });
+ }
+
+ private async replaceCondition(
+ { workspaceId, options }: RunOnWorkspaceArgs,
+ { from, to }: { from: string; to: string },
+ ): Promise<void> {
+ const { flatCommandMenuItemMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatCommandMenuItemMaps',
+ ]);
+
+ const commandMenuItemsToUpdate = INBOX_COMMAND_MENU_ITEM_NAMES.map(
+ (name) =>
+ flatCommandMenuItemMaps.byUniversalIdentifier[
+ STANDARD_COMMAND_MENU_ITEMS[name].universalIdentifier
+ ],
+ ).filter(
+ (commandMenuItem) =>
+ isDefined(commandMenuItem) &&
+ isDefined(commandMenuItem.conditionalAvailabilityExpression) &&
+ commandMenuItem.conditionalAvailabilityExpression.startsWith(from),
+ );
+
+ if (commandMenuItemsToUpdate.length === 0) {
+ return;
+ }
+
+ this.logger.log(
+ `${options.dryRun ? '[DRY RUN] ' : ''}Workspace ${workspaceId}: updating ${commandMenuItemsToUpdate.length} inbox command menu item(s)`,
+ );
+
+ if (options.dryRun) {
+ return;
+ }
+
+ const updatedAt = new Date().toISOString();
+
+ const result =
+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunLegacyWorkspaceMigration(
+ {
+ workspaceId,
+ isSystemBuild: true,
+ applicationUniversalIdentifier:
+ TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,
+ allFlatEntityOperationByMetadataName: {
+ commandMenuItem: {
+ flatEntityToCreate: [],
+ flatEntityToDelete: [],
+ flatEntityToUpdate: commandMenuItemsToUpdate
+ .filter(isDefined)
+ .map((commandMenuItem) => ({
+ ...commandMenuItem,
+ conditionalAvailabilityExpression:
+ commandMenuItem.conditionalAvailabilityExpression?.replace(
+ from,
+ to,
+ ) ?? null,
+ updatedAt,
+ })),
+ },
+ },
+ },
+ );
+
+ if (result.status === 'fail') {
+ throw new WorkspaceMigrationBuilderException(result);
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/__tests__/standard-ai-chat-inbox-command-menu-items.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/__tests__/standard-ai-chat-inbox-command-menu-items.spec.ts
index 5ff953d762c..9adc23ca26b 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/__tests__/standard-ai-chat-inbox-command-menu-items.spec.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/__tests__/standard-ai-chat-inbox-command-menu-items.spec.ts
@@ -9,20 +9,20 @@ const INBOX_COMMAND_MENU_ITEM_NAMES = [
'snoozeAiChat',
] as const;
-const getAvailableInboxCommands = (scope: 'INBOX' | 'SNOOZED' | 'ARCHIVED') =>
+type InboxScope = 'INBOX' | 'SNOOZED' | 'ARCHIVED';
+
+const getAvailableInboxCommands = (...scopes: InboxScope[]) =>
INBOX_COMMAND_MENU_ITEM_NAMES.filter((name) =>
evaluateConditionalAvailabilityExpression(
STANDARD_COMMAND_MENU_ITEMS[name].conditionalAvailabilityExpression,
{
- numberOfSelectedRecords: 1,
+ numberOfSelectedRecords: scopes.length,
permissionFlags: { AI: true },
- selectedRecords: [
- {
- id: 'thread-1',
- deletedAt: null,
- inboxStatus: { scope, isUnread: false, event: null },
- },
- ],
+ selectedRecords: scopes.map((scope, index) => ({
+ id: `thread-${index}`,
+ deletedAt: null,
+ inboxStatus: { scope, isUnread: false, event: null },
+ })),
},
),
);
@@ -45,4 +45,17 @@ describe('AI chat inbox command menu items', () => {
'snoozeAiChat',
]);
});
+
+ it('offers done and snooze on several open chats', () => {
+ expect(getAvailableInboxCommands('INBOX', 'INBOX')).toEqual([
+ 'markAiChatAsDone',
+ 'snoozeAiChat',
+ ]);
+ });
+
+ it('offers only what every selected chat allows', () => {
+ expect(getAvailableInboxCommands('INBOX', 'ARCHIVED')).toEqual([
+ 'snoozeAiChat',
+ ]);
+ });
});
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts
index eba1f1ea8ea..f72021bcf03 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/constants/standard-command-menu-item.constant.ts
@@ -953,7 +953,7 @@ export const STANDARD_COMMAND_MENU_ITEMS = {
),
availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
conditionalAvailabilityExpression:
- 'numberOfSelectedRecords == 1 and permissionFlags.AI and noneDefined(selectedRecords, "deletedAt") and every(selectedRecords, "inboxStatus.isUnread")',
+ 'numberOfSelectedRecords >= 1 and permissionFlags.AI and noneDefined(selectedRecords, "deletedAt") and every(selectedRecords, "inboxStatus.isUnread")',
availabilityObjectMetadataUniversalIdentifier:
STANDARD_OBJECTS.agentChatThread.universalIdentifier,
frontComponentUniversalIdentifier: null,
@@ -973,7 +973,7 @@ export const STANDARD_COMMAND_MENU_ITEMS = {
),
availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
conditionalAvailabilityExpression:
- 'numberOfSelectedRecords == 1 and permissionFlags.AI and noneDefined(selectedRecords, "deletedAt") and everyEquals(selectedRecords, "inboxStatus.isUnread", false)',
+ 'numberOfSelectedRecords >= 1 and permissionFlags.AI and noneDefined(selectedRecords, "deletedAt") and everyEquals(selectedRecords, "inboxStatus.isUnread", false)',
availabilityObjectMetadataUniversalIdentifier:
STANDARD_OBJECTS.agentChatThread.universalIdentifier,
frontComponentUniversalIdentifier: null,
@@ -993,7 +993,7 @@ export const STANDARD_COMMAND_MENU_ITEMS = {
),
availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
conditionalAvailabilityExpression:
- 'numberOfSelectedRecords == 1 and permissionFlags.AI and noneDefined(selectedRecords, "deletedAt") and everyEquals(selectedRecords, "inboxStatus.scope", "INBOX")',
+ 'numberOfSelectedRecords >= 1 and permissionFlags.AI and noneDefined(selectedRecords, "deletedAt") and everyEquals(selectedRecords, "inboxStatus.scope", "INBOX")',
availabilityObjectMetadataUniversalIdentifier:
STANDARD_OBJECTS.agentChatThread.universalIdentifier,
frontComponentUniversalIdentifier: null,
@@ -1013,7 +1013,7 @@ export const STANDARD_COMMAND_MENU_ITEMS = {
),
availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
conditionalAvailabilityExpression:
- 'numberOfSelectedRecords == 1 and permissionFlags.AI and noneDefined(selectedRecords, "deletedAt") and everyEquals(selectedRecords, "inboxStatus.scope", "ARCHIVED")',
+ 'numberOfSelectedRecords >= 1 and permissionFlags.AI and noneDefined(selectedRecords, "deletedAt") and everyEquals(selectedRecords, "inboxStatus.scope", "ARCHIVED")',
availabilityObjectMetadataUniversalIdentifier:
STANDARD_OBJECTS.agentChatThread.universalIdentifier,
frontComponentUniversalIdentifier: null,
@@ -1033,7 +1033,7 @@ export const STANDARD_COMMAND_MENU_ITEMS = {
),
availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
conditionalAvailabilityExpression:
- 'numberOfSelectedRecords == 1 and permissionFlags.AI and noneDefined(selectedRecords, "deletedAt") and everyEquals(selectedRecords, "inboxStatus.scope", "SNOOZED")',
+ 'numberOfSelectedRecords >= 1 and permissionFlags.AI and noneDefined(selectedRecords, "deletedAt") and everyEquals(selectedRecords, "inboxStatus.scope", "SNOOZED")',
availabilityObjectMetadataUniversalIdentifier:
STANDARD_OBJECTS.agentChatThread.universalIdentifier,
frontComponentUniversalIdentifier: null,
@@ -1053,7 +1053,7 @@ export const STANDARD_COMMAND_MENU_ITEMS = {
),
availabilityType: CommandMenuItemAvailabilityType.RECORD_SELECTION,
conditionalAvailabilityExpression:
- 'numberOfSelectedRecords == 1 and permissionFlags.AI and noneDefined(selectedRecords, "deletedAt") and everyDefined(selectedRecords, "inboxStatus") and noneEquals(selectedRecords, "inboxStatus.scope", "SNOOZED")',
+ 'numberOfSelectedRecords >= 1 and permissionFlags.AI and noneDefined(selectedRecords, "deletedAt") and everyDefined(selectedRecords, "inboxStatus") and noneEquals(selectedRecords, "inboxStatus.scope", "SNOOZED")',
availabilityObjectMetadataUniversalIdentifier:
STANDARD_OBJECTS.agentChatThread.universalIdentifier,
frontComponentUniversalIdentifier: null,