The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(admin-panel): drop the admin panel global AI chats list (#27920)
Etienne45f48dc695ac
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.tsindex e91421b2b30..24bd2707263 100644--- a/packages/twenty-front/src/generated-admin/graphql.ts+++ b/packages/twenty-front/src/generated-admin/graphql.ts@@ -81,51 +81,12 @@ export type AdminChatMessagePart = {type: Scalars['String']['output'];};-export type AdminChatThreadListItem = {- __typename?: 'AdminChatThreadListItem';- createdAt: Scalars['DateTime']['output'];- deletedAt?: Maybe<Scalars['DateTime']['output']>;- hasError: Scalars['Boolean']['output'];- id: Scalars['UUID']['output'];- isOnboardingThread: Scalars['Boolean']['output'];- messageCount: Scalars['Int']['output'];- title?: Maybe<Scalars['String']['output']>;- updatedAt: Scalars['DateTime']['output'];- userEmail?: Maybe<Scalars['String']['output']>;- userFirstName?: Maybe<Scalars['String']['output']>;- userLastName?: Maybe<Scalars['String']['output']>;- userReplyCount: Scalars['Int']['output'];- userWorkspaceId?: Maybe<Scalars['UUID']['output']>;- workspaceDisplayName?: Maybe<Scalars['String']['output']>;- workspaceId: Scalars['UUID']['output'];-};-export type AdminChatThreadMessages = {__typename?: 'AdminChatThreadMessages';messages: Array<AdminChatMessage>;thread: AdminWorkspaceChatThread;};-/** Scope of chat threads to list in the admin panel */-export enum AdminChatThreadScope {- ALL = 'ALL',- ONBOARDING = 'ONBOARDING'-}--/** Direction to sort admin chat threads */-export enum AdminChatThreadSortDirection {- ASC = 'ASC',- DESC = 'DESC'-}--/** Field to sort admin chat threads by */-export enum AdminChatThreadSortField {- CREATED_AT = 'CREATED_AT',- MESSAGE_COUNT = 'MESSAGE_COUNT',- REPLY_COUNT = 'REPLY_COUNT',- UPDATED_AT = 'UPDATED_AT'-}-export type AdminPanelHealthServiceData = {__typename?: 'AdminPanelHealthServiceData';description: Scalars['String']['output'];@@ -776,13 +737,6 @@ export type MutationUpdateWorkspaceUsageLimitArgs = {workspaceId: Scalars['UUID']['input'];};-export type PaginatedAdminChatThreads = {- __typename?: 'PaginatedAdminChatThreads';- hasMore: Scalars['Boolean']['output'];- threads: Array<AdminChatThreadListItem>;- totalCount: Scalars['Int']['output'];-};-export type PaginatedApplicationRegistrations = {__typename?: 'PaginatedApplicationRegistrations';hasMore: Scalars['Boolean']['output'];@@ -803,7 +757,6 @@ export type Query = {getAdminAiModels: AdminAiModels;getAdminAiUsageByWorkspace: Array<UsageBreakdownItem>;getAdminChatThreadMessages: AdminChatThreadMessages;- getAdminChatThreads: PaginatedAdminChatThreads;getAdminWorkspaceChatThreads: Array<AdminWorkspaceChatThread>;getAiProviders: Scalars['JSON']['output'];getConfigVariablesGrouped: ConfigVariables;@@ -886,18 +839,6 @@ export type QueryGetAdminChatThreadMessagesArgs = {};-export type QueryGetAdminChatThreadsArgs = {- hasErrorOnly?: InputMaybe<Scalars['Boolean']['input']>;- limit?: InputMaybe<Scalars['Int']['input']>;- offset?: InputMaybe<Scalars['Int']['input']>;- scope?: InputMaybe<AdminChatThreadScope>;- searchTerm?: InputMaybe<Scalars['String']['input']>;- sortBy?: InputMaybe<AdminChatThreadSortField>;- sortDirection?: InputMaybe<AdminChatThreadSortDirection>;- userNeverEngagedOnly?: InputMaybe<Scalars['Boolean']['input']>;-};--export type QueryGetAdminWorkspaceChatThreadsArgs = {workspaceId: Scalars['UUID']['input'];};@@ -1529,20 +1470,6 @@ export type GetAdminChatThreadMessagesQueryVariables = Exact<{export type GetAdminChatThreadMessagesQuery = { __typename?: 'Query', getAdminChatThreadMessages: { __typename?: 'AdminChatThreadMessages', thread: { __typename?: 'AdminWorkspaceChatThread', id: string, title?: string | null, totalInputTokens: number, totalOutputTokens: number, conversationSize: number, messageCount: number, createdAt: string, updatedAt: string }, messages: Array<{ __typename?: 'AdminChatMessage', id: string, role: AgentMessageRole, createdAt: string, parts: Array<{ __typename?: 'AdminChatMessagePart', type: string, orderIndex: number, textContent?: string | null, reasoningContent?: string | null, toolName?: string | null, toolCallId?: string | null, toolInput?: any | null, toolOutput?: any | null, state?: string | null, errorMessage?: string | null }> }> } };-export type GetAdminChatThreadsQueryVariables = Exact<{- scope?: InputMaybe<AdminChatThreadScope>;- hasErrorOnly?: InputMaybe<Scalars['Boolean']['input']>;- userNeverEngagedOnly?: InputMaybe<Scalars['Boolean']['input']>;- searchTerm?: InputMaybe<Scalars['String']['input']>;- sortBy?: InputMaybe<AdminChatThreadSortField>;- sortDirection?: InputMaybe<AdminChatThreadSortDirection>;- limit?: InputMaybe<Scalars['Int']['input']>;- offset?: InputMaybe<Scalars['Int']['input']>;-}>;---export type GetAdminChatThreadsQuery = { __typename?: 'Query', getAdminChatThreads: { __typename?: 'PaginatedAdminChatThreads', totalCount: number, hasMore: boolean, threads: Array<{ __typename?: 'AdminChatThreadListItem', id: string, title?: string | null, workspaceId: string, workspaceDisplayName?: string | null, userWorkspaceId?: string | null, userEmail?: string | null, userFirstName?: string | null, userLastName?: string | null, messageCount: number, userReplyCount: number, hasError: boolean, isOnboardingThread: boolean, deletedAt?: string | null, createdAt: string, updatedAt: string }> } };-export type GetAdminWorkspaceChatThreadsQueryVariables = Exact<{workspaceId: Scalars['UUID']['input'];}>;@@ -1724,7 +1651,6 @@ export const AdminPanelRecentUsersDocument = {"kind":"Document","definitions":[{export const AdminPanelTopWorkspacesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"AdminPanelTopWorkspaces"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"searchTerm"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"adminPanelTopWorkspaces"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"searchTerm"},"value":{"kind":"Variable","name":{"kind":"Name","value":"searchTerm"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"totalUsers"}},{"kind":"Field","name":{"kind":"Name","value":"subdomain"}}]}}]}}]} as unknown as DocumentNode<AdminPanelTopWorkspacesQuery, AdminPanelTopWorkspacesQueryVariables>;export const FindOneAdminApplicationRegistrationDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneAdminApplicationRegistration"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findOneAdminApplicationRegistration"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ApplicationRegistrationFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ApplicationRegistrationFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ApplicationRegistration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"galleryImagesUrls"}},{"kind":"Field","name":{"kind":"Name","value":"oAuthClientId"}},{"kind":"Field","name":{"kind":"Name","value":"oAuthRedirectUris"}},{"kind":"Field","name":{"kind":"Name","value":"oAuthScopes"}},{"kind":"Field","name":{"kind":"Name","value":"sourceType"}},{"kind":"Field","name":{"kind":"Name","value":"sourcePackage"}},{"kind":"Field","name":{"kind":"Name","value":"latestAvailableVersion"}},{"kind":"Field","name":{"kind":"Name","value":"isListed"}},{"kind":"Field","name":{"kind":"Name","value":"isVetted"}},{"kind":"Field","name":{"kind":"Name","value":"isPreInstalled"}},{"kind":"Field","name":{"kind":"Name","value":"isConfigured"}},{"kind":"Field","name":{"kind":"Name","value":"ownerWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<FindOneAdminApplicationRegistrationQuery, FindOneAdminApplicationRegistrationQueryVariables>;export const GetAdminChatThreadMessagesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAdminChatThreadMessages"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAdminChatThreadMessages"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}},{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"thread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"conversationSize"}},{"kind":"Field","name":{"kind":"Name","value":"messageCount"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"messages"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"parts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"orderIndex"}},{"kind":"Field","name":{"kind":"Name","value":"textContent"}},{"kind":"Field","name":{"kind":"Name","value":"reasoningContent"}},{"kind":"Field","name":{"kind":"Name","value":"toolName"}},{"kind":"Field","name":{"kind":"Name","value":"toolCallId"}},{"kind":"Field","name":{"kind":"Name","value":"toolInput"}},{"kind":"Field","name":{"kind":"Name","value":"toolOutput"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}}]}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}}]}}]} as unknown as DocumentNode<GetAdminChatThreadMessagesQuery, GetAdminChatThreadMessagesQueryVariables>;-export const GetAdminChatThreadsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAdminChatThreads"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"scope"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"AdminChatThreadScope"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"hasErrorOnly"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userNeverEngagedOnly"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"searchTerm"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"sortBy"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"AdminChatThreadSortField"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"sortDirection"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"AdminChatThreadSortDirection"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"limit"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"offset"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAdminChatThreads"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"scope"},"value":{"kind":"Variable","name":{"kind":"Name","value":"scope"}}},{"kind":"Argument","name":{"kind":"Name","value":"hasErrorOnly"},"value":{"kind":"Variable","name":{"kind":"Name","value":"hasErrorOnly"}}},{"kind":"Argument","name":{"kind":"Name","value":"userNeverEngagedOnly"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userNeverEngagedOnly"}}},{"kind":"Argument","name":{"kind":"Name","value":"searchTerm"},"value":{"kind":"Variable","name":{"kind":"Name","value":"searchTerm"}}},{"kind":"Argument","name":{"kind":"Name","value":"sortBy"},"value":{"kind":"Variable","name":{"kind":"Name","value":"sortBy"}}},{"kind":"Argument","name":{"kind":"Name","value":"sortDirection"},"value":{"kind":"Variable","name":{"kind":"Name","value":"sortDirection"}}},{"kind":"Argument","name":{"kind":"Name","value":"limit"},"value":{"kind":"Variable","name":{"kind":"Name","value":"limit"}}},{"kind":"Argument","name":{"kind":"Name","value":"offset"},"value":{"kind":"Variable","name":{"kind":"Name","value":"offset"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"totalCount"}},{"kind":"Field","name":{"kind":"Name","value":"hasMore"}},{"kind":"Field","name":{"kind":"Name","value":"threads"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceDisplayName"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"userEmail"}},{"kind":"Field","name":{"kind":"Name","value":"userFirstName"}},{"kind":"Field","name":{"kind":"Name","value":"userLastName"}},{"kind":"Field","name":{"kind":"Name","value":"messageCount"}},{"kind":"Field","name":{"kind":"Name","value":"userReplyCount"}},{"kind":"Field","name":{"kind":"Name","value":"hasError"}},{"kind":"Field","name":{"kind":"Name","value":"isOnboardingThread"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}}]} as unknown as DocumentNode<GetAdminChatThreadsQuery, GetAdminChatThreadsQueryVariables>;export const GetAdminWorkspaceChatThreadsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAdminWorkspaceChatThreads"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAdminWorkspaceChatThreads"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"conversationSize"}},{"kind":"Field","name":{"kind":"Name","value":"messageCount"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<GetAdminWorkspaceChatThreadsQuery, GetAdminWorkspaceChatThreadsQueryVariables>;export const GetServerAdminsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetServerAdmins"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getServerAdmins"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessFullAdminPanel"}},{"kind":"Field","name":{"kind":"Name","value":"canImpersonate"}}]}}]}}]} as unknown as DocumentNode<GetServerAdminsQuery, GetServerAdminsQueryVariables>;export const GetUpgradeStatusDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetUpgradeStatus"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceIds"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getUpgradeStatus"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceIds"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceIds"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"inferredVersion"}},{"kind":"Field","name":{"kind":"Name","value":"health"}},{"kind":"Field","name":{"kind":"Name","value":"latestCommand"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"executedByVersion"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}}]}}]} as unknown as DocumentNode<GetUpgradeStatusQuery, GetUpgradeStatusQueryVariables>;diff --git a/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx b/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsxindex c6f24f7471e..7ce55e956ad 100644--- a/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx+++ b/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx@@ -673,12 +673,6 @@ const SettingsAdminWorkspaceChatThread = lazy(() =>),);-const SettingsAdminChats = lazy(() =>- import('~/pages/settings/admin-panel/SettingsAdminChats').then((module) => ({- default: module.SettingsAdminChats,- })),-);-const SettingsCommunity = lazy(() =>import('~/pages/settings/community/SettingsCommunity').then((module) => ({default: module.SettingsCommunity,@@ -1220,10 +1214,6 @@ const createSettingsRouteElements = ({path={SettingsPath.AdminPanelWorkspaceChatThread}element={<SettingsAdminWorkspaceChatThread />}/>- <Route- path={SettingsPath.AdminPanelChats}- element={<SettingsAdminChats />}- /></>)}diff --git a/packages/twenty-front/src/modules/settings/admin-panel/ai/components/SettingsAdminAI.tsx b/packages/twenty-front/src/modules/settings/admin-panel/ai/components/SettingsAdminAI.tsxindex 3bbb399187c..124a5b5c974 100644--- a/packages/twenty-front/src/modules/settings/admin-panel/ai/components/SettingsAdminAI.tsx+++ b/packages/twenty-front/src/modules/settings/admin-panel/ai/components/SettingsAdminAI.tsx@@ -1,4 +1,3 @@-import { NavigationButton } from '@/ui/input/components/NavigationButton';import { useMemo, useState } from 'react';import { useToast } from 'twenty-ui/components/feedback';import { Section } from 'twenty-ui/components/layout';@@ -8,7 +7,6 @@ import { t } from '@lingui/core/macro';import { AI_MODEL_TIERS, type AiModelTier } from 'twenty-shared/ai';import { SettingsPath } from 'twenty-shared/types';import { getSettingsPath, isDefined } from 'twenty-shared/utils';-import { IconMessage } from 'twenty-ui/icon';import { Card } from 'twenty-ui/primitives/surfaces';import { themeCssVariables } from 'twenty-ui/theme';@@ -236,19 +234,6 @@ export const SettingsAdminAI = () => {</Section.Root>)}- <Section.Root>- <Section.Header- title={t`Chats`}- description={t`Browse AI chat threads across all workspaces, including onboarding chats`}- />- <NavigationButton- to={getSettingsPath(SettingsPath.AdminPanelChats)}- startIcon={<IconMessage />}- size="sm"- variant="outline"- >{t`View all chats`}</NavigationButton>- </Section.Root>-<Section.Root><Section.Headertitle={t`AI Usage by Workspace`}diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/components/SettingsAdminChatsContent.tsx b/packages/twenty-front/src/modules/settings/admin-panel/chats/components/SettingsAdminChatsContent.tsxdeleted file mode 100644index 983fded7209..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/components/SettingsAdminChatsContent.tsx+++ /dev/null@@ -1,50 +0,0 @@-import { t } from '@lingui/core/macro';-import { styled } from '@linaria/react';--import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';-import { themeCssVariables } from 'twenty-ui/theme';--import { SettingsAdminChatsTable } from '@/settings/admin-panel/chats/components/SettingsAdminChatsTable';-import { type AdminChatThreadListItem } from '@/settings/admin-panel/chats/types/AdminChatThreadListItem';-import { SettingsEmptyPlaceholder } from '@/settings/components/SettingsEmptyPlaceholder';--type SettingsAdminChatsContentProps = {- threads: AdminChatThreadListItem[];- loading: boolean;- error?: Error;-};--const StyledTableContainer = styled.div`- border-bottom: 1px solid ${themeCssVariables.border.color.light};- margin-top: ${themeCssVariables.spacing[3]};-`;--export const SettingsAdminChatsContent = ({- threads,- loading,- error,-}: SettingsAdminChatsContentProps) => {- if (isDefined(error)) {- return (- <SettingsEmptyPlaceholder>{t`Failed to load chats. Please try again.`}</SettingsEmptyPlaceholder>- );- }-- if (loading && !isNonEmptyArray(threads)) {- return (- <SettingsEmptyPlaceholder>{t`Loading chats...`}</SettingsEmptyPlaceholder>- );- }-- if (!isNonEmptyArray(threads)) {- return (- <SettingsEmptyPlaceholder>{t`No chats found`}</SettingsEmptyPlaceholder>- );- }-- return (- <StyledTableContainer>- <SettingsAdminChatsTable threads={threads} />- </StyledTableContainer>- );-};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/components/SettingsAdminChatsFilterDropdown.tsx b/packages/twenty-front/src/modules/settings/admin-panel/chats/components/SettingsAdminChatsFilterDropdown.tsxdeleted file mode 100644index b8aa155fb4e..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/components/SettingsAdminChatsFilterDropdown.tsx+++ /dev/null@@ -1,65 +0,0 @@-import { t } from '@lingui/core/macro';-import { type ReactElement } from 'react';-import { Dropdown } from 'twenty-ui/components/navigation';-import { SettingsRow } from 'twenty-ui/components/settings';--import { IconAlertTriangle, IconMessage, IconSparkles } from 'twenty-ui/icon';--import { type AdminChatsFilterState } from '@/settings/admin-panel/chats/types/AdminChatsFilterState';-import { DropdownRoot } from '@/ui/layout/dropdown/components/DropdownRoot';-import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';--type SettingsAdminChatsFilterDropdownProps = {- filterButton: ReactElement;- filters: AdminChatsFilterState;- onFiltersChange: (filters: AdminChatsFilterState) => void;-};--export const SettingsAdminChatsFilterDropdown = ({- filterButton,- filters,- onFiltersChange,-}: SettingsAdminChatsFilterDropdownProps) => {- return (- <DropdownRoot- dropdownId="settings-admin-chats-filter-dropdown"- type="panel"- >- <Dropdown.Trigger render={filterButton} />- <DropdownContent side="bottom" align="end" sideOffset={8} alignOffset={0}>- <Dropdown.Section>- <SettingsRow- startElement={<IconSparkles />}- onCheckedChange={() =>- onFiltersChange({- ...filters,- onboardingOnly: !filters.onboardingOnly,- })- }- checked={filters.onboardingOnly}- >{t`Onboarding only`}</SettingsRow>- <SettingsRow- startElement={<IconAlertTriangle />}- onCheckedChange={() =>- onFiltersChange({- ...filters,- hasErrorOnly: !filters.hasErrorOnly,- })- }- checked={filters.hasErrorOnly}- >{t`Has error`}</SettingsRow>- <SettingsRow- startElement={<IconMessage />}- onCheckedChange={() =>- onFiltersChange({- ...filters,- userNeverEngagedOnly: !filters.userNeverEngagedOnly,- })- }- checked={filters.userNeverEngagedOnly}- >{t`No user reply`}</SettingsRow>- </Dropdown.Section>- </DropdownContent>- </DropdownRoot>- );-};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/components/SettingsAdminChatsTable.tsx b/packages/twenty-front/src/modules/settings/admin-panel/chats/components/SettingsAdminChatsTable.tsxdeleted file mode 100644index 12919deb604..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/components/SettingsAdminChatsTable.tsx+++ /dev/null@@ -1,58 +0,0 @@-import { t } from '@lingui/core/macro';--import { SETTINGS_ADMIN_CHATS_TABLE_GRID } from '@/settings/admin-panel/chats/constants/SettingsAdminChatsTableGrid';-import { SETTINGS_ADMIN_CHATS_TABLE_ID } from '@/settings/admin-panel/chats/constants/SettingsAdminChatsTableId';-import { SettingsAdminChatsTableRow } from '@/settings/admin-panel/chats/components/SettingsAdminChatsTableRow';-import { type AdminChatThreadListItem } from '@/settings/admin-panel/chats/types/AdminChatThreadListItem';-import { SortableTableHeader } from '@/ui/layout/table/components/SortableTableHeader';-import { Table } from '@/ui/layout/table/components/Table';-import { TableBody } from '@/ui/layout/table/components/TableBody';-import { TableHeader } from '@/ui/layout/table/components/TableHeader';-import { TableRow } from '@/ui/layout/table/components/TableRow';-import { AdminChatThreadSortField } from '~/generated-admin/graphql';--type SettingsAdminChatsTableProps = {- threads: AdminChatThreadListItem[];-};--export const SettingsAdminChatsTable = ({- threads,-}: SettingsAdminChatsTableProps) => {- return (- <Table>- <TableRow gridAutoColumns={SETTINGS_ADMIN_CHATS_TABLE_GRID}>- <TableHeader>{t`Workspace`}</TableHeader>- <TableHeader>{t`User`}</TableHeader>- <TableHeader>{t`Title`}</TableHeader>- <SortableTableHeader- tableId={SETTINGS_ADMIN_CHATS_TABLE_ID}- fieldName={AdminChatThreadSortField.MESSAGE_COUNT}- label={t`Msgs`}- align="right"- />- <SortableTableHeader- tableId={SETTINGS_ADMIN_CHATS_TABLE_ID}- fieldName={AdminChatThreadSortField.REPLY_COUNT}- label={t`Replies`}- align="right"- />- <TableHeader>{t`Flags`}</TableHeader>- <SortableTableHeader- tableId={SETTINGS_ADMIN_CHATS_TABLE_ID}- fieldName={AdminChatThreadSortField.CREATED_AT}- label={t`Created`}- align="right"- initialSort={{- fieldName: AdminChatThreadSortField.CREATED_AT,- direction: 'desc',- }}- />- </TableRow>- <TableBody>- {threads.map((thread) => (- <SettingsAdminChatsTableRow key={thread.id} thread={thread} />- ))}- </TableBody>- </Table>- );-};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/components/SettingsAdminChatsTableRow.tsx b/packages/twenty-front/src/modules/settings/admin-panel/chats/components/SettingsAdminChatsTableRow.tsxdeleted file mode 100644index ee75f766294..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/components/SettingsAdminChatsTableRow.tsx+++ /dev/null@@ -1,85 +0,0 @@-import { styled } from '@linaria/react';-import { t } from '@lingui/core/macro';--import { isNonEmptyString } from '@sniptt/guards';-import { SettingsPath } from 'twenty-shared/types';-import { getSettingsPath, isDefined } from 'twenty-shared/utils';-import { OverflowingTextWithTooltip } from 'twenty-ui/primitives/typography';-import { Tag } from 'twenty-ui/primitives/data-display';-import { themeCssVariables } from 'twenty-ui/theme';--import { SETTINGS_ADMIN_CHATS_TABLE_GRID } from '@/settings/admin-panel/chats/constants/SettingsAdminChatsTableGrid';-import { type AdminChatThreadListItem } from '@/settings/admin-panel/chats/types/AdminChatThreadListItem';-import { TableCell } from '@/ui/layout/table/components/TableCell';-import { TableRow } from '@/ui/layout/table/components/TableRow';--type SettingsAdminChatsTableRowProps = {- thread: AdminChatThreadListItem;-};--const StyledFlagsContainer = styled.div`- display: flex;- gap: ${themeCssVariables.spacing[1]};- overflow: hidden;-`;--const StyledZeroReplies = styled.span`- color: ${themeCssVariables.color.red};-`;--export const SettingsAdminChatsTableRow = ({- thread,-}: SettingsAdminChatsTableRowProps) => {- return (- <TableRow- to={getSettingsPath(SettingsPath.AdminPanelWorkspaceChatThread, {- workspaceId: thread.workspaceId,- threadId: thread.id,- })}- gridAutoColumns={SETTINGS_ADMIN_CHATS_TABLE_GRID}- isClickable- >- <TableCell minWidth="0" overflow="hidden">- <OverflowingTextWithTooltip- text={- isNonEmptyString(thread.workspaceDisplayName)- ? thread.workspaceDisplayName- : thread.workspaceId- }- />- </TableCell>- <TableCell minWidth="0" overflow="hidden">- <OverflowingTextWithTooltip- text={isNonEmptyString(thread.userEmail) ? thread.userEmail : '-'}- />- </TableCell>- <TableCell- color={themeCssVariables.font.color.primary}- minWidth="0"- overflow="hidden"- >- <OverflowingTextWithTooltip- text={isNonEmptyString(thread.title) ? thread.title : t`Untitled`}- />- </TableCell>- <TableCell align="right">{thread.messageCount}</TableCell>- <TableCell align="right">- {thread.userReplyCount === 0 ? (- <StyledZeroReplies>{thread.userReplyCount}</StyledZeroReplies>- ) : (- thread.userReplyCount- )}- </TableCell>- <TableCell minWidth="0" overflow="hidden">- <StyledFlagsContainer>- {thread.hasError && <Tag color="red">{t`Error`}</Tag>}- {isDefined(thread.deletedAt) && <Tag color="gray">{t`Archived`}</Tag>}- {thread.isOnboardingThread && <Tag color="blue">{t`Onboarding`}</Tag>}- </StyledFlagsContainer>- </TableCell>- <TableCell align="right">- {new Date(thread.createdAt).toLocaleDateString()}- </TableCell>- </TableRow>- );-};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/components/__stories__/SettingsAdminChatsFilterDropdown.stories.tsx b/packages/twenty-front/src/modules/settings/admin-panel/chats/components/__stories__/SettingsAdminChatsFilterDropdown.stories.tsxdeleted file mode 100644index 02d2eec3c0b..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/components/__stories__/SettingsAdminChatsFilterDropdown.stories.tsx+++ /dev/null@@ -1,55 +0,0 @@-import { SettingsAdminChatsFilterDropdown } from '@/settings/admin-panel/chats/components/SettingsAdminChatsFilterDropdown';-import { type AdminChatsFilterState } from '@/settings/admin-panel/chats/types/AdminChatsFilterState';-import { type Meta, type StoryObj } from '@storybook/react-vite';-import { useState } from 'react';-import { expect, userEvent, waitFor, within } from 'storybook/test';-import { Button } from 'twenty-ui/primitives/input';-import { ComponentDecorator } from 'twenty-ui/testing';--const FilterExample = () => {- const [filters, setFilters] = useState<AdminChatsFilterState>({- onboardingOnly: false,- hasErrorOnly: false,- userNeverEngagedOnly: false,- });- return (- <SettingsAdminChatsFilterDropdown- filterButton={<Button>Filter chats</Button>}- filters={filters}- onFiltersChange={setFilters}- />- );-};--const meta: Meta = {- title: 'Modules/Settings/AdminPanel/Chats/Filters',- decorators: [ComponentDecorator],- render: () => <FilterExample />,-};-export default meta;-type Story = StoryObj;--export const ToggleWithoutClosing: Story = {- play: async ({ canvasElement }) => {- const trigger = within(canvasElement).getByRole('button', {- name: 'Filter chats',- });- const body = within(canvasElement.ownerDocument.body);- await userEvent.click(trigger);- const popup = await body.findByRole('dialog');- const switches = within(popup).getAllByRole('switch');- await userEvent.click(switches[0]);- expect(switches[0]).toBeChecked();- expect(popup).toBeVisible();- await userEvent.tab();- await userEvent.keyboard(' ');- expect(switches[1]).toBeChecked();- await userEvent.keyboard('{Escape}');- await waitFor(() => expect(popup).not.toBeInTheDocument());- await waitFor(() => expect(trigger).toHaveFocus());- await userEvent.click(trigger);- const reopened = await body.findByRole('dialog');- expect(within(reopened).getAllByRole('switch')[0]).toBeChecked();- await userEvent.keyboard('{Escape}');- },-};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/constants/DefaultAdminChatsFilterState.ts b/packages/twenty-front/src/modules/settings/admin-panel/chats/constants/DefaultAdminChatsFilterState.tsdeleted file mode 100644index b584d1c27d6..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/constants/DefaultAdminChatsFilterState.ts+++ /dev/null@@ -1,7 +0,0 @@-import { type AdminChatsFilterState } from '@/settings/admin-panel/chats/types/AdminChatsFilterState';--export const DEFAULT_ADMIN_CHATS_FILTER_STATE: AdminChatsFilterState = {- onboardingOnly: false,- hasErrorOnly: false,- userNeverEngagedOnly: false,-};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/constants/SettingsAdminChatsTableGrid.ts b/packages/twenty-front/src/modules/settings/admin-panel/chats/constants/SettingsAdminChatsTableGrid.tsdeleted file mode 100644index cc743f0c5e6..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/constants/SettingsAdminChatsTableGrid.ts+++ /dev/null@@ -1,2 +0,0 @@-export const SETTINGS_ADMIN_CHATS_TABLE_GRID =- '1fr 1fr 1fr 80px 80px 110px 90px';diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/constants/SettingsAdminChatsTableId.ts b/packages/twenty-front/src/modules/settings/admin-panel/chats/constants/SettingsAdminChatsTableId.tsdeleted file mode 100644index 9a53f944cf3..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/constants/SettingsAdminChatsTableId.ts+++ /dev/null@@ -1 +0,0 @@-export const SETTINGS_ADMIN_CHATS_TABLE_ID = 'settings-admin-chats-table';diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/hooks/useAdminChatThreads.ts b/packages/twenty-front/src/modules/settings/admin-panel/chats/hooks/useAdminChatThreads.tsdeleted file mode 100644index 1ce86b0e54e..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/hooks/useAdminChatThreads.ts+++ /dev/null@@ -1,126 +0,0 @@-import { useQuery } from '@apollo/client/react';-import { t } from '@lingui/core/macro';-import { useDebounce } from 'use-debounce';--import { isDefined } from 'twenty-shared/utils';--import { useApolloAdminClient } from '@/settings/admin-panel/apollo/hooks/useApolloAdminClient';-import { SETTINGS_ADMIN_CHATS_TABLE_ID } from '@/settings/admin-panel/chats/constants/SettingsAdminChatsTableId';-import { adminChatsFilterState } from '@/settings/admin-panel/chats/states/adminChatsFilterState';-import { adminChatsSearchQueryState } from '@/settings/admin-panel/chats/states/adminChatsSearchQueryState';-import { getAdminChatsSortVariables } from '@/settings/admin-panel/chats/utils/getAdminChatsSortVariables';-import { GET_ADMIN_CHAT_THREADS } from '@/settings/admin-panel/graphql/queries/getAdminChatThreads';-import { sortedFieldByTableFamilyState } from '@/ui/layout/table/states/sortedFieldByTableFamilyState';-import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyStateValue';-import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';-import { useToast } from 'twenty-ui/components/feedback';-import {- AdminChatThreadScope,- type GetAdminChatThreadsQuery,- type GetAdminChatThreadsQueryVariables,-} from '~/generated-admin/graphql';--const PAGE_SIZE = 25;--export const useAdminChatThreads = () => {- const apolloAdminClient = useApolloAdminClient();- const { enqueueToast } = useToast();- const [adminChatsSearchQuery, setAdminChatsSearchQuery] = useAtomState(- adminChatsSearchQueryState,- );- const [debouncedSearchQuery] = useDebounce(adminChatsSearchQuery, 300);- const [adminChatsFilter, setAdminChatsFilter] = useAtomState(- adminChatsFilterState,- );-- const sortedFieldByTable = useAtomFamilyStateValue(- sortedFieldByTableFamilyState,- {- tableId: SETTINGS_ADMIN_CHATS_TABLE_ID,- },- );- const { sortBy, sortDirection } =- getAdminChatsSortVariables(sortedFieldByTable);-- const { data, loading, error, fetchMore } = useQuery<- GetAdminChatThreadsQuery,- GetAdminChatThreadsQueryVariables- >(GET_ADMIN_CHAT_THREADS, {- client: apolloAdminClient,- notifyOnNetworkStatusChange: true,- variables: {- limit: PAGE_SIZE,- offset: 0,- searchTerm: debouncedSearchQuery,- scope: adminChatsFilter.onboardingOnly- ? AdminChatThreadScope.ONBOARDING- : AdminChatThreadScope.ALL,- hasErrorOnly: adminChatsFilter.hasErrorOnly,- userNeverEngagedOnly: adminChatsFilter.userNeverEngagedOnly,- sortBy,- sortDirection,- },- });-- const threads = data?.getAdminChatThreads.threads ?? [];- const totalCount = data?.getAdminChatThreads.totalCount ?? 0;- const hasMore = data?.getAdminChatThreads.hasMore ?? false;-- const isShowMoreDisabled =- loading || adminChatsSearchQuery !== debouncedSearchQuery;-- const handleShowMore = async () => {- if (isShowMoreDisabled) {- return;- }-- try {- await fetchMore({- variables: {- limit: PAGE_SIZE,- offset: threads.length,- },- updateQuery: (previousData, { fetchMoreResult }) => {- if (!isDefined(fetchMoreResult)) {- return previousData;- }-- const previousThreadIds = new Set(- previousData.getAdminChatThreads.threads.map((thread) => thread.id),- );-- return {- getAdminChatThreads: {- ...fetchMoreResult.getAdminChatThreads,- threads: [- ...previousData.getAdminChatThreads.threads,- ...fetchMoreResult.getAdminChatThreads.threads.filter(- (thread) => !previousThreadIds.has(thread.id),- ),- ],- },- };- },- });- } catch {- enqueueToast({- status: 'error',- children: t`Failed to load more chats.`,- });- }- };-- return {- searchQuery: adminChatsSearchQuery,- setSearchQuery: setAdminChatsSearchQuery,- filters: adminChatsFilter,- setFilters: setAdminChatsFilter,- threads,- totalCount,- hasMore,- loading,- isShowMoreDisabled,- error,- handleShowMore,- };-};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/states/adminChatsFilterState.ts b/packages/twenty-front/src/modules/settings/admin-panel/chats/states/adminChatsFilterState.tsdeleted file mode 100644index 2ca56a88f3e..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/states/adminChatsFilterState.ts+++ /dev/null@@ -1,8 +0,0 @@-import { DEFAULT_ADMIN_CHATS_FILTER_STATE } from '@/settings/admin-panel/chats/constants/DefaultAdminChatsFilterState';-import { type AdminChatsFilterState } from '@/settings/admin-panel/chats/types/AdminChatsFilterState';-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';--export const adminChatsFilterState = createAtomState<AdminChatsFilterState>({- key: 'adminChatsFilterState',- defaultValue: DEFAULT_ADMIN_CHATS_FILTER_STATE,-});diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/states/adminChatsSearchQueryState.ts b/packages/twenty-front/src/modules/settings/admin-panel/chats/states/adminChatsSearchQueryState.tsdeleted file mode 100644index 1f6fd2575f7..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/states/adminChatsSearchQueryState.ts+++ /dev/null@@ -1,6 +0,0 @@-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';--export const adminChatsSearchQueryState = createAtomState<string>({- key: 'adminChatsSearchQueryState',- defaultValue: '',-});diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/types/AdminChatThreadListItem.ts b/packages/twenty-front/src/modules/settings/admin-panel/chats/types/AdminChatThreadListItem.tsdeleted file mode 100644index 8b12a6ddad0..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/types/AdminChatThreadListItem.ts+++ /dev/null@@ -1,5 +0,0 @@-import { type GetAdminChatThreadsQuery } from '~/generated-admin/graphql';--export type AdminChatThreadListItem = NonNullable<- GetAdminChatThreadsQuery['getAdminChatThreads']->['threads'][number];diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/types/AdminChatsFilterState.ts b/packages/twenty-front/src/modules/settings/admin-panel/chats/types/AdminChatsFilterState.tsdeleted file mode 100644index 0defabc36b5..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/types/AdminChatsFilterState.ts+++ /dev/null@@ -1,5 +0,0 @@-export type AdminChatsFilterState = {- onboardingOnly: boolean;- hasErrorOnly: boolean;- userNeverEngagedOnly: boolean;-};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/utils/__tests__/getAdminChatsSortVariables.test.ts b/packages/twenty-front/src/modules/settings/admin-panel/chats/utils/__tests__/getAdminChatsSortVariables.test.tsdeleted file mode 100644index bc3f106e96a..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/utils/__tests__/getAdminChatsSortVariables.test.ts+++ /dev/null@@ -1,50 +0,0 @@-import { getAdminChatsSortVariables } from '@/settings/admin-panel/chats/utils/getAdminChatsSortVariables';-import {- AdminChatThreadSortDirection,- AdminChatThreadSortField,-} from '~/generated-admin/graphql';--describe('getAdminChatsSortVariables', () => {- it('should default to created at descending when no sort is set', () => {- expect(getAdminChatsSortVariables(null)).toEqual({- sortBy: AdminChatThreadSortField.CREATED_AT,- sortDirection: AdminChatThreadSortDirection.DESC,- });- });-- it('should default when the sorted field is not a server sort field', () => {- expect(- getAdminChatsSortVariables({- fieldName: 'unknownField',- direction: 'asc',- }),- ).toEqual({- sortBy: AdminChatThreadSortField.CREATED_AT,- sortDirection: AdminChatThreadSortDirection.DESC,- });- });-- it('should map an ascending message count sort', () => {- expect(- getAdminChatsSortVariables({- fieldName: AdminChatThreadSortField.MESSAGE_COUNT,- direction: 'asc',- }),- ).toEqual({- sortBy: AdminChatThreadSortField.MESSAGE_COUNT,- sortDirection: AdminChatThreadSortDirection.ASC,- });- });-- it('should map a descending updated at sort', () => {- expect(- getAdminChatsSortVariables({- fieldName: AdminChatThreadSortField.UPDATED_AT,- direction: 'desc',- }),- ).toEqual({- sortBy: AdminChatThreadSortField.UPDATED_AT,- sortDirection: AdminChatThreadSortDirection.DESC,- });- });-});diff --git a/packages/twenty-front/src/modules/settings/admin-panel/chats/utils/getAdminChatsSortVariables.ts b/packages/twenty-front/src/modules/settings/admin-panel/chats/utils/getAdminChatsSortVariables.tsdeleted file mode 100644index 035c5a976a2..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/chats/utils/getAdminChatsSortVariables.ts+++ /dev/null@@ -1,41 +0,0 @@-import { isDefined } from 'twenty-shared/utils';--import { type TableSortValue } from '@/ui/layout/table/types/TableSortValue';-import {- AdminChatThreadSortDirection,- AdminChatThreadSortField,-} from '~/generated-admin/graphql';--type AdminChatsSortVariables = {- sortBy: AdminChatThreadSortField;- sortDirection: AdminChatThreadSortDirection;-};--const isAdminChatThreadSortField = (- fieldName: string,-): fieldName is AdminChatThreadSortField =>- Object.values(AdminChatThreadSortField).includes(- fieldName as AdminChatThreadSortField,- );--export const getAdminChatsSortVariables = (- sortValue: TableSortValue | null,-): AdminChatsSortVariables => {- if (- !isDefined(sortValue) ||- !isAdminChatThreadSortField(sortValue.fieldName)- ) {- return {- sortBy: AdminChatThreadSortField.CREATED_AT,- sortDirection: AdminChatThreadSortDirection.DESC,- };- }-- return {- sortBy: sortValue.fieldName,- sortDirection:- sortValue.direction === 'asc'- ? AdminChatThreadSortDirection.ASC- : AdminChatThreadSortDirection.DESC,- };-};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/getAdminChatThreads.ts b/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/getAdminChatThreads.tsdeleted file mode 100644index c7e5ea8195e..00000000000--- a/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/getAdminChatThreads.ts+++ /dev/null@@ -1,45 +0,0 @@-import { gql } from '@apollo/client';--export const GET_ADMIN_CHAT_THREADS = gql`- query GetAdminChatThreads(- $scope: AdminChatThreadScope- $hasErrorOnly: Boolean- $userNeverEngagedOnly: Boolean- $searchTerm: String- $sortBy: AdminChatThreadSortField- $sortDirection: AdminChatThreadSortDirection- $limit: Int- $offset: Int- ) {- getAdminChatThreads(- scope: $scope- hasErrorOnly: $hasErrorOnly- userNeverEngagedOnly: $userNeverEngagedOnly- searchTerm: $searchTerm- sortBy: $sortBy- sortDirection: $sortDirection- limit: $limit- offset: $offset- ) {- totalCount- hasMore- threads {- id- title- workspaceId- workspaceDisplayName- userWorkspaceId- userEmail- userFirstName- userLastName- messageCount- userReplyCount- hasError- isOnboardingThread- deletedAt- createdAt- updatedAt- }- }- }-`;diff --git a/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminChats.tsx b/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminChats.tsxdeleted file mode 100644index 806350f6725..00000000000--- a/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminChats.tsx+++ /dev/null@@ -1,94 +0,0 @@-import { styled } from '@linaria/react';-import { t } from '@lingui/core/macro';--import { SettingsPath } from 'twenty-shared/types';-import { getSettingsPath, isDefined } from 'twenty-shared/utils';-import { SearchInput } from 'twenty-ui/components/input';-import { Section } from 'twenty-ui/components/layout';-import { IconDotsVertical } from 'twenty-ui/icon';-import { Button } from 'twenty-ui/primitives/input';-import { themeCssVariables } from 'twenty-ui/theme';--import { AI_ADMIN_PATH } from '@/settings/admin-panel/ai/constants/AiAdminPath';-import { SettingsAdminChatsContent } from '@/settings/admin-panel/chats/components/SettingsAdminChatsContent';-import { SettingsAdminChatsFilterDropdown } from '@/settings/admin-panel/chats/components/SettingsAdminChatsFilterDropdown';-import { useAdminChatThreads } from '@/settings/admin-panel/chats/hooks/useAdminChatThreads';-import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';-import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';--const StyledShowMoreContainer = styled.div`- display: flex;- justify-content: center;- margin-top: ${themeCssVariables.spacing[2]};-`;--export const SettingsAdminChats = () => {- const {- searchQuery,- setSearchQuery,- filters,- setFilters,- threads,- totalCount,- hasMore,- loading,- isShowMoreDisabled,- error,- handleShowMore,- } = useAdminChatThreads();-- return (- <SettingsPageLayout- links={[- {- children: t`Other`,- href: getSettingsPath(SettingsPath.AdminPanel),- },- {- children: t`Admin Panel - AI`,- href: AI_ADMIN_PATH,- },- {- children: t`Chats`,- },- ]}- >- <SettingsPageContainer>- <Section.Root>- <Section.Header- title={t`Chats`}- description={t`Browse AI chat threads across all workspaces (${totalCount} matching)`}- />- <SearchInput- placeholder={t`Search by workspace, user email or thread id...`}- value={searchQuery}- onValueChange={setSearchQuery}- filterDropdown={(filterButton) => (- <SettingsAdminChatsFilterDropdown- filterButton={filterButton}- filters={filters}- onFiltersChange={setFilters}- />- )}- />- <SettingsAdminChatsContent- threads={threads}- loading={loading}- error={error}- />- {hasMore && !isDefined(error) && (- <StyledShowMoreContainer>- <Button- startIcon={<IconDotsVertical />}- onClick={handleShowMore}- disabled={isShowMoreDisabled}- size="sm"- variant="outline"- >{t`Show more`}</Button>- </StyledShowMoreContainer>- )}- </Section.Root>- </SettingsPageContainer>- </SettingsPageLayout>- );-};diff --git a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts b/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.tsindex 5ce6c52ee3a..6ba13ea6b5d 100644--- a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts+++ b/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts@@ -23,10 +23,6 @@ import { WorkspaceSchemaIndexManagerService } from 'src/engine/twenty-orm/workspimport { updateAgentChatThreadUsage } from 'src/engine/metadata-modules/ai/ai-chat/utils/update-agent-chat-thread-usage.util';import { Logger } from '@nestjs/common';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';-import { AdminPanelGlobalChatThreadsService } from 'src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service';-import { AdminChatThreadScope } from 'src/engine/core-modules/admin-panel/enums/admin-chat-thread-scope.enum';-import { AdminChatThreadSortDirection } from 'src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-direction.enum';-import { AdminChatThreadSortField } from 'src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-field.enum';import { WorkspaceDataSource } from 'src/engine/twenty-orm/datasource/workspace-data-source';import { WorkspaceSchemaTableManagerService } from 'src/engine/twenty-orm/workspace-schema-manager/services/workspace-schema-table-manager.service';import { generateColumnDefinitions } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/generate-column-definitions.util';@@ -1256,63 +1252,12 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);});});- it('lists support threads only from workspaces with history tables', async () => {- const otherWorkspaceId = '20202020-9999-4999-8999-999999999999';- await dataSource.query(- `INSERT INTO core.workspace (id, "allowImpersonation") VALUES ($1, true)`,- [otherWorkspaceId],- );- const workspaceIds = [WORKSPACE_ID, otherWorkspaceId];- await workspaceStorage.runReadOnlyReport(- workspaceIds,- async ({ partitions }) =>- expect(partitions.map(({ workspaceIds }) => workspaceIds)).toEqual([- [WORKSPACE_ID],- ]),- );- const support = new AdminPanelGlobalChatThreadsService(- {- find: async () => workspaceIds.map((id) => ({ id })),- } as unknown as Repository<WorkspaceEntity>,- workspaceStorage,- );- await migration.migrate({- workspaceId: WORKSPACE_ID,- target: 'workspace',- });- await dataSource.query(- 'INSERT INTO core."userWorkspace" (id, "workspaceId", "userId", "deletedAt") VALUES ($1, $2, $3, now())',- ['20202020-0000-4000-8000-000000009999', WORKSPACE_ID, OWNER_ID],- );- expect(- await support.getGlobalChatThreads({- scope: AdminChatThreadScope.ALL,- hasErrorOnly: false,- userNeverEngagedOnly: false,- sortBy: AdminChatThreadSortField.CREATED_AT,- sortDirection: AdminChatThreadSortDirection.ASC,- limit: 1,- offset: 0,- }),- ).toMatchObject({- totalCount: 1,- hasMore: false,- threads: [{ id: THREAD_ID }],- });- });-- it('serves support search and thread lookup from workspace storage', async () => {- const otherWorkspaceId = '20202020-9999-4999-8999-999999999999';- await dataSource.query(- `INSERT INTO core.workspace (id, "allowImpersonation") VALUES ($1, true)`,- [otherWorkspaceId],- );+ it('serves thread lookup from workspace storage', async () => {await migration.migrate({workspaceId: WORKSPACE_ID,target: 'workspace',});const workspaceRepository = {- find: async () => [{ id: otherWorkspaceId }, { id: WORKSPACE_ID }],findOne: async ({ where }: { where: { id: string } }) =>(await dataSource.query(@@ -1321,21 +1266,6 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);))[0],} as unknown as Repository<WorkspaceEntity>;- const support = new AdminPanelGlobalChatThreadsService(- workspaceRepository,- workspaceStorage,- );- expect(- await support.getGlobalChatThreads({- scope: AdminChatThreadScope.ALL,- hasErrorOnly: false,- userNeverEngagedOnly: false,- sortBy: AdminChatThreadSortField.CREATED_AT,- sortDirection: AdminChatThreadSortDirection.ASC,- limit: 10,- offset: 0,- }),- ).toMatchObject({ totalCount: 1, threads: [{ id: THREAD_ID }] });const chat = new AdminPanelChatService(workspaceRepository,threads,@@ -1465,38 +1395,5 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);target: 'workspace',});});-- it('keeps support search counts and revocation checks after the move', async () => {- const support = new AdminPanelGlobalChatThreadsService(- {- find: jest.fn().mockResolvedValue([{ id: WORKSPACE_ID }]),- } as unknown as Repository<WorkspaceEntity>,- workspaceStorage,- );- const options = {- scope: AdminChatThreadScope.ONBOARDING,- hasErrorOnly: false,- userNeverEngagedOnly: false,- sortBy: AdminChatThreadSortField.UPDATED_AT,- sortDirection: AdminChatThreadSortDirection.DESC,- limit: 10,- offset: 0,- };- await dataSource.query(- `INSERT INTO core."agentMessage" ("workspaceId", "threadId", "turnId", role) VALUES ($1, $2, $3, 'user')`,- [WORKSPACE_ID, THREAD_ID, TURN_ID],- );- await migration.migrate({- workspaceId: WORKSPACE_ID,- target: 'workspace',- });- const after = await support.getGlobalChatThreads(options);- expect(after.totalCount).toBe(1);- expect(after.threads[0].messageCount).toBe(1);- await dataSource.query(- 'UPDATE core.workspace SET "allowImpersonation" = false',- );- expect((await support.getGlobalChatThreads(options)).threads).toEqual([]);- });},);diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.module.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.module.tsindex d0d34cc9740..55e728c424b 100644--- a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.module.ts+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.module.ts@@ -20,7 +20,6 @@ import { AdminPanelAiProviderService } from 'src/engine/core-modules/admin-panelimport { AdminPanelUsageLimitService } from 'src/engine/core-modules/admin-panel/services/admin-panel-usage-limit.service';import { AdminPanelBillingService } from 'src/engine/core-modules/admin-panel/services/admin-panel-billing.service';import { AdminPanelChatService } from 'src/engine/core-modules/admin-panel/services/admin-panel-chat.service';-import { AdminPanelGlobalChatThreadsService } from 'src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service';import { AdminPanelConfigService } from 'src/engine/core-modules/admin-panel/services/admin-panel-config.service';import { AdminPanelServerAdminService } from 'src/engine/core-modules/admin-panel/services/admin-panel-server-admin.service';import { AdminPanelSigningKeyService } from 'src/engine/core-modules/admin-panel/services/admin-panel-signing-key.service';@@ -96,7 +95,6 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspacAdminPanelStatisticsService,AdminPanelBillingService,AdminPanelChatService,- AdminPanelGlobalChatThreadsService,AdminPanelConfigService,AdminPanelSigningKeyService,AdminPanelVersionService,diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.tsindex e1b72b5eff9..2a8da9bfffc 100644--- a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts@@ -18,7 +18,6 @@ import { AdminPanelHealthService } from 'src/engine/core-modules/admin-panel/admimport { AdminPanelQueueService } from 'src/engine/core-modules/admin-panel/admin-panel-queue.service';import { AdminChatThreadMessagesDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-chat-thread-messages.dto';import { AdminPanelRecentUserDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-recent-user.dto';-import { PaginatedAdminChatThreadsDTO } from 'src/engine/core-modules/admin-panel/dtos/paginated-admin-chat-threads.dto';import { AdminPanelTopWorkspaceDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-top-workspace.dto';import { AdminPanelWorkspaceBillingDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-billing.dto';import { AdminPanelWorkspaceCreditGrantDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-credit-grant.dto';@@ -41,16 +40,12 @@ import { UpdateWorkspaceFeatureFlagInput } from 'src/engine/core-modules/admin-pimport { UserLookup } from 'src/engine/core-modules/admin-panel/dtos/user-lookup.dto';import { UserLookupInput } from 'src/engine/core-modules/admin-panel/dtos/user-lookup.input';import { VersionInfoDTO } from 'src/engine/core-modules/admin-panel/dtos/version-info.dto';-import { AdminChatThreadScope } from 'src/engine/core-modules/admin-panel/enums/admin-chat-thread-scope.enum';-import { AdminChatThreadSortDirection } from 'src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-direction.enum';-import { AdminChatThreadSortField } from 'src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-field.enum';import { HealthIndicatorId } from 'src/engine/core-modules/admin-panel/enums/health-indicator-id.enum';import { JobStateEnum } from 'src/engine/core-modules/message-queue/enums/job-state.enum';import { QueueMetricsTimeRange } from 'src/engine/core-modules/admin-panel/enums/queue-metrics-time-range.enum';import { MaintenanceModeService } from 'src/engine/core-modules/admin-panel/maintenance-mode.service';import { AdminPanelBillingService } from 'src/engine/core-modules/admin-panel/services/admin-panel-billing.service';import { AdminPanelChatService } from 'src/engine/core-modules/admin-panel/services/admin-panel-chat.service';-import { AdminPanelGlobalChatThreadsService } from 'src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service';import { AdminPanelConfigService } from 'src/engine/core-modules/admin-panel/services/admin-panel-config.service';import { AdminPanelSigningKeyService } from 'src/engine/core-modules/admin-panel/services/admin-panel-signing-key.service';import { AdminPanelServerAdminService } from 'src/engine/core-modules/admin-panel/services/admin-panel-server-admin.service';@@ -140,7 +135,6 @@ export class AdminPanelResolver {private readonly adminStatisticsService: AdminPanelStatisticsService,private readonly adminBillingService: AdminPanelBillingService,private readonly adminChatService: AdminPanelChatService,- private readonly adminGlobalChatThreadsService: AdminPanelGlobalChatThreadsService,private readonly adminConfigService: AdminPanelConfigService,private readonly adminVersionService: AdminPanelVersionService,private readonly adminPanelHealthService: AdminPanelHealthService,@@ -748,58 +742,6 @@ export class AdminPanelResolver {});}- @UseGuards(ServerLevelImpersonateGuard)- @Query(() => PaginatedAdminChatThreadsDTO)- async getAdminChatThreads(- @Args('scope', {- type: () => AdminChatThreadScope,- nullable: true,- defaultValue: AdminChatThreadScope.ALL,- })- scope: AdminChatThreadScope | null,- @Args('hasErrorOnly', {- type: () => Boolean,- nullable: true,- defaultValue: false,- })- hasErrorOnly: boolean | null,- @Args('userNeverEngagedOnly', {- type: () => Boolean,- nullable: true,- defaultValue: false,- })- userNeverEngagedOnly: boolean | null,- @Args('sortBy', {- type: () => AdminChatThreadSortField,- nullable: true,- defaultValue: AdminChatThreadSortField.CREATED_AT,- })- sortBy: AdminChatThreadSortField | null,- @Args('sortDirection', {- type: () => AdminChatThreadSortDirection,- nullable: true,- defaultValue: AdminChatThreadSortDirection.DESC,- })- sortDirection: AdminChatThreadSortDirection | null,- @Args('limit', { type: () => Int, nullable: true, defaultValue: 25 })- limit: number | null,- @Args('offset', { type: () => Int, nullable: true, defaultValue: 0 })- offset: number | null,- @Args('searchTerm', { type: () => String, nullable: true })- searchTerm?: string | null,- ): Promise<PaginatedAdminChatThreadsDTO> {- return this.adminGlobalChatThreadsService.getGlobalChatThreads({- scope: scope ?? AdminChatThreadScope.ALL,- hasErrorOnly: hasErrorOnly ?? false,- userNeverEngagedOnly: userNeverEngagedOnly ?? false,- searchTerm: searchTerm ?? undefined,- sortBy: sortBy ?? AdminChatThreadSortField.CREATED_AT,- sortDirection: sortDirection ?? AdminChatThreadSortDirection.DESC,- limit: limit ?? 25,- offset: offset ?? 0,- });- }-@UseGuards(AdminPanelGuard)@Query(() => ApplicationRegistrationEntity)async findOneAdminApplicationRegistration(diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/constants/admin-chat-threads-max-page-size.constant.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/constants/admin-chat-threads-max-page-size.constant.tsdeleted file mode 100644index 915f54c50eb..00000000000--- a/packages/twenty-server/src/engine/core-modules/admin-panel/constants/admin-chat-threads-max-page-size.constant.ts+++ /dev/null@@ -1 +0,0 @@-export const ADMIN_CHAT_THREADS_MAX_PAGE_SIZE = 100;diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-chat-thread-list-item.dto.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-chat-thread-list-item.dto.tsdeleted file mode 100644index 9f872a1e6ca..00000000000--- a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-chat-thread-list-item.dto.ts+++ /dev/null@@ -1,52 +0,0 @@-import { Field, Int, ObjectType } from '@nestjs/graphql';--import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';--@ObjectType('AdminChatThreadListItem')-export class AdminChatThreadListItemDTO {- @Field(() => UUIDScalarType)- id: string;-- @Field(() => String, { nullable: true })- title: string | null;-- @Field(() => UUIDScalarType)- workspaceId: string;-- @Field(() => String, { nullable: true })- workspaceDisplayName: string | null;-- // A workflow run's conversation belongs to the run, not to a member.- @Field(() => UUIDScalarType, { nullable: true })- userWorkspaceId: string | null;-- @Field(() => String, { nullable: true })- userEmail: string | null;-- @Field(() => String, { nullable: true })- userFirstName: string | null;-- @Field(() => String, { nullable: true })- userLastName: string | null;-- @Field(() => Int)- messageCount: number;-- @Field(() => Int)- userReplyCount: number;-- @Field(() => Boolean)- hasError: boolean;-- @Field(() => Boolean)- isOnboardingThread: boolean;-- @Field(() => Date, { nullable: true })- deletedAt: Date | null;-- @Field(() => Date)- createdAt: Date;-- @Field(() => Date)- updatedAt: Date;-}diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/paginated-admin-chat-threads.dto.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/paginated-admin-chat-threads.dto.tsdeleted file mode 100644index edadcb7b409..00000000000--- a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/paginated-admin-chat-threads.dto.ts+++ /dev/null@@ -1,15 +0,0 @@-import { Field, Int, ObjectType } from '@nestjs/graphql';--import { AdminChatThreadListItemDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-chat-thread-list-item.dto';--@ObjectType('PaginatedAdminChatThreads')-export class PaginatedAdminChatThreadsDTO {- @Field(() => [AdminChatThreadListItemDTO])- threads: AdminChatThreadListItemDTO[];-- @Field(() => Int)- totalCount: number;-- @Field(() => Boolean)- hasMore: boolean;-}diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/enums/admin-chat-thread-scope.enum.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/enums/admin-chat-thread-scope.enum.tsdeleted file mode 100644index 13b2811cfd1..00000000000--- a/packages/twenty-server/src/engine/core-modules/admin-panel/enums/admin-chat-thread-scope.enum.ts+++ /dev/null@@ -1,11 +0,0 @@-import { registerEnumType } from '@nestjs/graphql';--export enum AdminChatThreadScope {- ONBOARDING = 'ONBOARDING',- ALL = 'ALL',-}--registerEnumType(AdminChatThreadScope, {- name: 'AdminChatThreadScope',- description: 'Scope of chat threads to list in the admin panel',-});diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-direction.enum.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-direction.enum.tsdeleted file mode 100644index b22dd0f08eb..00000000000--- a/packages/twenty-server/src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-direction.enum.ts+++ /dev/null@@ -1,11 +0,0 @@-import { registerEnumType } from '@nestjs/graphql';--export enum AdminChatThreadSortDirection {- ASC = 'ASC',- DESC = 'DESC',-}--registerEnumType(AdminChatThreadSortDirection, {- name: 'AdminChatThreadSortDirection',- description: 'Direction to sort admin chat threads',-});diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-field.enum.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-field.enum.tsdeleted file mode 100644index 1725f83d086..00000000000--- a/packages/twenty-server/src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-field.enum.ts+++ /dev/null@@ -1,13 +0,0 @@-import { registerEnumType } from '@nestjs/graphql';--export enum AdminChatThreadSortField {- MESSAGE_COUNT = 'MESSAGE_COUNT',- REPLY_COUNT = 'REPLY_COUNT',- CREATED_AT = 'CREATED_AT',- UPDATED_AT = 'UPDATED_AT',-}--registerEnumType(AdminChatThreadSortField, {- name: 'AdminChatThreadSortField',- description: 'Field to sort admin chat threads by',-});diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/__tests__/admin-panel-global-chat-threads.postgres.spec.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/__tests__/admin-panel-global-chat-threads.postgres.spec.tsdeleted file mode 100644index 6554179056c..00000000000--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/__tests__/admin-panel-global-chat-threads.postgres.spec.ts+++ /dev/null@@ -1,162 +0,0 @@-import { DataSource } from 'typeorm';--import { AdminChatThreadScope } from 'src/engine/core-modules/admin-panel/enums/admin-chat-thread-scope.enum';-import { AdminChatThreadSortDirection } from 'src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-direction.enum';-import { AdminChatThreadSortField } from 'src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-field.enum';-import { AdminPanelGlobalChatThreadsService } from 'src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service';-import { AgentHistoryWorkspaceStorageService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';-import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';--jest.mock('src/engine/core-modules/workspace/workspace.entity', () => ({- WorkspaceEntity: class WorkspaceEntity {},-}));--const DATABASE_URL = process.env.ADMIN_CHAT_REPORT_TEST_DATABASE_URL;-const WORKSPACE_IDS = Array.from(- { length: 26 },- (_, index) =>- `20202020-1111-4111-8111-${String(index + 1).padStart(12, '0')}`,-);-const OPTIONS = {- scope: AdminChatThreadScope.ALL,- hasErrorOnly: false,- userNeverEngagedOnly: false,- sortBy: AdminChatThreadSortField.CREATED_AT,- sortDirection: AdminChatThreadSortDirection.ASC,- limit: 1,- offset: 1,-};--(DATABASE_URL ? describe : describe.skip)(- 'admin chat report on PostgreSQL',- () => {- const dataSource = new DataSource({- type: 'postgres',- url: DATABASE_URL,- entities: [],- synchronize: false,- });- const storage = new AgentHistoryWorkspaceStorageService(dataSource);- const service = new AdminPanelGlobalChatThreadsService(- {- find: jest.fn().mockResolvedValue(WORKSPACE_IDS.map((id) => ({ id }))),- },- storage,- );-- beforeAll(async () => {- jest.useRealTimers();- if (new URL(DATABASE_URL!).pathname !== '/admin_chat_report_test') {- throw new Error('Use the isolated admin_chat_report_test database');- }- await dataSource.initialize();- await dataSource.query('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"');- });-- beforeEach(async () => {- await dataSource.query(`CREATE SCHEMA core;- CREATE TABLE core.workspace (id uuid PRIMARY KEY, "displayName" text, "allowImpersonation" boolean, "deletedAt" timestamptz);- CREATE TABLE core."userWorkspace" (id uuid, "userId" uuid, "workspaceId" uuid, "deletedAt" timestamptz);- CREATE TABLE core."user" (id uuid, email text, "firstName" text, "lastName" text)`);- for (const [index, workspaceId] of WORKSPACE_IDS.entries()) {- const schema = getWorkspaceSchemaName(workspaceId);- await dataSource.query(`CREATE SCHEMA "${schema}";- CREATE TABLE "${schema}"."agentChatThread" (id uuid, title text, "workspaceMemberId" uuid, "deletedAt" timestamptz, "createdAt" timestamptz, "updatedAt" timestamptz);- CREATE TABLE "${schema}"."agentMessage" (id uuid, "threadId" uuid, role text, "isHidden" boolean);- CREATE TABLE "${schema}"."agentMessagePart" ("messageId" uuid, "toolName" text, "toolOutput" jsonb);- CREATE TABLE "${schema}"."workspaceMember" (id uuid, "userId" uuid)`);- await dataSource.query(- 'INSERT INTO core.workspace VALUES ($1, $2, true, null)',- [workspaceId, `Workspace ${index}`],- );- if (index === 0 || index === 25) {- await dataSource.query(- `INSERT INTO "${schema}"."agentChatThread" (id, title, "createdAt", "updatedAt") VALUES ($1, $2, $3, $3)`,- [- workspaceId,- `Chat ${index}`,- new Date(Date.UTC(2026, 0, index + 1)),- ],- );- }- }- });-- afterEach(async () => {- jest.restoreAllMocks();- if (!dataSource.isInitialized) {- return;- }- for (const workspaceId of WORKSPACE_IDS) {- await dataSource.query(- `DROP SCHEMA IF EXISTS "${getWorkspaceSchemaName(workspaceId)}" CASCADE`,- );- }- await dataSource.query('DROP SCHEMA IF EXISTS core CASCADE');- });-- afterAll(async () => {- if (dataSource.isInitialized) {- await dataSource.destroy();- }- });-- it('releases earlier workspace locks while later report queries run and preserves global pagination', async () => {- const createQueryRunner = dataSource.createQueryRunner.bind(dataSource);- const migrationRunner = createQueryRunner();- await migrationRunner.connect();- await migrationRunner.query("SET lock_timeout = '100ms'");- let isMigrationCompleted = false;- jest.spyOn(dataSource, 'createQueryRunner').mockImplementation((mode) => {- const runner = createQueryRunner(mode);- const query = runner.query.bind(runner);- jest- .spyOn(runner, 'query')- .mockImplementation(async (...parameters) => {- const [sql, values] = parameters;- if (- typeof sql === 'string' &&- sql.includes('WITH candidates') &&- Array.isArray(values) &&- Array.isArray(values[0]) &&- values[0][0] === WORKSPACE_IDS[25]- ) {- await migrationRunner.query(- `ALTER TABLE "${getWorkspaceSchemaName(WORKSPACE_IDS[0])}"."agentChatThread" ADD COLUMN "reportLockRegression" text`,- );- isMigrationCompleted = true;- }- return query(...parameters);- });- return runner;- });- try {- await expect(- service.getGlobalChatThreads(OPTIONS),- ).resolves.toMatchObject({- threads: [{ id: WORKSPACE_IDS[25] }],- totalCount: 2,- hasMore: false,- });- expect(isMigrationCompleted).toBe(true);- } finally {- await migrationRunner.release();- }- });-- it('continues past a batch with no provisioned history tables', async () => {- for (const workspaceId of WORKSPACE_IDS.slice(0, 25)) {- await dataSource.query(- `DROP SCHEMA "${getWorkspaceSchemaName(workspaceId)}" CASCADE`,- );- }- await expect(- service.getGlobalChatThreads({ ...OPTIONS, offset: 0 }),- ).resolves.toMatchObject({- threads: [{ id: WORKSPACE_IDS[25] }],- totalCount: 1,- hasMore: false,- });- });- },-);diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.tsdeleted file mode 100644index ae86c94526f..00000000000--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts+++ /dev/null@@ -1,185 +0,0 @@-import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';-import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';-import { Inject, Injectable } from '@nestjs/common';-import { InjectRepository } from '@nestjs/typeorm';-import chunk from 'lodash.chunk';-import { Repository } from 'typeorm';-import { isNonEmptyArray } from 'twenty-shared/utils';-import {- ASK_QUESTION_TOOL_NAME,- ASK_QUESTIONS_TOOL_NAME,-} from 'twenty-shared/ai';-import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';-import { AgentHistoryWorkspaceStorageService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';-import { ADMIN_CHAT_THREADS_MAX_PAGE_SIZE } from 'src/engine/core-modules/admin-panel/constants/admin-chat-threads-max-page-size.constant';-import { type PaginatedAdminChatThreadsDTO } from 'src/engine/core-modules/admin-panel/dtos/paginated-admin-chat-threads.dto';-import { AdminChatThreadScope } from 'src/engine/core-modules/admin-panel/enums/admin-chat-thread-scope.enum';-import { AdminChatThreadSortDirection } from 'src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-direction.enum';-import { AdminChatThreadSortField } from 'src/engine/core-modules/admin-panel/enums/admin-chat-thread-sort-field.enum';-import { WORKSPACE_SETUP_CHAT_THREAD_ID_NAMESPACE } from 'src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-chat-thread-id-namespace.constant';-import { AgentTurnStatus } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-turn-status.enum';--type GlobalChatThreadsArgs = {- scope: AdminChatThreadScope;- hasErrorOnly: boolean;- userNeverEngagedOnly: boolean;- searchTerm?: string;- sortBy: AdminChatThreadSortField;- sortDirection: AdminChatThreadSortDirection;- limit: number;- offset: number;-};--type GlobalChatThreadRawRow = {- id: string;- title: string | null;- workspaceId: string;- workspaceDisplayName: string | null;- userWorkspaceId: string | null;- userEmail: string | null;- userFirstName: string | null;- userLastName: string | null;- messageCount: number;- userReplyCount: number;- hasError: boolean;- isOnboardingThread: boolean;- deletedAt: Date | null;- createdAt: Date;- updatedAt: Date;-};--const ADMIN_CHAT_REPORT_WORKSPACE_BATCH_SIZE = 25;--const COLUMN_BY_SORT_FIELD: Record<- AdminChatThreadSortField,- 'messageCount' | 'userReplyCount' | 'createdAt' | 'updatedAt'-> = {- [AdminChatThreadSortField.MESSAGE_COUNT]: 'messageCount',- [AdminChatThreadSortField.REPLY_COUNT]: 'userReplyCount',- [AdminChatThreadSortField.CREATED_AT]: 'createdAt',- [AdminChatThreadSortField.UPDATED_AT]: 'updatedAt',-};--@Injectable()-export class AdminPanelGlobalChatThreadsService {- constructor(- @InjectRepository(WorkspaceEntity)- private readonly workspaceRepository: Pick<- Repository<WorkspaceEntity>,- 'find'- >,- @Inject(AgentHistoryWorkspaceStorageService)- private readonly historyStorage: Pick<- AgentHistoryWorkspaceStorageService,- 'runReadOnlyReport'- >,- ) {}-- async getGlobalChatThreads(- args: GlobalChatThreadsArgs,- ): Promise<PaginatedAdminChatThreadsDTO> {- const limit = Math.min(- Math.max(args.limit, 1),- ADMIN_CHAT_THREADS_MAX_PAGE_SIZE,- );- const offset = Math.max(args.offset, 0);- const field = COLUMN_BY_SORT_FIELD[args.sortBy];- const direction =- args.sortDirection === AdminChatThreadSortDirection.ASC ? 1 : -1;- const workspaces = await this.workspaceRepository.find({- where: { allowImpersonation: true },- select: { id: true },- order: { id: 'ASC' },- });- let candidates: GlobalChatThreadRawRow[] = [];- let totalCount = 0;- const compare = (- left: GlobalChatThreadRawRow,- right: GlobalChatThreadRawRow,- ) => {- const leftValue = Number(left[field]);- const rightValue = Number(right[field]);- return (- direction * (leftValue - rightValue) || left.id.localeCompare(right.id)- );- };-- // Release earlier workspace locks before scanning the next batch so upgrades can proceed.- for (const workspaceBatch of chunk(- workspaces,- ADMIN_CHAT_REPORT_WORKSPACE_BATCH_SIZE,- )) {- await this.historyStorage.runReadOnlyReport(- workspaceBatch.map((workspace) => workspace.id),- async ({ manager, partitions }) => {- if (!isNonEmptyArray(partitions)) {- return;- }-- const parameters: unknown[] = [];- const queries = partitions.map(- ({ workspaceIds, table }, partitionIndex) => {- const search = args.searchTerm?.trim().replace(/[\\%_]/g, '\\$&');- const query = `- WITH candidates AS (- SELECT thread.id, thread.title, workspace.id AS "workspaceId", workspace."displayName" AS "workspaceDisplayName",- membership.id AS "userWorkspaceId", owner.email AS "userEmail", owner."firstName" AS "userFirstName", owner."lastName" AS "userLastName",- thread."deletedAt", thread."createdAt", thread."updatedAt",- COALESCE((SELECT turn.status = '${AgentTurnStatus.FAILED}' FROM ${table('agentTurn')} turn WHERE turn."threadId" = thread.id ORDER BY turn."createdAt" DESC, turn.id DESC LIMIT 1), false) AS "hasError",- (EXISTS (SELECT 1 FROM ${table('agentMessage')} context WHERE context."threadId" = thread.id AND context.role = 'system')- OR (membership.id IS NOT NULL AND thread.id = public.uuid_generate_v5($2::uuid, workspace.id::text || ':' || membership.id::text))) AS "isOnboardingThread",- (SELECT COUNT(*)::int FROM ${table('agentMessage')} message WHERE message."threadId" = thread.id AND message.role <> 'system') AS "messageCount",- ((SELECT COUNT(*) FROM ${table('agentMessage')} message WHERE message."threadId" = thread.id AND message.role = 'user')- + (SELECT COUNT(*) FROM ${table('agentMessagePart')} part JOIN ${table('agentMessage')} message ON message.id = part."messageId"- WHERE message."threadId" = thread.id AND part."toolName" = ANY($3::text[]) AND part."toolOutput"->'result'->>'status' = 'answered'))::int AS "userReplyCount"- FROM ${table('agentChatThread')} thread- JOIN core.workspace workspace ON workspace.id = ANY($1::uuid[]) AND workspace."allowImpersonation" = true AND workspace."deletedAt" IS NULL- LEFT JOIN ${escapeIdentifier(getWorkspaceSchemaName(workspaceIds[0]))}."workspaceMember" member ON member.id = thread."workspaceMemberId"- LEFT JOIN core."userWorkspace" membership ON membership."userId" = member."userId" AND membership."workspaceId" = workspace.id AND membership."deletedAt" IS NULL- LEFT JOIN core."user" owner ON owner.id = member."userId"- WHERE true- AND ($4::text IS NULL OR workspace."displayName" ILIKE $4 OR owner.email ILIKE $4 OR thread.id::text ILIKE $4)- )- SELECT *, COUNT(*) OVER () AS "totalCount", $9::int AS "partitionIndex" FROM candidates- WHERE ($5::boolean = false OR "isOnboardingThread") AND ($6::boolean = false OR "hasError") AND ($7::boolean = false OR "userReplyCount" = 0)- ORDER BY "${field}" ${direction === 1 ? 'ASC' : 'DESC'}, id ASC LIMIT $8`;- const parameterOffset = parameters.length;- parameters.push(- workspaceIds,- WORKSPACE_SETUP_CHAT_THREAD_ID_NAMESPACE,- [ASK_QUESTION_TOOL_NAME, ASK_QUESTIONS_TOOL_NAME],- search ? `%${search}%` : null,- args.scope === AdminChatThreadScope.ONBOARDING,- args.hasErrorOnly,- args.userNeverEngagedOnly,- offset + limit,- partitionIndex,- );- return `(${query.replace(/\$(\d+)/g, (_, position: string) => `$${Number(position) + parameterOffset}`)})`;- },- );- const rows = await manager.query<- (GlobalChatThreadRawRow & {- totalCount: string;- partitionIndex: number;- })[]- >(queries.join(' UNION ALL '), parameters);- totalCount += [- ...new Map(- rows.map((row) => [row.partitionIndex, Number(row.totalCount)]),- ).values(),- ].reduce((total, count) => total + count, 0);- candidates = [...candidates, ...rows]- .sort(compare)- .slice(0, offset + limit);- },- );- }- const threads = candidates.slice(offset, offset + limit);- return {- threads,- totalCount,- hasMore: offset + threads.length < totalCount,- };- }-}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service.tsindex 12c84aee29a..cf93a1b55c9 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service.ts@@ -43,40 +43,4 @@ export class AgentHistoryWorkspaceStorageService {return this.dataSource.transaction((manager) => work({ manager, table }));}-- async runReadOnlyReport<TResult>(- workspaceIds: string[],- work: (context: {- manager: EntityManager;- partitions: {- workspaceIds: string[];- table: AgentHistoryStorageContext['table'];- }[];- }) => Promise<TResult>,- ): Promise<TResult> {- // One snapshot keeps a paginated report's rows and counts consistent- return this.dataSource.transaction('REPEATABLE READ', async (manager) => {- await manager.query('SET TRANSACTION READ ONLY');-- // Older installations can keep workspace records without a schema- const provisioned: { workspaceId: string }[] = await manager.query(- `SELECT id AS "workspaceId" FROM unnest($1::uuid[], $2::text[]) AS candidate(id, table_name)- WHERE to_regclass(table_name) IS NOT NULL`,- [- workspaceIds,- workspaceIds.map((workspaceId) =>- getWorkspaceAgentHistoryTable(workspaceId)('agentChatThread'),- ),- ],- );-- return work({- manager,- partitions: provisioned.map(({ workspaceId }) => ({- workspaceIds: [workspaceId],- table: getWorkspaceAgentHistoryTable(workspaceId),- })),- });- });- }}diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snapindex 0acc40913ea..e469314856f 100644--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap@@ -26,7 +26,6 @@ exports[`endpoint permission declarations should match the AuthPrincipalGuard an"AdminPanelResolver.getAdminAiModels {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AdminPanelResolver.getAdminAiUsageByWorkspace {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AdminPanelResolver.getAdminChatThreadMessages {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "AdminPanelResolver.getAdminChatThreads {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AdminPanelResolver.getAdminWorkspaceChatThreads {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AdminPanelResolver.getConfigVariablesGrouped {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AdminPanelResolver.getDatabaseConfigVariable {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",diff --git a/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.tsindex 5305e0f565a..670f88ac9bd 100644--- a/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts@@ -2,61 +2,15 @@ import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/geimport { randomUUID } from 'crypto';import { gql } from 'graphql-tag';-import { type DataSource } from 'typeorm';import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';import { type AgentHistoryUpgradeStorageService } from 'src/database/commands/agent-history/agent-history-upgrade-storage.service';import { type AgentHistoryObjectName } from 'src/engine/metadata-modules/ai/ai-history/types/agent-history-object-name.type';import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';-import { v5 } from 'uuid';-import { makeAdminPanelApiRequestWithGuestRole } from 'test/integration/graphql/suites/admin-panel/utils/make-admin-panel-api-request-with-guest-role.util';import { makeAdminPanelApiRequest } from 'test/integration/twenty-config/utils/make-admin-panel-api-request.util';-import { WORKSPACE_SETUP_CHAT_THREAD_ID_NAMESPACE } from 'src/engine/metadata-modules/ai/ai-chat/constants/workspace-setup-chat-thread-id-namespace.constant';import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';-const GET_ADMIN_CHAT_THREADS = gql`- query GetAdminChatThreads(- $scope: AdminChatThreadScope- $hasErrorOnly: Boolean- $userNeverEngagedOnly: Boolean- $searchTerm: String- $sortBy: AdminChatThreadSortField- $sortDirection: AdminChatThreadSortDirection- $limit: Int- $offset: Int- ) {- getAdminChatThreads(- scope: $scope- hasErrorOnly: $hasErrorOnly- userNeverEngagedOnly: $userNeverEngagedOnly- searchTerm: $searchTerm- sortBy: $sortBy- sortDirection: $sortDirection- limit: $limit- offset: $offset- ) {- totalCount- hasMore- threads {- id- title- workspaceId- workspaceDisplayName- userWorkspaceId- userEmail- messageCount- userReplyCount- hasError- isOnboardingThread- deletedAt- createdAt- updatedAt- }- }- }-`;-const GET_ADMIN_CHAT_THREAD_MESSAGES = gql`query GetAdminChatThreadMessages($workspaceId: UUID!, $threadId: UUID!) {getAdminChatThreadMessages(workspaceId: $workspaceId, threadId: $threadId) {@@ -85,30 +39,10 @@ const GET_ADMIN_CHAT_THREAD_MESSAGES = gql`}`;-type ThreadsResult = {- totalCount: number;- hasMore: boolean;- threads: {- id: string;- messageCount: number;- userReplyCount: number;- hasError: boolean;- isOnboardingThread: boolean;- userEmail: string | null;- }[];-};--describe('Admin panel global chat threads (integration)', () => {- let dataSource: DataSource;+describe('Admin panel chat thread messages (integration)', () => {let storage: AgentHistoryUpgradeStorageService;- let userWorkspaceId: string;let workspaceMemberId: string;- let userEmail: string;let kickoffThreadId: string;- let deterministicThreadId: string;- let regularThreadId: string;- let answeredQuestionThreadId: string;- let pendingQuestionThreadId: string;const seededThreadIds: string[] = [];const seededMessageIds: string[] = [];const seededPartIds: string[] = [];@@ -130,11 +64,9 @@ describe('Admin panel global chat threads (integration)', () => {const insertThread = async ({id,title,- hasFailedTurn = false,}: {id: string;title: string;- hasFailedTurn?: boolean;}): Promise<string> => {await insertHistory('agentChatThread',@@ -143,22 +75,6 @@ describe('Admin panel global chat threads (integration)', () => {'ON CONFLICT (id) DO NOTHING',);- if (hasFailedTurn) {- await insertHistory(- 'agentTurn',- ['id', 'threadId', 'status', 'error'],- [- randomUUID(),- id,- 'failed',- JSON.stringify({- code: 'STREAM_EXECUTION_FAILED',- message: 'stream failed',- }),- ],- );- }-seededThreadIds.push(id);return id;@@ -246,27 +162,13 @@ describe('Admin panel global chat threads (integration)', () => {return id;};- const fetchThreads = async (- variables: Record<string, unknown>,- ): Promise<ThreadsResult> => {- const response = await makeAdminPanelApiRequest({- query: GET_ADMIN_CHAT_THREADS,- variables,- });-- expect(response.body.errors).toBeUndefined();-- return response.body.data?.getAdminChatThreads;- };-beforeAll(async () => {- dataSource = global.testDataSource;storage = getAppProviderByClassName<AgentHistoryUpgradeStorageService>('AgentHistoryUpgradeStorageService',);- const [firstUserWorkspace] = await dataSource.query(- `SELECT "userWorkspace".id, "user".email, "workspaceMember".id AS "workspaceMemberId"+ const [firstUserWorkspace] = await global.testDataSource.query(+ `SELECT "workspaceMember".id AS "workspaceMemberId"FROM core."userWorkspace" "userWorkspace"JOIN core."user" "user" ON "user".id = "userWorkspace"."userId"JOIN "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."workspaceMember" "workspaceMember" ON "workspaceMember"."userId" = "user".id AND "workspaceMember"."deletedAt" IS NULL@@ -277,9 +179,7 @@ describe('Admin panel global chat threads (integration)', () => {[SEED_APPLE_WORKSPACE_ID],);- userWorkspaceId = firstUserWorkspace.id;workspaceMemberId = firstUserWorkspace.workspaceMemberId;- userEmail = firstUserWorkspace.email;kickoffThreadId = await insertThread({id: randomUUID(),@@ -325,106 +225,6 @@ describe('Admin panel global chat threads (integration)', () => {type: 'reasoning',reasoningContent: 'planning the data model',});-- deterministicThreadId = await insertThread({- id: v5(- `${SEED_APPLE_WORKSPACE_ID}:${userWorkspaceId}`,- WORKSPACE_SETUP_CHAT_THREAD_ID_NAMESPACE,- ),- title: 'integration-onboarding-deterministic-thread',- });-- regularThreadId = await insertThread({- id: randomUUID(),- title: 'integration-regular-thread',- hasFailedTurn: true,- });- const regularAssistantMessageId = await insertMessage({- threadId: regularThreadId,- role: 'assistant',- createdAt: '2026-01-01T00:03:00Z',- });-- await insertPart({- messageId: regularAssistantMessageId,- orderIndex: 0,- type: 'text',- textContent: 'assistant reply',- });-- const questionItems = [- {- header: 'Email type',- question: 'Which mailbox should we sync?',- options: [{ label: 'Work' }, { label: 'Personal' }],- },- ];-- answeredQuestionThreadId = await insertThread({- id: randomUUID(),- title: 'integration-answered-question-thread',- });- await insertMessage({- threadId: answeredQuestionThreadId,- role: 'system',- createdAt: '2026-01-01T00:04:00Z',- });-- const answeredQuestionMessageId = await insertMessage({- threadId: answeredQuestionThreadId,- role: 'assistant',- createdAt: '2026-01-01T00:05:00Z',- });-- await insertPart({- messageId: answeredQuestionMessageId,- orderIndex: 0,- type: 'tool-ask_question',- toolName: 'ask_question',- toolCallId: 'call-answered-question',- toolInput: questionItems[0],- toolOutput: {- success: true,- message: 'User answered the question.',- result: {- question: questionItems[0],- status: 'answered',- answer: { selectedOptionIndices: [0] },- },- },- state: 'output-available',- });-- pendingQuestionThreadId = await insertThread({- id: randomUUID(),- title: 'integration-pending-question-thread',- });- await insertMessage({- threadId: pendingQuestionThreadId,- role: 'system',- createdAt: '2026-01-01T00:06:00Z',- });-- const pendingQuestionMessageId = await insertMessage({- threadId: pendingQuestionThreadId,- role: 'assistant',- createdAt: '2026-01-01T00:07:00Z',- });-- await insertPart({- messageId: pendingQuestionMessageId,- orderIndex: 0,- type: 'tool-ask_questions',- toolName: 'ask_questions',- toolCallId: 'call-pending-questions',- toolInput: { questions: questionItems },- toolOutput: {- success: true,- message: 'Questions presented to the user; awaiting their answer.',- result: { questions: questionItems, status: 'pending' },- },- state: 'output-available',- });});afterAll(async () => {@@ -442,262 +242,6 @@ describe('Admin panel global chat threads (integration)', () => {}}});-- await dataSource.query(- `UPDATE core."workspace" SET "allowImpersonation" = true WHERE id = $1`,- [SEED_APPLE_WORKSPACE_ID],- );- });-- describe('getAdminChatThreads', () => {- it('returns only onboarding threads for the ONBOARDING scope', async () => {- const result = await fetchThreads({ scope: 'ONBOARDING', limit: 100 });-- const threadIds = result.threads.map((thread) => thread.id);-- expect(threadIds).toContain(kickoffThreadId);- expect(threadIds).toContain(deterministicThreadId);- expect(threadIds).not.toContain(regularThreadId);-- for (const thread of result.threads) {- expect(thread.isOnboardingThread).toBe(true);- }- });-- it('defaults to every scope when none is given', async () => {- const result = await fetchThreads({ limit: 100 });-- const threadIds = result.threads.map((thread) => thread.id);-- expect(threadIds).toContain(regularThreadId);- expect(threadIds).toContain(kickoffThreadId);- });-- it('returns all threads with the onboarding flag for the ALL scope', async () => {- const result = await fetchThreads({- scope: 'ALL',- searchTerm: regularThreadId,- });-- expect(result.totalCount).toBe(1);- expect(result.threads).toHaveLength(1);- expect(result.threads[0]).toMatchObject({- id: regularThreadId,- isOnboardingThread: false,- hasError: true,- messageCount: 1,- userReplyCount: 0,- userEmail,- });- });-- it('reports a soft deleted thread with its deletion date', async () => {- const deletedThreadId = await insertThread({- id: randomUUID(),- title: 'integration-soft-deleted-thread',- });-- await storage.run(SEED_APPLE_WORKSPACE_ID, (context) =>- context.manager.query(- `UPDATE ${context.table('agentChatThread')} SET "deletedAt" = $2 WHERE id = $1`,- [deletedThreadId, '2026-01-02T00:00:00.000Z'],- ),- );-- const result = await fetchThreads({- scope: 'ALL',- searchTerm: deletedThreadId,- });-- expect(result.threads).toEqual([- expect.objectContaining({- id: deletedThreadId,- deletedAt: '2026-01-02T00:00:00.000Z',- }),- ]);- });-- // Workflow-run conversations belong to no member; a null owner must not fail the whole list on a non-null field.- it('lists a thread without an owner', async () => {- const ownerlessThreadId = randomUUID();-- await insertHistory(- 'agentChatThread',- ['id', 'title'],- [ownerlessThreadId, 'Workflow run conversation'],- 'ON CONFLICT (id) DO NOTHING',- );- seededThreadIds.push(ownerlessThreadId);-- const result = await fetchThreads({- scope: 'ALL',- searchTerm: ownerlessThreadId,- });-- expect(result.threads).toEqual([- expect.objectContaining({- id: ownerlessThreadId,- userWorkspaceId: null,- userEmail: null,- isOnboardingThread: false,- }),- ]);- });-- it('counts only visible messages and user replies', async () => {- const result = await fetchThreads({- scope: 'ALL',- searchTerm: kickoffThreadId,- });-- expect(result.threads[0]).toMatchObject({- id: kickoffThreadId,- isOnboardingThread: true,- messageCount: 2,- userReplyCount: 1,- hasError: false,- });- });-- it('filters threads with errors via hasErrorOnly', async () => {- const result = await fetchThreads({- scope: 'ALL',- hasErrorOnly: true,- limit: 100,- });-- const threadIds = result.threads.map((thread) => thread.id);-- expect(threadIds).toContain(regularThreadId);- expect(threadIds).not.toContain(kickoffThreadId);- });-- it('filters threads without user replies via userNeverEngagedOnly', async () => {- const result = await fetchThreads({- scope: 'ONBOARDING',- userNeverEngagedOnly: true,- limit: 100,- });-- const threadIds = result.threads.map((thread) => thread.id);-- expect(threadIds).toContain(deterministicThreadId);- expect(threadIds).toContain(pendingQuestionThreadId);- expect(threadIds).not.toContain(kickoffThreadId);- expect(threadIds).not.toContain(answeredQuestionThreadId);- });-- it('counts an answered question card as a user reply', async () => {- const result = await fetchThreads({- scope: 'ALL',- searchTerm: answeredQuestionThreadId,- });-- expect(result.threads[0]).toMatchObject({- id: answeredQuestionThreadId,- messageCount: 1,- userReplyCount: 1,- });- });-- it('does not count a pending question card as a user reply', async () => {- const result = await fetchThreads({- scope: 'ALL',- searchTerm: pendingQuestionThreadId,- });-- expect(result.threads[0]).toMatchObject({- id: pendingQuestionThreadId,- messageCount: 1,- userReplyCount: 0,- });- });-- it('sorts by message count', async () => {- const result = await fetchThreads({- scope: 'ONBOARDING',- sortBy: 'MESSAGE_COUNT',- sortDirection: 'ASC',- limit: 100,- });-- const threadIds = result.threads.map((thread) => thread.id);-- expect(threadIds.indexOf(deterministicThreadId)).toBeLessThan(- threadIds.indexOf(kickoffThreadId),- );- });-- it('sorts by reply count, counting answered question cards', async () => {- const result = await fetchThreads({- scope: 'ALL',- sortBy: 'REPLY_COUNT',- sortDirection: 'DESC',- limit: 100,- });-- const threadIds = result.threads.map((thread) => thread.id);-- expect(threadIds.indexOf(answeredQuestionThreadId)).toBeLessThan(- threadIds.indexOf(pendingQuestionThreadId),- );- expect(threadIds.indexOf(kickoffThreadId)).toBeLessThan(- threadIds.indexOf(pendingQuestionThreadId),- );- });-- it('paginates with totalCount and hasMore', async () => {- const result = await fetchThreads({ scope: 'ONBOARDING', limit: 1 });-- expect(result.threads).toHaveLength(1);- expect(result.totalCount).toBeGreaterThanOrEqual(2);- expect(result.hasMore).toBe(true);- });-- it('finds threads by user email via searchTerm', async () => {- const result = await fetchThreads({- scope: 'ALL',- searchTerm: userEmail,- limit: 100,- });-- const threadIds = result.threads.map((thread) => thread.id);-- expect(threadIds).toContain(kickoffThreadId);- expect(threadIds).toContain(regularThreadId);- });-- it('excludes workspaces that disabled support access', async () => {- await dataSource.query(- `UPDATE core."workspace" SET "allowImpersonation" = false WHERE id = $1`,- [SEED_APPLE_WORKSPACE_ID],- );-- try {- const result = await fetchThreads({- scope: 'ALL',- searchTerm: kickoffThreadId,- });-- expect(result.totalCount).toBe(0);- expect(result.threads).toHaveLength(0);- } finally {- await dataSource.query(- `UPDATE core."workspace" SET "allowImpersonation" = true WHERE id = $1`,- [SEED_APPLE_WORKSPACE_ID],- );- }- });-- it('rejects a caller without the SECURITY permission flag', async () => {- const response = await makeAdminPanelApiRequestWithGuestRole({- query: GET_ADMIN_CHAT_THREADS,- variables: {},- });-- expect(response.body.errors).toBeDefined();- expect(response.body.data?.getAdminChatThreads).toBeFalsy();- });});describe('getAdminChatThreadMessages', () => {diff --git a/packages/twenty-shared/src/types/SettingsPath.ts b/packages/twenty-shared/src/types/SettingsPath.tsindex f150b7a5a12..f57c97ff659 100644--- a/packages/twenty-shared/src/types/SettingsPath.ts+++ b/packages/twenty-shared/src/types/SettingsPath.ts@@ -94,7 +94,6 @@ export enum SettingsPath {AdminPanelWorkspaceDetail = 'admin-panel/workspaces/:workspaceId',AdminPanelApplicationRegistrationDetail = 'admin-panel/applications/registrations/:applicationRegistrationId',AdminPanelWorkspaceChatThread = 'admin-panel/workspaces/:workspaceId/threads/:threadId',- AdminPanelChats = 'admin-panel/chats',Roles = 'members/roles',RoleCreate = 'members/roles/create',