The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Show conversation status in thread details (#29195)
Raphaël Bosi53d2d6a0c4d8
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsDropdown.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsDropdown.tsxindex 1da39a02537..623d08fcfaf 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsDropdown.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsDropdown.tsx@@ -18,6 +18,7 @@ import { themeCssVariables, useTheme } from 'twenty-ui/theme';import { AgentChatChannelIcon } from '@/ai/components/AgentChatChannelIcon';import { AiChatThreadChannelPicker } from '@/ai/components/AiChatThreadChannelPicker';+import { AiChatThreadDetailsStatus } from '@/ai/components/AiChatThreadDetailsStatus';import { AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX } from '@/ai/constants/AiChatThreadDetailsLabelWidthInPx';import { agentChatChannelsState } from '@/ai/states/agentChatChannelsState';import { useAiChatThreadRecordTargets } from '@/ai/hooks/useAiChatThreadRecordTargets';@@ -157,6 +158,10 @@ export const AiChatThreadDetailsDropdown = ({aria-label={t`Chat details`}><StyledDetails>+ <AiChatThreadDetailsStatus+ threadId={threadId}+ dropdownId={dropdownId}+ />{areRecordTargetsAvailable && (<DetailsRowlabelWidth={AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX}diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsStatus.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsStatus.tsxnew file mode 100644index 00000000000..b6c40a00669--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadDetailsStatus.tsx@@ -0,0 +1,45 @@+import { isDefined } from 'twenty-shared/utils';++import { AiChatThreadStatusField } from '@/ai/components/AiChatThreadStatusField';+import { useAiChatThreadDetailsStatus } from '@/ai/hooks/useAiChatThreadDetailsStatus';+import { type AiChatThreadTriageStatus } from '@/ai/types/AiChatThreadTriageStatus';+import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';++type AiChatThreadDetailsStatusProps = {+ threadId: string;+ dropdownId: string;+};++export const AiChatThreadDetailsStatus = ({+ threadId,+ dropdownId,+}: AiChatThreadDetailsStatusProps) => {+ const { status, scope, canChangeStatus, isPending, changeStatus } =+ useAiChatThreadDetailsStatus(threadId);+ const { closeDropdown } = useCloseDropdown();++ const handleStatusChange = ({+ status: nextStatus,+ }: {+ status: AiChatThreadTriageStatus;+ }) => {+ if (nextStatus === 'snoozed') {+ closeDropdown(dropdownId);+ }++ changeStatus(nextStatus);+ };++ if (!isDefined(status) || !isDefined(scope)) {+ return null;+ }++ return (+ <AiChatThreadStatusField+ status={status}+ scope={scope}+ isSaving={isPending}+ onStatusChange={canChangeStatus ? handleStatusChange : undefined}+ />+ );+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsxindex c873269fa46..4cbdc1849ee 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadListItem.tsx@@ -71,7 +71,9 @@ export const AiChatThreadListItem = ({isDropdownOpenComponentState,itemMenuDropdownId,);- const { status: triageStatus } = useAiChatThreadTriage(thread.id);+ const { status: triageStatus } = useAiChatThreadTriage({+ threadId: thread.id,+ });const shouldShowMore =isDefined(onDetach) ||isDefined(thread.deletedAt) ||diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadRowTriage.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadRowTriage.tsxindex 8c871a08eed..0eaac606211 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadRowTriage.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadRowTriage.tsx@@ -1,9 +1,10 @@import { isDefined } from 'twenty-shared/utils';import { AiChatThreadTriageButtons } from '@/ai/components/AiChatThreadTriageButtons';+import { AI_CHAT_THREAD_INBOX_ACTION_BY_TRIAGE_STATUS } from '@/ai/constants/AiChatThreadInboxActionByTriageStatus';import { useAiChatThreadTriage } from '@/ai/hooks/useAiChatThreadTriage';import { useExecuteAgentChatThreadInboxAction } from '@/ai/hooks/useExecuteAgentChatThreadInboxAction';-import { AgentChatInboxAction } from '~/generated-metadata/graphql';+import { type AiChatThreadTriageStatus } from '@/ai/types/AiChatThreadTriageStatus';type AiChatThreadRowTriageProps = {threadId: string;@@ -12,7 +13,7 @@ type AiChatThreadRowTriageProps = {export const AiChatThreadRowTriage = ({threadId,}: AiChatThreadRowTriageProps) => {- const { status, isInChannel } = useAiChatThreadTriage(threadId);+ const { status, isInChannel } = useAiChatThreadTriage({ threadId });const { executeAgentChatThreadInboxAction, isPending } =useExecuteAgentChatThreadInboxAction();@@ -20,10 +21,10 @@ export const AiChatThreadRowTriage = ({return null;}- const executeInboxAction = (action: AgentChatInboxAction) => {+ const moveToStatus = (nextStatus: AiChatThreadTriageStatus) => {void executeAgentChatThreadInboxAction({threadIds: [threadId],- action,+ action: AI_CHAT_THREAD_INBOX_ACTION_BY_TRIAGE_STATUS[nextStatus],isInChannel,});};@@ -32,9 +33,9 @@ export const AiChatThreadRowTriage = ({<AiChatThreadTriageButtonsstatus={status}isPending={isPending}- onSnooze={() => executeInboxAction(AgentChatInboxAction.SNOOZE)}- onDone={() => executeInboxAction(AgentChatInboxAction.ARCHIVE)}- onReopen={() => executeInboxAction(AgentChatInboxAction.MOVE_TO_INBOX)}+ onSnooze={() => moveToStatus('snoozed')}+ onDone={() => moveToStatus('done')}+ onReopen={() => moveToStatus('open')}/>);};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatThreadStatusField.tsx b/packages/twenty-front/src/modules/ai/components/AiChatThreadStatusField.tsxindex 100fb03cc35..85df517917e 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatThreadStatusField.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatThreadStatusField.tsx@@ -15,6 +15,7 @@ import { themeCssVariables } from 'twenty-ui/theme';import { AI_CHAT_THREAD_DETAILS_LABEL_WIDTH_IN_PX } from '@/ai/constants/AiChatThreadDetailsLabelWidthInPx';import { type AiChatThreadStatusScope } from '@/ai/types/AiChatThreadStatusScope';+import { type AiChatThreadTriageStatus } from '@/ai/types/AiChatThreadTriageStatus';const StyledScope = styled.span`color: ${themeCssVariables.font.color.tertiary};@@ -22,11 +23,11 @@ const StyledScope = styled.span``;type AiChatThreadStatusFieldProps = {- status: 'open' | 'snoozed' | 'done';+ status: AiChatThreadTriageStatus;scope: AiChatThreadStatusScope;isSaving?: boolean;onStatusChange?: (change: {- status: AiChatThreadStatusFieldProps['status'];+ status: AiChatThreadTriageStatus;scope: AiChatThreadStatusScope;}) => void;};diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatThreadDetailsStatus.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatThreadDetailsStatus.stories.tsxnew file mode 100644index 00000000000..2fa97b29a4e--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatThreadDetailsStatus.stories.tsx@@ -0,0 +1,503 @@+import { styled } from '@linaria/react';+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { graphql, HttpResponse } from 'msw';+import { MemoryRouter } from 'react-router-dom';+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';+import { SidePanelPages } from 'twenty-shared/types';+import { assertIsDefinedOrThrow } from 'twenty-shared/utils';+import { ComponentDecorator } from 'twenty-ui/testing';+import { themeCssVariables } from 'twenty-ui/theme';++import { AiChatThreadDetailsStatus } from '@/ai/components/AiChatThreadDetailsStatus';+import { agentChatChannelViewState } from '@/ai/states/agentChatChannelViewState';+import { agentChatChannelsState } from '@/ai/states/agentChatChannelsState';+import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';+import { setAgentChatThreadPermissions } from '@/ai/testing/setAgentChatThreadPermissions';+import { type AgentChatChannel } from '@/ai/types/AgentChatChannel';+import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';+import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';+import { recordStoreFamilyState } from '@/object-record/record-store/states/recordStoreFamilyState';+import { isSnoozeAiChatForChannelComponentState } from '@/side-panel/pages/snooze-ai-chat/states/isSnoozeAiChatForChannelComponentState';+import { snoozeAiChatThreadIdsComponentState } from '@/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdsComponentState';+import { sidePanelNavigationStackState } from '@/side-panel/states/sidePanelNavigationStackState';+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';+import {+ AgentChatChannelAssignmentFilter,+ AgentChatChannelThreadStatus,+ AgentChatInboxAction,+ type AgentChatThreadParticipantFieldsFragment,+ FeatureFlagKey,+ PermissionFlagType,+} from '~/generated-metadata/graphql';+import { MemoryRouterAppNavigatorProvider } from '~/testing/components/MemoryRouterAppNavigatorProvider';+import { RootDecorator } from '~/testing/decorators/RootDecorator';+import { ToastDecorator } from '~/testing/decorators/ToastDecorator';+import { graphqlMocks } from '~/testing/graphqlMocks';+import {+ mockCurrentWorkspace,+ mockedUserData,+ mockedWorkspaceMemberData,+} from '~/testing/mock-data/users';++const THREAD_ID = '20202020-0000-4000-8000-000000000001';+const CHANNEL_ID = '20202020-0000-4000-8000-000000000002';+const FILED_AT = '2020-01-02T00:00:00.000Z';+const ACTIVITY_AT = '2020-01-01T00:00:00.000Z';+const PERSONAL_STATUS_LABEL = 'Change status in Your inbox';+const CHANNEL_STATUS_LABEL = 'Change status in Sales';++const CHANNEL: AgentChatChannel = {+ id: CHANNEL_ID,+ name: 'Sales',+ icon: 'IconHash',+ color: 'green',+ isAccessible: true,+ applicationId: 'workspace-custom-application-id',+ position: 1,+ roleIds: [],+};++const PARTICIPANT: AgentChatThreadParticipantFieldsFragment = {+ __typename: 'AgentChatThreadParticipant',+ id: '20202020-0000-4000-8000-000000000003',+ threadId: THREAD_ID,+ lastReadAt: ACTIVITY_AT,+ archivedAt: null,+ snoozedUntil: null,+ isSubscribed: true,+ lastMentionedAt: null,+ updatedAt: ACTIVITY_AT,+};++const onPersonalAction = fn();+const onChannelDone = fn();+const onChannelReopen = fn();++const StyledDetails = styled.dl`+ background: ${themeCssVariables.background.primary};+ border: 1px solid ${themeCssVariables.border.color.medium};+ border-radius: ${themeCssVariables.border.radius.md};+ margin: 0;+ padding: ${themeCssVariables.spacing[2]};+ width: 100%;+`;++type StatusScenario = {+ hasChannel?: boolean;+ isChannelView?: boolean;+ isReadOnly?: boolean;+ areParticipantsLoading?: boolean;+ isNotInPersonalInbox?: boolean;+ areChannelsLoading?: boolean;+ isChannelInaccessible?: boolean;+ isDeleted?: boolean;+ isMissing?: boolean;+ hasReadAccess?: boolean;+ isInboxEnabled?: boolean;+ hasAiPermission?: boolean;+};++const changeStatus = async ({+ canvasElement,+ label,+ status,+}: {+ canvasElement: HTMLElement;+ label: string;+ status: 'Open' | 'Snoozed' | 'Done';+}) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const trigger = await canvas.findByRole('button', { name: label });++ await waitFor(() => expect(trigger).toBeEnabled());+ await userEvent.click(trigger);+ await userEvent.click(+ await body.findByRole('menuitemradio', { name: status }),+ );+};++const expectStatusHidden = async ({+ canvasElement,+}: {+ canvasElement: HTMLElement;+}) => {+ await expect(+ within(canvasElement).queryByText('Status'),+ ).not.toBeInTheDocument();+};++const checkSnoozeScope = async ({+ canvasElement,+ isInChannel,+}: {+ canvasElement: HTMLElement;+ isInChannel: boolean;+}) => {+ await changeStatus({+ canvasElement,+ label: isInChannel ? CHANNEL_STATUS_LABEL : PERSONAL_STATUS_LABEL,+ status: 'Snoozed',+ });++ const snoozePage = jotaiStore+ .get(sidePanelNavigationStackState.atom)+ .find(({ page }) => page === SidePanelPages.SnoozeAiChat);++ assertIsDefinedOrThrow(snoozePage);+ await expect(+ jotaiStore.get(+ snoozeAiChatThreadIdsComponentState.atomFamily({+ instanceId: snoozePage.pageId,+ }),+ ),+ ).toEqual([THREAD_ID]);++ await expect(+ jotaiStore.get(+ isSnoozeAiChatForChannelComponentState.atomFamily({+ instanceId: snoozePage.pageId,+ }),+ ),+ ).toBe(isInChannel);+ await expect(onPersonalAction).not.toHaveBeenCalled();+ await expect(onChannelDone).not.toHaveBeenCalled();+};++const DEFAULT_SCENARIO: StatusScenario = {};++const getScenarioParticipants = (+ scenario: Pick<+ StatusScenario,+ 'areParticipantsLoading' | 'isNotInPersonalInbox'+ >,+): Record<string, AgentChatThreadParticipantFieldsFragment> | null => {+ if (scenario.areParticipantsLoading) {+ return null;+ }++ if (scenario.isNotInPersonalInbox) {+ return {};+ }++ return { [THREAD_ID]: PARTICIPANT };+};++const seedStatusScenario = (scenario: StatusScenario) => {+ jotaiStore.set(currentWorkspaceState.atom, {+ ...mockCurrentWorkspace,+ featureFlags: [+ {+ key: FeatureFlagKey.IS_AI_CHAT_INBOX_ENABLED,+ value: scenario.isInboxEnabled ?? true,+ },+ ],+ });+ jotaiStore.set(currentWorkspaceMemberState.atom, mockedWorkspaceMemberData);+ jotaiStore.set(currentUserWorkspaceState.atom, {+ ...mockedUserData.currentUserWorkspace,+ permissionFlags:+ (scenario.hasAiPermission ?? true) ? [PermissionFlagType.AI] : [],+ });+ setAgentChatThreadPermissions(jotaiStore, THREAD_ID, {+ canRead: scenario.hasReadAccess ?? true,+ canUpdate: !scenario.isReadOnly,+ canDelete: false,+ canSoftDelete: false,+ });+ jotaiStore.set(+ recordStoreFamilyState.atomFamily(THREAD_ID),+ scenario.isMissing+ ? null+ : {+ __typename: 'AgentChatThread',+ id: THREAD_ID,+ title: 'Pricing questions',+ createdAt: ACTIVITY_AT,+ updatedAt: ACTIVITY_AT,+ lastActivityAt: ACTIVITY_AT,+ deletedAt: scenario.isDeleted ? FILED_AT : null,+ channelId: (scenario.hasChannel ?? true) ? CHANNEL_ID : null,+ channelArchivedAt: FILED_AT,+ channelSnoozedUntil: null,+ },+ );+ jotaiStore.set(+ agentChatChannelsState.atom,+ scenario.areChannelsLoading+ ? null+ : [{ ...CHANNEL, isAccessible: !scenario.isChannelInaccessible }],+ );+ jotaiStore.set(+ agentChatThreadParticipantsState.atom,+ getScenarioParticipants(scenario),+ );+ jotaiStore.set(+ agentChatChannelViewState.atom,+ scenario.isChannelView+ ? {+ channelId: CHANNEL_ID,+ channelStatus: AgentChatChannelThreadStatus.OPEN,+ assignment: AgentChatChannelAssignmentFilter.ANY,+ }+ : null,+ );+};++const meta = {+ title: 'Modules/AI/AiChatThreadDetailsStatus',+ component: AiChatThreadDetailsStatus,+ decorators: [+ (Story, { parameters }) => (+ <MemoryRouter initialEntries={[parameters.path ?? '/inbox']}>+ <MemoryRouterAppNavigatorProvider>+ <StyledDetails>+ <Story />+ </StyledDetails>+ </MemoryRouterAppNavigatorProvider>+ </MemoryRouter>+ ),+ ToastDecorator,+ RootDecorator,+ ComponentDecorator,+ ],+ args: { threadId: THREAD_ID, dropdownId: 'details-status-story' },+ beforeEach: ({ parameters }) => {+ const unsubscribeFromCurrentUserWorkspace = jotaiStore.sub(+ currentUserWorkspaceState.atom,+ () => undefined,+ );++ seedStatusScenario(parameters.statusScenario ?? DEFAULT_SCENARIO);+ onPersonalAction.mockClear();+ onChannelDone.mockClear();+ onChannelReopen.mockClear();++ return unsubscribeFromCurrentUserWorkspace;+ },+ parameters: {+ container: { width: 400, height: 240 },+ msw: {+ handlers: [+ graphql.mutation('UpdateAgentChatThreadInboxState', ({ variables }) => {+ onPersonalAction(variables);++ return HttpResponse.json({+ data: {+ updateAgentChatThreadInboxState: [+ jotaiStore.get(agentChatThreadParticipantsState.atom)?.[+ THREAD_ID+ ] ?? PARTICIPANT,+ ],+ },+ });+ }),+ graphql.mutation(+ 'MarkAgentChatThreadAsDoneInChannel',+ ({ variables }) => {+ onChannelDone(variables);++ return HttpResponse.json({+ data: { markAgentChatThreadAsDoneInChannel: true },+ });+ },+ ),+ graphql.mutation('ReopenAgentChatThreadInChannel', ({ variables }) => {+ onChannelReopen(variables);++ return HttpResponse.json({+ data: { reopenAgentChatThreadInChannel: true },+ });+ }),+ ...graphqlMocks.handlers,+ ],+ },+ },+} satisfies Meta<typeof AiChatThreadDetailsStatus>;++export default meta;+type Story = StoryObj<typeof meta>;++export const PersonalInbox: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(await canvas.findByText('Open')).toBeVisible();+ await changeStatus({+ canvasElement,+ label: PERSONAL_STATUS_LABEL,+ status: 'Open',+ });+ await changeStatus({+ canvasElement,+ label: PERSONAL_STATUS_LABEL,+ status: 'Done',+ });+ await waitFor(() => expect(onPersonalAction).toHaveBeenCalledTimes(1));+ await expect(onPersonalAction).toHaveBeenLastCalledWith({+ threadIds: [THREAD_ID],+ action: AgentChatInboxAction.ARCHIVE,+ });+ await expect(canvas.getByText('Done')).toBeVisible();+ await changeStatus({+ canvasElement,+ label: PERSONAL_STATUS_LABEL,+ status: 'Open',+ });+ await waitFor(() => expect(onPersonalAction).toHaveBeenCalledTimes(2));+ await expect(onPersonalAction).toHaveBeenLastCalledWith({+ threadIds: [THREAD_ID],+ action: AgentChatInboxAction.MOVE_TO_INBOX,+ });+ await expect(canvas.getByText('Open')).toBeVisible();+ await expect(+ jotaiStore.get(recordStoreFamilyState.atomFamily(THREAD_ID))+ ?.channelArchivedAt,+ ).toBe(FILED_AT);+ await expect(onChannelDone).not.toHaveBeenCalled();+ await expect(onChannelReopen).not.toHaveBeenCalled();+ },+};++export const ChannelInbox: Story = {+ parameters: { statusScenario: { isChannelView: true } },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(await canvas.findByText('Done')).toBeVisible();+ await changeStatus({+ canvasElement,+ label: CHANNEL_STATUS_LABEL,+ status: 'Done',+ });+ await changeStatus({+ canvasElement,+ label: CHANNEL_STATUS_LABEL,+ status: 'Open',+ });+ await waitFor(() => expect(onChannelReopen).toHaveBeenCalledTimes(1));+ await expect(onChannelReopen).toHaveBeenCalledWith({ threadId: THREAD_ID });+ await expect(onChannelDone).not.toHaveBeenCalled();+ await expect(canvas.getByText('Open')).toBeVisible();+ await changeStatus({+ canvasElement,+ label: CHANNEL_STATUS_LABEL,+ status: 'Done',+ });+ await waitFor(() => expect(onChannelDone).toHaveBeenCalledTimes(1));+ await expect(onChannelDone).toHaveBeenCalledWith({ threadId: THREAD_ID });+ await expect(canvas.getByText('Done')).toBeVisible();+ await expect(onPersonalAction).not.toHaveBeenCalled();+ },+};++export const StandaloneChannel: Story = {+ ...ChannelInbox,+ parameters: { path: '/chat', statusScenario: { isChannelView: false } },+};++export const StandalonePersonal: Story = {+ ...PersonalInbox,+ parameters: { path: '/chat', statusScenario: { hasChannel: false } },+};++export const ReadOnlyChannel: Story = {+ parameters: {+ statusScenario: { isChannelView: true, isReadOnly: true },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(await canvas.findByText('Done')).toBeVisible();+ await expect(canvas.getByText('Sales')).toBeVisible();+ await expect(canvas.queryByRole('button')).not.toBeInTheDocument();+ },+};++export const ReadOnlyPersonal: Story = {+ ...PersonalInbox,+ parameters: { statusScenario: { isReadOnly: true } },+};++export const ChannelWhileParticipantsLoad: Story = {+ parameters: {+ path: '/chat',+ statusScenario: { areParticipantsLoading: true },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(await canvas.findByText('Done')).toBeVisible();+ await expect(+ canvas.getByRole('button', { name: CHANNEL_STATUS_LABEL }),+ ).toBeEnabled();+ },+};++export const InaccessibleChannel: Story = {+ parameters: {+ path: '/chat',+ statusScenario: { isChannelInaccessible: true },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(+ await canvas.findByRole('button', { name: PERSONAL_STATUS_LABEL }),+ ).toBeEnabled();+ await expect(canvas.getByText('Open')).toBeVisible();+ await expect(canvas.queryByText('Sales')).not.toBeInTheDocument();+ },+};++export const PersonalSnooze: Story = {+ play: async ({ canvasElement }) =>+ checkSnoozeScope({ canvasElement, isInChannel: false }),+};++export const ChannelSnooze: Story = {+ parameters: { statusScenario: { isChannelView: true } },+ play: async ({ canvasElement }) =>+ checkSnoozeScope({ canvasElement, isInChannel: true }),+};++export const ChannelsLoading: Story = {+ parameters: { path: '/chat', statusScenario: { areChannelsLoading: true } },+ play: expectStatusHidden,+};++export const ParticipantsLoading: Story = {+ parameters: { statusScenario: { areParticipantsLoading: true } },+ play: expectStatusHidden,+};++export const OutsidePersonalInbox: Story = {+ parameters: { statusScenario: { isNotInPersonalInbox: true } },+ play: expectStatusHidden,+};++export const Deleted: Story = {+ parameters: { statusScenario: { isDeleted: true } },+ play: expectStatusHidden,+};++export const Missing: Story = {+ parameters: { statusScenario: { isMissing: true } },+ play: expectStatusHidden,+};++export const AccessRevoked: Story = {+ parameters: { statusScenario: { hasReadAccess: false } },+ play: expectStatusHidden,+};++export const InboxDisabled: Story = {+ parameters: { statusScenario: { isInboxEnabled: false } },+ play: expectStatusHidden,+};++export const WithoutAiPermission: Story = {+ parameters: { statusScenario: { hasAiPermission: false } },+ play: expectStatusHidden,+};diff --git a/packages/twenty-front/src/modules/ai/constants/AiChatThreadInboxActionByTriageStatus.ts b/packages/twenty-front/src/modules/ai/constants/AiChatThreadInboxActionByTriageStatus.tsnew file mode 100644index 00000000000..0803df1cf1f--- /dev/null+++ b/packages/twenty-front/src/modules/ai/constants/AiChatThreadInboxActionByTriageStatus.ts@@ -0,0 +1,11 @@+import { type AiChatThreadTriageStatus } from '@/ai/types/AiChatThreadTriageStatus';+import { AgentChatInboxAction } from '~/generated-metadata/graphql';++export const AI_CHAT_THREAD_INBOX_ACTION_BY_TRIAGE_STATUS: Record<+ AiChatThreadTriageStatus,+ AgentChatInboxAction+> = {+ open: AgentChatInboxAction.MOVE_TO_INBOX,+ snoozed: AgentChatInboxAction.SNOOZE,+ done: AgentChatInboxAction.ARCHIVE,+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadDetailsStatus.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadDetailsStatus.tsnew file mode 100644index 00000000000..045606271e0--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadDetailsStatus.ts@@ -0,0 +1,66 @@+import { AI_CHAT_THREAD_INBOX_ACTION_BY_TRIAGE_STATUS } from '@/ai/constants/AiChatThreadInboxActionByTriageStatus';+import { useAiChatThreadTriage } from '@/ai/hooks/useAiChatThreadTriage';+import { useExecuteAgentChatThreadInboxAction } from '@/ai/hooks/useExecuteAgentChatThreadInboxAction';+import { agentChatChannelsState } from '@/ai/states/agentChatChannelsState';+import { agentChatThreadPermissionsFamilySelector } from '@/ai/states/selectors/agentChatThreadPermissionsFamilySelector';+import { agentChatThreadRecordFamilySelector } from '@/ai/states/selectors/agentChatThreadRecordFamilySelector';+import { type AiChatThreadTriageStatus } from '@/ai/types/AiChatThreadTriageStatus';+import { getAiChatThreadChannelIdOutsideInbox } from '@/ai/utils/getAiChatThreadChannelIdOutsideInbox';+import { getAiChatThreadDetailsStatusAccess } from '@/ai/utils/getAiChatThreadDetailsStatusAccess';+import { getAiChatThreadStatusScope } from '@/ai/utils/getAiChatThreadStatusScope';+import { isAiChatThreadStatusChangeNoOp } from '@/ai/utils/isAiChatThreadStatusChangeNoOp';+import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';++export const useAiChatThreadDetailsStatus = (threadId: string) => {+ const thread = useAtomFamilySelectorValue(+ agentChatThreadRecordFamilySelector,+ threadId,+ );+ const permissions = useAtomFamilySelectorValue(+ agentChatThreadPermissionsFamilySelector,+ threadId,+ );+ const agentChatChannels = useAtomStateValue(agentChatChannelsState);+ const {+ status: triageStatus,+ isInChannel,+ channelId,+ } = useAiChatThreadTriage({+ threadId,+ channelIdOutsideInbox: getAiChatThreadChannelIdOutsideInbox({+ threadChannelId: thread?.channelId,+ channels: agentChatChannels,+ }),+ });+ const scope = getAiChatThreadStatusScope({+ isInChannel,+ channel: agentChatChannels?.find(({ id }) => id === channelId),+ });+ const { status, canChangeStatus } = getAiChatThreadDetailsStatusAccess({+ thread,+ permissions,+ triageStatus,+ scope,+ isInChannel,+ });+ const { executeAgentChatThreadInboxAction, isPending } =+ useExecuteAgentChatThreadInboxAction();++ const changeStatus = (nextStatus: AiChatThreadTriageStatus) => {+ if (+ !canChangeStatus ||+ isAiChatThreadStatusChangeNoOp({ currentStatus: status, nextStatus })+ ) {+ return;+ }++ void executeAgentChatThreadInboxAction({+ threadIds: [threadId],+ action: AI_CHAT_THREAD_INBOX_ACTION_BY_TRIAGE_STATUS[nextStatus],+ isInChannel,+ });+ };++ return { status, scope, canChangeStatus, isPending, changeStatus };+};diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadTriage.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadTriage.tsindex e4c757888b0..a0baf5368c7 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadTriage.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadTriage.ts@@ -15,7 +15,13 @@ import {} from '~/generated-metadata/graphql';import { isAiChatInboxPath } from '~/utils/isAiChatInboxPath';-export const useAiChatThreadTriage = (threadId: string) => {+export const useAiChatThreadTriage = ({+ threadId,+ channelIdOutsideInbox,+}: {+ threadId: string;+ channelIdOutsideInbox?: string | null;+}) => {const hasAiPermission = useHasPermissionFlag(PermissionFlagType.AI);const isInboxEnabled = useIsFeatureEnabled(FeatureFlagKey.IS_AI_CHAT_INBOX_ENABLED,@@ -27,23 +33,24 @@ export const useAiChatThreadTriage = (threadId: string) => {const agentChatShownChannelView = useAtomStateValue(agentChatShownChannelViewSelector,);+ const channelId = isAiChatInboxPath(location.pathname)+ ? (agentChatShownChannelView?.channelId ?? null)+ : (channelIdOutsideInbox ?? null);const { [threadId]: inboxStatus } = useAtomFamilySelectorValue(agentChatThreadInboxStatusByThreadIdFamilySelector,- {- threadIds: [threadId],- channelId: isAiChatInboxPath(location.pathname)- ? (agentChatShownChannelView?.channelId ?? null)- : null,- },+ { threadIds: [threadId], channelId },);+ const isInChannel = inboxStatus?.isChannelCopy ?? false;return {status: getAiChatThreadTriageStatus({hasAiPermission,isInboxEnabled,- areParticipantsLoaded: isDefined(agentChatThreadParticipants),+ areParticipantsLoaded:+ isInChannel || isDefined(agentChatThreadParticipants),scope: inboxStatus?.scope ?? 'NONE',}),- isInChannel: inboxStatus?.isChannelCopy ?? false,+ isInChannel,+ channelId,};};diff --git a/packages/twenty-front/src/modules/ai/types/AiChatThreadTriageStatus.ts b/packages/twenty-front/src/modules/ai/types/AiChatThreadTriageStatus.tsnew file mode 100644index 00000000000..5362b78950d--- /dev/null+++ b/packages/twenty-front/src/modules/ai/types/AiChatThreadTriageStatus.ts@@ -0,0 +1 @@+export type AiChatThreadTriageStatus = 'open' | 'snoozed' | 'done';diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatThreadChannelIdOutsideInbox.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatThreadChannelIdOutsideInbox.tsnew file mode 100644index 00000000000..5a828571be7--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatThreadChannelIdOutsideInbox.ts@@ -0,0 +1,25 @@+import { isDefined } from 'twenty-shared/utils';++import { type AgentChatChannel } from '@/ai/types/AgentChatChannel';++export const getAiChatThreadChannelIdOutsideInbox = ({+ threadChannelId,+ channels,+}: {+ threadChannelId: string | null | undefined;+ channels: AgentChatChannel[] | null;+}) => {+ if (!isDefined(threadChannelId)) {+ return null;+ }++ if (!isDefined(channels)) {+ return threadChannelId;+ }++ const isThreadChannelAccessible = channels.some(+ ({ id, isAccessible }) => isAccessible && id === threadChannelId,+ );++ return isThreadChannelAccessible ? threadChannelId : null;+};diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatThreadDetailsStatusAccess.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatThreadDetailsStatusAccess.tsnew file mode 100644index 00000000000..08b6ce75be2--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatThreadDetailsStatusAccess.ts@@ -0,0 +1,35 @@+import { isDefined } from 'twenty-shared/utils';++import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { type AiChatThreadStatusScope } from '@/ai/types/AiChatThreadStatusScope';+import { type AiChatThreadTriageStatus } from '@/ai/types/AiChatThreadTriageStatus';+import { type RecordPermissionsDto } from '~/generated-metadata/graphql';++export const getAiChatThreadDetailsStatusAccess = ({+ thread,+ permissions,+ triageStatus,+ scope,+ isInChannel,+}: {+ thread: Pick<AgentChatThreadRecord, 'deletedAt'> | null;+ permissions: Pick<RecordPermissionsDto, 'canRead' | 'canUpdate'> | undefined;+ triageStatus: AiChatThreadTriageStatus | undefined;+ scope: AiChatThreadStatusScope | undefined;+ isInChannel: boolean;+}) => {+ const isThreadAvailable =+ isDefined(thread) &&+ !isDefined(thread.deletedAt) &&+ (permissions?.canRead ?? false);++ if (!isThreadAvailable || !isDefined(triageStatus)) {+ return { status: undefined, canChangeStatus: false };+ }++ return {+ status: triageStatus,+ canChangeStatus:+ isDefined(scope) && (!isInChannel || (permissions?.canUpdate ?? false)),+ };+};diff --git a/packages/twenty-front/src/modules/ai/utils/getAiChatThreadStatusScope.ts b/packages/twenty-front/src/modules/ai/utils/getAiChatThreadStatusScope.tsnew file mode 100644index 00000000000..dc4245db9ad--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getAiChatThreadStatusScope.ts@@ -0,0 +1,22 @@+import { isDefined } from 'twenty-shared/utils';++import { type AgentChatChannel } from '@/ai/types/AgentChatChannel';+import { type AiChatThreadStatusScope } from '@/ai/types/AiChatThreadStatusScope';++export const getAiChatThreadStatusScope = ({+ isInChannel,+ channel,+}: {+ isInChannel: boolean;+ channel: AgentChatChannel | undefined;+}): AiChatThreadStatusScope | undefined => {+ if (!isInChannel) {+ return { type: 'personal' };+ }++ if (!isDefined(channel)) {+ return undefined;+ }++ return { type: 'channel', channelId: channel.id, channelName: channel.name };+};diff --git a/packages/twenty-front/src/modules/ai/utils/isAiChatThreadStatusChangeNoOp.ts b/packages/twenty-front/src/modules/ai/utils/isAiChatThreadStatusChangeNoOp.tsnew file mode 100644index 00000000000..9eeb72e5d04--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/isAiChatThreadStatusChangeNoOp.ts@@ -0,0 +1,9 @@+import { type AiChatThreadTriageStatus } from '@/ai/types/AiChatThreadTriageStatus';++export const isAiChatThreadStatusChangeNoOp = ({+ currentStatus,+ nextStatus,+}: {+ currentStatus: AiChatThreadTriageStatus | undefined;+ nextStatus: AiChatThreadTriageStatus;+}) => nextStatus === currentStatus && nextStatus !== 'snoozed';